File: mainwindow_events.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 (1237 lines) | stat: -rw-r--r-- 44,798 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
/*
	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 "ui_mainwindow.h"
#include "PolygonHelper.h"
#include "wiredialog.h"
#include "bomdialog.h"
#include "finddialog.h"
#include "pindialog.h"
#include <QtGlobal>
#include <QCloseEvent>

Q_DECL_CONSTEXPR static const bool ALLOW_DELAY_BASED_SMART_PAN = true;
Q_DECL_CONSTEXPR static const bool ALLOW_DELAY_BASED_PAD_SHIFT = true;

// Following 2 are to slow down the auto-panning while moving components with the mouse
static std::chrono::steady_clock::time_point g_lastAutoPanTime;
static bool g_bHaveAutoPanned = false;

#ifdef VEROROUTE_ANDROID
#define AVOID_RECT_REDRAWS
#endif

#ifdef AVOID_RECT_REDRAWS
// Following is to avoid too many redraws while defining rectangles
static std::chrono::steady_clock::time_point g_lastDrawRect;
#endif

static std::chrono::steady_clock::time_point g_lastMouseClickTime;	// For implementation of ALLOW_DELAY_BASED_SMART_PAN / ALLOW_DELAY_BASED_PAD_SHIFT
static bool g_bPinClicked = false;									// For implementation of ALLOW_DELAY_BASED_PAD_SHIFT

void MainWindow::GetPixMapXY(const QPoint& currentPoint, int& pixmapX, int& pixmapY) const
{
	pixmapX = currentPoint.x() + m_scrollArea->horizontalScrollBar()->value();
	pixmapY = currentPoint.y() + m_scrollArea->verticalScrollBar()->value();

	int gndL, gndR, gndT, gndB;
	m_board.GetGroundFillBounds(gndL, gndR, gndT, gndB);

	const int iEdge = static_cast<int>( m_board.GetEdgeWidth() );

	pixmapX += gndL - iEdge;
	pixmapY += gndT - iEdge;
}

bool MainWindow::GetRowCol(const QPoint& currentPoint, int& row, int& col, double& deltaRow, double& deltaCol) const
{
	return GetRowCol(currentPoint, m_board.GetRows(), m_board.GetCols(), row, col, deltaRow, deltaCol);
}

bool MainWindow::GetRowCol(const QPoint& currentPoint, const int rows, const int cols, int& row, int& col, double& deltaRow, double& deltaCol) const
{
	const int& W = m_board.GetGRIDPIXELS();	// Square width in pixels

	int pixmapX(0), pixmapY(0);
	GetPixMapXY(currentPoint, pixmapX, pixmapY);

	deltaRow = pixmapY * 1.0 / W;
	deltaCol = pixmapX * 1.0 / W;
	row		 = pixmapY / W;
	col		 = pixmapX / W;
	deltaRow -= row;	// We just want an error in terms of grid squares
	deltaCol -= col;
	const bool bInGrid = ( row >= 0 && row < rows ) && ( col >= 0 && col < cols);
	row = std::max(0, std::min(rows-1, row));
	col = std::max(0, std::min(cols-1, col));
	return bInGrid;
}

bool MainWindow::HaveZeroDeltaRowCol(int& deltaRow, int& deltaCol)
{
	// Modify deltaRow/deltaCol to account for out-of-grid locations
	int pixmapX(0), pixmapY(0);
	GetPixMapXY(m_mousePos, pixmapX, pixmapY);

	const int&	W	 = m_board.GetGRIDPIXELS();
	const int	rows = ( m_board.GetCompEdit() ) ? m_board.GetCompDefiner().GetScreenRows() : m_board.GetRows();
	const int	cols = ( m_board.GetCompEdit() ) ? m_board.GetCompDefiner().GetScreenCols() : m_board.GetCols();

	if ( deltaRow == 0 ) { if ( pixmapY > W * rows ) deltaRow++; }
	if ( deltaCol == 0 ) { if ( pixmapX > W * cols ) deltaCol++; }
	if ( deltaRow == 0 ) { if ( pixmapY < 0 ) deltaRow--; }
	if ( deltaCol == 0 ) { if ( pixmapX < 0 ) deltaCol--; }
	return deltaRow == 0 && deltaCol == 0;
}

void MainWindow::wheelEvent(QWheelEvent* event)
{
#if QT_VERSION >= QT_VERSION_CHECK(5,14,0)
	m_mousePos = event->position().toPoint();
#else
	m_mousePos = event->posF().toPoint();
#endif

	if ( GetShiftKeyDown() ) return;	// Ignore wheel events while trying to group components
	const bool bBack = ( event->angleDelta().y() < 0 );
	if ( GetCtrlKeyDown() )
	{
		if ( bBack ) ZoomOut(); else ZoomIn();
	}
	else if ( m_board.GetCompEdit() )
		DefinerIncPinNumber(!bBack);
	else if ( !m_board.GetMirrored() )
		CompStretch(!bBack);
	event->accept();	// If we don't do this, we can get the same event passed multiple times if we're on MS Windows.
}

void MainWindow::closeEvent(QCloseEvent* event)
{
#ifndef VEROROUTE_ANDROID	
	if ( GetIsModified() )
	{
		if ( QMessageBox::question(this, tr("Really Quit?"),
										 tr("Your layout is not saved. You will lose changes if you quit.  Continue?"),
										 QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No )
			return event->ignore();
	}
#endif
	event->accept();
}

bool MainWindow::CanModifyRuler() const
{
	return m_bRuler && !( m_board.GetCompEdit() || GetSmartPan() || GetShiftKeyDown() || GetResizingText() ||
						  GetDefiningRect() || GetPaintPins() || GetErasePins() || GetPaintBoard() || GetEraseBoard() || GetPaintFlood() );
}

bool MainWindow::GetHaveFloatingPinTH(int& iFloatingNodeId)	// Checks for a floating through-hole pin
{
	iFloatingNodeId = BAD_NODEID;

	const Element* pC = m_board.Get(m_board.GetCurrentLayer(), m_gridRow, m_gridCol);
	// This method is called to see if we should automatically erase both layers (to help a floating pin TH be placed)
	if ( pC->GetHasPin() ) return false;	// Skip if we already have a placed pin on either layer

	for (auto& mapObj : m_board.GetCompMgr().GetMapIdToComp())
	{
		const Component& comp = mapObj.second;
		if ( comp.GetIsPlaced() ) continue;	// Only want floating components
		const auto& eType = comp.GetType();
		if ( eType == COMP::WIRE || eType == COMP::MARK || eType == COMP::VERO_NUMBER || eType == COMP::VERO_LETTER ) continue;
		if ( comp.GetIsSOIC() ) continue;	// SOIC parts are not through-hole

		const int j(m_gridRow - comp.GetRow());		if ( j < 0 || j >= comp.GetCompRows() ) continue;
		const int i(m_gridCol - comp.GetCol());		if ( i < 0 || i >= comp.GetCompCols() ) continue;

		const CompElement* p = comp.GetCompElement(j, i);
		if ( !p->GetIsPin() ) continue;

		iFloatingNodeId = comp.GetNodeId( p->GetPinIndex() );
		return true;
	}
	return false;
}

void MainWindow::MousePressEvent(const QPoint& pos, bool bLeftClick, bool bRightClick)
{
	SetMouseActionString("");

	m_bReRoute = m_bReListNodes = false;	// Reset both flags

	g_bPinClicked = false;

	g_bHaveAutoPanned = false;	// Reset flags for avoiding repeated re-draws

	if ( !m_findDlg->isVisible() ) ClearFind();	// Clear the set of found components

	m_mousePos = m_clickedPos = pos;
	if ( !m_board.GetCompEdit() && m_board.GetMirrored() ) return;

	const TRACKMODE&	trackMode	= m_board.GetTrackMode();
	const COMPSMODE&	compMode	= m_board.GetCompMode();
	CompDefiner&		compDefiner	= m_board.GetCompDefiner();
	const int&			layer		= m_board.GetCurrentLayer();

	// Get row col
	double dRow(0), dCol(0);	// Fractional correction to row, col for SwapDiagLinks() call

	bool bInGrid(false);
	if ( m_board.GetCompEdit() )
		bInGrid = GetRowCol(m_mousePos, compDefiner.GetScreenRows(), compDefiner.GetScreenCols(), m_gridRow, m_gridCol, dRow, dCol);
	else
		bInGrid = GetRowCol(m_mousePos, m_gridRow, m_gridCol, dRow, dCol);
	if ( !bInGrid)
		return HidePadOffsetDialog();

	m_bMouseClick	= true;		// Set the flag meaning "click begin"
	m_bLeftClick	= bLeftClick;
	m_bRightClick	= bRightClick;
#ifdef VEROROUTE_ANDROID
	m_bLeftClick	= m_bRightClick = true;	// Making the point that there is no difference between left/right clicks in the Android version of the app
#endif

	if ( m_board.GetCompEdit() )
	{
		HidePadOffsetDialog();
		// Pin/Shape selection
		const int pinId		= compDefiner.GetPinId(m_gridRow, m_gridCol);
		const int shapeId	= compDefiner.GetShapeId(m_gridRow + dRow - 0.5, m_gridCol + dCol - 0.5);
		if ( GetCurrentPinId() != pinId )
		{
			SetCurrentPinId(pinId);
			SetMouseActionString(( pinId == BAD_ID ) ? "unselect point in footprint" : "select point in footprint");
		}
		if ( GetCurrentShapeId() != shapeId )
		{
			SetCurrentShapeId(shapeId);
			SetMouseActionString(( shapeId == BAD_ID ) ? "unselect shape" : "select shape");
		}
		UpdateCompDialog();
		return RepaintSkipRouting();
	}

	// Cursor modification
	if ( GetSmartPan() )
		centralWidget()->setCursor(Qt::ClosedHandCursor);
	else if ( GetPaintPins() || GetErasePins() || GetPaintBoard() || GetEraseBoard() || GetPaintFlood() || GetEditLayerPref() )
		centralWidget()->setCursor(Qt::CrossCursor);
	else if ( GetResizingText() )
		centralWidget()->setCursor(Qt::SizeFDiagCursor);
	else if ( AllowCurrentTextId() || AllowCurrentCompId() )
		centralWidget()->setCursor(Qt::ClosedHandCursor);
	else
		centralWidget()->setCursor(Qt::OpenHandCursor);

	if ( CanModifyRuler() )
	{
		HidePadOffsetDialog();
		const QPoint current(m_gridCol, m_gridRow);
		if      ( current == m_rulerA ) m_bModifyRulerA = false;	// Do nothing, but prefer end B next time
		else if ( current == m_rulerB ) m_bModifyRulerA = true;		// Do nothing, but prefer end A next time
		else
		{
			if ( m_bModifyRulerA )	m_rulerA = current;
			else					m_rulerB = current;
			m_bModifyRulerA = !m_bModifyRulerA;
		}
	}

	if ( GetDefiningRect() )
	{
		if ( m_dockPinDlg->isVisible() ) m_dockPinDlg->hide();
		HidePadOffsetDialog();
#ifdef VEROROUTE_ANDROID
		if ( m_bMouseClick )
#else
		if ( m_bLeftClick )	// Only define rectangles using left-click
#endif
		{
			centralWidget()->setCursor(Qt::SizeFDiagCursor);
			m_board.GetRectMgr().StartNewRect(m_gridRow, m_gridCol);
			SelectAllInRects();
			SetMouseActionString("select parts / tracks by area");
#ifdef AVOID_RECT_REDRAWS
			g_lastDrawRect = std::chrono::steady_clock::now();
#endif
			ShowCurrentRectSize();
		}
#ifndef VEROROUTE_ANDROID
		else				// Right/middle click quits rectangle mode
		{
			SetDefiningRect( false );
			UpdateControls();
		}
#endif
		return RepaintSkipRouting();
	}

	if ( !GetSmartPan() && !GetShiftKeyDown() )
		m_board.GetRectMgr().Clear();

	SetResizingText(false);

	if ( !GetSmartPan() )	// If not grabbing the board ...
	{
		// Text box selection
		if ( m_board.GetShowText() && m_board.GetTrackMode() != TRACKMODE::PCB )
		{
			const int textId = m_board.GetTextId(m_gridRow, m_gridCol);
			if ( GetCurrentTextId() != textId )	// If we're changing textId
			{
				// If we've clicked away from an empty text box, then delete it
				if ( GetCurrentTextId() != BAD_TEXTID && StringHelper::IsEmptyStr( GetCurrentTextRect().GetStr() ) )
					m_board.GetTextMgr().DestroyRect( GetCurrentTextId() );

				if ( textId != BAD_TEXTID )
					SetMouseActionString("select text box");

				SetCurrentTextId(textId);
			}
			if ( GetCurrentTextId() != BAD_TEXTID )
			{
				// If we're on the bottom-right corner of the text box, then resize it rather than move it
				const TextRect& rect = GetCurrentTextRect();
				if ( rect.m_rowMax == m_gridRow && rect.m_colMax == m_gridCol && dRow >= 0.5 && dCol >= 0.5 )
					SetResizingText(true);
			}
		}
		if ( compMode != COMPSMODE::OFF )
		{
			// Component selection (if text is not selected)
			const int compId = !AllowCurrentTextId() ? m_board.GetComponentId(m_gridRow, m_gridCol) : BAD_COMPID;
			if ( GetCurrentCompId() != compId ) SetCurrentCompId(compId);

			// Group manipulation
			GroupManager& groupMgr = m_board.GetGroupMgr();
			if ( GetShiftKeyDown() )
			{
				groupMgr.UpdateUserGroup( GetCurrentCompId() );	// Add/remove current comp (and its siblings) to user group
				UpdateControls();
				if ( !AllowCurrentTextId() )
					SetMouseActionString("(un)select part(s)");
			}
			else if ( !groupMgr.GetIsUserComp( GetCurrentCompId() ) )
			{
				CompManager& compMgr = m_board.GetCompMgr();
				groupMgr.ResetUserGroup( GetCurrentCompId() );	// Reset the user group with the current comp (and its siblings)
				compMgr.ClearTrax();
				UpdateControls();
				if ( !AllowCurrentTextId() )
					SetMouseActionString("(un)select part(s)");
			}
		}
	}

	// Painting/Unpainting the component pins or board
	if ( GetSmartPan() || GetShiftKeyDown() || trackMode == TRACKMODE::OFF ) return;

	if ( AllowCurrentTextId() )
	{
		if ( m_dockPinDlg->isVisible() ) m_dockPinDlg->hide();
		HidePadOffsetDialog();
		return RepaintSkipRouting();	// Don't modify nodeId or paint if editing text
	}

	const Element* pC = m_board.Get(layer, m_gridRow, m_gridCol);

	const bool bColor		= ( trackMode == TRACKMODE::COLOR );
	const bool bColoredMono	= ( trackMode == TRACKMODE::MONO && m_board.GetColoredMono() );
	if ( GetPaintFlood() && (bColor || bColoredMono) )
	{
		if ( m_dockPinDlg->isVisible() ) m_dockPinDlg->hide();
		HidePadOffsetDialog();
#ifdef VEROROUTE_ANDROID
		if ( m_bMouseClick )
#else
		if ( m_bLeftClick )
#endif
		{
			if ( GetCurrentNodeId() == BAD_NODEID )			// If trying to left-click paint a BAD_NODEID ...
				SetCurrentNodeId( m_board.GetNewNodeId() );	// ... use a new NodeId instead

			m_board.GetColorMgr().ReAssignColors();	// Forces colors to be worked out again

			assert( GetCurrentNodeId() != BAD_NODEID );
			assert( !m_board.GetRoutingEnabled() );	// Sanity check

			const int tmp = GetCurrentNodeId();	// Need to temporarily change current nodeId for HandleRouting()
			SetCurrentNodeId( pC->GetNodeId() );
			HandleRouting(true);	// Work out all MH distances for the flood
			SetCurrentNodeId(tmp);	// Restore current nodeId

			m_board.FloodNodeId( GetCurrentNodeId() );
			SetMouseActionString("paint (flood)", GetCurrentNodeId());
			m_bReRoute = m_bReListNodes = true;
		}
	}
	else if ( ( (GetPaintPins() || GetErasePins()) && (bColor || bColoredMono) ) || GetPaintBoard() || GetEraseBoard() )
	{
		if ( m_dockPinDlg->isVisible() ) m_dockPinDlg->hide();
		HidePadOffsetDialog();

		// Handle competing diagonals first
		bool bDoSwap(false);
		if ( GetPaintBoard() && m_board.GetTrackMode() != TRACKMODE::OFF )
		{
			const bool bCloseToCrossPoint = ( hypot(std::min(dRow, 1.0 - dRow), std::min(dCol, 1.0 - dCol)) <= 0.5 );	// true ==> clicked close to crossing diagonals point
			if ( bCloseToCrossPoint )	// Only consider clicks close to crossing diagonals point
			{
				const int	dR = ( dRow > 0.5 ) ? 1 : 0;	// Correct row, col to account for crossing ...
				const int	dC = ( dCol > 0.5 ) ? 1 : 0;	// ... point being near corner of element
				const int&	layer	 = m_board.GetCurrentLayer();

				Element* pRB = m_board.Get(layer, m_gridRow + dR, m_gridCol + dC);
				if ( pRB->CanSwapDiagLinks() )
				{
					Element* pLB = pRB->GetNbr(NBR_L);
					bDoSwap	= ( pRB->GetNodeId() == GetCurrentNodeId() && !ReadCodeBit(NBR_LT, pRB->GetCode()) )	// pRB has correct nodeID but no diagonal to LT
						   || ( pLB->GetNodeId() == GetCurrentNodeId() && !ReadCodeBit(NBR_RT, pLB->GetCode()) );	// pLB has correct nodeID but no diagonal to RT
					if ( bDoSwap )
					{
						pRB->SwapDiagLinks();
						SetMouseActionString("swap competing diagonals");
						m_bReRoute = m_bReListNodes = true;
					}
				}
			}
		}

		const bool bTruePin = pC->GetLyrHasPin() && !pC->GetHasWire();
		if ( ( GetPaintPins() || GetErasePins() ) && !bTruePin && !bDoSwap )	// Restrict painting/erasing pins to true pins (not wires)
			return;

#ifdef VEROROUTE_ANDROID
		//TODO Could allow this in Desktop version too
		const bool bClickedValidNodeID = pC->GetNodeId() != BAD_NODEID;
		if ( GetPaintBoard() && bClickedValidNodeID && pC->GetNodeId() == GetCurrentNodeId() && pC->ReadFlagBits(USERSET) && !bDoSwap )	// If we're painting board and clicked on a point with matching valid nodeID
		{
			const bool bChanged = m_board.SetNodeIdByUser(layer, m_gridRow, m_gridCol, BAD_NODEID, false);	// ... then erase the point instead of painting it
			if ( !bChanged ) return;
			SetMouseActionString("erase", GetCurrentNodeId());
			m_bReRoute = m_bReListNodes = true;
		}
		else
#endif

#ifdef VEROROUTE_ANDROID
		if ( ( GetPaintPins() || GetPaintBoard() ) && !bDoSwap )	// Paint
#else
		if ( m_bLeftClick && !bDoSwap )	// Paint
#endif
		{
			if ( GetCurrentNodeId() == BAD_NODEID )			// If trying to left-click paint a BAD_NODEID ...
				SetCurrentNodeId( m_board.GetNewNodeId() );	// ... use a new NodeId instead

			m_board.GetColorMgr().ReAssignColors();	// Forces colors to be worked out again

			const bool bChanged = m_board.SetNodeIdByUser(layer, m_gridRow, m_gridCol, GetCurrentNodeId(), GetPaintPins() || GetErasePins());
			if ( !bChanged ) return;
			SetMouseActionString("paint", GetCurrentNodeId());
			m_bReRoute = m_bReListNodes = true;
		}

#ifdef VEROROUTE_ANDROID
		else if ( ( GetErasePins() || GetEraseBoard() ) && !bDoSwap )	// Erase
#else
		else if ( m_bRightClick && !bDoSwap )	// Erase
#endif
		{
			// Erase both layers if it makes it easier to let a floating part fall into place.
			int iFloatingNodeId(BAD_NODEID);
			const bool bEraseBothLayers = m_board.GetLyrs() > 1 &&					// If 2-layer board ...
										  !GetPaintPins() && !GetErasePins() &&		// ... and not erasing a pin
										  GetHaveFloatingPinTH(iFloatingNodeId);	// ... then see if we have a floating through-hole pin and gets its nodeId

			bool bChanged = m_board.SetNodeIdByUser(layer, m_gridRow, m_gridCol, BAD_NODEID, GetPaintPins() || GetErasePins());
			if ( bEraseBothLayers )
			{
				const int	layerOther	= ( layer == 0 ) ? 1 : 0;
				const int&	otherNodeId	= m_board.Get(layerOther, m_gridRow, m_gridCol)->GetNodeId();
				// Only erase if the other layer has a valid nodeId that does not match the floating nodeId
				if ( otherNodeId != BAD_NODEID && otherNodeId != iFloatingNodeId )
					bChanged = m_board.SetNodeIdByUser(layerOther, m_gridRow, m_gridCol, BAD_NODEID, GetPaintPins() || GetErasePins()) || bChanged;
			}
			if ( !bChanged ) return;
			SetMouseActionString("erase", GetCurrentNodeId());
			m_bReRoute = m_bReListNodes = true;
		}
	}
	else if ( GetEditLayerPref() )
	{
		const bool bCloseToGridPoint = ( hypot(dRow - 0.5, dCol - 0.5) <= 0.5 );	// true ==> clicked close to grid point
		if ( bCloseToGridPoint && pC->GetPinSupportsLayerPref() )
		{
			const bool bToggled = m_board.ToggleLyrPref(layer, m_gridRow, m_gridCol);	assert(bToggled);
			if ( bToggled )
			{
				size_t	pinIndex;
				int		compId;
				m_board.GetSlotInfoForTH(pC, pinIndex, compId);
	
				SetMouseActionString("change pin layer preference", compId);
			}
		}
	}
	else
	{
		if ( ALLOW_DELAY_BASED_PAD_SHIFT && pC->GetPinSupportsOffsetPads() )
			g_bPinClicked = true;

		if ( !pC->GetPinSupportsOffsetPads() )	// Hide the pad offset dialog if we click on a place that cannot have a pad offset
			HidePadOffsetDialog();
	}

	g_lastMouseClickTime = std::chrono::steady_clock::now();

	if ( m_bReRoute )
	{
		m_board.WipeAutoSetPoints();
		m_board.PlaceFloaters();	// See if we can now place floating components down
		RepaintWithRouting();
	}
	else
		RepaintSkipRouting();
}

void MainWindow::MouseDoubleClickEvent(const QPoint& pos)
{
	SetMouseActionString("");

	g_bPinClicked = false;

	m_mousePos = pos;
	if ( !m_board.GetCompEdit() && m_board.GetMirrored() ) return;
	if ( m_board.GetCompEdit() ) return;

	if ( GetSmartPan() || GetShiftKeyDown() ) return;

	if ( GetDefiningRect() )
	{
		SetDefiningRect(false);	// Quit define rectangles mode
		UpdateControls();
		return;
	}

	if ( AllowCurrentTextId() )
		return ShowTextDialog();

	const bool bCompsOn	= m_board.GetCompMode()  != COMPSMODE::OFF;
	const bool bTrackOn	= m_board.GetTrackMode() != TRACKMODE::OFF;

	if ( !bTrackOn && !bCompsOn ) return;

	const bool bSameLocation = ( PolygonHelper::Length(m_mousePos - m_clickedPos) ) < m_board.GetGRIDPIXELS();	// Tolerance of one grid square
	if ( !bSameLocation ) return;

	// Get row col
	double dRow(0), dCol(0);	// Fractional correction to row, col for SwapDiagLinks() call
	const bool bInGrid			= GetRowCol(m_mousePos, m_gridRow, m_gridCol, dRow, dCol);
	if ( !bInGrid ) return;

	const int&	layer		= m_board.GetCurrentLayer();
	Element*	pC			= m_board.Get(layer, m_gridRow, m_gridCol);
	const bool	bWire		= pC->GetHasWire();
	const bool	bTruePin	= pC->GetLyrHasPin() && !bWire;

	// Cursor modification
	centralWidget()->setCursor(Qt::CrossCursor);

	const bool bCloseToGridPoint = ( hypot(dRow - 0.5, dCol - 0.5) <= 0.5 );	// true ==> clicked close to grid point

	// Handle competing diagonals
	if ( bTrackOn && !GetPaintAction() )
	{
		const bool bCloseToCrossPoint = ( hypot(std::min(dRow, 1.0 - dRow), std::min(dCol, 1.0 - dCol)) <= 0.5 );	// true ==> clicked close to crossing diagonals point
		if ( bCloseToCrossPoint )	// Only consider clicks close to crossing diagonals point
		{
			const int	dR	= ( dRow > 0.5 ) ? 1 : 0;	// Correct row, col to account for crossing ...
			const int	dC	= ( dCol > 0.5 ) ? 1 : 0;	// ... point being near corner of element
			Element*	pRB	= m_board.Get(layer, m_gridRow + dR, m_gridCol + dC);
			if ( pRB->SwapDiagLinks() )
			{
				SetMouseActionString("swap competing diagonals");
				m_bReRoute = m_bReListNodes = true;
				m_board.WipeAutoSetPoints();
				m_board.PlaceFloaters();	// See if we can now place floating components down
				return;
			}
		}
	}

	// Handle selection of nodeId when double-clicking on a pin (when tracks are displayed)
	if ( bTrackOn && bWire && !GetPaintBoard() && !GetEraseBoard() && !GetPaintFlood() && bCloseToGridPoint )	// Only consider clicks that are close to the grid point
	{
		if ( GetCurrentNodeId() != pC->GetNodeId() )
		{
			SetCurrentNodeId( pC->GetNodeId() );
			SetMouseActionString( ( GetCurrentNodeId() == BAD_NODEID ) ? "unselect net" : "select net", 0);
			m_bReRoute = true;	// Dont' need to set m_bReListNodes when choosing different nodeID
		}
		return;
	}
	if ( bTrackOn && bTruePin && !GetPaintPins() && !GetErasePins() && !GetPaintFlood()	&& bCloseToGridPoint )	// Only consider clicks that are close to the grid point
	{
		if ( GetCurrentNodeId() != pC->GetNodeId() )
		{
			SetCurrentNodeId( pC->GetNodeId() );
			SetMouseActionString( ( GetCurrentNodeId() == BAD_NODEID ) ? "unselect net" : "select net", 0);
			m_bReRoute = true;	// Dont' need to set m_bReListNodes when choosing different nodeID
		}
		return;
	}

	// Handle component rotation
	/*
	if ( bCompsOn && ( m_eMouseMode == MOUSE_MODE::SELECT || GetPaintPins() || GetErasePins() ) && GetCurrentCompId() != BAD_COMPID )
	{
		if ( !bTruePin )	//	... Only allow rotate if we did not click on a pin
		{
			m_bReRoute = m_bReListNodes = false;	// Set these false since CompRotateCW() calls RepaintWithListNodes() directly
			SetMouseActionString("");	// CompRotateCW() will write history
			return CompRotateCW();
		}
	}
	*/

	// Handle selection of nodeId (fallback case)
	if ( bTrackOn && !GetPaintAction() )
	{
		if ( GetCurrentNodeId() != pC->GetNodeId() )
		{
			SetCurrentNodeId( pC->GetNodeId() );
			SetMouseActionString( ( GetCurrentNodeId() == BAD_NODEID ) ? "unselect net" : "select net", 0);
			m_bReRoute = true;	// Dont' need to set m_bReListNodes when choosing different nodeID
		}
	}
}

void MainWindow::MouseMoveEvent(const QPoint& pos)
{
	m_mousePos = pos;
	if ( !m_board.GetCompEdit() && m_board.GetMirrored() ) return;
	if ( !m_bMouseClick ) return;
	const TRACKMODE&	trackMode	= m_board.GetTrackMode();
	const COMPSMODE&	compMode	= m_board.GetCompMode();
	CompDefiner&		compDefiner	= m_board.GetCompDefiner();
	const int&			layer		= m_board.GetCurrentLayer();

	if ( GetPaintFlood() ) return;		// Ignore mouse move while flooding
	if ( GetShiftKeyDown() ) return;	// Ignore mouse move while trying to group components

	if ( ALLOW_DELAY_BASED_SMART_PAN
		 && !m_board.GetCompEdit() && !GetDefiningRect() && !GetPaintBoard() && !GetEraseBoard() && !CanModifyRuler()
		 && !AllowCurrentTextId() && !AllowCurrentCompId() )
	{
		const auto elapsed		= std::chrono::steady_clock::now() - g_lastMouseClickTime;
		const auto duration_ms	= std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
		if ( duration_ms > 500 )	// ... Force smart pan after 500 ms of last mouse click
			SetSmartPan(true);
	}

	if ( m_board.GetCompEdit() && GetCurrentShapeId() != BAD_ID && m_bMouseClick )
		centralWidget()->setCursor(Qt::ClosedHandCursor);
	else if ( GetSmartPan() )
		centralWidget()->setCursor(Qt::ClosedHandCursor);
	else if ( GetDefiningRect() || GetResizingText() )
		centralWidget()->setCursor(Qt::SizeFDiagCursor);
	else if ( GetPaintBoard() || GetEraseBoard() || GetPaintPins() || GetErasePins() || GetPaintFlood() || GetEditLayerPref() )
		centralWidget()->setCursor(Qt::CrossCursor);
	else if ( AllowCurrentTextId() && m_bMouseClick )
		centralWidget()->setCursor(Qt::ClosedHandCursor);
	else if ( AllowCurrentCompId() && m_bMouseClick )
		centralWidget()->setCursor(Qt::ClosedHandCursor);
	else
		centralWidget()->setCursor(Qt::OpenHandCursor);

	// Get row col
	int row(0), col(0);
	double dRow(0), dCol(0);	// Fractional correction to row, col for SwapDiagLinks() call
	bool bInGrid(false);
	if ( m_board.GetCompEdit() )
		bInGrid = GetRowCol(m_mousePos, compDefiner.GetScreenRows(), compDefiner.GetScreenCols(), row, col, dRow, dCol);
	else
		bInGrid = GetRowCol(m_mousePos, row, col, dRow, dCol);

	int deltaRow = row - m_gridRow;
	int deltaCol = col - m_gridCol;

	int oldRow(m_gridRow), oldCol(m_gridCol);
	m_gridRow = row;
	m_gridCol = col;

	// g_bPinClicked needs to be set false in a limited set of cases.
	// If we don't do anything with the move operation, then we can preserve g_bPinClicked
	if ( m_board.GetCompEdit() || GetPaintAction() || GetDefiningRect() || GetResizingText() || CanModifyRuler() )
		g_bPinClicked = false;

	if ( m_board.GetCompEdit() )
	{
		if ( GetCurrentShapeId() != BAD_ID )
		{
			if ( HaveZeroDeltaRowCol(deltaRow, deltaCol) ) return;	// No change

			compDefiner.SetCurrentPinId(BAD_ID);				// Clear pin selection
			compDefiner.MoveCurrentShape(deltaRow, deltaCol);	// Move the shape
			SetMouseActionString("move shape", GetCurrentShapeId());
			UpdateCompDialog();
		}
	}
	else if ( !GetSmartPan() && GetDefiningRect() )
	{
		if ( deltaRow != 0 || deltaCol != 0 ) 	// No change of row or column ==> No change in current rect size
		{
			m_board.GetRectMgr().UpdateNewRect(m_gridRow, m_gridCol);
			SelectAllInRects();
		}
	}
	else if ( !GetSmartPan() && ( GetPaintBoard() || GetEraseBoard() ) && trackMode != TRACKMODE::OFF )	// (Un)Paint nodeId on board but NOT pins
	{
		if ( !bInGrid ) return;

		// Handle competing diagonals first
		bool bDoSwap(false);
		const bool bCloseToCrossPoint = ( hypot(std::min(dRow, 1.0 - dRow), std::min(dCol, 1.0 - dCol)) <= 0.5 );	// true ==> clicked close to crossing diagonals point
		if ( bCloseToCrossPoint )	// Only consider clicks close to crossing diagonals point
		{
			const int	dR = ( dRow > 0.5 ) ? 1 : 0;	// Correct row, col to account for crossing ...
			const int	dC = ( dCol > 0.5 ) ? 1 : 0;	// ... point being near corner of element
			const int&	layer	 = m_board.GetCurrentLayer();

			Element* pRB = m_board.Get(layer, m_gridRow + dR, m_gridCol + dC);
			if ( pRB->CanSwapDiagLinks() )
			{
				Element* pLB = pRB->GetNbr(NBR_L);
				bDoSwap	= ( pRB->GetNodeId() == GetCurrentNodeId() && !ReadCodeBit(NBR_LT, pRB->GetCode()) )	// pRB has correct nodeID but no diagonal to LT
					   || ( pLB->GetNodeId() == GetCurrentNodeId() && !ReadCodeBit(NBR_RT, pLB->GetCode()) );	// pLB has correct nodeID but no diagonal to RT
				if ( bDoSwap )
				{
					pRB->SwapDiagLinks();
					SetMouseActionString("swap competing diagonals");
					m_bReRoute = m_bReListNodes = true;
				}
			}
		}

		assert( !GetPaintPins() && !GetErasePins() && !GetPaintFlood() );	// Sanity check
#ifdef VEROROUTE_ANDROID
		if ( GetPaintBoard() && !bDoSwap )	// Paint
#else
		if ( m_bLeftClick && !bDoSwap )		// Paint
#endif
		{
			const bool bChanged = m_board.SetNodeIdByUser(layer, m_gridRow, m_gridCol, GetCurrentNodeId(), false);	// false ==> Only allow paint board (not pins)
			if ( !bChanged ) return;	// No change
			SetMouseActionString("paint", GetCurrentNodeId());
			m_bReRoute = m_bReListNodes = true;
		}

#ifdef VEROROUTE_ANDROID
		if ( GetEraseBoard() && !bDoSwap )	// Erase
#else
		if ( m_bRightClick && !bDoSwap )	// Erase
#endif
		{
			// Erase both layers if it makes it easier to let a floating part fall into place.
			int iFloatingNodeId(BAD_NODEID);
			const bool bEraseBothLayers = m_board.GetLyrs() > 1 &&					// If 2-layer board ...
										  !GetPaintPins() && !GetErasePins() &&		// ... and not erasing a pin
										  GetHaveFloatingPinTH(iFloatingNodeId);	// ... then see if we have a floating through-hole pin and gets its nodeId

			bool bChanged = m_board.SetNodeIdByUser(layer, m_gridRow, m_gridCol, BAD_NODEID, false);	// false ==> Only allow erase board (not pins)
			if ( bEraseBothLayers )
			{
				const int	layerOther	= ( layer == 0 ) ? 1 : 0;
				const int&	otherNodeId	= m_board.Get(layerOther, m_gridRow, m_gridCol)->GetNodeId();
				// Only erase if the other layer has a valid nodeId that does not match the floating nodeId
				if ( otherNodeId != BAD_NODEID && otherNodeId != iFloatingNodeId )
					bChanged = m_board.SetNodeIdByUser(layerOther, m_gridRow, m_gridCol, BAD_NODEID, false) || bChanged;	// false ==> Only allow erase board (not pins)
			}
			if ( !bChanged ) return;	// No change
			SetMouseActionString("erase", GetCurrentNodeId());
			m_bReRoute = m_bReListNodes = true;
		}
		m_board.WipeAutoSetPoints();
		m_board.PlaceFloaters();	// See if we can now place floating components down
	}
	else if ( !GetSmartPan() && AllowCurrentTextId() )
	{
		if ( HaveZeroDeltaRowCol(deltaRow, deltaCol) ) return;	// No change

		if ( g_bHaveAutoPanned )	// If we've auto-panned the grid before ...
		{
			const auto elapsed		= std::chrono::steady_clock::now() - g_lastAutoPanTime;
			const auto duration_ms	= std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
			if ( duration_ms >= 0 && duration_ms < 40 ) return;	// ... do nothing if within 40 ms of the last auto-pan
		}

		if ( GetResizingText() )
		{
			m_board.GetTextMgr().UpdateRect( GetCurrentTextId(), m_gridRow, m_gridCol );
		}
		else
		{
			const bool bAutoPanned = m_board.MoveTextBox(deltaRow, deltaCol);	// Move the text box and note if the grid was auto-panned
			if ( bAutoPanned )
			{
				g_bHaveAutoPanned = true;
				g_lastAutoPanTime = std::chrono::steady_clock::now();
				m_bReRoute = m_bReListNodes = true;
			}
		}
		SetMouseActionString(GetResizingText() ? "resize text box" : "move text box", GetCurrentTextId());
	}
	else if ( !GetSmartPan() && AllowCurrentCompId() && compMode != COMPSMODE::OFF )	// Move user-group components
	{
		if ( HaveZeroDeltaRowCol(deltaRow, deltaCol) ) return;	// No change

		if ( g_bHaveAutoPanned )	// If we've auto-panned the grid before ...
		{
			const auto elapsed		= std::chrono::steady_clock::now() - g_lastAutoPanTime;
			const auto duration_ms	= std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
			if ( duration_ms >= 0 && duration_ms < 40 ) return;	// ... do nothing if within 40 ms of the last auto-pan
		}

		const bool bAutoPanned = m_board.MoveUserComps(deltaRow, deltaCol);	// Move the components and note if the grid was auto-panned
		if ( bAutoPanned )
		{
			g_bHaveAutoPanned = true;
			g_lastAutoPanTime = std::chrono::steady_clock::now();
		}
		const bool bPlural = ( m_board.GetGroupMgr().GetNumUserComps() > 1 );
		SetMouseActionString(bPlural ? "move parts" : "move part", bPlural ? -1 : GetCurrentCompId());
		m_bReRoute = m_bReListNodes = true;
	}
	else if ( GetSmartPan() )	// If we're not moving anything else, we can smart pan
	{
		if ( HaveZeroDeltaRowCol(deltaRow, deltaCol) ) return;	// No change

		m_board.SmartPan(deltaRow, deltaCol);	// Pan whole circuit w.r.t. grid area, growing/shrinking as needed
		SetMouseActionString("move whole layout", 0);
		m_bReRoute = m_bReListNodes = true;
	}

	if ( CanModifyRuler() )
	{
		const QPoint old(oldCol, oldRow);
		const QPoint current(m_gridCol, m_gridRow);
		bool bModifyA = ( old == m_rulerA );
		bool bModifyB = !bModifyA && ( old == m_rulerB );
		if ( !(bModifyA || bModifyB) )
			bModifyA = PolygonHelper::Length(current - m_rulerA) < PolygonHelper::Length(current - m_rulerB);	// Choose nearest
		if ( bModifyA )	m_rulerA = current;
		else			m_rulerB = current;
		m_bModifyRulerA = !bModifyA;
	}

	if ( abs(deltaRow) <= 1 && abs(deltaCol) <= 1 )	// If not moved mouse too fast ...
	{
		if ( GetDefiningRect() )
		{
			if ( deltaRow != 0 || deltaCol != 0 )	// No change of row or column ==> No change in current rect size
			{
				ShowCurrentRectSize();
#ifdef AVOID_RECT_REDRAWS
				const auto elapsed		= std::chrono::steady_clock::now() - g_lastDrawRect;
				const auto duration_ms	= std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
				if ( duration_ms >= 0 && duration_ms < 200 ) return;	// ... do nothing if within 40 ms of the last draw
				g_lastDrawRect = std::chrono::steady_clock::now();
#endif
				RepaintSkipRouting();
			}
		}
		else
		{
			if ( m_bReRoute )
				RepaintWithRouting();
			else
				RepaintSkipRouting();

			m_bReRoute = false;
		}
	}

	if ( abs(deltaRow) > 0 || abs(deltaCol) > 0 )
		g_bPinClicked = false;
}

void MainWindow::MouseReleaseEvent(const QPoint& pos)
{
	bool bShowPadOffsetDialog(false);
	if ( g_bPinClicked && !m_board.GetVeroTracks() && !m_bRuler )
	{
		const auto elapsed		= std::chrono::steady_clock::now() - g_lastMouseClickTime;
		const auto duration_ms	= std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count();
		bShowPadOffsetDialog = ( duration_ms >= 1000 );
	}
	g_bPinClicked = false;

	m_mousePos = pos;
	releaseMouse();

	if ( GetSmartPan() )
		SetSmartPan(false);

	if ( !m_board.GetCompEdit() && m_board.GetMirrored() ) return;

	m_bMouseClick = false;

	if ( m_board.GetCompEdit() )
	{
	}
	else if ( GetResizingText() )
	{
		centralWidget()->setCursor(Qt::OpenHandCursor);
		SetResizingText(false);
	}
	else if ( GetDefiningRect() )
	{
		centralWidget()->setCursor(Qt::SizeFDiagCursor);
		m_board.GetRectMgr().EndNewRect();
		SelectAllInRects();
		ShowCurrentRectSize();
	}
	else if ( GetPaintPins() || GetErasePins() || GetPaintBoard() || GetEraseBoard() || GetPaintFlood() || GetEditLayerPref() )
		centralWidget()->setCursor(Qt::CrossCursor);
	else
		centralWidget()->setCursor(Qt::OpenHandCursor);

	UpdateHistory(m_mouseActionString, m_mouseObjId);
	UpdateControls();

	if ( m_bReListNodes )
		RepaintWithListNodes();
	else if ( m_bReRoute )
		RepaintWithRouting();
	else
		RepaintSkipRouting();

	if ( bShowPadOffsetDialog )
		ShowPadOffsetDialog();

	m_bReRoute = m_bReListNodes = false;	// Clear both flags
}

void MainWindow::keyPressEvent(QKeyEvent* event)
{
#ifndef VEROROUTE_ANDROID
	commonKeyPressEvent(event);

	if ( GetCtrlKeyDown() ) return;		// Try to keep Ctrl key input handled by menu items
	if ( GetShiftKeyDown() ) return;	// Ignore other key presses while trying to group components

	if ( !m_board.GetCompEdit() && m_board.GetMirrored() ) return;

	const TRACKMODE&	trackMode		= m_board.GetTrackMode();
	const COMPSMODE&	compMode		= m_board.GetCompMode();
	CompDefiner&		compDefiner		= m_board.GetCompDefiner();
	GroupManager&		groupMgr		= m_board.GetGroupMgr();
	const int			nComps			= groupMgr.GetNumUserComps();
	const bool			bIsAutoRepeat	= event->isAutoRepeat();

#ifdef _GRID_DEBUG
	switch(event->key())
	{
		case Qt::Key_F4: m_iGridDebugMode = ( m_iGridDebugMode + 1 ) % DEBUGMODE_END;	break;
	}
#endif
	
	if ( m_board.GetCompEdit() )
	{
		if ( GetCurrentShapeId() != BAD_ID )
		{
			switch( event->key() )
			{
				case Qt::Key_Left:	compDefiner.MoveCurrentShape( 0, -1); UpdateCompDialog(); RepaintSkipRouting(); break;
				case Qt::Key_Right:	compDefiner.MoveCurrentShape( 0,  1); UpdateCompDialog(); RepaintSkipRouting(); break;
				case Qt::Key_Up:	compDefiner.MoveCurrentShape(-1,  0); UpdateCompDialog(); RepaintSkipRouting(); break;
				case Qt::Key_Down:	compDefiner.MoveCurrentShape( 1,  0); UpdateCompDialog(); RepaintSkipRouting(); break;
			}
			if ( !bIsAutoRepeat )
			{
				switch( event->key() )
				{
					case Qt::Key_Backspace:
					case Qt::Key_Delete:	Delete();	break;
				}
			}
		}
		event->accept();
		return;
	}

	bool bUpdateControls(false);

	// Rectangle mode
	if ( !bIsAutoRepeat )
	{
		switch( event->key() )
		{
			case Qt::Key_R:	SetDefiningRect(true);	bUpdateControls = true; break;
		}
	}

	const bool	bSingle	= ( m_board.GetGroupMgr().GetNumUserComps() == 1 );
	const int	objID	= ( bSingle ) ? m_board.GetUserComponent().GetId() : -1;
	// Component manipulation
	switch( event->key() )
	{
		case Qt::Key_Underscore:
		case Qt::Key_Minus:		CompShrink();	break;
		case Qt::Key_Plus:
		case Qt::Key_Equal:		CompGrow();		break;
		case Qt::Key_Left:		if ( !m_board.GetDisableMove() ) { m_board.MoveUserComps(0,-1);	UpdateHistory(bSingle ? "move part" : "move parts", objID); RepaintWithRouting(); } break;
		case Qt::Key_Right:		if ( !m_board.GetDisableMove() ) { m_board.MoveUserComps(0, 1);	UpdateHistory(bSingle ? "move part" : "move parts", objID); RepaintWithRouting(); } break;
		case Qt::Key_Up:		if ( !m_board.GetDisableMove() ) { m_board.MoveUserComps(-1,0);	UpdateHistory(bSingle ? "move part" : "move parts", objID); RepaintWithRouting(); } break;
		case Qt::Key_Down:		if ( !m_board.GetDisableMove() ) { m_board.MoveUserComps( 1,0);	UpdateHistory(bSingle ? "move part" : "move parts", objID); RepaintWithRouting(); } break;
	}
	if ( !bIsAutoRepeat )
	{
		switch( event->key() )
		{
			case Qt::Key_Z:			CompRotateCCW();	break;
			case Qt::Key_X:			CompRotateCW();		break;
			case Qt::Key_Delete:	if ( AllowCurrentTextId() || ( nComps && compMode != COMPSMODE::OFF ) )
										Delete();	//	So delete works like the backspace keyboard shortcut
									break;
		}
	}
	// Painting/Unpainting
	if ( !bIsAutoRepeat )
	{
		const bool bAllowPaintPins = ( compMode != COMPSMODE::OFF ) &&
									 ( ( trackMode == TRACKMODE::COLOR ) || ( trackMode == TRACKMODE::MONO && m_board.GetColoredMono() ) );
		// Only one flag for paint-board/paint-pins/paint-flood must be true
		switch( event->key() )
		{
			case Qt::Key_P:		if ( !bAllowPaintPins || GetPaintBoard() || GetEraseBoard() || GetPaintFlood() ) return;
								SetPaintPins(true);		break;
			case Qt::Key_Space:	if ( trackMode == TRACKMODE::OFF || GetPaintPins() || GetErasePins() || GetPaintFlood() ) return;
								SetPaintBoard(true);	break;
			case Qt::Key_F:		if ( !bAllowPaintPins || GetPaintBoard() || GetEraseBoard() || GetPaintPins() || GetErasePins() || m_board.GetRoutingEnabled() ) return;
								SetPaintFlood(true);	break;
			case Qt::Key_W:		WipeTracks();	break;
		}
	}

	if ( !GetDefiningRect() )
		m_board.GetRectMgr().Clear();

	if ( bUpdateControls )
		UpdateControls();
#endif
	event->accept();	// If we don't do this, we can get the same event passed multiple times if we're on MS Windows.
}

void MainWindow::keyReleaseEvent(QKeyEvent* event)
{
#ifdef VEROROUTE_ANDROID
	if ( event->key() == Qt::Key_Back )
	{
		if ( m_bHistoryDir && m_historyMgr.GetCanUndo() )
			QTimer::singleShot(0, this, SLOT(Undo()));
		return event->accept();
	}
#else
	commonKeyReleaseEvent(event);

	if ( GetSmartPan() )
		SetSmartPan(false);

	if ( !m_board.GetCompEdit() && m_board.GetMirrored() ) return;
	if ( event->isAutoRepeat() ) return;

	if ( m_board.GetCompEdit() )
		UpdateCompDialog();
	else
	{
		switch( event->key() )
		{
			case Qt::Key_R:		SetDefiningRect(false);	break;
			case Qt::Key_P:		SetPaintPins(false);	break;
			case Qt::Key_F:		SetPaintFlood(false);	break;
			case Qt::Key_Space:	SetPaintBoard(false);	break;
			default:
				if ( AllowCurrentTextId() && m_bMouseClick )
					centralWidget()->setCursor(Qt::ClosedHandCursor);
				else if ( AllowCurrentCompId() && m_bMouseClick )
					centralWidget()->setCursor(Qt::ClosedHandCursor);
				else
					centralWidget()->setCursor(Qt::OpenHandCursor);
		}
		UpdateControls();
		RepaintWithListNodes();
	}
	event->accept();	// If we don't do this, we can get the same event passed multiple times if we're on MS Windows.
#endif
}

#ifndef VEROROUTE_ANDROID
void MainWindow::commonKeyPressEvent(QKeyEvent* event)		// So child dialogs can relay Ctrl and Shift to the main window
{
	g_bPinClicked = false;
	switch( event->key() )
	{
		case Qt::Key_Shift:		return SetShiftKeyDown(true);
		case Qt::Key_Control:	if ( m_bMouseClick ) centralWidget()->setCursor(Qt::ClosedHandCursor);
								return SetCtrlKeyDown(true);
	}
}

void MainWindow::commonKeyReleaseEvent(QKeyEvent* event)	// So child dialogs can relay Ctrl and Shift to the main window
{
	g_bPinClicked = false;
	switch( event->key() )
	{
		case Qt::Key_Shift:		return SetShiftKeyDown(false);
		case Qt::Key_Control:	return SetCtrlKeyDown(false);
	}
}

void MainWindow::specialKeyPressEvent(QKeyEvent* event)		// So child dialogs can do Ctrl+Q etc
{
	commonKeyPressEvent(event);
	if ( !GetCtrlKeyDown() ) return;
	switch( event->key() )
	{
		case Qt::Key_N:	return New();
		case Qt::Key_O:	return Open();
		case Qt::Key_M:	return Merge();
		case Qt::Key_S:	return GetShiftKeyDown() ? SaveAs() : Save();
		case Qt::Key_Q:	return Quit();
	}
}
#endif

void MainWindow::dragEnterEvent(QDragEnterEvent *e)
{
	if ( e->mimeData()->hasUrls() )
		e->acceptProposedAction();
}

void MainWindow::dropEvent(QDropEvent *e)
{
	if ( e->mimeData()->hasUrls() )
	{
		QString fileName = e->mimeData()->urls().first().toLocalFile();
		if ( fileName.isEmpty() ) return;

		SetCtrlKeyDown(false);	// Clear flag since key release can get missed.
		if ( GetIsModified() )
			if ( QMessageBox::question(this, tr("Confirm Open"),
											 tr("Your layout is not saved. You will lose changes if you open a new one.  Continue?"),
											 QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::No ) return;
		OpenVrt(fileName, false);
	}
}

bool MainWindow::eventFilter(QObject* object, QEvent* event)
{
	// Intercept the Android "back" button event
	if ( event->type() == QEvent::KeyRelease && qobject_cast<QMenu*>(object) )
	{
		QKeyEvent* ke = (QKeyEvent*)event;
		if ( ke->key() == Qt::Key_Back )
		{
			ke->accept();
			return true;
		}
	}
	return QWidget::eventFilter(object, event);
}

void MainWindow::SetPaintPins(bool b)
{
	if ( b == GetPaintPins() ) return;
	if ( b ) HideAllNonDockedDlgs();
	m_eMouseMode = ( b ) ? MOUSE_MODE::PAINT_PINS : MOUSE_MODE::SELECT;
	centralWidget()->setCursor(b ? Qt::CrossCursor : Qt::OpenHandCursor);
	UpdateControls();
}
void MainWindow::SetErasePins(bool b)
{
	if ( b == GetErasePins() ) return;
	if ( b ) HideAllNonDockedDlgs();
	m_eMouseMode = ( b ) ? MOUSE_MODE::ERASE_PINS : MOUSE_MODE::SELECT;
	centralWidget()->setCursor(b ? Qt::CrossCursor : Qt::OpenHandCursor);
	UpdateControls();
}
void MainWindow::SetPaintBoard(bool b)
{
	if ( b == GetPaintBoard() ) return;
	if ( b ) HideAllNonDockedDlgs();
	m_eMouseMode = ( b ) ? MOUSE_MODE::PAINT_GRID : MOUSE_MODE::SELECT;;
	centralWidget()->setCursor(b ? Qt::CrossCursor : Qt::OpenHandCursor);
	UpdateControls();
}
void MainWindow::SetEraseBoard(bool b)
{
	if ( b == GetEraseBoard() ) return;
	if ( b ) HideAllNonDockedDlgs();
	m_eMouseMode = ( b ) ? MOUSE_MODE::ERASE_GRID : MOUSE_MODE::SELECT;;
	centralWidget()->setCursor(b ? Qt::CrossCursor : Qt::OpenHandCursor);
	UpdateControls();
}
void MainWindow::SetPaintFlood(bool b)
{
	if ( b == GetPaintFlood() ) return;
	if ( b ) HideAllNonDockedDlgs();
	m_eMouseMode = ( b ) ? MOUSE_MODE::PAINT_FLOOD : MOUSE_MODE::SELECT;
	centralWidget()->setCursor(b ? Qt::CrossCursor : Qt::OpenHandCursor);
	UpdateControls();
}
void MainWindow::SetEditLayerPref(bool b)
{
	if ( b == GetEditLayerPref() ) return;
	if ( b ) HideAllNonDockedDlgs();
	m_eMouseMode = ( b ) ? MOUSE_MODE::EDIT_LAYER_PREF : MOUSE_MODE::SELECT;
	centralWidget()->setCursor(b ? Qt::CrossCursor : Qt::OpenHandCursor);
	UpdateControls();
}

void MainWindow::SetDefiningRect(bool b)
{
	if ( b == GetDefiningRect() ) return;
	if ( b ) HideAllNonDockedDlgs();
	m_eMouseMode = ( b ) ? MOUSE_MODE::DEFINE_RECT : MOUSE_MODE::SELECT;
	centralWidget()->setCursor(b ? Qt::SizeFDiagCursor : Qt::OpenHandCursor);
	UpdateControls();
}
void MainWindow::SetResizingText(bool b)
{
	if ( b == GetResizingText() ) return;
	if ( b ) { m_wireDlg->hide();	m_bomDlg->hide();	m_findDlg->hide(); }	// Mutually exclusive with m_textDlg
	m_eMouseMode = ( b ) ? MOUSE_MODE::RESIZE_TEXT : MOUSE_MODE::SELECT;
	UpdateControls();
}
void MainWindow::SetSmartPan(bool b)
{
	if ( b == GetSmartPan() ) return;
	if ( b ) HideAllNonDockedDlgs();
	m_eMouseMode = ( b ) ? MOUSE_MODE::SMART_PAN : MOUSE_MODE::SELECT;
	centralWidget()->setCursor(Qt::OpenHandCursor);
	UpdateControls();
}

void MainWindow::SetMouseActionString(const std::string& str, const int objId)
{
	m_mouseActionString	= str;
	m_mouseObjId		= objId;
}