File: SignalManager.cpp

package info (click to toggle)
kwave 25.04.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 23,272 kB
  • sloc: cpp: 56,173; xml: 817; perl: 688; sh: 57; makefile: 11
file content (2017 lines) | stat: -rw-r--r-- 69,302 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
/***************************************************************************
       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 <math.h>

#include <new>

#include <QApplication>
#include <QByteArray>
#include <QCursor>
#include <QDate>
#include <QFile>
#include <QFileInfo>
#include <QMutableListIterator>
#include <QMutexLocker>
#include <QUrl>
#include <QVector>

#include <KAboutData>
#include <KLocalizedString>
#include <kxmlgui_version.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/LabelList.h"
#include "libkwave/MessageBox.h"
#include "libkwave/MultiTrackReader.h"
#include "libkwave/MultiTrackWriter.h"
#include "libkwave/Parser.h"
#include "libkwave/Sample.h"
#include "libkwave/Signal.h"
#include "libkwave/SignalManager.h"
#include "libkwave/String.h"
#include "libkwave/Track.h"
#include "libkwave/Utils.h"
#include "libkwave/Writer.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"
#include "libkwave/undo/UndoTransactionGuard.h"

#define CASE_COMMAND(x) } else if (parser.command() == _(x)) {

//***************************************************************************
Kwave::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(*this),
    m_undo_enabled(false),
    m_undo_buffer(),
    m_redo_buffer(),
    m_undo_transaction(nullptr),
    m_undo_transaction_level(0),
    m_undo_transaction_lock(),
    m_meta_data()
{
    // connect to the track's signals
    Kwave::Signal *sig = &m_signal;
    connect(sig, SIGNAL(sigTrackInserted(uint,Kwave::Track*)),
            this, SLOT(slotTrackInserted(uint,Kwave::Track*)));
    connect(sig, SIGNAL(sigTrackDeleted(uint,Kwave::Track*)),
            this, SLOT(slotTrackDeleted(uint,Kwave::Track*)));
    connect(sig, SIGNAL(sigTrackSelectionChanged(bool)),
            this,SIGNAL(sigTrackSelectionChanged(bool)));
    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)));
}

//***************************************************************************
Kwave::SignalManager::~SignalManager()
{
    close();
}

//***************************************************************************
int Kwave::SignalManager::loadFile(const QUrl &url)
{
    int res = 0;
    Kwave::FileProgress *dialog = nullptr;

    // take over the new file name, so that we have a valid signal
    // name during loading
    QString filename = url.path();
    QFile src(filename);
    QFileInfo fi(src);
    {
        Kwave::FileInfo info(m_meta_data);
        info.set(Kwave::INF_FILENAME, fi.absoluteFilePath());
        m_meta_data.replace(Kwave::MetaDataList(info));
    }

    // work with a copy of meta data, to avoid flicker effects
    Kwave::MetaDataList meta_data(m_meta_data);

    // enter and stay in not modified state
    enableModifiedChange(true);
    setModified(false);
    enableModifiedChange(false);

    // disable undo (discards all undo/redo data)
    disableUndo();

    QString mimetype = Kwave::CodecManager::mimeTypeOf(url);
    qDebug("SignalManager::loadFile(%s) - [%s]",
           DBG(url.toDisplayString()), DBG(mimetype));
    Kwave::Decoder *decoder = Kwave::CodecManager::decoder(mimetype);
    while (decoder) {
        // be sure that the current signal is really closed
        m_signal.close();

        // open the source file
        if (!(res = decoder->open(m_parent_widget, src))) {
            qWarning("unable to open source: '%s'", DBG(url.toDisplayString()));
            res = -EIO;
            break;
        }

        // get the initial meta data from the decoder
        meta_data = decoder->metaData();
        Kwave::FileInfo info(meta_data);

        // take the preliminary meta data, needed for estimated length
        m_meta_data = 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.insertTrack(0, length, nullptr);
            Q_ASSERT(t);
            if (!t || (t->length() != length)) {
                qWarning("SignalManager::loadFile: 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 ?
        Kwave::InsertMode mode = (streaming) ? Kwave::Append : Kwave::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
        quint64 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(std::nothrow) Kwave::FileProgress(m_parent_widget,
            QUrl(filename), resulting_size,
            info.length(), info.rate(), info.bits(), info.tracks());
        Q_ASSERT(dialog);

        if (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
            meta_data = decoder->metaData();
            info = Kwave::FileInfo(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
        info.set(Kwave::INF_FILENAME, fi.absoluteFilePath());
        info.set(Kwave::INF_FILESIZE, src.size());
        if (!info.contains(Kwave::INF_MIMETYPE))
            info.set(Kwave::INF_MIMETYPE, mimetype);

        // remove the estimated length again, it is no longer needed
        info.set(Kwave::INF_ESTIMATED_LENGTH, QVariant());

        // take over the decoded and updated file info
        meta_data.replace(Kwave::MetaDataList(info));
        m_meta_data = meta_data;

        // 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;
    }

    // process any queued events of the writers, like "sigSamplesInserted"
    qApp->processEvents(QEventLoop::ExcludeUserInputEvents);

    // 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);

    delete dialog;
    if (res) close();

    m_meta_data.dump();

    // we now have new meta data
    emit sigMetaDataChanged(m_meta_data);

    return res;
}

//***************************************************************************
int Kwave::SignalManager::save(const QUrl &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 = static_cast<unsigned int>(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 = Kwave::CodecManager::mimeTypeOf(url);
    qDebug("SignalManager::save(%s) - [%s] (%u bit, selection=%d)",
        DBG(url.toDisplayString()), DBG(mimetype_name), bits, selection);

    Kwave::Encoder *encoder = Kwave::CodecManager::encoder(mimetype_name);
    Kwave::FileInfo file_info(m_meta_data);
    if (encoder) {

        // maybe we now have a new mime type
        file_info.set(Kwave::INF_MIMETYPE, mimetype_name);

        // check if we lose information and ask the user if this would
        // be acceptable
        QList<Kwave::FileProperty> unsupported = encoder->unsupportedProperties(
            file_info.properties().keys());
        if (!unsupported.isEmpty()) {
            QString list_of_lost_properties = _("\n");
            foreach (const Kwave::FileProperty &p, unsupported) {
                list_of_lost_properties +=
                    i18n(UTF8(file_info.name(p))) + _("\n");
            }

            // 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?",
                     list_of_lost_properties),
                QString(),
                QString(),
                QString(),
                _("accept_lose_attributes_on_export")
                ) != KMessageBox::Continue)
            {
                delete encoder;
                return -1;
            }
        }

        // open the destination file
        QString filename = url.path();
        QFile dst(filename);

        Kwave::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(Kwave::INF_SOFTWARE) &&
            encoder->supportedProperties().contains(Kwave::INF_SOFTWARE))
        {
            // add our Kwave Software tag
            const KAboutData about_data = KAboutData::applicationData();
            QString software = about_data.displayName() + _("-") +
                               about_data.version() + _(" ") +
                               i18n("(built with KDE Frameworks %1)",
                                    _(KXMLGUI_VERSION_STRING));
            file_info.set(Kwave::INF_SOFTWARE, software);
        }

        if (!file_info.contains(Kwave::INF_CREATION_DATE) &&
            encoder->supportedProperties().contains(Kwave::INF_CREATION_DATE))
        {
            // add a date tag
            QString date(QDate::currentDate().toString(_("yyyy-MM-dd")));
            qDebug("adding date tag: '%s'", DBG(date));
            file_info.set(Kwave::INF_CREATION_DATE, date);
        }

        // prepare and show the progress dialog
        Kwave::FileProgress *dialog = new(std::nothrow)
            Kwave::FileProgress(m_parent_widget, QUrl(filename),
                file_info.length() * file_info.tracks() *
                (file_info.bits() >> 3),
                file_info.length(), file_info.rate(), file_info.bits(),
                file_info.tracks()
            );
        Q_ASSERT(dialog);
        if (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(Kwave::MetaDataList(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);

            // set the filename in the copy of the fileinfo, the original
            // file which is currently open keeps it's name
            Kwave::FileInfo info(meta);
            info.set(Kwave::INF_FILENAME, filename);
            meta.replace(Kwave::MetaDataList(info));

            encoded = encoder->encode(m_parent_widget, src, dst, meta);
        } else {
            // in case of a "save as" -> modify the current filename
            file_info.set(Kwave::INF_FILENAME, filename);
            m_meta_data.replace(Kwave::MetaDataList(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;
        }

        delete encoder;
        encoder = nullptr;

        if (dialog) {
            qApp->processEvents();
            if (dialog->isCanceled()) {
                // user really pressed cancel !
                Kwave::MessageBox::error(m_parent_widget,
                    i18n("The file has been truncated and "
                          "might be corrupted."));
                res = -EINTR;
            }
            delete dialog;
            dialog = nullptr;
        }
    } else {
        Kwave::MessageBox::error(m_parent_widget,
            i18n("Sorry, the file type is not supported."));
        res = -EINVAL;
    }

    if (!res && !selection) {
        // 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 Kwave::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();
    Kwave::FileInfo file_info(m_meta_data);
    file_info.setRate(rate);
    file_info.setBits(bits);
    file_info.setTracks(tracks);
    m_meta_data.replace(Kwave::MetaDataList(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.insertTrack(0, samples, nullptr);
        tracks--;
    }

    // remember the last length
    m_last_length = samples;
    file_info.setLength(length());
    m_meta_data.replace(Kwave::MetaDataList(file_info));
    rememberCurrentSelection();

    // from now on, undo is enabled
    enableUndo();

    emit sigMetaDataChanged(m_meta_data);
}

//***************************************************************************
void Kwave::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 Kwave::SignalManager::signalName()
{
    // if a file is loaded -> path of the URL if it has one
    QUrl url;
    url = QUrl(Kwave::FileInfo(m_meta_data).get(
               Kwave::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 QVector<unsigned int> Kwave::SignalManager::selectedTracks()
{
    QVector<unsigned int> list;
    const unsigned int tracks = this->tracks();

    for (unsigned int track = 0; track < tracks; track++) {
        if (!m_signal.trackSelected(track)) continue;
        list.append(track);
    }

    return list;
}

//***************************************************************************
const QVector<unsigned int> Kwave::SignalManager::allTracks()
{
    return m_signal.allTracks();
}

//***************************************************************************
int Kwave::SignalManager::executeCommand(const QString &command)
{
    sample_index_t offset = m_selection.offset();
    sample_index_t length = m_selection.length();

    if (!command.length()) return -EINVAL;
    Kwave::Parser parser(command);

    if (false) {
    // --- undo / redo ---
    CASE_COMMAND("undo")
        undo();
    CASE_COMMAND("redo")
        redo();
    CASE_COMMAND("undo_all")
        while (m_undo_enabled && !m_undo_buffer.isEmpty())
            undo();
    CASE_COMMAND("redo_all")
        while (!m_redo_buffer.isEmpty())
            redo();

    // --- copy & paste + clipboard ---
    CASE_COMMAND("copy")
        if (length) {
            Kwave::ClipBoard &clip = Kwave::ClipBoard::instance();
            clip.copy(
                m_parent_widget,
                *this,
                selectedTracks(),
                offset, length
            );
            // remember the last selection
            rememberCurrentSelection();
        }
    CASE_COMMAND("insert_at")
        Kwave::ClipBoard &clip = Kwave::ClipBoard::instance();
        if (clip.isEmpty()) return 0;
        if (!selectedTracks().size()) return 0;
        sample_index_t ofs = parser.toSampleIndex();

        Kwave::UndoTransactionGuard undo(*this,
                                         i18n("Insert Clipboard at position"));

        selectRange(ofs, 0);
        clip.paste(m_parent_widget, *this, ofs, 0);

    CASE_COMMAND("paste")
        Kwave::ClipBoard &clip = Kwave::ClipBoard::instance();
        if (clip.isEmpty()) return 0;
        if (!selectedTracks().size()) return 0;

        Kwave::UndoTransactionGuard undo(*this, i18n("Paste"));
        clip.paste(m_parent_widget, *this, offset, length);
    CASE_COMMAND("cut")
        if (length) {
            // remember the last selection
            rememberCurrentSelection();

            Kwave::ClipBoard &clip = Kwave::ClipBoard::instance();
            clip.copy(
                m_parent_widget,
                *this,
                selectedTracks(),
                offset, length
            );
            Kwave::UndoTransactionGuard undo(*this, i18n("Cut"));
            deleteRange(offset, length);
            selectRange(m_selection.offset(), 0);
        }
    CASE_COMMAND("clipboard_flush")
        Kwave::ClipBoard::instance().clear();
    CASE_COMMAND("crop")
        if (length) {
            Kwave::UndoTransactionGuard undo(*this, i18n("Crop"));
            sample_index_t rest = this->length() - offset;
            rest = (rest > length) ? (rest-length) : 0;
            QVector<unsigned int> tracks = selectedTracks();
            if (saveUndoDelete(tracks, offset+length, rest) &&
                saveUndoDelete(tracks, 0, offset))
            {
                // remember the last selection
                rememberCurrentSelection();

                unsigned int count = static_cast<unsigned int>(tracks.count());
                while (count--) {
                    m_signal.deleteRange(count, offset+length, rest);
                    m_signal.deleteRange(count, 0, offset);
                }
                selectRange(0, length);
            }
        }
    CASE_COMMAND("delete")
        Kwave::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("label:delete")
        int index = parser.toInt();
        deleteLabel(index, true);

    CASE_COMMAND("expandtolabel")
        Kwave::UndoTransactionGuard undo(*this,
                                         i18n("Expand Selection to Label"));
        sample_index_t selection_left  = m_selection.first();
        sample_index_t selection_right = m_selection.last();
        Kwave::LabelList labels(m_meta_data);
        if (labels.isEmpty()) return false; // we need labels for this
        Kwave::Label label_left  = Kwave::Label();
        Kwave::Label label_right = Kwave::Label();

        // the last label <= selection start -> label_left
        // the first label >= selection end  -> label_right
        foreach (const Kwave::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")
        Kwave::UndoTransactionGuard undo(*this, i18n("Select Next Labels"));
        sample_index_t selection_left;
        sample_index_t selection_right = m_selection.last();
        Kwave::Label label_left  = Kwave::Label();
        Kwave::Label label_right = Kwave::Label();
        Kwave::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()) {
                Kwave::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() : Kwave::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) ?
            (selection_right - selection_left + 1) : 1;
        selectRange(selection_left, len);

    CASE_COMMAND("selectprevlabels")
        Kwave::UndoTransactionGuard undo(*this, i18n("Select Previous Labels"));
        sample_index_t selection_left  = selection().first();
        Kwave::Label label_left  = Kwave::Label();
        Kwave::Label label_right = Kwave::Label();
        Kwave::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 (const Kwave::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 !?
        sample_index_t 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")
        Kwave::Parser p(command);
        unsigned int track = p.toUInt();
        if (track >= tracks()) return -EINVAL;
        deleteTrack(track);
    CASE_COMMAND("insert_track")
        Kwave::Parser p(command);
        unsigned int track = p.toUInt();
        insertTrack(track);

    // track selection
    CASE_COMMAND("select_track:all")
        Kwave::UndoTransactionGuard undo(*this, i18n("Select All Tracks"));
        foreach (unsigned int track, allTracks())
            selectTrack(track, true);
    CASE_COMMAND("select_track:none")
        Kwave::UndoTransactionGuard undo(*this, i18n("Deselect all tracks"));
        foreach (unsigned int track, allTracks())
            selectTrack(track, false);
    CASE_COMMAND("select_track:invert")
        Kwave::UndoTransactionGuard undo(*this, i18n("Invert Track Selection"));
        foreach (unsigned int track, allTracks())
            selectTrack(track, !trackSelected(track));
    CASE_COMMAND("select_track:on")
        unsigned int track = parser.toUInt();
        if (track >= tracks()) return -EINVAL;
        Kwave::UndoTransactionGuard undo(*this, i18n("Select Track"));
        selectTrack(track, true);
    CASE_COMMAND("select_track:off")
        unsigned int track = parser.toUInt();
        if (track >= tracks()) return -EINVAL;
        Kwave::UndoTransactionGuard undo(*this, i18n("Deselect Track"));
        selectTrack(track, false);
    CASE_COMMAND("select_track:toggle")
        unsigned int track = parser.toUInt();
        if (track >= tracks()) return -EINVAL;
        Kwave::UndoTransactionGuard undo(*this, i18n("Toggle Track Selection"));
        selectTrack(track, !(trackSelected(track)));

    // playback control
    CASE_COMMAND("playback_start")
        m_playback_controller.playbackStart();

    CASE_COMMAND("fileinfo")
        QString property = parser.firstParam();
        QString value    = parser.nextParam();
        Kwave::FileInfo info(m_meta_data);
        bool found = false;
        foreach (Kwave::FileProperty p, info.allKnownProperties()) {
            if (info.name(p) == property) {
                if (value.length())
                    info.set(p, QVariant(value)); // add/modify
                else
                    info.set(p, QVariant());      // delete
                found = true;
                break;
            }
        }

        if (found) {
            m_meta_data.replace(Kwave::MetaDataList(info));
            // we now have new meta data
            emit sigMetaDataChanged(m_meta_data);
        } else
            return -EINVAL;
    CASE_COMMAND("dump_metadata")
        qDebug("DUMP OF META DATA => %s", DBG(parser.firstParam()));
        m_meta_data.dump();
    } else {
        return -ENOSYS;
    }

    return 0;
}

//***************************************************************************
void Kwave::SignalManager::appendTrack()
{
    Kwave::UndoTransactionGuard undo(*this, i18n("Append Track"));
    insertTrack(tracks());
}

//***************************************************************************
void Kwave::SignalManager::insertTrack(unsigned int index)
{
    Kwave::UndoTransactionGuard undo(*this, i18n("Insert Track"));

    const unsigned int count = tracks();
    if (index > count) index = count;

    // undo action for the track insert
    if (m_undo_enabled && !registerUndoAction(
        new(std::nothrow) Kwave::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;

    // insert/append to the list
    m_signal.insertTrack(index, len, nullptr);

    // remember the last length
    m_last_length = length();
}

//***************************************************************************
void Kwave::SignalManager::deleteTrack(unsigned int index)
{
    Kwave::UndoTransactionGuard undo(*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(std::nothrow)
            UndoDeleteTrack(m_signal, index)))
                return;
    }

    setModified(true);
    m_signal.deleteTrack(index);
}

//***************************************************************************
void Kwave::SignalManager::slotTrackInserted(unsigned int index,
                                             Kwave::Track *track)
{
    setModified(true);

    Kwave::FileInfo file_info(m_meta_data);
    file_info.setTracks(tracks());
    m_meta_data.replace(Kwave::MetaDataList(file_info));

    emit sigTrackInserted(index, track);
    emit sigMetaDataChanged(m_meta_data);
}

//***************************************************************************
void Kwave::SignalManager::slotTrackDeleted(unsigned int index,
                                             Kwave::Track *track)
{
    setModified(true);

    Kwave::FileInfo file_info(m_meta_data);
    file_info.setTracks(tracks());
    m_meta_data.replace(Kwave::MetaDataList(file_info));

    emit sigTrackDeleted(index, track);
    emit sigMetaDataChanged(m_meta_data);
}

//***************************************************************************
void Kwave::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
    QVector<unsigned int> tracks = selectedTracks();
    if (track == tracks.first()) {
        m_meta_data.shiftRight(offset, length);
    }

    emit sigSamplesInserted(track, offset, length);

    Kwave::FileInfo info(m_meta_data);
    info.setLength(m_last_length);
    m_meta_data.replace(Kwave::MetaDataList(info));
    emit sigMetaDataChanged(m_meta_data);
}

//***************************************************************************
void Kwave::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
    QVector<unsigned int> tracks = selectedTracks();
    if (track == tracks.first()) {
        m_meta_data.shiftLeft(offset, length);
    }

    emit sigSamplesDeleted(track, offset, length);

    Kwave::FileInfo info(m_meta_data);
    info.setLength(m_last_length);
    m_meta_data.replace(Kwave::MetaDataList(info));
    emit sigMetaDataChanged(m_meta_data);
}

//***************************************************************************
void Kwave::SignalManager::slotSamplesModified(unsigned int track,
        sample_index_t offset, sample_index_t length)
{
    setModified(true);
    emit sigSamplesModified(track, offset, length);
}

//***************************************************************************
bool Kwave::SignalManager::deleteRange(sample_index_t offset,
                                       sample_index_t length,
                                       const QVector<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(std::nothrow) UndoDeleteMetaDataAction(
            m_meta_data.copy(offset, length))))
        {
            abortUndoTransaction();
            return false;
        }
        m_meta_data.deleteRange(offset, length);

        // store undo data for all audio data (without meta data)
        if (!registerUndoAction(new(std::nothrow) UndoDeleteAction(
            m_parent_widget, track_list, offset, length)))
        {
            abortUndoTransaction();
            return false;
        }
    } else {
        // delete without undo
        m_meta_data.deleteRange(offset, length);
    }

    // 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 Kwave::SignalManager::deleteRange(sample_index_t offset,
                                       sample_index_t length)
{
    return deleteRange(offset, length, selectedTracks());
}

//***************************************************************************
bool Kwave::SignalManager::insertSpace(sample_index_t offset,
                                       sample_index_t length,
                                       const QVector<unsigned int> &track_list)
{
    if (!length || track_list.isEmpty()) return true; // nothing to do

    Kwave::UndoTransactionGuard undo(*this, i18n("Insert Space"));

    // first store undo data for all tracks
    if (m_undo_enabled) {
        if (!registerUndoAction(new(std::nothrow) Kwave::UndoInsertAction(
            m_parent_widget, track_list, offset, length))) return false;
    }

    // then insert space into all tracks
    foreach (unsigned int track, track_list) {
        m_signal.insertSpace(track, offset, length);
    }

    return true;
}

//***************************************************************************
void Kwave::SignalManager::selectRange(sample_index_t offset,
                                       sample_index_t length)
{
    // first do some range checking
    sample_index_t len = this->length();

    if (length > len)  length = len;
    if (offset >= len) offset = (len) ? (len - 1) : 0;
    if ((offset + length) > len) length = len - offset;

    m_selection.select(offset, length);
}

//***************************************************************************
void Kwave::SignalManager::selectTracks(QVector<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 Kwave::SignalManager::selectTrack(unsigned int track, bool select)
{
    bool old_select = m_signal.trackSelected(track);
    if (select != old_select) {
        m_signal.selectTrack(track, select);
    }
}

//***************************************************************************
QList<Kwave::Stripe::List> Kwave::SignalManager::stripes(
    const QVector<unsigned int> &track_list,
    sample_index_t left, sample_index_t right)
{
    QList<Kwave::Stripe::List> stripes;

    foreach (unsigned int track, track_list) {
        Kwave::Stripe::List s = m_signal.stripes(track, left, right);
        if (s.isEmpty()) {
            stripes.clear(); // something went wrong -> abort
            break;
        }
        stripes.append(s);
    }

    return stripes;
}

//***************************************************************************
bool Kwave::SignalManager::mergeStripes(
    const QList<Kwave::Stripe::List> &stripes,
    const QVector<unsigned int> &track_list)
{
    Q_ASSERT(stripes.count() == track_list.count());
    if (stripes.count() != track_list.count())
        return false;

    QListIterator<Kwave::Stripe::List> it_s(stripes);
    QVector<unsigned int>::const_iterator it_t = track_list.constBegin();
    while (it_s.hasNext() && (it_t != track_list.constEnd())) {
        Kwave::Stripe::List s = it_s.next();
        unsigned int        t = *(it_t++);
        if (!m_signal.mergeStripes(s, t))
            return false; // operation failed
    }

    return true;
}

//***************************************************************************
Kwave::PlaybackController &Kwave::SignalManager::playbackController()
{
    return m_playback_controller;
}

//***************************************************************************
void Kwave::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(std::nothrow) Kwave::UndoTransaction(name);
        Q_ASSERT(m_undo_transaction);
        if (!m_undo_transaction) return;

        // give all registered undo handlers a chance to register their own
        // undo actions
        if (!m_undo_manager.startUndoTransaction(m_undo_transaction)) {
            delete m_undo_transaction;
            m_undo_transaction = nullptr;
        }

        // if it is the start of the transaction, also create one
        // for the selection
        UndoAction *selection = new(std::nothrow) Kwave::UndoSelection(*this);
        Q_ASSERT(selection);
        if (selection && selection->store(*this)) {
            m_undo_transaction->append(selection);
        } else {
            // out of memory
            delete selection;
            delete m_undo_transaction;
            m_undo_transaction = nullptr;
        }
    }
}

//***************************************************************************
void Kwave::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 = nullptr;
                } else {
                    m_undo_buffer.append(m_undo_transaction);
                }
            } else {
                qDebug("SignalManager::closeUndoTransaction(): empty");
                delete m_undo_transaction;
                m_undo_transaction = nullptr;
            }
        }

        // dump, for debugging
//      if (m_undo_transaction)
//          m_undo_transaction->dump("closed undo transaction: ");

        // declare the current transaction as "closed"
        rememberCurrentSelection();
        m_undo_transaction = nullptr;
        emitUndoRedoInfo();
    }
}

//***************************************************************************
void Kwave::SignalManager::enableUndo()
{
    m_undo_enabled = true;
    emitUndoRedoInfo();
}

//***************************************************************************
void Kwave::SignalManager::disableUndo()
{
    if (m_undo_transaction_level)
        qWarning("SignalManager::disableUndo(): undo transaction level=%u",
            m_undo_transaction_level);

    flushUndoBuffers();
    m_undo_enabled = false;
}

//***************************************************************************
void Kwave::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 Kwave::SignalManager::abortUndoTransaction()
{
    // abort the current transaction
    if (m_undo_transaction) m_undo_transaction->abort();
}

//***************************************************************************
void Kwave::SignalManager::flushRedoBuffer()
{
    qDeleteAll(m_redo_buffer);
    m_redo_buffer.clear();
    emitUndoRedoInfo();
}

//***************************************************************************
bool Kwave::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'.",
             i18n("Settings"),
             i18n("Memory") +
        _("</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())
            delete m_undo_transaction->takeLast();

        // 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 Kwave::SignalManager::registerUndoAction(Kwave::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
    qint64 limit_mb     = Kwave::undoLimit();
    qint64 needed_size  = action->undoSize();
    qint64 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 Kwave::SignalManager::saveUndoDelete(QVector<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(std::nothrow)
        UndoDeleteAction(m_parent_widget, track_list, offset, length);
    if (!registerUndoAction(action)) return false;

    return true;
}

//***************************************************************************
qint64 Kwave::SignalManager::usedUndoRedoMemory()
{
    qint64 size = 0;

    foreach (Kwave::UndoTransaction *undo, m_undo_buffer)
        if (undo) size += undo->undoSize();

    foreach (Kwave::UndoTransaction *redo, m_redo_buffer)
        if (redo) size += redo->undoSize();

    return size;
}

//***************************************************************************
void Kwave::SignalManager::freeUndoMemory(qint64 needed)
{
    qint64 size = usedUndoRedoMemory() + needed;
    qint64 undo_limit = Kwave::undoLimit() << 20;

    // remove old undo actions if not enough free memory
    while (!m_undo_buffer.isEmpty() && (size > undo_limit)) {
        Kwave::UndoTransaction *undo = m_undo_buffer.takeFirst();
        if (!undo) continue;
        qint64 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)) {
        Kwave::UndoTransaction *redo = m_redo_buffer.takeLast();
        if (!redo) continue;
        qint64 s = redo->undoSize();
        size = (size >= s) ? (size - s) : 0;
        delete redo;
    }
}

//***************************************************************************
void Kwave::SignalManager::emitUndoRedoInfo()
{
    QString undo_name = QString();
    QString redo_name = QString();

    if (m_undo_enabled) {
        Kwave::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 Kwave::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;
    Kwave::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
    qint64 undo_limit = Kwave::undoLimit() << 20;
    qint64 redo_size = undo_transaction->redoSize();
    qint64 undo_size = undo_transaction->undoSize();
    Kwave::UndoTransaction *redo_transaction = nullptr;
    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(std::nothrow) Kwave::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 != nullptr));

        // 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 = nullptr;
    }

    // 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);
        QVector<unsigned int> tracks = selectedTracks();
        bool tracks_modified = !(tracks == m_last_track_selection);
        if (range_modified || tracks_modified) {
            UndoAction *redo_action = new(std::nothrow) Kwave::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 (Kwave::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 Kwave::SignalManager::redo()
{
    QMutexLocker lock(&m_undo_transaction_lock);

    // get the last redo transaction and abort if none present
    if (m_redo_buffer.isEmpty()) return;
    Kwave::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
    qint64 undo_limit = Kwave::undoLimit() << 20;
    qint64 undo_size = redo_transaction->undoSize();
    qint64 redo_size = redo_transaction->redoSize();
    Kwave::UndoTransaction *undo_transaction = nullptr;
    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(std::nothrow) Kwave::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 != nullptr));

        // 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 Kwave::SignalManager::setModified(bool mod)
{
    if (!m_modified_enabled) return;

    if (m_modified != mod) {
        m_modified = mod;
//      qDebug("SignalManager::setModified(%d)",mod);
        emit sigModified();
    }
}

//***************************************************************************
void Kwave::SignalManager::enableModifiedChange(bool en)
{
    m_modified_enabled = en;
}

//***************************************************************************
void Kwave::SignalManager::setFileInfo(const Kwave::FileInfo &new_info,
                                       bool with_undo)
{
    if (m_undo_enabled && with_undo) {
        /* save data for undo */
        Kwave::UndoTransactionGuard undo_transaction(*this,
                                                     i18n("Modify File Info"));
        Kwave::FileInfo old_inf(m_meta_data);
        if (!registerUndoAction(
            new(std::nothrow) Kwave::UndoModifyMetaDataAction(
                Kwave::MetaDataList(old_inf))))
            return;
    }

    m_meta_data.replace(Kwave::MetaDataList(new_info));
    setModified(true);
    emitUndoRedoInfo();
    emit sigMetaDataChanged(m_meta_data);
}

//***************************************************************************
Kwave::Label Kwave::SignalManager::findLabel(sample_index_t pos)
{
    Kwave::LabelList labels(m_meta_data);
    foreach (const Kwave::Label &label, labels) {
        if (label.pos() == pos) return label; // found it
    }
    return Kwave::Label(); // nothing found
}

//***************************************************************************
int Kwave::SignalManager::labelIndex(const Kwave::Label &label) const
{
    int index = 0;
    Kwave::LabelList labels(m_meta_data);
    foreach (const Kwave::Label &l, labels) {
        if (l == label) return index; // found it
        index++;
    }
    return -1; // nothing found*/
}

//***************************************************************************
Kwave::Label Kwave::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 Kwave::Label();

    // create a new label
    Kwave::Label label(pos, name);

    // register the undo action
    if (m_undo_enabled) {
        Kwave::UndoTransactionGuard undo(*this, i18n("Add Label"));
        if (!registerUndoAction(new(std::nothrow) UndoAddMetaDataAction(
                Kwave::MetaDataList(label))))
            return Kwave::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 Kwave::SignalManager::deleteLabel(int index, bool with_undo)
{
    Kwave::LabelList labels(m_meta_data);
    int count = Kwave::toInt(labels.count());
    if (!count) return;

    if (index == -1) {
        // special handling for index == -1 -> delete all labels

        if (with_undo) startUndoTransaction(i18n("Delete All Labels"));

        for (index = count - 1; index >= 0; --index) {
            Kwave::MetaData label(labels.at(index));
            if (with_undo) {
                if (!registerUndoAction(new(std::nothrow)
                    UndoDeleteMetaDataAction(Kwave::MetaDataList(label))))
                    break;
            }
            m_meta_data.remove(label);
        }
    } else {
        // delete a single label
        if ((index < 0) || (index >= count)) return;

        Kwave::MetaData label(labels.at(index));

        // register the undo action
        if (with_undo) {
            startUndoTransaction(i18n("Delete Label"));
            if (!registerUndoAction(new(std::nothrow)
                UndoDeleteMetaDataAction(Kwave::MetaDataList(label)))) {
                abortUndoTransaction();
                return;
            }
        }

        m_meta_data.remove(label);
    }

    if (with_undo) closeUndoTransaction();

    // register this as a modification
    setModified(true);

    emit sigMetaDataChanged(m_meta_data);
}

//***************************************************************************
bool Kwave::SignalManager::modifyLabel(int index, sample_index_t pos,
                                       const QString &name,
                                       bool with_undo)
{
    Kwave::LabelList labels(m_meta_data);
    if ((index < 0) || (index >= Kwave::toInt(labels.count())))
        return false;

    Kwave::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 (with_undo && m_undo_enabled) {
        Kwave::UndoModifyMetaDataAction *undo_modify =
            new(std::nothrow) Kwave::UndoModifyMetaDataAction(
                    Kwave::MetaDataList(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 Kwave::SignalManager::mergeMetaData(const Kwave::MetaDataList &meta_data)
{
    m_meta_data.add(meta_data);
    emit sigMetaDataChanged(m_meta_data);
}

//***************************************************************************
void Kwave::SignalManager::rememberCurrentSelection()
{
    m_last_selection       = m_selection;
    m_last_track_selection = selectedTracks();
}

//***************************************************************************
void Kwave::SignalManager::checkSelectionChange()
{
    if (m_undo_transaction_level) return;

    // detect sample selection change
    bool range_modified = !(m_selection == m_last_selection);

    // detect track selection change
    QVector<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)
        Kwave::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)
            Kwave::UndoTransactionGuard undo(*this,
                                             i18n("Manual Track Selection"));
        else
            Kwave::UndoTransactionGuard undo(*this,
                                             i18n("Manual Selection"));

        // restore the current selection again
        m_selection = new_selection;
        selectTracks(tracks);
    }

}

//***************************************************************************
//***************************************************************************

#include "moc_SignalManager.cpp"