File: xyscanWindow.cpp

package info (click to toggle)
xyscan 4.30-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 3,516 kB
  • sloc: cpp: 3,371; xml: 67; makefile: 15
file content (2722 lines) | stat: -rw-r--r-- 101,572 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
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
//-----------------------------------------------------------------------------
//  Copyright (C) 2002-2017 Thomas S. Ullrich
//
//  This file is part of "xyscan".
//
//  This file may be used under the terms of the GNU General Public License.
//  This project is free software; you can redistribute it and/or modify it
//  under the terms of the GNU General Public License.
//  
//  Author: Thomas S. Ullrich
//  Last update: November 9, 2017
//-----------------------------------------------------------------------------
#include <QAction>
#include <QListWidget>
#include <QMenu>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QToolBox>
#include <QLineEdit>
#include <QPushButton>
#include <QRadioButton>
#include <QComboBox>
#include <QGraphicsPixmapItem>
#include <QGraphicsLineItem>
#include <QGraphicsSceneDragDropEvent>
#include <QDoubleSpinBox>
#include <QLabel>
#include <QGridLayout>
#include <QDockWidget>
#include <QMessageBox>
#include <QStatusBar>
#include <QMenuBar>
#include <QHeaderView>
#include <QGroupBox>
#include <QInputDialog>
#include <QApplication>
#include <QDesktopWidget>
#include <QColorDialog>
#include <QFileDialog>
#include <QPrintDialog>
#include <QPrinter>
#include <QShortcut>
#include <QMimeData>
#include <QtPrintSupport>
#include <QEvent>
#include <cmath>
#include <cfloat>
#include <iostream>
#ifndef Q_OS_WIN 
#include <poppler-qt5.h>
#endif
#include "xyscanWindow.h"
#include "xyscanVersion.h"
#include "xyscanAbout.h"
#include "xyscanHelpBrowser.h"
#include "xyscanMarkerMaps.h"
#include "xyscanUpdater.h"
#include "xyscanGraphicsView.h"
#include "xyscanDataTable.h"

using namespace std;

#define PR(x) cout << #x << " = " << (x) << endl;

xyscanWindow::xyscanWindow()
{
    //
    //  First handle command line arguments
    //
    QCommandLineParser parser;
    parser.setApplicationDescription(tr("xyscan, a data thief for scientific applications"));
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("image", tr("Image file to scan"));
    
    parser.process(*qApp);
    
    QString commandLineImageFile;
    const QStringList args = parser.positionalArguments();
    if (args.size()) commandLineImageFile = args.at(0);  // use only first

    //
    //  Create central widget and main elements:
    //  graphic view and tool box.
    //
    mCentralWidget = new QWidget(this);
    auto gridLayout = new QGridLayout(mCentralWidget);
    auto splitter = new QSplitter(mCentralWidget);
    splitter->setOrientation(Qt::Horizontal);
    mImageView = new xyscanGraphicsView(splitter);
    splitter->addWidget(mImageView);
    mToolBox = new QToolBox(splitter);
    mToolBox->setMaximumWidth(280);
    splitter->addWidget(mToolBox);
    gridLayout->addWidget(splitter, 0, 0, 1, 1);
    setCentralWidget(mCentralWidget);
   
    //
    //  Default colors for crosshair and markers
    //
    //  By setting these as custom colors, the user can always
    //  go back to the default color.
    //
    mCrosshairColor = Qt::red;
    mMarkerColor = QColor("#00BB00");
    QColorDialog::setCustomColor(0, mCrosshairColor);
    QColorDialog::setCustomColor(1, mMarkerColor);

    //
    //  Create widgets, docks, and dialogs.
    //  Order matters here a lot.
    //
    mImageScene = new QGraphicsScene(mImageView);
    mImageView->setScene(mImageScene);
    mImageView->setCacheMode(QGraphicsView::CacheBackground);
    mImageView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    mAboutDialog = new xyscanAbout(this);
        
    mImageAngle = 0;
    mImageScale = 1;
    
    createMenuActions();
    createMenus();
    createStatusBar();
    createToolBox();
    createTableDockingWidget();
    createMarker();
    createCrosshair();
    createZoomDockingWidget();
    createSettingMarkerActions();  
    createHelpBrowser();
    createToolTips();
    
    //
    //  Create sound effects
    //
    mSoundEffect.setSource(QUrl::fromLocalFile(":/sounds/buttonClick.wav"));
    mSoundEffect.setVolume(0.2);
    mSoundEffect.setLoopCount(1);
    
    //
    // Connect remaining signals and slots
    //
    connect(mLogXRadioButton, SIGNAL(toggled(bool)), this, SLOT(updateWhenAxisScaleChanged()));
    connect(mLogYRadioButton, SIGNAL(toggled(bool)), this, SLOT(updateWhenAxisScaleChanged()));
    connect(mAngleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(rotateImage(double)));
    connect(mScaleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(scaleImage(double)));
    connect(mImageView, SIGNAL(fileDropped(QString)), this, SLOT(loadDroppedFile(QString)));
    connect(&mUpdater, SIGNAL(userReminded()), this, SLOT(userWasRemindedOfAvailableUpdate()));
    connect(mStartMeasureButton , SIGNAL(toggled(bool)), this, SLOT(enableMeasuring(bool)));
    connect(mMeasureAngleRadiansCheckBox , SIGNAL(toggled(bool)), this, SLOT(updateMeasureDisplay()));
    connect(mMeasureScaleComboBox , SIGNAL(currentIndexChanged(int)), this, SLOT(updateMeasureDisplay()));
    connect(mMeasureUserScaleField , SIGNAL(textEdited(const QString)), this, SLOT(updateMeasureDisplay()));
    connect(mDeleteLastAction, SIGNAL(triggered()), mDataTable, SLOT(deleteLast()));
    connect(mDeleteAllAction, SIGNAL(triggered()), mDataTable, SLOT(deleteAll()));

    //
    //  Set main window properties
    //
    setWindowTitle("xyscan");
    setWindowIcon(QIcon(QString::fromUtf8(":/images/xyscanIcon.png")));
    
    //
    //  Create line for measure tool
    //
    mMeasureLine = new QGraphicsLineItem();
    mMeasureLine->setPen(QPen(mMarkerColor));
    mMeasureLine->setZValue(1);
    mImageScene->addItem(mMeasureLine);

    //
    //  Initialize remaining data member
    //
    mCurrentPixmap = 0;
    for (int i=0; i<4; i++)
        mMarkerPixel[i] = mMarkerPlotCoordinate[i] = 0;
    mClearHistoryAction->setDisabled(true);
    
    //
    //  Read the preferences from file.
    //  This comes late in the init phase
    //  by purpose since some parts need to be
    //  created first. Don't move.
    //
    loadSettings();

    //
    //  Disable all buttons that are useless 
    //  when no image is loaded ...
    //
    mSetLowerXButton->setDisabled(true);
    mSetUpperXButton->setDisabled(true);
    mSetLowerYButton->setDisabled(true);
    mSetUpperYButton->setDisabled(true);
    mLogXRadioButton->setDisabled(true);
    mLogYRadioButton->setDisabled(true);    
    mAngleSpinBox->setDisabled(true);    
    mScaleSpinBox->setDisabled(true);    
    mErrorXModeComboBox->setDisabled(true);
    mErrorYModeComboBox->setDisabled(true);
    mSaveAction->setDisabled(true);
    mPrintAction->setDisabled(true);
    mShowPrecisionAction->setDisabled(true);
    mDeleteLastAction->setDisabled(true);
    mDeleteAllAction->setDisabled(true);
    mEditCommentAction->setDisabled(true);
    mEditCrosshairColorAction->setDisabled(true);
    mEditMarkerColorAction->setDisabled(true);
    mStartMeasureButton->setDisabled(true);

    //
    //  Give window some reasonable initial size
    //
    this->resize(800, 480);
    this->setMinimumHeight(450); // good size ensuring all too box items are visible
    
    //
    //  Screen scan is off by default. Set boolean that flags
    //  the state. Is set true in enableScreenScan().
    //
    mScreenScanIsOn = false;
    
    //
    //  Event filter:
    //  We filter (i) graphics scene events here
    //  to handle mouse events to, e.g move the cursor
    //  and (ii) receive all events from the
    //  application to intercept tool tips in order
    //  to ignore them in case the user disabled
    //  tooltips (Help menu). See also main().
    //
    mImageScene->installEventFilter(this);
    qApp->installEventFilter(this);
    
    //
    //  Act if command line argumets were present
    //
    if (!commandLineImageFile.isEmpty()) openFromFile(commandLineImageFile);
    
    //
    //  Auto check for updates. We ignore all error messages
    //  in that process. Only if an update is present a info
    //  dialog pops up. To not annoy the user we do this only
    //  3-4 days after the last reminder.
    //
    QDateTime now = QDateTime::currentDateTime();
    if (mLastReminderTime.daysTo(now) > 3) {
        mUpdater.setNextCheckIsSilent(true);
        checkForUpdates();
    }
}

xyscanWindow::~xyscanWindow() { /* no op */ }

void xyscanWindow::about() 
{
    mAboutDialog->show();
}

void xyscanWindow::addToTable(double x, double y, double dxl, double dxu, double dyl, double dyu)
{
    //
    //  Store data into new table row
    //
    mDataTable->addPoint(x, y, dxl, dxu, dyl, dyu);

    //
    //  Enable all buttons that make sense once 
    //  at least one data point is scanned ...
    //
    mSaveAction->setDisabled(false);
    mPrintAction->setDisabled(false);
    mDeleteLastAction->setDisabled(false);
    mDeleteAllAction->setDisabled(false);
}

void xyscanWindow::checkForUpdates()
{
    mUpdater.checkForNewVersion(QUrl("http://rhig.physics.yale.edu/~ullrich/software/xyscan/xyscanLatestVersion.xml"));
}

bool xyscanWindow::checkForUnsavedData()
{
    //
    //  Allows he user to save the data before continuing.
    //  Method returns true when data was saved or explicitly
    //  discarded or false when Cancel was pressed.
    //
    if (!(mCurrentPixmap && mDataTable->rowCount() && !mDataTable->dataSaved())) return true;
    
    int ret = QMessageBox::warning(this, "xyscan",
                                   tr("Do you want to save the data you scanned?\n"
                                      "The content of the data table will be lost if you don’t save it."),
                                   QMessageBox::Save | QMessageBox::Discard |
                                   QMessageBox::Cancel, QMessageBox::Save);
    if (ret == QMessageBox::Save) {
        save();
        return true;
    }
    else if (ret == QMessageBox::Cancel)
        return false;
    else
        return true;
}

void xyscanWindow::clearHistory() 
{
    //
    //  Remove all stored recent files from submenu (File/Open Recent)
    //
    for (int i = 0; i < mRecentFiles.size(); ++i) {
        mRecentFileAction[i]->setVisible(false);
    }
    mRecentFiles.clear();
    mClearHistoryAction->setDisabled(true);
}

void xyscanWindow::closeEvent(QCloseEvent* e)
{
    //
    //  Reimplement, otherwise pressing the x button on the
    //  window frame closes the applications and we have
    //  no chance for storing the settings and checking
    //  for unsaved data.
    //
    finish(); 
    e->ignore();   // exit initiated in finish() or not at all
}

void xyscanWindow::createAdjustmentToolBoxItem(QWidget *form)
{
    QGridLayout *gridLayout = new QGridLayout(form);
    
    //
    //  Info label on top
    //
    mPlotInfoLabel = new QLabel(form);
    mPlotInfoLabel->setText(tr("No plot loaded"));
    gridLayout->addWidget(mPlotInfoLabel, 0, 0, 1, 1);
    
    //
    //  Separator line
    //
    QFrame *line = new QFrame(form);
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    gridLayout->addWidget(line, 1, 0, 1, 1);

    //
    //  Angle/rotate spin box with label
    //
    QLabel* labelAngle = new QLabel(form);
    labelAngle->setText(tr("Rotate:"));
    QFontMetrics fontMetrics(labelAngle->font());
    int labelWidth = fontMetrics.width(labelAngle->text());   // use that width for all distance labels
    labelAngle->setFixedWidth(labelWidth);
    mAngleSpinBox = new QDoubleSpinBox(form);
    mAngleSpinBox->setMinimum(-90);
    mAngleSpinBox->setMaximum(180);
    mAngleSpinBox->setSingleStep(0.05);
    mAngleSpinBox->setAccelerated(true);
    mAngleSpinBox->setValue(mImageAngle);
    QLabel* labelScale = new QLabel(form);
    labelScale->setText(tr("Scale:"));
    labelScale->setFixedWidth(labelWidth);
    mScaleSpinBox = new QDoubleSpinBox(form);
    mScaleSpinBox->setMinimum(0.1);
    mScaleSpinBox->setMaximum(10);
    mScaleSpinBox->setSingleStep(0.05);
    mScaleSpinBox->setAccelerated(true);
    mScaleSpinBox->setValue(mImageScale);
    
    QHBoxLayout *horizontalLayoutAngle = new QHBoxLayout();
    horizontalLayoutAngle->addWidget(labelAngle);
    horizontalLayoutAngle->addWidget(mAngleSpinBox);
    horizontalLayoutAngle->addItem(new QSpacerItem(100, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));
    QHBoxLayout *horizontalLayoutScale = new QHBoxLayout();
    horizontalLayoutScale->addWidget(labelScale);
    horizontalLayoutScale->addWidget(mScaleSpinBox);
    horizontalLayoutScale->addItem(new QSpacerItem(100, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));

    gridLayout->addLayout(horizontalLayoutAngle, 2, 0, 1, 1);
    gridLayout->addLayout(horizontalLayoutScale, 3, 0, 1, 1);
    
    //
    //  Spacers
    //
    QSpacerItem *verticalSpacer = new QSpacerItem(20, 100, QSizePolicy::Minimum, QSizePolicy::Expanding);
    QSpacerItem *horizontalSpacer = new QSpacerItem(100, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    
    gridLayout->addItem(horizontalSpacer, 2, 1, 1, 1);
    gridLayout->addItem(verticalSpacer, 4, 0, 1, 1);
}

void xyscanWindow::createAxisSettingsToolBoxItem(QWidget *form)
{
    QGridLayout *gridLayout = new QGridLayout(form);
#if defined(Q_OS_MAC)
    gridLayout->setVerticalSpacing(0);  // On macOs too much room around Set buttons
#endif
    
    //
    //  Markers widgets
    //
    QLabel *labelLX = new QLabel(form);
    QLabel *labelUX = new QLabel(form);
    QLabel *labelLY = new QLabel(form);
    QLabel *labelUY = new QLabel(form);
    mSetLowerXButton = new QPushButton(form);
    mSetUpperXButton = new QPushButton(form);
    mSetLowerYButton = new QPushButton(form);
    mSetUpperYButton = new QPushButton(form);
    mLowerXValueField = new QLineEdit(form);
    mLowerXValueField->setReadOnly(true);
    mUpperXValueField = new QLineEdit(form);
    mUpperXValueField->setReadOnly(true);
    mLowerYValueField = new QLineEdit(form);
    mLowerYValueField->setReadOnly(true);
    mUpperYValueField = new QLineEdit(form);
    mUpperYValueField->setReadOnly(true);
    
    QHBoxLayout *horizontalLayoutLX = new QHBoxLayout();
    horizontalLayoutLX->addWidget(labelLX);
    horizontalLayoutLX->addWidget(mLowerXValueField);
    horizontalLayoutLX->addWidget(mSetLowerXButton);
    
    gridLayout->addLayout(horizontalLayoutLX, 0, 0, 1, 1);
    QHBoxLayout *horizontalLayoutUX = new QHBoxLayout();
    horizontalLayoutUX->addWidget(labelUX);
    horizontalLayoutUX->addWidget(mUpperXValueField);
    horizontalLayoutUX->addWidget(mSetUpperXButton);
    gridLayout->addLayout(horizontalLayoutUX, 1, 0, 1, 1);
    QHBoxLayout *horizontalLayoutLY = new QHBoxLayout();
    horizontalLayoutLY->addWidget(labelLY);
    horizontalLayoutLY->addWidget(mLowerYValueField);
    horizontalLayoutLY->addWidget(mSetLowerYButton);
    gridLayout->addLayout(horizontalLayoutLY, 2, 0, 1, 1);
    QHBoxLayout *horizontalLayoutUY = new QHBoxLayout();
    horizontalLayoutUY->addWidget(labelUY);
    horizontalLayoutUY->addWidget(mUpperYValueField);
    horizontalLayoutUY->addWidget(mSetUpperYButton);
    gridLayout->addLayout(horizontalLayoutUY, 3, 0, 1, 1);
    
    //
    //  Axis mode (lin/log) and rotate & scale of plot
    //
    QLabel *labelLinLog = new QLabel(form);
    mLogXRadioButton = new QRadioButton(form);
    mLogYRadioButton = new QRadioButton(form);
    mLogXRadioButton->setAutoExclusive(false);
    mLogYRadioButton->setAutoExclusive(false);  // not a toggle radio button

    QHBoxLayout *horizontalLayoutLinLog = new QHBoxLayout();
    horizontalLayoutLinLog->addWidget(labelLinLog);
    horizontalLayoutLinLog->addWidget(mLogXRadioButton);
    horizontalLayoutLinLog->addWidget(mLogYRadioButton);
 
    gridLayout->addWidget(new QLabel(form), 4, 0, 1, 1);
    gridLayout->addLayout(horizontalLayoutLinLog, 5, 0, 1, 1);

    //
    //  Spacers
    //
    QSpacerItem *verticalSpacer = new QSpacerItem(20, 100, QSizePolicy::Minimum, QSizePolicy::Expanding);
    QSpacerItem *horizontalSpacer = new QSpacerItem(100, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    
    gridLayout->addItem(horizontalSpacer, 4, 1, 1, 1);
    gridLayout->addItem(verticalSpacer, 6, 0, 1, 1);

    //
    //  Set text of all labels
    //
    labelLX->setText(tr("Lower x:"));
    mSetLowerXButton->setText(tr("Set"));
    mLowerXValueField->setText(tr("undefined"));
    labelUX->setText(tr("Upper x:"));
    mSetUpperXButton->setText(tr("Set"));
    mUpperXValueField->setText(tr("undefined"));
    labelLY->setText(tr("Lower y:"));
    mSetLowerYButton->setText(tr("Set"));
    mLowerYValueField->setText(tr("undefined"));
    labelUY->setText(tr("Upper y:"));
    mSetUpperYButton->setText(tr("Set"));
    mUpperYValueField->setText(tr("undefined"));
    mLogXRadioButton->setText(tr("Log x"));
    mLogYRadioButton->setText(tr("Log y"));
    labelLinLog->setText(tr("Lin/Log Scale:"));
}

void xyscanWindow::createCoordinateToolBoxItem(QWidget *form)
{
    const int lineEditWidth = 150;
    QGridLayout *gridLayout = new QGridLayout(form);
    
    //
    //  Pixel coordinates
    //
    QLabel *pixelLabel = new QLabel(form);
    QLabel *xpLabel = new QLabel(form);
    QLabel *ypLabel = new QLabel(form);
    mPixelXDisplay = new QLineEdit(form);
    mPixelXDisplay->setReadOnly(true);
    mPixelXDisplay->setText(tr("N/A"));
    mPixelXDisplay->setFixedWidth(lineEditWidth);
    mPixelYDisplay = new QLineEdit(form);
    mPixelYDisplay->setReadOnly(true);
    mPixelYDisplay->setText(tr("N/A"));
    mPixelYDisplay->setFixedWidth(lineEditWidth);
    
    QHBoxLayout *horizontalLayoutPX = new QHBoxLayout();
    horizontalLayoutPX->addWidget(xpLabel);
    horizontalLayoutPX->addWidget(mPixelXDisplay);
    QHBoxLayout *horizontalLayoutPY = new QHBoxLayout();
    horizontalLayoutPY->addWidget(ypLabel);
    horizontalLayoutPY->addWidget(mPixelYDisplay);
    
    gridLayout->addWidget(pixelLabel, 0, 0, 1, 1);
    gridLayout->addLayout(horizontalLayoutPX, 1, 0, 1, 1);
    gridLayout->addLayout(horizontalLayoutPY, 2, 0, 1, 1);
    gridLayout->addWidget(new QLabel(form), 3, 0, 1, 1);

    //
    //  Plot coordinates
    //
    QLabel *plotCoordinateLabel = new QLabel(form);
    QLabel *xcLabel = new QLabel(form);
    QLabel *ycLabel = new QLabel(form);
    mPlotXDisplay = new QLineEdit(form);
    mPlotXDisplay->setReadOnly(true);
    mPlotXDisplay->setText(tr("N/A"));
    mPlotXDisplay->setFixedWidth(lineEditWidth);
    mPlotYDisplay = new QLineEdit(form);
    mPlotYDisplay->setReadOnly(true);
    mPlotYDisplay->setText(tr("N/A"));
    mPlotYDisplay->setFixedWidth(lineEditWidth);

    QHBoxLayout *horizontalLayoutCX = new QHBoxLayout();
    horizontalLayoutCX->addWidget(xcLabel);
    horizontalLayoutCX->addWidget(mPlotXDisplay);
    QHBoxLayout *horizontalLayoutCY = new QHBoxLayout();
    horizontalLayoutCY->addWidget(ycLabel);
    horizontalLayoutCY->addWidget(mPlotYDisplay);

    gridLayout->addWidget(plotCoordinateLabel, 4, 0, 1, 1);
    gridLayout->addLayout(horizontalLayoutCX, 5, 0, 1, 1);
    gridLayout->addLayout(horizontalLayoutCY, 6, 0, 1, 1);

    //
    //  Spacers
    //
    QSpacerItem *verticalSpacer = new QSpacerItem(20, 100, QSizePolicy::Minimum, QSizePolicy::Expanding);
    QSpacerItem *horizontalSpacer = new QSpacerItem(100, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    
    gridLayout->addItem(horizontalSpacer, 2, 1, 1, 1);
    gridLayout->addItem(verticalSpacer, 7, 0, 1, 1);

    //
    //  Set text of all labels
    //
    pixelLabel->setText(tr("Pixel:"));
    xpLabel->setText(tr("x:"));
    ypLabel->setText(tr("y:"));
    plotCoordinateLabel->setText(tr("Plot Coordinates:"));
    xcLabel->setText(tr("x:"));
    ycLabel->setText(tr("y:"));
}

void xyscanWindow::createCrosshair()
{
    QRectF r = mImageScene->sceneRect();
    
    mCrosshairH = new QGraphicsLineItem(-5000, 0, 5000, 0); // big enough for all evantualities
    mCrosshairH->setZValue(2);
    mCrosshairH->setPen(QPen(mCrosshairColor));
    mCrosshairH->setVisible(false);
    mImageScene->addItem(mCrosshairH);
    
    mCrosshairV = new QGraphicsLineItem(0, -5000, 0, 5000);
    mCrosshairV->setZValue(2);
    mCrosshairV->setPen(QPen(mCrosshairColor));
    mCrosshairV->setVisible(false);
    mImageScene->addItem(mCrosshairV);
    
    mImageScene->setSceneRect(r); // don't alter the size of the scene yet,
                                  // otherwise scrollbars appear for an empty canvas
}

void xyscanWindow::createErrorBarScanModeToolBoxItem(QWidget *form)
{
    QGridLayout *gridLayout = new QGridLayout(form);
    
    QLabel *label1 = new QLabel(form);
    mErrorXModeComboBox = new QComboBox(form);
    QLabel *label2 = new QLabel(form);
    mErrorYModeComboBox = new QComboBox(form);
    
    QHBoxLayout *horizontalLayoutEX = new QHBoxLayout();
    horizontalLayoutEX->addWidget(label1);
    horizontalLayoutEX->addWidget(mErrorXModeComboBox);
    QHBoxLayout *horizontalLayoutEY = new QHBoxLayout();
    horizontalLayoutEY->addWidget(label2);
    horizontalLayoutEY->addWidget(mErrorYModeComboBox);
    
    gridLayout->addLayout(horizontalLayoutEX, 0, 0, 1, 1);
    gridLayout->addLayout(horizontalLayoutEY, 1, 0, 1, 1);
    
    //
    //    Spacers
    //
    QSpacerItem *verticalSpacer = new QSpacerItem(20, 100, QSizePolicy::Minimum, QSizePolicy::Expanding);
    QSpacerItem *horizontalSpacer = new QSpacerItem(100, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    
    gridLayout->addItem(horizontalSpacer, 0, 1, 1, 1);
    gridLayout->addItem(verticalSpacer, 2, 0, 1, 1);

    //
    //    Set text
    //
    label1->setText(tr("x-Error:"));
    mErrorXModeComboBox->clear();
    mErrorXModeComboBox->insertItems(0, QStringList()
                                     << tr("No Scan")
                                     << tr("Asymmetric")
                                     << tr("Symmetric (mean)")
                                     << tr("Symmetric (max)")
                                     );
    label2->setText(tr("y-Error:"));
    mErrorYModeComboBox->clear();
    mErrorYModeComboBox->insertItems(0, QStringList()
                                     << tr("No Scan")
                                     << tr("Asymmetric")
                                     << tr("Symmetric (mean)")
                                     << tr("Symmetric (max)")
                                     );
}

void xyscanWindow::createHelpBrowser()
{
    mHelpBrowser = 0;
    
    //
    //  The documentation is in the docs/ directory.
    //  On MacOS it is the app bundle under Resources,
    //  on Linux typically in /usr/share/xyscan.
    //  Here we go through the various options step by step.
    //
    
    QString path;
    
    //
    //  1. This is for the developer using xyscan/docs directly
    //  for easier testing and turn around times.
    //
    path = "/Users/ullrich/Documents/Projects/xyscan/docs";
    QDir dir(path);
    
    //
    //  2. MacOS
    //
    if (!dir.exists()) {
        path = qApp->applicationDirPath() + "/../Resources/docs";
        dir.setPath(path);
    }
    
    //
    //  3. Windows
    //
    if (!dir.exists()) {
        path = qApp->applicationDirPath() + "/docs";
        dir.setPath(path);
    }
	if (!dir.exists()) {
		path = qApp->applicationDirPath() + "/../../docs";
		dir.setPath(path);
	}

    //
    //  4. Linux
    //
    if (!dir.exists()) {
        path = "/usr/share/xyscan/docs";
        dir.setPath(path);
    }
    if (!dir.exists()) {
        path = "/opt/share/xyscan/docs";
        dir.setPath(path);
    }
    
    //
    //  4. Just in case we check other locations if nothing
    //     was found so far. More an act of desperation.
    //
    if (!dir.exists()) {
        path = "/usr/xyscan/docs";
        dir.setPath(path);
    }
    if (!dir.exists()) {
        path = "/opt/xyscan/docs";
        dir.setPath(path);
    }
    if (!dir.exists()) {
        path = "/usr/share/doc/xyscan/docs";
        dir.setPath(path);
    }
    if (!dir.exists()) {
       path = qApp->applicationDirPath() + "/docs";
       dir.setPath(path);
    }
    if (!dir.exists()) {
        path = qApp->applicationDirPath() + "/../docs";
        dir.setPath(path);
    }
    if (!dir.exists()) {
        path = qApp->applicationDirPath() + "../../docs";
        dir.setPath(path);
    }

    if (!dir.exists()) {
        QMessageBox::warning( 0, "xyscan",
                             tr("Cannot find the directory holding the help files (docs). "
                                "No online help will be available. "
                                "Check your installation and reinstall if necessary."));
        return;
    }

    //
    //  Setup the help browser
    //
    
    QString descFile = path + "/doc.index";
    
    QFileInfo file(descFile);
    if (file.exists())
        mHelpBrowser = new xyscanHelpBrowser(descFile, path);
    else {
        QMessageBox::warning( 0, "xyscan",
                             tr("Cannot find the index descriptor to setup the help system. "
                                "No online help will be available. "
                                "Check your installation and reinstall if necessary."));
    }
}

void xyscanWindow::createMarker()
{
    QColor color = Qt::gray;
    
    for (int i=mXLower; i<= mYUpper; i++) {
        if (i == mXLower || i == mXUpper)
            mMarker[i] = new QGraphicsLineItem(0, -5000, 0, 5000);
        else
            mMarker[i] = new QGraphicsLineItem(-5000, 0, 5000, 0);
        mMarker[i]->setPen(QPen(color));
        mMarker[i]->setZValue(1);
        mImageScene->addItem(mMarker[i]);
        mMarker[i]->setVisible(false);
    }    
    
    QPixmap imgpm(marker_cross_xpm);
    mPointMarker = new QGraphicsPixmapItem(imgpm, 0);
    mImageScene->addItem(mPointMarker);
    mPointMarker->setZValue(1);
    mPointMarker->setVisible(false);
    
    mImageScene->setSceneRect(0, 0, 200, 200); // avoid sliders at beginning
}

void xyscanWindow::createMeasureToolBoxItem(QWidget *form)
{
    QGridLayout *gridLayout = new QGridLayout(form);
    
    const int maxMeasureNumbersDisplayWidth = 150;
    
    //
    //   Start button
    //
    mStartMeasureButton = new QPushButton(form);
    mStartMeasureButton->setText(tr("Start Measuring"));
    mStartMeasureButton->setCheckable(true);
    gridLayout->addWidget(mStartMeasureButton, 0, 0, 1, 1);
    
    //
    //   Measure displays
    //
    
    //
    //   delta x
    //
    QHBoxLayout *horizontalLayoutDX = new QHBoxLayout();
    QLabel *labelDX = new QLabel(form);
    labelDX->setText(tr("dx:"));
    QSizePolicy sizePolicy(QSizePolicy::Minimum, QSizePolicy::Preferred);
    labelDX->setSizePolicy(sizePolicy);
    QFontMetrics fontMetrics(labelDX->font());
    int labelWidth = fontMetrics.width(labelDX->text());   // use that width for all distance labels
    labelDX->setFixedWidth(labelWidth);

    mMeasureDXDisplay = new QLineEdit(form);
    mMeasureDXDisplay->setReadOnly(true);
    mMeasureDXDisplay->setText(tr("N/A"));
    mMeasureDXDisplay->setMaximumWidth(maxMeasureNumbersDisplayWidth);
    
    horizontalLayoutDX->addWidget(labelDX);
    horizontalLayoutDX->addWidget(mMeasureDXDisplay);
    gridLayout->addLayout(horizontalLayoutDX, 1, 0, 1, 1);
    
    //
    //   delta y
    //
    QHBoxLayout *horizontalLayoutDY = new QHBoxLayout();
    QLabel *labelDY = new QLabel(form);
    labelDY->setText(tr("dy:"));
    labelDY->setSizePolicy(sizePolicy);
    labelDY->setFixedWidth(labelWidth);
    
    mMeasureDYDisplay = new QLineEdit(form);
    mMeasureDYDisplay->setReadOnly(true);
    mMeasureDYDisplay->setText(tr("N/A"));
    mMeasureDYDisplay->setMaximumWidth(maxMeasureNumbersDisplayWidth);
    
    horizontalLayoutDY->addWidget(labelDY);
    horizontalLayoutDY->addWidget(mMeasureDYDisplay);
    gridLayout->addLayout(horizontalLayoutDY, 2, 0, 1, 1);
    
    //
    //    Radial/Total distance
    //
    QHBoxLayout *horizontalLayoutDR = new QHBoxLayout();
    QLabel *labelDR = new QLabel(form);
    labelDR->setText(tr("r:"));
    labelDR->setSizePolicy(sizePolicy);
    labelDR->setFixedWidth(labelWidth);

    mMeasureDRDisplay = new QLineEdit(form);
    mMeasureDRDisplay->setReadOnly(true);
    mMeasureDRDisplay->setText(tr("N/A"));
    mMeasureDRDisplay->setMaximumWidth(maxMeasureNumbersDisplayWidth);
    
    horizontalLayoutDR->addWidget(labelDR);
    horizontalLayoutDR->addWidget(mMeasureDRDisplay);
    gridLayout->addLayout(horizontalLayoutDR, 3, 0, 1, 1);
    
    //
    //    Angle
    //
    QHBoxLayout *horizontalLayoutDA = new QHBoxLayout();
    QLabel *labelDA = new QLabel(form);
#if defined(Q_OS_WIN)
    labelDA->setText(QString::fromWCharArray(L"\u2220:"));
#else
    labelDA->setText(QString::fromUtf8("\u2220:"));
#endif
    labelDA->setSizePolicy(sizePolicy);
    labelDA->setFixedWidth(labelWidth);

    mMeasureDADisplay = new QLineEdit(form);
    mMeasureDADisplay->setReadOnly(true);
    mMeasureDADisplay->setText(tr("N/A"));
    mMeasureDADisplay->setMaximumWidth(maxMeasureNumbersDisplayWidth);
    
    horizontalLayoutDA->addWidget(labelDA);
    horizontalLayoutDA->addWidget(mMeasureDADisplay);

    gridLayout->addLayout(horizontalLayoutDA, 4, 0, 1, 1);

    //
    //  Check box to select radians instead of degrees
    //
    mMeasureAngleRadiansCheckBox = new QCheckBox(tr("Radians"), form);
    gridLayout->addWidget(mMeasureAngleRadiansCheckBox, 4, 1, 1, 1);

    //
    //  Units Selector
    //
    QLabel *labelUS = new QLabel(form);
    labelUS->setText(tr("Units:"));
    mMeasureScaleComboBox = new QComboBox(form);
    mMeasureScaleComboBox->clear();
    mMeasureScaleComboBox->insertItems(0, QStringList()
                                       << tr("Pixel")
                                       << tr("Plot Units")
                                       << tr("User Scale")
                                       );
    mMeasureScaleComboBox->setCurrentIndex(mPixelUnits);
    mMeasureScaleComboBox->setDisabled(true);
    mMeasureUserScaleField = new QLineEdit(form);
    mMeasureUserScaleField->setVisible(false);
    mMeasureUserScaleField->setText("1.0");
    QHBoxLayout *horizontalLayoutUS = new QHBoxLayout();
    horizontalLayoutUS->addWidget(labelUS);
    horizontalLayoutUS->addWidget(mMeasureScaleComboBox);
    gridLayout->addLayout(horizontalLayoutUS, 5, 0, 1, 1);
    gridLayout->addWidget(mMeasureUserScaleField, 5, 1, 1, 1);

    //
    //  Spacers
    //
    QSpacerItem *verticalSpacer = new QSpacerItem(20, 100, QSizePolicy::Minimum, QSizePolicy::Expanding);
    QSpacerItem *horizontalSpacer = new QSpacerItem(100, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
    
    gridLayout->addItem(horizontalSpacer, 2, 1, 1, 1);
    gridLayout->addItem(verticalSpacer, 6, 0, 1, 1);
    
    //
    //  Define shortcut for the normalization of the user scale
    //
    QShortcut *shortcutX = new QShortcut(Qt::CTRL + Qt::Key_N, mMeasureUserScaleField);
    connect(shortcutX, &QShortcut::activated, [=](){this->normalizeUserScale();});
    QShortcut *shortcutM = new QShortcut(Qt::CTRL + Qt::Key_M, mMeasureItem);
    connect(shortcutM, &QShortcut::activated, [=](){this->enableMeasuring(true);});
}

void xyscanWindow::createMenus()
{
    mFileMenu = menuBar()->addMenu(tr("&File"));
    mFileMenu->addAction(mOpenAction);
    mRecentFilesMenu = mFileMenu->addMenu(tr("Open &Recent")); // submenu
    for (int i = 0; i < mMaxRecentFiles; ++i)
        mRecentFilesMenu->addAction(mRecentFileAction[i]);
    mRecentFilesMenu->addSeparator();
    mRecentFilesMenu->addAction(mClearHistoryAction);
    mFileMenu->addAction(mSaveAction);
    mFileMenu->addSeparator();
    mFileMenu->addAction(mScreenScanAction);
    mFileMenu->addSeparator();
    mFileMenu->addAction(mPrintAction);
#if !defined(Q_OS_MAC)
    mFileMenu->addSeparator();
#endif
    mFileMenu->addAction(mFinishAction);

    mEditMenu = menuBar()->addMenu(tr("&Edit"));
    mEditMenu->addAction(mEditCrosshairColorAction); 
    mEditMenu->addAction(mEditMarkerColorAction);
    mEditMenu->addSeparator();
    mEditMenu->addAction(mPasteImageAction); 
    mEditMenu->addSeparator();
    mEditMenu->addAction(mDeleteLastAction);
    mEditMenu->addAction(mDeleteAllAction);
    mEditMenu->addSeparator();
    mEditMenu->addAction(mEditCommentAction);
    
    mViewMenu = menuBar()->addMenu(tr("&View"));
    mViewMenu->addAction(mShowPrecisionAction);

    mViewMenu->addSeparator();
    // dock windows toggle menues added later in createDockWindows()
    
    mHelpMenu = menuBar()->addMenu(tr("&Help"));
    mHelpMenu->addAction(mCheckForUpdatesAction);
    mHelpMenu->addSeparator();
    mHelpMenu->addAction(mShowTooltipsAction);
    mHelpMenu->addAction(mHelpAction);
#if !defined(Q_OS_MAC)
    mHelpMenu->addSeparator();
#endif    
    mHelpMenu->addAction(mAboutAction);  // In application menu on MacOS/X
}

void xyscanWindow::createMenuActions()
{
    mOpenAction = new QAction(tr("&Open..."), this);
    mOpenAction->setShortcut(QKeySequence::Open);
    connect(mOpenAction, SIGNAL(triggered()), this, SLOT(open()));
    
    for (int i = 0; i < mMaxRecentFiles; ++i) {
        mRecentFileAction[i] = new QAction(this);
        mRecentFileAction[i]->setVisible(false);
        connect(mRecentFileAction[i], SIGNAL(triggered()), this, SLOT(openRecent()));
    }
    
    mClearHistoryAction = new QAction(tr("&Clear History"), this);
    connect(mClearHistoryAction, SIGNAL(triggered()), this, SLOT(clearHistory()));
    
    mSaveAction = new QAction(tr("&Save..."), this);
    mSaveAction->setShortcut(QKeySequence::Save); // Qt::CTRL + Qt::Key_S);
    connect(mSaveAction, SIGNAL(triggered()), this, SLOT(save()));
    
    mPrintAction = new QAction(tr("&Print..."), this);
    mPrintAction->setShortcut(QKeySequence::Print);
    connect(mPrintAction, SIGNAL(triggered()), this, SLOT(print()));
    
    mFinishAction = new QAction(tr("&Quit xyscan"), this);
    mFinishAction->setShortcut(QKeySequence::Quit);
    connect(mFinishAction, SIGNAL(triggered()), this, SLOT(finish()));
    
    mPasteImageAction = new QAction(tr("&Paste Image"), this);
    mPasteImageAction->setShortcut(QKeySequence::Paste);
    connect(mPasteImageAction, SIGNAL(triggered()), this, SLOT(pasteImage()));
    
    mEditCrosshairColorAction = new QAction(tr("Crosshair Color..."), this);
    connect(mEditCrosshairColorAction, SIGNAL(triggered()), this, SLOT(editCrosshairColor()));

    mEditMarkerColorAction = new QAction(tr("Marker Color..."), this);
    connect(mEditMarkerColorAction, SIGNAL(triggered()), this, SLOT(editMarkerColor()));

    mDeleteLastAction = new QAction(tr("Delete &Last"), this);
    mDeleteLastAction->setShortcut(QKeySequence::Undo);

    mDeleteAllAction = new QAction(tr("Delete &All"), this);
    
    mEditCommentAction = new QAction(tr("&Comment..."), this);
    mEditCommentAction->setShortcut(QKeySequence::AddTab);
    connect(mEditCommentAction, SIGNAL(triggered()), this, SLOT(editComment()));

    mShowPrecisionAction = new QAction(tr("&Current Precision"), this);
    mShowPrecisionAction->setShortcut(Qt::CTRL + Qt::Key_I);
    connect(mShowPrecisionAction, SIGNAL(triggered()), this, SLOT(showPrecision()));
    
    mScreenScanAction = new QAction(tr("Scan Screen"), this);
    mScreenScanAction->setCheckable(true);
    mScreenScanAction->setChecked(false);
    connect(mScreenScanAction, SIGNAL(triggered(bool)), this, SLOT(enableScreenScan(bool)));

    mAboutAction = new QAction(tr("&About xyscan"), this);
    connect(mAboutAction, SIGNAL(triggered()), this, SLOT(about()));
#if defined(Q_OS_MAC)
    mAboutAction->setMenuRole(QAction::AboutRole);
#endif
    
    mHelpAction = new QAction(tr("xyscan &Help"), this);
    connect(mHelpAction, SIGNAL(triggered()), this, SLOT(help()));

    mShowTooltipsAction = new QAction(tr("&Tool Tips"), this);
    mShowTooltipsAction->setCheckable(true);
    mShowTooltipsAction->setChecked(false);
    
    mCheckForUpdatesAction = new QAction(tr("&Check For Updates ..."), this);
    connect(mCheckForUpdatesAction, SIGNAL(triggered()), this, SLOT(checkForUpdates()));
}

void xyscanWindow::createSettingMarkerActions()
{
    connect(mSetLowerXButton, &QPushButton::clicked, [=](){this->setPlotCoordinateValueForMarker(mXLower);});
    connect(mSetUpperXButton, &QPushButton::clicked, [=](){this->setPlotCoordinateValueForMarker(mXUpper);});
    connect(mSetLowerYButton, &QPushButton::clicked, [=](){this->setPlotCoordinateValueForMarker(mYLower);});
    connect(mSetUpperYButton, &QPushButton::clicked, [=](){this->setPlotCoordinateValueForMarker(mYUpper);});
    
    QShortcut *shortcut1 = new QShortcut(Qt::CTRL + Qt::Key_1, mSetLowerXButton);
    QShortcut *shortcut2 = new QShortcut(Qt::CTRL + Qt::Key_2, mSetUpperXButton);
    QShortcut *shortcut3 = new QShortcut(Qt::CTRL + Qt::Key_3, mSetLowerYButton);
    QShortcut *shortcut4 = new QShortcut(Qt::CTRL + Qt::Key_4, mSetUpperYButton);

    connect(shortcut1, &QShortcut::activated, [=](){this->setPlotCoordinateValueForMarker(mXLower);});
    connect(shortcut2, &QShortcut::activated, [=](){this->setPlotCoordinateValueForMarker(mXUpper);});
    connect(shortcut3, &QShortcut::activated, [=](){this->setPlotCoordinateValueForMarker(mYLower);});
    connect(shortcut4, &QShortcut::activated, [=](){this->setPlotCoordinateValueForMarker(mYUpper);});
}

void xyscanWindow::createStatusBar()
{
    statusBar()->showMessage(tr("Ready"));
}

void xyscanWindow::createTableDockingWidget()
{
    mTableDock = new QDockWidget(tr("Data Table"), this);
    mTableDock->setVisible(false);
    mTableDock->setAllowedAreas(Qt::BottomDockWidgetArea | Qt::TopDockWidgetArea);
    QWidget *tableDockContents = new QWidget();
    
    mDataTable = new xyscanDataTable(tableDockContents);
    
    QGridLayout *gridLayout = new QGridLayout(tableDockContents);
    gridLayout->addWidget(mDataTable, 0, 0, 1, 1);
    
    mTableDock->setWidget(tableDockContents);
    addDockWidget(Qt::BottomDockWidgetArea, mTableDock);
    mTableDock->toggleViewAction()->setText(tr("&Data Table"));
    mTableDock->toggleViewAction()->setShortcut(Qt::CTRL + Qt::Key_D );

    mViewMenu->addAction(mTableDock->toggleViewAction());
    mTableDock->setFloating(true);
    mTableDock->resize(800,300);
}

void xyscanWindow::createToolBox()
{
    mPlotAdjustmentItem = new QWidget();
    mAxisSettingsItem = new QWidget();
    mErrorScanModeItem = new QWidget();
    mCoordinatesItem = new QWidget();
    mMeasureItem = new QWidget();

    mToolBox->addItem(mPlotAdjustmentItem, QString(tr("Plot Adjustment")));
    mToolBox->addItem(mAxisSettingsItem, QString(tr("Axis Settings")));
    mToolBox->addItem(mErrorScanModeItem, QString(tr("Error Bar Scan Mode")));
    mToolBox->addItem(mCoordinatesItem, QString(tr("Coordinates")));
    mToolBox->addItem(mMeasureItem, QString(tr("Measure Tool")));

    mToolBox->setCurrentIndex(1);

    createMeasureToolBoxItem(mMeasureItem);
    createCoordinateToolBoxItem(mCoordinatesItem);
    createErrorBarScanModeToolBoxItem(mErrorScanModeItem);
    createAxisSettingsToolBoxItem(mAxisSettingsItem);
    createAdjustmentToolBoxItem(mPlotAdjustmentItem);

    //
    //  Shortcuts to Coordinates and Axis Settings pages
    //  that are the most used ones.
    //
    QShortcut *shortcut1 = new QShortcut(Qt::CTRL + Qt::Key_C, mToolBox);
    connect(shortcut1, &QShortcut::activated, [=](){mToolBox->setCurrentIndex(3);});
    QShortcut *shortcut2 = new QShortcut(Qt::CTRL + Qt::Key_A, mToolBox);
    connect(shortcut2, &QShortcut::activated, [=](){mToolBox->setCurrentIndex(1);});
}

void xyscanWindow::createToolTips()
{
    ;
#if defined(Q_OS_MAC)
    QString platformCtrl(tr("Command"));
#else
    QString platformCtrl(tr("Ctrl"));
#endif
    
    //
    //    General
    //
    mImageView->setToolTip(tr("Scan area. Loaded plots\n"
                              "are displayed here."));
    if (mHelpBrowser) mHelpBrowser->setToolTip(tr("Help and Documentation for xyscan."));
    statusBar()->setToolTip(tr("Status bar. Displays instruction during scanning."));
    mCrosshairH->setToolTip(tr("Horizontal bar of crosshairs cursor."));
    mCrosshairV->setToolTip(tr("Vertical bar of crosshairs cursor."));
    mMarker[mXLower]->setToolTip(tr("Marker for lower x-axis position."));
    mMarker[mXUpper]->setToolTip(tr("Marker for upper x-axis position."));
    mMarker[mYLower]->setToolTip(tr("Marker for lower y-axis position."));
    mMarker[mYUpper]->setToolTip(tr("Marker for upper y-axis position."));
    
    //
    //   Measure tool
    //
    mMeasureItem->setToolTip(tr("Measure Tool Window:\n"
                                "Allows to measure distances in plots and maps."));
    mMeasureScaleComboBox->setToolTip(tr("Unit Selector:\n"
                                         "Select the units in which the distance is displayed.\n"));
    mMeasureUserScaleField->setToolTip(tr("User Scale:\n"
                                          "Allows to enter a scale in which the measured\n"
                                          "distances will be expressed."));
    mStartMeasureButton->setToolTip(tr("Starts and stops measuring."));
    mMeasureDXDisplay->setToolTip(tr("While measuring displays the horizontal distance."));
    mMeasureDYDisplay->setToolTip(tr("While measuring displays the vertical distance."));
    mMeasureDRDisplay->setToolTip(tr("While measuring displays the radial distance."));
    mMeasureDADisplay->setToolTip(tr("While measuring displays the angle w.r.t. the horizontal axis."));
    mMeasureAngleRadiansCheckBox->setToolTip(tr("Select angle to be displayed in radians."));
    
    //
    //   Zoom window
    //
    mZoomDock->setToolTip(tr("Cursor Zoom Window:\n"
                             "Displays a zoomed view of the are\n"
                             "surrounding the cross-hair allowing\n"
                             "for higher scan precision."));
    mZoomSpinBox->setToolTip(tr("Set the zoom scale."));
    
    //
    //   Coordinates
    //
    mCoordinatesItem->setToolTip(tr("Coordinates Window:\n"
                                    "Displays cursor position in local\n"
                                    "(pixel) and plot coordinates.\n"
                                    "Shortcut is %1+C.").arg(platformCtrl));
    mPixelXDisplay->setToolTip(tr("Displays the x coordinate of the cursor in pixel (screen) units."));
    mPixelYDisplay->setToolTip(tr("Displays the y coordinate of the cursor in pixel (screen) units."));
    mPlotXDisplay->setToolTip(tr("Displays the x coordinate of the cursor in plot units.\n"
                                 "When the point is recorded (space key) this coordinate\n"
                                 "gets stored in the data table."));
    mPlotYDisplay->setToolTip(tr("Displays the y coordinate of the cursor in plot units.\n"
                                 "When the point is recorded (space key) this coordinate\n"
                                 "gets stored in the data table."));
    
    //
    //    Axis settings
    //
    mAxisSettingsItem->setToolTip(tr("Axis Settings Window:\n"
                                     "Use to set axes marker\n"
                                     "and set log/lin scales.\n"
                                     "Shortcut is %1+A.").arg(platformCtrl));
    mSetLowerXButton->setToolTip(tr("Set marker to define the first (lower) position on the x-axis.\n"
                                    "Launches input dialog for the referring value in plot coordinates.\n"
                                    "Shortcut is %1+1.").arg(platformCtrl));
    mSetUpperXButton->setToolTip(tr("Set marker to define the second (upper) position on the x-axis.\n"
                                    "Launches input dialog for the referring value in plot coordinates.\n"
                                    "Shortcut is %1+2.").arg(platformCtrl));
    mSetLowerYButton->setToolTip(tr("Set marker to define the first (lower) position on the y-axis.\n"
                                    "Launches input dialog for the referring value in plot coordinates.\n"
                                    "Shortcut is %1+3.").arg(platformCtrl));
    mSetUpperYButton->setToolTip(tr("Set marker to define the second (upper) position on the y-axis.\n"
                                    "Launches input dialog for the referring value in plot coordinates.\n"
                                    "Shortcut is %1+4.").arg(platformCtrl));
    mUpperYValueField->setToolTip(tr("x-axis value in plot coordinates assigned to the low-x marker (read only)."));
    mLowerYValueField->setToolTip(tr("x-axis value in plot coordinates assigned to the upper-x marker (read only)."));
    mUpperXValueField->setToolTip(tr("y-axis value in plot coordinates assigned to the low-y marker (read only)."));
    mLowerXValueField->setToolTip(tr("y-axis value in plot coordinates assigned to the upper-y marker (read only)."));
    mLogXRadioButton->setToolTip(tr("Check if x-axis on plot has log scale."));
    mLogYRadioButton->setToolTip(tr("Check if y-axis on plot has log scale."));

    //
    //    Plot adjustments
    //
    mPlotAdjustmentItem->setToolTip(tr("Plot Adjustments:\n"
                                       "Window displaying info on the current plot and controls\n"
                                       "that allows to scale (zoom in/out) and rotate the plot."));
    mAngleSpinBox->setToolTip(tr("Rotate current plot (degrees)."));
    mScaleSpinBox->setToolTip(tr("Scale (zoom in/out) the current plot."));
    mPlotInfoLabel->setToolTip(tr("Show dimension and depth of current plot."));

    //
    //   Errors
    //
    mErrorScanModeItem->setToolTip(tr("Error Bar Settings:\n"
                                      "Define how to scan error bars."));
    mErrorXModeComboBox->setToolTip(tr("Defines scan mode for error bars in x."));
    mErrorYModeComboBox->setToolTip(tr("Defines scan mode for error bars in y."));
    
    //
    //    Data table
    //
    mTableDock->setToolTip(tr("Data Table Window:\n"
                              "Window displaying the data table that holds \n "
                              "all points (and error bars) scanned so far."));
    mDataTable->setToolTip(tr("Data table holding all poinst scanned so far."));
    
    //
    //   Actions (don't show on the Mac)
    //
    mOpenAction->setToolTip(tr("Open file to read in image."));
    mScreenScanAction->setToolTip(tr("Scan screen directly withour loading image.\n"
                                     "xyscan will turn semi-transparent."));
    mSaveAction->setToolTip(tr("Save the scanned data in text file."));
    mPrintAction->setToolTip(tr("Print the plot together with the scanned data."));
    mFinishAction->setToolTip(tr("Quit xyscan."));
    mDeleteLastAction->setToolTip(tr("Delete last scanned point from data table."));
    mDeleteAllAction->setToolTip(tr("Delete all scanned point from data table."));
    mEditCommentAction->setToolTip(tr("Write comment that will be added to the\n"
                                      "scanned data when saved to file."));
    mPasteImageAction->setToolTip(tr("Paste image from clipboard."));
    mClearHistoryAction->setToolTip(tr("Clear list of recently opened files."));
    mShowPrecisionAction->setToolTip(tr("Shows scan precision at current cursor point."));
    mShowTooltipsAction->setToolTip(tr("Switch on/off tool tips."));
}

void xyscanWindow::createZoomDockingWidget()
{
    //
    //  Cursor zoom window.
    //  Made as a docking widget for convinience
    //  but make non-dockable.
    //
    mZoomDock = new QDockWidget(tr("Cursor Zoom"), this);
    mZoomDock->setVisible(false);
    mZoomDock->setAllowedAreas(Qt::NoDockWidgetArea);
    
    mZoomView = new QGraphicsView(mImageScene, mZoomDock);
    mZoomDock->setWidget(mZoomView);

    addDockWidget(Qt::TopDockWidgetArea, mZoomDock); // widget area is only a dummy here
    mZoomDock->toggleViewAction()->setText(tr("&Cursor Zoom"));
    mZoomDock->toggleViewAction()->setShortcut(Qt::CTRL + Qt::Key_Y);
    
    mViewMenu->addAction(mZoomDock->toggleViewAction());
    mZoomDock->setFloating(true);
    mZoomDock->resize(200,200);
    
    mZoomScale = 8;
    mZoomView->scale(mZoomScale,mZoomScale);

    mZoomSpinBox = new QDoubleSpinBox(mZoomView);
    mZoomSpinBox->setDecimals(1);
    mZoomSpinBox->setMinimum(1);
    mZoomSpinBox->setSingleStep(0.5);
    mZoomSpinBox->setValue(mZoomScale);
   
    connect(mZoomSpinBox, SIGNAL(valueChanged(double)), this, SLOT(zoomScale(double)));
}

void xyscanWindow::editComment()
{
    bool ok;
    QString txt = QInputDialog::getText(this, tr("xyscan - Comment"),
                                        tr("The following comment will be written "
                                           "together with the data when saved to file or when printed:\t"), 
                                        QLineEdit::Normal, mDataTable->userComment(), &ok);
    if (ok) mDataTable->setUserComment(txt);
}

void xyscanWindow::editCrosshairColor()
{
    QColor newColor = QColorDialog::getColor (mCrosshairColor, this, tr("Crosshair Color")); // title doesn't show on macOS
    if (newColor.isValid()) 
        mCrosshairColor = newColor;
    mCrosshairV->setPen(QPen(mCrosshairColor));
    mCrosshairH->setPen(QPen(mCrosshairColor));
}

void xyscanWindow::editMarkerColor()
{
    QColor newColor = QColorDialog::getColor (mMarkerColor, this, tr("Marker Color"));
    if (!newColor.isValid()) return;
    
    mMarkerColor = newColor;
    mMeasureLine->setPen(QPen(mMarkerColor));
    QImage imgpm(marker_cross_xpm);
    int index = imgpm.color(0) == 0 ? 1 : 0;
    imgpm.setColor(index, mMarkerColor.rgb());
    QPixmap newpix = QPixmap::fromImage(imgpm);
    mPointMarker->setPixmap(newpix);
}

void xyscanWindow::enableScreenScan(bool val)
{
    //
    //  If true load an empty (dummy) pixmap to trigger the initialization
    //  that is happening in loadPixmap(). We also need to disable the
    //  zoom window since it's view is tied to the scene in the window
    //  (the loaded pixmap) and not the screen behind the xyscan window.
    //  The xyscan window will turn transparent with an opacity of 70%.
    //
    
    if (val && !checkForUnsavedData()) {
        mScreenScanAction->setChecked(false);
        return;
    }
    
    if (val) {
        QPixmap *pm = new QPixmap(":images/empty.png");
        mCurrentSource = QString("Screen Scan");
        loadPixmap(pm);
        statusBar()->showMessage(tr("Ready for screen scan. No markers set."));
    }
    else {
        if (mCurrentSource == QString("Screen Scan")) {   // no new image loaded, onlt screen scan off
            mCurrentSource = QString();
            statusBar()->showMessage(tr("Ready"));
        }
        setWindowTitle("xyscan");
    }
    
    setWindowOpacity(val ? 0.7 : 1);
    if (mZoomDock->isVisible()) mZoomDock->setHidden(val);
    mZoomDock->toggleViewAction()->setDisabled(val);
    
    mScreenScanIsOn = val;
}

void xyscanWindow::enableMeasuring(bool state)
{
    //
    //  Switches measuring process on/off
    //
    
    mMeasuringIsOn = state;
    
    if (state) {
        mStartMeasureButton->setText(tr("Stop Measuring"));
        
        QPointF pos(mCrosshairH->pos().x(), mCrosshairV->pos().y());
        pos -= QPointF(mPointMarker->pixmap().width()/2+mPointMarkerOffset, mPointMarker->pixmap().height()/2+mPointMarkerOffset);
        mPointMarker->setPos(pos);
        mPointMarker->show();
        mMeasureLine->show();
        
        updateMeasureDisplay();
        
        //
        //  Typicall this method is called when the
        //  mStartMeasureButton is pressed. However,
        //  we might need to start and stop measuring
        //  by directly calling this method from other
        //  places, hence we have to make sure the button
        //  is in the right state.
        //
        if (!mStartMeasureButton->isChecked()) mStartMeasureButton->setChecked(true);
        
        statusBar()->showMessage(tr("Measuring tool is on."));
    }
    else {
        mStartMeasureButton->setText(tr("Start Measuring"));
        mPointMarker->hide();
        mMeasureLine->hide();
        if (mStartMeasureButton->isChecked()) mStartMeasureButton->setChecked(false);
        statusBar()->showMessage(tr("Ready"));
    }
}

void xyscanWindow::ensureCursorVisible()
{
    QRectF rect(mCrosshairH->pos().x()-25, mCrosshairV->pos().y()-25, 50, 50);
    mImageView->ensureVisible(rect);
}

bool xyscanWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (!event) return false;
    
    //
    //  First we see if this is an FileOpen event passed
    //  along from the application. On the Mac this means
    //  the user opened an image file from the finder. 
    //
    if (obj == qApp) {
        if (event->type() == QEvent::FileOpen) {
            QFileOpenEvent* fileOpenEvent = dynamic_cast<QFileOpenEvent*>(event);
            if (fileOpenEvent) {
                if (!checkForUnsavedData()) return false;
                QString fname = fileOpenEvent->file();
                if(fname.isEmpty()) return false;
                this->openFromFile(fname);
                return true;    // handled it
            }
            else
                return false;
        }
        else
            return false;
    }

    //
    //  If Tool Tips are not wanted we filter
    //  them out here.
    if (event->type() == QEvent::ToolTip &&
        !mShowTooltipsAction->isChecked()) return true;

    //
    // If method retuns true, the event stops here otherwise its
    // passed down. Here we catch all dispatched events from the
    // image scene (canvas). 
    // 
    static bool leftMousePressedNearCrosshair = false;
    QGraphicsSceneMouseEvent *mevt;
    
    if (obj == mImageScene) {
        
        if (event->type() == QEvent::KeyPress) {
            handleKeyEvent(dynamic_cast<QKeyEvent*>(event));  // to complex to handle here
            return true;
        } 
        else if (event->type() == QEvent::GraphicsSceneMousePress) {
            mevt = dynamic_cast<QGraphicsSceneMouseEvent*>(event);  
            update();
            QPointF mpos = mevt->scenePos();
            QPointF cpos(mCrosshairH->pos().x(), mCrosshairV->pos().y());
            double d = (mpos.x()-cpos.x())*(mpos.x()-cpos.x())
                + (mpos.y()-cpos.y())*(mpos.y()-cpos.y());
            if (d < 50) leftMousePressedNearCrosshair = true;
            return true;
        }
        else if (event->type() == QEvent::GraphicsSceneMouseRelease) {
            leftMousePressedNearCrosshair = false;
            return true;
        }        
        else if ( (event->type() == QEvent::GraphicsSceneMouseMove && leftMousePressedNearCrosshair ) || event->type() == QEvent::GraphicsSceneMouseDoubleClick) {
            mevt = dynamic_cast<QGraphicsSceneMouseEvent*>(event);    
            //
            //  In principle straighforward except for the case
            //  where we scan for errors (x, y or both) and one
            //  line is hidden. The idea is that for an x-error scan
            //  mCrosshairH is hidden and stays at const y and
            //  for an y error scan mCrosshairV is hidden and stays
            //  at const x. So when lines are hidden (which is
            //  only the case during the error scan) we have to keep
            //  one coordinate const.
            //
            if (mCrosshairH->isVisible() && mCrosshairV->isVisible()) {
                mCrosshairH->setPos(mevt->scenePos());
                mCrosshairV->setPos(mevt->scenePos());
            }
            else if (mCrosshairH->isVisible() && !mCrosshairV->isVisible()) {
                QPointF pos = QPointF(mCrosshairV->pos().x(), mevt->scenePos().y());
                mCrosshairV->setPos(pos);
                mCrosshairH->setPos(pos);
            }
            else if (!mCrosshairH->isVisible() && mCrosshairV->isVisible()) {
                QPointF pos(mevt->scenePos().x(), mCrosshairH->pos().y());
                mCrosshairH->setPos(pos);
                mCrosshairV->setPos(pos);
            }
            
            //
            //  Handle the measurement tool
            //
            if (mMeasuringIsOn) {
                if (event->type() == QEvent::GraphicsSceneMouseDoubleClick)
                    enableMeasuring(true);
                else
                    updateMeasureDisplay();
            }
            
            //
            //  Update all displays and fields impacted
            //
            updatePixelDisplay();
            updatePlotCoordinateDisplay();
            ensureCursorVisible();
            updateZoomDisplay();
            return true;
        }
        else {
            return false;
        }
    }
    return QObject::eventFilter(obj, event);  // standard event processing
}

void xyscanWindow::finish() 
{
    //
    //  Gracefully end xyscan. 
    //  Check for unsaved data and write settings/preferences.
    //
    if (!checkForUnsavedData()) return;
    writeSettings();
    QApplication::exit(0);
}

void xyscanWindow::handleKeyEvent(QKeyEvent* k)
{
    //
    //  This is where most of the action happens.
    //  Since the logic is really mind-blowing,
    //  especially for the x and y-error scan
    //  a state machine is used which determines
    //  what is allowed at which point.
    //
    static QPointF originalHPosition;
    static QPointF originalVPosition;
    static QPointF xy(0,0);
    static QPointF errorX(0,0);
    static QPointF errorY(0,0);
    QPointF point;
    
    static bool previousShiftPressed = false;
    static bool previousAltPressed = false;
    static int  previousKey  = 0;
    bool shiftPressed = false;
    bool altPressed = false;
    int  key = 0;
    
    //
    //  There's a slight problem in Qt when Shift+arrow
    //  or Alt-arrow is pressed continuously: the Shift/Alt
    //  key gets lost.
    //  We repair that by checking for 'AutoRepeat' and
    //  remembering the Shift/Alt key state before 'AutoRepeat'
    //  was signaled.
    //
    if (k->isAutoRepeat() && !(k->key() == Qt::Key_Space)) {
        shiftPressed = previousShiftPressed;
        altPressed = previousAltPressed;
        key = previousKey;
    }
    else {
        shiftPressed = k->modifiers() & Qt::ShiftModifier;
        altPressed = k->modifiers() & Qt::AltModifier;
        key = k->key();
    }
    previousShiftPressed = shiftPressed;
    previousAltPressed = altPressed;
    previousKey = key;
    
    double dx_fine = 0.1;   // very fine move (alt+arrow)
    double dy_fine = 0.1;
    double dx_step = 1;     // simple move (arrow)
    double dy_step = 1;
    double dx_jump = 10;    // fast (shift+arrow)
    double dy_jump = 10;
    
    double dx, dy;
    if (shiftPressed) {
        dx = dx_jump;
        dy = dy_jump;
    }
    else if (altPressed) {
        dx = dx_fine;
        dy = dy_fine;
    }
    else {
        dx = dx_step;
        dy = dy_step;
    }

    //  Pass settings (x-, y-error scan) to the state machine.
    mStateMachine.setScanErrorXSelected(mErrorXModeComboBox->currentIndex());
    mStateMachine.setScanErrorYSelected(mErrorYModeComboBox->currentIndex());
    
    switch(key) {
        case Qt::Key_Left:
            if (mCrosshairV && mStateMachine.allowKeyLeft()) {
                mCrosshairV->setPos(mCrosshairV->pos() + QPointF(-dx, 0));
                mCrosshairH->setPos(mCrosshairH->pos() + QPointF(-dx, 0));
            }
            break;
        case Qt::Key_Right:
            if (mCrosshairV && mStateMachine.allowKeyRight()) {
                mCrosshairV->setPos(mCrosshairV->pos() + QPointF(dx, 0));
                mCrosshairH->setPos(mCrosshairH->pos() + QPointF(dx, 0));
            }
            break;
        case Qt::Key_Up:
            if (mCrosshairH && mStateMachine.allowKeyUp()) {
                mCrosshairV->setPos(mCrosshairV->pos() + QPointF(0, -dy));
                mCrosshairH->setPos(mCrosshairH->pos() + QPointF(0, -dy));
            }
            break;
        case Qt::Key_Down:
            if (mCrosshairH && mStateMachine.allowKeyDown()) {
                mCrosshairV->setPos(mCrosshairV->pos() + QPointF(0, dy));
                mCrosshairH->setPos(mCrosshairH->pos() + QPointF(0, dy));
            }
            break;
        case Qt::Key_Space:
            if (readyForScan()) {
                mSoundEffect.play();   // sound to indicate succesfull scan
                if (mMeasuringIsOn) enableMeasuring(false);
                if (mStateMachine.allowXYScan()) {
                    xy = scan();
                    updatePixelDisplay();
                    updatePlotCoordinateDisplay();
                    updateZoomDisplay();
                    originalHPosition  = mCrosshairH->pos(); // later we return to this point after errors are scanned
                    originalVPosition  = mCrosshairV->pos();
                    mStateMachine.setXYScanDone(true);
                }
                
                if (mStateMachine.disableSettingsMenu()) {
                    mSetLowerXButton->setDisabled(true);
                    mSetUpperXButton->setDisabled(true);
                    mSetLowerYButton->setDisabled(true);
                    mSetUpperYButton->setDisabled(true);                
                    mErrorXModeComboBox->setDisabled(true);
                    mErrorYModeComboBox->setDisabled(true);
                    mLogXRadioButton->setDisabled(true);
                    mLogYRadioButton->setDisabled(true);
                }
                
                if (mStateMachine.doPrepareErrorXScan()) {
                    mCrosshairH->hide();
                    //
                    //  Set a marker (cross) where the original point was.
                    //  This helps remembering the point in case there are
                    //  many close by points. Removed once the errors are
                    //  all scanned.
                    //
                    QPointF pos(originalVPosition.x(), originalHPosition.y());
                    pos -= QPointF(mPointMarker->pixmap().width()/2+mPointMarkerOffset, mPointMarker->pixmap().height()/2+mPointMarkerOffset);
                    mPointMarker->setPos(pos);
                    mPointMarker->show();
                    
                    statusBar()->showMessage(tr("Scan x-error (-dx): move crosshair to end of left error bar and press [space]."));
                    mStateMachine.setErrorXScanPrepared(true);
                    break;
                }
                
                if (mStateMachine.allowScanXLeft()) {
                    point = scan();
                    void updatePixelDisplay();
                    void updatePlotCoordinateDisplay();
                    updateZoomDisplay();
                    errorX.setX(point.x() - xy.x());
                    statusBar()->showMessage(tr("Scan x-error (+dx): move crosshair to end of right error bar and press [space]."));
                    mStateMachine.setScanXLeftDone(true);
                    break;
                }
                
                if (mStateMachine.allowScanXRight()) {
                    point = scan();
                    void updatePixelDisplay();
                    void updatePlotCoordinateDisplay();
                    updateZoomDisplay();
                    errorX.setY(point.x() - xy.x());
                    point = errorX;
                    if (point.x() < 0) {
                        errorX.setX(fabs(point.x()));
                        errorX.setY(point.y());
                    }
                    else {
                        errorX.setX(fabs(point.y()));
                        errorX.setY(point.x());
                    }
                    mStateMachine.setScanXRightDone(true);
                }
                
                if (mStateMachine.removeErrorXScanSetup()) {
                    mPointMarker->hide();
                    mCrosshairH->show();
                    mCrosshairH->setPos(originalHPosition);
                    mCrosshairV->setPos(originalVPosition);
                    point = scan();
                    updatePixelDisplay();
                    updatePlotCoordinateDisplay();
                    updateZoomDisplay();
                    mStateMachine.setErrorXScanSetupRemoved(true);
                }                
                
                if (mStateMachine.allowScanYLower()) {
                    point = scan();
                    updatePixelDisplay();
                    updatePlotCoordinateDisplay();
                    updateZoomDisplay();
                    errorY.setX(point.y() - xy.y());
                    statusBar()->showMessage(tr("Scan y-error (+dy): move crosshair to end of upper error bar and press [space]."));
                    mStateMachine.setScanYLowerDone(true);
                    break;
                }
                
                if (mStateMachine.allowScanYUpper()) {
                    point = scan();
                    updatePixelDisplay();
                    updatePlotCoordinateDisplay();
                    updateZoomDisplay();
                    errorY.setY(point.y() - xy.y());
                    point = errorY;
                    if (point.x() < 0) {
                        errorY.setX(fabs(point.x()));
                        errorY.setY(point.y());
                    }
                    else {
                        errorY.setX(fabs(point.y()));
                        errorY.setY(point.x());
                    }
                    mStateMachine.setScanYUpperDone(true);
                }
                
                if (mStateMachine.doPrepareErrorYScan()) {
                    mCrosshairV->hide();
                    //
                    //  Set a marker (cross) where the original point was.
                    //  This helps remembering the point in case there are
                    //  many close by points. Removed once the errors are
                    //  all scanned.
                    //
                    QPointF pos(originalVPosition.x(), originalHPosition.y());
                    pos -= QPointF(mPointMarker->pixmap().width()/2+mPointMarkerOffset,
                                   mPointMarker->pixmap().height()/2+mPointMarkerOffset);
                    mPointMarker->setPos(pos);
                    mPointMarker->show();
                    
                    statusBar()->showMessage(tr("Scan y-error (-dy): "
                                                "move crosshair to end of lower "
                                                "error bar and press [space]."));
                    mStateMachine.setErrorYScanPrepared(true);
                    break;
                }
                
                if (mStateMachine.removeErrorYScanSetup()) {
                    mPointMarker->hide();
                    mCrosshairV->show();
                    mCrosshairV->setPos(originalVPosition);
                    mCrosshairH->setPos(originalHPosition);
                    point = scan();
                    updatePixelDisplay();
                    updatePlotCoordinateDisplay();
                    updateZoomDisplay();
                    mStateMachine.setErrorYScanSetupRemoved(true);
                }
                
                if (mStateMachine.enableSettingsMenu()) {
                    mSetLowerXButton->setDisabled(false);
                    mSetUpperXButton->setDisabled(false);
                    mSetLowerYButton->setDisabled(false);
                    mSetUpperYButton->setDisabled(false);                
                    mErrorXModeComboBox->setDisabled(false);
                    mErrorYModeComboBox->setDisabled(false);
                    mLogXRadioButton->setDisabled(false);
                    mLogYRadioButton->setDisabled(false);
                }
                
                //
                //  Calculate the x,y errors according to the selected mode
                //  and fill data into table.
                //

                double firstY = fabs(errorY.x());
                double secondY = fabs(errorY.y());
                double firstX = fabs(errorX.x());
                double secondX = fabs(errorX.y());
                if (mErrorXModeComboBox->currentIndex() == mMax) {    // max(lower, upper)
                    firstX = firstX > secondX ? firstX : secondX;
                    secondX = firstX;
                }
                else if (mErrorXModeComboBox->currentIndex() == mAverage) {  // avg(lower, upper)
                    firstX = (firstX+secondX)/2;
                    secondX = firstX;
                }
                if (mErrorYModeComboBox->currentIndex() == mMax) {
                    firstY = firstY > secondY ? firstY : secondY;
                    secondY = firstY;
                }
                else if (mErrorYModeComboBox->currentIndex() == mAverage) {
                    firstY = (firstY+secondY)/2;
                    secondY = firstY;
                }
                
                if (mStateMachine.allowWriteXY()) {
                    addToTable(xy.x(), xy.y(), 0, 0, 0, 0);
                    statusBar()->showMessage(tr("Data point stored."));
                    mStateMachine.setDataWritten(true);
                }
                else if (mStateMachine.allowWriteXYErrorY()) {
                    addToTable(xy.x(), xy.y(), 0, 0, firstY, secondY);
                    statusBar()->showMessage(tr("Data point and y-error stored."));
                    mStateMachine.setDataWritten(true);
                }
                else if (mStateMachine.allowWriteXYErrorX()) {
                    addToTable(xy.x(), xy.y(), firstX, secondX, 0, 0);
                    statusBar()->showMessage(tr("Data point and x-error stored."));
                    mStateMachine.setDataWritten(true);
                }
                else if (mStateMachine.allowWriteXYErrorXErrorY()) {
                    addToTable(xy.x(), xy.y(), firstX, secondX, firstY, secondY);
                    statusBar()->showMessage(tr("Data point, x- and y-errors stored."));
                    mStateMachine.setDataWritten(true);
                }
             }
            else {
                QMessageBox::information(0, "xyscan",
                                         tr("Cannot scan yet. Not sufficient information available to perform "
                                            "the coordinate transformation. You need to define 2 points on the "
                                            "x-axis (x1 & x1) and 2 on the y-axis (y1 & y2)."));
            }
            break;
        default:
            k->ignore();
            break;
    }
    
    //
    //  Update coordinate display if an arrow key was pressed 
    // 
    if (key == Qt::Key_Left || key == Qt::Key_Right || key == Qt::Key_Up || key == Qt::Key_Down) {
        if (mMeasuringIsOn) updateMeasureDisplay();
        updatePixelDisplay();
        updatePlotCoordinateDisplay();
        ensureCursorVisible();
        updateZoomDisplay();
    }
}

void xyscanWindow::help() 
{
    if (mHelpBrowser) {
        mHelpBrowser->show();
        mHelpBrowser->raise();
    }
    else
        QMessageBox::warning( 0, "xyscan",
                              tr("Sorry no help available.\n"
                              "Help files are missing in this installation. "
                              "Check your installation and reinstall if necessary."));    
}

void xyscanWindow::loadDroppedFile(QString filename)
{
    if (!checkForUnsavedData()) return;
    openFromFile(filename);
}

void xyscanWindow::loadPixmap(QPixmap* pixmap)
{
    //
    //  All pixmaps/images displayed in xyscan go through here
    //  no matter how they were loaded.
    //
    QApplication::setOverrideCursor(Qt::WaitCursor);
    if (mCurrentPixmap) delete mCurrentPixmap;
    
    //
    //  If Screen scan is on, switch it off
    //
    if (mScreenScanIsOn) {
        enableScreenScan(false);
        mScreenScanAction->setChecked(false);
    }

    //
    //  If Measure tool is on, switch it off
    //
    if (mMeasuringIsOn) enableMeasuring(false);
    
    //
    //  Add pixmap to scene with lowest z to not
    //  obscure cursors and lines.
    //
    mImageAngle = 0;
    mImageScale = 1;
    mCurrentPixmap = mImageScene->addPixmap(*pixmap);
    mCurrentPixmap->setZValue(0);
    mImageScene->setSceneRect(0, 0, pixmap->width(), pixmap->height());
    update();
    
    //
    //  Not bigger than the desktop
    //
    if (QApplication::desktop()->width() > width() + 50 &&
        QApplication::desktop()->height() > height() + 50)
        show();
    else
        showMaximized();
    
    //
    //  Show crosshair and position
    //
    mCrosshairV->setVisible(true);
    mCrosshairH->setVisible(true);
    mCrosshairH->setPos(pixmap->width()/2,pixmap->height()/2);
    mCrosshairV->setPos(pixmap->width()/2,pixmap->height()/2);
    updatePixelDisplay();
    updatePlotCoordinateDisplay(); // sets display to N/A if not ready
    updateZoomDisplay();
   
    //
    //  No markers shown yet
    //
    resetMarker();
    
    //
    //  Remove all traces of the previous scan
    //
    mDataTable->setUserComment("");
    mAngleSpinBox->setValue(mImageAngle);
    mScaleSpinBox->setValue(mImageScale);
    mDataTable->deleteAll();        // clear table
   
    //
    //  Enable all buttons that make sense to use
    //  once the image is loaded (or not).
    //
    mSetLowerXButton->setDisabled(false);
    mSetUpperXButton->setDisabled(false);
    mSetLowerYButton->setDisabled(false);
    mSetUpperYButton->setDisabled(false);
    mLogXRadioButton->setDisabled(false);
    mLogYRadioButton->setDisabled(false);    
    mErrorXModeComboBox->setDisabled(false);
    mErrorYModeComboBox->setDisabled(false);
    mEditCommentAction->setDisabled(false);
    mEditCrosshairColorAction->setDisabled(false);
    mEditMarkerColorAction->setDisabled(false);
    mShowPrecisionAction->setDisabled(false);
    mAngleSpinBox->setDisabled(false);    
    mScaleSpinBox->setDisabled(false);   
    mPrintAction->setDisabled(true);
    mStartMeasureButton->setDisabled(false);
    mMeasureScaleComboBox->setCurrentIndex(mPixelUnits);
    //
    //  When plot is loaded pixels and user units should be allowed
    //  but not plot coordinates that requure all markers to be set
    //
    mMeasureScaleComboBox->setDisabled(false);
    auto model = dynamic_cast<QStandardItemModel*>(mMeasureScaleComboBox->model());
    auto item = model->item(mPlotUnits, 0);
    item->setEnabled(false);

    statusBar()->showMessage(tr("Image loaded, no markers set."));

    //
    //  Add info to Plot Adjustement window
    //
    QString txt = tr("<html><table border=\"0\">" 
                     "<tr><td>Info:"
                     "<tr><td align=\"right\">&nbsp;Dimensions:&nbsp;<td>%1x%2"
                     "<tr><td align=\"right\">&nbsp;Depth:&nbsp;<td>%3 bit"
                     "<tr><td align=\"right\">&nbsp;Alpha channel:&nbsp;<td>%4</table></html>")
    .arg(pixmap->width()).arg(pixmap->height()).arg(pixmap->depth()).arg(pixmap->hasAlphaChannel() ? tr("Yes"):tr("No"));
    mPlotInfoLabel->setText(txt);
    
    QApplication::restoreOverrideCursor();
    
    //
    //  Resize main window to fit pixmap 
    //  but not exceed screen size.
    //
    const int offset = 10;
    QSize offsetSize(10,10);  // small offset
    QSize mainSize = size();
    QSize viewSize = mImageView->size();
    QSize pixSize  = pixmap->size();
    QSize deltaSize = pixSize-viewSize;
    
    QSize newSize = mainSize+deltaSize+offsetSize;
    
    QRect maxRect = QGuiApplication::primaryScreen()->availableGeometry();
    maxRect.setWidth(maxRect.width()-5*offset);
    maxRect.setHeight(maxRect.height()-5*offset);
    
    if (newSize.width() > maxRect.width()) newSize.setWidth(maxRect.width());
    if (newSize.height() > maxRect.height()) newSize.setHeight(maxRect.height());

    resize(newSize);
    
    QString newTitle("xyscan - ");
    QString fname = mCurrentSource;
    int i = fname.lastIndexOf('/');
    fname.remove(0, i+1);
    newTitle += fname;
    setWindowTitle(newTitle);
    
    update();
}

void xyscanWindow::loadSettings()
{
    QSettings settings(QSettings::NativeFormat, QSettings::UserScope, "tu", "xyscan");
    move(settings.value("xyscan/position", QPoint(75, 45)).toPoint());
    bool toolTips = settings.value("xyscan/showToolTips", true).toBool();
    mShowTooltipsAction->setChecked(toolTips);
    mOpenFileDirectory = settings.value("xyscan/lastOpenFileDirectory", QDir::homePath()).toString();
    mSaveFileDirectory = settings.value("xyscan/lastSaveFileDirectory", QDir::homePath()).toString();
    mRecentFiles = settings.value("xyscan/recentFiles").toStringList();
    
    while (mRecentFiles.size() > mMaxRecentFiles)
        mRecentFiles.removeLast();
    for (int i = 0; i < mRecentFiles.size(); ++i) {
        QString text = tr("&%1  %2").arg(i + 1).arg(QFileInfo(mRecentFiles[i]).fileName());
        mRecentFileAction[i]->setText(text);
        mRecentFileAction[i]->setData(mRecentFiles[i]);
        mRecentFileAction[i]->setVisible(true);
    }
    for (int j = mRecentFiles.size(); j < mMaxRecentFiles; ++j)
        mRecentFileAction[j]->setVisible(false);

    if (mRecentFiles.size()) mClearHistoryAction->setDisabled(false);
    
    //
    //   Crosshair and marker colors
    //
    QVariant var = settings.value("xyscan/crosshairColor", mCrosshairColor);
    QColor theColor = var.value<QColor>();
    if (theColor.isValid()) mCrosshairColor = theColor;
    mCrosshairV->setPen(QPen(mCrosshairColor));
    mCrosshairH->setPen(QPen(mCrosshairColor));

    var = settings.value("xyscan/markerColor", mMarkerColor);
    theColor = var.value<QColor>();
    if (theColor.isValid()) mMarkerColor = theColor;
    mMeasureLine->setPen(QPen(mMarkerColor));
    QImage imgpm(marker_cross_xpm);
    int index = imgpm.color(0) == 0 ? 1 : 0;
    imgpm.setColor(index, mMarkerColor.rgb());
    QPixmap newpix = QPixmap::fromImage(imgpm);
    mPointMarker->setPixmap(newpix);

    //
    //  Set default far enough in the past so it triggers an initial check
    //
    QDateTime defaultDateTime = QDateTime::currentDateTime();
    mLastReminderTime = settings.value("xyscan/lastReminderTime",
                                       defaultDateTime.addDays(-10)).toDateTime();
}

void xyscanWindow::normalizeUserScale()
{
    if (!mMeasuringIsOn) return;
    
    bool ok;
    double a = mMeasureUserScaleField->text().toDouble(&ok);
    if (!ok || a < 0) return;
    double b = mMeasureDRDisplay->text().toDouble(&ok);
    if (!ok) return;
    QString str;
    str.setNum(a*a/b); // dx, dy, or dr were already scaled by a hence a^2
    mMeasureUserScaleField->setText(str);
    updateMeasureDisplay();
}

int  xyscanWindow::numberOfMarkersSet()
{
    int n = 0;
    for (int i=0; i<4; i++)
        if (mMarker[i]->isVisible()) n++;
    return n;
}

void xyscanWindow::open() 
{
    if (!checkForUnsavedData()) return;
    
    //
    //  We get here when the user uses the open action
    //  in the file menu.
    //  Check which image formats are supported and use
    //  them as filters for the file dialog.
    //  Here we add pdf as valid format, which we handle
    //  separatly using the poppler library.
    //
    QString formats(tr("Images ("));
    QList<QByteArray> imgFormats = QImageReader::supportedImageFormats();
    imgFormats.append("pdf");
    for (int i=0; i< imgFormats.size() ; i++) {
        formats += tr("*.%1").arg(QString(imgFormats[i]));
        if (i < imgFormats.size()-1) formats += tr(" ");
    }
    formats += tr(")");
    
    QString filename = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                    mOpenFileDirectory,
                                                    formats);   
    if (filename.isEmpty()) return;
    
    openFromFile(filename);
}

void xyscanWindow::openFromFile(const QString& filename)
{
    //
    //  All pixmap/images associated to a file are loaded
    //  are handled here. For images pasted from the clipboard
    //  see pasteImage().
    //

    mOpenFileDirectory = filename;
    mOpenFileDirectory.truncate(mOpenFileDirectory.lastIndexOf('/'));
        
    if (!QFile::exists(filename)) {
        QMessageBox::warning(0, "xyscan", tr("File '%1' does not exist.").arg(filename));
        return;
    }
    
    QMimeDatabase mimeDb;
    QMimeType mtype = mimeDb.mimeTypeForFile(filename);
    bool isPdf = mtype.name() == QString("application/pdf");
    
    //
    //  Create the pixel map of the plot.
    //  PDF plots are rastered by poppler.
    //
    QPixmap	*pixmap = 0;
    if (isPdf) {
#if defined(Q_OS_WIN)
		QMessageBox::warning(0, "xyscan", tr("On Windows pdf files are currently not supported. Please convert the file into one of the supported pixel formats and try again."));
		return;
#else
        Poppler::Document* document = Poppler::Document::load(filename);
        if (!document || document->isLocked()) {
            QMessageBox::warning(0, "xyscan", tr("Cannot load PDF file '%1'.").arg(filename));
            delete document;
            return;
        }
        Poppler::Page* pdfPage = document->page(0);  // Document starts at page 0
        if (pdfPage == 0) {
            QMessageBox::warning(0, "xyscan", tr("Failed to extract page from PDF file '%1'.").arg(filename));
            return;
        }
        //
        //  Generate a QImage of the rendered page.
        //  Get dpi from user (default = 300).
        //
        bool ok;
        int dpi = QInputDialog::getInt(this, tr("Raster Precision"),
                                       tr("PDF needs to be rastered to be displayed.\nEnter pixel/inch:"),
                                       300, 72, 2400, 1, &ok, Qt::Sheet);
        if (!ok) return;
        QImage image = pdfPage->renderToImage(dpi, dpi);
        if (image.isNull()) {
            QMessageBox::warning(0, "xyscan", tr("Error rendering PDF file '%1'.").arg(filename));
            return;
        }
        pixmap = new QPixmap(QPixmap::fromImage(image));
        delete pdfPage;
#endif
    }
    else
        pixmap = new QPixmap(filename);
   
    if (pixmap->isNull()) {
        QMessageBox::warning(0, "xyscan", tr("Cannot load image from file '%1'. "
                                             "Either the file content is damaged or the "
                                             "image file format is not supported.").arg(filename));
        return;
    }
    
    //
    //  Store the file in the recent file list
    //  and enable the referring actions in the
    //  File submenu (Open Recent).
    //
    mClearHistoryAction->setDisabled(false);
    mRecentFiles.removeAll(filename);
    mRecentFiles.prepend(filename);
    while (mRecentFiles.size() > mMaxRecentFiles)
        mRecentFiles.removeLast();

    for (int i = 0; i < mRecentFiles.size(); ++i) {
        QString text = tr("&%1  %2").arg(i + 1).arg(QFileInfo(mRecentFiles[i]).fileName());
        mRecentFileAction[i]->setText(text);
        mRecentFileAction[i]->setData(mRecentFiles[i]);
        mRecentFileAction[i]->setVisible(true);
    }
    for (int j = mRecentFiles.size(); j < mMaxRecentFiles; ++j)
        mRecentFileAction[j]->setVisible(false);

    mCurrentSource = filename;

    loadPixmap(pixmap);
}


void xyscanWindow::openRecent() 
{
    if (!checkForUnsavedData()) return;
    QAction *action = qobject_cast<QAction *>(sender());
    if (action) {
        QString filename = action->data().toString();
        openFromFile(filename);
    }
}

void xyscanWindow::pasteImage()
{
    //
    //  Broken in Qt 5.0.1 on Mac
    //  Wait for next version/release
    //
    
    QPixmap *pixmap = 0;
    
    const QClipboard *clipboard = QApplication::clipboard();
    const QMimeData *mimeData = clipboard->mimeData();
        
    if (mimeData->hasImage()) {
        QImage image = qvariant_cast<QImage>(mimeData->imageData());
        pixmap = new QPixmap(QPixmap::fromImage(image));
    }
    
    if (!pixmap || pixmap->isNull()) {
        QMessageBox::warning(0, "xyscan", tr("Cannot load image from clipboard.\n"
                                             "Either the clipboard does not contain an "
                                             "image or it contains an image in an "
                                             "unsupported image format."));
        return;
    }
    
    mCurrentSource = "Clipboard";
    
    loadPixmap(pixmap);
}

void xyscanWindow::print()
{
    //
    //  Create document for printing.
    //  xyscanDataTable does all the formatting and writing.
    //
    QTextDocument document;
    QImage original;
    if (mCurrentSource == QString("Screen Scan")) {
        mDataTable->writePrinterDocument(document, mCurrentSource);  // no image
    }
    else {
        original = mCurrentPixmap->pixmap().toImage();
        mDataTable->writePrinterDocument(document, mCurrentSource, &original);
    }
    
    //
    //  Start printer dialog and print the document we just created
    //
    QPrinter printer(QPrinter::HighResolution);
    QPrintDialog *dlg = new QPrintDialog(&printer, this);
    dlg->setWindowTitle(tr("xyscan - Print"));
    if (dlg->exec() != QDialog::Accepted) return;
    document.print(&printer);

    statusBar()->showMessage(tr("Ready"));
}

bool xyscanWindow::readyForScan()
{
    bool OK;
    bool allMarkers = (numberOfMarkersSet() == 4);
    bool allAxisValues = true;
    mLowerXValueField->text().toDouble(&OK); if (!OK) allAxisValues = false;
    mUpperXValueField->text().toDouble(&OK); if (!OK) allAxisValues = false;
    mLowerYValueField->text().toDouble(&OK); if (!OK) allAxisValues = false;
    mUpperYValueField->text().toDouble(&OK); if (!OK) allAxisValues = false;
    if (allMarkers && allAxisValues)
        return true;
    else
        return false;
}

void xyscanWindow::resetMarker()
{
    mMarker[mXLower]->setVisible(false);    
    mMarker[mXUpper]->setVisible(false);    
    mMarker[mYLower]->setVisible(false);    
    mMarker[mYUpper]->setVisible(false);    
    mLowerXValueField->setText(tr("undefined"));
    mUpperXValueField->setText(tr("undefined"));
    mLowerYValueField->setText(tr("undefined"));
    mUpperYValueField->setText(tr("undefined"));

    mAngleSpinBox->setDisabled(false);    
    mScaleSpinBox->setDisabled(false);    
}

void xyscanWindow::rotateImage(double d)
{
    QSize s = mCurrentPixmap->pixmap().size();
    double x = s.width()/2;
    double y = s.height()/2;
    if (mCurrentPixmap) {
        // rotate around center
        mCurrentPixmap->setTransform(QTransform().translate(x, y).scale(mImageScale, mImageScale).rotate(-d).translate(-x, -y));
        mImageAngle = -d;
        QRectF rectf = mCurrentPixmap->sceneBoundingRect();
        mImageScene->setSceneRect(rectf);
        update();
    }
}

void xyscanWindow::save()
{
    QString fileName =  QFileDialog::getSaveFileName(this, tr("Save File"),
                                                    mSaveFileDirectory+QString("/xyscan.txt"));
    if (fileName.isEmpty()) return;
    
    mSaveFileDirectory = fileName;
    mSaveFileDirectory.truncate(mSaveFileDirectory.lastIndexOf('/'));
    
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, "xyscan",
                             tr("Cannot write file %1:\n%2.")
                             .arg(fileName)
                             .arg(file.errorString()));
        return;
    }
    
    bool writeAsRootMacro = fileName.endsWith(".C");     
    
    QApplication::setOverrideCursor(Qt::WaitCursor);
    
    if (writeAsRootMacro)
        mDataTable->writeRootMacro(file, mCurrentSource,
                                        mLogXRadioButton->isChecked(),
                                        mLogYRadioButton->isChecked(),
                                        mMarkerPlotCoordinate);
    else
        mDataTable->writeTextFile(file, mCurrentSource);
        
    if (writeAsRootMacro) 
        statusBar()->showMessage(tr("Data saved in ROOT macro '%1'.").arg(fileName));
    else
        statusBar()->showMessage(tr("Data saved in '%1'.").arg(fileName));
    
    QApplication::restoreOverrideCursor();
}

void xyscanWindow::scaleImage(double z)
{
    QSize s = mCurrentPixmap->pixmap().size();
    double x = s.width()/2;
    double y = s.height()/2;
    if (mCurrentPixmap) {
        // scale around center
        mCurrentPixmap->setTransform(QTransform().translate(x, y).scale(z, z).rotate(mImageAngle).translate(-x, -y));
        mImageScale = z;        
        QRectF rectf = mCurrentPixmap->sceneBoundingRect();
        mImageScene->setSceneRect(rectf);
        update();
    }
}

QPointF xyscanWindow::scan(QPointF* auxPos)
{
    //
    //  This is where the transformation from pixel
    //  to graph coordinates is performed. 
    //
    
    QPointF xy(0,0);
 
    bool logx = mLogXRadioButton->isChecked();
    bool logy = mLogYRadioButton->isChecked();
        
    //
    //  Consistency and numerics checks
    //
    QMessageBox::StandardButton reply;
    
    if (!readyForScan()) {
        QMessageBox::information(0, "xyscan",
                                 tr("Cannot scan yet. Not sufficient information available to perform "
                                    "the coordinate transformation. You need to define 2 points on the "
                                    "x-axis (x1 & x1) and 2 on the y-axis (y1 & y2)."));
        return xy;
    }    
    
    if (fabs(mMarkerPixel[mXUpper]-mMarkerPixel[mXLower]) < 2) {
        reply = QMessageBox::critical(0, "xyscan",
                                      tr("Error in calculating transformation.\n"
                                         "Markers on x-axis are less than two pixels apart. "
                                         "Cannot continue with current settings."),
                                      QMessageBox::Reset|QMessageBox::Ignore, QMessageBox::Reset);
        if (reply == QMessageBox::Reset) {resetMarker();}
        return xy;
    }
    if (fabs(mMarkerPixel[mYUpper]-mMarkerPixel[mYLower]) < 2) {
        reply = QMessageBox::critical(0, "xyscan",
                                      tr("Error in calculating transformation.\n"
                                         "Markers on y-axis are less than two pixels apart. "
                                         "Cannot continue with current settings."),
                                      QMessageBox::Reset|QMessageBox::Ignore, QMessageBox::Reset);
        if (reply == QMessageBox::Reset) {resetMarker();}
        return xy;
    }
    
    if (logx) {
        if (mMarkerPlotCoordinate[mXUpper] <= 0 || mMarkerPlotCoordinate[mXLower] <= 0) {
            QMessageBox::critical(0, "xyscan",
                                  tr("Error in calculating transformation.\n"
                                     "Logarithmic x-axis selected but negative (or zero) values assigned to markers. "
                                     "Cannot continue with current settings."));
            return xy;
        }
    }
    
    if (logy) {
        if (mMarkerPlotCoordinate[mYUpper] <= 0 || mMarkerPlotCoordinate[mYLower] <= 0) {
            QMessageBox::critical(0, "xyscan",
                                  tr("Error in calculating transformation.\n"
                                     "Logarithmic y-axis selected but negative (or zero) values assigned to markers. "
                                     "Cannot continue with current settings."));
            return xy;
        }
    }
    
    mShowPrecisionAction->setDisabled(false); // OK from here on

    //
    //  Coordinate transformation
    //
    
    double m11, m22, dx, dy;
    if (logx) {
        m11 = (log10(mMarkerPlotCoordinate[mXUpper])-log10(mMarkerPlotCoordinate[mXLower]))/(mMarkerPixel[mXUpper]-mMarkerPixel[mXLower]);
        dx = log10(mMarkerPlotCoordinate[mXUpper])-m11*mMarkerPixel[mXUpper];
    }
    else {
        m11 = (mMarkerPlotCoordinate[mXUpper]-mMarkerPlotCoordinate[mXLower])/(mMarkerPixel[mXUpper]-mMarkerPixel[mXLower]);
        dx = mMarkerPlotCoordinate[mXUpper]-m11*mMarkerPixel[mXUpper];
    }
    if (logy) {
        m22 = (log10(mMarkerPlotCoordinate[mYUpper])-log10(mMarkerPlotCoordinate[mYLower]))/(mMarkerPixel[mYUpper]-mMarkerPixel[mYLower]);
        dy = log10(mMarkerPlotCoordinate[mYUpper])-m22*mMarkerPixel[mYUpper];
    }
    else {
        m22 = (mMarkerPlotCoordinate[mYUpper]-mMarkerPlotCoordinate[mYLower])/(mMarkerPixel[mYUpper]-mMarkerPixel[mYLower]);
        dy = mMarkerPlotCoordinate[mYUpper]-m22*mMarkerPixel[mYUpper];
    }
    QTransform M(m11, 0, 0, m22, dx, dy);
    QPointF cross;
    if (auxPos) {
        cross.setX(auxPos->x());
        cross.setY(auxPos->y());
    }
    else {
        cross.setX(mCrosshairV->pos().x());
        cross.setY(mCrosshairH->pos().y());
    }
    xy = M.map(cross);
    if (logx) xy.setX(pow(10.,xy.x()));
    if (logy) xy.setY(pow(10.,xy.y()));
    
    return xy;
}

void xyscanWindow::setPlotCoordinateValueForMarker(int markerType)
{
    bool ok;
    double r = mMarkerPlotCoordinate[markerType];
    char axis = (markerType == mXLower || markerType == mXUpper) ? 'x' : 'y';
    QString uplow = (markerType == mXLower || markerType == mYLower) ? QString("lower") : QString("upper");
    QString txt = QString(tr("Enter the %1 %2-value at marker position:").arg(uplow).arg(axis));
    QString ret = QInputDialog::getText(this, "xyscan", txt,
                                        QLineEdit::Normal, QString("%1").arg(r), &ok);
    if (!ok) return;
    r = ret.toDouble(&ok);
    if (!ok) {
        QMessageBox::warning( 0, "xyscan",
                             tr("%1 is not a valid floating point number.").arg(ret));
        return;
    }
    
    mMarkerPlotCoordinate[markerType] = r;
    QString str;
    str.setNum(r);
    if (markerType == mXLower)
        mLowerXValueField->setText(str);
    else if (markerType == mXUpper)
        mUpperXValueField->setText(str);
    else if (markerType == mYLower)
        mLowerYValueField->setText(str);
    else if (markerType == mYUpper)
        mUpperYValueField->setText(str);
    
    QPointF pos(mCrosshairH->pos().x(), mCrosshairV->pos().y());
    
    if (markerType == mXLower || markerType == mXUpper)
        mMarkerPixel[markerType] = pos.x();
    else
        mMarkerPixel[markerType] = pos.y();

    mMarker[markerType]->setPos(pos);
    mMarker[markerType]->setVisible(true);
    
    if (readyForScan()) {
        statusBar()->showMessage(tr("Ready to scan. Press space bar to record current cursor position."));
        mStartMeasureButton->setDisabled(false);
        mMeasureScaleComboBox->setDisabled(false);
        auto model = dynamic_cast<QStandardItemModel*>(mMeasureScaleComboBox->model());
        auto item = model->item(mPlotUnits, 0);
        item->setEnabled(true);
    }
    else
        statusBar()->showMessage(QString(tr("%1 of 4 markers set.")).arg(numberOfMarkersSet()));
    
    if (mMeasuringIsOn) updateMeasureDisplay(); // any change of marker does change measure
    mAngleSpinBox->setDisabled(true);  // rotating would void marker position
    mScaleSpinBox->setDisabled(true);  // same for scaling (zoomig in/out)
}

void xyscanWindow::showPrecision()
{
    QPointF point, currentV, currentH;
    QPointF left, right, up, down;
    QString str;
    double mdx, pdx, mdy, pdy;
    if (readyForScan()) {
        currentV = mCrosshairV->pos();
        currentH = mCrosshairH->pos();
        point = scan();
        
        mCrosshairV->moveBy(-1,0);
        mCrosshairH->moveBy(-1,0);
        left = scan();
        mCrosshairV->setPos(currentV);
        mCrosshairH->setPos(currentH);
        
        mCrosshairV->moveBy(1,0);
        mCrosshairH->moveBy(1,0);
        right = scan();
        mCrosshairV->setPos(currentV);
        mCrosshairH->setPos(currentH);

        mCrosshairV->moveBy(0,1);
        mCrosshairH->moveBy(0,1);
        down = scan();
        mCrosshairV->setPos(currentV);
        mCrosshairH->setPos(currentH);
        
        mCrosshairV->moveBy(0,-1);
        mCrosshairH->moveBy(0,-1);
        up = scan();
        mCrosshairV->setPos(currentV);
        mCrosshairH->setPos(currentH);
        
        mdx = fabs(point.x()-left.x());
        pdx = fabs(point.x()-right.x());
        mdy = fabs(point.y()-down.y());
        pdy = fabs(point.y()-up.y());
        str = tr("Estimated precision at current point:\ndx = +%1  -%2\ndy = +%3  -%4").arg(pdx).arg(mdx).arg(pdy).arg(mdy);
    }
    else {
        str = tr("Cannot determin precision yet.\nPlace all 4 markers first.");
    }
    
    //
    //  Sheet attached to main window on Mac
    //
    QMessageBox msgBox(QMessageBox::NoIcon,
                       "xyscan",
                       str,
                       QMessageBox::Ok,
                       this,
                       Qt::Sheet);
    msgBox.setWindowModality(Qt::WindowModal);
    
    msgBox.exec();
}

void xyscanWindow::updatePixelDisplay()
{
    QString str;
    str.setNum(mCrosshairH->pos().x());
    mPixelXDisplay->setText(str);
    str.setNum(mCrosshairV->pos().y());
    mPixelYDisplay->setText(str);
}

void xyscanWindow::updateMeasureDisplay()
{
    //
    //  This method is invoked every time the cursor moves,
    //  a double mouse clicks happen, or any input filed in
    //  the Measure tool item is altered.
    //
    if (mMeasureScaleComboBox->currentIndex() == mUserUnits) {
        QPalette palette;
        bool ok;
        mMeasureUserScaleField->setVisible(true);
        mMeasureUserScale = mMeasureUserScaleField->text().toDouble(&ok);
        if (mMeasureUserScale < 0 || !ok) {
            mMeasureUserScale = 0;
            palette.setColor(QPalette::Text, Qt::red);
            mMeasureUserScaleField->setPalette(palette);
        }
        else {
            mMeasureUserScaleField->setPalette(palette);
        }
    }
    else {
        mMeasureUserScaleField->setVisible(false);
    }
    
    if (!mMeasuringIsOn) return;
    
    //
    //  Get start and end point
    //
    QPointF endPoint(mCrosshairV->pos().x(), mCrosshairH->pos().y());
    QPointF startPoint(mPointMarker->pos());
    startPoint += QPointF(mPointMarker->pixmap().width()/2+mPointMarkerOffset, mPointMarker->pixmap().height()/2+mPointMarkerOffset); 
    
    //
    //  Calculate the distance
    //
    double dx = 0;
    double dy = 0;
    
    if (mMeasureScaleComboBox->currentIndex() == mPixelUnits) {
        dx = endPoint.x()-startPoint.x();
        dy = startPoint.y()-endPoint.y();  // switch y
    }
    else if (mMeasureScaleComboBox->currentIndex() == mPlotUnits) {
        QPointF startPlotCoordinate = scan(&startPoint);
        QPointF endPlotCoordinate = scan(&endPoint);
        dx = endPlotCoordinate.x()-startPlotCoordinate.x();
        dy = endPlotCoordinate.y()-startPlotCoordinate.y();
    }
    else if (mMeasureScaleComboBox->currentIndex() == mUserUnits) {
        dx = endPoint.x()-startPoint.x();
        dy = startPoint.y()-endPoint.y();  // switch y
        dx *= mMeasureUserScale;
        dy *= mMeasureUserScale;
    }
    double dr = sqrt(dx*dx+dy*dy);
    double dphi = atan2(dy, dx);
    if (dphi < 0) dphi = 2*M_PI+dphi;  // since atan2() returns -pi to pi
    
    //
    //  Update display
    //
    QString str;
    str.setNum(dx);
    mMeasureDXDisplay->setText(str);
    str.setNum(dy);
    mMeasureDYDisplay->setText(str);
    str.setNum(dr);
    mMeasureDRDisplay->setText(str);
    str.setNum(mMeasureAngleRadiansCheckBox->isChecked() ? dphi : dphi*180/M_PI);
    mMeasureDADisplay->setText(str);
    
    mMeasureLine->setLine(startPoint.x(), startPoint.y(), endPoint.x(), endPoint.y());
//    mMeasureLine->setPen(QPen(mMarkerColor));
}

void xyscanWindow::updatePlotCoordinateDisplay()
{
    if (readyForScan()) {
        QPointF xy = scan();
        QString str;
        str.setNum(xy.x());
        mPlotXDisplay->setText(str);
        str.setNum(xy.y());
        mPlotYDisplay->setText(str);
    }
    else {
        mPlotXDisplay->setText(tr("N/A"));
        mPlotYDisplay->setText(tr("N/A"));
    }
}

void xyscanWindow::updateWhenAxisScaleChanged()
{
    updatePixelDisplay();
    updatePlotCoordinateDisplay();
    updateZoomDisplay();
}

void xyscanWindow::updateZoomDisplay()
{
    mZoomView->centerOn(mCrosshairH->pos().x(), mCrosshairV->pos().y());
    update();
}

void xyscanWindow::userWasRemindedOfAvailableUpdate()
{
    mLastReminderTime = QDateTime::currentDateTime();
}

void xyscanWindow::writeSettings()
{
    QSettings settings(QSettings::NativeFormat, QSettings::UserScope, "tu", "xyscan");
    settings.setValue("xyscan/Version", VERSION_NUMBER);  // not used but good to have
    settings.setValue("xyscan/position", pos());
    settings.setValue("xyscan/showToolTips", mShowTooltipsAction->isChecked());
    settings.setValue("xyscan/lastOpenFileDirectory", mOpenFileDirectory);
    settings.setValue("xyscan/lastSaveFileDirectory", mSaveFileDirectory);
    settings.setValue("xyscan/recentFiles", mRecentFiles);
    settings.setValue("xyscan/crosshairColor", mCrosshairColor);
    settings.setValue("xyscan/markerColor", mMarkerColor);
    settings.setValue("xyscan/lastReminderTime", mLastReminderTime);
}

void xyscanWindow::zoomScale(double s)
{
    double relativeScale = s/mZoomScale;
    mZoomView->scale(relativeScale, relativeScale);
    mZoomScale = s;
}