File: editcommands.cpp

package info (click to toggle)
rosegarden4 1.0-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 22,344 kB
  • ctags: 14,022
  • sloc: cpp: 131,139; sh: 9,429; perl: 2,620; xml: 2,231; makefile: 607; python: 374; ansic: 339; ruby: 173; php: 2
file content (1936 lines) | stat: -rw-r--r-- 53,874 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
// -*- c-basic-offset: 4 -*-

/*
    Rosegarden-4
    A sequencer and musical notation editor.

    This program is Copyright 2000-2005
        Guillaume Laurent   <glaurent@telegraph-road.org>,
        Chris Cannam        <cannam@all-day-breakfast.com>,
        Richard Bown        <bownie@bownie.com>

    The moral right of the authors to claim authorship of this work
    has been asserted.

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.  See the file
    COPYING included with this distribution for more information.
*/

#include "editcommands.h"

#include <qregexp.h>

#include <kconfig.h>

#include "NotationTypes.h"
#include "Selection.h"
#include "SegmentNotationHelper.h"
#include "SegmentMatrixHelper.h"
#include "BaseProperties.h"
#include "Clipboard.h"
#include "Profiler.h"
#include "Marker.h"

#include "notationproperties.h"
#include "segmentcommands.h"

#include "rosestrings.h"
#include "rosedebug.h"
#include "rgapplication.h"

using Rosegarden::Segment;
using Rosegarden::SegmentNotationHelper;
using Rosegarden::Event;
using Rosegarden::timeT;
using Rosegarden::Note;
using Rosegarden::Clef;
using Rosegarden::Int;
using Rosegarden::String;
using Rosegarden::Text;
using Rosegarden::Accidental;
using Rosegarden::Accidentals::NoAccidental;
using Rosegarden::Indication;
using Rosegarden::EventSelection;
using Rosegarden::SegmentSelection;
using Rosegarden::TrackId;

using namespace Rosegarden::BaseProperties;

using std::string;
using std::endl;


CutCommand::CutCommand(EventSelection &selection,
		       Rosegarden::Clipboard *clipboard) :
    KMacroCommand(getGlobalName())
{
    addCommand(new CopyCommand(selection, clipboard));
    addCommand(new EraseCommand(selection));
}

CutCommand::CutCommand(SegmentSelection &selection,
		       Rosegarden::Clipboard *clipboard) :
    KMacroCommand(getGlobalName())
{
    addCommand(new CopyCommand(selection, clipboard));

    for (SegmentSelection::iterator i = selection.begin();
	 i != selection.end(); ++i) {
	addCommand(new SegmentEraseCommand(*i));
    }
}


CutAndCloseCommand::CutAndCloseCommand(Rosegarden::EventSelection &selection,
				       Rosegarden::Clipboard *clipboard) :
    KMacroCommand(getGlobalName())
{
    addCommand(new CutCommand(selection, clipboard));
    addCommand(new CloseCommand(&selection.getSegment(),
				selection.getEndTime(),
				selection.getStartTime()));
}

void
CutAndCloseCommand::CloseCommand::execute()
{
    // We shift all the events from m_gapEnd to the end of the
    // segment back so that they start at m_gapStart instead of m_gapEnd.

    assert(m_gapEnd >= m_gapStart);
    if (m_gapEnd == m_gapStart) return;

    // We also need to record how many events there are already at
    // m_gapStart so that we can leave those unchanged when we undo.
    // (This command is executed on the understanding that the area
    // between m_gapStart and m_gapEnd is empty of all but rests, but
    // in practice there may be other things such as a clef at the
    // same time as m_gapStart.  This will only work for events that
    // have smaller subordering than notes etc.)

    m_staticEvents = 0;
    for (Segment::iterator i = m_segment->findTime(m_gapStart);
	 m_segment->isBeforeEndMarker(i); ++i) {
	if ((*i)->getAbsoluteTime() > m_gapStart) break;
	if ((*i)->isa(Rosegarden::Note::EventRestType)) continue;
	++m_staticEvents;
    }

    std::vector<Event *> events;
    timeT timeDifference = m_gapEnd - m_gapStart;

    for (Segment::iterator i = m_segment->findTime(m_gapEnd);
	 m_segment->isBeforeEndMarker(i); ++i) {
	events.push_back(new Event
			 (**i,
			  (*i)->getAbsoluteTime() - timeDifference,
			  (*i)->getDuration(),
			  (*i)->getSubOrdering(),
			  (*i)->getNotationAbsoluteTime() - timeDifference,
			  (*i)->getNotationDuration()));
    }

    timeT oldEndTime = m_segment->getEndTime();

    // remove rests from target area, and everything thereafter
    for (Segment::iterator i = m_segment->findTime(m_gapStart);
	 m_segment->isBeforeEndMarker(i); ) {
	if ((*i)->getAbsoluteTime() >= m_gapEnd ||
	    (*i)->isa(Rosegarden::Note::EventRestType)) {
	    Segment::iterator j(i);
	    ++j;
	    m_segment->erase(i);
	    i = j;
	} else {
	    ++i;
	}
    }
    
    for (unsigned int i = 0; i < events.size(); ++i) {
	m_segment->insert(events[i]);
    }

    m_segment->normalizeRests(m_segment->getEndTime(), oldEndTime);
}

void
CutAndCloseCommand::CloseCommand::unexecute()
{
    // We want to shift events from m_gapStart to the end of the
    // segment forward so as to start at m_gapEnd instead of
    // m_gapStart.

    assert(m_gapEnd >= m_gapStart);
    if (m_gapEnd == m_gapStart) return;

    // May need to ignore some static events at m_gapStart.
    // These are assumed to have smaller subordering than whatever
    // we're not ignoring.  Actually this still isn't quite right:
    // it'll do the wrong thing where we have, say, a clef then
    // some notes then another clef and we cut-and-close all the
    // notes and then undo.  But it's better than we were doing
    // before.

    Segment::iterator starti = m_segment->findTime(m_gapStart);

    while (m_segment->isBeforeEndMarker(starti)) {
	if (m_staticEvents == 0) break;
	if ((*starti)->getAbsoluteTime() > m_gapStart) break;
	if (!(*starti)->isa(Note::EventRestType)) --m_staticEvents;
	++starti;
    }

    std::vector<Event *> events;
    timeT timeDifference = m_gapEnd - m_gapStart;

    for (Segment::iterator i = starti; m_segment->isBeforeEndMarker(i); ) {
	Segment::iterator j(i);
	++j;
	events.push_back(new Event
			 (**i,
			  (*i)->getAbsoluteTime() + timeDifference,
			  (*i)->getDuration(),
			  (*i)->getSubOrdering(),
			  (*i)->getNotationAbsoluteTime() + timeDifference,
			  (*i)->getNotationDuration()));
	m_segment->erase(i);
	i = j;
    }

    for (unsigned int i = 0; i < events.size(); ++i) {
	m_segment->insert(events[i]);
    }

    timeT endTime = m_segment->getEndTime();
    NOTATION_DEBUG << "setting end time to " << (endTime - timeDifference) << endl;
//!!! this following is not working for bugaccidentals.rg:
    m_segment->setEndTime(endTime - timeDifference);

    m_segment->normalizeRests(m_gapStart, m_gapEnd);
}  


CopyCommand::CopyCommand(EventSelection &selection,
			 Rosegarden::Clipboard *clipboard) :
    KNamedCommand(getGlobalName()),
    m_targetClipboard(clipboard)
{
    m_sourceClipboard = new Rosegarden::Clipboard;
    m_sourceClipboard->newSegment(&selection)->setLabel
	(selection.getSegment().getLabel() + " " + qstrtostr(i18n("(excerpt)")));
}

CopyCommand::CopyCommand(SegmentSelection &selection,
			 Rosegarden::Clipboard *clipboard) :
    KNamedCommand(getGlobalName()),
    m_targetClipboard(clipboard)
{
    m_sourceClipboard = new Rosegarden::Clipboard;

    for (SegmentSelection::iterator i = selection.begin();
	 i != selection.end(); ++i) {
	m_sourceClipboard->newSegment(*i)->setLabel((*i)->getLabel() + " " +
						    qstrtostr(i18n("(copied)")));
    }
}

CopyCommand::~CopyCommand()
{
    delete m_sourceClipboard;
}

void
CopyCommand::execute()
{
//    RG_DEBUG << "CopyCommand::execute" << endl;

    Rosegarden::Clipboard temp(*m_targetClipboard);
    m_targetClipboard->copyFrom(m_sourceClipboard);
    m_sourceClipboard->copyFrom(&temp);
}

void
CopyCommand::unexecute()
{
//    RG_DEBUG << "CopyCommand::unexecute" << endl;

    Rosegarden::Clipboard temp(*m_sourceClipboard);
    m_sourceClipboard->copyFrom(m_targetClipboard);
    m_targetClipboard->copyFrom(&temp);
}


PasteSegmentsCommand::PasteSegmentsCommand(Rosegarden::Composition *composition,
					   Rosegarden::Clipboard *clipboard,
					   Rosegarden::timeT pasteTime) :
    KNamedCommand(getGlobalName()),
    m_composition(composition),
    m_clipboard(clipboard),
    m_pasteTime(pasteTime),
    m_detached(false)
{
    // nothing else
}

PasteSegmentsCommand::~PasteSegmentsCommand()
{
    if (m_detached) {
	for (unsigned int i = 0; i < m_addedSegments.size(); ++i) {
	    delete m_addedSegments[i];
	}
    }
}

void
PasteSegmentsCommand::execute()
{
    if (m_addedSegments.size() > 0) {
	// been here before
	for (unsigned int i = 0; i < m_addedSegments.size(); ++i) {
            m_addedSegments[i]->setTrack(m_composition->getSelectedTrack());
	    m_composition->addSegment(m_addedSegments[i]);
	}
	return;
    }

    if (m_clipboard->isEmpty()) return;

    // We want to paste such that the earliest Segment starts at
    // m_pasteTime and the others start at the same times relative
    // to that as they did before

    timeT earliestStartTime = 0;
    timeT latestEndTime = 0;
    int trackOffset = 0;

    for (Rosegarden::Clipboard::iterator i = m_clipboard->begin();
	 i != m_clipboard->end(); ++i) {

	if (i == m_clipboard->begin() ||
	    (*i)->getStartTime() < earliestStartTime) {
	    earliestStartTime = (*i)->getStartTime();
            trackOffset = (*i)->getTrack();
	}

        if ((*i)->getEndMarkerTime() > latestEndTime)
            latestEndTime = (*i)->getEndMarkerTime();
    }

    timeT offset = m_pasteTime - earliestStartTime;

    for (Rosegarden::Clipboard::iterator i = m_clipboard->begin();
	 i != m_clipboard->end(); ++i) {

        TrackId newTrackId = m_composition->getSelectedTrack() 
            + (*i)->getTrack()
            - trackOffset;

        // needs to check for valid id
        if (newTrackId < m_composition->getMinTrackId() ||
            newTrackId > m_composition->getMaxTrackId()) continue;

	Segment *segment = new Segment(**i);
	segment->setStartTime(segment->getStartTime() + offset);
        segment->setTrack(newTrackId);
        m_composition->addSegment(segment);
	if (m_clipboard->isPartial()) {
	    segment->normalizeRests(segment->getStartTime(),
				    segment->getEndMarkerTime() + offset);
	}
	m_addedSegments.push_back(segment);
    }

    // User preference? Update song pointer position on paste
    m_composition->setPosition(latestEndTime 
                               + m_pasteTime 
                               - earliestStartTime);
    
    m_detached = false;
}

void
PasteSegmentsCommand::unexecute()
{
    for (unsigned int i = 0; i < m_addedSegments.size(); ++i) {
	m_composition->detachSegment(m_addedSegments[i]);
    }
    m_detached = true;
}
    

PasteEventsCommand::PasteEventsCommand(Rosegarden::Segment &segment,
				       Rosegarden::Clipboard *clipboard,
				       Rosegarden::timeT pasteTime,
				       PasteType pasteType) :
    BasicCommand(getGlobalName(), segment, pasteTime,
		 getEffectiveEndTime(segment, clipboard, pasteTime)),
    m_relayoutEndTime(getEndTime()),
    m_clipboard(clipboard),
    m_pasteType(pasteType)
{
    if (pasteType != OpenAndPaste) {

	// paste clef or key -> relayout to end

	if (clipboard->isSingleSegment()) {

	    Segment *s(clipboard->getSingleSegment());
	    for (Segment::iterator i = s->begin(); i != s->end(); ++i) {
		if ((*i)->isa(Rosegarden::Clef::EventType) ||
		    (*i)->isa(Rosegarden::Key::EventType)) {
		    m_relayoutEndTime = s->getEndTime();
		    break;
		}
	    }
	}
    }
}

PasteEventsCommand::PasteEventsCommand(Rosegarden::Segment &segment,
				       Rosegarden::Clipboard *clipboard,
				       Rosegarden::timeT pasteTime,
				       Rosegarden::timeT pasteEndTime,
				       PasteType pasteType) :
    BasicCommand(getGlobalName(), segment, pasteTime, pasteEndTime),
    m_relayoutEndTime(getEndTime()),
    m_clipboard(clipboard),
    m_pasteType(pasteType)
{
}

PasteEventsCommand::PasteTypeMap
PasteEventsCommand::getPasteTypes()
{
    static PasteTypeMap types;
    static bool haveTypes = false;
    if (!haveTypes) {
	types[Restricted] =
	    i18n("Paste into an existing gap [\"restricted\"]");
	types[Simple] =
	    i18n("Erase existing events to make room [\"simple\"]");
	types[OpenAndPaste] =
	    i18n("Move existing events out of the way [\"open-n-paste\"]");
	types[NoteOverlay] =
	    i18n("Overlay notes, tying against present notes [\"note-overlay\"]");
	types[MatrixOverlay] =
	    i18n("Overlay notes, ignoring present notes [\"matrix-overlay\"]");
    }
    return types;
}

timeT
PasteEventsCommand::getEffectiveEndTime(Rosegarden::Segment &segment,
					Rosegarden::Clipboard *clipboard,
					Rosegarden::timeT pasteTime)
{
    if (!clipboard->isSingleSegment()) {
	RG_DEBUG << "PasteEventsCommand::getEffectiveEndTime: not single segment" << endl;
	return pasteTime;
    }

    RG_DEBUG << "PasteEventsCommand::getEffectiveEndTime: clipboard "
	     << clipboard->getSingleSegment()->getStartTime()
	     << " -> "
	     << clipboard->getSingleSegment()->getEndTime() << endl;

    timeT d = clipboard->getSingleSegment()->getEndTime() -
 	      clipboard->getSingleSegment()->getStartTime();

    if (m_pasteType == OpenAndPaste) {
	return segment.getEndTime() + d;
    } else {
	Segment::iterator i = segment.findTime(pasteTime + d);
	if (i == segment.end()) return segment.getEndTime();
	else return (*i)->getAbsoluteTime();
    }
}

timeT
PasteEventsCommand::getRelayoutEndTime()
{
    return m_relayoutEndTime;
}

bool
PasteEventsCommand::isPossible() 
{
    if (m_clipboard->isEmpty() || !m_clipboard->isSingleSegment()) {
	return false;
    }
    
    if (m_pasteType != Restricted) {
	return true;
    }

    Segment *source = m_clipboard->getSingleSegment();

    timeT pasteTime = getStartTime();
    timeT origin = source->getStartTime();
    timeT duration = source->getEndTime() - origin;

    RG_DEBUG << "PasteEventsCommand::isPossible: paste time is " << pasteTime << ", origin is " << origin << ", duration is " << duration << endl;

    SegmentNotationHelper helper(getSegment());
    return helper.removeRests(pasteTime, duration, true);
}


void
PasteEventsCommand::modifySegment()
{
    RG_DEBUG << "PasteEventsCommand::modifySegment" << endl;

    if (!m_clipboard->isSingleSegment()) return;

    Segment *source = m_clipboard->getSingleSegment();

    timeT pasteTime = getStartTime();
    timeT origin = source->getStartTime();
    timeT duration = source->getEndTime() - origin;
    
    Segment *destination(&getSegment());
    SegmentNotationHelper helper(*destination);

    RG_DEBUG << "PasteEventsCommand::modifySegment() : paste type = "
             << m_pasteType << " - pasteTime = "
             << pasteTime << " - origin = " << origin << endl;

    // First check for group IDs, which we want to make unique in the
    // copies in the destination segment

    std::map<long, long> groupIdMap;
    for (Segment::iterator i = source->begin(); i != source->end(); ++i) {
	long groupId = -1;
	if ((*i)->get<Int>(BEAMED_GROUP_ID, groupId)) {
	    if (groupIdMap.find(groupId) == groupIdMap.end()) {
		groupIdMap[groupId] = destination->getNextId();
	    }
	}
    }
    
    switch (m_pasteType) {

	// Do some preliminary work to make space or whatever;
	// we do the actual paste after this switch statement
	// (except where individual cases do the work and return)

    case Restricted:
	if (!helper.removeRests(pasteTime, duration)) return;
	break;

    case Simple:
	destination->erase(destination->findTime(pasteTime),
			   destination->findTime(pasteTime + duration));
	break;

    case OpenAndPaste:
    {
	std::vector<Event *> copies;
	for (Segment::iterator i = destination->findTime(pasteTime);
	     i != destination->end(); ++i) {
	    Event *e = new Event(**i, (*i)->getAbsoluteTime() + duration);
	    if (e->has(BEAMED_GROUP_ID)) {
		e->set<Int>(BEAMED_GROUP_ID, groupIdMap[e->get<Int>(BEAMED_GROUP_ID)]);
	    }
	    copies.push_back(e);
	}

	destination->erase(destination->findTime(pasteTime),
			   destination->end());

	for (unsigned int i = 0; i < copies.size(); ++i) {
	    destination->insert(copies[i]);
	}

	break;
    }

    case NoteOverlay:
	for (Segment::iterator i = source->begin(); i != source->end(); ++i) {
	    if ((*i)->isa(Note::EventRestType)) continue;
	    if ((*i)->isa(Note::EventType)) {
		Event *e = new Event(**i,
				     (*i)->getAbsoluteTime() - origin + pasteTime,
				     (*i)->getDuration(),
				     (*i)->getSubOrdering(),
				     (*i)->getNotationAbsoluteTime() - origin + pasteTime,
				     (*i)->getNotationDuration());
		if (e->has(BEAMED_GROUP_ID)) {
		    e->set<Int>(BEAMED_GROUP_ID, groupIdMap[e->get<Int>(BEAMED_GROUP_ID)]);
		}
		helper.insertNote(e); // e is model event: we retain ownership of it
		delete e;
	    } else {
		Event *e = new Event
		    (**i, (*i)->getAbsoluteTime() - origin + pasteTime);
		if (e->has(BEAMED_GROUP_ID)) {
		    e->set<Int>(BEAMED_GROUP_ID, groupIdMap[e->get<Int>(BEAMED_GROUP_ID)]);
		}
		destination->insert(e);
	    }
	}

	return;

    case MatrixOverlay:

	for (Segment::iterator i = source->begin(); i != source->end(); ++i) {

	    if ((*i)->isa(Note::EventRestType)) continue;

	    Event *e = new Event
		(**i, (*i)->getAbsoluteTime() - origin + pasteTime);

	    if (e->has(BEAMED_GROUP_TYPE) &&
		e->get<String>(BEAMED_GROUP_TYPE) == GROUP_TYPE_BEAMED) {
		e->unset(BEAMED_GROUP_ID);
		e->unset(BEAMED_GROUP_TYPE);
	    }

	    if (e->has(BEAMED_GROUP_ID)) {
		e->set<Int>(BEAMED_GROUP_ID, groupIdMap[e->get<Int>(BEAMED_GROUP_ID)]);
	    }

	    destination->insert(e);
	}

	destination->normalizeRests
	    (source->getStartTime(), source->getEndTime());

	return;
    }

    RG_DEBUG << "PasteEventsCommand::modifySegment() - inserting\n";

    for (Segment::iterator i = source->begin(); i != source->end(); ++i) {
	Event *e = new Event
	    (**i, (*i)->getAbsoluteTime() - origin + pasteTime);
	if (e->has(BEAMED_GROUP_ID)) {
	    e->set<Int>(BEAMED_GROUP_ID, groupIdMap[e->get<Int>(BEAMED_GROUP_ID)]);
	}
	destination->insert(e);
    }

    destination->normalizeRests
	(source->getStartTime(), source->getEndTime());
}


EraseCommand::EraseCommand(EventSelection &selection) :
    BasicSelectionCommand(getGlobalName(), selection, true),
    m_selection(&selection),
    m_relayoutEndTime(getEndTime())
{
    // nothing else
}

void
EraseCommand::modifySegment()
{
    RG_DEBUG << "EraseCommand::modifySegment" << endl;

    std::vector<Event *> toErase;
    EventSelection::eventcontainer::iterator i;

    for (i  = m_selection->getSegmentEvents().begin();
	 i != m_selection->getSegmentEvents().end(); ++i) {
	
	if ((*i)->isa(Rosegarden::Clef::EventType) ||
	    (*i)->isa(Rosegarden::Key ::EventType)) {
	    m_relayoutEndTime = getSegment().getEndTime();
	}

	// We used to do this by calling SegmentNotationHelper::deleteEvent
	// on each event in the selection, but it's probably easier to
	// cope with general selections by deleting everything in the
	// selection and then normalizing the rests.  The deleteEvent
	// mechanism is still the more sensitive way to do it for single
	// events, and it's what's used by EraseEventCommand and thus
	// the notation eraser tool.

	toErase.push_back(*i);
    }

    for (unsigned int j = 0; j < toErase.size(); ++j) {
	getSegment().eraseSingle(toErase[j]);
    }

    getSegment().normalizeRests(getStartTime(), getEndTime());
}

timeT
EraseCommand::getRelayoutEndTime()
{
    return m_relayoutEndTime;
}



EventEditCommand::EventEditCommand(Rosegarden::Segment &segment,
				   Rosegarden::Event *eventToModify,
				   const Rosegarden::Event &newEvent) :
    BasicCommand(getGlobalName(),
		 segment,
		 std::min(eventToModify->getAbsoluteTime(),
			  newEvent.getAbsoluteTime()),
		 std::max(eventToModify->getAbsoluteTime() +
			  eventToModify->getDuration(),
			  newEvent.getAbsoluteTime() +
			  newEvent.getDuration()),
		 true), // bruteForceRedo
    m_oldEvent(eventToModify),
    m_newEvent(newEvent)
{
    // nothing else to see here
}

void
EventEditCommand::modifySegment()
{
    Segment &segment(getSegment());
    segment.eraseSingle(m_oldEvent);
    segment.insert(new Event(m_newEvent));
    segment.normalizeRests(getStartTime(), getEndTime());
}

// -------------------- SelectionPropertyCommand -----------------
//
//
SelectionPropertyCommand::SelectionPropertyCommand(
        Rosegarden::EventSelection *selection,
        const Rosegarden::PropertyName &property,
        Rosegarden::PropertyPattern pattern,
        int value1,
        int value2):
    BasicSelectionCommand(getGlobalName(), *selection, true),
    m_selection(selection),
    m_property(property),
    m_pattern(pattern),
    m_value1(value1),
    m_value2(value2)
{
}

void
SelectionPropertyCommand::modifySegment()
{
    EventSelection::eventcontainer::iterator i =
        m_selection->getSegmentEvents().begin();

    int count = 0;

    Rosegarden::timeT endTime = 0;
    Rosegarden::timeT startTime = 0;
    bool haveStart = false, haveEnd = false;

    // Get start and end times
    //
    for (;i != m_selection->getSegmentEvents().end(); ++i)
    {
        if ((*i)->getAbsoluteTime() < startTime || !haveStart) {
            startTime = (*i)->getAbsoluteTime();
	    haveStart = true;
	}
        
        if ((*i)->getAbsoluteTime() > endTime || !haveEnd) {
            endTime = (*i)->getAbsoluteTime();
	    haveEnd = true;
	}
    }

    double step = double(m_value1 - m_value2) / double(endTime - startTime);
    double lowStep = double(m_value2) / double(endTime - startTime);

    for (i = m_selection->getSegmentEvents().begin();
         i != m_selection->getSegmentEvents().end(); ++i)
    {
        if (m_pattern == Rosegarden::FlatPattern)
            (*i)->set<Rosegarden::Int>(m_property, m_value1);
        else if (m_pattern == Rosegarden::AlternatingPattern)
        {
            if (count % 2 == 0)
                (*i)->set<Rosegarden::Int>(m_property, m_value1);
            else
                (*i)->set<Rosegarden::Int>(m_property, m_value2);

        } else if (m_pattern == Rosegarden::CrescendoPattern)
        {
            (*i)->set<Rosegarden::Int>(m_property,
                                       m_value2 +
                                       int(step *
					   ((*i)->getAbsoluteTime() - startTime)));
        } else if (m_pattern == Rosegarden::DecrescendoPattern)
        {
            (*i)->set<Rosegarden::Int>(m_property,
                                       m_value1 -
                                       int(step *
					   ((*i)->getAbsoluteTime() - startTime)));
        } else if (m_pattern == Rosegarden::RingingPattern)
        {
            if (count % 2 == 0)
                (*i)->set<Rosegarden::Int>
                    (m_property,
                     m_value1 - int(step * 
				    ((*i)->getAbsoluteTime() - startTime)));
            else
            {
                int value = m_value2 - int(lowStep *
					   ((*i)->getAbsoluteTime() - startTime));
                if (value < 0) value = 0;

                (*i)->set<Rosegarden::Int>(m_property, value);
            }
        }

        count++;
    }
}


// -------------------- EventQuantizeCommand --------------------
//
//
EventQuantizeCommand::EventQuantizeCommand(Rosegarden::Segment &segment,
					   Rosegarden::timeT startTime,
					   Rosegarden::timeT endTime,
					   Rosegarden::Quantizer *quantizer):
    BasicCommand(getGlobalName(quantizer), segment, startTime, endTime,
		 true), // bruteForceRedo
    m_quantizer(quantizer),
    m_selection(0)
{
    // nothing else
}

EventQuantizeCommand::EventQuantizeCommand(Rosegarden::EventSelection &selection,
					   Rosegarden::Quantizer *quantizer):
    BasicCommand(getGlobalName(quantizer),
		 selection.getSegment(),
		 selection.getStartTime(),
		 selection.getEndTime(),
		 true), // bruteForceRedo
    m_quantizer(quantizer),
    m_selection(&selection)
{
    // nothing else
}

EventQuantizeCommand::EventQuantizeCommand(Rosegarden::Segment &segment,
					   Rosegarden::timeT startTime,
					   Rosegarden::timeT endTime,
					   QString configGroup,
					   bool notation):
    BasicCommand(getGlobalName(makeQuantizer(configGroup, notation)),
		 segment, startTime, endTime,
		 true), // bruteForceRedo
    m_selection(0),
    m_configGroup(configGroup)
{
    // nothing else -- m_quantizer set by makeQuantizer
}

EventQuantizeCommand::EventQuantizeCommand(Rosegarden::EventSelection &selection,
					   QString configGroup,
					   bool notation):
    BasicCommand(getGlobalName(makeQuantizer(configGroup, notation)),
		 selection.getSegment(),
		 selection.getStartTime(),
		 selection.getEndTime(),
		 true), // bruteForceRedo
    m_selection(&selection),
    m_configGroup(configGroup)
{
    // nothing else -- m_quantizer set by makeQuantizer
}

EventQuantizeCommand::~EventQuantizeCommand()
{
    delete m_quantizer;
}

QString
EventQuantizeCommand::getGlobalName(Rosegarden::Quantizer *quantizer)
{
    if (quantizer) {
	if (dynamic_cast<Rosegarden::NotationQuantizer *>(quantizer)) {
	    return i18n("Heuristic Notation &Quantize");
	} else {
	    return i18n("Grid &Quantize");
	}
    }

    return i18n("&Quantize...");
}

void
EventQuantizeCommand::modifySegment()
{
    Rosegarden::Profiler profiler("EventQuantizeCommand::modifySegment", true);

    Segment &segment = getSegment();
    SegmentNotationHelper helper(segment);

    bool rebeam = false;
    bool makeviable = false;
    bool decounterpoint = false;

    if (m_configGroup) {
 //!!! need way to decide whether to do these even if no config group (i.e. through args to the command)
	KConfig *config = kapp->config();
	config->setGroup(m_configGroup);

	rebeam = config->readBoolEntry("quantizerebeam", true);
	makeviable = config->readBoolEntry("quantizemakeviable", false);
	decounterpoint = config->readBoolEntry("quantizedecounterpoint", false);
    }

    if (m_selection) {
        m_quantizer->quantize(m_selection);

    } else {
	m_quantizer->quantize(&segment,
			      segment.findTime(getStartTime()),
			      segment.findTime(getEndTime()));
    }

    if (m_progressTotal > 0) {
	if (rebeam || makeviable || decounterpoint) {
	    emit incrementProgress(m_progressTotal / 2);
	    rgapp->refreshGUI(50);
	} else {
	    emit incrementProgress(m_progressTotal);
	    rgapp->refreshGUI(50);
	}
    }	    

    if (m_selection) {
	EventSelection::RangeTimeList ranges(m_selection->getRangeTimes());
	for (EventSelection::RangeTimeList::iterator i = ranges.begin();
	     i != ranges.end(); ++i) {
	    if (makeviable) {
		helper.makeNotesViable(i->first, i->second, true);
	    }
	    if (decounterpoint) {
		helper.deCounterpoint(i->first, i->second);
	    }
	    if (rebeam) {
		helper.autoBeam(i->first, i->second, GROUP_TYPE_BEAMED);
		helper.autoSlur(i->first, i->second, true);
	    }
	}
    } else {
	if (makeviable) {
	    helper.makeNotesViable(getStartTime(), getEndTime(), true);
	}
	if (decounterpoint) {
	    helper.deCounterpoint(getStartTime(), getEndTime());
	}
	if (rebeam) {
	    helper.autoBeam(getStartTime(), getEndTime(), GROUP_TYPE_BEAMED);
	    helper.autoSlur(getStartTime(), getEndTime(), true);
	}
    }

    if (m_progressTotal > 0) {
	if (rebeam || makeviable || decounterpoint) {
	    emit incrementProgress(m_progressTotal / 2);
	    rgapp->refreshGUI(50);
	}
    }	    
}

Rosegarden::Quantizer *
EventQuantizeCommand::makeQuantizer(QString configGroup,
				    bool notationDefault)
{
    //!!! Excessive duplication with
    // RosegardenQuantizeParameters::getQuantizer in widgets.cpp

    KConfig *config = kapp->config();
    config->setGroup(configGroup);

    Rosegarden::timeT defaultUnit = 
	Rosegarden::Note(Rosegarden::Note::Demisemiquaver).getDuration();
    
    int type = config->readNumEntry("quantizetype", notationDefault ? 2 : 0);
    Rosegarden::timeT unit = config->readNumEntry("quantizeunit",defaultUnit);
    bool notateOnly = config->readBoolEntry("quantizenotationonly", notationDefault);
    bool durations = config->readBoolEntry("quantizedurations", false);
    int simplicity = config->readNumEntry("quantizesimplicity", 13);
    int maxTuplet = config->readNumEntry("quantizemaxtuplet", 3);
    bool counterpoint = config->readNumEntry("quantizecounterpoint", false);
    bool articulate = config->readBoolEntry("quantizearticulate", true);
    int swing = config->readNumEntry("quantizeswing", 0);
    int iterate = config->readNumEntry("quantizeiterate", 100);

    m_quantizer = 0;

    if (type == 0) {
	if (notateOnly) {
	    m_quantizer = new Rosegarden::BasicQuantizer
		(Rosegarden::Quantizer::RawEventData,
		 Rosegarden::Quantizer::NotationPrefix,
		 unit, durations, swing, iterate);
	} else {
	    m_quantizer = new Rosegarden::BasicQuantizer
		(Rosegarden::Quantizer::RawEventData,
		 Rosegarden::Quantizer::RawEventData,
		 unit, durations, swing, iterate);
	}
    } else if (type == 1) {
	if (notateOnly) {
	    m_quantizer = new Rosegarden::LegatoQuantizer
		(Rosegarden::Quantizer::RawEventData,
		 Rosegarden::Quantizer::NotationPrefix, unit);
	} else {
	    m_quantizer = new Rosegarden::LegatoQuantizer
		(Rosegarden::Quantizer::RawEventData,
		 Rosegarden::Quantizer::RawEventData, unit);
	}
    } else {
	
	Rosegarden::NotationQuantizer *nq;

	if (notateOnly) {
	    nq = new Rosegarden::NotationQuantizer();
	} else {
	    nq = new Rosegarden::NotationQuantizer
		(Rosegarden::Quantizer::RawEventData,
		 Rosegarden::Quantizer::RawEventData);
	}

	nq->setUnit(unit);
	nq->setSimplicityFactor(simplicity);
	nq->setMaxTuplet(maxTuplet);
	nq->setContrapuntal(counterpoint);
	nq->setArticulate(articulate);

	m_quantizer = nq;
    }

    return m_quantizer;
}
    


// ---------------- Unquantize -----------
EventUnquantizeCommand::EventUnquantizeCommand(Rosegarden::Segment &segment,
					       Rosegarden::timeT startTime,
					       Rosegarden::timeT endTime,
					       Rosegarden::Quantizer *quantizer) :
    BasicCommand(i18n("Unquantize Events"), segment, startTime, endTime,
		 true), // bruteForceRedo
    m_quantizer(quantizer),
    m_selection(0)
{
    // nothing else
}

EventUnquantizeCommand::EventUnquantizeCommand(
        Rosegarden::EventSelection &selection,
        Rosegarden::Quantizer *quantizer) :
    BasicCommand(i18n("Unquantize Events"),
		 selection.getSegment(),
		 selection.getStartTime(),
		 selection.getEndTime(),
		 true), // bruteForceRedo
    m_quantizer(quantizer),
    m_selection(&selection)
{
    // nothing else
}

EventUnquantizeCommand::~EventUnquantizeCommand()
{
    delete m_quantizer;
}

QString
EventUnquantizeCommand::getGlobalName(Rosegarden::Quantizer *)
{
/*!!!
    if (quantizer) {
	switch (quantizer->getType()) {
	case Rosegarden::Quantizer::PositionQuantize:
	    return i18n("Position &Quantize");
	case Rosegarden::Quantizer::UnitQuantize:
	    return i18n("Unit &Quantize");
	case Rosegarden::Quantizer::NoteQuantize:
	    return i18n("Note &Quantize");
	case Rosegarden::Quantizer::LegatoQuantize:
	    return i18n("Smoothing &Quantize");
	}
    }
*/
    return i18n("&Quantize...");
}

void
EventUnquantizeCommand::modifySegment()
{
    Segment &segment = getSegment();

    if (m_selection) {

        m_quantizer->unquantize(m_selection);

    } else {
	m_quantizer->unquantize(&segment,
				segment.findTime(getStartTime()),
				segment.findTime(getEndTime()));
    }
}


//-----------------Collapse Notes Command-------------------
//
//
void
AdjustMenuCollapseNotesCommand::modifySegment()
{
    SegmentNotationHelper helper(getSegment());
    timeT endTime = getEndTime();

    // This is really nasty stuff.  We can't go in forward direction
    // using the j-iterator trick because collapseNoteAggressively may
    // erase the following iterator as well as the preceding one.  We
    // can't go backward naively, because collapseNoteAggressively
    // erases i from the EventSelection now that it's a
    // SegmentObserver.  We need the fancy hybrid j-iterator-backward
    // technique applied to selections instead of segments.
    
    EventSelection::eventcontainer::iterator i =
	m_selection->getSegmentEvents().end();
    EventSelection::eventcontainer::iterator j = i;
    EventSelection::eventcontainer::iterator beg =
	m_selection->getSegmentEvents().begin();
    bool thisOne = false;

    while (i != beg && (!thisOne || (*i != *beg))) {
	
	--j;

	if (thisOne) {
	    helper.collapseNoteAggressively(*i, endTime);
	}
	
	// rather than "true" one could perform a test to see
	// whether j pointed to a candidate for collapsing:
	thisOne = true;
	
	i = j;
    }
    
    if (thisOne) {
	helper.collapseNoteAggressively(*i, endTime);
    }
}



SetLyricsCommand::SetLyricsCommand(Segment *segment, QString newLyricData) :
    KNamedCommand(getGlobalName()),
    m_segment(segment),
    m_newLyricData(newLyricData)
{
    // nothing
}

SetLyricsCommand::~SetLyricsCommand()
{
    for (std::vector<Event *>::iterator i = m_oldLyricEvents.begin();
	 i != m_oldLyricEvents.end(); ++i) {
	delete *i;
    }
}

void
SetLyricsCommand::execute()
{
    // This and LyricEditDialog::unparse() are opposites that will
    // need to be kept in sync with any changes to one another.  (They
    // should really both be in a common lyric management class.)

    // first remove old lyric events
    
    Segment::iterator i = m_segment->begin();

    while (i != m_segment->end()) {

	Segment::iterator j = i;
	++j;

	if ((*i)->isa(Text::EventType)) {
	    std::string textType;
	    if ((*i)->get<String>(Text::TextTypePropertyName, textType) &&
		textType == Text::Lyric) {
		m_oldLyricEvents.push_back(new Event(**i));
		m_segment->erase(i);
	    }
	}

	i = j;
    }

    // now parse the new string

    QStringList barStrings =
	QStringList::split("/", m_newLyricData, true); // empties ok
    
    Rosegarden::Composition *comp = m_segment->getComposition();
    int barNo = comp->getBarNumber(m_segment->getStartTime());
    
    for (QStringList::Iterator bsi = barStrings.begin();
	 bsi != barStrings.end(); ++bsi) {

	NOTATION_DEBUG << "Parsing lyrics for bar number " << barNo << ": \"" << *bsi << "\"" << endl;

	std::pair<timeT, timeT> barRange = comp->getBarRange(barNo++);
	QString syllables = *bsi;
	syllables.replace(QRegExp("\\[\\d+\\] "), " ");
	QStringList syllableList = QStringList::split(" ", syllables); // no empties
	
	i = m_segment->findTime(barRange.first);
	timeT laterThan = barRange.first - 1;

	for (QStringList::Iterator ssi = syllableList.begin();
	     ssi != syllableList.end(); ++ssi) {

	    while (m_segment->isBeforeEndMarker(i) &&
		   (*i)->getAbsoluteTime() < barRange.second &&
		   (!(*i)->isa(Note::EventType) ||
		    (*i)->getNotationAbsoluteTime() <= laterThan ||
		    ((*i)->has(TIED_BACKWARD) &&
		     (*i)->get<Rosegarden::Bool>(TIED_BACKWARD)))) ++i;

	    timeT time = m_segment->getEndMarkerTime();
	    timeT notationTime = time;
	    if (m_segment->isBeforeEndMarker(i)) {
		time = (*i)->getAbsoluteTime();
		notationTime = (*i)->getNotationAbsoluteTime();
	    }

	    QString syllable = *ssi;
	    syllable.replace(QRegExp("~"), " ");
	    syllable = syllable.simplifyWhiteSpace();
	    if (syllable == "") continue;
	    laterThan = notationTime + 1;
	    if (syllable == ".") continue;

	    NOTATION_DEBUG << "Syllable \"" << syllable << "\" at time " << time <<  endl;

	    Text text(qstrtostr(syllable), Text::Lyric);
	    m_segment->insert(text.getAsEvent(time));
	}
    }
}

void
SetLyricsCommand::unexecute()
{
    // Before we inserted the new lyric events (in execute()), we
    // removed all the existing ones.  That means we know any lyric
    // events found now must have been inserted by execute(), so we
    // can safely remove them before restoring the old ones.
    
    Segment::iterator i = m_segment->begin();

    while (i != m_segment->end()) {

	Segment::iterator j = i;
	++j;

	if ((*i)->isa(Text::EventType)) {
	    std::string textType;
	    if ((*i)->get<String>(Text::TextTypePropertyName, textType) &&
		textType == Text::Lyric) {
		m_segment->erase(i);
	    }
	}

	i = j;
    }

    // Now restore the old ones and clear out the vector.

    for (std::vector<Event *>::iterator i = m_oldLyricEvents.begin();
	 i != m_oldLyricEvents.end(); ++i) {
	m_segment->insert(*i);
    }

    m_oldLyricEvents.clear();
}

    
void
TransposeCommand::modifySegment()
{
    EventSelection::eventcontainer::iterator i;

    for (i  = m_selection->getSegmentEvents().begin();
	 i != m_selection->getSegmentEvents().end(); ++i) {

	if ((*i)->isa(Note::EventType)) {
	    try {
		long pitch = (*i)->get<Int>(PITCH);
		pitch += m_semitones;
		(*i)->set<Int>(PITCH, pitch); 
		(*i)->unset(ACCIDENTAL);
	    } catch (...) { }
	}
    }
}


RescaleCommand::RescaleCommand(EventSelection &sel,
			       timeT newDuration,
			       bool closeGap) :
    BasicCommand(getGlobalName(), sel.getSegment(),
		 sel.getStartTime(),
		 getAffectedEndTime(sel, newDuration, closeGap),
		 true),
    m_selection(&sel),
    m_oldDuration(sel.getTotalDuration()),
    m_newDuration(newDuration),
    m_closeGap(closeGap)
{
    // nothing else
}

timeT
RescaleCommand::getAffectedEndTime(EventSelection &sel,
				   timeT newDuration,
				   bool closeGap)
{
    timeT preScaleEnd = sel.getEndTime();
    if (closeGap) preScaleEnd = sel.getSegment().getEndMarkerTime();

    // dupe of rescale(), but we can't use that here as the m_
    // variables may not have been set
    double d = preScaleEnd;
    d *= newDuration;
    d /= sel.getTotalDuration();
    d += 0.5;
    timeT postScaleEnd = (timeT)d;
    
    return std::max(preScaleEnd, postScaleEnd);
}

timeT
RescaleCommand::rescale(timeT t)
{
    // avoid overflows by using doubles
    double d = t;
    d *= m_newDuration;
    d /= m_oldDuration;
    d += 0.5;
    return (timeT)d;
}

void
RescaleCommand::modifySegment()
{
    if (m_oldDuration == m_newDuration) return;

    timeT startTime = m_selection->getStartTime();
    timeT diff = m_newDuration - m_oldDuration;
    std::vector<Event *> toErase;
    std::vector<Event *> toInsert;
    
    Segment &segment = m_selection->getSegment();

    for (EventSelection::eventcontainer::iterator i = 
	     m_selection->getSegmentEvents().begin();
	 i != m_selection->getSegmentEvents().end(); ++i) {

	toErase.push_back(*i);

	timeT t = (*i)->getAbsoluteTime() - startTime;
	timeT d = (*i)->getDuration();
	t = rescale(t);
	d = rescale(d);

	toInsert.push_back(new Event(**i, startTime + t, d));
    }

    if (m_closeGap) {
	for (Segment::iterator i = segment.findTime(startTime + m_oldDuration);
	     i != segment.end(); ++i) {
	    // move all events including any following the end marker
	    toErase.push_back(*i);
	    toInsert.push_back(new Event(**i, (*i)->getAbsoluteTime() + diff));
	}
    }

    for (std::vector<Event *>::iterator i = toErase.begin(); i != toErase.end(); ++i) {
        m_selection->removeEvent(*i); // remove from selection
	segment.eraseSingle(*i);
    }

    for (std::vector<Event *>::iterator i = toInsert.begin(); i != toInsert.end(); ++i) {
	segment.insert(*i);
        m_selection->addEvent(*i);  // add to selection
    }

    if (m_closeGap && diff > 0) {
	segment.setEndMarkerTime(startTime +
				 rescale(segment.getEndMarkerTime() - startTime));
    }

    segment.normalizeRests(getStartTime(), getEndTime());
}


MoveCommand::MoveCommand(Segment &s, timeT delta, bool useNotationTimings,
			 EventSelection &sel) :
    BasicCommand(getGlobalName(), s,
		 delta < 0 ? sel.getStartTime() + delta : sel.getStartTime(),
		 delta < 0 ? sel.getEndTime()+1 : sel.getEndTime()+1 + delta,
		 true),
    m_selection(&sel),
    m_delta(delta),
    m_useNotationTimings(useNotationTimings),
    m_lastInsertedEvent(0)
{
    // nothing else
}

QString
MoveCommand::getGlobalName(Rosegarden::timeT delta)
{
    if (delta == 0) {
	return "&Move Events";
    } else if (delta < 0) {
	return "&Move Events Back";
    } else {
	return "&Move Events Forward";
    }
}

void
MoveCommand::modifySegment()
{
    RG_DEBUG << "MoveCommand::modifySegment: delta is " << m_delta
	     << ", useNotationTimings " << m_useNotationTimings
	     << ", start time " << m_selection->getStartTime()
	     << ", end time " << m_selection->getEndTime() << endl;

    std::vector<Event *> toErase;
    std::vector<Event *> toInsert;

    timeT a0 = m_selection->getStartTime();
    timeT a1 = m_selection->getEndTime();
    timeT b0 = a0 + m_delta;
    timeT b1 = b0 + (a1 - a0);

    EventSelection::eventcontainer::iterator i;

    for (i  = m_selection->getSegmentEvents().begin();
	 i != m_selection->getSegmentEvents().end(); ++i) {

	if ((*i)->isa(Note::EventRestType)) continue;

	toErase.push_back(*i);
	timeT newTime =
	    (m_useNotationTimings ?
	     (*i)->getNotationAbsoluteTime() : (*i)->getAbsoluteTime()) + m_delta;

	Event *e;
	if (m_useNotationTimings) {
	    e = new Event(**i, newTime, (*i)->getDuration(), (*i)->getSubOrdering(),
			  newTime, (*i)->getNotationDuration());
	} else {
	    e = new Event(**i, newTime);
	}

	toInsert.push_back(e);
    }

    Segment &segment(m_selection->getSegment());

    for (unsigned int j = 0; j < toErase.size(); ++j) {
	Segment::iterator jtr(segment.findSingle(toErase[j]));
	if (jtr != segment.end()) segment.erase(jtr);
    }

    for (unsigned int j = 0; j < toInsert.size(); ++j) {

	Segment::iterator jtr = segment.end();

	// somewhat like the NoteOverlay part of PasteEventsCommand::modifySegment
/* nah -- let's do a de-counterpoint afterwards perhaps
	if (m_useNotationTimings && toInsert[j]->isa(Note::EventType)) {
	    long pitch = 0;
	    Accidental explicitAccidental = NoAccidental;
	    toInsert[j]->get<String>(ACCIDENTAL, explicitAccidental);
	    if (toInsert[j]->get<Int>(PITCH, pitch)) {
		jtr = SegmentNotationHelper(segment).insertNote
		    (toInsert[j]->getAbsoluteTime(),
		     Note::getNearestNote(toInsert[j]->getDuration()),
		     pitch, explicitAccidental);
		delete toInsert[j];
		toInsert[j] = *jtr;
	    }
	} else {
*/
	    jtr = segment.insert(toInsert[j]);
//	}

        // insert new event back into selection
        m_selection->addEvent(toInsert[j]);

	if (jtr != segment.end()) m_lastInsertedEvent = toInsert[j];
    }

    if (m_useNotationTimings) {
	SegmentNotationHelper(segment).deCounterpoint(b0, b1);
    }

    segment.normalizeRests(a0, a1);
    segment.normalizeRests(b0, b1);
}
   

MoveAcrossSegmentsCommand::MoveAcrossSegmentsCommand(Rosegarden::Segment &,
						     Rosegarden::Segment &secondSegment,
						     Rosegarden::timeT newStartTime,
						     bool notation,
						     Rosegarden::EventSelection &selection) :
    KMacroCommand(getGlobalName()),
    m_clipboard(new Rosegarden::Clipboard())
{
    addCommand(new CutCommand(selection, m_clipboard));

    timeT newEndTime = newStartTime + selection.getEndTime() - selection.getStartTime();
    Segment::iterator i = secondSegment.findTime(newEndTime);
    if (i == secondSegment.end()) newEndTime = secondSegment.getEndTime();
    else newEndTime = (*i)->getAbsoluteTime();

    addCommand(new PasteEventsCommand(secondSegment, m_clipboard,
				      newStartTime,
				      newEndTime,
				      notation ?
				      PasteEventsCommand::NoteOverlay :
				      PasteEventsCommand::MatrixOverlay));
}

MoveAcrossSegmentsCommand::~MoveAcrossSegmentsCommand()
{
    delete m_clipboard;
}

QString
MoveAcrossSegmentsCommand::getGlobalName()
{
    return i18n("&Move Events to Other Segment");
}



void
ChangeVelocityCommand::modifySegment()
{
    EventSelection::eventcontainer::iterator i;

    for (i  = m_selection->getSegmentEvents().begin();
	 i != m_selection->getSegmentEvents().end(); ++i) {

	if ((*i)->isa(Note::EventType)) {

	    long velocity = 100;
	    (*i)->get<Int>(VELOCITY, velocity);

	    // round velocity up to the next multiple of delta
	    velocity /= m_delta;
	    velocity *= m_delta;
	    velocity += m_delta;

	    if (velocity < 0) velocity = 0;
	    if (velocity > 127) velocity = 127;
	    (*i)->set<Int>(VELOCITY, velocity); 
	}
    }
}

// ------------------- Markers -------------------
//
//


AddMarkerCommand::AddMarkerCommand(Rosegarden::Composition *comp,
                                   Rosegarden::timeT time,
                                   const std::string &name,
                                   const std::string &description):
    KNamedCommand(getGlobalName()),
    m_composition(comp),
    m_detached(true)
{
    m_marker = new Rosegarden::Marker(time, name, description);
}

AddMarkerCommand::~AddMarkerCommand()
{
    if (m_detached) delete m_marker;
}

void
AddMarkerCommand::execute()
{
    m_composition->addMarker(m_marker);
    m_detached = false;
}

void
AddMarkerCommand::unexecute()
{
    m_composition->detachMarker(m_marker);
    m_detached = true;
}


RemoveMarkerCommand::RemoveMarkerCommand(Rosegarden::Composition *comp,
                                         Rosegarden::timeT time,
                                         const std::string &name,
                                         const std::string &description):
    KNamedCommand(getGlobalName()),
    m_composition(comp),
    m_marker(0),
    m_time(time),
    m_name(name),
    m_descr(description),
    m_detached(false)
{
}

RemoveMarkerCommand::~RemoveMarkerCommand()
{
    if (m_detached) delete m_marker;
}

void
RemoveMarkerCommand::execute()
{
    Rosegarden::Composition::markercontainer markers = 
        m_composition->getMarkers();

    Rosegarden::Composition::markerconstiterator it = markers.begin();

    for (; it != markers.end(); ++it)
    {
        if ((*it)->getTime() == m_time && 
            (*it)->getName() == m_name && 
            (*it)->getDescription() == m_descr)
        {
            m_marker = (*it);
            m_composition->detachMarker(m_marker);
	    m_detached = true;
            return;
        }
    }
}

void
RemoveMarkerCommand::unexecute()
{
    if (m_marker) m_composition->addMarker(m_marker);
    m_detached = false;
}

ModifyMarkerCommand::ModifyMarkerCommand(Rosegarden::Composition *comp,
                                         Rosegarden::timeT time,
                                         Rosegarden::timeT newTime,
                                         const std::string &name,
                                         const std::string &des):
    KNamedCommand(getGlobalName()),
    m_composition(comp),
    m_time(time),
    m_newTime(newTime),
    m_name(name),
    m_description(des),
    m_oldName(""),
    m_oldDescription("")
{
}

ModifyMarkerCommand::~ModifyMarkerCommand()
{
}

void
ModifyMarkerCommand::execute()
{
    Rosegarden::Composition::markercontainer markers = 
        m_composition->getMarkers();

    Rosegarden::Composition::markerconstiterator it = markers.begin();

    for (; it != markers.end(); ++it)
    {
        if ((*it)->getTime() == m_time)
        {
            if (m_oldName.empty()) m_oldName = (*it)->getName();
            if (m_oldDescription.empty()) 
                m_oldDescription = (*it)->getDescription();

            (*it)->setName(m_name);
            (*it)->setDescription(m_description);
            (*it)->setTime(m_newTime);
            return;
        }
    }
}

void
ModifyMarkerCommand::unexecute()
{
    Rosegarden::Composition::markercontainer markers = 
        m_composition->getMarkers();

    Rosegarden::Composition::markerconstiterator it = markers.begin();

    for (; it != markers.end(); ++it)
    {
        if ((*it)->getTime() == m_newTime)
        {
            (*it)->setName(m_oldName);
            (*it)->setDescription(m_oldDescription);
            (*it)->setTime(m_time);
        }
    }
}


void
SetTriggerCommand::modifySegment()
{
    EventSelection::eventcontainer::iterator i;

    for (i  = m_selection->getSegmentEvents().begin();
	 i != m_selection->getSegmentEvents().end(); ++i) {

	if (!m_notesOnly || (*i)->isa(Note::EventType)) {
	    (*i)->set<Int>(TRIGGER_SEGMENT_ID, m_triggerSegmentId);
	    (*i)->set<Rosegarden::Bool>(TRIGGER_SEGMENT_RETUNE, m_retune);
	    (*i)->set<Rosegarden::String>(TRIGGER_SEGMENT_ADJUST_TIMES, m_timeAdjust);
	    if (m_mark != Rosegarden::Marks::NoMark) {
		Rosegarden::Marks::addMark(**i, m_mark, true);
	    }
	}
    }

    // Update the rec references here, without bothering to do so in unexecute
    // or in ClearTriggersCommand -- because it doesn't matter if a trigger
    // has references to segments that don't actually trigger it, whereas it
    // does matter if it loses a reference to something that does

    Rosegarden::TriggerSegmentRec *rec =
	m_selection->getSegment().getComposition()->getTriggerSegmentRec
	(m_triggerSegmentId);

    if (rec) rec->updateReferences();
}

void
ClearTriggersCommand::modifySegment()
{
    EventSelection::eventcontainer::iterator i;

    for (i  = m_selection->getSegmentEvents().begin();
	 i != m_selection->getSegmentEvents().end(); ++i) {

	(*i)->unset(TRIGGER_SEGMENT_ID);
	(*i)->unset(TRIGGER_SEGMENT_RETUNE);
	(*i)->unset(TRIGGER_SEGMENT_ADJUST_TIMES);
    }
}


InsertTriggerNoteCommand::InsertTriggerNoteCommand(Rosegarden::Segment &segment,
						   Rosegarden::timeT time,
						   Rosegarden::Note note,
						   int pitch,
						   int velocity,
						   NoteStyleName noteStyle,
						   Rosegarden::TriggerSegmentId id,
						   bool retune,
						   std::string timeAdjust,
						   Rosegarden::Mark mark) :
    BasicCommand(i18n("Insert Trigger Note"), segment,
		 time, time + note.getDuration()),
    m_time(time),
    m_note(note),
    m_pitch(pitch),
    m_velocity(velocity),
    m_noteStyle(noteStyle),
    m_id(id),
    m_retune(retune),
    m_timeAdjust(timeAdjust),
    m_mark(mark)
{
    // nothing
}

InsertTriggerNoteCommand::~InsertTriggerNoteCommand()
{
    // nothing
}

void
InsertTriggerNoteCommand::modifySegment()
{
    // Insert via a model event, so as to apply the note style.
    // This is a subset of the work done by NoteInsertionCommand
    
    Event *e = new Event(Note::EventType, m_time, m_note.getDuration());

    e->set<Int>(PITCH, m_pitch);
    e->set<Int>(VELOCITY, m_velocity);

    if (m_noteStyle != NoteStyleFactory::DefaultStyle) {
	e->set<String>(NotationProperties::NOTE_STYLE, m_noteStyle);
    }

    e->set<Int>(TRIGGER_SEGMENT_ID, m_id);
    e->set<Rosegarden::Bool>(TRIGGER_SEGMENT_RETUNE, m_retune);
    e->set<Rosegarden::String>(TRIGGER_SEGMENT_ADJUST_TIMES, m_timeAdjust);

    if (m_mark != Rosegarden::Marks::NoMark) {
	Rosegarden::Marks::addMark(*e, m_mark, true);
    }

    Segment &s(getSegment());
    Segment::iterator i = Rosegarden::SegmentMatrixHelper(s).insertNote(e);

    Segment::iterator j = i;
    while (++j != s.end()) {
	if ((*j)->getAbsoluteTime() >
	    (*i)->getAbsoluteTime() + (*i)->getDuration()) break;
	if ((*j)->isa(Note::EventType)) {
	    if ((*j)->getAbsoluteTime() ==
		(*i)->getAbsoluteTime() + (*i)->getDuration()) {
		if ((*j)->has(TIED_BACKWARD) && (*j)->get<Rosegarden::Bool>(TIED_BACKWARD) &&
		    (*j)->has(PITCH) && ((*j)->get<Int>(PITCH) == m_pitch)) {
		    (*i)->set<Rosegarden::Bool>(TIED_FORWARD, true);
		}
	    }
	}
    }

    Rosegarden::TriggerSegmentRec *rec =
	getSegment().getComposition()->getTriggerSegmentRec(m_id);

    if (rec) rec->updateReferences();
}


void
SetNoteTypeCommand::modifySegment()
{
    std::vector<Event *> toErase;
    std::vector<Event *> toInsert;
    
    EventSelection::eventcontainer::iterator i;
    timeT endTime = getEndTime();

    for (i  = m_selection->getSegmentEvents().begin();
	 i != m_selection->getSegmentEvents().end(); ++i) {

	if ((*i)->isa(Rosegarden::Note::EventType)) {
	    toErase.push_back(*i);
	    
	    Event *e;
	    if (m_notationOnly) {
		e = new Event(**i,
			      (*i)->getAbsoluteTime(),
			      (*i)->getDuration(),
			      (*i)->getSubOrdering(),
			      (*i)->getNotationAbsoluteTime(),
			      Rosegarden::Note(m_type).getDuration());
	    } else {
		e = new Event(**i,
			      (*i)->getNotationAbsoluteTime(),
			      Rosegarden::Note(m_type).getDuration());
	    }
		
	    if (e->getNotationAbsoluteTime() + e->getNotationDuration() > endTime) {
		endTime = e->getNotationAbsoluteTime() + e->getNotationDuration();
	    }

	    toInsert.push_back(e);
	}
    }

    for (std::vector<Event *>::iterator i = toErase.begin(); i != toErase.end(); ++i) {
	m_selection->getSegment().eraseSingle(*i);
    }

    for (std::vector<Event *>::iterator i = toInsert.begin(); i != toInsert.end(); ++i) {
	m_selection->getSegment().insert(*i);
	m_selection->addEvent(*i);
    }

    m_selection->getSegment().normalizeRests(getStartTime(), endTime);
}

void
AddDotCommand::modifySegment()
{
    std::vector<Event *> toErase;
    std::vector<Event *> toInsert;
    
    EventSelection::eventcontainer::iterator i;
    timeT endTime = getEndTime();

    for (i  = m_selection->getSegmentEvents().begin();
	 i != m_selection->getSegmentEvents().end(); ++i) {

	if ((*i)->isa(Rosegarden::Note::EventType)) {

	    Rosegarden::Note note = Rosegarden::Note::getNearestNote
		((*i)->getNotationDuration());
	    int dots = note.getDots();
	    if (++dots > 2) dots = 0;

	    toErase.push_back(*i);

	    Event *e;

	    if (m_notationOnly) {
		e = new Event(**i,
			      (*i)->getAbsoluteTime(),
			      (*i)->getDuration(),
			      (*i)->getSubOrdering(),
			      (*i)->getNotationAbsoluteTime(),
			      Rosegarden::Note(note.getNoteType(),
					       dots).getDuration());

	    } else {
		e = new Event(**i,
			      (*i)->getNotationAbsoluteTime(),
			      Rosegarden::Note(note.getNoteType(),
					       dots).getDuration());
	    }

	    if (e->getNotationAbsoluteTime() + e->getNotationDuration() > endTime) {
		endTime = e->getNotationAbsoluteTime() + e->getNotationDuration();
	    }

	    toInsert.push_back(e);
	}
    }

    for (std::vector<Event *>::iterator i = toErase.begin(); i != toErase.end(); ++i) {
	m_selection->getSegment().eraseSingle(*i);
    }

    for (std::vector<Event *>::iterator i = toInsert.begin(); i != toInsert.end(); ++i) {
	m_selection->getSegment().insert(*i);
	m_selection->addEvent(*i);
    }

    m_selection->getSegment().normalizeRests(getStartTime(), endTime);
}