[r12985]: branches / edit_controllers / rosegarden / src / document / RosegardenDocument.cpp Maximize Restore History

Download this file

RosegardenDocument.cpp    2984 lines (2364 with data), 100.8 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
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
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
/*
Rosegarden
A MIDI and audio sequencer and musical notation editor.
Copyright 2000-2012 the Rosegarden development team.
Other copyrights also apply to some parts of this work. Please
see the AUTHORS file and individual file headers for details.
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. See the file
COPYING included with this distribution for more information.
*/
#include "RosegardenDocument.h"
#include "CommandHistory.h"
#include "RoseXmlHandler.h"
#include "GzipFile.h"
#include "base/AudioDevice.h"
#include "base/AudioPluginInstance.h"
#include "base/BaseProperties.h"
#include "base/Clipboard.h"
#include "base/Composition.h"
#include "base/Configuration.h"
#include "base/Device.h"
#include "base/Event.h"
#include "base/Exception.h"
#include "base/Instrument.h"
#include "base/SegmentLinker.h"
#include "base/MidiDevice.h"
#include "base/MidiProgram.h"
#include "base/MidiTypes.h"
#include "base/NotationTypes.h"
#include "base/Profiler.h"
#include "base/RealTime.h"
#include "base/Segment.h"
#include "base/SoftSynthDevice.h"
#include "base/Studio.h"
#include "base/Track.h"
#include "base/XmlExportable.h"
#include "commands/edit/EventQuantizeCommand.h"
#include "commands/notation/NormalizeRestsCommand.h"
#include "commands/segment/AddTracksCommand.h"
#include "commands/segment/SegmentInsertCommand.h"
#include "commands/segment/SegmentRecordCommand.h"
#include "commands/segment/ChangeCompositionLengthCommand.h"
#include "gui/editors/segment/TrackEditor.h"
#include "gui/editors/segment/TrackButtons.h"
#include "gui/general/ClefIndex.h"
#include "gui/application/TransportStatus.h"
#include "gui/application/RosegardenMainWindow.h"
#include "gui/application/RosegardenMainViewWidget.h"
#include "gui/dialogs/UnusedAudioSelectionDialog.h"
#include "gui/editors/segment/compositionview/AudioPreviewThread.h"
#include "gui/editors/segment/TrackLabel.h"
#include "gui/general/EditViewBase.h"
#include "gui/general/GUIPalette.h"
#include "gui/general/ResourceFinder.h"
#include "gui/widgets/StartupLogo.h"
#include "gui/seqmanager/SequenceManager.h"
#include "gui/studio/AudioPluginManager.h"
#include "gui/studio/StudioControl.h"
#include "gui/widgets/CurrentProgressDialog.h"
#include "gui/widgets/ProgressDialog.h"
#include "gui/general/AutoSaveFinder.h"
#include "sequencer/RosegardenSequencer.h"
#include "sound/AudioFile.h"
#include "sound/AudioFileManager.h"
#include "sound/MappedCommon.h"
#include "sound/MappedEventList.h"
#include "sound/MappedDevice.h"
#include "sound/MappedInstrument.h"
#include "sound/MappedEvent.h"
#include "sound/MappedStudio.h"
#include "sound/PluginIdentifier.h"
#include "sound/SoundDriver.h"
#include "sound/Midi.h"
#include "misc/AppendLabel.h"
#include "misc/Debug.h"
#include "misc/Strings.h"
#include "document/Command.h"
#include "misc/ConfigGroups.h"
#include <QApplication>
#include <QSettings>
#include <QMessageBox>
#include <QProcess>
#include <QTemporaryFile>
#include <QByteArray>
#include <QDataStream>
#include <QDialog>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QObject>
#include <QString>
#include <QStringList>
#include <QTextStream>
#include <QWidget>
#include <QPointer>
namespace Rosegarden
{
using namespace BaseProperties;
RosegardenDocument::RosegardenDocument(QWidget *parent,
AudioPluginManager *pluginManager,
bool skipAutoload,
bool clearCommandHistory)
: QObject(parent),
m_modified(false),
m_autoSaved(false),
m_audioPreviewThread(&m_audioFileManager),
m_pluginManager(pluginManager),
m_audioRecordLatency(0, 0),
m_quickMarkerTime(-1),
m_autoSavePeriod(0),
m_beingDestroyed(false),
m_clearCommandHistory(clearCommandHistory)
{
checkSequencerTimer();
//### FIX-qt4-removed:
// m_viewList.setAutoDelete(false);
// m_editViewList.setAutoDelete(false);
connect(CommandHistory::getInstance(), SIGNAL(commandExecuted()),
this, SLOT(slotDocumentModified()));
connect(CommandHistory::getInstance(), SIGNAL(documentRestored()),
this, SLOT(slotDocumentRestored()));
// autoload a new document
if (!skipAutoload) performAutoload();
// now set it up as a "new document"
newDocument();
}
RosegardenDocument::~RosegardenDocument()
{
RG_DEBUG << "~RosegardenDocument()\n";
m_beingDestroyed = true;
m_audioPreviewThread.finish();
m_audioPreviewThread.wait();
deleteEditViews();
// ControlRulerCanvasRepository::clear();
if (m_clearCommandHistory) CommandHistory::getInstance()->clear(); // before Composition is deleted
}
unsigned int
RosegardenDocument::getAutoSavePeriod() const
{
QSettings settings;
settings.beginGroup( GeneralOptionsConfigGroup );
unsigned int ret;
ret = settings.value("autosaveinterval", 60).toUInt();
settings.endGroup(); // corresponding to: settings.beginGroup( GeneralOptionsConfigGroup );
return ret;
}
void RosegardenDocument::attachView(RosegardenMainViewWidget *view)
{
m_viewList.append(view);
}
void RosegardenDocument::detachView(RosegardenMainViewWidget *view)
{
m_viewList.removeOne(view);
}
void RosegardenDocument::attachEditView(EditViewBase *view)
{
m_editViewList.append(view);
}
void RosegardenDocument::detachEditView(EditViewBase *view)
{
// auto-deletion is disabled, as
// the editview detaches itself when being deleted
m_editViewList.removeOne(view);
}
void RosegardenDocument::deleteEditViews()
{
QList<EditViewBase*> views = m_editViewList;
m_editViewList.clear();
for (int i = 0; i < int(views.size()); ++i) {
delete views[i];
}
}
void RosegardenDocument::setAbsFilePath(const QString &filename)
{
m_absFilePath = filename;
}
void RosegardenDocument::setTitle(const QString &_t)
{
m_title = _t;
}
const QString &RosegardenDocument::getAbsFilePath() const
{
return m_absFilePath;
}
const QString& RosegardenDocument::getTitle() const
{
return m_title;
}
void RosegardenDocument::slotUpdateAllViews(RosegardenMainViewWidget *sender)
{
RG_DEBUG << "RosegardenDocument::slotUpdateAllViews" << endl;
for (int i = 0; i < int(m_viewList.size()); ++i ){
if (m_viewList.at(i) != sender) {
// try to fix another crash, though I don't really understand
// exactly what m_viewList is, etc.
if (m_viewList.at(i)) {
m_viewList.at(i)->update();
}
}
}
}
void RosegardenDocument::setModified(bool m)
{
m_modified = m;
RG_DEBUG << "RosegardenDocument[" << this << "]::setModified(" << m << ")\n";
}
void RosegardenDocument::clearModifiedStatus()
{
setModified(false);
setAutoSaved(true);
RG_DEBUG << "RosegardenDocument EMITTING documentModified(false)" << endl;
emit documentModified(false);
}
void RosegardenDocument::slotDocumentModified()
{
RG_DEBUG << "RosegardenDocument::slotDocumentModified()" << endl;
setModified(true);
setAutoSaved(false);
RG_DEBUG << "RosegardenDocument EMITTING documentModified(true)" << endl;
emit documentModified(true);
}
void RosegardenDocument::slotDocumentRestored()
{
RG_DEBUG << "RosegardenDocument::slotDocumentRestored()\n";
setModified(false);
// if we hit the bottom of the undo stack, emit this so the modified flag
// will be cleared from assorted title bars
emit documentModified(false);
}
void
RosegardenDocument::setQuickMarker()
{
RG_DEBUG << "RosegardenDocument::setQuickMarker" << endl;
m_quickMarkerTime = getComposition().getPosition();
}
void
RosegardenDocument::jumpToQuickMarker()
{
RG_DEBUG << "RosegardenDocument::jumpToQuickMarker" << endl;
if (m_quickMarkerTime >= 0)
slotSetPointerPosition(m_quickMarkerTime);
}
QString RosegardenDocument::getAutoSaveFileName()
{
QString filename = getAbsFilePath();
if (filename.isEmpty())
filename = QDir::currentPath() + "/" + getTitle();
//!!! NB this should _not_ use the new TempDirectory class -- that
//!!! is for files that are more temporary than this. Its files
//!!! are cleaned up after a crash, the next time RG is started,
//!!! so they aren't appropriate for recovery purposes.
QString autoSaveFileName = AutoSaveFinder().getAutoSavePath(filename);
RG_DEBUG << "RosegardenDocument::getAutoSaveFilename(): returning "
<< autoSaveFileName
<< endl;
return autoSaveFileName;
}
void RosegardenDocument::slotAutoSave()
{
// RG_DEBUG << "RosegardenDocument::slotAutoSave()\n" << endl;
if (isAutoSaved() || !isModified())
return ;
QString autoSaveFileName = getAutoSaveFileName();
RG_DEBUG << "RosegardenDocument::slotAutoSave() - doc modified - saving '"
<< getAbsFilePath() << "' as "
<< autoSaveFileName << endl;
QString errMsg;
saveDocument(autoSaveFileName, errMsg, true);
}
bool RosegardenDocument::isRegularDotRGFile()
{
return getAbsFilePath().right(3).toLower() == ".rg";
}
bool RosegardenDocument::saveIfModified()
{
RG_DEBUG << "RosegardenDocument::saveIfModified()" << endl;
bool completed = true;
if (!isModified())
return completed;
RosegardenMainWindow *win = (RosegardenMainWindow *)parent();
int wantSave = QMessageBox::warning( dynamic_cast<QWidget*>(win), tr("Rosegarden - Warning"), tr("<qt><p>The current file has been modified.</p><p>Do you want to save it?</p></qt>"), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Cancel );
RG_DEBUG << "wantSave = " << wantSave << endl;
switch (wantSave) {
case QMessageBox::Yes:
if (!isRegularDotRGFile()) {
RG_DEBUG << "RosegardenDocument::saveIfModified() : new or imported file\n";
completed = win->slotFileSaveAs();
} else {
RG_DEBUG << "RosegardenDocument::saveIfModified() : regular file\n";
QString errMsg;
completed = saveDocument(getAbsFilePath(), errMsg);
if (!completed) {
if (!errMsg.isEmpty()) {
QMessageBox::critical( dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), tr("Could not save document at %1\n(%2)").arg(getAbsFilePath()).arg(errMsg));
} else {
QMessageBox::critical( dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), tr("Could not save document at %1").arg( getAbsFilePath() ));
}
}
}
break;
case QMessageBox::No:
// delete the autosave file so it won't annoy
// the user when reloading the file.
QFile::remove
(getAutoSaveFileName());
completed = true;
break;
case QMessageBox::Cancel:
completed = false;
break;
default:
completed = false;
break;
}
if (completed) {
completed = deleteOrphanedAudioFiles(wantSave == QMessageBox::No);
if (completed) {
m_audioFileManager.resetRecentlyCreatedFiles();
}
}
if (completed)
setModified(false);
return completed;
}
bool
RosegardenDocument::deleteOrphanedAudioFiles(bool documentWillNotBeSaved)
{
std::vector<QString> recordedOrphans;
std::vector<QString> derivedOrphans;
if (documentWillNotBeSaved) {
// All audio files recorded or derived in this session are
// about to become orphans
for (std::vector<AudioFile *>::const_iterator i =
m_audioFileManager.begin();
i != m_audioFileManager.end(); ++i) {
if (m_audioFileManager.wasAudioFileRecentlyRecorded((*i)->getId())) {
recordedOrphans.push_back((*i)->getFilename());
}
if (m_audioFileManager.wasAudioFileRecentlyDerived((*i)->getId())) {
derivedOrphans.push_back((*i)->getFilename());
}
}
}
// Whether we save or not, explicitly orphaned (i.e. recorded in
// this session and then unloaded) recorded files are orphans.
// Make sure they are actually unknown to the audio file manager
// (i.e. they haven't been loaded more than once, or reloaded
// after orphaning).
for (std::vector<QString>::iterator i = m_orphanedRecordedAudioFiles.begin();
i != m_orphanedRecordedAudioFiles.end(); ++i) {
bool stillHave = false;
for (std::vector<AudioFile *>::const_iterator j =
m_audioFileManager.begin();
j != m_audioFileManager.end(); ++j) {
if ((*j)->getFilename() == *i) {
stillHave = true;
break;
}
}
if (!stillHave) recordedOrphans.push_back(*i);
}
// Derived orphans get deleted whatever happens
//!!! Should we orphan any file derived during this session that
//is not currently used in a segment? Probably: we have no way to
//reuse them
for (std::vector<QString>::iterator i = m_orphanedDerivedAudioFiles.begin();
i != m_orphanedDerivedAudioFiles.end(); ++i) {
bool stillHave = false;
for (std::vector<AudioFile *>::const_iterator j =
m_audioFileManager.begin();
j != m_audioFileManager.end(); ++j) {
if ((*j)->getFilename() == *i) {
stillHave = true;
break;
}
}
if (!stillHave) derivedOrphans.push_back(*i);
}
for (size_t i = 0; i < derivedOrphans.size(); ++i) {
QFile file(derivedOrphans[i]);
if (!file.remove()) {
std::cerr << "WARNING: Failed to remove orphaned derived audio file \"" << derivedOrphans[i] << std::endl;
}
QFile peakFile(QString("%1.pk").arg(derivedOrphans[i]));
peakFile.remove();
}
m_orphanedDerivedAudioFiles.clear();
if (recordedOrphans.empty())
return true;
if (documentWillNotBeSaved) {
int reply = QMessageBox::warning
(dynamic_cast<QWidget *>(parent()), "Warning",
tr("Delete the %n audio file(s) recorded during the unsaved session?", "", recordedOrphans.size()),
QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel,
QMessageBox::Cancel);
switch (reply) {
case QMessageBox::Yes:
break;
case QMessageBox::No:
return true;
default:
case QMessageBox::Cancel:
return false;
}
} else {
UnusedAudioSelectionDialog *dialog =
new UnusedAudioSelectionDialog
(dynamic_cast<QWidget *>(parent()),
tr("The following audio files were recorded during this session but have been unloaded\nfrom the audio file manager, and so are no longer in use in the document you are saving.\n\nYou may want to clean up these files to save disk space.\n\nPlease select any you wish to delete permanently from the hard disk.\n"),
recordedOrphans);
if (dialog->exec() != QDialog::Accepted) {
delete dialog;
return true;
}
recordedOrphans = dialog->getSelectedAudioFileNames();
delete dialog;
}
if (recordedOrphans.empty())
return true;
QString question =
tr("<qt>About to delete %n audio file(s) permanently from the hard disk.<br>There will be no way to recover the file(s).<br>Are you sure?</qt>", "", recordedOrphans.size());
int reply = QMessageBox::warning(dynamic_cast<QWidget *>(parent()), "Warning", question, QMessageBox::Ok | QMessageBox::Cancel);
if (reply == QMessageBox::Ok) {
for (size_t i = 0; i < recordedOrphans.size(); ++i) {
QFile file(recordedOrphans[i]);
if (!file.remove()) {
QMessageBox::critical(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), tr("File %1 could not be deleted.")
.arg(recordedOrphans[i]));
}
QFile peakFile(QString("%1.pk").arg(recordedOrphans[i]));
peakFile.remove();
}
}
return true;
}
void RosegardenDocument::newDocument()
{
setModified(false);
setAbsFilePath(QString::null);
setTitle(tr("Untitled"));
if (m_clearCommandHistory) CommandHistory::getInstance()->clear();
}
void RosegardenDocument::performAutoload()
{
QString autoloadFile = ResourceFinder().getAutoloadPath();
QFileInfo autoloadFileInfo(autoloadFile);
if (autoloadFile == "" || !autoloadFileInfo.isReadable()) {
std::cerr << "WARNING: RosegardenDocument::performAutoload - "
<< "can't find autoload file - defaulting" << std::endl;
return ;
}
bool permanent = true, squelch = true;
openDocument(autoloadFile, permanent, squelch);
}
bool RosegardenDocument::openDocument(const QString& filename,
bool permanent,
bool squelch,
const char* /*format*/ /*=0*/)
{
RG_DEBUG << "RosegardenDocument::openDocument(" << filename << ")" << endl;
if ( filename.isEmpty() )
return false;
newDocument();
QFileInfo fileInfo(filename);
setTitle(fileInfo.fileName());
// Check if file readable with fileInfo ?
if (!fileInfo.isReadable() || fileInfo.isDir()) {
StartupLogo::hideIfStillThere();
QString msg(tr("Can't open file '%1'").arg(filename));
QMessageBox::warning(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), msg);
return false;
}
//cc 20120508: avoid dereferencing self-deleted progress dialog
//after user has closed it, by using a QPointer
QPointer<ProgressDialog> progressDlg = 0;
if (!squelch) {
progressDlg = new ProgressDialog(tr("Reading file..."),
(QWidget*)parent());
connect(progressDlg, SIGNAL(canceled()),
&m_audioFileManager, SLOT(slotStopPreview()));
CurrentProgressDialog::set(progressDlg);
}
setAbsFilePath(fileInfo.absoluteFilePath());
QString errMsg;
QString fileContents;
bool cancelled = false;
bool okay = GzipFile::readFromFile(filename, fileContents);
if (progressDlg)
progressDlg->show();
if (!okay) errMsg = tr("Could not open Rosegarden file");
else {
okay = xmlParse(fileContents,
errMsg,
progressDlg,
permanent,
cancelled);
}
if (!okay) {
StartupLogo::hideIfStillThere();
QString msg(tr("Error when parsing file '%1': \"%2\"")
.arg(filename)
.arg(errMsg));
if (progressDlg) CurrentProgressDialog::freeze();
QMessageBox::warning(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), msg);
if (progressDlg) {
CurrentProgressDialog::thaw();
progressDlg->close();
}
return false;
} else if (cancelled) {
if (progressDlg) {
progressDlg->close();
}
newDocument();
return false;
}
RG_DEBUG << "RosegardenDocument::openDocument() end - "
<< "m_composition : " << &m_composition
<< " - m_composition->getNbSegments() : "
<< m_composition.getNbSegments()
<< " - m_composition->getDuration() : "
<< m_composition.getDuration() << endl;
if (m_composition.begin() != m_composition.end()) {
RG_DEBUG << "First segment starts at " << (*m_composition.begin())->getStartTime() << endl;
}
if (progressDlg) {
progressDlg->setLabelText(tr("Generating audio previews..."));
progressDlg->setValue(0);
connect(&m_audioFileManager, SIGNAL(setValue(int)),
progressDlg, SLOT(setValue(int)));
}
try {
// generate any audio previews after loading the files
m_audioFileManager.generatePreviews();
} catch (Exception e) {
StartupLogo::hideIfStillThere();
if (progressDlg) CurrentProgressDialog::freeze();
QMessageBox::critical(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), strtoqstr(e.getMessage()));
if (progressDlg) CurrentProgressDialog::thaw();
}
if (isSequencerRunning()) {
RG_DEBUG << "RosegardenDocument::openDocument: Sequencer is running, initialising studio" << endl;
// Initialise the whole studio - faders, plugins etc.
//
initialiseStudio();
} else {
RG_DEBUG << "RosegardenDocument::openDocument: Sequencer is not running" << endl;
}
std::cerr << "RosegardenDocument::openDocument: Successfully opened document \"" << filename << "\"" << std::endl;
if (progressDlg) {
progressDlg->close();
}
return true;
}
void
RosegardenDocument::mergeDocument(RosegardenDocument *doc,
int options)
{
MacroCommand *command = new MacroCommand(tr("Merge"));
timeT time0 = 0;
if (options & MERGE_AT_END) {
time0 = getComposition().getBarEndForTime(getComposition().getDuration());
}
int myMaxTrack = getComposition().getNbTracks();
int yrMinTrack = 0;
int yrMaxTrack = doc->getComposition().getNbTracks();
int yrNrTracks = yrMaxTrack - yrMinTrack + 1;
int firstAlteredTrack = yrMinTrack;
if (options & MERGE_IN_NEW_TRACKS) {
//!!! worry about instruments and other studio stuff later... if at all
command->addCommand(new AddTracksCommand
(&getComposition(),
yrNrTracks,
MidiInstrumentBase,
-1));
firstAlteredTrack = myMaxTrack + 1;
} else if (yrMaxTrack > myMaxTrack) {
command->addCommand(new AddTracksCommand
(&getComposition(),
yrMaxTrack - myMaxTrack,
MidiInstrumentBase,
-1));
}
TrackId firstNewTrackId = getComposition().getNewTrackId();
timeT lastSegmentEndTime = 0;
for (Composition::iterator i = doc->getComposition().begin(), j = i;
i != doc->getComposition().end(); i = j) {
++j;
Segment *s = *i;
timeT segmentEndTime = s->getEndMarkerTime();
int yrTrack = s->getTrack();
Track *t = doc->getComposition().getTrackById(yrTrack);
if (t) yrTrack = t->getPosition();
int myTrack = yrTrack;
if (options & MERGE_IN_NEW_TRACKS) {
myTrack = yrTrack - yrMinTrack + myMaxTrack + 1;
}
doc->getComposition().detachSegment(s);
if (options & MERGE_AT_END) {
s->setStartTime(s->getStartTime() + time0);
segmentEndTime += time0;
}
if (segmentEndTime > lastSegmentEndTime) {
lastSegmentEndTime = segmentEndTime;
}
Track *track = getComposition().getTrackByPosition(myTrack);
TrackId tid = 0;
if (track) tid = track->getId();
else tid = firstNewTrackId + yrTrack - yrMinTrack;
command->addCommand(new SegmentInsertCommand(&getComposition(), s, tid));
}
if (!(options & MERGE_KEEP_OLD_TIMINGS)) {
for (int i = getComposition().getTimeSignatureCount() - 1; i >= 0; --i) {
getComposition().removeTimeSignature(i);
}
for (int i = getComposition().getTempoChangeCount() - 1; i >= 0; --i) {
getComposition().removeTempoChange(i);
}
}
if (options & MERGE_KEEP_NEW_TIMINGS) {
for (int i = 0; i < doc->getComposition().getTimeSignatureCount(); ++i) {
std::pair<timeT, TimeSignature> ts =
doc->getComposition().getTimeSignatureChange(i);
getComposition().addTimeSignature(ts.first + time0, ts.second);
}
for (int i = 0; i < doc->getComposition().getTempoChangeCount(); ++i) {
std::pair<timeT, tempoT> t =
doc->getComposition().getTempoChange(i);
getComposition().addTempoAtTime(t.first + time0, t.second);
}
}
if (lastSegmentEndTime > getComposition().getEndMarker()) {
command->addCommand(new ChangeCompositionLengthCommand
(&getComposition(),
getComposition().getStartMarker(),
lastSegmentEndTime));
}
CommandHistory::getInstance()->addCommand(command);
emit makeTrackVisible(firstAlteredTrack + yrNrTracks/2 + 1);
}
void RosegardenDocument::clearStudio()
{
RosegardenSequencer::getInstance()->clearStudio();
RG_DEBUG << "cleared studio\n";
}
void RosegardenDocument::initialiseStudio()
{
Profiler profiler("initialiseStudio", true);
RG_DEBUG << "RosegardenDocument::initialiseStudio - "
<< "clearing down and initialising" << endl;
clearStudio();
InstrumentList list = m_studio.getAllInstruments();
InstrumentList::iterator it = list.begin();
int audioCount = 0;
BussList busses = m_studio.getBusses();
RecordInList recordIns = m_studio.getRecordIns();
// To reduce the number of DCOP calls at this stage, we put some
// of the float property values in a big list and commit in one
// single call at the end. We can only do this with properties
// that aren't depended on by other port, connection, or non-float
// properties during the initialisation process.
MappedObjectIdList ids;
MappedObjectPropertyList properties;
MappedObjectValueList values;
std::vector<PluginContainer *> pluginContainers;
for (unsigned int i = 0; i < (unsigned int)busses.size(); ++i) {
// first one is master
MappedObjectId mappedId =
StudioControl::createStudioObject(
MappedObject::AudioBuss);
StudioControl::setStudioObjectProperty
(mappedId,
MappedAudioBuss::BussId,
MappedObjectValue(i));
ids.push_back(mappedId);
properties.push_back(MappedAudioBuss::Level);
values.push_back(MappedObjectValue(busses[i]->getLevel()));
ids.push_back(mappedId);
properties.push_back(MappedAudioBuss::Pan);
values.push_back(MappedObjectValue(busses[i]->getPan()) - 100.0);
busses[i]->setMappedId(mappedId);
pluginContainers.push_back(busses[i]);
}
for (size_t i = 0; i < recordIns.size(); ++i) {
MappedObjectId mappedId =
StudioControl::createStudioObject(
MappedObject::AudioInput);
StudioControl::setStudioObjectProperty
(mappedId,
MappedAudioInput::InputNumber,
MappedObjectValue(i));
recordIns[i]->setMappedId(mappedId);
}
for (; it != list.end(); ++it) {
if ((*it)->getType() == Instrument::Audio ||
(*it)->getType() == Instrument::SoftSynth) {
MappedObjectId mappedId =
StudioControl::createStudioObject(
MappedObject::AudioFader);
// Set the object id against the instrument
//
(*it)->setMappedId(mappedId);
/*
cout << "SETTING MAPPED OBJECT ID = " << mappedId
<< " - on Instrument " << (*it)->getId() << endl;
*/
// Set the instrument id against this object
//
StudioControl::setStudioObjectProperty
(mappedId,
MappedObject::Instrument,
MappedObjectValue((*it)->getId()));
// Set the level
//
ids.push_back(mappedId);
properties.push_back(MappedAudioFader::FaderLevel);
values.push_back(MappedObjectValue((*it)->getLevel()));
// Set the record level
//
ids.push_back(mappedId);
properties.push_back(MappedAudioFader::FaderRecordLevel);
values.push_back(MappedObjectValue((*it)->getRecordLevel()));
// Set the number of channels
//
ids.push_back(mappedId);
properties.push_back(MappedAudioFader::Channels);
values.push_back(MappedObjectValue((*it)->getAudioChannels()));
// Set the pan - 0 based
//
ids.push_back(mappedId);
properties.push_back(MappedAudioFader::Pan);
values.push_back(MappedObjectValue(float((*it)->getPan())) - 100.0);
// Set up connections: first clear any existing ones (shouldn't
// be necessary, but)
//
StudioControl::disconnectStudioObject(mappedId);
// then handle the output connection
//
BussId outputBuss = (*it)->getAudioOutput();
if (outputBuss < (unsigned int)busses.size()) {
MappedObjectId bmi = busses[outputBuss]->getMappedId();
if (bmi > 0) {
StudioControl::connectStudioObjects(mappedId, bmi);
}
}
// then the input
//
bool isBuss;
int channel;
int input = (*it)->getAudioInput(isBuss, channel);
MappedObjectId rmi = 0;
if (isBuss) {
if (input < int(busses.size())) {
rmi = busses[input]->getMappedId();
}
} else {
if (input < int(recordIns.size())) {
rmi = recordIns[input]->getMappedId();
}
}
ids.push_back(mappedId);
properties.push_back(MappedAudioFader::InputChannel);
values.push_back(MappedObjectValue(channel));
if (rmi > 0) {
StudioControl::connectStudioObjects(rmi, mappedId);
}
pluginContainers.push_back(*it);
audioCount++;
}
}
RG_DEBUG << "RosegardenDocument::initialiseStudio: Have " << pluginContainers.size() << " plugin container(s)" << endl;
for (std::vector<PluginContainer *>::iterator pci =
pluginContainers.begin(); pci != pluginContainers.end(); ++pci) {
// Initialise all the plugins for this Instrument or Buss
for (PluginInstanceIterator pli = (*pci)->beginPlugins();
pli != (*pci)->endPlugins(); ++pli) {
AudioPluginInstance *plugin = *pli;
RG_DEBUG << "Container id " << (*pci)->getId()
<< ", plugin position " << plugin->getPosition()
<< ", identifier " << plugin->getIdentifier()
<< ", assigned " << plugin->isAssigned()
<< endl;
if (plugin->isAssigned()) {
RG_DEBUG << "Found an assigned plugin" << endl;
// Create the plugin slot at the sequencer Studio
//
MappedObjectId pluginMappedId =
StudioControl::createStudioObject(
MappedObject::PluginSlot);
// Create the back linkage from the instance to the
// studio id
//
plugin->setMappedId(pluginMappedId);
RG_DEBUG << "CREATING PLUGIN ID = "
<< pluginMappedId << endl;
// Set the position
StudioControl::setStudioObjectProperty
(pluginMappedId,
MappedObject::Position,
MappedObjectValue(plugin->getPosition()));
// Set the id of this instrument or buss on the plugin
//
StudioControl::setStudioObjectProperty
(pluginMappedId,
MappedObject::Instrument,
(*pci)->getId());
// Set the plugin type id - this will set it up ready
// for the rest of the settings. String value, so can't
// go in the main property list.
//
StudioControl::setStudioObjectProperty
(pluginMappedId,
MappedPluginSlot::Identifier,
plugin->getIdentifier().c_str());
plugin->setConfigurationValue
(qstrtostr(PluginIdentifier::RESERVED_PROJECT_DIRECTORY_KEY),
qstrtostr(getAudioFileManager().getAudioPath()));
// Set opaque string configuration data (e.g. for DSSI plugin)
//
MappedObjectPropertyList config;
for (AudioPluginInstance::ConfigMap::const_iterator
i = plugin->getConfiguration().begin();
i != plugin->getConfiguration().end(); ++i) {
config.push_back(strtoqstr(i->first));
config.push_back(strtoqstr(i->second));
RG_DEBUG << "plugin configuration: " << i->first << " -> "
<< i->second << endl;
}
RG_DEBUG << "plugin configuration: " << config.size() << " values" << endl;
QString error =
StudioControl::setStudioObjectPropertyList
(pluginMappedId,
MappedPluginSlot::Configuration,
config);
if (error != "") {
StartupLogo::hideIfStillThere();
CurrentProgressDialog::freeze();
QMessageBox::warning(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), error);
CurrentProgressDialog::thaw();
}
// Set the bypass
//
ids.push_back(pluginMappedId);
properties.push_back(MappedPluginSlot::Bypassed);
values.push_back(MappedObjectValue(plugin->isBypassed()));
// Set all the port values
//
PortInstanceIterator portIt;
for (portIt = plugin->begin();
portIt != plugin->end(); ++portIt) {
StudioControl::setStudioPluginPort
(pluginMappedId,
(*portIt)->number,
(*portIt)->value);
}
// Set the program
//
if (plugin->getProgram() != "") {
StudioControl::setStudioObjectProperty
(pluginMappedId,
MappedPluginSlot::Program,
strtoqstr(plugin->getProgram()));
}
// Set the post-program port values
//
for (portIt = plugin->begin();
portIt != plugin->end(); ++portIt) {
if ((*portIt)->changedSinceProgramChange) {
StudioControl::setStudioPluginPort
(pluginMappedId,
(*portIt)->number,
(*portIt)->value);
}
}
}
}
}
// Now commit all the remaining changes
StudioControl::setStudioObjectProperties(ids, properties, values);
QSettings settings;
settings.beginGroup( SequencerOptionsConfigGroup );
bool faderOuts = qStrToBool( settings.value("audiofaderouts", "false" ) ) ;
bool submasterOuts = qStrToBool( settings.value("audiosubmasterouts", "false" ) ) ;
unsigned int audioFileFormat = settings.value("audiorecordfileformat", 1).toUInt() ;
settings.endGroup();
MidiByte ports = 0;
if (faderOuts) {
ports |= MappedEvent::FaderOuts;
}
if (submasterOuts) {
ports |= MappedEvent::SubmasterOuts;
}
MappedEvent mEports
(MidiInstrumentBase,
MappedEvent::SystemAudioPorts,
ports);
StudioControl::sendMappedEvent(mEports);
MappedEvent mEff
(MidiInstrumentBase,
MappedEvent::SystemAudioFileFormat,
audioFileFormat);
StudioControl::sendMappedEvent(mEff);
}
SequenceManager *
RosegardenDocument::getSequenceManager()
{
return (dynamic_cast<RosegardenMainWindow*>(parent()))->getSequenceManager();
}
// FILE FORMAT VERSION NUMBERS
//
// These should be updated when the file format changes.
//
// Increment the major version number only for updates so
// substantial that we shouldn't bother even trying to read a file
// saved with a newer major version number than our own.
//
// Increment the minor version number for updates that may break
// compatibility such that we should warn when reading a file
// that was saved with a newer minor version than our own.
//
// Increment the point version number for updates that shouldn't
// break compatibility in either direction, just for informational
// purposes.
//
// When updating major, reset minor to zero; when updating minor,
// reset point to zero.
//
int RosegardenDocument::FILE_FORMAT_VERSION_MAJOR = 1;
int RosegardenDocument::FILE_FORMAT_VERSION_MINOR = 6;
int RosegardenDocument::FILE_FORMAT_VERSION_POINT = 1;
bool RosegardenDocument::saveDocument(const QString& filename,
QString& errMsg,
bool autosave)
{
if (!QFileInfo(filename).exists()) { // safe to write directly
return saveDocumentActual(filename, errMsg, autosave);
}
QTemporaryFile temp(filename + ".");
//!!! was: KTempFile temp(filename + ".", "", 0644); // will be umask'd
temp.setAutoRemove(false);
temp.open(); // This creates the file and opens it atomically
if ( temp.error() ) {
errMsg = tr("Could not create temporary file in directory of '%1': %2").arg(filename).arg(temp.errorString()); //### removed .arg(strerror(status))
return false;
}
QString tempFileName = temp.fileName(); // Must do this before temp.close()
// The temporary file is now open: close it (without removing it)
temp.close();
if( temp.error() ){
//status = temp.status();
errMsg = tr("Failure in temporary file handling for file '%1': %2")
.arg(tempFileName).arg(temp.errorString()); // .arg(strerror(status))
return false;
}
bool success = saveDocumentActual(tempFileName, errMsg, autosave);
if (!success) {
// errMsg should be already set
return false;
}
QDir dir(QFileInfo(tempFileName).dir());
// According to http://doc.trolltech.com/4.4/qdir.html#rename
// some systems fail, if renaming over an existing file.
// Therefore, delete first the existing file.
if (dir.exists(filename)) dir.remove(filename);
if (!dir.rename(tempFileName, filename)) {
errMsg = tr("Failed to rename temporary output file '%1' to desired output file '%2'").arg(tempFileName).arg(filename);
return false;
}
return true;
}
bool RosegardenDocument::saveDocumentActual(const QString& filename,
QString& errMsg,
bool autosave)
{
Profiler profiler("RosegardenDocument::saveDocumentActual");
RG_DEBUG << "RosegardenDocument::saveDocumentActual(" << filename << ")\n";
QString outText;
QTextStream outStream(&outText, QIODevice::WriteOnly);
// outStream.setEncoding(QTextStream::UnicodeUTF8); qt3
outStream.setCodec("UTF-8");
// output XML header
//
outStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
<< "<!DOCTYPE rosegarden-data>\n"
<< "<rosegarden-data version=\"" << VERSION
<< "\" format-version-major=\"" << FILE_FORMAT_VERSION_MAJOR
<< "\" format-version-minor=\"" << FILE_FORMAT_VERSION_MINOR
<< "\" format-version-point=\"" << FILE_FORMAT_VERSION_POINT
<< "\">\n";
ProgressDialog *progress = 0;
// Disable the progress dialog on saving in all cases, because the alternative
// is really complicated, and this progress dialog adds little, if any, value.
//
// if (!autosave) {
//
// progress = new ProgressDialog(tr("Saving file..."),
// (QWidget*)parent());
//
// }
// First make sure all MIDI devices know their current connections
//
m_studio.resyncDeviceConnections();
if (progress) {
progress->setValue(10);
}
// Send out Composition (this includes Tracks, Instruments, Tempo
// and Time Signature changes and any other sub-objects)
//
outStream << strtoqstr(getComposition().toXmlString())
<< endl << endl;
if (progress) {
progress->setValue(20);
}
outStream << strtoqstr(getAudioFileManager().toXmlString())
<< endl << endl;
if (progress) {
progress->setValue(30);
}
outStream << strtoqstr(getConfiguration().toXmlString())
<< endl << endl;
if (progress) {
progress->setValue(40);
}
long totalEvents = 0;
for (Composition::iterator segitr = m_composition.begin();
segitr != m_composition.end(); ++segitr) {
totalEvents += (long)(*segitr)->size();
}
if (progress) {
progress->setValue(50);
}
for (Composition::triggersegmentcontaineriterator ci =
m_composition.getTriggerSegments().begin();
ci != m_composition.getTriggerSegments().end(); ++ci) {
totalEvents += (long)(*ci)->getSegment()->size();
}
if (progress) {
progress->setValue(60);
}
// output all elements
//
// Iterate on segments
long eventCount = 0;
// Put a break in the file
//
outStream << endl << endl;
for (Composition::iterator segitr = m_composition.begin();
segitr != m_composition.end(); ++segitr) {
Segment *segment = *segitr;
if (segment->isLinked()) {
QString attsString = QString("linkerid=\"%1\" ");
attsString += QString("linkertransposechangekey=\"%2\" ");
attsString += QString("linkertransposesteps=\"%3\" ");
attsString += QString("linkertransposesemitones=\"%4\" ");
attsString += QString("linkertransposesegmentback=\"%5\" ");
QString linkedSegAtts = QString(attsString)
.arg(segment->getLinker()->getSegmentLinkerId())
.arg(segment->getLinkTransposeParams().m_changeKey ? "true" :
"false")
.arg(segment->getLinkTransposeParams().m_steps)
.arg(segment->getLinkTransposeParams().m_semitones)
.arg(segment->getLinkTransposeParams().m_transposeSegmentBack
? "true" : "false");
saveSegment(outStream, segment, progress, totalEvents,
eventCount, linkedSegAtts);
} else {
saveSegment(outStream, segment, progress, totalEvents, eventCount);
}
}
if (progress) {
progress->setValue(70);
}
// Put a break in the file
//
outStream << endl << endl;
for (Composition::triggersegmentcontaineriterator ci =
m_composition.getTriggerSegments().begin();
ci != m_composition.getTriggerSegments().end(); ++ci) {
QString triggerAtts = QString
("triggerid=\"%1\" triggerbasepitch=\"%2\" triggerbasevelocity=\"%3\" triggerretune=\"%4\" triggeradjusttimes=\"%5\" ")
.arg((*ci)->getId())
.arg((*ci)->getBasePitch())
.arg((*ci)->getBaseVelocity())
.arg((*ci)->getDefaultRetune())
.arg(strtoqstr((*ci)->getDefaultTimeAdjust()));
Segment *segment = (*ci)->getSegment();
saveSegment(outStream, segment, progress, totalEvents, eventCount, triggerAtts);
}
if (progress) {
progress->setValue(80);
}
// Put a break in the file
//
outStream << endl << endl;
// Send out the studio - a self contained command
//
outStream << strtoqstr(m_studio.toXmlString()) << endl << endl;
if (progress) {
progress->setValue(90);
}
// Send out the appearance data
outStream << "<appearance>" << endl;
outStream << strtoqstr(getComposition().getSegmentColourMap().toXmlString("segmentmap"));
outStream << strtoqstr(getComposition().getGeneralColourMap().toXmlString("generalmap"));
outStream << "</appearance>" << endl << endl << endl;
if (progress) {
progress->setValue(95);
}
// close the top-level XML tag
//
outStream << "</rosegarden-data>\n";
bool okay = GzipFile::writeToFile(filename, outText);
if (!okay) {
errMsg = tr("Error while writing on '%1'").arg(filename);
return false;
}
if (progress) {
progress->setValue(100);
}
RG_DEBUG << endl << "RosegardenDocument::saveDocument() finished\n";
if (!autosave) {
emit documentModified(false);
setModified(false);
CommandHistory::getInstance()->documentSaved();
}
if (progress) {
progress->close(); // is deleteOnClose
progress = 0;
}
setAutoSaved(true);
return true;
}
bool RosegardenDocument::exportStudio(const QString& filename,
QString &errMsg,
std::vector<DeviceId> devices)
{
Profiler profiler("RosegardenDocument::exportStudio");
RG_DEBUG << "RosegardenDocument::exportStudio("
<< filename << ")\n";
QString outText;
QTextStream outStream(&outText, QIODevice::WriteOnly);
// outStream.setEncoding(QTextStream::UnicodeUTF8); qt3
outStream.setCodec("UTF-8");
// output XML header
//
outStream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
<< "<!DOCTYPE rosegarden-data>\n"
<< "<rosegarden-data version=\"" << VERSION << "\">\n";
// Send out the studio - a self contained command
//
outStream << strtoqstr(m_studio.toXmlString(devices)) << endl << endl;
// close the top-level XML tag
//
outStream << "</rosegarden-data>\n";
bool okay = GzipFile::writeToFile(filename, outText);
if (!okay) {
errMsg = tr("Could not open file '%1' for writing").arg(filename);
return false;
}
RG_DEBUG << endl << "RosegardenDocument::exportStudio() finished\n";
return true;
}
void RosegardenDocument::saveSegment(QTextStream& outStream, Segment *segment,
ProgressDialog* progress, long totalEvents, long &count,
QString extraAttributes)
{
QString time;
outStream << QString("<%1 track=\"%2\" start=\"%3\" ")
.arg(segment->getXmlElementName())
.arg(segment->getTrack())
.arg(segment->getStartTime());
if (!extraAttributes.isEmpty())
outStream << extraAttributes << " ";
outStream << "label=\"" <<
strtoqstr(XmlExportable::encode(segment->getLabel()));
if (segment->isRepeating()) {
outStream << "\" repeat=\"true";
}
if (segment->getTranspose() != 0) {
outStream << "\" transpose=\"" << segment->getTranspose();
}
if (segment->getDelay() != 0) {
outStream << "\" delay=\"" << segment->getDelay();
}
if (segment->getRealTimeDelay() != RealTime::zeroTime) {
outStream << "\" rtdelaysec=\"" << segment->getRealTimeDelay().sec
<< "\" rtdelaynsec=\"" << segment->getRealTimeDelay().nsec;
}
if (segment->getColourIndex() != 0) {
outStream << "\" colourindex=\"" << segment->getColourIndex();
}
if (segment->getSnapGridSize() != -1) {
outStream << "\" snapgridsize=\"" << segment->getSnapGridSize();
}
if (segment->getViewFeatures() != 0) {
outStream << "\" viewfeatures=\"" << segment->getViewFeatures();
}
const timeT *endMarker = segment->getRawEndMarkerTime();
if (endMarker) {
outStream << "\" endmarker=\"" << *endMarker;
}
if (segment->getType() == Segment::Audio) {
outStream << "\" type=\"audio\" "
<< "file=\""
<< segment->getAudioFileId();
if (segment->getStretchRatio() != 1.f &&
segment->getStretchRatio() != 0.f) {
outStream << "\" unstretched=\""
<< segment->getUnstretchedFileId()
<< "\" stretch=\""
<< segment->getStretchRatio();
}
outStream << "\">\n";
// convert out - should do this as XmlExportable really
// once all this code is centralised
//
time.sprintf("%d.%06d", segment->getAudioStartTime().sec,
segment->getAudioStartTime().usec());
outStream << " <begin index=\""
<< time
<< "\"/>\n";
time.sprintf("%d.%06d", segment->getAudioEndTime().sec,
segment->getAudioEndTime().usec());
outStream << " <end index=\""
<< time
<< "\"/>\n";
if (segment->isAutoFading()) {
time.sprintf("%d.%06d", segment->getFadeInTime().sec,
segment->getFadeInTime().usec());
outStream << " <fadein time=\""
<< time
<< "\"/>\n";
time.sprintf("%d.%06d", segment->getFadeOutTime().sec,
segment->getFadeOutTime().usec());
outStream << " <fadeout time=\""
<< time
<< "\"/>\n";
}
} else // Internal type
{
outStream << "\">\n";
bool inChord = false;
timeT chordStart = 0, chordDuration = 0;
timeT expectedTime = segment->getStartTime();
for (Segment::iterator i = segment->begin();
i != segment->end(); ++i) {
timeT absTime = (*i)->getAbsoluteTime();
Segment::iterator nextEl = i;
++nextEl;
if (nextEl != segment->end() &&
(*nextEl)->getAbsoluteTime() == absTime &&
(*i)->getDuration() != 0 &&
!inChord) {
outStream << "<chord>" << endl;
inChord = true;
chordStart = absTime;
chordDuration = 0;
}
if (inChord && (*i)->getDuration() > 0)
if (chordDuration == 0 || (*i)->getDuration() < chordDuration)
chordDuration = (*i)->getDuration();
outStream << '\t'
<< strtoqstr((*i)->toXmlString(expectedTime)) << endl;
if (nextEl != segment->end() &&
(*nextEl)->getAbsoluteTime() != absTime &&
inChord) {
outStream << "</chord>\n";
inChord = false;
expectedTime = chordStart + chordDuration;
} else if (inChord) {
expectedTime = absTime;
} else {
expectedTime = absTime + (*i)->getDuration();
}
if ((++count % 500 == 0) && progress) {
progress->setValue(count * 100 / totalEvents);
}
}
if (inChord) {
outStream << "</chord>\n";
}
// Add EventRulers to segment - we call them controllers because of
// a historical mistake in naming them. My bad. RWB.
//
Segment::EventRulerList list = segment->getEventRulerList();
if (list.size()) {
outStream << "<gui>\n"; // gui elements
Segment::EventRulerListConstIterator it;
for (it = list.begin(); it != list.end(); ++it) {
outStream << " <controller type=\"" << strtoqstr((*it)->m_type);
if ((*it)->m_type == Controller::EventType) {
outStream << "\" value =\"" << (*it)->m_controllerValue;
}
outStream << "\"/>\n";
}
outStream << "</gui>\n";
}
}
outStream << QString("</%1>\n").arg(segment->getXmlElementName()); //-------------------------
}
bool RosegardenDocument::isSequencerRunning()
{
RosegardenMainWindow* parentApp = dynamic_cast<RosegardenMainWindow*>(parent());
if (!parentApp) {
RG_DEBUG << "RosegardenDocument::isSequencerRunning() : parentApp == 0\n";
return false;
}
return parentApp->isSequencerRunning();
}
bool
RosegardenDocument::xmlParse(QString fileContents, QString &errMsg,
ProgressDialog *progress,
bool permanent,
bool &cancelled)
{
Profiler profiler("RosegardenDocument::xmlParse");
cancelled = false;
unsigned int elementCount = 0;
for (int i = 0; i < fileContents.length() - 1; ++i) {
if (fileContents[i] == '<' && fileContents[i+1] != '/') {
++elementCount;
}
}
if (permanent) RosegardenSequencer::getInstance()->removeAllDevices();
RoseXmlHandler handler(this, elementCount, permanent);
if (progress) {
std::cout << "I am here!" << std::endl;
connect(&handler, SIGNAL(setValue(int)),
progress, SLOT(setValue(int)));
connect(progress, SIGNAL(canceled()),
&handler, SLOT(slotCancel()));
}
QXmlInputSource source;
source.setData(fileContents);
QXmlSimpleReader reader;
reader.setContentHandler(&handler);
reader.setErrorHandler(&handler);
bool ok = reader.parse(source);
if (!ok) {
if (handler.isCancelled()) {
RG_DEBUG << "File load cancelled\n";
StartupLogo::hideIfStillThere();
QMessageBox::information(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), tr("File load cancelled"));
cancelled = true;
if (progress) {
// Disconnect all signals /slots
disconnect(&handler, 0, progress, 0);
disconnect(progress, 0, &handler, 0);
}
return true;
} else {
errMsg = handler.errorString();
}
} else {
if (getSequenceManager() &&
!(getSequenceManager()->getSoundDriverStatus() & AUDIO_OK)) {
StartupLogo::hideIfStillThere();
CurrentProgressDialog::freeze();
if (handler.hasActiveAudio() ||
(m_pluginManager && !handler.pluginsNotFound().empty())) {
#ifdef HAVE_LIBJACK
QMessageBox::information
(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), tr("<h3>Audio and plugins not available</h3><p>This composition uses audio files or plugins, but Rosegarden is currently running without audio because the JACK audio server was not available on startup.</p><p>Please exit Rosegarden, start the JACK audio server and re-start Rosegarden if you wish to load this complete composition.</p><p><b>WARNING:</b> If you re-save this composition, all audio and plugin data and settings in it will be lost.</p>"));
#else
QMessageBox::information
(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), tr("<h3>Audio and plugins not available</h3><p>This composition uses audio files or plugins, but you are running a version of Rosegarden that was compiled without audio support.</p><p><b>WARNING:</b> If you re-save this composition from this version of Rosegarden, all audio and plugin data and settings in it will be lost.</p>"));
#endif
}
CurrentProgressDialog::thaw();
} else {
bool shownWarning = false;
int sr = 0;
if (getSequenceManager()) {
sr = getSequenceManager()->getSampleRate();
}
int er = m_audioFileManager.getExpectedSampleRate();
std::set<int> rates = m_audioFileManager.getActualSampleRates();
bool other = false;
bool mixed = (rates.size() > 1);
for (std::set<int>::iterator i = rates.begin();
i != rates.end(); ++i) {
if (*i != sr) {
other = true;
break;
}
}
if (sr != 0 &&
handler.hasActiveAudio() &&
((er != 0 && er != sr) ||
(other && !mixed))) {
if (er == 0) er = *rates.begin();
StartupLogo::hideIfStillThere();
CurrentProgressDialog::freeze();
QMessageBox::information(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), tr("<h3>Incorrect audio sample rate</h3><p>This composition contains audio files that were recorded or imported with the audio server running at a different sample rate (%1 Hz) from the current JACK server sample rate (%2 Hz).</p><p>Rosegarden will play this composition at the correct speed, but any audio files in it will probably sound awful.</p><p>Please consider re-starting the JACK server at the correct rate (%3 Hz) and re-loading this composition before you do any more work with it.</p>").arg(er).arg(sr).arg(er));
CurrentProgressDialog::thaw();
shownWarning = true;
} else if (sr != 0 && mixed) {
StartupLogo::hideIfStillThere();
CurrentProgressDialog::freeze();
QMessageBox::information(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), tr("<h3>Inconsistent audio sample rates</h3><p>This composition contains audio files at more than one sample rate.</p><p>Rosegarden will play them at the correct speed, but any audio files that were recorded or imported at rates different from the current JACK server sample rate (%1 Hz) will probably sound awful.</p><p>Please see the audio file manager dialog for more details, and consider resampling any files that are at the wrong rate.</p>").arg(sr),
tr("Inconsistent sample rates"),
"file-load-inconsistent-samplerates");
CurrentProgressDialog::thaw();
shownWarning = true;
}
if (m_pluginManager && !handler.pluginsNotFound().empty()) {
// We only warn if a plugin manager is present, so as
// to avoid warnings when importing a studio from
// another file (which is the normal case in which we
// have no plugin manager).
QString msg(tr("<h3>Plugins not found</h3><p>The following audio plugins could not be loaded:</p><ul>"));
for (std::set<QString>::iterator i = handler.pluginsNotFound().begin();
i != handler.pluginsNotFound().end(); ++i) {
QString ident = *i;
QString type, soName, label;
PluginIdentifier::parseIdentifier(ident, type, soName, label);
QString pluginFileName = QFileInfo(soName).fileName();
msg += tr("<li>%1 (from %2)</li>").arg(label).arg(pluginFileName);
}
msg += "</ul>";
StartupLogo::hideIfStillThere();
CurrentProgressDialog::freeze();
QMessageBox::information(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), msg);
CurrentProgressDialog::thaw();
shownWarning = true;
}
if (handler.isDeprecated() && !shownWarning) {
QString msg(tr("This file contains one or more old element types that are now deprecated.\nSupport for these elements may disappear in future versions of Rosegarden.\nWe recommend you re-save this file from this version of Rosegarden to ensure that it can still be re-loaded in future versions."));
slotDocumentModified(); // so file can be re-saved immediately
StartupLogo::hideIfStillThere();
CurrentProgressDialog::freeze();
QMessageBox::information(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), msg);
CurrentProgressDialog::thaw();
}
}
getComposition().resetLinkedSegmentRefreshStatuses();
}
// Set to maximum just incase reading did not do this.
if (progress) {
progress->setValue(progress->maximum());
// Disconnect all signals /slots
disconnect(&handler, 0, progress, 0);
disconnect(progress, 0, &handler, 0);
}
return ok;
}
void
RosegardenDocument::insertRecordedMidi(const MappedEventList &mC)
{
//RG_DEBUG << "RosegardenDocument::insertRecordedMidi: " << mC.size() << " events";
// Just create a new record Segment if we don't have one already.
// Make sure we don't recreate the record segment if it's already
// freed.
//
//Track *midiRecordTrack = 0;
const Composition::recordtrackcontainer &tr =
getComposition().getRecordTracks();
bool haveMIDIRecordTrack = false;
// For each recording track
for (Composition::recordtrackcontainer::const_iterator i =
tr.begin(); i != tr.end(); ++i) {
TrackId tid = (*i);
Track *track = getComposition().getTrackById(tid);
if (track) {
Instrument *instrument =
m_studio.getInstrumentById(track->getInstrument());
if (instrument->getType() == Instrument::Midi ||
instrument->getType() == Instrument::SoftSynth) {
haveMIDIRecordTrack = true;
if (!m_recordMIDISegments[track->getInstrument()]) {
addRecordMIDISegment(track->getId());
}
break;
}
}
}
if (!haveMIDIRecordTrack)
return ;
if (mC.size() > 0) {
Event *rEvent = 0;
timeT duration, absTime;
timeT updateFrom = m_composition.getDuration();
bool haveNotes = false;
MappedEventList::const_iterator i;
// process all the incoming MappedEvents
//
int lenx = int(m_viewList.size());
RosegardenMainViewWidget *v;
int k = 0;
// For each incoming event
for (i = mC.begin(); i != mC.end(); ++i) {
if ((*i)->getRecordedDevice() == Device::CONTROL_DEVICE) {
// send to GUI
//QList<RosegardenMainViewWidget *>::iterator v;
//for( v=m_viewList.begin(); v!=m_viewList.end(); v++ ) {
for( k=0; k<lenx; k++){
v = m_viewList.value( k );
v->slotControllerDeviceEventReceived(*i);
}
continue;
}
absTime = m_composition.getElapsedTimeForRealTime((*i)->getEventTime());
/* This is incorrect, unless the tempo at absTime happens to
be the same as the tempo at zero and there are no tempo
changes within the given duration after either zero or
absTime
duration = m_composition.getElapsedTimeForRealTime((*i)->getDuration());
*/
duration = m_composition.
getElapsedTimeForRealTime((*i)->getEventTime() +
(*i)->getDuration()) - absTime;
rEvent = 0;
bool isNoteOn = false;
int pitch = (*i)->getPitch();
int channel = (*i)->getRecordedChannel();
int device = (*i)->getRecordedDevice();
switch ((*i)->getType()) {
case MappedEvent::MidiNote:
if ((*i)->getDuration() < RealTime::zeroTime) {
// it's a note-on; give it a default duration
// for insertion into the segment, and make a
// mental note to stick it in the note-on map
// for when we see the corresponding note-off
duration = Note(Note::Crotchet).getDuration();
isNoteOn = true;
rEvent = new Event(Note::EventType,
absTime,
duration);
rEvent->set<Int>(PITCH, pitch);
rEvent->set<Int>(VELOCITY, (*i)->getVelocity());
} else {
// it's a note-off
PitchMap *pm = &m_noteOnEvents[device][channel];
PitchMap::iterator mi = pm->find(pitch);
if (mi != pm->end()) {
// modify the previously held note-on event,
// instead of assigning to rEvent
NoteOnRecSet rec_vec = mi->second;
Event *oldEv = *rec_vec[0].m_segmentIterator;
Event *newEv = new Event
(*oldEv, oldEv->getAbsoluteTime(), duration);
newEv->set<Int>(RECORDED_CHANNEL, channel);
NoteOnRecSet *replaced =
replaceRecordedEvent(rec_vec, newEv);
delete replaced;
pm->erase(mi);
if (updateFrom > newEv->getAbsoluteTime()) {
updateFrom = newEv->getAbsoluteTime();
}
haveNotes = true;
delete newEv;
// at this point we could quantize the bar if we were
// tracking in a notation view
} else {
RG_DEBUG << " WARNING: NOTE OFF received without corresponding NOTE ON";
}
}
break;
case MappedEvent::MidiPitchBend:
rEvent = PitchBend
((*i)->getData1(), (*i)->getData2()).getAsEvent(absTime);
rEvent->set<Int>(RECORDED_CHANNEL, channel);
break;
case MappedEvent::MidiController:
rEvent = Controller
((*i)->getData1(), (*i)->getData2()).getAsEvent(absTime);
rEvent->set<Int>(RECORDED_CHANNEL, channel);
break;
case MappedEvent::MidiProgramChange:
RG_DEBUG << "RosegardenDocument::insertRecordedMidi()"
<< " - got Program Change (unsupported)"
<< endl;
break;
case MappedEvent::MidiKeyPressure:
rEvent = KeyPressure
((*i)->getData1(), (*i)->getData2()).getAsEvent(absTime);
rEvent->set<Int>(RECORDED_CHANNEL, channel);
break;
case MappedEvent::MidiChannelPressure:
rEvent = ChannelPressure
((*i)->getData1()).getAsEvent(absTime);
rEvent->set<Int>(RECORDED_CHANNEL, channel);
break;
case MappedEvent::MidiSystemMessage:
channel = -1;
if ((*i)->getData1() == MIDI_SYSTEM_EXCLUSIVE) {
rEvent = SystemExclusive
(DataBlockRepository::getDataBlockForEvent((*i))).getAsEvent(absTime);
}
// Ignore other SystemMessage events for the moment
//
break;
case MappedEvent::MidiNoteOneShot:
RG_DEBUG << "RosegardenDocument::insertRecordedMidi() - "
<< "GOT UNEXPECTED MappedEvent::MidiNoteOneShot";
break;
// Audio control signals - ignore these
case MappedEvent::Audio:
case MappedEvent::AudioCancel:
case MappedEvent::AudioLevel:
case MappedEvent::AudioStopped:
case MappedEvent::AudioGeneratePreview:
case MappedEvent::SystemUpdateInstruments:
break;
// list everything in the enum to avoid the annoying compiler
// warning
case MappedEvent::InvalidMappedEvent:
case MappedEvent::Marker:
case MappedEvent::SystemJackTransport:
case MappedEvent::SystemMMCTransport:
case MappedEvent::SystemMIDIClock:
case MappedEvent::SystemMetronomeDevice:
case MappedEvent::SystemAudioPortCounts:
case MappedEvent::SystemAudioPorts:
case MappedEvent::SystemFailure:
case MappedEvent::Text:
case MappedEvent::TimeSignature:
case MappedEvent::Tempo:
case MappedEvent::Panic:
case MappedEvent::SystemMTCTransport:
case MappedEvent::SystemMIDISyncAuto:
case MappedEvent::SystemAudioFileFormat:
default:
RG_DEBUG << "RosegardenDocument::insertRecordedMidi() - "
<< "GOT UNSUPPORTED MAPPED EVENT";
break;
}
// sanity check
//
if (rEvent == 0)
continue;
// Set the recorded input port
//
rEvent->set<Int>(RECORDED_PORT, device);
// Set the proper start index (if we haven't before)
//
for (RecordingSegmentMap::const_iterator it = m_recordMIDISegments.begin();
it != m_recordMIDISegments.end(); ++it) {
Segment *recordMIDISegment = it->second;
if (recordMIDISegment->size() == 0) {
recordMIDISegment->setStartTime (m_composition.getBarStartForTime(absTime));
recordMIDISegment->fillWithRests(absTime);
}
}
// Now insert the new event
//
insertRecordedEvent(rEvent, device, channel, isNoteOn);
delete rEvent;
}
// If we have note events, quantize the notation for the recording
// segments.
if (haveNotes) {
QSettings settings;
settings.beginGroup( GeneralOptionsConfigGroup );
int tracking = settings.value("recordtracking", 0).toUInt() ;
settings.endGroup();
if (tracking == 1) { // notation
for (RecordingSegmentMap::const_iterator it = m_recordMIDISegments.begin();
it != m_recordMIDISegments.end(); ++it) {
Segment *recordMIDISegment = it->second;
EventQuantizeCommand *command = new EventQuantizeCommand
(*recordMIDISegment,
updateFrom,
recordMIDISegment->getEndTime(),
NotationOptionsConfigGroup,
EventQuantizeCommand::QUANTIZE_NOTATION_ONLY);
// don't add to history
command->execute();
}
}
// this signal is currently unused - leaving just in case
// recording segments are updated through the SegmentObserver::eventAdded() interface
// emit recordMIDISegmentUpdated(m_recordMIDISegment, updateFrom);
}
}
}
void
RosegardenDocument::updateRecordingMIDISegment()
{
// RG_DEBUG << "RosegardenDocument::updateRecordingMIDISegment" << endl;
if (m_recordMIDISegments.size() == 0) {
// make this call once to create one
insertRecordedMidi(MappedEventList());
if (m_recordMIDISegments.size() == 0)
return ; // not recording any MIDI
}
// RG_DEBUG << "RosegardenDocument::updateRecordingMIDISegment: have record MIDI segment" << endl;
NoteOnMap tweakedNoteOnEvents;
for (NoteOnMap::iterator mi = m_noteOnEvents.begin();
mi != m_noteOnEvents.end(); ++mi)
for (ChanMap::iterator cm = mi->second.begin();
cm != mi->second.end(); ++cm)
for (PitchMap::iterator pm = cm->second.begin();
pm != cm->second.end(); ++pm) {
// anything in the note-on map should be tweaked so as to end
// at the recording pointer
NoteOnRecSet rec_vec = pm->second;
if (rec_vec.size() > 0) {
Event *oldEv = *rec_vec[0].m_segmentIterator;
Event *newEv = new Event(
*oldEv, oldEv->getAbsoluteTime(),
m_composition.getPosition() - oldEv->getAbsoluteTime() );
tweakedNoteOnEvents[mi->first][cm->first][pm->first] =
*replaceRecordedEvent(rec_vec, newEv);
delete newEv;
}
}
m_noteOnEvents = tweakedNoteOnEvents;
}
void
RosegardenDocument::transposeRecordedSegment(Segment *s)
{
// get a selection of all the events in the segment, since we apparently
// can't just iterate through a segment's events without one. (?)
EventSelection *selectedWholeSegment = new EventSelection(
*s,
s->getStartTime(),
s->getEndMarkerTime());
// Say we've got a recorded segment destined for a Bb trumpet track.
// It will have transpose of -2, and we want to move the notation +2 to
// compensate, so the user hears the same thing she just recorded
//
// (All debate over whether this is the right way to go with this whole
// issue is now officially settled, and no longer tentative.)
Composition *c = s->getComposition();
if (c) {
Track *t = c->getTrackById(s->getTrack());
if (t) {
// pull transpose from the destination track
int semitones = t->getTranspose();
for (EventSelection::eventcontainer::iterator i =
selectedWholeSegment->getSegmentEvents().begin();
i != selectedWholeSegment->getSegmentEvents().end(); ++i) {
if ((*i)->isa(Note::EventType)) {
if (semitones != 0) {
if (!(*i)->has(PITCH)) {
std::cerr << "WARNING! RosegardenDocument::transposeRecordedSegment: Note has no pitch! Andy says \"Oh noes!!! ZOMFG!!!\"" << std::endl;
} else {
int pitch = (*i)->get<Int>(PITCH) - semitones;
std::cerr << "pitch = " << pitch
<< " after transpose = "
<< semitones << " (for track "
<< s->getTrack() << ")" << std::endl;
(*i)->set<Int>(PITCH, pitch);
}
}
}
}
}
}
}
RosegardenDocument::NoteOnRecSet *
RosegardenDocument::replaceRecordedEvent(NoteOnRecSet& rec_vec, Event *fresh)
{
NoteOnRecSet *new_vector = new NoteOnRecSet();
for (NoteOnRecSet::const_iterator i = rec_vec.begin(); i != rec_vec.end(); ++i) {
Segment *recordMIDISegment = i->m_segment;
recordMIDISegment->erase(i->m_segmentIterator);
NoteOnRec noteRec;
noteRec.m_segment = recordMIDISegment;
noteRec.m_segmentIterator = recordMIDISegment->insert(new Event(*fresh));
// don't need to transpose this event; it was copied from an
// event that had been transposed already (in storeNoteOnEvent)
new_vector->push_back(noteRec);
}
return new_vector;
}
void
RosegardenDocument::storeNoteOnEvent(Segment *s, Segment::iterator it, int device, int channel)
{
NoteOnRec record;
record.m_segment = s;
record.m_segmentIterator = it;
int pitch = (*it)->get<Int>(PITCH);
m_noteOnEvents[device][channel][pitch].push_back(record);
}
void
RosegardenDocument::insertRecordedEvent(Event *ev, int device, int channel, bool isNoteOn)
{
Segment::iterator it;
for ( RecordingSegmentMap::const_iterator i = m_recordMIDISegments.begin();
i != m_recordMIDISegments.end(); ++i) {
Segment *recordMIDISegment = i->second;
TrackId tid = recordMIDISegment->getTrack();
Track *track = getComposition().getTrackById(tid);
if (track) {
//Instrument *instrument =
// m_studio.getInstrumentById(track->getInstrument());
int chan_filter = track->getMidiInputChannel();
int dev_filter = track->getMidiInputDevice();
if (((chan_filter < 0) || (chan_filter == channel)) &&
((dev_filter == int(Device::ALL_DEVICES)) || (dev_filter == device))) {
// Insert the event into the segment.
it = recordMIDISegment->insert(new Event(*ev));
if (isNoteOn) {
// Add the event to m_noteOnEvents.
// To match up with a note-off later.
storeNoteOnEvent(recordMIDISegment, it, device, channel);
}
//RG_DEBUG << "RosegardenDocument::insertRecordedEvent() - matches filter";
} else {
//RG_DEBUG << "RosegardenDocument::insertRecordedEvent() - unmatched event discarded";
}
}
}
}
void
RosegardenDocument::stopPlaying()
{
emit pointerPositionChanged(m_composition.getPosition());
}
void
RosegardenDocument::stopRecordingMidi()
{
RG_DEBUG << "RosegardenDocument::stopRecordingMidi" << endl;
Composition &c = getComposition();
timeT endTime = c.getBarEnd(0);
bool haveMeaning = false;
timeT earliestMeaning = 0;
std::vector<RecordingSegmentMap::iterator> toErase;
for (RecordingSegmentMap::iterator i = m_recordMIDISegments.begin();
i != m_recordMIDISegments.end();
++i) {
Segment *s = i->second;
bool meaningless = true;
for (Segment::iterator si = s->begin(); si != s->end(); ++si) {
if ((*si)->isa(Clef::EventType)) continue;
// no rests in the segment yet, so anything else is meaningful
meaningless = false;
if (!haveMeaning || (*si)->getAbsoluteTime() < earliestMeaning) {
earliestMeaning = (*si)->getAbsoluteTime();
}
haveMeaning = true;
break;
}
if (meaningless) {
if (!c.deleteSegment(s)) delete s;
toErase.push_back(i);
} else {
if (endTime < s->getEndTime()) {
endTime = s->getEndTime();
}
}
}
for (size_t i = 0; i < toErase.size(); ++i) {
m_recordMIDISegments.erase(toErase[i]);
}
if (!haveMeaning) return;
RG_DEBUG << "RosegardenDocument::stopRecordingMidi: have something" << endl;
// adjust the clef timings so as not to leave a clef stranded at
// the start of an otherwise empty count-in
timeT meaningfulBarStart = c.getBarStartForTime(earliestMeaning);
for (RecordingSegmentMap::iterator i = m_recordMIDISegments.begin();
i != m_recordMIDISegments.end();
++i) {
Segment *s = i->second;
Segment::iterator j = s->begin();
if (j == s->end() || !(*j)->isa(Clef::EventType)) continue;
if ((*j)->getAbsoluteTime() < meaningfulBarStart) {
Event *e = new Event(**j, meaningfulBarStart);
s->erase(j);
s->insert(e);
}
}
for (NoteOnMap::iterator mi = m_noteOnEvents.begin();
mi != m_noteOnEvents.end(); ++mi) {
for (ChanMap::iterator cm = mi->second.begin();
cm != mi->second.end(); ++cm) {
for (PitchMap::iterator pm = cm->second.begin();
pm != cm->second.end(); ++pm) {
// anything remaining in the note-on map should be
// made to end at the end of the segment
NoteOnRecSet rec_vec = pm->second;
if (rec_vec.size() > 0) {
Event *oldEv = *rec_vec[0].m_segmentIterator;
Event *newEv = new Event
(*oldEv, oldEv->getAbsoluteTime(),
endTime - oldEv->getAbsoluteTime());
NoteOnRecSet *replaced =
replaceRecordedEvent(rec_vec, newEv);
delete newEv;
delete replaced;
}
}
}
}
m_noteOnEvents.clear();
while (!m_recordMIDISegments.empty()) {
Segment *s = m_recordMIDISegments.begin()->second;
m_recordMIDISegments.erase(m_recordMIDISegments.begin());
// the record segment will have already been added to the
// composition if there was anything in it; otherwise we don't
// need to do so
if (s->getComposition() == 0) {
delete s;
continue;
}
// Quantize for notation only -- doesn't affect performance timings.
MacroCommand *command = new MacroCommand(tr("Insert Recorded MIDI"));
command->addCommand(new EventQuantizeCommand
(*s,
s->getStartTime(),
s->getEndTime(),
NotationOptionsConfigGroup,
EventQuantizeCommand::QUANTIZE_NOTATION_ONLY));
command->addCommand(new NormalizeRestsCommand
(*s,
c.getBarStartForTime(s->getStartTime()),
c.getBarEndForTime(s->getEndTime())));
command->addCommand(new SegmentRecordCommand(s));
// Transpose the entire recorded segment as a unit, rather than
// transposing its individual events one time. This allows the same
// source recording to be transposed to multiple destination tracks in
// different transpositions as part of one simultaneous operation from
// the user's perspective. This wasn't done as a command, because it
// will be undone if the segment itself is undone, and I wanted to avoid
// writing a new command at a time when we've got something completely
// different over in the new Qt4 branch; to facilitate porting.
transposeRecordedSegment(s);
CommandHistory::getInstance()->addCommand(command);
}
emit stoppedMIDIRecording();
slotUpdateAllViews(0);
emit pointerPositionChanged(m_composition.getPosition());
}
void
RosegardenDocument::prepareAudio()
{
if (!isSequencerRunning()) return;
// Clear down the sequencer AudioFilePlayer object
//
RosegardenSequencer::getInstance()->clearAllAudioFiles();
for (AudioFileManagerIterator it = m_audioFileManager.begin();
it != m_audioFileManager.end(); it++) {
bool result = RosegardenSequencer::getInstance()->
addAudioFile((*it)->getFilename(),
(*it)->getId());
if (!result) {
RG_DEBUG << "prepareAudio() - failed to add file \""
<< (*it)->getFilename() << "\"" << endl;
}
}
}
void
RosegardenDocument::slotSetPointerPosition(timeT t)
{
m_composition.setPosition(t);
emit pointerPositionChanged(t);
}
void
RosegardenDocument::setLoop(timeT t0, timeT t1)
{
m_composition.setLoopStart(t0);
m_composition.setLoopEnd(t1);
emit loopChanged(t0, t1);
}
void
RosegardenDocument::checkSequencerTimer()
{
Profiler profiler("RosegardenDocument::checkSequencerTimer", true);
if (!isSequencerRunning()) return;
// Set the default timer. We only do this first time and when
// changed in the configuration dialog.
static bool setTimer = false;
if (!setTimer) {
QSettings settings;
settings.beginGroup( SequencerOptionsConfigGroup );
QString currentTimer = getCurrentTimer();
currentTimer = settings.value("timer", currentTimer).toString();
setCurrentTimer(currentTimer);
setTimer = true;
settings.endGroup();
}
}
void
RosegardenDocument::addRecordMIDISegment(TrackId tid)
{
RG_DEBUG << "RosegardenDocument::addRecordMIDISegment(" << tid << ")" << endl;
// std::cerr << kdBacktrace() << std::endl;
Segment *recordMIDISegment;
recordMIDISegment = new Segment();
recordMIDISegment->setTrack(tid);
recordMIDISegment->setStartTime(m_recordStartTime);
// Set an appropriate segment label
//
std::string label = "";
Track *track = m_composition.getTrackById(tid);
if (track) {
if (track->getPresetLabel() != "") {
label = track->getPresetLabel();
} else if (track->getLabel() == "") {
Instrument *instr =
m_studio.getInstrumentById(track->getInstrument());
if (instr) {
label = m_studio.getSegmentName(instr->getId());
}
} else {
label = track->getLabel();
}
}
recordMIDISegment->setLabel(appendLabel(label,
qstrtostr(tr("(recorded)"))));
// set segment transpose, color, highest/lowest playable from track parameters
Clef clef = clefIndexToClef(track->getClef());
recordMIDISegment->insert(clef.getAsEvent
(recordMIDISegment->getStartTime()));
recordMIDISegment->setTranspose(track->getTranspose());
recordMIDISegment->setColourIndex(track->getColor());
recordMIDISegment->setHighestPlayable(track->getHighestPlayable());
recordMIDISegment->setLowestPlayable(track->getLowestPlayable());
m_composition.addSegment(recordMIDISegment);
m_recordMIDISegments[track->getInstrument()] = recordMIDISegment;
RosegardenMainViewWidget *w;
int lenx = m_viewList.count();
int i = 0;
//for (w = m_viewList.first(); w != 0; w = m_viewList.next()) {
for( i=0; i<lenx; i++ ){
w = m_viewList.value( i );
w->getTrackEditor()->getTrackButtons()->slotUpdateTracks();
}
emit newMIDIRecordingSegment(recordMIDISegment);
}
void
RosegardenDocument::addRecordAudioSegment(InstrumentId iid,
AudioFileId auid)
{
Segment *recordSegment = new Segment
(Segment::Audio);
// Find the right track
Track *recordTrack = 0;
const Composition::recordtrackcontainer &tr =
getComposition().getRecordTracks();
for (Composition::recordtrackcontainer::const_iterator i =
tr.begin(); i != tr.end(); ++i) {
TrackId tid = (*i);
Track *track = getComposition().getTrackById(tid);
if (track) {
if (iid == track->getInstrument()) {
recordTrack = track;
break;
}
}
}
if (!recordTrack) {
RG_DEBUG << "RosegardenDocument::addRecordAudioSegment(" << iid << ", "
<< auid << "): No record-armed track found for instrument!"
<< endl;
return ;
}
recordSegment->setTrack(recordTrack->getId());
recordSegment->setStartTime(m_recordStartTime);
recordSegment->setAudioStartTime(RealTime::zeroTime);
// Set an appropriate segment label
//
std::string label = "";
if (recordTrack) {
if (recordTrack->getLabel() == "") {
Instrument *instr =
m_studio.getInstrumentById(recordTrack->getInstrument());
if (instr) {
label = instr->getName();
}
} else {
label = recordTrack->getLabel();
}
}
recordSegment->setLabel(appendLabel(label, qstrtostr(RosegardenDocument::tr("(recorded)"))));
recordSegment->setAudioFileId(auid);
// set color for audio segment to distinguish it from a MIDI segment on an
// audio track drawn with the pencil (depends on having the current
// autoload.rg or a file derived from it to deliever predictable results,
// but the worst case here is segments drawn in the wrong color when
// adding new segments to old files, which I don't forsee as being enough
// of a problem to be worth cooking up a more robust implementation of
// this new color for new audio segments (DMM)
recordSegment->setColourIndex(GUIPalette::AudioDefaultIndex);
RG_DEBUG << "RosegardenDocument::addRecordAudioSegment: adding record segment for instrument " << iid << " on track " << recordTrack->getId() << endl;
m_recordAudioSegments[iid] = recordSegment;
RosegardenMainViewWidget *w;
int lenx = m_viewList.count();
int i = 0;
//for (w = m_viewList.first(); w != 0; w = m_viewList.next()) {
for( i=0; i<lenx; i++ ){
w = m_viewList.value( i );
w->getTrackEditor()->getTrackButtons()->slotUpdateTracks();
}
emit newAudioRecordingSegment(recordSegment);
}
void
RosegardenDocument::updateRecordingAudioSegments()
{
const Composition::recordtrackcontainer &tr =
getComposition().getRecordTracks();
for (Composition::recordtrackcontainer::const_iterator i =
tr.begin(); i != tr.end(); ++i) {
TrackId tid = (*i);
Track *track = getComposition().getTrackById(tid);
if (track) {
InstrumentId iid = track->getInstrument();
if (m_recordAudioSegments[iid]) {
Segment *recordSegment = m_recordAudioSegments[iid];
if (!recordSegment->getComposition()) {
// always insert straight away for audio
m_composition.addSegment(recordSegment);
}
recordSegment->setAudioEndTime(
m_composition.getRealTimeDifference(recordSegment->getStartTime(),
m_composition.getPosition()));
} else {
// RG_DEBUG << "RosegardenDocument::updateRecordingAudioSegments: no segment for instr "
// << iid << endl;
}
}
}
}
void
RosegardenDocument::stopRecordingAudio()
{
RG_DEBUG << "RosegardenDocument::stopRecordingAudio" << endl;
for (RecordingSegmentMap::iterator ri = m_recordAudioSegments.begin();
ri != m_recordAudioSegments.end(); ++ri) {
Segment *recordSegment = ri->second;
if (!recordSegment)
continue;
// set the audio end time
//
recordSegment->setAudioEndTime(
m_composition.getRealTimeDifference(recordSegment->getStartTime(),
m_composition.getPosition()));
// now add the Segment
RG_DEBUG << "RosegardenDocument::stopRecordingAudio - "
<< "got recorded segment" << endl;
// now move the segment back by the record latency
//
/*!!!
No. I don't like this.
The record latency doesn't always exist -- for example, if recording
from a synth plugin there is no record latency, and we have no way
here to distinguish.
The record latency is a total latency figure that actually includes
some play latency, and we compensate for that again on playback (see
bug #1378766).
The timeT conversion of record latency is approximate in frames,
giving potential phase error.
Cutting this out won't break any existing files, as the latency
compensation there is already encoded into the file.
RealTime adjustedStartTime =
m_composition.getElapsedRealTime(recordSegment->getStartTime()) -
m_audioRecordLatency;
timeT shiftedStartTime =
m_composition.getElapsedTimeForRealTime(adjustedStartTime);
RG_DEBUG << "RosegardenDocument::stopRecordingAudio - "
<< "shifted recorded audio segment by "
<< recordSegment->getStartTime() - shiftedStartTime
<< " clicks (from " << recordSegment->getStartTime()
<< " to " << shiftedStartTime << ")" << endl;
recordSegment->setStartTime(shiftedStartTime);
*/
}
emit stoppedAudioRecording();
emit pointerPositionChanged(m_composition.getPosition());
}
void
RosegardenDocument::finalizeAudioFile(InstrumentId iid)
{
RG_DEBUG << "RosegardenDocument::finalizeAudioFile(" << iid << ")" << endl;
Segment *recordSegment = 0;
recordSegment = m_recordAudioSegments[iid];
if (!recordSegment) {
RG_DEBUG << "RosegardenDocument::finalizeAudioFile: Failed to find segment" << endl;
return ;
}
AudioFile *newAudioFile = m_audioFileManager.getAudioFile
(recordSegment->getAudioFileId());
if (!newAudioFile) {
std::cerr << "WARNING: RosegardenDocument::finalizeAudioFile: No audio file found for instrument " << iid << " (audio file id " << recordSegment->getAudioFileId() << ")" << std::endl;
return ;
}
// Create a progress dialog
//
ProgressDialog *progressDlg = new ProgressDialog ( tr("Generating audio preview..."), (QWidget*)parent() );
connect(progressDlg, SIGNAL(canceled()),
&m_audioFileManager, SLOT(slotStopPreview()));
connect(&m_audioFileManager, SIGNAL(setValue(int)),
progressDlg, SLOT(setValue(int)));
try {
m_audioFileManager.generatePreview(newAudioFile->getId());
//!!! mtr just for now?: or better to do this once after the fact?
//!!! m_audioFileManager.generatePreviews();
} catch (Exception e) {
StartupLogo::hideIfStillThere();
CurrentProgressDialog::freeze();
QMessageBox::critical(dynamic_cast<QWidget *>(parent()), tr("Rosegarden"), strtoqstr(e.getMessage()));
CurrentProgressDialog::thaw();
}
progressDlg->close(); // is deleteOnClose
progressDlg = 0;
if (!recordSegment->getComposition()) {
getComposition().addSegment(recordSegment);
}
CommandHistory::getInstance()->addCommand
(new SegmentRecordCommand(recordSegment));
// update views
slotUpdateAllViews(0);
// Now install the file in the sequencer
//
RosegardenSequencer::getInstance()->addAudioFile
(newAudioFile->getFilename(),
newAudioFile->getId());
// clear down
m_recordAudioSegments.erase(iid);
emit audioFileFinalized(recordSegment);
}
RealTime
RosegardenDocument::getAudioPlayLatency()
{
return RosegardenSequencer::getInstance()->getAudioPlayLatency();
}
RealTime
RosegardenDocument::getAudioRecordLatency()
{
return RosegardenSequencer::getInstance()->getAudioRecordLatency();
}
void
RosegardenDocument::updateAudioRecordLatency()
{
m_audioRecordLatency = getAudioRecordLatency();
}
QStringList
RosegardenDocument::getTimers()
{
QStringList list;
unsigned int count = RosegardenSequencer::getInstance()->getTimers();
for (unsigned int i = 0; i < count; ++i) {
list.push_back(RosegardenSequencer::getInstance()->getTimer(i));
}
return list;
}
QString
RosegardenDocument::getCurrentTimer()
{
return RosegardenSequencer::getInstance()->getCurrentTimer();
}
void
RosegardenDocument::setCurrentTimer(QString name)
{
RosegardenSequencer::getInstance()->setCurrentTimer(name);
}
void
RosegardenDocument::clearAllPlugins()
{
RG_DEBUG << "clearAllPlugins" << endl;
InstrumentList list = m_studio.getAllInstruments();
MappedEventList mC;
InstrumentList::iterator it = list.begin();
for (; it != list.end(); ++it) {
if ((*it)->getType() == Instrument::Audio) {
PluginInstanceIterator pIt = (*it)->beginPlugins();
for (; pIt != (*it)->endPlugins(); pIt++) {
if ((*pIt)->getMappedId() != -1) {
if (StudioControl::
destroyStudioObject((*pIt)->getMappedId()) == false) {
RG_DEBUG << "RosegardenDocument::clearAllPlugins - "
<< "couldn't find plugin instance "
<< (*pIt)->getMappedId() << endl;
}
}
(*pIt)->clearPorts();
}
(*it)->emptyPlugins();
/*
RG_DEBUG << "RosegardenDocument::clearAllPlugins - "
<< "cleared " << (*it)->getName() << endl;
*/
}
}
}
Clipboard*
RosegardenDocument::getClipboard()
{
RosegardenMainWindow *mainWindow = (RosegardenMainWindow*)parent();
return mainWindow->getClipboard();
}
void RosegardenDocument::slotDocColoursChanged()
{
RG_DEBUG << "RosegardenDocument::slotDocColoursChanged(): emitting docColoursChanged()" << endl;
emit docColoursChanged();
}
void
RosegardenDocument::addOrphanedRecordedAudioFile(QString fileName)
{
m_orphanedRecordedAudioFiles.push_back(fileName);
slotDocumentModified();
}
void
RosegardenDocument::addOrphanedDerivedAudioFile(QString fileName)
{
m_orphanedDerivedAudioFiles.push_back(fileName);
slotDocumentModified();
}
void
RosegardenDocument::notifyAudioFileRemoval(AudioFileId id)
{
AudioFile *file = 0;
if (m_audioFileManager.wasAudioFileRecentlyRecorded(id)) {
file = m_audioFileManager.getAudioFile(id);
if (file) addOrphanedRecordedAudioFile( file->getFilename() );
return;
}
if (m_audioFileManager.wasAudioFileRecentlyDerived(id)) {
file = m_audioFileManager.getAudioFile(id);
if (file) addOrphanedDerivedAudioFile( file->getFilename() );
return;
}
}
// Get the instrument that plays the segment.
// @returns a pointer to the instrument object
Instrument *
RosegardenDocument::
getInstrument(Segment *segment)
{
if (!segment)
{ return 0; }
Studio &studio = getStudio();
Instrument *instrument =
studio.getInstrumentById
(segment->getComposition()->getTrackById(segment->getTrack())->
getInstrument());
return instrument;
}
void
RosegardenDocument::checkAudioPath(Track *track)
{
// Might consider calling this from a trackChanged() handler. Although
// it might not be a good idea to do a dialog from there, and the dialog
// could keep popping up over and over without some sort of static flag.
if (!track->isArmed())
return;
Instrument *instrument =
getStudio().getInstrumentById(track->getInstrument());
bool audio = (instrument &&
instrument->getType() == Instrument::Audio);
if (!audio)
return;
try {
getAudioFileManager().testAudioPath();
} catch (AudioFileManager::BadAudioPathException & /*e*/) {
// ho ho, here was the real culprit: this dialog inherited style
// from the track button, hence the weird background and black
// foreground!
if (QMessageBox::warning(0,
tr("Warning"),
tr("The audio file path does not exist or is not writable.\nPlease set the audio file path to a valid directory in Document Properties before recording audio.\nWould you like to set it now?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel
) == QMessageBox::Yes) {
RosegardenMainWindow::self()->slotOpenAudioPathSettings();
}
}
}
}
#include "RosegardenDocument.moc"