File: mainwindow_drawing.cpp

package info (click to toggle)
veroroute 2.38-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,044 kB
  • sloc: cpp: 21,512; xml: 89; sh: 65; lisp: 20; makefile: 5
file content (1840 lines) | stat: -rw-r--r-- 71,212 bytes parent folder | download
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
/*
	VeroRoute - Qt based Veroboard/Perfboard/PCB layout & routing application.

	Copyright (C) 2017  Alex Lawrow    ( dralx@users.sourceforge.net )

	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 3 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, see <http://www.gnu.org/licenses/>.
*/

#include "mainwindow.h"
#include "padoffsetdialog.h"
#include "GPainter.h"
#include "SpanningTreeHelper.h"

//#define PAINTBOARD_TIMER

void MainWindow::PaintViaGrey(const GuiControl& guiCtrl, QPainter& painter, const QPointF& pC)
{
	assert(!m_bWriteGerber);
	const int width = guiCtrl.GetHalfPixelsFromMIL( guiCtrl.GetVIAPAD_MIL() ) << 1;
	static QPen	pen(QColor(200,200,200,255), 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
	pen.setWidth(width);
	painter.setPen(pen);
	painter.setBrush(Qt::NoBrush);
	painter.drawPoint(pC);
}

void MainWindow::PaintPadGrey(const GuiControl& guiCtrl, QPainter& painter, QPen& pen, const QPointF& pC, int iPadWidthMIL)
{
	assert(!m_bWriteGerber);

	const int w		= ( iPadWidthMIL == 0 ) ? guiCtrl.GetPAD_MIL() : iPadWidthMIL;
	const int width	= guiCtrl.GetHalfPixelsFromMIL( w ) << 1;
	pen.setWidth(width);
	painter.setPen(pen);
	painter.setBrush(Qt::NoBrush);
	painter.drawPoint(pC);
}

void MainWindow::PaintSOIC(const GuiControl& guiCtrl, QPainter& painter, const QColor& color, const QPointF& pC, size_t pinIndex, const Component* pComp, bool bIsGnd, bool bGap)
{
	assert(pComp);
	const int W = guiCtrl.GetGRIDPIXELS();

	std::list<MyPolygonF> polygonList;
	guiCtrl.CalcSOIC(W, pC, pinIndex, pComp, polygonList, false, bIsGnd, bGap);	// Populate polygonList

	if ( m_bWriteGerber )	// Write to Gerber
	{
		if ( !bGap )	// Use this as an opportunity to get the solder mask info
		{
			std::list<MyPolygonF> solderMask;
			guiCtrl.CalcSOIC(W, pC, pinIndex, pComp, solderMask, true, bIsGnd, bGap);	// Populate polygonList

			GStream& os = m_gWriter.GetStream(GFILE::GTS);	// Top solder mask layer
			for (auto& polygon : solderMask)
			{
				if ( polygon.empty() ) continue;
				assert(polygon.m_ePadPen == GPEN::NONE && polygon.m_eTrkPen == GPEN::NONE && polygon.m_bClosed);

				os.AddRegion(polygon);
			}
		}
		for (int k = 0; k < m_board.GetLyrs(); k++)
		{
			GStream& os = m_gWriter.GetStream(k == 0 ? GFILE::GBL : GFILE::GTL);	// Bottom/Top copper layer
			for (auto& polygon : polygonList)
			{
				if ( polygon.empty() ) continue;
				assert(polygon.m_ePadPen == GPEN::NONE);

				const bool bTrk	= polygon.m_eTrkPen != GPEN::NONE && !polygon.m_bClosed;
				const bool bPad	= polygon.m_eTrkPen == GPEN::NONE &&  polygon.m_bClosed;
				if ( !bTrk && !bPad ) continue;

				if ( bPad )
					os.AddRegion(polygon);
				else
					os.AddTrack(polygon, polygon.m_eTrkPen);
			}
		}
	}
	else	// Draw to pixmap
	{
		const int	gapWidth	= bGap ? guiCtrl.GetPixelsFromMIL( guiCtrl.GetGAP_MIL() ) : 0;
		const int	trackWidth	= ( guiCtrl.GetHalfPixelsFromMIL( guiCtrl.GetTRACK_IC_MIL() ) + gapWidth ) << 1;	// Track width in pixels
		const int	minWidth	= ( guiCtrl.GetHalfPixelsFromMIL( guiCtrl.GetMIN_IC_MIL() ) + gapWidth ) << 1;		// Thin track width in pixels

		static QPen		pen(Qt::black, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
		static QBrush	brush(Qt::black,  Qt::SolidPattern);
		pen.setColor(color);
		brush.setColor(color);
		painter.setBrush(brush);

		for (auto& polygon : polygonList)
		{
			if ( polygon.empty() ) continue;

			assert(polygon.m_ePadPen == GPEN::NONE);

			bool bTrk(false), bMin(false), bPad(false);	// Determine track/pad from m_eTrkPen
			switch(polygon.m_eTrkPen)
			{
				case GPEN::MIN_IC:	
				case GPEN::MIN_IC_GAP:	bMin = !polygon.m_bClosed;	break;
				case GPEN::TRK_IC:
				case GPEN::TRK_IC_GAP:	bTrk = !polygon.m_bClosed;	break;
				case GPEN::NONE:		bPad =  polygon.m_bClosed;	break;
				default:				break;
			}
			if ( !bTrk && !bMin && !bPad ) continue;

			pen.setWidth(bMin ? minWidth : bTrk ? trackWidth : 0);
			painter.setPen(pen);

			if ( bPad )
				painter.drawPolygon(polygon);
			else	// bTrk || bMin
			{
				auto iterA = polygon.begin();
				auto iterB = iterA; iterB++;
				while( iterB != polygon.end() )
				{
					painter.drawLine(*iterA, *iterB); ++iterA; ++iterB;
				}
			}
		}
	}
}

void MainWindow::PaintVia(const GuiControl& guiCtrl, QPainter& painter, const QColor& color, const QPointF& pC, bool bGap)
{
	if ( m_bWriteGerber )
	{
		m_gWriter.GetStream(GFILE::GTL).AddViaPad(pC, bGap ? GPEN::VIA_GAP : GPEN::VIA);	// Top    copper layer
		m_gWriter.GetStream(GFILE::GBL).AddViaPad(pC, bGap ? GPEN::VIA_GAP : GPEN::VIA);	// Bottom copper layer
		if ( !bGap )
		{
			m_gWriter.GetStream(GFILE::GTS).AddViaPad(pC, GPEN::VIA_MSK);	// Top    solder mask layer
			m_gWriter.GetStream(GFILE::GBS).AddViaPad(pC, GPEN::VIA_MSK);	// Bottom solder mask layer
			m_gWriter.GetStream(GFILE::DRL).AddHole(pC,   GPEN::VIA_HLE);	// Drill file
		}
	}
	else
	{
		const int gapWidth = bGap ? guiCtrl.GetPixelsFromMIL( guiCtrl.GetGAP_MIL() ) : 0;
		const int padWidth = ( guiCtrl.GetHalfPixelsFromMIL( guiCtrl.GetVIAPAD_MIL() ) + gapWidth ) << 1;
		static QPen	pen(Qt::black, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
		pen.setColor(color);
		pen.setWidth(padWidth);
		painter.setPen(pen);
		painter.setBrush(Qt::NoBrush);
		painter.drawPoint(pC);
	}
}

void MainWindow::PaintPad(const GuiControl& guiCtrl, QPainter& painter, const QColor& color, const QPointF& pC, int iPadWidthMIL, int iHoleWidthMIL, bool bGap)
{
	if ( m_bWriteGerber )
	{
		m_gWriter.GetStream(GFILE::GTL).AddPad(pC, bGap ? GPEN::PAD_GAP : GPEN::PAD, iPadWidthMIL); // Top    copper layer
		m_gWriter.GetStream(GFILE::GBL).AddPad(pC, bGap ? GPEN::PAD_GAP : GPEN::PAD, iPadWidthMIL); // Bottom copper layer
		if ( !bGap )
		{
			m_gWriter.GetStream(GFILE::GTS).AddPad(pC,  GPEN::PAD_MSK, iPadWidthMIL);	// Top    solder mask layer
			m_gWriter.GetStream(GFILE::GBS).AddPad(pC,  GPEN::PAD_MSK, iPadWidthMIL);	// Bottom solder mask layer
			m_gWriter.GetStream(GFILE::DRL).AddHole(pC, GPEN::PAD_HLE, iHoleWidthMIL);	// Drill file
		}
	}
	else
	{
		const int gapWidth	= bGap ? guiCtrl.GetPixelsFromMIL( guiCtrl.GetGAP_MIL() ) : 0;
		const int w			= ( iPadWidthMIL == 0 ) ? guiCtrl.GetPAD_MIL() : iPadWidthMIL;
		const int padWidth	= ( guiCtrl.GetHalfPixelsFromMIL( w ) + gapWidth ) << 1;
		static QPen	pen(Qt::black, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
		pen.setColor(color);
		pen.setWidth(padWidth);
		painter.setPen(pen);
		painter.setBrush(Qt::NoBrush);
		painter.drawPoint(pC);
	}
}

void MainWindow::PaintBlob(const GuiControl& guiCtrl, QPainter& painter, const QColor& color, const QPointF& pC, const QPointF& pCoffset,
						   int iPadWidthMIL, int iPerimeterCode, int iTagCode,
						   bool bHavePad, bool bHaveSoic, bool bIsGnd, bool bGap)
{
	std::list<MyPolygonF> polygonList;
	guiCtrl.CalcBlob(guiCtrl.GetGRIDPIXELS(), pC, pCoffset, iPadWidthMIL, iPerimeterCode, iTagCode, polygonList, bHavePad, bHaveSoic, bIsGnd, bGap);	// Populate polygonList

	if ( m_bWriteGerber )	// Write to Gerber
	{
		for (int k = 0; k < m_board.GetLyrs(); k++)
		{
			GStream& os = m_gWriter.GetStream(k == 0 ? GFILE::GBL : GFILE::GTL);	// Bottom/Top copper layer

			for (auto& polygon : polygonList)
			{
				if ( polygon.empty() ) continue;

				const bool bPad	= polygon.m_ePadPen != GPEN::NONE;
				const bool bTrk	= polygon.m_eTrkPen != GPEN::NONE;
				if ( !bTrk && !bPad && !polygon.m_bClosed ) continue;

				const GPEN& ePen = bTrk ? polygon.m_eTrkPen : polygon.m_ePadPen;

				if ( polygon.m_bClosed )
				{
					if ( bPad || bTrk )
						os.AddLoop(polygon, ePen);	// Closed polygon outline
					if ( !bGap )
						os.AddRegion(polygon);		// Only non-Gap polygon needs filling
				}
				else if ( bPad && bTrk )	// Fat tracks with diagonals
					os.AddVariTrack(polygon, polygon.m_ePadPen, polygon.m_eTrkPen);
				else if ( bPad || bTrk )
					os.AddTrack(polygon, ePen);
			}
		}
	}
	else	// Draw to pixmap
	{
		const int	gapWidth	= bGap ? guiCtrl.GetPixelsFromMIL( guiCtrl.GetGAP_MIL() ) : 0;
		const int	padWidth	= ( guiCtrl.GetHalfPixelsFromMIL( guiCtrl.GetPAD_MIL() )   + gapWidth ) << 1;	// Pad width in pixels
		const int	trackWidth	= ( guiCtrl.GetHalfPixelsFromMIL( bIsGnd ? guiCtrl.GetTAG_MIL() : guiCtrl.GetTRACK_MIL() ) + gapWidth ) << 1;	// Track width in pixels

		static QPen		pen(Qt::black, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
		static QBrush	brush(Qt::black,  Qt::SolidPattern);
		pen.setColor(color);
		brush.setColor(color);
		painter.setBrush(brush);

		for (auto& polygon : polygonList)
		{
			if ( polygon.empty() ) continue;

			const bool bTrk	= polygon.m_eTrkPen != GPEN::NONE;
			const bool bPad	= polygon.m_ePadPen != GPEN::NONE;
			if ( !bTrk && !bPad && !polygon.m_bClosed ) continue;

			pen.setWidth(bTrk ? trackWidth : bPad ? padWidth : 0);
			painter.setPen(pen);

			if ( polygon.m_bClosed )
				painter.drawPolygon(polygon);
			else if ( bPad && bTrk )	// Fat tracks with diagonals
			{
				//polygon.Process();	// Not needed since m_bFatEdge already populated
				size_t i(0);
				auto iterA = polygon.begin();
				auto iterB = iterA; iterB++;
				while( iterB != polygon.end() )
				{
					pen.setWidth(polygon.m_bFatEdge[i++] ? padWidth : trackWidth);	painter.setPen(pen);
					painter.drawLine(*iterA, *iterB); ++iterA; ++iterB;
				}
			}
			else if ( bPad || bTrk )
			{
				if ( polygon.size() == 1 )
					painter.drawPoint( polygon.first() );
				else
				{
					auto iterA = polygon.begin();
					auto iterB = iterA; iterB++;
					while( iterB != polygon.end() )
					{
						painter.drawLine(*iterA, *iterB); ++iterA; ++iterB;
					}
				}
			}
		}
	}
}

void MainWindow::paintEvent(QPaintEvent*)
{
	if ( !m_bRepaint ) return;

	if ( m_board.GetCompEdit() )
		PaintCompDefiner();
	else
		PaintBoard();

	// Tidy up
	m_label->setPixmap(m_mainPixmap);
	m_scrollArea->setVisible(true);
	m_scrollArea->setWidgetResizable(false);
	m_label->adjustSize();

	m_scrollArea->CentreView();	// Centre the scrollbars (if needed) for component editor mode

	m_bRepaint = false;
}

void MainWindow::PaintCompDefiner()	// The paint method in "component editor mode"
{
	Board&			board		= m_board;
	CompDefiner&	def			= board.GetCompDefiner();
	const PinGrid&	grid		= def.GetGrid();
	const int&		W			= board.GetGRIDPIXELS();	// Square width in pixels
	const int		C			= W >> 1;					// Half square width in pixels
	const double	dTextScale	= W / 24.0;					// For scaling text when zooming

	// Shift comp to near grid centre
	const int ROWS(def.GetScreenRows()), COLS(def.GetScreenCols());

	const Rect rect(def.GetGridRowMin(), def.GetGridRowMax(), def.GetGridColMin(), def.GetGridColMax());

	QPainter painter;
	const int reqW(W * COLS), reqH(W * ROWS);
	if ( m_mainPixmap.width() != reqW || m_mainPixmap.height() != reqH )
	{
		m_mainPixmap = QPixmap(reqW, reqH);
		m_mainPixmap.setDevicePixelRatio(1.0);
	}
	painter.begin(&m_mainPixmap);	// Paint to main pixmap

	SetQuality(painter);

	m_XCORRECTION = m_YCORRECTION = 0;
	painter.fillRect(m_XGRIDOFFSET, m_YGRIDOFFSET, reqW, reqH, Qt::white);

	m_blackPen.setWidth(0);
	m_whitePen.setWidth(0);
	painter.setPen(m_blackPen);
	painter.setBrush(Qt::NoBrush);

	int X(0), Y(0), L(0), R(0), T(0), B(0);

	// Draw rect around whole board area =========================================================
	int dummy;
	GetLRTB(board, 110, 0, 0, L, dummy, T, dummy);				// 110% size square
	GetLRTB(board, 110, ROWS-1, COLS-1, dummy, R, dummy, B);	// 110% size square
	painter.drawRect(L, T, R-L, B-T);

	// Get footprint bounds ======================================================================
	GetLRTB(board, rect, L, R, T, B);
	L -= C; R += C; T -= C; B += C;
	const int AXIS_X = ( L + R ) / 2;
	const int AXIS_Y = ( T + B ) / 2;

	// Draw shapes ===============================================================================
	painter.save();
	painter.translate(AXIS_X, AXIS_Y);
	for (const auto& mapObj : def.GetShapes() )
	{
		const Shape& s = mapObj.second;

		if ( s.GetDrawFill() )
			m_varBrush.setColor( s.GetFillColor().GetQColor() );
		const bool bCurrentShape = ( mapObj.first == def.GetCurrentShapeId() );
		m_blackPen.setWidth( bCurrentShape ? 3 : 2 );

		painter.setPen( s.GetDrawLine() ? m_blackPen : Qt::NoPen );
		painter.setBrush( s.GetDrawFill() ? m_varBrush : Qt::NoBrush );

		painter.save();
		painter.translate( s.GetCX() * W, s.GetCY() * W );
		painter.rotate( -s.GetA3() );	// A3 > 0 ==> CCW
		const int DX	= static_cast<int>(s.GetDX() * W);
		const int DY	= static_cast<int>(s.GetDY() * W);
		const int X		= static_cast<int>(s.GetDX() * W * 0.5);
		const int Y		= static_cast<int>(s.GetDY() * W * 0.5);
		const int A		= static_cast<int>(s.GetA1() * 16);
		const int Alen	= static_cast<int>(s.GetAlen() * 16);
		switch( s.GetType() )
		{
			case SHAPE::RECT:			painter.drawRect(-X, -Y, DX, DY);	break;
			case SHAPE::ROUNDED_RECT:	painter.drawRoundedRect(-X, -Y, DX, DY, 0.35 * W, 0.35 * W);	break;
			case SHAPE::ELLIPSE:		painter.drawEllipse(-X, -Y, DX, DY);	break;
			case SHAPE::ARC:			painter.drawArc(  -X, -Y, DX, DY, A, Alen);	break;
			case SHAPE::CHORD:			painter.drawChord(-X, -Y, DX, DY, A, Alen);	break;
			default:					assert(SHAPE::LINE == s.GetType() );
										painter.drawLine(-X, -Y, X, Y);		break;
		}
		if ( bCurrentShape )
		{
			// Show the base rect/ellipse for line/arc/chord
			painter.setPen(m_dotPen);
			painter.setBrush(Qt::NoBrush);
			switch( s.GetType() )
			{
				case SHAPE::LINE:	painter.drawRect(-X, -Y, DX, DY);	break;
				case SHAPE::ARC:
				case SHAPE::CHORD:	painter.drawEllipse(-X, -Y, DX, DY);	break;
				default:			break;
			}
		}
		painter.restore();
	}
	painter.restore();
	//============================================================================================

	// Draw grid points ==========================================================================
	if ( board.GetShowGrid() )
		for (int j = 0; j < ROWS; j++)
		for (int i = 0; i < COLS; i++)
		{
			GetXY(board, j, i, X, Y);
			painter.drawPoint(X, Y);
		}

	// Draw dashed rect around footprint boundary and along central axes =========================
	painter.setPen(m_dashPen);
	painter.setBrush(Qt::NoBrush);
	painter.drawRect(L, T, R-L, B-T);
	painter.setPen(m_dotPen);
	painter.drawLine(0, AXIS_Y, reqW, AXIS_Y);
	painter.drawLine(AXIS_X, 0, AXIS_X, reqH);

	// Draw pins =================================================================================
	QFont pinsFont = painter.font();	// Copy of current font
	pinsFont.setPointSize( m_board.GetTextSizePins() );
	painter.setFont(pinsFont);

	m_varBrush.setColor(QColor(192,192,255,128));	// Light blue

	for (int iLoop = 0; iLoop < 2; iLoop++)
	{
		int iPinId(0);
		for (int j = 0, jMax = grid.GetRows(); j < jMax; j++)
		for (int i = 0, iMax = grid.GetCols(); i < iMax; i++, iPinId++)
		{
			auto p = grid.Get(0,j,i);	// Always layer 0 for component editor
			GetXY(board, def.GetGridRowMin() + j, def.GetGridColMin() + i, X, Y );

			painter.save();
			painter.translate(X, Y);

			if ( iLoop == 0 )	// Shade according to GetSurface()
			{
				painter.setPen(Qt::NoPen);
				painter.setBrush(p->GetSurface() == SURFACE_FREE ? Qt::NoBrush :
								 p->GetSurface() == SURFACE_HOLE ? m_darkBrush : m_varBrush);	//TODO Handle SURFACE_GAP, SURFACE PLUG in future
				painter.drawRect(-C,-C,W,W);
			}
			if ( iLoop == 1 )	// Draw pins/labels
			{
				if ( iPinId == def.GetCurrentPinId() )
				{
					painter.setPen(m_redPen);
					painter.drawEllipse(-C,-C,W,W);
				}
				if ( p->GetIsPin() )
				{
					painter.setPen(m_blackPen);
					painter.rotate(270);

					const size_t pinIndex = p->GetPinIndex();
					std::string strPinLabel = ( pinIndex < def.GetNumPins() ) ? def.GetPinLabel(pinIndex) : CompTypes::GetDefaultPinLabel(pinIndex);
					int iFlag = ( pinIndex < def.GetNumPins() ) ? def.GetPinAlign(pinIndex) : Qt::AlignCenter;
					if ( iFlag == Qt::AlignLeft || iFlag == Qt::AlignRight )
					{
						const bool bLeft = ( iFlag == Qt::AlignLeft );
						painter.translate(bLeft ? -C/2 : C/2, 0);
					}
					iFlag |= ( Qt::TextDontClip | Qt::AlignVCenter );

					painter.scale(dTextScale, dTextScale);
					painter.drawText(0,0,0,0, iFlag, strPinLabel.c_str());
				}
			}
			painter.restore();
		}
	}
	painter.end();
}

void MainWindow::PaintBoard()	// The paint method in "circuit layout mode"
{
#ifdef PAINTBOARD_TIMER
	const auto start = std::chrono::steady_clock::now();
#endif

	Board&			 board			= m_board;
	CompManager&	 compMgr		= board.GetCompMgr();
	ColorManager&	 colorMgr		= board.GetColorMgr();
	const TRACKMODE& trackMode		= board.GetTrackMode();
	const COMPSMODE& compMode		= board.GetCompMode();
	const bool&		 bVero			= board.GetVeroTracks();
	const bool		 bColor			= trackMode == TRACKMODE::COLOR;
	const bool		 bMono			= trackMode == TRACKMODE::MONO;
	const bool		 bPCB			= trackMode == TRACKMODE::PCB;
	const bool		 bMonoPCB		= bMono || bPCB;
	const bool		 bGroundFill	= !bVero && bMonoPCB && board.GetGroundFill();
	const bool		 bForceXthermal	= board.GetXthermals();
	const bool		 bDirect		= !bVero && !bGroundFill;	// true ==> Draw track "blobs" and pads directly (PDF/Gerber)
	const int&		 layer			= board.GetCurrentLayer();
	const int&		 groundNodeId	= board.GetGroundNodeId(layer);
	const bool		 bTopLyr		= ( layer == LYR_TOP );
	const bool		 bWiresAsTracks	= m_bWriteGerber && m_bTwoLayerGerber && board.GetLyrs() == 1;	// true ==> Convert wires to tracks on the top layer
	const int&		 W				= board.GetGRIDPIXELS();		// Square width in pixels
	const int		 C				= W >> 1;						// Half square width in pixels
	const int		 iHalfGap		= std::max(1, W / 12);			// For vero only
	const int		 iGap			= iHalfGap + iHalfGap;			// For vero only
	const int		 iWirePenWidth	= board.GetHalfPixelsFromMIL( board.GetPAD_MIL() ) / 4;	// For wires with no NodeID
	const int		 iWireBoxWidth	= 3 * iWirePenWidth;			// For wires with no NodeID
	const double	 dTextScale		= ( m_bWritePDF ) ? (48.0 / W) : (W / 24.0);	// For scaling text when zooming
	if ( bVero && trackMode != TRACKMODE::OFF ) board.CalcSolder();	// Calculate positions of solder blobs for stripboard builds

	int X(0), Y(0), L(0), R(0), T(0), B(0);

	QPen penGry(QColor(200,200,200,255), 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
	QPen penTop(penGry);	penTop.setColor( colorMgr.GetPixmapColor(MY_LYR_TOP) );
	QPen penBot(penGry);	penBot.setColor( colorMgr.GetPixmapColor(MY_LYR_BOT) );

	colorMgr.SetSaturation( board.GetSaturation() );			// Must do this BEFORE making pixmaps (if these are reintroduced)
	colorMgr.SetFillSaturation( board.GetFillSaturation() );	// Must do this BEFORE making pixmaps (if these are reintroduced)

	board.CalculateColors();	// Work out best way to color things

	// Pre-process component list for rendering
	std::vector<const Component*> sortedComps;
	compMgr.CalculateWireInfo();			// Work out shifts for overlaid wires and flag crossing wires
	compMgr.GetSortedComps(sortedComps);	// Sorted so floating and "plug" components get rendered last

	// Get bounds to minimise looping
	int minRow, minCol, maxRow, maxCol;
	board.GetBounds(minRow, minCol, maxRow, maxCol);

	int gndL, gndR, gndT, gndB;
	board.CalcGroundFillBounds();
	board.GetGroundFillBounds(gndL, gndR, gndT, gndB);

	const double dEdge = board.GetEdgeWidth();
	const int iEdge = static_cast<int>( dEdge );
	const int reqW(gndR - gndL + (iEdge<<1)), reqH(gndB - gndT + (iEdge<<1));

	m_XCORRECTION = -gndL;
	m_YCORRECTION = -gndT;

	GPainter painter;	// Works like QPainter unless you give it a GStream for Gerber

	QPdfWriter* pdfWriter = nullptr;
	if ( m_bWritePDF )
	{
		pdfWriter = new QPdfWriter(m_pdfFileName);
		pdfWriter->setCreator("VeroRoute");
		pdfWriter->setPageSize(QPageSize(QPageSize::A4));
		pdfWriter->setPageOrientation(QPageLayout::Landscape);
		pdfWriter->setResolution(1200);
		painter.begin(pdfWriter);	// Paint to PDF file
	}
	else if ( m_bWriteGerber )
	{
		assert( bPCB && !board.GetMirrored() );
		auto& os = m_gWriter.GetStream(GFILE::GTO);	// Top silk layer
		os.SetPolarity(GPOLARITY::DARK);
		os.ClearBuffers();
		painter.SetGStream(&os);
	}
	else
	{
		if ( m_mainPixmap.width() != reqW || m_mainPixmap.height() != reqH )
		{
			m_mainPixmap = QPixmap(reqW, reqH);
			m_mainPixmap.setDevicePixelRatio(1.0);
		}
		painter.begin(&m_mainPixmap);	// Paint to main pixmap
	}

	if ( !m_bWriteGerber )
		SetQuality(painter);

	if ( board.GetFlipH() )
	{
		painter.translate(2*m_XGRIDOFFSET + reqW, 0);
		painter.scale(-1, 1);	// Mirror L-R
	}
	if ( board.GetFlipV() )
	{
		painter.translate(0, 2*m_YGRIDOFFSET + reqH);
		painter.scale(1, -1);	// Mirror T-B
	}

	const bool bInverseMono(bMono && board.GetInverseMono());
	const bool bColoredMono(bMono && board.GetColoredMono());

	const QColor backgroundColor	= ( bInverseMono ) ? Qt::black : ( m_bWritePDF ) ? Qt::white : GetBackgroundColor();
	m_backgroundPen.setColor(backgroundColor);
	m_backgroundBrush.setColor(backgroundColor);

	const int	 dotColorID			= bInverseMono ? MY_WHITE : MY_BLACK;
	const QColor dotColor			= ( !m_bWritePDF && dotColorID == MY_WHITE ) ? GetBackgroundColor() : colorMgr.GetPixmapColor(dotColorID);
	const int	 groundFillColorId	= bPCB ? ( layer == 0 ? MY_LYR_BOT : MY_LYR_TOP ) : ( bInverseMono ? MY_WHITE : MY_BLACK );
	const QColor groundFillColor	= ( !m_bWritePDF && groundFillColorId == MY_WHITE ) ? GetBackgroundColor() : colorMgr.GetPixmapColor(groundFillColorId);

	QPen dotPen(m_blackPen);
	dotPen.setColor(dotColor);

	QPen wirePen(m_blackPen);
	wirePen.setColor(bGroundFill ? backgroundColor : groundFillColor);
	wirePen.setWidth(iWirePenWidth);

	// Draw board background
	QPolygonF edge;		// The board outline in Gerber
	QPolygonF gndPoly;	// The rectangle for ground fill
	if ( m_bWriteGerber )
	{
		// Grow board outline to guarantee separation from tracks and ground
		const double R(reqW - dEdge*2), B(reqH - dEdge*2);
		const double X = m_XGRIDOFFSET + dEdge;
		const double Y = m_YGRIDOFFSET + dEdge;
		gndPoly << QPointF(X,     Y);		edge << QPointF(X	  - dEdge, Y	 - dEdge);
		gndPoly << QPointF(X + R, Y);		edge << QPointF(X + R + dEdge, Y	 - dEdge);
		gndPoly << QPointF(X + R, Y + B);	edge << QPointF(X + R + dEdge, Y + B + dEdge);
		gndPoly << QPointF(X,     Y + B);	edge << QPointF(X	  - dEdge, Y + B + dEdge);
		if ( bGroundFill )
		{
			m_gWriter.GetStream(GFILE::GTL).DrawRegion(gndPoly);	// Top    copper layer
			m_gWriter.GetStream(GFILE::GBL).DrawRegion(gndPoly);	// Bottom copper layer
		}
	}
	else
	{
		painter.fillRect(m_XGRIDOFFSET, m_YGRIDOFFSET, reqW, reqH, backgroundColor);
		if ( bGroundFill )
			painter.fillRect(m_XGRIDOFFSET + iEdge, m_YGRIDOFFSET + iEdge, reqW - (iEdge<<1), reqH - (iEdge<<1), groundFillColor);
	}

	// Draw rect around whole board area =========================================================
	if ( m_bWriteGerber )
	{
		m_gWriter.GetStream(GFILE::GKO).DrawLoop(edge, GPEN::GKO);	// Board outline layer
	}
	else
	{
		const int iPenWidth = ( bPCB ) ? static_cast<int>(W * 0.100) : 0;	// Like GPEN::GKO = 10 mil used for Gerber
		dotPen.setWidth(iPenWidth);
		m_whitePen.setWidth(iPenWidth);
		painter.setPen( bPCB ? m_whitePen :  dotPen );
		painter.setBrush(Qt::NoBrush);
		painter.drawRect(m_XGRIDOFFSET, m_YGRIDOFFSET, reqW, reqH);
	}

	// Draw grid points ==========================================================================
	if ( !bPCB && board.GetShowGrid() )
	{
		for (int j = 0, jMax = board.GetRows(); j < jMax; j++)
		for (int i = 0, iMax = board.GetCols(); i < iMax; i++)
		{
			const Element* pC = board.Get(layer, j, i);
			if ( trackMode == TRACKMODE::OFF || ( !pC->GetHasPin() && pC->GetNodeId() == BAD_NODEID ) )
			{
				GetXY(board, j, i, X, Y);
				painter.drawPoint(X, Y);
			}
		}
	}

	// Draw tracks ===============================================================================
	if ( bPCB || trackMode != TRACKMODE::OFF )	// Force tracks in PCB mode
	{
		painter.save();
		const bool	bGreyPads	= bPCB && !m_bWriteGerber;
		const int	numLoops	= ( bGroundFill ? 2 : 1 ) + ( bGreyPads ? 1 : 0);
		// bGroundFill		==> 1st pass draws fat tracks in white, 2nd pass draws tracks
		// bGreyPads		==> A final pass will draw the pads in grey
		for (int iLoop = 0; iLoop < numLoops; iLoop++)
		{
			const bool bLastPass = ( iLoop == numLoops - 1 );
			const bool bGap		 = bGroundFill && iLoop == 0;
			const bool bDrawGrey = ( bGreyPads && bLastPass );
			if ( m_bWriteGerber )
			{
				m_gWriter.GetStream(GFILE::GTS).ClearBuffers();	// Top solder mask layer
				m_gWriter.GetStream(GFILE::GTL).ClearBuffers();	// Top copper layer
				m_gWriter.GetStream(GFILE::GTL).SetPolarity(bGap ? GPOLARITY::CLEAR : GPOLARITY::DARK);
				m_gWriter.GetStream(GFILE::GBS).ClearBuffers();	// Bottom solder mask layer
				m_gWriter.GetStream(GFILE::GBL).ClearBuffers();	// Bottom copper layer
				m_gWriter.GetStream(GFILE::GBL).SetPolarity(bGap ? GPOLARITY::CLEAR : GPOLARITY::DARK);
				m_gWriter.GetStream(GFILE::DRL).ClearBuffers();	// Drill file
			}

			for (int j = minRow; j <= maxRow; j++)
			for (int i = minCol; i <= maxCol; i++)
			{
				const Element*	pC				= board.Get(layer, j, i);
				const int&		nodeId			= pC->GetNodeId();
				const bool		bWire			= pC->GetHasWire();
				const bool		bWireAsVia		= bWire && bWiresAsTracks;	// true ==> draw small via pad
				const int		iPerimeterCode	= board.GetPerimeterCode(pC);	// 0 to 255
				const bool		bVia			= pC->GetIsVia()  ||  bWireAsVia;
				const bool		bPad			= !bWireAsVia && pC->GetHasPinTH();	// Only want through-hole pads
				const bool		bSoicPad		= bTopLyr && pC->GetHasPinSOIC();

				size_t iPinIndexSOIC(BAD_PININDEX);
				const Component* pCompSOIC(nullptr);
				if ( bSoicPad )	// Work out which slot contains the SOIC component
				{
					const int iSOICslot = ( pC->GetSlotCompId(0) != BAD_COMPID && compMgr.GetComponentById(pC->GetSlotCompId(0)).GetIsSOIC() ) ? 0 : 1;
					int compIdSOIC;
					pC->GetSlotInfo(iSOICslot, iPinIndexSOIC, compIdSOIC);
					pCompSOIC = &compMgr.GetComponentById(compIdSOIC);
					assert( pCompSOIC->GetIsSOIC() );
				}

				assert( !(bVia && bPad) );	// Can't be both a via and a pad
				const bool		bIsGnd			= bGroundFill && nodeId == groundNodeId;
				const int		iTagCode		= ( bPad && bIsGnd && nodeId != BAD_NODEID ) ? board.GetTagCode(pC, iPerimeterCode) : 0;

				// Skip places with no NodeID assigned unless they are wire ends, or pins in Mono/PCB mode
				const bool bPointOK = ( nodeId != BAD_NODEID || bWire || bSoicPad || (bMonoPCB && bPad) );	// Point OK ==> We have some track/pad to draw
				if ( !bPointOK ) continue;

				if ( bForceXthermal && !bPad && !bVia && !bSoicPad && bIsGnd ) continue;	// Don't render ground tracks if forcing X shaped thermal reliefs

				bool	bCustomSize(false);
				int		iPadWidthMIL(0), iHoleWidthMIL(0);	// 0 ==> Not a custom size value
				uchar	layerPref(LAYER_X);

				int		padOffsetX(0), padOffsetY(0);
				if ( bPad && !bWire )
				{
					if ( !bVero && board.GetPadOffsets(pC, padOffsetX, padOffsetY) )	// Get offsets in mil
					{
						padOffsetX = (padOffsetX * W) / 100;	// Convert from mil to pixels
						padOffsetY = (padOffsetY * W) / 100;	// Convert from mil to pixels
					}

					if ( board.GetLyrs() == 2 && pC->GetPinSupportsLayerPref() )
						layerPref = board.GetLayerPref(pC);

					size_t	pinIndex;
					int		compId;
					board.GetSlotInfoForTH(pC, pinIndex, compId);

					const Component& comp = compMgr.GetComponentById( compId );
					assert( comp.GetType() != COMP::INVALID );

					bCustomSize = comp.GetCustomPads();
					if ( bCustomSize )
					{
						iPadWidthMIL	= comp.GetPadWidth();
						iHoleWidthMIL	= comp.GetHoleWidth();
					}
				}
				const bool bPadOffset	= ( padOffsetX != 0 || padOffsetY != 0 );
				const bool bBlob		= ( !bPadOffset || iPerimeterCode != 0 || ( bForceXthermal && bIsGnd ) );
				const bool bDrawBlob	= bPointOK && bBlob;
				const bool bDrawPad		= bPointOK && bPad;
				const bool bDrawVia		= bPointOK && bVia;

				QPen& greyPen = ( layerPref == LAYER_X ) ? penGry :
								( layerPref == LAYER_T ) ? penTop : penBot;

				// Use GetPixmapRGB for pixmaps.  It can handle MY_GREY, MY_WHITE, MY_BLACK as special cases
				const int	colorId				= colorMgr.GetColorId(nodeId);
				const bool	bInvalidColor		= colorId == BAD_COLORID || ( bPCB  && nodeId != GetCurrentNodeId() )
																		 || ( bMono && nodeId != GetCurrentNodeId() && !bColoredMono )
																		 || ( bMono && nodeId != GetCurrentNodeId() &&  bColoredMono && bGroundFill && nodeId == groundNodeId );
				const int	iEffColorId			= ( bInvalidColor )	? groundFillColorId
												: ( nodeId == GetCurrentNodeId() ) ? MY_GREY : ( colorId % MYNUMCOLORS );
				const bool	 bAllowCustomColor	=	iEffColorId != MY_GREY		&&	iEffColorId != MY_WHITE		&&	iEffColorId != MY_BLACK
												&&	iEffColorId != MY_LYR_BOT	&&	iEffColorId != MY_LYR_TOP;
				const QColor color				= bAllowCustomColor ? colorMgr.GetColorFromNodeId(nodeId)
																	: ( !m_bWritePDF && iEffColorId == MY_WHITE ) ? GetBackgroundColor() :  colorMgr.GetPixmapColor(iEffColorId);

				GetLRTB(board, 100, j, i, L, R, T, B);	// 100% size square
				const int X((L+R)/2), Y((T+B)/2);
				const QPointF pCentre(X,Y);
				const QPointF pCentreOff(X+padOffsetX, Y+padOffsetY);

				// Common special case: Draw blank wire-ends as squares (so we can easily see them)
				if ( nodeId == BAD_NODEID && bWire )
				{
					painter.setPen(wirePen);
					painter.setBrush(Qt::NoBrush);
					painter.drawRect(X-iWireBoxWidth, Y-iWireBoxWidth, iWireBoxWidth*2, iWireBoxWidth*2);
					if ( !bSoicPad ) continue;	// Next grid square
				}

				// Note that bVero, bGroundFill, bDirect are mutually exclusive

				if ( bVero ) // Vero shows squares and strips with holes
				{
					if ( bPCB ) continue;	// Vero mode not compatible with PCB mode

					const bool bVertical = board.GetVerticalStrips();
					if ( bVertical )
					{
						L += iHalfGap;
						R -= iHalfGap;
					}
					else
					{
						T += iHalfGap;
						B -= iHalfGap;
					}
					painter.setBrush(color);
					painter.setPen(Qt::NoPen);
					painter.drawRect(L, T, R-L, B-T);
					m_backgroundPen.setWidth(std::max(1, W/4));
					painter.setPen(m_backgroundPen);
					painter.setBrush(Qt::NoBrush);
					painter.drawPoint(pCentre);

					// Emphasize strip breaks
					painter.setPen(Qt::NoPen);
					painter.setBrush(m_backgroundBrush);
					if ( bVertical )
					{
						if ( j > minRow && pC->GetNbr(NBR_T)->IsClash(nodeId) ) painter.drawRect(L, T-iHalfGap, R-L, iGap);
						if ( j < maxRow && pC->GetNbr(NBR_B)->IsClash(nodeId) ) painter.drawRect(L, B-iHalfGap, R-L, iGap);
					}
					else
					{
						if ( i > minCol && pC->GetNbr(NBR_L)->IsClash(nodeId) ) painter.drawRect(L-iHalfGap, T, iGap, B-T);
						if ( i < maxCol && pC->GetNbr(NBR_R)->IsClash(nodeId) ) painter.drawRect(R-iHalfGap, B, iGap, B-T);
					}
				}
				if ( bGroundFill )	// Draw track "blobs" and pads directly (PDF/Gerber)
				{
					if ( iLoop == 0 )
					{
						if ( !bIsGnd && bDrawBlob )	// Only the non-ground tracks have a "white" surround
							PaintBlob(board, painter, backgroundColor, pCentre, pCentreOff, iPadWidthMIL, iPerimeterCode, iTagCode, bPad, bSoicPad, bIsGnd, true);	// Draw fat "white" track blob
						if ( !bIsGnd && bDrawVia )	// Only the non-ground vias have a "white" surround
							PaintVia(board, painter, backgroundColor, pCentre, true);	// Draw fat "white" via
						if ( bDrawPad ) PaintPad(board, painter, backgroundColor, pCentreOff, iPadWidthMIL, iHoleWidthMIL, true);	// Draw fat "white" pad
						if ( bSoicPad ) PaintSOIC(board, painter, backgroundColor, pCentre, iPinIndexSOIC, pCompSOIC, bIsGnd, true);
					}
					else if ( iLoop == 1 )	// Draw track "blobs" and pads directly
					{
						if ( bDrawBlob ) PaintBlob(board, painter, color, pCentre, pCentreOff, iPadWidthMIL, iPerimeterCode, iTagCode, bPad, bSoicPad, bIsGnd);	// Draw track blob
						if ( bDrawVia )  PaintVia(board, painter, color, pCentre);									// Draw via same color as track
						if ( bDrawPad )  PaintPad(board, painter, color, pCentreOff, iPadWidthMIL, iHoleWidthMIL);	// Draw pad same color as track
						if ( bSoicPad ) PaintSOIC(board, painter, color, pCentre, iPinIndexSOIC, pCompSOIC, bIsGnd);
					}
					else if ( bDrawGrey )
					{
						if ( bDrawVia ) PaintViaGrey(board, painter, pCentre);								// Draw grey via
						if ( bDrawPad ) PaintPadGrey(board, painter, greyPen, pCentreOff, iPadWidthMIL);	// Draw "grey" pad
					}
				}
				if ( bDirect )	// Draw track "blobs" and pads directly (PDF/Gerber)
				{
					if ( iLoop == 0 )
					{
						if ( bDrawBlob ) PaintBlob(board, painter, color, pCentre, pCentreOff, iPadWidthMIL, iPerimeterCode, iTagCode, bPad, bSoicPad, false);	// Draw track blob
						if ( bDrawVia )  PaintVia(board, painter, color, pCentre);									// Draw via same color as track
						if ( bDrawPad )  PaintPad(board, painter, color, pCentreOff, iPadWidthMIL, iHoleWidthMIL);	// Draw pad same color as track
						if ( bSoicPad ) PaintSOIC(board, painter, color, pCentre, iPinIndexSOIC, pCompSOIC, bIsGnd);
					}
					else if ( bDrawGrey )
					{
						if ( bDrawVia ) PaintViaGrey(board, painter, pCentre);								// Draw grey via
						if ( bDrawPad ) PaintPadGrey(board, painter, greyPen, pCentreOff, iPadWidthMIL);	// Draw "grey" pad
					}
				}
			}
			if ( bWiresAsTracks )
			{
				for (const auto& pComp : sortedComps)	// Iterate sorted components
				{
					const Component& comp = *pComp;
					if ( comp.GetType() != COMP::WIRE || !comp.GetIsPlaced() ) continue;	// Only want placed wires
					if ( !compMgr.GetWireCanBeTrack(&comp) ) continue;

					QPolygonF polygon;
					GetXY(board, comp.GetRow(), comp.GetCol(), X, Y);
					polygon << QPointF(X, Y);
					GetXY(board, comp.GetRow() + comp.GetCompRows() - 1, comp.GetCol() + comp.GetCompCols() - 1, X, Y);
					polygon << QPointF(X, Y);
					m_gWriter.GetStream(GFILE::GTL).AddTrack(polygon, bGap ? GPEN::TRK_GAP : GPEN::TRK);
				}
			}
			if ( m_bWriteGerber )
			{
				m_gWriter.GetStream(GFILE::GTS).DrawBuffers();	// Top solder mask layer
				m_gWriter.GetStream(GFILE::GTL).DrawBuffers();	// Top copper layer
				m_gWriter.GetStream(GFILE::GBS).DrawBuffers();	// Bottom solder mask layer
				m_gWriter.GetStream(GFILE::GBL).DrawBuffers();	// Bottom copper layer
				m_gWriter.GetStream(GFILE::DRL).DrawBuffers();	// Drill file
			}
		}	// Next iLoop
		painter.restore();
	}

	// Draw target board area ====================================================================
	if ( m_board.GetShowTarget() && !bMonoPCB )
	{
		const int targetT = ( board.GetRows() - m_board.GetTargetRows() ) / 2;
		const int targetB = targetT + m_board.GetTargetRows() - 1;
		const int targetL = ( board.GetCols() - m_board.GetTargetCols() ) / 2;
		const int targetR = targetL + m_board.GetTargetCols() - 1;

		int l(0), r(0), t(0), b(0);
		GetXY(board, 0, 0, L, T);
		GetXY(board, board.GetRows()-1, board.GetCols()-1, R, B);
		GetXY(board, targetT, targetL, l, t);
		GetXY(board, targetB, targetR, r, b);
		L -= C; l -= C; T -= C; t -= C;
		R += C; r += C; B += C; b += C;

		painter.save();
		m_varBrush.setColor( QColor(0,128,128,32) );	// Very transparent light cyan tint
		painter.setPen(Qt::NoPen);
		painter.setBrush(m_varBrush);
		painter.drawRect(L, T, R-L, t-T);
		painter.drawRect(L, t, l-L, b-t);
		painter.drawRect(r, t, R-r, b-t);
		painter.drawRect(L, b, R-L, B-b);
		painter.restore();
	}

	// Draw hatched lines ========================================================================
	if ( !m_bWriteGerber && trackMode != TRACKMODE::OFF && board.GetRoutingEnabled() )
	{
		painter.save();
		m_redPen.setWidth(W / 8);
		m_backgroundPen.setWidth(0);
		painter.setBrush(Qt::NoBrush);
		for (int j = minRow; j <= maxRow; j++)
		for (int i = minCol; i <= maxCol; i++)
		{
			const Element* pC = board.Get(layer, j, i);
			if ( pC->GetNodeId() == BAD_NODEID ) continue;
			GetLRTB(board, 100, j, i, L, R, T, B);	// 100% size square

			if ( pC->ReadFlagBits(AUTOSET) && !pC->ReadFlagBits(USERSET) )
			{
				painter.setPen(m_backgroundPen);
				painter.drawLine(L, T, R, B);		// Draw "\" (hatched) line
				painter.drawLine(L+C, T, R, B-C);	// Draw "\" (hatched) line
				painter.drawLine(L, T+C, R-C, B);	// Draw "\" (hatched) line
				painter.drawLine(L, B, R, T);		// Draw "/" (hatched) line
				painter.drawLine(L+C, B, R, T+C);	// Draw "/" (hatched) line
				painter.drawLine(L, B-C, R-C, T);	// Draw "/" (hatched) line
			}
		}
		painter.restore();
	}

#ifdef _GRID_DEBUG
	if ( m_iGridDebugMode != DEBUGMODE_OFF && m_iGridDebugMode != DEBUGMODE_LAYERINFO )
	{
		painter.save();
		painter.setPen(Qt::NoPen);
		painter.setBrush(m_darkBrush);
		for (int j = minRow; j <= maxRow; j++)
		for (int i = minCol; i <= maxCol; i++)
		{
			const Element* pC = board.Get(layer, j, i);
			int iVal;
			switch( m_iGridDebugMode )
			{
				case DEBUGMODE_SOICINFO:	iVal = (int) pC->GetSoicChar();	break;
				case DEBUGMODE_ROUTEID:		iVal = pC->GetRouteId();		break;
				case DEBUGMODE_NODEID:		iVal = pC->GetNodeId();			break;
				case DEBUGMODE_PININDEX:	iVal = pC->GetSlotPinIndex(0);	break;
			}
			GetLRTB(board, 100, j, i, L, R, T, B);	// 100% size square
			painter.save();
			painter.translate((L+R)/2, (T+B)/2);
			painter.scale(dTextScale, dTextScale);
			painter.setPen(m_blackPen);
			painter.drawText(0,0,0,0, Qt::TextDontClip | Qt::AlignVCenter | Qt::AlignHCenter, std::to_string(iVal).c_str());
			painter.restore();
		}
		painter.restore();
	}
#endif

	// Draw solder ===============================================================================
	if ( ( bColor || bMono ) && bVero )
	{
		const bool bVertical = board.GetVerticalStrips();
		painter.save();
		painter.setPen(Qt::NoPen);
		painter.setBrush(m_darkBrush);
		for (int j = minRow; j <= maxRow; j++)
		for (int i = minCol; i <= maxCol; i++)
		{
			const Element* pC = board.Get(layer, j, i);
			if ( !pC->GetSolderR() ) continue;
			GetLRTB(board, 100, j, i, L, R, T, B);	// 100% size square
			if ( bVertical )
				painter.drawEllipse(R-(W/3), (T+B)/2 - (W/6), (2*W)/3, W/3);
			else
				painter.drawEllipse((L+R)/2 - (W/6), B-(W/3), W/3, (2*W)/3);
		}
		painter.restore();
	}

	// Draw vias =================================================================================
	if ( !m_bWriteGerber && !bVero && ( bPCB || trackMode != TRACKMODE::OFF ) )	// Force in PCB mode
	{
		painter.save();
		m_backgroundPen.setWidth( board.GetPixelsFromMIL( board.GetVIAHOLE_MIL() ) );
		painter.setPen(m_backgroundPen);
		painter.setBrush(Qt::NoBrush);
		for (int j = minRow; j <= maxRow; j++)
		for (int i = minCol; i <= maxCol; i++)
		{
			const Element* pC = board.Get(layer, j, i);
			if ( !pC->GetIsVia() ) continue;
			GetLRTB(board, 100, j, i, L, R, T, B);	// 100% size square
			painter.drawPoint((L+R)/2, (T+B)/2);
		}
		painter.restore();
	}

	// Draw Component outlines and pins ==========================================================
	QPen& penPlaced	= ( bMono ) ? m_lightBluePen : ( bPCB ) ? m_whitePen : m_blackPen;	// For placed (non-floating) components
	QPen  fillBlackPen = m_blackPen;	// Used for lines in the component pixmap
	fillBlackPen.setWidth(2);

	if ( compMode != COMPSMODE::OFF || bMonoPCB )	// Mono/PCB modes still need pin holes drawn for placed parts
	{
		const bool bFill = !bMonoPCB && board.GetFillSaturation() > 0;	// No component fill in Mono/PCB mode
		for (const auto& pComp : sortedComps)	// Iterate sorted components
		{
			const Component& comp			= *pComp;
			const COMP&		 compType		= comp.GetType();
			const char&		 compDirection	= comp.GetDirection();
			const bool		 bMark			= compType == COMP::MARK;
			const bool		 bWire			= compType == COMP::WIRE;
			const bool		 bVeroLabel		= compType == COMP::VERO_NUMBER || compType == COMP::VERO_LETTER;
			const bool		 bSOIC			= comp.GetIsSOIC();
			const bool		 bPlaced		= comp.GetIsPlaced();
			if ( bPCB && (bMark || bVeroLabel) )	continue;	// Don't show markers and vero-lables in PCB mode
			if ( m_bWriteGerber && !bPlaced ) continue;	// Don't write floating components to Gerber
			if ( bWiresAsTracks && bWire && compMgr.GetWireCanBeTrack(&comp) ) continue;
			const bool		 bFound			= compMgr.GetFound( comp.GetId() );
			const bool		 bPinLabels		= !bMonoPCB && (comp.GetPinFlags() & PIN_LABELS) > 0 && board.GetShowPinLabels() && (!bSOIC || bTopLyr);	// Only show SOIC pin labels on top layer
			const bool		 bRectPins		= !bMonoPCB && (comp.GetPinFlags() & PIN_RECT) > 0;
			const bool		 bHighlightComp	= board.GetGroupMgr().GetIsUserComp( comp.GetId() );
			const bool		 bCustomSize	= comp.GetCustomPads();
			const int		 iPadWidthMIL	= bCustomSize ? comp.GetPadWidth()  : board.GetPAD_MIL();
			const int		 iHoleWidthMIL	= bCustomSize ? comp.GetHoleWidth() : board.GetHOLE_MIL();
			const bool		 blankWire		= bWire && comp.GetNodeId(0) == BAD_NODEID;

			// Begin draw component pins ---------------------------------------------------------
			if ( !m_bWriteGerber && !blankWire && ( compMode != COMPSMODE::OFF || ( bMonoPCB && bPlaced && !bSOIC ) ) ) 	// Skip blank wires and SOIC parts
			{
				painter.save();

				QFont pinsFont = painter.font();	// Copy of current font
				pinsFont.setPointSize( m_board.GetTextSizePins() );
				painter.setFont(pinsFont);

				if ( bMonoPCB && bPlaced && !bSOIC )
				{
					m_backgroundPen.setWidth( board.GetPixelsFromMIL(iHoleWidthMIL) );
					painter.setPen(m_backgroundPen);
				}
				else
				{
					penPlaced.setWidth(0);		// For pin labels
					m_orangePen.setWidth(0);	// For pin labels and pins
					m_redPen.setWidth(0);		// For pin labels and pins
					m_greyPen.setWidth(0);		// For pins
					painter.setPen(bFound ? m_orangePen : bPlaced ? m_greyPen : m_redPen);
				}
				painter.setBrush(Qt::NoBrush);

				if ( bMark )	// Markers are a special case since they don't actually have a pin !!!
				{
					// Only draw markers as holes in ground fill MONO mode and only in places with no track
					if ( bMono && bGroundFill && board.Get(layer, comp.GetRow(), comp.GetCol())->GetNodeId() == BAD_NODEID )
					{
						GetLRTB(board, 100, comp.GetRow(), comp.GetCol(), L, R, T, B);	// 100% size square
						painter.drawPoint((L+R)/2, (T+B)/2);							// A pin is drawn with a circle
					}
				}
				else			// Regular components/pads/wires ...
				{
					for (int jj = 0, jjMax = comp.GetCompRows(), j = comp.GetRow(); jj < jjMax; jj++, j++)
					for (int ii = 0, iiMax = comp.GetCompCols(), i = comp.GetCol(); ii < iiMax; ii++, i++)
					{
						const size_t iPinIndex = comp.GetCompElement(jj,ii)->GetPinIndex();
						if ( iPinIndex == BAD_PININDEX ) continue;

						int padOffsetX(0), padOffsetY(0);
						if ( !bWire && !bVero && !bSOIC )
						{
							comp.GetCompPinOffsets(iPinIndex, padOffsetX, padOffsetY);	// Get offsets in mil
							padOffsetX = (padOffsetX * W) / 100;	// Convert from mil to pixels
							padOffsetY = (padOffsetY * W) / 100;	// Convert from mil to pixels
						}

						if ( !bPlaced )	// If floating component ...
						{
							if ( bColor )	// Color pins (if in Color mode)
							{
								const int&	 nodeId			= comp.GetNodeId(iPinIndex);
								const bool	 bCurrentNodeId	= nodeId != BAD_NODEID && nodeId == GetCurrentNodeId();
								const QColor color			= bCurrentNodeId ? colorMgr.GetPixmapColor(MY_GREY)
																			 : colorMgr.GetColorFromNodeId(nodeId);
								m_varPen.setColor(color);
								m_varBrush.setColor(color);
								painter.setBrush( bMonoPCB ? Qt::NoBrush : m_varBrush);	// No pin color fill in Mono/PCB mode
							}
							if ( bSOIC && bTopLyr )	//	Draw tracks of floating IC
							{
								int X, Y;
								GetXY(board, j, i, X, Y);
								PaintSOIC(board, painter, Qt::red, QPointF(X,Y), iPinIndex, &comp, false, false);
							}
						}

						const int iPinSizeMIL = ( !bColor || bPlaced ) ? iHoleWidthMIL : std::min(3*iHoleWidthMIL/2, iPadWidthMIL);
						GetLRTB(board, iPinSizeMIL, j, i, L, R, T, B);
						L += padOffsetX;	R += padOffsetX;	T += padOffsetY;	B += padOffsetY;

						// Stop pins vanishing if zoomed too far out
						if ( L == R ) { L--; R++; }
						if ( T == B ) { T--; B++; }

						if ( bPinLabels )	// Write pin labels
						{
							painter.save();
							painter.translate((L+R)/2, (T+B)/2);

							// Set text orientation
							switch( compDirection )
							{
								case 'W':
								case 'E':	painter.rotate(270);	break;
							}

							// Handle L/R pin label alignment
							int iFlag = comp.GetPinAlign(iPinIndex);
							if ( iFlag == Qt::AlignLeft || iFlag == Qt::AlignRight )
							{
								const bool bLeft = ( iFlag == Qt::AlignLeft );
								switch( compDirection )
								{
									case 'E':
									case 'S':	iFlag = bLeft ? Qt::AlignRight : Qt::AlignLeft;	// Swap align L/R
												painter.translate(bLeft ? C/2 : -C/2, 0);
												break;
									default:	painter.translate(bLeft ? -C/2 : C/2, 0);
								}
							}
							iFlag |= ( Qt::TextDontClip | Qt::AlignVCenter );

							painter.scale(dTextScale, dTextScale);
							painter.setPen(bFound ? m_orangePen : bPlaced ? penPlaced : m_redPen);
							painter.drawText(0,0,0,0, iFlag, comp.GetPinLabel(iPinIndex).c_str());
							painter.restore();
						}
						else if ( bRectPins )	// Draw switch pins as rectangles
						{
							const int d = board.GetHalfPixelsFromMIL( iPinSizeMIL );
							switch( compDirection )
							{
								case 'W':
								case 'E':	L -= d; R += d;	break;
								case 'N':
								case 'S':	T -= d; B += d;	break;
							}
							painter.drawRect(L, T, R-L, B-T);
						}
						else	// A regular pin is drawn as a circle
						{
							if ( bMonoPCB && bPlaced && !bSOIC )
							{
								GetLRTB(board, 100, j, i, L, R, T, B);	// 100% size square
								painter.drawPoint(padOffsetX + (L+R)/2, padOffsetY + (T+B)/2);
							}
							else if ( !bSOIC || ( bColor && bPlaced && bTopLyr ) )	// OK to highlight pin location for placed SOICs in color mode
								painter.drawEllipse(L, T, R-L, B-T);	
						}
					}
				}
				painter.restore();
			}
			// End draw component pins -----------------------------------------------------------

			// Begin draw component fill + outline -----------------------------------------------
			if ( compMode != COMPSMODE::OFF && !comp.GetShapes().empty() )
			{
				// Set pen width.  Selected component shown thicker than normal components

				if ( bFound )
					m_orangePen.setWidth(4);// Make found components stand out
				else if ( bPlaced )
				{
					if ( bMonoPCB )	// Use floating point pen width to better match Gerber output
						penPlaced.setWidthF( bHighlightComp ? ( board.GetSilkWidth() * 1.5 )
															: ( bMark ? ( board.GetSilkWidth() * 0.5 )
																	  :   board.GetSilkWidth() ) );
					else
						penPlaced.setWidth( bHighlightComp ? 3 : bMark ? 1 : 2 );
				}
				else
					m_redPen.setWidth(4);	// Make floating components stand out in red

				QPen& linePen = bFound ? m_orangePen : bPlaced ? penPlaced : m_redPen;
				painter.setPen(linePen);
				painter.setBrush(Qt::NoBrush);

				GetXY(board, comp, X, Y);	// Get footprint centre

				// Implement wire shift
				if ( bWire && bPlaced )
				{
					if ( comp.GetCompRows() == 1 )	// Horizontal
						Y += compMgr.GetWireShift( &comp ) * 0.1 * W;
					else
						X += compMgr.GetWireShift( &comp ) * 0.1 * W;
				}

				double SL,ST,SR,SB;
				comp.GetSafeBounds(SL,SR,ST,SB);
				SL = SL * W - C;	SR = SR * W + C;
				ST = ST * W - C;	SB = SB * W + C;
				const int iReqW	= static_cast<int>(SR - SL);
				const int iReqH	= static_cast<int>(SB - ST);
				const int iSL	= static_cast<int>(SL);
				const int iST	= static_cast<int>(ST);
				GPainter painterTmp;
				QPixmap tmpPixmap(iReqW, iReqH);
				tmpPixmap.setDevicePixelRatio(1.0);
				const QColor maskColor = comp.GetNewColor().GetQColor();// We'll mask out pixels with this color at the end

				if ( bFill )
				{
					painterTmp.begin(&tmpPixmap);
					painterTmp.fillRect(0, 0, iReqW, iReqH, maskColor);	// This will be turned transparent later
					painterTmp.setPen(Qt::NoPen);
				}

				for (int iLoop = ( bFill ) ? 0 : 1; iLoop < 2; iLoop++)
				{
					GPainter* pPainter = ( iLoop == 0 ) ? &painterTmp : &painter;

					pPainter->save();	// Save (original axes)
					if ( iLoop == 0 )
						pPainter->translate(-SL,-ST);	// Shape coordinates are relative to pixmap top left
					else
						pPainter->translate(X, Y);		// Shape coordinates are relative to footprint centre

					if ( bFill && iLoop == 1 )	// Draw the pixmap created on the previous pass
					{
						painter.setOpacity( /*bWire ? 1.0 :*/ board.GetFillSaturation() * 0.01);
						painter.drawPixmap(iSL, iST, tmpPixmap);
						painter.setOpacity(1.0);
					}

					switch( compDirection )	// Rotated axes at footprint centre
					{
						case 'W':	break;
						case 'E':	pPainter->rotate(180);	break;
						case 'N':	pPainter->rotate(90);	break;
						case 'S':	pPainter->rotate(270);	break;
					}

					for (size_t i = 0, numShapes = comp.GetNumShapes(); i < numShapes; i++)
					{
						const Shape& s = comp.GetShape(i);

						if ( iLoop == 0 && !s.GetDrawFill() ) continue;
						if ( iLoop == 1 && (s.GetDrawFill() || !s.GetDrawLine()) ) continue;
						if ( iLoop == 0 )	// Drawing fill
						{
							m_varBrush.setColor( s.GetFillColor().GetQColor() );
							pPainter->setBrush(m_varBrush);
							pPainter->setPen( s.GetDrawLine() ? fillBlackPen : Qt::NoPen );
						}
						else if ( bColor && !bFill && bWire )	// If Fill slider if fully left in Color mode, draw wire in color
						{
							const int nodeId = comp.GetNodeId(0);
							if ( nodeId != BAD_NODEID )
							{
								const QColor color = ( nodeId == GetCurrentNodeId() ) ? colorMgr.GetPixmapColor(MY_GREY)
																					  : colorMgr.GetColorFromNodeId(nodeId);
								m_varBrush.setColor( color );
								pPainter->setBrush(m_varBrush);
								pPainter->setPen( s.GetDrawLine() ? fillBlackPen : Qt::NoPen );
							}
						}

						pPainter->save();
						pPainter->translate( s.GetCX() * W, s.GetCY() * W );	// Translate to shape centre
						pPainter->rotate( -s.GetA3() );	// A3 > 0 ==> CCW		// Rotate about shape centre

						const int DX	= static_cast<int>(s.GetDX() * W);
						const int DY	= static_cast<int>(s.GetDY() * W);
						const int X		= static_cast<int>(s.GetDX() * W * 0.5);
						const int Y		= static_cast<int>(s.GetDY() * W * 0.5);
						const int A		= static_cast<int>(s.GetA1() * 16);
						const int Alen	= static_cast<int>(s.GetAlen() * 16);
						switch( s.GetType() )
						{
							case SHAPE::RECT:			pPainter->drawRect(-X, -Y, DX, DY);	break;
							case SHAPE::ROUNDED_RECT:	pPainter->drawRoundedRect(-X, -Y, DX, DY, 0.35 * W, 0.35 * W);	break;
							case SHAPE::ELLIPSE:		pPainter->drawEllipse(-X, -Y, DX, DY);	break;
							case SHAPE::ARC:			pPainter->drawArc(  -X, -Y, DX, DY, A, Alen);	break;
							case SHAPE::CHORD:			pPainter->drawChord(-X, -Y, DX, DY, A, Alen);	break;
							default:					assert( SHAPE::LINE == s.GetType() );
														pPainter->drawLine(-X, -Y, X, Y);	break;
						}
						pPainter->restore();
					}
					pPainter->restore();	// Restore (original axes)

					if ( iLoop == 0 )	// Finish off making the pixmap
					{
						painterTmp.end();
						// Turn the "mask" pixels transparent
						tmpPixmap.setMask( tmpPixmap.createMaskFromColor(maskColor, Qt::MaskInColor) );
					}
				}
			}
		}
	}

	// Draw air wires ============================================================================
	if ( !m_bWriteGerber && trackMode != TRACKMODE::OFF && GetCurrentNodeId() != BAD_NODEID )
	{
		painter.save();
		m_redPen.setWidth( static_cast<int>(0.175 * W) );
		m_redPen.setCapStyle(Qt::SquareCap);
		m_redPen.setStyle(Qt::DotLine);
		painter.setPen(m_redPen);
		painter.setBrush(Qt::NoBrush);

		int padOffsetX(0), padOffsetY(0);	// For handling offset pads

		std::list<SpanningTreeHelper::AIRWIRE_POINT> spanTreePoints;

		for (int jj = minRow; jj <= maxRow; jj++)
		for (int ii = minCol; ii <= maxCol; ii++)
		{
			Element*	pD		= board.Get(0, jj, ii);	// Layer 0 only
			const bool	bPin	= pD->GetHasPin() && !pD->GetHasWire();
			if ( !bPin ) continue;

			// We may just have an SOIC pad on layer 1, but pD is on layer 0, so ...
			if ( !pD->GetHasPinTH() ) pD = pD->GetNbr(NBR_X);

			if ( pD == nullptr || pD->GetNodeId() != GetCurrentNodeId() ) continue;

			GetXY(board, jj, ii, X, Y);

			// Handle offset pads
			if ( !bVero && board.GetPadOffsets(pD, padOffsetX, padOffsetY) )	// Get offsets in mil
			{
				X += (padOffsetX * W) / 100;	// Convert from mil to pixels
				Y += (padOffsetY * W) / 100;	// Convert from mil to pixels
			}

			spanTreePoints.push_back( SpanningTreeHelper::AIRWIRE_POINT(QPointF(X, Y), pD->GetRouteId()) );
		}

		std::list< SpanningTreeHelper::AIRWIRE_LINE > spanTreeLines;
		SpanningTreeHelper::BuildAirWires(spanTreePoints, spanTreeLines);	// Build air-wires

		for (const auto& o : spanTreeLines)
			painter.drawLine(o.first.first, o.second.first);

		m_redPen.setCapStyle(Qt::RoundCap);
		m_redPen.setStyle(Qt::SolidLine);
		painter.restore();
	}

	// Draw flying wires =========================================================================
	if ( !m_bWriteGerber && !bMonoPCB && compMode != COMPSMODE::OFF && board.GetShowFlyWires() )
	{
		painter.save();

		QPen  blackPen = m_blackPen;	// Used for lines in the component pixmap
		blackPen.setWidth(2);
		m_varPen.setWidth(static_cast<int>(0.175 * W));
		m_varPen.setCapStyle(Qt::SquareCap);
		m_varPen.setStyle(Qt::DotLine);
		painter.setBrush(Qt::NoBrush);
		const int		dH = static_cast<int>(0.1*W);	// Param for wire rounded rect
		const double	dW(0.35*W);						// Param for wire rounded rect

		int padOffsetX(0), padOffsetY(0);	// For handling offset pads

		std::set<int> visitedNodeIds;

		for (int j = minRow; j <= maxRow; j++)
		for (int i = minCol; i <= maxCol; i++)
		{
			Element*	pC		= board.Get(0, j, i);	// Layer 0 only
			if ( !board.GetAllowFlyWire(pC) ) continue;
			const int&	nodeId	= pC->GetNodeId();
			if ( visitedNodeIds.find(nodeId) != visitedNodeIds.end() ) continue;
			visitedNodeIds.insert(nodeId);

			const bool	 bCurrentNodeId	= nodeId == GetCurrentNodeId();
			const QColor color	= bCurrentNodeId ? colorMgr.GetPixmapColor(MY_GREY)
												 : colorMgr.GetColorFromNodeId(nodeId);
			m_varPen.setColor(color);

			std::list<QPointF> spanTreePoints;

			GetXY(board, j, i, X, Y);

			// Handle offset pads
			if ( !bVero && board.GetPadOffsets(pC, padOffsetX, padOffsetY) )	// Get offsets in mil
			{
				X += (padOffsetX * W) / 100;	// Convert from mil to pixels
				Y += (padOffsetY * W) / 100;	// Convert from mil to pixels
			}

			spanTreePoints.push_back( QPointF(X, Y) );

			for (int jj = j; jj <= maxRow; jj++)
			for (int ii = (jj == j) ? (i+1) : minCol; ii <= maxCol; ii++)
			{
				Element*	pD	= board.Get(0, jj, ii);	// Layer 0 only
				if ( pD->GetNodeId() != nodeId || !board.GetAllowFlyWire(pD) ) continue;

				GetXY(board, jj, ii, X, Y);

				// Handle offset pads
				if ( !bVero && board.GetPadOffsets(pD, padOffsetX, padOffsetY) )	// Get offsets in mil
				{
					X += (padOffsetX * W) / 100;	// Convert from mil to pixels
					Y += (padOffsetY * W) / 100;	// Convert from mil to pixels
				}

				spanTreePoints.push_back( QPointF(X, Y) );
			}

			std::list< SpanningTreeHelper::LINE > spanTreeLines;
			SpanningTreeHelper::Build(spanTreePoints, spanTreeLines, true);	// true ==> daisy chain
			for (const auto& o : spanTreeLines)
			{
				const QPointF	vec	= ( o.second - o.first );
				const QPointF	mid	= ( o.second + o.first ) * 0.5;
				const int		dL	= static_cast<int>(PolygonHelper::Length(vec) * 0.5);
				painter.save();
				painter.translate(mid.x(), mid.y());
				painter.rotate(atan2(vec.y(), vec.x()) * DEGREES_PER_RADIAN);
				painter.setPen(m_varPen);		painter.drawLine(-dL, 0, dL, 0);
				painter.setPen(fillBlackPen);	painter.drawRoundedRect(-dL, -dH, dL+dL, dH+dH, dW, dW);
				painter.restore();
			}
		}
		m_varPen.setCapStyle(Qt::RoundCap);
		painter.restore();
	}

	// Draw component text =======================================================================
	if ( compMode != COMPSMODE::OFF )
	{
		for (const auto& pComp : sortedComps)	// Iterate sorted components
		{
			const Component& comp			= *pComp;
			const COMP&		 compType		= comp.GetType();
			const char&		 compDirection	= comp.GetDirection();
			const bool		 bMark			= compType == COMP::MARK;
			const bool		 bWire			= compType == COMP::WIRE;
			const bool		 bVeroLabel		= compType == COMP::VERO_NUMBER || compType == COMP::VERO_LETTER;
			if ( bMark || bWire || bVeroLabel ) continue;
			const bool		 bPlaced		= comp.GetIsPlaced();
			if ( m_bWriteGerber && !bPlaced ) continue;		// Don't write floating components to Gerber
			const bool		 bFound			= compMgr.GetFound( comp.GetId() );

			painter.save();
			double dCopyTextScale = dTextScale;
			if ( bMonoPCB )
			{
				dCopyTextScale *= m_board.GetTextSizeComp() * (20.0 / 243 );	// Scale to make the Gerber font size similar to regular component font size
			}
			else
			{
				QFont compFont = painter.font();	// Copy of current font
				compFont.setPointSize( m_board.GetTextSizeComp() );
				painter.setFont(compFont);
			}

			// Use floating point pen width to better match Gerber output.
			// Scale the pen width down to compensate for painter.scale() scaling things up in the loop below.
			const double dPenWidth = ( bMonoPCB ) ? board.GetSilkWidth() / dCopyTextScale : 0;
			m_orangePen.setWidthF(dPenWidth);	// Use colored text for found components
			m_redPen.setWidthF(dPenWidth);		// Use red text for floating components
			penPlaced.setWidthF(dPenWidth);		// Use this for placed components

			GetXY(board, comp, X, Y);	// Get footprint centre

			int offsetRow(0), offsetCol(0);
			comp.GetLabelOffsets(offsetRow, offsetCol);

			X += W * 0.0625 * offsetCol; // Offset for text is 1/16 of a grid square
			Y += W * 0.0625 * offsetRow; // Offset for text is 1/16 of a grid square

			painter.translate(X, Y);
			if ( compDirection == 'N' || compDirection == 'S' )
				painter.rotate(270);

			const std::string& myStr = ( compMode == COMPSMODE::NAME )  ? comp.GetNameStr() :
									   ( compMode == COMPSMODE::VALUE ) ? comp.GetValueStr() : "";

			painter.scale(dCopyTextScale, dCopyTextScale);
			painter.setPen(bFound ? m_orangePen : bPlaced ? penPlaced : m_redPen);
			painter.drawText(0,0,0,0, Qt::AlignCenter | Qt::TextDontClip, myStr.c_str(), bMonoPCB);
			painter.restore();
		}
	}

	// Draw the User-defined "trax" component ====================================================
	if ( !m_bWriteGerber && ( compMode != COMPSMODE::OFF || trackMode != TRACKMODE::OFF ) )
	{
		Component& trax = compMgr.GetTrax();
		if ( trax.GetSize() > 0 )
		{
			if ( trax.GetIsPlaced() )
				m_varBrush.setColor( QColor(128,128,128,128) );	// light grey
			else
				m_varBrush.setColor( QColor(192,128,192,128) );	// magenta tint
			painter.setPen(Qt::NoPen);
			painter.setBrush(m_varBrush);

			for (int j = 0, jRow = trax.GetRow(), compRows = trax.GetCompRows(); j < compRows; j++, jRow++)
			for (int i = 0, iCol = trax.GetCol(), compCols = trax.GetCompCols(); i < compCols; i++, iCol++)
				if ( trax.GetCompElement(j, i)->ReadFlagBits(RECTSET) )
				{
					GetLRTB(board, 100, jRow, iCol, L, R, T, B);	// 100% size square
					painter.drawRect(L,T,R-L,B-T);
				}
		}
	}

	// Draw vero labels ==========================================================================
	if ( !bPCB )
	{
		painter.save();

		QFont labelsFont = painter.font();	// Copy of current font
		labelsFont.setPointSize( m_board.GetTextSizeComp() );
		painter.setFont(labelsFont);

		painter.setBrush(Qt::NoBrush);
		penPlaced.setWidth(0);
		m_redPen.setWidth(0);

		for (const auto& pComp : sortedComps)	// Iterate sorted components
		{
			const Component& comp			= *pComp;
			const COMP&		 compType		= comp.GetType();
			const bool		 bVeroNumber	= compType == COMP::VERO_NUMBER;
			const bool		 bVeroLetter	= compType == COMP::VERO_LETTER;
			if ( !(bVeroNumber || bVeroLetter) ) continue;
			const char&		 compDirection	= comp.GetDirection();
			const bool		 bPlaced		= comp.GetIsPlaced();	// Only unplaced when a label is created by copying another ("V" key)

			int index(0), length(comp.GetSize());
			for (int jj = 0, jjMax = comp.GetCompRows(), j = comp.GetRow(); jj < jjMax; jj++, j++)
			for (int ii = 0, iiMax = comp.GetCompCols(), i = comp.GetCol(); ii < iiMax; ii++, i++, index++)
			{
				GetLRTB(board, 100, j, i, L, R, T, B);

				painter.save();
				painter.translate((L+R)/2, (T+B)/2);

				// Set text orientation, and forward/reverse number order
				int iNumber = index + 1;	// Increasing numbers by default
				switch( compDirection )
				{
					case 'W':	painter.rotate(270);			break;
					case 'E':	painter.rotate(270);
								iNumber = 1 + length - iNumber;	break;	// Reverse number order
					case 'S':	iNumber = 1 + length - iNumber;	break;	// Reverse number order
				}

				std::string label("");
				if ( bVeroNumber )	// Numbers go: 1,2,3 etc
					label = std::to_string(iNumber);
				else				// Letters go: A,B,...,Y,Z,AA,AB,...,AY,AZ,BA,BB, ... etc
				{
					if ( iNumber > 26 ) label += ( char('A') + static_cast<char>((iNumber-1)/26 - 1) );
					label += ( char('A') + (iNumber-1)%26 );
				}

				// We always want the vero labels to appear non-mirrored
				if ( board.GetFlipH() )	painter.scale(-1, 1);	// Mirror L-R
				if ( board.GetFlipV() )	painter.scale(1, -1);	// Mirror T-B

				painter.scale(dTextScale, dTextScale);
				painter.setPen(bPlaced ? penPlaced : m_redPen);
				painter.drawText(0,0,0,0, Qt::TextDontClip | Qt::AlignVCenter | Qt::AlignHCenter, label.c_str());
				painter.restore();
			}
		}
		painter.restore();
	}

	// Draw User-defined labels ==================================================================
	if ( !bPCB && board.GetShowText() )
	{
		QFont font = painter.font();	// Copy of current font
		TextManager& textMgr = m_board.GetTextMgr();
		for (const auto& mapObj : textMgr.GetMapIdToText())
		{
			const TextRect& rect = mapObj.second;
			if ( !rect.GetIsValid() ) continue;

			GetXY(board, rect.m_rowMin, rect.m_colMin, L, T);
			GetXY(board, rect.m_rowMax, rect.m_colMax, R, B);
			L -= C; T -= C; R += C; B += C;

			const int textW = static_cast<int>((R-L)/dTextScale);
			const int textH = static_cast<int>((B-T)/dTextScale);

			painter.save();
			font.setBold( rect.GetStyle() & TEXT_BOLD );
			font.setItalic( rect.GetStyle() & TEXT_ITALIC );
			font.setUnderline( rect.GetStyle() & TEXT_UNDERLINE );
			font.setPointSize( rect.GetSize() );
			painter.setFont(font);

			m_varPen.setColor(!bMono ? rect.GetQColor() : ( bGroundFill == bInverseMono ) ? Qt::black : Qt::white);
			painter.setPen(m_varPen);
			painter.setBrush(Qt::NoBrush);

			painter.translate((bMono && layer == 0) ? R : L, T);							// Mirror all text boxes in Mono mode for bottom layer
			painter.scale((bMono && layer == 0) ? -dTextScale : dTextScale, dTextScale);	// Mirror all text boxes in Mono mode for bottom layer
			painter.drawText(0, 0, textW, textH, Qt::TextWordWrap | rect.GetFlagsH() | rect.GetFlagsV(), QString::fromStdString(rect.GetStr()));
			painter.restore();

			if ( mapObj.first == GetCurrentTextId() )
			{
				painter.setPen(m_dotPen);
				painter.drawRect(L, T, R-L, B-T);
				painter.drawRect(R-C, B-C, C, C);
			}
		}
	}

	// Draw a cross on the pad being used for pad offset =========================================
	if ( !m_bWriteGerber && !bVero && m_padOffsetDlg->isVisible() )
	{
		const Element* pC = m_board.Get(layer, m_gridRow, m_gridCol);

		int padOffsetX(0), padOffsetY(0);
		if ( board.GetPadOffsets(pC, padOffsetX, padOffsetY) )	// Get offsets in mil
		{
			GetXY(board, m_gridRow, m_gridCol, X, Y);
			X += (padOffsetX * W) / 100;	// Convert from mil to pixels
			Y += (padOffsetY * W) / 100;	// Convert from mil to pixels

			painter.save();
			painter.setBrush(Qt::NoBrush);
			m_yellowPen.setWidth(2);
			painter.setPen(m_yellowPen);
			painter.drawLine(X-C, Y, X+C, Y);
			painter.drawLine(X, Y-C, X, Y+C);
			painter.restore();
		}
	}

	// Draw places of min track separation =======================================================
	if ( !m_bWriteGerber && !bVero && trackMode != TRACKMODE::OFF && m_board.GetShowCloseTracks() )
	{
		painter.save();
		painter.setBrush(Qt::NoBrush);
		for (int lyr = 0; lyr < m_board.GetLyrs(); lyr++)
		{
			m_orangePen.setWidth(lyr == layer ? 3 : 1);	// Current layer shown fatter
			painter.setPen(m_orangePen);
			for (const auto& o : m_board.GetWarnPoints(lyr))
			{
				GetXY(board, o.y(), o.x(), X, Y);
				if ( lyr == layer )
					painter.drawRect(X-C/3, Y-C/3, W/3, W/3);
				else
					painter.drawRect(X-C/6, Y-C/6, W/6, W/6);
			}
		}
		painter.restore();
	}

	if ( !m_bWriteGerber && m_bRuler )
	{
		QPointF A,B;
		GetRulerExact(board, m_rulerA, A);
		GetRulerExact(board, m_rulerB, B);

		int XA, YA, XB, YB;
		GetXY(board, A.ry(), A.rx(), XA, YA);
		GetXY(board, B.ry(), B.rx(), XB, YB);

		painter.save();
		m_rulerPen.setWidth(C);
		painter.setPen(m_rulerPen);
		painter.setBrush(Qt::NoBrush);
		painter.drawLine(XA,YA,XB,YB);
		painter.restore();
	}

	if ( m_bWriteGerber )
		m_gWriter.GetStream(GFILE::GTO).DrawBuffers();	// Top silk layer

#ifdef _GRID_DEBUG
	if ( m_iGridDebugMode == DEBUGMODE_LAYERINFO )
	{
		GetLRTB(board, 100, 0, 0, L, R, T, B);	// 100% size square
		painter.save();
		painter.translate((L+R)/2, (T+B)/2);
		painter.scale(dTextScale, dTextScale);
		painter.setPen(m_blackPen);
		std::string txt("nodeId  // nodeId  Srf  Soic  Hole //  Comp1  Pin1  OrigId  //  Comp2  Pin2  OrigId");
		painter.drawText(0,0,0,0, Qt::TextDontClip | Qt::AlignVCenter | Qt::AlignLeft, txt.c_str());
		painter.restore();

		for (int iLyr = 0; iLyr < board.GetLyrs(); iLyr++)
		{
			const Element* pC = m_board.Get(iLyr, m_gridRow, m_gridCol);
			std::string txt;
			if ( layer == iLyr )
				txt = "*";
			else
				txt = " ";
			const int iNodeId		= pC->GetNodeId();				txt += std::to_string(iNodeId) + " // ";	
			const int iNodeIdRaw	= pC->GetNodeIdRaw();			txt += std::to_string(iNodeIdRaw) + " ";
			const int iSurface		= (int)pC->GetSurfaceRaw();		txt += std::to_string(iSurface) + " ";
			const int iSoic			= (int)pC->GetSoicCharRaw();	txt += std::to_string(iSoic) + " ";
			const int iHole			= (int)pC->GetHoleUseRaw();		txt += std::to_string(iHole) + " // ";
			const int iCompId		= pC->GetCompIdRaw();			txt += std::to_string(iCompId) + "  ";
			const int iPinIndex		= pC->GetPinIndexRaw();			txt += std::to_string(iPinIndex) + " ";
			if ( iCompId != BAD_COMPID )
				txt += std::to_string( compMgr.GetComponentById(iCompId).GetOrigId(iLyr, iPinIndex) ) + " // ";
			else
				txt += "NA // ";
			const int iCompId2		= pC->GetCompId2Raw();			txt += std::to_string(iCompId2) + " ";
			const int iPinIndex2	= pC->GetPinIndex2Raw();		txt += std::to_string(iPinIndex2) + " ";
			if ( iCompId2 != BAD_COMPID )
				txt += std::to_string( compMgr.GetComponentById(iCompId2).GetOrigId(iLyr, iPinIndex2) ) + " // ";
			else
				txt += "NA // ";
			GetLRTB(board, 100, 2 - iLyr, 0, L, R, T, B);	// 100% size square
			painter.save();
			painter.translate((L+R)/2, (T+B)/2);
			painter.scale(dTextScale, dTextScale);
			painter.setPen(m_blackPen);
			painter.drawText(0,0,0,0, Qt::TextDontClip | Qt::AlignVCenter | Qt::AlignLeft, txt.c_str());
			painter.restore();
		}
	}
#endif

	painter.end();

	delete pdfWriter;

#ifdef PAINTBOARD_TIMER
	const auto elapsed = std::chrono::steady_clock::now() - start;
	const auto duration_ms	= std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
	std::cout << "Time : " << duration_ms << std::endl;
#endif
}

void MainWindow::GetFirstRowCol(int& iRow, int& iCol) const
{
	const int& W = m_board.GetGRIDPIXELS();	// Square width in pixels
	iRow = 1 + m_scrollArea->verticalScrollBar()->value()   / W;	// The first fully visible row
	iCol = 1 + m_scrollArea->horizontalScrollBar()->value() / W;	// The first fully visible col
}

void MainWindow::GetXY(const GuiControl& guiCtrl, double row, double col, int& X, int& Y) const
{
	// For rendering.
	// Takes a point in the Board and returns coordinates in the drawn image.
	const int& W = guiCtrl.GetGRIDPIXELS();	// Square width in pixels
	const int  C = W >> 1;					// Half square width in pixels
	const int  iEdge = static_cast<int>( guiCtrl.GetEdgeWidth() );
	X = m_XGRIDOFFSET + m_XCORRECTION + C + static_cast<int>(col * W) + iEdge;
	Y = m_YGRIDOFFSET + m_YCORRECTION + C + static_cast<int>(row * W) + iEdge;
}

void MainWindow::GetLRTB(const GuiControl& guiCtrl, double percent, double row, double col, int& L, int& R, int& T, int& B) const
{
	// For rendering.
	// Takes a point in the Board and returns bounding box coordinates in the drawn image.
	// Setting percent to 100 will make the bounding box the same size as the grid square.
	const int& W = guiCtrl.GetGRIDPIXELS();	// Square width in pixels
	int X(0), Y(0);
	GetXY(guiCtrl, row, col, X, Y);
	const int S = static_cast<int>( round(W * 0.005 * percent) );
	L = X - S;	T = Y - S;
	R = X + S;	B = Y + S;
}

void MainWindow::GetLRTB(const GuiControl& guiCtrl, const Component& comp, int& L, int& R, int& T, int& B) const
{
	// For rendering.
	// Takes a component in the Board and returns bounding box coordinates in the drawn image.
	GetXY(guiCtrl, comp.GetRow(),		comp.GetCol(),		L, T);
	GetXY(guiCtrl, comp.GetLastRow(),	comp.GetLastCol(),	R, B);
}

void MainWindow::GetLRTB(const GuiControl& guiCtrl, const Rect& rect, int& L, int& R, int& T, int& B) const
{
	// For rendering.
	// Takes a Rect returns bounding box coordinates in the drawn image.
	GetXY(guiCtrl, rect.m_rowMin, rect.m_colMin, L, T);
	GetXY(guiCtrl, rect.m_rowMax, rect.m_colMax, R, B);
}

void MainWindow::GetXY(const GuiControl& guiCtrl, const Component& comp, int& X, int& Y) const
{
	// For rendering.
	// Takes a component in the Board and returns the footprint centre in the drawn image.
	int L, R, T, B;
	GetLRTB(guiCtrl, comp, L, R, T, B);
	X = ( L + R ) / 2;
	Y = ( T + B ) / 2;

	if ( !guiCtrl.GetVeroTracks() )	// Offset the footprint if all pin offsets are equal
	{
		const int& W = guiCtrl.GetGRIDPIXELS();	// Square width in pixels
		int padOffsetX, padOffsetY;
		comp.GetCompShapeOffsets(padOffsetX, padOffsetY);	// Get offsets in mil
		X += (padOffsetX * W) / 100;	// Convert from mil to pixels
		Y += (padOffsetY * W) / 100;	// Convert from mil to pixels
	}
}

void MainWindow::GetRulerExact(Board& board, const QPoint& p, QPointF& pOut) const
{
	pOut =  p;
	if ( !board.GetVeroTracks() )
	{
		const Element* pC = board.Get(0, p.y(), p.x());

		int padOffsetX(0), padOffsetY(0);
		if ( board.GetPadOffsets(pC, padOffsetX, padOffsetY) )	// Get offsets in mil
			pOut += QPointF(0.01 * padOffsetX, 0.01 * padOffsetY);
	}
}