[97f304]: libgui / SignalWidget.cpp Maximize Restore History

Download this file

SignalWidget.cpp    2647 lines (2308 with data), 81.0 kB

   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
/***************************************************************************
SignalWidget.cpp - Widget for displaying the signal
-------------------
begin : 1999
copyright : (C) 1999 by Martin Wilz
email : Martin Wilz <mwilz@ernie.mi.uni-koeln.de>
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "config.h"
#include <errno.h>
#include <math.h>
#include <stdlib.h>
#include <sys/time.h>
#include <QBitmap>
#include <QContextMenuEvent>
#include <QDragLeaveEvent>
#include <QEvent>
#include <QFrame>
#include <QDragEnterEvent>
#include <QDragMoveEvent>
#include <QDropEvent>
#include <QMenu>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QResizeEvent>
#include <QTime>
#include <QToolTip>
#include <kcursor.h>
#include <kglobal.h>
#include <kglobalsettings.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kiconloader.h>
#include "libkwave/ClipBoard.h"
#include "libkwave/CodecManager.h"
#include "libkwave/FileInfo.h"
#include "libkwave/KwaveDrag.h"
#include "libkwave/Label.h"
#include "libkwave/LabelList.h"
#include "libkwave/MessageBox.h"
#include "libkwave/MultiTrackReader.h"
#include "libkwave/Parser.h"
#include "libkwave/SampleReader.h"
#include "libkwave/SignalManager.h"
#include "libkwave/Track.h"
#include "libkwave/undo/UndoTransactionGuard.h"
#include "libgui/LabelPropertiesWidget.h"
#include "libgui/MenuManager.h"
#include "libgui/SignalWidget.h"
#include "libgui/TrackPixmap.h"
#include "MouseMark.h"
#ifdef DEBUG
#include <time.h>
#include <sys/time.h>
#endif
#define LAYER_SIGNAL 0
#define LAYER_SELECTION 1
#define LAYER_MARKERS 2
/**
* useful macro for command parsing
*/
#define CASE_COMMAND(x) } else if (parser.command() == x) {
/**
* Limits the zoom to a minimum number of samples visible in one
* screen.
*/
#define MINIMUM_SAMPLES_PER_SCREEN 5
/**
* Default widht of the display in seconds when in streaming mode,
* where no initial length information is available
*/
#define DEFAULT_DISPLAY_TIME 60.0
/** number of milliseconds between repaints */
#define REPAINT_INTERVAL 50
/** number of milliseconds until the position widget disappears */
#define POSITION_WIDGET_TIME 5000
/**
* tolerance in pixel for snapping to a label or selection border
* @todo selection tolerance should depend on some KDE setting,
* but which ?
*/
#define SELECTION_TOLERANCE 10
/** vertical zoom factor: minimum value */
#define VERTICAL_ZOOM_MIN 1.0
/** vertical zoom factor: maximum value */
#define VERTICAL_ZOOM_MAX 100.0
/** vertical zoom factor: increment/decrement factor */
#define VERTICAL_ZOOM_STEP_FACTOR 1.5
//***************************************************************************
//***************************************************************************
namespace KwaveFileDrag
{
static bool canDecode(const QMimeData *source) {
if (!source) return false;
if (source->hasUrls()) {
// dropping URLs
foreach (QUrl url, source->urls()) {
QString filename = url.toLocalFile();
QString mimetype = CodecManager::whatContains(filename);
if (CodecManager::canDecode(mimetype)) {
return true;
}
}
}
foreach (QString format, source->formats()) {
// dropping known mime type
if (CodecManager::canDecode(format)) {
qDebug("KwaveFileDrag::canDecode(%s)", format.toLocal8Bit().data());
return true;
}
}
return false;
}
}
//***************************************************************************
//***************************************************************************
SignalWidget::SignalWidget(QWidget *parent)
:QWidget(parent), m_image(),
m_offset(0), m_width(0), m_height(0), m_last_width(0), m_last_height(0),
m_zoom(0.0), m_vertical_zoom(1.0), m_playpointer(-1), m_last_playpointer(-1),
m_redraw(false), m_inhibit_repaint(0), m_selection(0), m_signal_manager(this),
m_track_pixmaps(), m_mouse_mode(Kwave::MouseMark::MouseNormal),
m_mouse_down_x(0), m_repaint_timer(this), m_position_widget(this),
m_position_widget_timer(this)
{
// qDebug("SignalWidget::SignalWidget()");
for (int i=0; i < 3; i++) {
m_layer[i] = QImage();
m_update_layer[i] = true;
}
m_selection = new Kwave::MouseMark();
Q_ASSERT(m_selection);
if (!m_selection) return;
// connect to the signal manager's signals
SignalManager *sig = &m_signal_manager;
connect(sig, SIGNAL(sigTrackInserted(unsigned int, Track *)),
this, SLOT(slotTrackInserted(unsigned int, Track *)));
connect(sig, SIGNAL(sigTrackDeleted(unsigned int)),
this, SLOT(slotTrackDeleted(unsigned int)));
connect(sig, SIGNAL(sigSamplesDeleted(unsigned int, sample_index_t,
sample_index_t)),
this, SLOT(slotSamplesDeleted(unsigned int, sample_index_t,
sample_index_t)));
connect(sig, SIGNAL(sigSamplesInserted(unsigned int, sample_index_t,
sample_index_t)),
this, SLOT(slotSamplesInserted(unsigned int, sample_index_t,
sample_index_t)));
connect(sig, SIGNAL(sigSamplesModified(unsigned int, sample_index_t,
sample_index_t)),
this, SLOT(slotSamplesModified(unsigned int, sample_index_t,
sample_index_t)));
connect(sig, SIGNAL(sigLabelCountChanged()),
this, SLOT(hidePosition()),
Qt::QueuedConnection);
connect(sig, SIGNAL(sigLabelCountChanged()),
this, SLOT(refreshMarkersLayer()),
Qt::QueuedConnection);
connect(sig, SIGNAL(labelsChanged(LabelList)),
this, SLOT(refreshMarkersLayer()),
Qt::QueuedConnection);
connect(&(sig->selection()), SIGNAL(changed(sample_index_t, sample_index_t)),
this, SLOT(slotSelectionChanged(sample_index_t, sample_index_t)));
// connect to the playback controller
connect(&(playbackController()), SIGNAL(sigPlaybackPos(sample_index_t)),
this, SLOT(updatePlaybackPointer(sample_index_t)));
// connect repaint timer
connect(&m_repaint_timer, SIGNAL(timeout()),
this, SLOT(timedRepaint()));
// connect the timer of the position widget
connect(&m_position_widget_timer, SIGNAL(timeout()),
&m_position_widget, SLOT(hide()));
// m_menu_manager.clearNumberedMenu("ID_LABELS_TYPE");
// for (LabelType *tmp = globals.markertypes.first(); tmp;
// tmp = globals.markertypes.next())
// {
// m_menu_manager.addNumberedMenuEntry("ID_LABELS_TYPE", (char *)tmp->name);
// }
//
// markertype = globals.markertypes.first();
QPalette pal = palette();
pal.setColor(QPalette::Window, Qt::black);
setMouseTracking(true);
setAcceptDrops(true); // enable drag&drop
setAutoFillBackground(false);
setAttribute(Qt::WA_OpaquePaintEvent, true);
setAttribute(Qt::WA_NoSystemBackground, true);
setZoom(0.0);
// qDebug("SignalWidget::SignalWidget(): done.");
}
//***************************************************************************
void SignalWidget::refreshSignalLayer()
{
refreshLayer(LAYER_SIGNAL);
}
//***************************************************************************
void SignalWidget::refreshMarkersLayer()
{
refreshLayer(LAYER_MARKERS);
}
//***************************************************************************
bool SignalWidget::isOK()
{
Q_ASSERT(m_selection);
return ( m_selection );
}
//***************************************************************************
SignalWidget::~SignalWidget()
{
inhibitRepaint();
close();
labels().clear();
if (m_selection) delete m_selection;
m_selection = 0;
for (int i=0; i < 3; i++)
m_layer[i] = QImage();
}
//***************************************************************************
void SignalWidget::toggleTrackSelection(int track)
{
// here we have to convert to unsigned
Q_ASSERT(track >= 0);
if (track < 0) return;
unsigned int t = static_cast<unsigned int>(track);
bool select = !m_signal_manager.trackSelected(t);
m_signal_manager.selectTrack(t, select);
}
//***************************************************************************
bool SignalWidget::executeNavigationCommand(const QString &command)
{
if (!command.length()) return true;
Parser parser(command);
const unsigned int visible_samples = pixels2samples(m_width);
if (false) {
// zoom
CASE_COMMAND("zoomin")
zoomIn();
CASE_COMMAND("zoomout")
zoomOut();
CASE_COMMAND("zoomselection")
zoomSelection();
CASE_COMMAND("zoomall")
zoomAll();
CASE_COMMAND("zoomnormal")
zoomNormal();
// navigation
CASE_COMMAND("goto")
sample_index_t offset = parser.toUInt();
setOffset((offset > (visible_samples / 2)) ?
(offset - (visible_samples / 2)) : 0);
selectRange(offset, 0);
CASE_COMMAND("scrollright")
setOffset(m_offset + visible_samples / 10);
CASE_COMMAND("scrollleft")
setOffset(((visible_samples / 10) < m_offset) ?
(m_offset - visible_samples / 10) : 0);
CASE_COMMAND("viewstart")
setOffset(0);
selectRange(0,0);
CASE_COMMAND("viewend")
sample_index_t len = m_signal_manager.length();
if (len >= visible_samples) setOffset(len - visible_samples);
CASE_COMMAND("viewnext")
setOffset(m_offset + visible_samples);
CASE_COMMAND("viewprev")
setOffset((visible_samples < m_offset) ?
(m_offset - visible_samples) : 0);
// selection
CASE_COMMAND("selectall")
selectRange(0, m_signal_manager.length());
CASE_COMMAND("selectnext")
if (m_signal_manager.selection().length())
selectRange(m_signal_manager.selection().last()+1,
m_signal_manager.selection().length());
else
selectRange(m_signal_manager.length() - 1, 0);
CASE_COMMAND("selectprev")
sample_index_t ofs = m_signal_manager.selection().first();
sample_index_t len = m_signal_manager.selection().length();
if (!len) len = 1;
if (len > ofs) len = ofs;
selectRange(ofs-len, len);
CASE_COMMAND("selecttoleft")
selectRange(0, m_signal_manager.selection().last()+1);
CASE_COMMAND("selecttoright")
selectRange(m_signal_manager.selection().first(),
m_signal_manager.length()-m_signal_manager.selection().first()
);
CASE_COMMAND("selectvisible")
selectRange(m_offset, pixels2samples(m_width) - 1);
CASE_COMMAND("selectnone")
selectRange(m_offset, 0);
} else return false;
return true;
}
//***************************************************************************
int SignalWidget::executeCommand(const QString &command)
{
InhibitRepaintGuard inhibit(*this);
Parser parser(command);
if (!command.length()) return -EINVAL;
if (executeNavigationCommand(command)) {
return 0;
// label commands
CASE_COMMAND("label")
unsigned int pos = parser.toUInt();
addLabel(pos);
CASE_COMMAND("deletelabel")
int index = parser.toInt();
m_signal_manager.deleteLabel(index, true);
// CASE_COMMAND("chooselabel")
// Parser parser(command);
// markertype = globals.markertypes.at(parser.toInt());
// CASE_COMMAND("amptolabel")
// markSignal(command);
// CASE_COMMAND("pitch")
// markPeriods(command);
// CASE_COMMAND("labeltopitch")
// convertMarkstoPitch(command);
// CASE_COMMAND("loadlabel")
// loadLabel();
// CASE_COMMAND("savelabel")
// saveLabel(command);
CASE_COMMAND("expandtolabel")
UndoTransactionGuard undo(m_signal_manager,
i18n("Expand Selection to Label"));
sample_index_t selection_left = m_signal_manager.selection().first();
sample_index_t selection_right = m_signal_manager.selection().last();
if (labels().isEmpty()) return false; // we need labels for this
Label label_left = Label();
Label label_right = Label();
// the last label <= selection start -> label_left
// the first label >= selection end -> label_right
foreach (Label label, labels()) {
unsigned int lp = label.pos();
if (lp <= selection_left)
label_left = label;
if ((lp >= selection_right) && (label_right.isNull())) {
label_right = label;
break; // done
}
}
// default left label = start of file
selection_left = (label_left.isNull()) ? 0 :
label_left.pos();
// default right label = end of file
selection_right = (label_right.isNull()) ?
m_signal_manager.length() - 1 : label_right.pos();
sample_index_t length = selection_right - selection_left + 1;
selectRange(selection_left, length);
CASE_COMMAND("selectnextlabels")
UndoTransactionGuard undo(m_signal_manager,
i18n("Select Next Labels"));
sample_index_t selection_left;
sample_index_t selection_right = m_signal_manager.selection().last();
Label label_left = Label();
Label label_right = Label();
if (labels().isEmpty()) return false; // we need labels for this
// special case: nothing selected -> select up to the first label
if (selection_right == 0) {
label_right = labels().first();
selection_left = 0;
} else {
// find the first label starting after the current selection
LabelListIterator it(labels());
while (it.hasNext()) {
Label label = it.next();
if (label.pos() >= selection_right) {
// take it as selection start
label_left = label;
// and it's next one as selection end (might be null)
label_right = it.hasNext() ? it.next() : Label();
break;
}
}
// default selection start = last label
if (label_left.isNull()) label_left = labels().last();
if (label_left.isNull()) return false; // no labels at all !?
selection_left = label_left.pos();
}
// default selection end = end of the file
selection_right = (label_right.isNull()) ?
m_signal_manager.length() - 1 : label_right.pos();
sample_index_t length = selection_right - selection_left + 1;
selectRange(selection_left, length);
CASE_COMMAND("selectprevlabels")
UndoTransactionGuard undo(m_signal_manager,
i18n("Select Previous Labels"));
sample_index_t selection_left = m_signal_manager.selection().first();
sample_index_t selection_right = m_signal_manager.selection().last();
Label label_left = Label();
Label label_right = Label();
if (labels().isEmpty()) return false; // we need labels for this
// find the last label before the start of the selection
foreach (Label label, labels()) {
if (label.pos() > selection_left)
break; // done
label_left = label_right;
label_right = label;
}
// default selection start = start of file
selection_left = (label_left.isNull()) ? 0 :
label_left.pos();
// default selection end = first label
if (label_right.isNull()) label_right = labels().first();
if (label_right.isNull()) return false; // no labels at all !?
selection_right = label_right.pos();
sample_index_t length = selection_right - selection_left + 1;
selectRange(selection_left, length);
// CASE_COMMAND("markperiod")
// markPeriods(command);
// CASE_COMMAND("saveperiods")
// savePeriods();
// track selection
CASE_COMMAND("select_all_tracks")
UndoTransactionGuard undo(m_signal_manager,
i18n("Select All Tracks"));
foreach (unsigned int track, m_signal_manager.allTracks())
m_signal_manager.selectTrack(track, true);
CASE_COMMAND("deselect_all_tracks")
UndoTransactionGuard undo(m_signal_manager,
i18n("Deselect all tracks"));
foreach (unsigned int track, m_signal_manager.allTracks())
m_signal_manager.selectTrack(track, false);
CASE_COMMAND("invert_track_selection")
UndoTransactionGuard undo(m_signal_manager,
i18n("Invert Track Selection"));
foreach (unsigned int track, m_signal_manager.allTracks())
m_signal_manager.selectTrack(
track,
!m_signal_manager.trackSelected(track)
);
CASE_COMMAND("select_track")
int track = parser.toInt();
UndoTransactionGuard undo(m_signal_manager, i18n("Select Track"));
m_signal_manager.selectTrack(track, true);
CASE_COMMAND("deselect_track")
int track = parser.toInt();
UndoTransactionGuard undo(m_signal_manager, i18n("Deselect Track"));
m_signal_manager.selectTrack(track, false);
} else {
return m_signal_manager.executeCommand(command);
}
return 0;
}
//***************************************************************************
void SignalWidget::selectRange(unsigned int offset, unsigned int length)
{
m_signal_manager.selectRange(offset, length);
}
//***************************************************************************
void SignalWidget::slotSelectionChanged(sample_index_t offset,
sample_index_t length)
{
m_signal_manager.selectRange(offset, length);
offset = m_signal_manager.selection().offset();
length = m_signal_manager.selection().length();
refreshLayer(LAYER_SELECTION);
emit selectedTimeInfo(offset, length, m_signal_manager.rate());
}
//***************************************************************************
void SignalWidget::forwardCommand(const QString &command)
{
emit sigCommand(command);
}
//***************************************************************************
int SignalWidget::tracks()
{
return m_signal_manager.tracks();
}
//***************************************************************************
PlaybackController &SignalWidget::playbackController()
{
return m_signal_manager.playbackController();
}
//***************************************************************************
SignalManager &SignalWidget::signalManager()
{
return m_signal_manager;
}
//***************************************************************************
int SignalWidget::loadFile(const KUrl &url)
{
// load a new signal
int res = m_signal_manager.loadFile(url);
if (m_signal_manager.isClosed() && res) {
qWarning("SignalWidget::loadFile() failed:"\
" zero-length or out of memory?");
QString reason;
switch (res) {
case -ENOMEM:
reason = i18n("Out of memory");
break;
case -EIO:
reason = i18n("Unable to open '%1'",
url.prettyUrl());
break;
case -EINVAL:
reason = i18n("Invalid or unknown file type: '%1'",
url.prettyUrl());
break;
default:
reason = "";
}
// show an error message box if the reason was known
if (reason.length()) {
Kwave::MessageBox::error(this, reason);
}
close();
}
// if the signal is smaller than expected,
// zoom it to full size
if (m_zoom > getFullZoom()) setZoom(getFullZoom());
return res;
}
//***************************************************************************
void SignalWidget::newSignal(sample_index_t samples, double rate,
unsigned int bits, unsigned int tracks)
{
m_signal_manager.newSignal(samples,rate,bits,tracks);
}
//***************************************************************************
void SignalWidget::close()
{
// first stop playback
m_signal_manager.playbackController().playbackStop();
m_signal_manager.playbackController().reset();
// discard all labels
labels().clear();
// clear the display
qDeleteAll(m_track_pixmaps);
m_track_pixmaps.clear();
setZoom(0.0);
setOffset(0);
// close the signal manager
m_signal_manager.close();
// reset the status, zoom and selection
selectRange(0, 0);
zoomAll();
refreshAllLayers();
setMouseMode(Kwave::MouseMark::MouseNormal);
}
//***************************************************************************
void SignalWidget::setOffset(sample_index_t new_offset)
{
InhibitRepaintGuard inhibit(*this);
m_offset = new_offset;
fixZoomAndOffset();
// forward the zoom and offset to all track pixmaps
foreach (Kwave::TrackPixmap *pix, m_track_pixmaps) {
if (!pix) continue;
pix->setOffset(m_offset);
pix->setZoom(m_zoom);
}
refreshAllLayers();
emit viewInfo(m_offset, pixels2samples(QWidget::width()-1)+1,
m_signal_manager.length());
}
//***************************************************************************
double SignalWidget::getFullZoom()
{
if (m_signal_manager.isEmpty()) return 0.0; // no zoom if no signal
sample_index_t length = m_signal_manager.length();
if (!length) {
// no length: streaming mode -> start with a default
// zoom, use one minute (just guessed)
length = static_cast<unsigned int>(ceil(DEFAULT_DISPLAY_TIME *
m_signal_manager.rate()));
}
// example: width = 100 [pixels] and length = 3 [samples]
// -> samples should be at positions 0, 49.5 and 99
// -> 49.5 [pixels / sample]
// -> zoom = 1 / 49.5 [samples / pixel]
// => full zoom [samples/pixel] = (length-1) / (width-1)
return static_cast<double>(length - 1) /
static_cast<double>(QWidget::width() - 1);
}
//***************************************************************************
void SignalWidget::setZoom(double new_zoom)
{
double old_zoom = m_zoom;
InhibitRepaintGuard inhibit(*this);
m_zoom = new_zoom;
fixZoomAndOffset();
if (m_zoom == old_zoom) return; // nothing to do
// forward the zoom and offset to all track pixmaps
foreach (Kwave::TrackPixmap *pix, m_track_pixmaps) {
if (!pix) continue;
pix->setOffset(m_offset);
pix->setZoom(m_zoom);
}
refreshAllLayers();
emit viewInfo(m_offset, pixels2samples(QWidget::width()-1)+1,
m_signal_manager.length());
emit sigZoomChanged(m_zoom);
}
//***************************************************************************
void SignalWidget::fixZoomAndOffset()
{
double max_zoom;
double min_zoom;
sample_index_t length;
length = m_signal_manager.length();
if (!length) {
// in streaming mode we have to use a guessed length
length = static_cast<unsigned int>(ceil(width() * getFullZoom()));
}
if (!m_width) return;
// ensure that m_offset is [0...length-1]
if (m_offset > length-1) m_offset = length-1;
// ensure that the zoom is in a proper range
max_zoom = getFullZoom();
min_zoom = static_cast<double>(MINIMUM_SAMPLES_PER_SCREEN) /
static_cast<double>(m_width);
if (m_zoom < min_zoom) m_zoom = min_zoom;
if (m_zoom > max_zoom) m_zoom = max_zoom;
// try to correct the offset if there is not enough data to fill
// the current window
// example: width=100 [pixels], length=3 [samples],
// offset=1 [sample], zoom=1/49.5 [samples/pixel] (full)
// -> current last displayed sample = length-offset
// = 3 - 1 = 2
// -> available space = pixels2samples(width-1) + 1
// = (99/49.5) + 1 = 3
// -> decrease offset by 3 - 2 = 1
Q_ASSERT(length >= m_offset);
if (pixels2samples(m_width - 1) + 1 > length-m_offset) {
// there is space after the signal -> move offset right
sample_index_t shift = pixels2samples(m_width - 1) + 1 -
(length - m_offset);
if (shift >= m_offset) {
m_offset = 0;
} else {
m_offset -= shift;
}
}
// not really needed, has side-effects e.g. when a .ogg file
// has been loaded
// // if reducing the offset was not enough, zoom in
// if (pixels2samples(m_width - 1) + 1 > length - m_offset) {
// // there is still space after the signal -> zoom in
// // (this should never happen as the zoom has been limited before)
// m_zoom = max_zoom;
// }
// this made some strange effects, so I disabled it :-[
// // adjust the zoom factor in order to make a whole number
// // of samples fit into the current window
// int samples = pixels2samples(width) + 1;
// zoom = (double)(samples) / (double)(width - 1);
// do some final range checking
if (m_zoom < min_zoom) m_zoom = min_zoom;
if (m_zoom > max_zoom) m_zoom = max_zoom;
}
//***************************************************************************
void SignalWidget::setMouseMode(Kwave::MouseMark::Mode mode)
{
if (mode == m_mouse_mode) return;
m_mouse_mode = mode;
switch (mode) {
case Kwave::MouseMark::MouseNormal:
setCursor(Qt::ArrowCursor);
break;
case Kwave::MouseMark::MouseAtSelectionBorder:
setCursor(Qt::SizeHorCursor);
break;
case Kwave::MouseMark::MouseInSelection:
setCursor(Qt::ArrowCursor);
break;
case Kwave::MouseMark::MouseSelect:
setCursor(Qt::SizeHorCursor);
break;
}
emit sigMouseChanged(mode);
}
//***************************************************************************
void SignalWidget::zoomAll()
{
InhibitRepaintGuard inhibit(*this);
setZoom(getFullZoom());
refreshAllLayers();
}
//***************************************************************************
void SignalWidget::zoomNormal()
{
InhibitRepaintGuard inhibit(*this);
m_offset += pixels2samples(m_width) / 2;
setZoom(1.0);
sample_index_t shift = pixels2samples(m_width) / 2;
setOffset((shift < m_offset) ? (m_offset-shift) : 0);
refreshAllLayers();
}
//***************************************************************************
void SignalWidget::zoomOut()
{
InhibitRepaintGuard inhibit(*this);
m_offset += pixels2samples(m_width) / 2;
setZoom(m_zoom*3);
sample_index_t shift = pixels2samples(m_width) / 2;
setOffset((shift < m_offset) ? (m_offset-shift) : 0);
refreshAllLayers();
}
//***************************************************************************
void SignalWidget::zoomIn()
{
InhibitRepaintGuard inhibit(*this);
m_offset += pixels2samples(m_width) / 2;
setZoom(m_zoom / 3);
sample_index_t shift = pixels2samples(m_width) / 2;
setOffset((shift < m_offset) ? (m_offset-shift) : 0);
refreshAllLayers();
}
//***************************************************************************
void SignalWidget::zoomSelection()
{
InhibitRepaintGuard inhibit(*this);
sample_index_t ofs = m_signal_manager.selection().offset();
sample_index_t len = m_signal_manager.selection().length();
if (len) {
m_offset = ofs;
setZoom((static_cast<double>(len)) / static_cast<double>(m_width - 1));
}
}
//***************************************************************************
void SignalWidget::resizeEvent(QResizeEvent *)
{
emit viewInfo(m_offset, pixels2samples(QWidget::width()-1)+1,
m_signal_manager.length());
}
//***************************************************************************
void SignalWidget::inhibitRepaint()
{
m_inhibit_repaint++;
}
//***************************************************************************
void SignalWidget::allowRepaint(bool repaint)
{
Q_ASSERT(m_inhibit_repaint);
if (!m_inhibit_repaint) return;
// decrease the number of repaint locks
m_inhibit_repaint--;
// if the number reached zero, *do* the repaint if allowed
if (!m_inhibit_repaint && repaint) {
if (m_repaint_timer.isActive()) {
// repainting is inhibited -> wait until the
// repaint timer is elapsed
return;
} else {
// start the repaint timer
m_repaint_timer.setSingleShot(true);
m_repaint_timer.start(REPAINT_INTERVAL);
}
}
}
//***************************************************************************
void SignalWidget::timedRepaint()
{
this->repaint();
}
//***************************************************************************
void SignalWidget::refreshAllLayers()
{
InhibitRepaintGuard inhibit(*this);
for (int i=0; i < 3; i++) {
m_update_layer[i] = true;
}
m_redraw = true;
}
//***************************************************************************
void SignalWidget::refreshLayer(int layer)
{
InhibitRepaintGuard inhibit(*this);
Q_ASSERT(layer >= 0);
Q_ASSERT(layer < 3);
if ((layer < 0) || (layer >= 3)) return;
m_update_layer[layer] = true;
m_redraw = true;
}
//***************************************************************************
int SignalWidget::selectionPosition(const int x)
{
const int tol = SELECTION_TOLERANCE;
const sample_index_t first = m_signal_manager.selection().first();
const sample_index_t last = m_signal_manager.selection().last();
const sample_index_t ofs = m_offset;
Q_ASSERT(first <= last);
// get pixel coordinates
const int l = (first < ofs) ? -(2*tol) : (samples2pixels(first-ofs));
const int r = (last < ofs) ? -(2*tol) : (samples2pixels(last-ofs));
const int ll = (l > tol) ? (l-tol) : 0;
const int lr = l + tol;
const int rl = (r > tol) ? (r-tol) : 0;
const int rr = r + tol;
// the simple cases...
int pos = None;
if ((x >= ll) && (x <= lr) && (x <= r)) pos |= LeftBorder;
if ((x >= rl) && (x <= rr) && (x >= l)) pos |= RightBorder;
if ((x > l) && (x < r)) pos |= Selection;
if ((pos & LeftBorder) && (pos & RightBorder)) {
// special case: determine which border is nearer
if ((x - l) < (r - x))
pos &= ~RightBorder; // more on the left
else
pos &= ~LeftBorder; // more on the right
}
return pos;
}
//***************************************************************************
bool SignalWidget::isSelectionBorder(int x)
{
SelectionPos pos = static_cast<SignalWidget::SelectionPos>(
selectionPosition(x) & ~Selection);
return ((pos & LeftBorder) || (pos & RightBorder));
}
//***************************************************************************
bool SignalWidget::isInSelection(int x)
{
return (selectionPosition(x) & Selection) != 0;
}
//***************************************************************************
void SignalWidget::mousePressEvent(QMouseEvent *e)
{
Q_ASSERT(e);
Q_ASSERT(m_selection);
if (!e) return;
if (!m_selection) return;
// abort if no signal is loaded
if (!m_signal_manager.length()) return;
// ignore all mouse press events in playback mode
if (m_signal_manager.playbackController().running()) return;
if (e->button() == Qt::LeftButton) {
int mx = e->pos().x();
if (mx < 0) mx = 0;
if (mx >= m_width) mx = m_width-1;
sample_index_t x = m_offset + pixels2samples(mx);
sample_index_t len = m_signal_manager.selection().length();
switch (e->modifiers()) {
case Qt::ShiftModifier: {
// expand the selection to "here"
m_selection->set(m_signal_manager.selection().first(),
m_signal_manager.selection().last());
m_selection->grep(x);
selectRange(m_selection->left(), m_selection->length());
setMouseMode(Kwave::MouseMark::MouseSelect);
break;
}
case Qt::ControlModifier: {
if (isInSelection(e->pos().x()) && (len > 1)) {
// start a drag&drop operation in "copy" mode
startDragging();
}
break;
}
case 0: {
if (isSelectionBorder(e->pos().x())) {
// modify selection border
m_selection->set(m_signal_manager.selection().first(),
m_signal_manager.selection().last());
m_selection->grep(x);
selectRange(m_selection->left(), m_selection->length());
setMouseMode(Kwave::MouseMark::MouseSelect);
} else if (isInSelection(e->pos().x()) && (len > 1)) {
// store the x position for later drag&drop
m_mouse_down_x = e->pos().x();
} else {
// start a new selection
m_selection->set(x, x);
selectRange(x, 0);
setMouseMode(Kwave::MouseMark::MouseSelect);
}
break;
}
}
}
}
//***************************************************************************
void SignalWidget::contextMenuEvent(QContextMenuEvent *e)
{
Q_ASSERT(e);
Q_ASSERT(m_selection);
if (!e || !m_selection) return;
SignalManager *manager = &signalManager();
bool have_signal = !manager->isEmpty();
if (!have_signal)return;
bool have_selection = (manager->selection().length() > 1);
bool have_labels = !labels().isEmpty();
QMenu *context_menu = new QMenu(this);
Q_ASSERT(context_menu);
if (!context_menu) return;
QMenu *submenu_select = context_menu->addMenu(i18n("&Selection"));
Q_ASSERT(submenu_select);
if (!submenu_select) return;
QMenu *submenu_label = context_menu->addMenu(i18n("&Label"));
Q_ASSERT(submenu_label);
if (!submenu_label) return;
KIconLoader icon_loader;
/* menu items common to all cases */
// undo
QAction *action;
action = context_menu->addAction(
icon_loader.loadIcon("edit-undo", KIconLoader::Toolbar),
i18n("&Undo"), this, SLOT(contextMenuEditUndo()),
Qt::CTRL + Qt::Key_Z);
Q_ASSERT(action);
if (!action) return;
if (!manager->canUndo())
action->setEnabled(false);
// redo
action = context_menu->addAction(
icon_loader.loadIcon("edit-redo", KIconLoader::Toolbar),
i18n("&Redo"), this, SLOT(contextMenuEditRedo()),
Qt::CTRL + Qt::Key_Y);
Q_ASSERT(action);
if (!action) return;
if (!manager->canRedo())
action->setEnabled(false);
context_menu->addSeparator();
// cut/copy/paste
QAction *action_cut = context_menu->addAction(
icon_loader.loadIcon("edit-cut", KIconLoader::Toolbar),
i18n("Cu&t"), this, SLOT(contextMenuEditCut()),
Qt::CTRL + Qt::Key_X);
QAction *action_copy = context_menu->addAction(
icon_loader.loadIcon("edit-copy", KIconLoader::Toolbar),
i18n("&Copy"), this, SLOT(contextMenuEditCopy()),
Qt::CTRL + Qt::Key_C);
QAction *action_paste = context_menu->addAction(
icon_loader.loadIcon("edit-paste", KIconLoader::Toolbar),
i18n("&Paste"), this, SLOT(contextMenuEditPaste()),
Qt::CTRL + Qt::Key_V);
context_menu->addSeparator();
if (action_cut) action_cut->setEnabled(have_selection);
if (action_copy) action_copy->setEnabled(have_selection);
if (action_paste)
action_paste->setEnabled(!ClipBoard::instance().isEmpty());
int mouse_x = mapFromGlobal(e->globalPos()).x();
if (mouse_x < 0) mouse_x = 0;
if (mouse_x >= width()) mouse_x = width() - 1;
// Selection / &Save
QAction *action_select_save = submenu_select->addAction(
icon_loader.loadIcon("document-save", KIconLoader::Toolbar),
i18n("&Save..."), this, SLOT(contextMenuSaveSelection()));
Q_ASSERT(action_select_save);
if (!action_select_save) return;
action_select_save->setEnabled(have_selection);
// Selection / &Expand to labels
QAction *action_select_expand_to_labels = submenu_select->addAction(
i18n("&Expand to Labels"), this,
SLOT(contextMenuSelectionExpandToLabels()), Qt::Key_E);
Q_ASSERT(action_select_expand_to_labels);
if (!action_select_expand_to_labels) return;
action_select_expand_to_labels->setEnabled(have_labels);
// Selection / to next labels
QAction *action_select_next_labels = submenu_select->addAction(
i18n("To Next Labels"), this,
SLOT(contextMenuSelectionNextLabels()),
Qt::SHIFT + Qt::CTRL + Qt::Key_N);
Q_ASSERT(action_select_next_labels);
if (!action_select_next_labels) return;
action_select_next_labels->setEnabled(have_labels);
// Selection / to previous labels
QAction *action_select_prev_labels = submenu_select->addAction(
i18n("To Previous Labels"), this,
SLOT(contextMenuSelectionPrevLabels()),
Qt::SHIFT + Qt::CTRL + Qt::Key_P);
Q_ASSERT(action_select_prev_labels);
if (!action_select_prev_labels) return;
action_select_prev_labels->setEnabled(have_labels);
// label handling
QAction *action_label_new = submenu_label->addAction(
icon_loader.loadIcon("list-add", KIconLoader::Toolbar),
i18n("&New"), this, SLOT(contextMenuLabelNew()));
Q_ASSERT(action_label_new);
if (!action_label_new) return;
action_label_new->setEnabled(have_signal);
QAction *action_label_delete = submenu_label->addAction(
icon_loader.loadIcon("list-remove", KIconLoader::Toolbar),
i18n("&Delete"), this, SLOT(contextMenuLabelDelete()));
Q_ASSERT(action_label_delete);
if (!action_label_delete) return;
action_label_delete->setEnabled(false);
QAction *action_label_properties = submenu_label->addAction(
icon_loader.loadIcon("configure", KIconLoader::Toolbar),
i18n("&Properties..."), this, SLOT(contextMenuLabelProperties()));
Q_ASSERT(action_label_properties);
if (!action_label_properties) return;
action_label_properties->setEnabled(false);
// store the menu position in the mouse selection
unsigned int pos = m_offset + pixels2samples(mouse_x);
m_selection->set(pos, pos);
Label label;
if (!((label = findLabelNearMouse(mouse_x)).isNull())) {
// delete label ?
// label properties ?
action_label_new->setEnabled(false);
action_label_properties->setEnabled(true);
action_label_delete->setEnabled(true);
pos = label.pos();
m_selection->set(pos, pos);
}
if (isSelectionBorder(mouse_x)) {
// context menu: do something with the selection border
// expand to next marker (right) ?
// expand to next marker (left) ?
}
// if (isInSelection(mouse_x) && have_selection) {
// // context menu: do something with the selection
// }
context_menu->exec(QCursor::pos());
delete context_menu;
}
//***************************************************************************
void SignalWidget::contextMenuLabelNew()
{
Q_ASSERT(m_selection);
if (!m_selection) return;
forwardCommand(QString("label(%1)").arg(m_selection->left()));
}
//***************************************************************************
void SignalWidget::contextMenuLabelDelete()
{
Q_ASSERT(m_selection);
if (!m_selection) return;
Label label = m_signal_manager.findLabel(m_selection->left());
if (label.isNull()) return;
int index = m_signal_manager.labelIndex(label);
forwardCommand(QString("deletelabel(%1)").arg(index));
}
//***************************************************************************
void SignalWidget::contextMenuLabelProperties()
{
Q_ASSERT(m_selection);
if (!m_selection) return;
Label label = m_signal_manager.findLabel(m_selection->left());
if (label.isNull()) return;
labelProperties(label);
}
//***************************************************************************
void SignalWidget::mouseReleaseEvent(QMouseEvent *e)
{
Q_ASSERT(e);
Q_ASSERT(m_selection);
if (!e) return;
if (!m_selection) return;
// abort if no signal is loaded
if (!m_signal_manager.length()) return;
// ignore all mouse release events in playback mode
if (m_signal_manager.playbackController().running()) return;
switch (m_mouse_mode) {
case Kwave::MouseMark::MouseSelect: {
sample_index_t x = m_offset + pixels2samples(e->pos().x());
m_selection->update(x);
selectRange(m_selection->left(), m_selection->length());
setMouseMode(Kwave::MouseMark::MouseNormal);
hidePosition();
break;
}
case Kwave::MouseMark::MouseInSelection: {
int dmin = KGlobalSettings::dndEventDelay();
if ((e->button() & Qt::LeftButton) &&
((e->pos().x() >= m_mouse_down_x - dmin) ||
(e->pos().x() <= m_mouse_down_x + dmin)) )
{
// deselect if only clicked without moving
sample_index_t pos = m_offset + pixels2samples(e->pos().x());
selectRange(pos, 0);
setMouseMode(Kwave::MouseMark::MouseNormal);
hidePosition();
}
break;
}
default: ;
}
}
//***************************************************************************
SignalWidget::PositionWidget::PositionWidget(QWidget *parent)
:QWidget(parent), m_label(0), m_alignment(0),
m_radius(10), m_arrow_length(30), m_last_alignment(Qt::AlignHCenter),
m_last_size(QSize(0,0)), m_polygon()
{
hide();
m_label = new QLabel(this);
Q_ASSERT(m_label);
if (!m_label) return;
m_label->setFrameStyle(QFrame::Panel | QFrame::Plain);
m_label->setPalette(QToolTip::palette()); // use same colors as a QToolTip
m_label->setFocusPolicy(Qt::NoFocus);
m_label->setMouseTracking(true);
m_label->setLineWidth(0);
setPalette(QToolTip::palette()); // use same colors as a QToolTip
setFocusPolicy(Qt::NoFocus);
setMouseTracking(true);
}
//***************************************************************************
SignalWidget::PositionWidget::~PositionWidget()
{
if (m_label) delete m_label;
m_label = 0;
}
//***************************************************************************
void SignalWidget::PositionWidget::setText(const QString &text,
Qt::Alignment alignment)
{
if (!m_label) return;
m_alignment = alignment;
m_label->setText(text);
m_label->setAlignment(m_alignment);
m_label->resize(m_label->sizeHint());
switch (m_alignment) {
case Qt::AlignLeft:
resize(m_arrow_length + m_radius + m_label->width() + m_radius,
m_radius + m_label->height() + m_radius);
m_label->move(m_arrow_length + m_radius, m_radius);
break;
case Qt::AlignRight:
resize(m_radius + m_label->width() + m_radius + m_arrow_length,
m_radius + m_label->height() + m_radius);
m_label->move(m_radius, m_radius);
break;
case Qt::AlignHCenter:
resize(m_radius + m_label->width() + m_radius,
m_arrow_length + m_radius + m_label->height() + m_radius);
m_label->move(m_radius, m_arrow_length + m_radius);
break;
default:
;
}
updateMask();
}
//***************************************************************************
bool SignalWidget::PositionWidget::event(QEvent *e)
{
if (!e) return false;
// ignore any kind of event that might be of interest
// for the parent widget (in our case the SignalWidget)
switch (e->type()) {
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseButtonDblClick:
case QEvent::MouseMove:
case QEvent::KeyPress:
case QEvent::KeyRelease:
case QEvent::Shortcut:
case QEvent::Wheel:
case QEvent::Clipboard:
case QEvent::Speech:
case QEvent::DragEnter:
case QEvent::DragMove:
case QEvent::DragLeave:
case QEvent::Drop:
case QEvent::DragResponse:
case QEvent::TabletMove:
case QEvent::TabletPress:
case QEvent::TabletRelease:
return false;
default:
;
}
// everything else: let it be handled by QLabel
return QWidget::event(e);
}
//***************************************************************************
void SignalWidget::PositionWidget::updateMask()
{
// bail out if nothing has changed
if ((size() == m_last_size) && (m_alignment == m_last_alignment))
return;
QPainter p;
QBitmap bmp(size());
bmp.fill(Qt::color0);
p.begin(&bmp);
QBrush brush(Qt::color1);
p.setBrush(brush);
p.setPen(Qt::color1);
const int h = height();
const int w = width();
// re-create the polygon, depending on alignment
switch (m_alignment) {
case Qt::AlignLeft:
m_polygon.setPoints(8,
m_arrow_length, 0,
w-1, 0,
w-1, h-1,
m_arrow_length, h-1,
m_arrow_length, 2*h/3,
0, h/2,
m_arrow_length, h/3,
m_arrow_length, 0
);
break;
case Qt::AlignRight:
m_polygon.setPoints(8,
0, 0,
w-1-m_arrow_length, 0,
w-1-m_arrow_length, h/3,
w-1, h/2,
w-1-m_arrow_length, 2*h/3,
w-1-m_arrow_length, h-1,
0, h-1,
0, 0
);
break;
case Qt::AlignHCenter:
break;
default:
;
}
p.drawPolygon(m_polygon);
p.end();
// activate the new widget mask
clearMask();
setMask(bmp);
// remember size/alignment for detecing changes
m_last_alignment = m_alignment;
m_last_size = size();
}
//***************************************************************************
void SignalWidget::PositionWidget::paintEvent(QPaintEvent *)
{
QPainter p(this);
p.setBrush(palette().background().color());
p.drawPolygon(m_polygon);
}
//***************************************************************************
void SignalWidget::showPosition(const QString &text, sample_index_t pos,
double ms, const QPoint &mouse)
{
int x = mouse.x();
int y = mouse.y();
// x/y == -1/-1 -> reset/hide the position
if ((x < 0) && (y < 0)) {
m_position_widget_timer.stop();
m_position_widget.hide();
return;
}
setUpdatesEnabled(false);
m_position_widget.hide();
unsigned int t, h, m, s, tms;
t = static_cast<unsigned int>(rint(ms * 10.0));
tms = t % 10000;
t /= 10000;
s = t % 60;
t /= 60;
m = t % 60;
t /= 60;
h = t;
QString hms;
hms.sprintf("%02u:%02u:%02u.%04u", h, m, s, tms);
QString txt = QString("%1\n%2\n%3").arg(text).arg(pos).arg(hms);
switch (selectionPosition(mouse.x()) & ~Selection) {
case LeftBorder:
m_position_widget.setText(txt, Qt::AlignRight);
x = samples2pixels(pos - m_offset) - m_position_widget.width();
if (x < 0) {
// switch to left aligned mode
m_position_widget.setText(txt, Qt::AlignLeft);
x = samples2pixels(pos - m_offset);
}
break;
case RightBorder:
default:
m_position_widget.setText(txt, Qt::AlignLeft);
x = samples2pixels(pos - m_offset);
if (x + m_position_widget.width() > width()) {
// switch to right aligned mode
m_position_widget.setText(txt, Qt::AlignRight);
x = samples2pixels(pos - m_offset) - m_position_widget.width();
}
break;
}
// adjust the position to avoid vertical clipping
int lh = m_position_widget.height();
if (y - lh/2 < 0) {
y = 0;
} else if (y + lh/2 > height()) {
y = height() - lh;
} else {
y -= lh/2;
}
m_position_widget.move(x, y);
if (!m_position_widget.isVisible())
m_position_widget.show();
m_position_widget_timer.stop();
m_position_widget_timer.setSingleShot(true);
m_position_widget_timer.start(POSITION_WIDGET_TIME);
setUpdatesEnabled(true);
}
//***************************************************************************
void SignalWidget::mouseMoveEvent(QMouseEvent *e)
{
Q_ASSERT(e);
Q_ASSERT(m_selection);
Q_ASSERT(m_width);
if (!e) return;
if (!m_selection) return;
if (!m_width) return;
// abort if no signal is loaded
if (!m_signal_manager.length()) return;
// there seems to be a BUG in Qt, sometimes e->pos() produces flicker/wrong
// coordinates on the start of a fast move!?
// globalPos() seems not to have this effect
int mouse_x = mapFromGlobal(e->globalPos()).x();
int mouse_y = mapFromGlobal(e->globalPos()).y();
if (mouse_x < 0) mouse_x = 0;
if (mouse_y < 0) mouse_y = 0;
if (mouse_x >= width()) mouse_x = width() - 1;
if (mouse_y >= height()) mouse_y = height() - 1;
QPoint pos(mouse_x, mouse_y);
// bail out if the position did not change
static int last_x = -1;
static int last_y = -1;
if ((mouse_x == last_x) && (mouse_y == last_y))
return;
last_x = mouse_x;
last_y = mouse_y;
switch (m_mouse_mode) {
case Kwave::MouseMark::MouseSelect: {
// in move mode, a new selection was created or an old one grabbed
// this does the changes with every mouse move...
unsigned int x = m_offset + pixels2samples(mouse_x);
m_selection->update(x);
selectRange(m_selection->left(), m_selection->length());
showPosition(i18n("Selection"), x, samples2ms(x), pos);
break;
}
default: {
unsigned int first = m_signal_manager.selection().first();
unsigned int last = m_signal_manager.selection().last();
Label label = findLabelNearMouse(mouse_x);
// find out what is nearer: label or selection border ?
if (!label.isNull() && (first != last) && isSelectionBorder(mouse_x)) {
const unsigned int pos = m_offset + pixels2samples(mouse_x);
const unsigned int d_label = (pos > label.pos()) ?
(pos - label.pos()) : (label.pos() - pos);
const unsigned int d_left = (pos > first) ?
(pos - first) : (first - pos);
const unsigned int d_right = (pos > last) ?
(pos - last) : (last - pos);
if ( ((d_label ^ 2) > (d_left ^ 2)) &&
((d_label ^ 2) > (d_right ^ 2)) )
{
// selection borders are nearer
label = Label();
}
}
// yes, this code gives the nifty cursor change....
if (!label.isNull()) {
setMouseMode(Kwave::MouseMark::MouseAtSelectionBorder);
int index = m_signal_manager.labelIndex(label);
QString text = (label.name().length()) ?
i18n("Label #%1 (%2)", index, label.name()) :
i18n("Label #%1", index);
showPosition(text, label.pos(), samples2ms(label.pos()), pos);
break;
} else if ((first != last) && isSelectionBorder(mouse_x)) {
setMouseMode(Kwave::MouseMark::MouseAtSelectionBorder);
switch (selectionPosition(mouse_x) & ~Selection) {
case LeftBorder:
showPosition(i18n("Selection, left border"),
first, samples2ms(first), pos);
break;
case RightBorder:
showPosition(i18n("Selection, right border"),
last, samples2ms(last), pos);
break;
default:
hidePosition();
}
} else if (isInSelection(mouse_x)) {
setMouseMode(Kwave::MouseMark::MouseInSelection);
hidePosition();
int dmin = KGlobalSettings::dndEventDelay();
if ((e->buttons() & Qt::LeftButton) &&
((mouse_x < m_mouse_down_x - dmin) ||
(mouse_x > m_mouse_down_x + dmin)) )
{
startDragging();
}
} else {
setMouseMode(Kwave::MouseMark::MouseNormal);
hidePosition();
}
}
}
}
//***************************************************************************
void SignalWidget::wheelEvent(QWheelEvent *event)
{
if (!event) return;
// we currently are only interested in <Alt> + <WheelUp/Down>
if (event->modifiers() != Qt::AltModifier) {
event->ignore();
return;
}
if ((event->delta() > 0) && (m_vertical_zoom < VERTICAL_ZOOM_MAX)) {
// zom in
m_vertical_zoom *= VERTICAL_ZOOM_STEP_FACTOR;
if (m_vertical_zoom > VERTICAL_ZOOM_MAX)
m_vertical_zoom = VERTICAL_ZOOM_MAX;
event->accept();
refreshSignalLayer();
} else if ((event->delta() < 0) && (m_vertical_zoom > VERTICAL_ZOOM_MIN)) {
// zoom out
m_vertical_zoom /= VERTICAL_ZOOM_STEP_FACTOR;
if (m_vertical_zoom < VERTICAL_ZOOM_MIN)
m_vertical_zoom = VERTICAL_ZOOM_MIN;
event->accept();
refreshSignalLayer();
} else {
// no change
event->ignore();
}
}
//***************************************************************************
void SignalWidget::paintEvent(QPaintEvent *)
{
InhibitRepaintGuard inhibit(*this, false); // avoid recursion
// qDebug("SignalWidget::paintEvent()");
// #define DEBUG_REPAINT_TIMES
#ifdef DEBUG_REPAINT_TIMES
QTime time;
time.start();
#endif /* DEBUG_REPAINT_TIMES */
QPainter p;
int n_tracks = m_signal_manager.isClosed() ? 0 : tracks();
m_width = QWidget::width();
m_height = QWidget::height();
// qDebug("SignalWidget::paintEvent(): width=%d, height=%d",m_width,m_height);
// --- detect size changes and refresh the whole display ---
if ((m_width != m_last_width) || (m_height != m_last_height)) {
// qDebug("SignalWidget::paintEvent(): window size changed from "
// "%dx%d to %dx%d",lastWidth,lastHeight,m_width,m_height);
for (int i=0; i<3; i++) {
m_layer[i] = QImage(m_width, m_height,
QImage::Format_ARGB32_Premultiplied);
m_update_layer[i] = true;
}
m_image = QImage(m_width, m_height,
QImage::Format_ARGB32_Premultiplied);
m_last_width = m_width;
m_last_height = m_height;
// check and correct m_zoom and m_offset
setZoom(m_zoom);
}
// --- repaint of the signal layer ---
if (m_update_layer[LAYER_SIGNAL]) {
// qDebug("SignalWidget::paintEvent(): - redraw of signal layer -");
int track_height = (n_tracks) ? (m_height / n_tracks) : 0;
int top = 0;
p.begin(&m_layer[LAYER_SIGNAL]);
// all black if empty
if (!n_tracks)
p.fillRect(0, 0, m_width, m_height, Qt::black);
foreach (Kwave::TrackPixmap *pix, m_track_pixmaps) {
if (!pix) continue; // signal closed ?
// fix the width and height of the track pixmap
if ((pix->width() != m_width) || (pix->height() != track_height))
pix->resize(m_width, track_height);
pix->setVerticalZoom(m_vertical_zoom);
if (pix->isModified())
pix->repaint();
p.setCompositionMode(QPainter::CompositionMode_Source);
p.drawPixmap(0, top, pix->pixmap());
top += track_height;
}
p.end();
m_update_layer[LAYER_SIGNAL] = false;
}
// --- repaint of the markers layer ---
if (m_update_layer[LAYER_MARKERS]) {
// qDebug("SignalWidget::paintEvent(): - redraw of markers layer -");
p.begin(&m_layer[LAYER_MARKERS]);
p.fillRect(0, 0, m_width, m_height, Qt::black);
int last_marker = -1;
foreach (const Label label, labels()) {
unsigned int pos = label.pos();
if (pos < m_offset) continue; // outside left
int x = samples2pixels(pos - m_offset);
if (x >= m_width) continue; // outside right
// position must differ from the last one, otherwise we
// would wipe out the last one with XOR mode
if (x == last_marker) continue;
p.setPen(Qt::cyan);
p.setCompositionMode(QPainter::CompositionMode_Exclusion);
p.drawLine(x, 0, x, m_height);
last_marker = x;
}
p.end();
m_update_layer[LAYER_MARKERS] = false;
}
// --- repaint of the selection layer ---
if (m_update_layer[LAYER_SELECTION]) {
// qDebug("SignalWidget::paintEvent(): - redraw of selection layer -");
p.begin(&m_layer[LAYER_SELECTION]);
p.fillRect(0, 0, m_width, m_height, Qt::black);
if (n_tracks) {
unsigned int left = m_signal_manager.selection().first();
unsigned int right = m_signal_manager.selection().last();
if ((right > m_offset) && (left < m_offset+pixels2samples(m_width))) {
// transform to pixel coordinates
if (left < m_offset) left = m_offset;
left = samples2pixels(left - m_offset);
right = samples2pixels(right - m_offset);
if (right >= static_cast<unsigned int>(m_width))
right=m_width-1;
if (left > right)
left = right;
p.setPen(Qt::yellow);
if (left == right) {
p.drawLine(left, 0, left, m_height);
} else {
p.setBrush(Qt::yellow);
p.drawRect(left, 0, right-left+1, m_height);
}
}
}
p.end();
m_update_layer[LAYER_SELECTION] = false;
}
// bitBlt all layers together
p.begin(&m_image);
p.fillRect(0, 0, m_width, m_height, Qt::black);
const QPainter::CompositionMode layer_rop[3] = {
QPainter::CompositionMode_Source, /* LAYER_SIGNAL */
QPainter::CompositionMode_Exclusion, /* LAYER_SELECTION */
QPainter::CompositionMode_Exclusion /* LAYER_MARKERS */
};
for (int i=0; i < 3; i++) {
p.setCompositionMode(layer_rop[i]);
p.drawImage(0, 0, m_layer[i]);
}
m_last_playpointer = -2;
// --- redraw the playpointer if a signal is present ---
m_playpointer = samples2pixels(
m_signal_manager.playbackController().currentPos() - m_offset);
if (n_tracks) {
p.setPen(Qt::yellow);
p.setCompositionMode(QPainter::CompositionMode_Exclusion);
if (m_last_playpointer >= 0)
p.drawLine(m_last_playpointer, 0, m_last_playpointer, m_height);
if ( (m_signal_manager.playbackController().running() ||
m_signal_manager.playbackController().paused() ) &&
((m_playpointer >= 0) && (m_playpointer < m_width)) )
{
p.drawLine(m_playpointer, 0, m_playpointer, m_height);
m_last_playpointer = m_playpointer;
} else {
m_last_playpointer = -1;
}
}
p.end();
// draw the result
p.begin(this);
p.drawImage(0, 0, m_image);
p.end();
#ifdef DEBUG_REPAINT_TIMES
qDebug("SignalWidget::paintEvent() -- done, t=%d ms --", time.elapsed());
#endif /* DEBUG_REPAINT_TIMES */
}
//***************************************************************************
sample_index_t SignalWidget::ms2samples(double ms)
{
return static_cast<sample_index_t>(
rint(ms * m_signal_manager.rate() / 1E3));
}
//***************************************************************************
double SignalWidget::samples2ms(sample_index_t samples)
{
double rate = m_signal_manager.rate();
if (rate == 0.0) return 0.0;
return static_cast<double>(samples) * 1E3 / rate;
}
//***************************************************************************
sample_index_t SignalWidget::pixels2samples(int pixels) const
{
if ((pixels < 0) || (m_zoom <= 0.0)) return 0;
return static_cast<unsigned int>(rint(
static_cast<double>(pixels) * m_zoom));
}
//***************************************************************************
int SignalWidget::samples2pixels(sample_index_t samples) const
{
if (m_zoom == 0.0) return 0;
return static_cast<int>(rint(static_cast<double>(samples) / m_zoom));
}
//***************************************************************************
int SignalWidget::displaySamples()
{
return pixels2samples(width()-1);
}
//***************************************************************************
Label SignalWidget::findLabelNearMouse(int x) const
{
const int tol = SELECTION_TOLERANCE;
sample_index_t pos = m_offset + pixels2samples(x);
Label nearest;
sample_index_t dmin = pixels2samples(SELECTION_TOLERANCE) + 1;
foreach (Label label, labels()) {
unsigned int lp = label.pos();
if (lp < m_offset) continue; // outside left
int lx = samples2pixels(lp - m_offset);
if (lx >= m_width) continue; // outside right
if ((lx + tol < x) || (lx > x + tol))
continue; // out of tolerance
sample_index_t dist = (pos > lp) ? (pos - lp) : (lp - pos);
if (dist < dmin) {
// found a new "nearest" label
dmin = dist;
nearest = label;
}
}
return nearest;
}
//***************************************************************************
void SignalWidget::addLabel(sample_index_t pos)
{
UndoTransactionGuard undo(m_signal_manager, i18n("Add Label"));
// add a new label, with undo
if (!m_signal_manager.addLabel(pos)) {
m_signal_manager.abortUndoTransaction();
return;
}
// find the new label
Label label = m_signal_manager.findLabel(pos);
if (label.isNull()) return;
// edit the properties of the new label
if (!labelProperties(label)) {
// aborted or failed -> delete (without undo)
int index = m_signal_manager.labelIndex(label);
m_signal_manager.deleteLabel(index, false);
m_signal_manager.abortUndoTransaction();
}
refreshMarkersLayer();
hidePosition();
}
////****************************************************************************
//void SignalWidget::loadLabel()
//{
// labels().clear(); //remove old Labels...
// appendLabel ();
//}
//
////****************************************************************************
//void SignalWidget::saveLabel (const char *typestring)
//{
// QString name = KFileDialog::getSaveFileName (0, "*.label", this);
// if (!name.isNull()) {
// FILE *out;
// out = fopen (name.local8Bit(), "w");
//
// Parser parser (typestring);
// Label *tmp;
// LabelType *act;
//
// const char *actstring = parser.getFirstParam();
//
// while (actstring) {
// printf ("selecting %s\n", actstring);
// for (act = globals.markertypes.first(); act; act = globals.markertypes.next())
// if (strcmp(act->name, actstring) == 0) {
// printf ("selected\n");
// act->selected = true;
// break;
// }
// actstring = parser.getNextParam();
// }
//
// for (act = globals.markertypes.first(); act; act = globals.markertypes.next())
// //write out all selected label types
// if (act->selected)
// fprintf (out, "%s\n", act->getCommand());
//
// //ended writing of types, so go on with the labels...
//
// for (tmp = labels().first(); tmp; tmp = labels().next()) //write out labels
// {
// fprintf (out, tmp->getCommand());
// fprintf (out, "\n");
// }
//
// fclose (out);
// }
//}
//***************************************************************************
bool SignalWidget::labelProperties(Label &label)
{
if (label.isNull()) return false;
int index = m_signal_manager.labelIndex(label);
Q_ASSERT(index >= 0);
if (index < 0) return false;
// try to modify the label. just in case that the user moves it
// to a position where we already have one, catch this situation
// and ask if he wants to abort, re-enter the label properties
// dialog or just replace (remove) the label at the target position
bool accepted;
sample_index_t new_pos = label.pos();
QString new_name = label.name();
int old_index = -1;
while (true) {
// create and prepare the dialog
LabelPropertiesWidget *dlg = new LabelPropertiesWidget(this);
Q_ASSERT(dlg);
if (!dlg) return false;
dlg->setLabelIndex(index);
dlg->setLabelPosition(new_pos, m_signal_manager.length(),
m_signal_manager.rate());
dlg->setLabelName(new_name);
// execute the dialog
accepted = (dlg->exec() == QDialog::Accepted);
if (!accepted) {
// user pressed "cancel"
delete dlg;
break;
}
// if we get here the user pressed "OK"
new_pos = dlg->labelPosition();
new_name = dlg->labelName();
dlg->saveSettings();
delete dlg;
// check: if there already is a label at the new position
// -> ask the user if he wants to overwrite that one
if ((new_pos != label.pos()) &&
!m_signal_manager.findLabel(new_pos).isNull())
{
int res = Kwave::MessageBox::warningYesNoCancel(this, i18n(
"There already is a label at the position "\
"you have chosen.\n"\
"Do you want to replace it?"));
if (res == KMessageBox::Yes) {
// delete the label at the target position (with undo)
Label old = m_signal_manager.findLabel(new_pos);
old_index = m_signal_manager.labelIndex(old);
break;
}
if (res == KMessageBox::No) {
// make another try -> re-enter the dialog
continue;
}
// cancel -> abort the whole action
accepted = false;
break;
} else {
// ok, we can put it there
break;
}
}
if (accepted) {
// shortcut: abort if nothing has changed
if ((new_name == label.name()) && (new_pos == label.pos()))
return false;
UndoTransactionGuard undo(m_signal_manager, i18n("Modify Label"));
// if there is a label at the target position, remove it first
if (old_index >= 0) {
m_signal_manager.deleteLabel(old_index, true);
// this might have changed the current index!
index = m_signal_manager.labelIndex(label);
}
// modify the label through the signal manager
if (!m_signal_manager.modifyLabel(index, new_pos, new_name)) {
// position is already occupied
m_signal_manager.abortUndoTransaction();
return false;
}
// reflect the change in the passed label
label.moveTo(new_pos);
label.rename(new_name);
// NOTE: moving might also change the index, so the complete
// markers layer has to be refreshed
refreshMarkersLayer();
}
else
m_signal_manager.abortUndoTransaction();
return accepted;
}
////****************************************************************************
//void SignalWidget::jumptoLabel ()
// another fine function contributed by Gerhard Zintel
// if lmarker == rmarker (no range selected) cursor jumps to the nearest label
// if lmarker < rmarker (range is selected) lmarker jumps to next lower label or zero
// rmarker jumps to next higher label or end
//{
// if (signalmanage) {
// int lmarker = signalmanage->getLMarker();
// int rmarker = signalmanage->getRMarker();
// bool RangeSelected = (rmarker - lmarker) > 0;
// if (!labels().isEmpty()) {
// Label *tmp;
// int position = 0;
// for (tmp = labels->first(); tmp; tmp = labels->next())
// if (RangeSelected) {
// if (tmp->pos < lmarker)
// if (qAbs(lmarker - position) >
// qAbs(lmarker - ms2samples(tmp->pos)))
// position = ms2samples(tmp->pos);
// } else if (qAbs(lmarker - position) >
// qAbs(lmarker - ms2samples(tmp->pos)))
// position = ms2samples(tmp->pos);
//
// lmarker = position;
// position = signalmanage->getLength();
// for (tmp = labels->first(); tmp; tmp = labels->next())
// if (tmp->pos > rmarker)
// if (qAbs(rmarker - position) >
// qAbs(rmarker - ms2samples(tmp->pos)))
// position = ms2samples(tmp->pos);
// rmarker = position;
// if (RangeSelected) setRange(lmarker, rmarker);
// else setRange (lmarker, lmarker);
// refresh ();
// }
// }
//}
//
////****************************************************************************
//void SignalWidget::savePeriods ()
//{
// if (signalmanage) {
// Dialog *dialog =
// DynamicLoader::getDialog ("marksave", new DialogOperation(&globals, signalmanage->getRate(), 0, 0));
//
// if ((dialog) && (dialog->exec())) {
// selectMarkers (dialog->getCommand());
//
// LabelType *act;
// Label *tmp;
// int last = 0;
// int rate = signalmanage->getRate ();
//
// QString name = KFileDialog::getSaveFileName (0, "*.dat", this);
// if (!name.isNull()) {
// QFile out(name.local8Bit());
// char buf[160];
// float freq = 0, time, lastfreq = 0;
// out.open (QIODevice::WriteOnly);
// int first = true;
//
// for (act = globals.markertypes.first(); act; act = globals.markertypes.next())
// //write only selected label type
// if (act->selected)
// //traverse list of all labels
// for (tmp = labels->first(); tmp; tmp = labels->next()) {
// if (tmp->getType() == act) {
// freq = tmp->pos - last;
// time = last * 1000 / rate;
//
// if ((!first) && (freq != lastfreq)) {
// lastfreq = freq;
// freq = 1 / (freq / rate);
// snprintf (buf, sizeof(buf), "%f %f\n",
// time, freq);
// out.writeBlock (&buf[0], strlen(buf));
// } else lastfreq = freq;
// first = false;
// last = ms2samples(tmp->pos);
// }
// }
//
// if (!first) //make sure last tone gets its length
// {
// time = last * 1000 / rate;
// snprintf (buf, sizeof(buf), "%f %f\n", time, freq);
// out.writeBlock (&buf[0], strlen(buf));
// }
//
// out.close ();
// }
// }
// }
//}
////****************************************************************************
//void SignalWidget::markSignal (const char *str)
//{
// if (signalmanage) {
// Label *newmark;
//
// Parser parser (str);
//
// int level = (int) (parser.toDouble() / 100 * (1 << 23));
//
// int len = signalmanage->getLength();
// int *sam = signalmanage->getSignal(0)->getSample(); // ### @@@ ###
// LabelType *start = findMarkerType(parser.getNextParam());
// LabelType *stop = findMarkerType (parser.getNextParam());
// int time = (int) (parser.toDouble () * signalmanage->getRate() / 1000);
//
// printf ("%d %d\n", level, time);
// printf ("%s %s\n", start->name, stop->name);
//
// ProgressDialog *dialog =
// new ProgressDialog (len, "Searching for Signal portions...");
//
// if (dialog && start && stop) {
// dialog->show();
//
// newmark = new Label(0, start); //generate initial Label
//
// labels->inSort (newmark);
//
// for (int i = 0; i < len; i++) {
// if (qAbs(sam[i]) < level) {
// int j = i;
// while ((i < len) && (qAbs(sam[i]) < level)) i++;
//
// if (i - j > time) {
// //insert labels...
// newmark = new Label(i, start);
// labels->inSort (newmark);
//
// if (start != stop) {
// newmark = new Label(j, stop);
// labels->inSort (newmark);
// }
// }
// }
// dialog->setProgress (i);
// }
//
// newmark = new Label(len - 1, stop);
// labels->inSort (newmark);
//
// refresh ();
// delete dialog;
// }
// }
//}
//
////****************************************************************************
//void SignalWidget::markPeriods (const char *str)
//{
// if (signalmanage) {
// Parser parser (str);
//
// int high = signalmanage->getRate() / parser.toInt();
// int low = signalmanage->getRate() / parser.toInt();
// int octave = parser.toBool ("true");
// double adjust = parser.toDouble ();
//
// for (int i = 0; i < AUTOKORRWIN; i++)
// autotable[i] = 1 - (((double)i * i * i) / (AUTOKORRWIN * AUTOKORRWIN * AUTOKORRWIN)); //generate static weighting function
//
// if (octave) for (int i = 0; i < AUTOKORRWIN; i++) weighttable[i] = 1; //initialise moving weight table
//
// Label *newmark;
// int next;
// int len = signalmanage->getLength();
// int *sam = signalmanage->getSignal(0)->getSample(); // ### @@@ ###
// LabelType *start = markertype;
// int cnt = findFirstMark (sam, len);
//
// ProgressDialog *dialog = new ProgressDialog (len - AUTOKORRWIN, "Correlating Signal to find Periods:");
// if (dialog) {
// dialog->show();
//
// newmark = new Label(cnt, start);
// labels->inSort (newmark);
//
// while (cnt < len - 2*AUTOKORRWIN) {
// if (octave)
// next = findNextRepeatOctave (&sam[cnt], high, adjust);
// else
// next = findNextRepeat (&sam[cnt], high);
//
// if ((next < low) && (next > high)) {
// newmark = new Label(cnt, start);
//
// labels->inSort (newmark);
// }
// if (next < AUTOKORRWIN) cnt += next;
// else
// if (cnt < len - AUTOKORRWIN) {
// int a = findFirstMark (&sam[cnt], len - cnt);
// if (a > 0) cnt += a;
// else cnt += high;
// } else cnt = len;
//
// dialog->setProgress (cnt);
// }
//
// delete dialog;
//
// refresh ();
// }
// }
//}
////*****************************************************************************
//int findNextRepeat (int *sample, int high)
////autocorellation of a windowed part of the sample
////returns length of period, if found
//{
// int i, j;
// double gmax = 0, max, c;
// int maxpos = AUTOKORRWIN;
// int down, up; //flags
//
// max = 0;
// for (j = 0; j < AUTOKORRWIN; j++)
// gmax += ((double)sample[j]) * sample [j];
//
// //correlate signal with itself for finding maximum integral
//
// down = 0;
// up = 0;
// i = high;
// max = 0;
// while (i < AUTOKORRWIN) {
// c = 0;
// for (j = 0; j < AUTOKORRWIN; j++) c += ((double)sample[j]) * sample [i + j];
// c = c * autotable[i]; //multiply window with weight for preference of high frequencies
// if (c > max) max = c, maxpos = i;
// i++;
// }
// return maxpos;
//}
//
////*****************************************************************************
//int findNextRepeatOctave (int *sample, int high, double adjust = 1.005)
////autocorellation of a windowed part of the sample
////same as above only with an adaptive weighting to decrease fast period changes
//{
// int i, j;
// double gmax = 0, max, c;
// int maxpos = AUTOKORRWIN;
// int down, up; //flags
//
// max = 0;
// for (j = 0; j < AUTOKORRWIN; j++)
// gmax += ((double)sample[j]) * sample [j];
//
// //correlate signal with itself for finding maximum integral
//
// down = 0;
// up = 0;
// i = high;
// max = 0;
// while (i < AUTOKORRWIN) {
// c = 0;
// for (j = 0; j < AUTOKORRWIN; j++) c += ((double)sample[j]) * sample [i + j];
// c = c * autotable[i] * weighttable[i];
// //multiply window with weight for preference of high frequencies
// if (c > max) max = c, maxpos = i;
// i++;
// }
//
// for (int i = 0; i < AUTOKORRWIN; i++) weighttable[i] /= adjust;
//
// weighttable[maxpos] = 1;
// weighttable[maxpos + 1] = .9;
// weighttable[maxpos - 1] = .9;
// weighttable[maxpos + 2] = .8;
// weighttable[maxpos - 2] = .8;
//
// float buf[7];
//
// for (int i = 0; i < 7; buf[i++] = .1)
//
// //low pass filter
// for (int i = high; i < AUTOKORRWIN - 3; i++) {
// buf[i % 7] = weighttable[i + 3];
// weighttable[i] = (buf[0] + buf[1] + buf[2] + buf[3] + buf[4] + buf[5] + buf[6]) / 7;
// }
//
// return maxpos;
//}
//
//*****************************************************************************
//int findFirstMark (int *sample, int len)
////finds first sample that is non-zero, or one that preceeds a zero crossing
//{
// int i = 1;
// int last = sample[0];
// int act = last;
// if ((last < 100) && (last > -100)) i = 0;
// else
// while (i < len) {
// act = sample[i];
// if ((act < 0) && (last >= 0)) break;
// if ((act > 0) && (last <= 0)) break;
// last = act;
// i++;
// }
// return i;
//}
//***************************************************************************
void SignalWidget::playbackStopped()
{
InhibitRepaintGuard inhibit(*this);
}
//***************************************************************************
void SignalWidget::updatePlaybackPointer(sample_index_t)
{
InhibitRepaintGuard inhibit(*this);
}
//***************************************************************************
void SignalWidget::slotTrackInserted(unsigned int index, Track *track)
{
Q_ASSERT(track);
if (!track) return;
// insert a new track into the track pixmap list
Kwave::TrackPixmap *pix = new Kwave::TrackPixmap(*track);
Q_ASSERT(pix);
m_track_pixmaps.insert(index, pix);
if (!pix) return;
// first track: start with full zoom
if (tracks() == 1) zoomAll();
// emit the signal sigTrackInserted now, so that the signal widget
// gets resized if needed, but the new pixmap is still empty
emit sigTrackInserted(index);
pix->setOffset(m_offset);
pix->setZoom(m_zoom);
if (pix->isModified()) refreshSignalLayer();
// connect all signals
connect(pix, SIGNAL(sigModified()),
this, SLOT(refreshSignalLayer()));
connect(track, SIGNAL(sigSelectionChanged(bool)),
this, SIGNAL(sigTrackSelectionChanged()));
connect(track, SIGNAL(sigSelectionChanged(bool)),
this, SLOT(refreshSignalLayer()));
}
//***************************************************************************
void SignalWidget::slotTrackDeleted(unsigned int index)
{
// delete the track from the list
if (static_cast<int>(index) < m_track_pixmaps.count()) {
Kwave::TrackPixmap *pixmap = m_track_pixmaps.takeAt(index);
if (pixmap) delete pixmap;
}
// emit the signal sigTrackInserted now, so that the signal widget
// gets resized if needed, but the new pixmap is still empty
emit sigTrackDeleted(index);
refreshSignalLayer();
}
//***************************************************************************
void SignalWidget::slotSamplesInserted(unsigned int track,
sample_index_t offset, sample_index_t length)
{
// qDebug("SignalWidget(): slotSamplesInserted(%u, %u,%u)", track,
// offset, length);
Q_UNUSED(track);
Q_UNUSED(offset);
Q_UNUSED(length);
// length has changed -> update overview
emit viewInfo(m_offset, pixels2samples(QWidget::width()-1)+1,
m_signal_manager.length());
refreshMarkersLayer();
}
//***************************************************************************
void SignalWidget::slotSamplesDeleted(unsigned int track,
sample_index_t offset, sample_index_t length)
{
// qDebug("SignalWidget(): slotSamplesDeleted(%u, %u...%u)", track,
// offset, offset+length-1);
Q_UNUSED(track);
Q_UNUSED(offset);
Q_UNUSED(length);
// length has changed -> update overview
emit viewInfo(m_offset, pixels2samples(QWidget::width()-1)+1,
m_signal_manager.length());
refreshMarkersLayer();
}
//***************************************************************************
void SignalWidget::slotSamplesModified(unsigned int /*track*/,
sample_index_t /*offset*/, sample_index_t /*length*/)
{
// qDebug("SignalWidget(): slotSamplesModified(%u, %u,%u)", track,
// offset, length);
}
//***************************************************************************
void SignalWidget::startDragging()
{
const unsigned int length = m_signal_manager.selection().length();
if (!length) return;
KwaveDrag *d = new KwaveDrag(this);
Q_ASSERT(d);
if (!d) return;
const sample_index_t first = m_signal_manager.selection().first();
const sample_index_t last = m_signal_manager.selection().last();
const double rate = m_signal_manager.rate();
const unsigned int bits = m_signal_manager.bits();
MultiTrackReader src(Kwave::SinglePassForward, m_signal_manager,
m_signal_manager.selectedTracks(), first, last);
// create the file info
FileInfo info = m_signal_manager.fileInfo();
info.setLength(last - first + 1);
info.setRate(rate);
info.setBits(bits);
info.setTracks(src.tracks());
if (!d->encode(this, src, info)) {
delete d;
return;
}
// start drag&drop, mode is determined automatically
InhibitRepaintGuard inhibit(*this);
UndoTransactionGuard undo(m_signal_manager, i18n("Drag and Drop"));
Qt::DropAction drop = d->exec(Qt::CopyAction | Qt::MoveAction);
if (drop == Qt::MoveAction) {
// deleting also affects the selection !
const sample_index_t f = m_signal_manager.selection().first();
const sample_index_t l = m_signal_manager.selection().last();
const sample_index_t len = l-f+1;
// special case: when dropping into the same widget, before
// the previous selection, the previous range has already
// been moved to the right !
sample_index_t src = first;
if ((d->target() == this) && (f < src)) src += len;
m_signal_manager.deleteRange(src, len,
m_signal_manager.selectedTracks());
// restore the new selection
selectRange((first < f) ? f-len : f, len);
}
}
//***************************************************************************
void SignalWidget::dragEnterEvent(QDragEnterEvent *event)
{
if (!event) return;
if ((event->proposedAction() != Qt::MoveAction) &&
(event->proposedAction() != Qt::CopyAction))
return; /* unsupported action */
if (KwaveFileDrag::canDecode(event->mimeData()))
event->acceptProposedAction();
}
//***************************************************************************
void SignalWidget::dragLeaveEvent(QDragLeaveEvent *)
{
setMouseMode(Kwave::MouseMark::MouseNormal);
}
//***************************************************************************
void SignalWidget::dropEvent(QDropEvent *event)
{
if (!event) return;
if (!event->mimeData()) return;
if (KwaveDrag::canDecode(event->mimeData())) {
UndoTransactionGuard undo(m_signal_manager, i18n("Drag and Drop"));
InhibitRepaintGuard inhibit(*this);
sample_index_t pos = m_offset + pixels2samples(event->pos().x());
sample_index_t len = 0;
if ((len = KwaveDrag::decode(this, event->mimeData(),
m_signal_manager, pos)))
{
// set selection to the new area where the drop was done
selectRange(pos, len);
event->acceptProposedAction();
} else {
qWarning("SignalWidget::dropEvent(%s): failed !", event->format(0));
event->ignore();
}
} else if (event->mimeData()->hasUrls()) {
bool first = true;
foreach (QUrl url, event->mimeData()->urls()) {
QString filename = url.toLocalFile();
QString mimetype = CodecManager::whatContains(filename);
if (CodecManager::canDecode(mimetype)) {
if (first) {
// first dropped URL -> open in this window
emit sigCommand("open(" + filename + ")");
first = false;
} else {
// all others -> open a new window
emit sigCommand("newwindow(" + filename + ")");
}
}
}
}
qDebug("SignalWidget::dropEvent(): done");
setMouseMode(Kwave::MouseMark::MouseNormal);
}
//***************************************************************************
void SignalWidget::dragMoveEvent(QDragMoveEvent* event)
{
if (!event) return;
const int x = event->pos().x();
if ((event->source() == this) && isInSelection(x)) {
// disable drag&drop into the selection itself
// this would be nonsense
sample_index_t left = m_signal_manager.selection().first();
sample_index_t right = m_signal_manager.selection().last();
const sample_index_t w = pixels2samples(m_width);
QRect r(this->rect());
// crop selection to widget borders
if (left < m_offset) left = m_offset;
if (right > m_offset+w) right = m_offset+w-1;
// transform to pixel coordinates
left = samples2pixels(left - m_offset);
right = samples2pixels(right - m_offset);
if (right >= static_cast<unsigned int>(m_width))
right=m_width-1;
if (left > right)
left = right;
r.setLeft(left);
r.setRight(right);
event->ignore(r);
} else if (KwaveDrag::canDecode(event->mimeData())) {
// accept if it is decodeable within the
// current range (if it's outside our own selection)
event->acceptProposedAction();
} else if (KwaveFileDrag::canDecode(event->mimeData())) {
// file drag
event->accept();
} else event->ignore();
}
//***************************************************************************
#include "SignalWidget.moc"
//***************************************************************************
//***************************************************************************