[84b6f5]: libkwave / SignalManager.cpp Maximize Restore History

Download this file

SignalManager.cpp    1909 lines (1607 with data), 58.0 kB

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
/***************************************************************************
SignalManager.cpp - manager class for multi-channel signals
-------------------
begin : Sun Oct 15 2000
copyright : (C) 2000 by Thomas Eschenbacher
email : Thomas.Eschenbacher@gmx.de
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "config.h"
#include <errno.h>
#include <limits.h>
#include <math.h>
#include <QApplication>
#include <QCursor>
#include <QFile>
#include <QFileInfo>
#include <QMutexLocker>
#include <QMutableListIterator>
#include <kaboutdata.h>
#include <kapplication.h>
#include <kcomponentdata.h>
#include <klocale.h>
#include <kmimetype.h>
#include <kprogressdialog.h>
#include <kurl.h>
#include "libkwave/ClipBoard.h"
#include "libkwave/CodecManager.h"
#include "libkwave/Decoder.h"
#include "libkwave/Encoder.h"
#include "libkwave/FileProgress.h"
#include "libkwave/InsertMode.h"
#include "libkwave/MemoryManager.h"
#include "libkwave/MessageBox.h"
#include "libkwave/MultiTrackReader.h"
#include "libkwave/MultiTrackWriter.h"
#include "libkwave/Parser.h"
#include "libkwave/Sample.h"
#include "libkwave/SampleReader.h"
#include "libkwave/Signal.h"
#include "libkwave/SignalManager.h"
#include "libkwave/Track.h"
#include "libkwave/Writer.h"
#include "libkwave/undo/UndoTransactionGuard.h"
#include "libkwave/undo/UndoAction.h"
#include "libkwave/undo/UndoAddMetaDataAction.h"
#include "libkwave/undo/UndoDeleteAction.h"
#include "libkwave/undo/UndoDeleteMetaDataAction.h"
#include "libkwave/undo/UndoDeleteTrack.h"
#include "libkwave/undo/UndoInsertAction.h"
#include "libkwave/undo/UndoInsertTrack.h"
#include "libkwave/undo/UndoModifyAction.h"
#include "libkwave/undo/UndoModifyMetaDataAction.h"
#include "libkwave/undo/UndoSelection.h"
#include "libkwave/undo/UndoTransaction.h"
#define CASE_COMMAND(x) } else if (parser.command() == x) {
//***************************************************************************
SignalManager::SignalManager(QWidget *parent)
:QObject(),
m_parent_widget(parent),
m_closed(true),
m_empty(true),
m_modified(false),
m_modified_enabled(true),
m_signal(),
m_selection(0,0),
m_last_selection(0,0),
m_last_track_selection(),
m_last_length(0),
m_playback_controller(),
m_undo_enabled(false),
m_undo_buffer(),
m_redo_buffer(),
m_undo_transaction(0),
m_undo_transaction_level(0),
m_undo_transaction_lock(QMutex::Recursive),
m_meta_data()
{
// connect to the track's signals
Signal *sig = &m_signal;
connect(sig, SIGNAL(sigTrackInserted(unsigned int, Kwave::Track *)),
this, SLOT(slotTrackInserted(unsigned int, Kwave::Track *)));
connect(sig, SIGNAL(sigTrackDeleted(unsigned int)),
this, SLOT(slotTrackDeleted(unsigned int)));
connect(sig, SIGNAL(sigSamplesDeleted(unsigned int, sample_index_t,
sample_index_t)),
this, SLOT(slotSamplesDeleted(unsigned int, sample_index_t,
sample_index_t)));
connect(sig, SIGNAL(sigSamplesInserted(unsigned int, sample_index_t,
sample_index_t)),
this, SLOT(slotSamplesInserted(unsigned int, sample_index_t,
sample_index_t)));
connect(sig, SIGNAL(sigSamplesModified(unsigned int, sample_index_t,
sample_index_t)),
this, SLOT(slotSamplesModified(unsigned int, sample_index_t,
sample_index_t)));
}
//***************************************************************************
SignalManager::~SignalManager()
{
close();
}
//***************************************************************************
int SignalManager::loadFile(const KUrl &url)
{
int res = 0;
FileProgress *dialog = 0;
// enter and stay in not modified state
enableModifiedChange(true);
setModified(false);
enableModifiedChange(false);
// disable undo (discards all undo/redo data)
disableUndo();
QString mimetype = CodecManager::whatContains(url);
qDebug("SignalManager::loadFile(%s) - [%s]",
url.prettyUrl().toLocal8Bit().data(),
mimetype.toLocal8Bit().data());
Decoder *decoder = CodecManager::decoder(mimetype);
while (decoder) {
// be sure that the current signal is really closed
m_signal.close();
// open the source file
QString filename = url.path();
QFile src(filename);
if (!(res = decoder->open(m_parent_widget, src))) {
qWarning("unable to open source: '%s'",
url.prettyUrl().toLocal8Bit().data());
res = -EIO;
break;
}
// get the initial meta data from the decoder
m_meta_data = decoder->metaData();
FileInfo info(m_meta_data);
// detect stream mode. if so, use one sample as display
bool streaming = (!info.length());
// we must change to open state to see the file while
// it is loaded
m_closed = false;
m_empty = false;
// create all tracks (empty)
unsigned int track;
const unsigned int tracks = info.tracks();
const sample_index_t length = info.length();
Q_ASSERT(tracks);
if (!tracks) break;
for (track = 0; track < tracks; ++track) {
Kwave::Track *t = m_signal.appendTrack(length);
Q_ASSERT(t);
if (!t || (t->length() != length)) {
qWarning("out of memory");
res = -ENOMEM;
break;
}
}
if (track < tracks) break;
// create the multitrack writer as destination
// if length was zero -> append mode / decode a stream ?
InsertMode mode = (streaming) ? Append : Overwrite;
Kwave::MultiTrackWriter writers(*this, allTracks(), mode, 0,
(length) ? length-1 : 0);
// try to calculate the resulting length, but if this is
// not possible, we try to use the source length instead
unsigned int resulting_size = info.tracks() * info.length() *
(info.bits() >> 3);
bool use_src_size = (!resulting_size);
if (use_src_size) resulting_size = src.size();
//prepare and show the progress dialog
dialog = new FileProgress(m_parent_widget,
filename, resulting_size,
info.length(), info.rate(), info.bits(), info.tracks());
Q_ASSERT(dialog);
if (use_src_size) {
// use source size for progress / stream mode
QObject::connect(decoder, SIGNAL(sourceProcessed(quint64)),
dialog, SLOT(setBytePosition(quint64)));
QObject::connect(&writers, SIGNAL(written(quint64)),
dialog, SLOT(setLength(quint64)));
} else {
// use resulting size percentage for progress
QObject::connect(&writers, SIGNAL(progress(qreal)),
dialog, SLOT(setValue(qreal)));
}
QObject::connect(dialog, SIGNAL(canceled()),
&writers, SLOT(cancel()));
// now decode
res = 0;
if (!decoder->decode(m_parent_widget, writers)) {
qWarning("decoding failed.");
res = -EIO;
} else {
// read information back from the decoder, some settings
// might have become available during the decoding process
m_meta_data = decoder->metaData();
info = FileInfo(m_meta_data);
}
decoder->close();
// check for length info in stream mode
if (!res && streaming) {
// source was opened in stream mode -> now we have the length
writers.flush();
sample_index_t new_length = writers.last();
if (new_length) new_length++;
info.setLength(new_length);
} else {
info.setLength(this->length());
info.setTracks(tracks);
}
// enter the filename/mimetype and size into the file info
QFileInfo fi(src);
info.set(INF_FILENAME, fi.absoluteFilePath());
info.set(INF_FILESIZE, static_cast<unsigned int>(src.size()));
info.set(INF_MIMETYPE, mimetype);
// take over the decoded and updated file info
m_meta_data.replace(info);
// update the length info in the progress dialog if needed
if (dialog && use_src_size) {
dialog->setLength(
quint64(info.length()) *
quint64(info.tracks()));
dialog->setBytePosition(src.size());
}
break;
}
if (!decoder) {
qWarning("unknown file type");
res = -EINVAL;
} else {
delete decoder;
}
// remember the last length and selection
m_last_length = length();
rememberCurrentSelection();
// from now on, undo is enabled
enableUndo();
// modified can change from now on
enableModifiedChange(true);
if (dialog) delete dialog;
if (res) close();
m_meta_data.dump();
// we now have new meta data
emit sigMetaDataChanged(m_meta_data);
return res;
}
//***************************************************************************
int SignalManager::save(const KUrl &url, bool selection)
{
int res = 0;
sample_index_t ofs = 0;
sample_index_t len = length();
unsigned int tracks = this->tracks();
unsigned int bits = this->bits();
if (selection) {
// zero-length -> nothing to do
ofs = m_selection.offset();
len = m_selection.length();
tracks = selectedTracks().count();
}
if (!tracks || !len) {
Kwave::MessageBox::error(m_parent_widget,
i18n("Signal is empty, nothing to save."));
return 0;
}
QString mimetype_name;
mimetype_name = CodecManager::whatContains(url);
qDebug("SignalManager::save(%s) - [%s] (%d bit, selection=%d)",
url.prettyUrl().toLocal8Bit().data(),
mimetype_name.toLocal8Bit().data(),
bits, selection);
Encoder *encoder = CodecManager::encoder(mimetype_name);
FileInfo file_info(m_meta_data);
if (encoder) {
// maybe we now have a new mime type
file_info.set(INF_MIMETYPE, mimetype_name);
// check if we lose information and ask the user if this would
// be acceptable if so
QList<FileProperty> supported = encoder->supportedProperties();
QMap<FileProperty, QVariant> properties(file_info.properties());
bool all_supported = true;
QMap<FileProperty, QVariant>::Iterator it;
QString lost_properties;
for (it = properties.begin(); it != properties.end(); ++it) {
if ( (! supported.contains(it.key())) &&
(file_info.canLoadSave(it.key())) )
{
qWarning("SignalManager::save(): unsupported property '%s'",
file_info.name(it.key()).toLocal8Bit().data());
all_supported = false;
lost_properties += i18n("%1", file_info.name(it.key()))
+ "\n";
}
}
if (!all_supported) {
// show a warning to the user and ask him if he wants to continue
if (Kwave::MessageBox::warningContinueCancel(m_parent_widget,
i18n("Saving in this format will lose the following "
"additional file attribute(s):\n"
"%1\n"
"Do you still want to continue?",
lost_properties)
) != KMessageBox::Continue)
{
delete encoder;
return -1;
}
}
// open the destination file
QString filename = url.path();
QFile dst(filename);
MultiTrackReader src(Kwave::SinglePassForward, *this,
(selection) ? selectedTracks() : allTracks(),
ofs, ofs+len-1);
// update the file information
file_info.setLength(len);
file_info.setRate(rate());
file_info.setBits(bits);
file_info.setTracks(tracks);
if (!file_info.contains(INF_SOFTWARE) &&
encoder->supportedProperties().contains(INF_SOFTWARE))
{
// add our Kwave Software tag
const KAboutData *about_data =
KGlobal::mainComponent().aboutData();
QString software = about_data->programName() + "-" +
about_data->version() +
i18n(" for KDE ") +
i18n(KDE_VERSION_STRING);
qDebug("adding software tag: '%s'",
software.toLocal8Bit().data());
file_info.set(INF_SOFTWARE, software);
}
if (!file_info.contains(INF_CREATION_DATE) &&
encoder->supportedProperties().contains(INF_CREATION_DATE))
{
// add a date tag
QDate now(QDate::currentDate());
QString date;
date = date.sprintf("%04d-%02d-%02d",
now.year(), now.month(), now.day());
QVariant value = date.toUtf8();
qDebug("adding date tag: '%s'",
date.toLocal8Bit().data());
file_info.set(INF_CREATION_DATE, value);
}
// prepare and show the progress dialog
FileProgress *dialog = new FileProgress(m_parent_widget,
filename, file_info.tracks() * file_info.length() *
(file_info.bits() >> 3),
file_info.length(), file_info.rate(), file_info.bits(),
file_info.tracks());
Q_ASSERT(dialog);
QObject::connect(&src, SIGNAL(progress(qreal)),
dialog, SLOT(setValue(qreal)),
Qt::QueuedConnection);
QObject::connect(dialog, SIGNAL(canceled()),
&src, SLOT(cancel()));
// invoke the encoder...
bool encoded = false;
m_meta_data.replace(file_info);
if (selection) {
// use a copy, don't touch the original !
Kwave::MetaDataList meta = m_meta_data;
// we have to adjust all position aware meta data
meta.cropByRange(ofs, ofs + len - 1);
// filter out all the track bound meta data that is not selected
meta.cropByTracks(selectedTracks());
// set the filename in the copy of the fileinfo, the original
// file which is currently open keeps it's name
FileInfo info(meta);
info.set(INF_FILENAME, filename);
meta.replace(info);
encoded = encoder->encode(m_parent_widget, src, dst, meta);
} else {
// in case of a "save as" -> modify the current filename
file_info.set(INF_FILENAME, filename);
m_meta_data.replace(file_info);
encoded = encoder->encode(m_parent_widget, src, dst, m_meta_data);
}
if (!encoded) {
Kwave::MessageBox::error(m_parent_widget,
i18n("An error occurred while saving the file."));
res = -1;
}
qApp->flush();
delete encoder;
if (dialog) {
if (dialog->isCanceled()) {
// user really pressed cancel !
Kwave::MessageBox::error(m_parent_widget,
i18n("The file has been truncated and "\
"might be corrupted."));
}
dialog->deleteLater();
qApp->flush();
}
} else {
Kwave::MessageBox::error(m_parent_widget,
i18n("Sorry, the file type is not supported."));
res = -EINVAL;
}
if (!res) {
// saved without error -> no longer modified
flushUndoBuffers();
enableModifiedChange(true);
setModified(false);
}
emit sigMetaDataChanged(m_meta_data);
qDebug("SignalManager::save(): res=%d",res);
return res;
}
//***************************************************************************
void SignalManager::newSignal(sample_index_t samples, double rate,
unsigned int bits, unsigned int tracks)
{
// enter and stay in modified state
enableModifiedChange(true);
setModified(true);
enableModifiedChange(false);
// disable undo (discards all undo/redo data)
disableUndo();
m_meta_data.clear();
FileInfo file_info(m_meta_data);
file_info.setRate(rate);
file_info.setBits(bits);
file_info.setTracks(tracks);
m_meta_data.replace(file_info);
// now the signal is considered not to be empty
m_closed = false;
m_empty = false;
// add all empty tracks
while (tracks--) m_signal.appendTrack(samples);
// remember the last length
m_last_length = samples;
file_info.setLength(length());
m_meta_data.replace(file_info);
rememberCurrentSelection();
// from now on, undo is enabled
enableUndo();
emit sigMetaDataChanged(m_meta_data);
}
//***************************************************************************
void SignalManager::close()
{
// stop the playback
m_playback_controller.playbackStop();
m_playback_controller.reset();
// fix the modified flag to false
enableModifiedChange(true);
setModified(false);
enableModifiedChange(false);
// reset the last length of the signal
m_last_length = 0;
// disable undo and discard all undo buffers
// undo will be re-enabled when a signal is loaded or created
disableUndo();
// for safety: flush all undo/redo buffers
flushUndoBuffers();
flushRedoBuffer();
// reset the selection
m_selection.clear();
m_empty = true;
while (tracks()) deleteTrack(tracks()-1);
m_signal.close();
// clear all meta data
m_meta_data.clear();
m_closed = true;
rememberCurrentSelection();
emit sigMetaDataChanged(m_meta_data);
}
//***************************************************************************
QString SignalManager::signalName()
{
// if a file is loaded -> path of the URL if it has one
KUrl url;
url = FileInfo(m_meta_data).get(INF_FILENAME).toString();
if (url.isValid()) return url.path();
// we have something, but no name yet
if (!isClosed()) return QString(NEW_FILENAME);
// otherwise: closed, nothing loaded
return "";
}
//***************************************************************************
const QList<unsigned int> SignalManager::selectedTracks()
{
unsigned int track;
QList<unsigned int> list;
const unsigned int tracks = this->tracks();
for (track = 0; track < tracks; track++) {
if (!m_signal.trackSelected(track)) continue;
list.append(track);
}
return list;
}
//***************************************************************************
const QList<unsigned int> SignalManager::allTracks()
{
return m_signal.allTracks();
}
//***************************************************************************
Kwave::Writer *SignalManager::openWriter(unsigned int track,
InsertMode mode, sample_index_t left, sample_index_t right)
{
return m_signal.openWriter(track, mode, left, right);
}
//***************************************************************************
int SignalManager::executeCommand(const QString &command)
{
sample_index_t offset = m_selection.offset();
sample_index_t length = m_selection.length();
if (!command.length()) return -EINVAL;
Parser parser(command);
if (false) {
// --- undo / redo ---
CASE_COMMAND("undo")
undo();
CASE_COMMAND("redo")
redo();
// --- copy & paste + clipboard ---
CASE_COMMAND("copy")
if (length) {
ClipBoard &clip = ClipBoard::instance();
clip.copy(
m_parent_widget,
*this,
selectedTracks(),
offset, length
);
// remember the last selection
rememberCurrentSelection();
}
CASE_COMMAND("insert_at")
ClipBoard &clip = ClipBoard::instance();
if (clip.isEmpty()) return 0;
if (!selectedTracks().size()) return 0;
sample_index_t offset = parser.toUInt();
UndoTransactionGuard undo(*this, i18n("Insert Clipboard at position"));
selectRange(offset, 0);
clip.paste(m_parent_widget, *this, offset, 0);
CASE_COMMAND("paste")
ClipBoard &clip = ClipBoard::instance();
if (clip.isEmpty()) return 0;
if (!selectedTracks().size()) return 0;
UndoTransactionGuard undo(*this, i18n("Paste"));
clip.paste(m_parent_widget, *this, offset, length);
CASE_COMMAND("cut")
if (length) {
// remember the last selection
rememberCurrentSelection();
ClipBoard &clip = ClipBoard::instance();
clip.copy(
m_parent_widget,
*this,
selectedTracks(),
offset, length
);
UndoTransactionGuard undo(*this, i18n("Cut"));
deleteRange(offset, length);
selectRange(m_selection.offset(), 0);
}
CASE_COMMAND("clipboard_flush")
ClipBoard::instance().clear();
CASE_COMMAND("crop")
UndoTransactionGuard undo(*this, i18n("Crop"));
sample_index_t rest = this->length() - offset;
rest = (rest > length) ? (rest-length) : 0;
QList<unsigned int> tracks = selectedTracks();
if (saveUndoDelete(tracks, offset+length, rest) &&
saveUndoDelete(tracks, 0, offset))
{
// remember the last selection
rememberCurrentSelection();
unsigned int count = tracks.count();
while (count--) {
m_signal.deleteRange(count, offset+length, rest);
m_signal.deleteRange(count, 0, offset);
}
selectRange(0, length);
}
CASE_COMMAND("delete")
UndoTransactionGuard undo(*this, i18n("Delete"));
deleteRange(offset, length);
selectRange(m_selection.offset(), 0);
// CASE_COMMAND("mixpaste")
// if (globals.clipboard) {
// SignalManager *toinsert = globals.clipboard->getSignal();
// if (toinsert) {
// unsigned int clipchan = toinsert->channels();
// unsigned int sourcechan = 0;
//
// /* ### check if the signal has to be re-sampled ### */
//
// for (unsigned int i = 0; i < m_channels; i++) {
// Q_ASSERT(signal.at(i));
// if (signal.at(i)) {
// signal.at(i)->mixPaste(
// toinsert->getSignal(sourcechan)
// );
// }
// sourcechan++;
// sourcechan %= clipchan;
// }
// }
// }
CASE_COMMAND("delete_label")
int index = parser.toInt();
deleteLabel(index, true);
CASE_COMMAND("expandtolabel")
UndoTransactionGuard undo(*this, i18n("Expand Selection to Label"));
sample_index_t selection_left = m_selection.first();
sample_index_t selection_right = m_selection.last();
LabelList labels(m_meta_data);
if (labels.isEmpty()) return false; // we need labels for this
Label label_left = Label();
Label label_right = Label();
// the last label <= selection start -> label_left
// the first label >= selection end -> label_right
foreach (Label label, labels) {
sample_index_t lp = label.pos();
if (lp <= selection_left)
label_left = label;
if ((lp >= selection_right) && (label_right.isNull())) {
label_right = label;
break; // done
}
}
// default left label = start of file
selection_left = (label_left.isNull()) ? 0 :
label_left.pos();
// default right label = end of file
selection_right = (label_right.isNull()) ?
(this->length() - 1) : label_right.pos();
sample_index_t len = selection_right - selection_left + 1;
selectRange(selection_left, len);
CASE_COMMAND("selectnextlabels")
UndoTransactionGuard undo(*this, i18n("Select Next Labels"));
sample_index_t selection_left;
sample_index_t selection_right = m_selection.last();
Label label_left = Label();
Label label_right = Label();
LabelList labels(m_meta_data);
if (labels.isEmpty()) return false; // we need labels for this
// special case: nothing selected -> select up to the first label
if (selection_right == 0) {
label_right = labels.first();
selection_left = 0;
} else {
// find the first label starting after the current selection
LabelListIterator it(labels);
while (it.hasNext()) {
Label label = it.next();
if (label.pos() >= selection_right) {
// take it as selection start
label_left = label;
// and it's next one as selection end (might be null)
label_right = it.hasNext() ? it.next() : Label();
break;
}
}
// default selection start = last label
if (label_left.isNull()) label_left = labels.last();
if (label_left.isNull()) return false; // no labels at all !?
selection_left = label_left.pos();
}
// default selection end = end of the file
selection_right = (label_right.isNull()) ?
(this->length() - 1) : label_right.pos();
sample_index_t len = selection_right - selection_left + 1;
selectRange(selection_left, len);
CASE_COMMAND("selectprevlabels")
UndoTransactionGuard undo(*this, i18n("Select Previous Labels"));
sample_index_t selection_left = selection().first();
sample_index_t selection_right = selection().last();
Label label_left = Label();
Label label_right = Label();
LabelList labels(m_meta_data);
if (labels.isEmpty()) return false; // we need labels for this
// find the last label before the start of the selection
foreach (Label label, labels) {
if (label.pos() > selection_left)
break; // done
label_left = label_right;
label_right = label;
}
// default selection start = start of file
selection_left = (label_left.isNull()) ? 0 :
label_left.pos();
// default selection end = first label
if (label_right.isNull()) label_right = labels.first();
if (label_right.isNull()) return false; // no labels at all !?
selection_right = label_right.pos();
sample_index_t len = selection_right - selection_left + 1;
selectRange(selection_left, len);
// --- track related functions ---
CASE_COMMAND("add_track")
appendTrack();
CASE_COMMAND("delete_track")
Parser parser(command);
unsigned int track = parser.toUInt();
deleteTrack(track);
CASE_COMMAND("insert_track")
Parser parser(command);
unsigned int track = parser.toUInt();
insertTrack(track);
// track selection
CASE_COMMAND("select_all_tracks")
UndoTransactionGuard undo(*this, i18n("Select All Tracks"));
foreach (unsigned int track, allTracks())
selectTrack(track, true);
CASE_COMMAND("deselect_all_tracks")
UndoTransactionGuard undo(*this, i18n("Deselect all tracks"));
foreach (unsigned int track, allTracks())
selectTrack(track, false);
CASE_COMMAND("invert_track_selection")
UndoTransactionGuard undo(*this, i18n("Invert Track Selection"));
foreach (unsigned int track, allTracks())
selectTrack(track, !trackSelected(track));
CASE_COMMAND("select_track")
int track = parser.toInt();
UndoTransactionGuard undo(*this, i18n("Select Track"));
selectTrack(track, true);
CASE_COMMAND("deselect_track")
int track = parser.toInt();
UndoTransactionGuard undo(*this, i18n("Deselect Track"));
selectTrack(track, false);
CASE_COMMAND("toggle_track_selection")
int track = parser.toInt();
UndoTransactionGuard undo(*this, i18n("Toggle Track Selection"));
selectTrack(track, !(trackSelected(track)));
CASE_COMMAND("dump_metadata")
qDebug("DUMP OF META DATA => %s",
parser.firstParam().toLocal8Bit().data());
m_meta_data.dump();
} else {
return -ENOSYS;
}
return 0;
}
//***************************************************************************
void SignalManager::appendTrack()
{
UndoTransactionGuard u(*this, i18n("Append Track"));
insertTrack(tracks());
}
//***************************************************************************
void SignalManager::insertTrack(unsigned int index)
{
UndoTransactionGuard u(*this, i18n("Insert Track"));
const unsigned int count = tracks();
Q_ASSERT(index <= count);
if (index > count) index = count;
// undo action for the track insert
if (m_undo_enabled && !registerUndoAction(
new UndoInsertTrack(m_signal, index))) return;
// if the signal is currently empty, use the last
// known length instead of the current one
sample_index_t len = (count) ? length() : m_last_length;
if (index >= count) {
// do an "append"
m_signal.appendTrack(len);
} else {
if (m_undo_enabled) {
// undo action for the corresponding meta data change
QList<unsigned int> tracks;
for (unsigned int t = index; t < count; t++) tracks.append(t);
Kwave::MetaDataList list = m_meta_data.selectByTracks(tracks);
if (!list.isEmpty() && !registerUndoAction(
new UndoModifyMetaDataAction(list))) return;
}
// adjust the track bound meta data
m_meta_data.insertTrack(index);
// insert into the list
m_signal.insertTrack(index, len);
}
// remember the last length
m_last_length = length();
}
//***************************************************************************
void SignalManager::deleteTrack(unsigned int index)
{
UndoTransactionGuard u(*this, i18n("Delete Track"));
const unsigned int count = tracks();
Q_ASSERT(index <= count);
if (index > count) return;
if (m_undo_enabled) {
// undo action for the track deletion
if (!registerUndoAction(new UndoDeleteTrack(m_signal, index))) return;
// undo action for the corresponding meta data change
QList<unsigned int> tracks;
for (unsigned int t = index; t < count; t++) tracks.append(t);
Kwave::MetaDataList list = m_meta_data.selectByTracks(tracks);
if (!list.isEmpty() && !registerUndoAction(
new UndoModifyMetaDataAction(list))) return;
}
// adjust the track bound meta data
m_meta_data.deleteTrack(index);
setModified(true);
m_signal.deleteTrack(index);
}
//***************************************************************************
void SignalManager::slotTrackInserted(unsigned int index,
Kwave::Track *track)
{
setModified(true);
FileInfo file_info(m_meta_data);
file_info.setTracks(tracks());
m_meta_data.replace(file_info);
emit sigTrackInserted(index, track);
emit sigMetaDataChanged(m_meta_data);
}
//***************************************************************************
void SignalManager::slotTrackDeleted(unsigned int index)
{
setModified(true);
FileInfo file_info(m_meta_data);
file_info.setTracks(tracks());
m_meta_data.replace(file_info);
emit sigTrackDeleted(index);
emit sigMetaDataChanged(m_meta_data);
}
//***************************************************************************
void SignalManager::slotSamplesInserted(unsigned int track,
sample_index_t offset, sample_index_t length)
{
// remember the last known length
m_last_length = m_signal.length();
setModified(true);
// only adjust the meta data once per operation
QList<unsigned int> tracks = selectedTracks();
if (track == tracks[0]) {
m_meta_data.shiftRight(offset, length, tracks);
}
emit sigSamplesInserted(track, offset, length);
FileInfo info(m_meta_data);
info.setLength(m_last_length);
m_meta_data.replace(info);
emit sigMetaDataChanged(m_meta_data);
}
//***************************************************************************
void SignalManager::slotSamplesDeleted(unsigned int track,
sample_index_t offset, sample_index_t length)
{
// remember the last known length
m_last_length = m_signal.length();
setModified(true);
// only adjust the meta data once per operation
QList<unsigned int> tracks = selectedTracks();
if (track == tracks[0]) {
m_meta_data.shiftLeft(offset, length, tracks);
}
emit sigSamplesDeleted(track, offset, length);
FileInfo info(m_meta_data);
info.setLength(m_last_length);
m_meta_data.replace(info);
emit sigMetaDataChanged(m_meta_data);
}
//***************************************************************************
void SignalManager::slotSamplesModified(unsigned int track,
sample_index_t offset, sample_index_t length)
{
setModified(true);
emit sigSamplesModified(track, offset, length);
}
//***************************************************************************
bool SignalManager::deleteRange(sample_index_t offset, sample_index_t length,
const QList<unsigned int> &track_list)
{
if (!length || track_list.isEmpty()) return true; // nothing to do
// put the selected meta data into a undo action
if (m_undo_enabled) {
if (!registerUndoAction(new UndoDeleteMetaDataAction(
m_meta_data.copy(offset, length, track_list))))
{
abortUndoTransaction();
return false;
}
m_meta_data.deleteRange(offset, length, track_list);
// store undo data for all audio data (without meta data)
if (!registerUndoAction(new UndoDeleteAction(
m_parent_widget, track_list, offset, length)))
{
abortUndoTransaction();
return false;
}
} else {
// delete without undo
m_meta_data.deleteRange(offset, length, track_list);
}
// delete the ranges in all tracks
// (this makes all metadata positions after the selected range invalid)
foreach (unsigned int track, track_list) {
m_signal.deleteRange(track, offset, length);
}
emit sigMetaDataChanged(m_meta_data);
return true;
}
//***************************************************************************
bool SignalManager::deleteRange(sample_index_t offset, sample_index_t length)
{
return deleteRange(offset, length, selectedTracks());
}
//***************************************************************************
bool SignalManager::insertSpace(sample_index_t offset, sample_index_t length,
const QList<unsigned int> &track_list)
{
if (!length) return true; // nothing to do
UndoTransactionGuard undo(*this, i18n("Insert Space"));
unsigned int count = track_list.count();
if (!count) return true; // nothing to do
// first store undo data for all tracks
unsigned int track;
if (m_undo_enabled) {
if (!registerUndoAction(new UndoInsertAction(
m_parent_widget, track_list, offset, length))) return false;
}
// then insert space into all tracks
foreach (track, track_list) {
m_signal.insertSpace(track, offset, length);
}
return true;
}
//***************************************************************************
void SignalManager::selectRange(sample_index_t offset, sample_index_t length)
{
// first do some range checking
sample_index_t len = this->length();
if (offset >= len) offset = len ? (len - 1) : 0;
if ((offset + length) > len) length = len - offset;
m_selection.select(offset, length);
}
//***************************************************************************
void SignalManager::selectTracks(QList<unsigned int> &track_list)
{
unsigned int track;
unsigned int n_tracks = tracks();
for (track = 0; track < n_tracks; track++) {
bool old_select = m_signal.trackSelected(track);
bool new_select = track_list.contains(track);
if (new_select != old_select) {
m_signal.selectTrack(track, new_select);
}
}
}
//***************************************************************************
void SignalManager::selectTrack(unsigned int track, bool select)
{
bool old_select = m_signal.trackSelected(track);
if (select != old_select) {
m_signal.selectTrack(track, select);
// if selection changed during playback, reload with pause/continue
if (m_playback_controller.running()) {
m_playback_controller.reload();
}
}
}
//***************************************************************************
PlaybackController &SignalManager::playbackController()
{
return m_playback_controller;
}
//***************************************************************************
void SignalManager::startUndoTransaction(const QString &name)
{
if (!m_undo_enabled) return; // undo is currently not enabled
QMutexLocker lock(&m_undo_transaction_lock);
// check for modified selection
checkSelectionChange();
// increase recursion level
m_undo_transaction_level++;
// start/create a new transaction if none existing
if (!m_undo_transaction) {
// if a new action starts, discard all redo actions !
flushRedoBuffer();
m_undo_transaction = new UndoTransaction(name);
Q_ASSERT(m_undo_transaction);
if (!m_undo_transaction) return;
// if it is the start of the transaction, also create one
// for the selection
UndoAction *selection = new UndoSelection(*this);
Q_ASSERT(selection);
if (selection) {
if (selection->store(*this)) {
m_undo_transaction->append(selection);
} else {
// out of memory
delete selection;
delete m_undo_transaction;
m_undo_transaction = 0;
}
}
}
}
//***************************************************************************
void SignalManager::closeUndoTransaction()
{
QMutexLocker lock(&m_undo_transaction_lock);
// decrease recursion level
if (!m_undo_transaction_level) return; // undo was not enabled ?
m_undo_transaction_level--;
if (!m_undo_transaction_level) {
// append the current transaction to the undo buffer if
// not empty
if (m_undo_transaction) {
if (!m_undo_transaction->isEmpty()) {
// if the transaction has been aborted, undo all actions
// that have currently been queued but do not
// use the transaction any more, instead delete it.
if (m_undo_transaction->isAborted()) {
qDebug("SignalManager::closeUndoTransaction(): aborted");
while (!m_undo_transaction->isEmpty()) {
UndoAction *undo_action;
UndoAction *redo_action;
// unqueue the undo action
undo_action = m_undo_transaction->takeLast();
Q_ASSERT(undo_action);
if (!undo_action) continue;
// execute the undo operation
redo_action = undo_action->undo(*this, false);
// remove the old undo action if no longer used
if (redo_action && (redo_action != undo_action))
delete redo_action;
delete undo_action;
}
delete m_undo_transaction;
m_undo_transaction = 0;
} else {
m_undo_buffer.append(m_undo_transaction);
}
} else {
qDebug("SignalManager::closeUndoTransaction(): empty");
delete m_undo_transaction;
m_undo_transaction = 0;
}
}
// dump, for debugging
// if (m_undo_transaction)
// m_undo_transaction->dump("closed undo transaction: ");
// declare the current transaction as "closed"
rememberCurrentSelection();
m_undo_transaction = 0;
emitUndoRedoInfo();
}
}
//***************************************************************************
void SignalManager::enableUndo()
{
m_undo_enabled = true;
emitUndoRedoInfo();
}
//***************************************************************************
void SignalManager::disableUndo()
{
Q_ASSERT(m_undo_transaction_level == 0);
flushUndoBuffers();
m_undo_enabled = false;
}
//***************************************************************************
void SignalManager::flushUndoBuffers()
{
QMutexLocker lock(&m_undo_transaction_lock);
// if the signal was modified, it will stay in this state, it is
// not possible to change to "non-modified" state through undo
if ((!m_undo_buffer.isEmpty()) && (m_modified)) {
enableModifiedChange(false);
}
// clear all buffers
qDeleteAll(m_undo_buffer);
qDeleteAll(m_redo_buffer);
m_undo_buffer.clear();
m_redo_buffer.clear();
emitUndoRedoInfo();
}
//***************************************************************************
void SignalManager::abortUndoTransaction()
{
// abort the current transaction
if (m_undo_transaction) m_undo_transaction->abort();
}
//***************************************************************************
void SignalManager::flushRedoBuffer()
{
qDeleteAll(m_redo_buffer);
m_redo_buffer.clear();
emitUndoRedoInfo();
}
//***************************************************************************
bool SignalManager::continueWithoutUndo()
{
// undo has not been enabled before?
if (!m_undo_transaction) return true;
// transaction has been aborted before
if (m_undo_transaction->isAborted()) return false;
// transaction is empty -> must have been flushed before, otherwise
// it would contain at least a undo action for the selection
// => user already has pressed "continue"
if (m_undo_transaction->isEmpty()) return true;
if (Kwave::MessageBox::warningContinueCancel(m_parent_widget,
"<html>"+i18n("Not enough memory for saving undo information.") +
"<br><br><b>"+
i18n("Do you want to continue without the possibility to undo?") +
"</b><br><br><i>" +
i18n("<b>Hint</b>: you can configure the amount of memory<br>"
"available for undo under '%1'/'%2'.").arg(
i18n("&Options").replace(QRegExp("&(.)"), "<u>\\1</u>")).arg(
i18n("&Memory").replace(QRegExp("&(.)"), "<u>\\1</u>") +
"</i></html>")) == KMessageBox::Continue)
{
// the signal was modified, it will stay in this state, it is
// not possible to change to "non-modified" state through undo
// from now on...
setModified(true);
enableModifiedChange(false);
// flush the current undo transaction
while (!m_undo_transaction->isEmpty()) {
UndoAction *undo_action = m_undo_transaction->takeLast();
if (undo_action) delete undo_action;
}
// flush all undo/redo buffers
flushUndoBuffers();
return true;
}
// Set the undo transaction into "aborted" state. The final
// closeUndoTransaction() will take care of the rest when
// detecting that state and clean up...
abortUndoTransaction();
return false;
}
//***************************************************************************
bool SignalManager::registerUndoAction(UndoAction *action)
{
QMutexLocker lock(&m_undo_transaction_lock);
if (!action) return continueWithoutUndo();
// if undo is not enabled, this will fail -> discard the action
if (!m_undo_enabled) {
delete action;
return true;
}
// check if the undo action is too large
unsigned int limit_mb = Kwave::MemoryManager::instance().undoLimit();
unsigned int needed_size = action->undoSize();
unsigned int needed_mb = needed_size >> 20;
if (needed_mb > limit_mb) {
delete action;
return continueWithoutUndo();
}
// undo has been aborted before ?
if (!m_undo_transaction) return true;
// transaction has been aborted before
if (m_undo_transaction->isAborted()) {
delete action;
return true;
}
// make room...
freeUndoMemory(needed_size);
// now we might have enough place to append the undo action
// and store all undo info
if (!action->store(*this)) {
delete action;
return continueWithoutUndo();
}
// everything went ok, register internally
m_undo_transaction->append(action);
return true;
}
//***************************************************************************
bool SignalManager::saveUndoDelete(QList<unsigned int> &track_list,
sample_index_t offset, sample_index_t length)
{
if (!m_undo_enabled) return true;
if (track_list.isEmpty()) return true;
// create a undo action for deletion
UndoDeleteAction *action =
new UndoDeleteAction(m_parent_widget, track_list, offset, length);
if (!registerUndoAction(action)) return false;
return true;
}
//***************************************************************************
unsigned int SignalManager::usedUndoRedoMemory()
{
unsigned int size = 0;
foreach (UndoTransaction *undo, m_undo_buffer)
if (undo) size += undo->undoSize();
foreach (UndoTransaction *redo, m_redo_buffer)
if (redo) size += redo->undoSize();
return size;
}
//***************************************************************************
void SignalManager::freeUndoMemory(unsigned int needed)
{
unsigned int size = usedUndoRedoMemory() + needed;
unsigned int undo_limit =
Kwave::MemoryManager::instance().undoLimit() << 20;
// remove old undo actions if not enough free memory
while (!m_undo_buffer.isEmpty() && (size > undo_limit)) {
UndoTransaction *undo = m_undo_buffer.takeFirst();
if (!undo) continue;
unsigned int s = undo->undoSize();
size = (size >= s) ? (size - s) : 0;
delete undo;
// if the signal was modified, it will stay in this state, it is
// not possible to change to "non-modified" state through undo
if (m_modified) enableModifiedChange(false);
}
// remove old redo actions if still not enough memory
while (!m_redo_buffer.isEmpty() && (size > undo_limit)) {
UndoTransaction *redo = m_redo_buffer.takeLast();
if (!redo) continue;
unsigned int s = redo->undoSize();
size = (size >= s) ? (size - s) : 0;
delete redo;
}
}
//***************************************************************************
void SignalManager::emitUndoRedoInfo()
{
QString undo_name = 0;
QString redo_name = 0;
if (m_undo_enabled) {
UndoTransaction *transaction;
// get the description of the last undo action
if (!m_undo_buffer.isEmpty()) {
transaction = m_undo_buffer.last();
if (transaction) undo_name = transaction->description();
if (!undo_name.length()) undo_name = i18n("Last Action");
}
// get the description of the last redo action
if (!m_redo_buffer.isEmpty()) {
transaction = m_redo_buffer.first();
if (transaction) redo_name = transaction->description();
if (!redo_name.length()) redo_name = i18n("Last Action");
}
}
// now emit the undo/redo transaction names
emit sigUndoRedoInfo(undo_name, redo_name);
}
//***************************************************************************
void SignalManager::undo()
{
QMutexLocker lock(&m_undo_transaction_lock);
// check for modified selection
checkSelectionChange();
// remember the last selection
rememberCurrentSelection();
// get the last undo transaction and abort if none present
if (m_undo_buffer.isEmpty()) return;
UndoTransaction *undo_transaction = m_undo_buffer.takeLast();
if (!undo_transaction) return;
// dump, for debugging
// undo_transaction->dump("before undo: ");
// temporarily disable undo while undo itself is running
bool old_undo_enabled = m_undo_enabled;
m_undo_enabled = false;
// get free memory for redo
unsigned int undo_limit =
Kwave::MemoryManager::instance().undoLimit() << 20;
unsigned int redo_size = undo_transaction->redoSize();
unsigned int undo_size = undo_transaction->undoSize();
UndoTransaction *redo_transaction = 0;
if ((redo_size > undo_size) && (redo_size - undo_size > undo_limit)) {
// not enough memory for redo
qWarning("SignalManager::undo(): not enough memory for redo !");
} else {
// only free the memory if it will be used
freeUndoMemory(redo_size);
// create a new redo transaction
QString name = undo_transaction->description();
redo_transaction = new UndoTransaction(name);
Q_ASSERT(redo_transaction);
}
// if *one* redo fails, all following redoes will also fail or
// produce inconsistent data -> remove all of them !
if (!redo_transaction) {
flushRedoBuffer();
qDebug("SignalManager::undo(): redo buffer flushed!");
}
// set hourglass cursor
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
// execute all undo actions and store the resulting redo
// actions into the redo transaction
while (!undo_transaction->isEmpty()) {
UndoAction *undo_action;
UndoAction *redo_action;
// unqueue the undo action
undo_action = undo_transaction->takeLast();
Q_ASSERT(undo_action);
if (!undo_action) continue;
// execute the undo operation
redo_action = undo_action->undo(*this, (redo_transaction != 0));
// remove the old undo action if no longer used
if (redo_action != undo_action) {
delete undo_action;
}
// queue the action into the redo transaction
if (redo_action) {
if (redo_transaction) {
redo_transaction->prepend(redo_action);
} else {
// redo is not usable :-(
delete redo_action;
}
}
}
// now the undo_transaction should be empty -> get rid of it
Q_ASSERT(undo_transaction->isEmpty());
delete undo_transaction;
if (redo_transaction && (redo_transaction->count() < 1)) {
// if there is no redo action -> no redo possible
qWarning("SignalManager::undo(): no redo possible");
delete redo_transaction;
redo_transaction = 0;
}
// check whether the selection has changed, if yes: put a undo action
// for this selection change at the end of the redo transaction
if (redo_transaction) {
bool range_modified = !(m_selection == m_last_selection);
QList<unsigned int> tracks = selectedTracks();
bool tracks_modified = !(tracks == m_last_track_selection);
if (range_modified || tracks_modified) {
UndoAction *redo_action = new UndoSelection(*this,
m_last_track_selection,
m_last_selection.offset(),
m_last_selection.length());
Q_ASSERT(redo_action);
if (redo_action) redo_transaction->append(redo_action);
}
}
// find out if there is still an action in the undo buffer
// that has to do with modification of the signal
if (m_modified) {
bool stay_modified = false;
foreach (UndoTransaction *transaction, m_undo_buffer) {
if (!transaction) continue;
if (transaction->containsModification()) {
stay_modified = true;
break;
}
}
if (!stay_modified) {
// try to return to non-modified mode (might be a nop if
// not enabled)
setModified(false);
}
}
// save "redo" information if possible
if (redo_transaction)
m_redo_buffer.prepend(redo_transaction);
// remember the last selection
rememberCurrentSelection();
// re-enable undo
m_undo_enabled = old_undo_enabled;
// finished / buffers have changed, emit new undo/redo info
emitUndoRedoInfo();
// maybe the meta data has changed
emit sigMetaDataChanged(m_meta_data);
// remove hourglass
QApplication::restoreOverrideCursor();
}
//***************************************************************************
void SignalManager::redo()
{
QMutexLocker lock(&m_undo_transaction_lock);
// get the last redo transaction and abort if none present
if (m_redo_buffer.isEmpty()) return;
UndoTransaction *redo_transaction = m_redo_buffer.takeFirst();
if (!redo_transaction) return;
// check for modified selection
checkSelectionChange();
// temporarily disable undo while redo is running
bool old_undo_enabled = m_undo_enabled;
m_undo_enabled = false;
// get free memory for undo
unsigned int undo_limit =
Kwave::MemoryManager::instance().undoLimit() << 20;
unsigned int undo_size = redo_transaction->undoSize();
unsigned int redo_size = redo_transaction->redoSize();
UndoTransaction *undo_transaction = 0;
if ((undo_size > redo_size) && (undo_size - redo_size > undo_limit)) {
// not enough memory for undo
qWarning("SignalManager::redo(): not enough memory for undo !");
} else {
// only free the memory if it will be used
freeUndoMemory(undo_size);
// create a new undo transaction
QString name = redo_transaction->description();
undo_transaction = new UndoTransaction(name);
Q_ASSERT(undo_transaction);
}
// if *one* undo fails, all following undoes will also fail or
// produce inconsistent data -> remove all of them !
if (!undo_transaction) {
qDeleteAll(m_undo_buffer);
m_undo_buffer.clear();
} else {
m_undo_buffer.append(undo_transaction);
}
// set hourglass cursor
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
// execute all redo actions and store the resulting undo
// actions into the undo transaction
bool modified = false;
while (!redo_transaction->isEmpty()) {
UndoAction *undo_action;
UndoAction *redo_action;
// unqueue the undo action
redo_action = redo_transaction->takeFirst();
// execute the redo operation
Q_ASSERT(redo_action);
if (!redo_action) continue;
modified |= redo_transaction->containsModification();
undo_action = redo_action->undo(*this, (undo_transaction != 0));
// remove the old redo action if no longer used
if (redo_action != undo_action) {
delete redo_action;
}
// queue the action into the undo transaction
if (undo_action) {
if (undo_transaction) {
undo_transaction->append(undo_action);
} else {
// undo is not usable :-(
delete undo_action;
}
}
}
// now the redo_transaction should be empty -> get rid of it
Q_ASSERT(redo_transaction->isEmpty());
delete redo_transaction;
if (undo_transaction && (undo_transaction->count() < 1)) {
// if there is no undo action -> no undo possible
qWarning("SignalManager::redo(): no undo possible");
m_undo_buffer.removeAll(undo_transaction);
delete undo_transaction;
}
// if the redo operation modified something,
// we have to update the "modified" flag of the current signal
if (modified) setModified(true);
// remember the last selection
rememberCurrentSelection();
// re-enable undo
m_undo_enabled = old_undo_enabled;
// finished / buffers have changed, emit new undo/redo info
emitUndoRedoInfo();
// maybe the meta data has changed
emit sigMetaDataChanged(m_meta_data);
// remove hourglass
QApplication::restoreOverrideCursor();
}
//***************************************************************************
void SignalManager::setModified(bool mod)
{
if (!m_modified_enabled) return;
if (m_modified != mod) {
m_modified = mod;
// qDebug("SignalManager::setModified(%d)",mod);
emit sigModified(m_modified);
}
}
//***************************************************************************
void SignalManager::enableModifiedChange(bool en)
{
m_modified_enabled = en;
}
//***************************************************************************
void SignalManager::setFileInfo(FileInfo &new_info, bool with_undo)
{
if (m_undo_enabled && with_undo) {
/* save data for undo */
UndoTransactionGuard undo_transaction(*this, i18n("Modify File Info"));
FileInfo old_inf(m_meta_data);
if (!registerUndoAction(new UndoModifyMetaDataAction(old_inf))) return;
}
m_meta_data.replace(new_info);
setModified(true);
emitUndoRedoInfo();
emit sigMetaDataChanged(m_meta_data);
}
//***************************************************************************
Label SignalManager::findLabel(sample_index_t pos)
{
LabelList labels(m_meta_data);
foreach (const Label &label, labels) {
if (label.pos() == pos) return label; // found it
}
return Label(); // nothing found
}
//***************************************************************************
int SignalManager::labelIndex(const Label &label) const
{
int index = 0;
LabelList labels(m_meta_data);
foreach (const Label &l, labels) {
if (l == label) return index; // found it
index++;
}
return -1; // nothing found*/
}
//***************************************************************************
Label SignalManager::addLabel(sample_index_t pos, const QString &name)
{
// if there already is a label at the given position, do nothing
if (!findLabel(pos).isNull()) return Label();
// create a new label
Label label(pos, name);
// register the undo action
if (m_undo_enabled) {
UndoTransactionGuard undo(*this, i18n("Add Label"));
if (!registerUndoAction(new UndoAddMetaDataAction(label)))
return Label();
}
// put the label into the list
m_meta_data.add(label);
// register this as a modification
setModified(true);
emit sigMetaDataChanged(m_meta_data);
return label;
}
//***************************************************************************
void SignalManager::deleteLabel(int index, bool with_undo)
{
LabelList labels(m_meta_data);
Q_ASSERT(index >= 0);
Q_ASSERT(index < static_cast<int>(labels.count()));
if ((index < 0) || (index >= static_cast<int>(labels.count()))) return;
Kwave::MetaData label(labels.at(index));
// register the undo action
if (with_undo) {
UndoTransactionGuard undo(*this, i18n("Delete Label"));
if (!registerUndoAction(new UndoDeleteMetaDataAction(label)))
return;
}
m_meta_data.remove(label);
// register this as a modification
setModified(true);
emit sigMetaDataChanged(m_meta_data);
}
//***************************************************************************
bool SignalManager::modifyLabel(int index, sample_index_t pos,
const QString &name)
{
LabelList labels(m_meta_data);
Q_ASSERT(index >= 0);
Q_ASSERT(index < static_cast<int>(labels.count()));
if ((index < 0) || (index >= static_cast<int>(labels.count())))
return false;
Label label = labels.at(index);
// check: if the label should be moved and there already is a label
// at the new position -> fail
if ((pos != label.pos()) && !findLabel(pos).isNull())
return false;
// add a undo action
if (m_undo_enabled) {
UndoModifyMetaDataAction *undo_modify =
new UndoModifyMetaDataAction(label);
if (!registerUndoAction(undo_modify))
return false;
}
// now modify the label
label.moveTo(pos);
label.rename(name);
m_meta_data.add(label);
// register this as a modification
setModified(true);
emit sigMetaDataChanged(m_meta_data);
return true;
}
//***************************************************************************
void SignalManager::rememberCurrentSelection()
{
m_last_selection = m_selection;
m_last_track_selection = selectedTracks();
}
//***************************************************************************
void SignalManager::checkSelectionChange()
{
if (m_undo_transaction_level) return;
// detect sample selection change
bool range_modified = !(m_selection == m_last_selection);
// detect track selection change
QList<unsigned int> tracks = selectedTracks();
bool tracks_modified = !(tracks == m_last_track_selection);
if (range_modified || tracks_modified) {
// selection has changed since last undo/redo operation
// qDebug("SignalManager::checkSelectionChange() => manually modified");
// qDebug(" before: [%8u...%8u]", m_last_selection.first(), m_last_selection.last());
// qDebug(" after : [%8u...%8u]", m_selection.first(), m_selection.last());
// temporarily activate the previous selection (last stored)
Selection new_selection(m_selection);
m_selection = m_last_selection;
selectTracks(m_last_track_selection);
// save the last selection into a undo action
if (tracks_modified && !range_modified)
UndoTransactionGuard undo(*this, i18n("Manual Track Selection"));
else
UndoTransactionGuard undo(*this, i18n("Manual Selection"));
// restore the current selection again
m_selection = new_selection;
selectTracks(tracks);
}
}
//***************************************************************************
#include "SignalManager.moc"
//***************************************************************************
//***************************************************************************