forked from ghchen99/mcp-musescore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmusescore-mcp-websocket.qml
More file actions
1168 lines (960 loc) · 41.8 KB
/
Copy pathmusescore-mcp-websocket.qml
File metadata and controls
1168 lines (960 loc) · 41.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import QtQuick 2.9
import MuseScore 3.0
MuseScore {
id: root
menuPath: "Plugins.MuseScore API Server"
description: "Exposes MuseScore API via WebSocket (Clean Version)"
version: "2.0"
property var clientConnections: []
property var selectionState: ({
startStaff: 0,
endStaff: 1,
startTick: 0,
elements: []
})
// ========================================
// WEBSOCKET & MESSAGE PROCESSING
// ========================================
function processMessage(message, clientId) {
console.log("Received message: " + message);
try {
var command = JSON.parse(message);
var result = processCommand(command);
api.websocketserver.send(clientId, JSON.stringify({
status: "success",
result: result
}));
} catch (e) {
console.log("Error processing command: " + e.toString());
api.websocketserver.send(clientId, JSON.stringify({
status: "error",
message: e.toString()
}));
}
}
function processCommand(command) {
console.log("Processing command: " + command.action);
switch(command.action) {
// Core operations
case "getScore": return getScore(command.params);
case "syncStateToSelection": return syncStateToSelection();
case "ping": return "pong";
case "undo": return undo();
case "goToBeginningOfScore": return goToBeginningOfScore(command.params);
case "processSequence": return processSequence(command.params);
// Navigation
case "getCursorInfo": return getCursorInfo(command.params);
case "goToMeasure": return goToMeasure(command.params);
case "goToFinalMeasure": return goToFinalMeasure(command.params);
case "nextElement": return nextElement(command.params);
case "prevElement": return prevElement(command.params);
case "nextStaff": return nextStaff(command.params);
case "prevStaff": return prevStaff(command.params);
// Selection
case "selectCurrentMeasure": return selectCurrentMeasure(command.params);
case "selectCustomRange": return selectCustomRange(command.params);
// Notes & Music
case "addNote": return addNote(command.params);
case "addRest": return addRest(command.params);
case "addTuplet": return addTuplet(command.params);
case "addLyrics": return addLyrics(command.params);
// Measures
case "appendMeasure": return appendMeasure(command.params);
case "insertMeasure": return insertMeasure(command.params);
case "deleteSelection": return deleteSelection(command.params);
// Staff & Instruments
case "addInstrument": return addInstrument(command.params);
case "setStaffMute": return setStaffMute(command.params);
case "setInstrumentSound": return setInstrumentSound(command.params);
case "setTimeSignature": return setTimeSignature(command.params);
case "setTempo": return setTempo(command.params);
default:
throw new Error("Unknown command: " + command.action);
}
}
// ========================================
// UTILITY FUNCTIONS
// ========================================
function validateParams(params, required) {
var missing = [];
for (var i = 0; i < required.length; i++) {
if (params[required[i]] === undefined) {
missing.push(required[i]);
}
}
return missing.length > 0 ? { error: "Missing required parameters: " + missing.join(", ") } : { valid: true };
}
function executeWithUndo(operation) {
if (!curScore) return { error: "No score open" };
curScore.startCmd();
try {
var result = operation();
curScore.endCmd();
return result;
} catch (e) {
curScore.endCmd(true);
return { error: e.toString() };
}
}
function getNoteName(note) {
const noteNames = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
return noteNames[note % 12];
}
function getTpcName(tpc) {
if (tpc === -1) return "Fbb";
var tpcNames = [
"Cbb", "Gbb", "Dbb", "Abb", "Ebb", "Bbb", "Fb",
"Cb", "Gb", "Db", "Ab", "Eb", "Bb", "F",
"C", "G", "D", "A", "E", "B", "F#",
"C#", "G#", "D#", "A#", "E#", "B#", "F##",
"C##", "G##", "D##", "A##", "E##", "B##", "F###"
];
if (tpc >= 0 && tpc < tpcNames.length) {
return tpcNames[tpc];
}
return "Unknown";
}
function getDurationName(duration) {
const durationNames = ["LONG","BREVE","WHOLE","HALF","QUARTER","EIGHTH","16TH","32ND","64TH","128TH","256TH","512TH","1024TH","ZERO","MEASURE","INVALID"];
return durationNames[duration] || "UNKNOWN";
}
// ========================================
// CURSOR MANAGEMENT
// ========================================
function createCursor(params) {
if (!curScore) throw new Error("No score open");
if (!params || Object.keys(params).length === 0) {
params = selectionState;
}
var cursor = curScore.newCursor();
cursor.inputStateMode = Cursor.INPUT_STATE_SYNC_WITH_SCORE;
// Set track
if (params.startStaff !== undefined) cursor.staffIdx = params.startStaff;
if (params.voice !== undefined) cursor.voice = params.voice;
// Position cursor
if (params.rewindMode !== undefined) {
cursor.rewind(params.rewindMode);
} else if (params.startTick !== undefined) {
try {
cursor.rewindToTick(params.startTick);
} catch (e) {
console.log("rewindToTick failed, using manual navigation");
cursor.rewind(0);
while (cursor.tick < params.startTick && cursor.next()) {}
}
} else if (params.measure !== undefined) {
cursor.rewind(0);
for (var i = 0; i < params.measure && cursor.nextMeasure(); i++) {}
} else {
cursor.rewind(0);
}
// Set duration
if (params.duration) {
cursor.setDuration(params.duration.numerator || 1, params.duration.denominator || 4);
}
return cursor;
}
function initCursorState() {
if (!curScore) return "No score open";
return executeWithUndo(function() {
var cursor = curScore.newCursor();
cursor.rewind(0);
var startTick = cursor.tick;
cursor.next();
var endTick = cursor.tick;
var element = cursor.element;
selectionState = {
startStaff: cursor.staffIdx,
endStaff: cursor.staffIdx + 1,
startTick: startTick,
elements: element ? [processElement(element)] : []
};
curScore.selection.clear();
curScore.selection.selectRange(startTick, endTick, 0, 0);
return "Initialized at " + [startTick, endTick, 0, 0].join(',');
});
}
// ========================================
// ELEMENT PROCESSING
// ========================================
function processElement(element) {
if (!element) return null;
if (element.name !== "Chord" && element.name !== "Rest") return null;
var base = {
name: element.name,
durationTicks: element.actualDuration ? element.actualDuration.ticks : 0,
isTie: element.tieForward ? true : false,
isTuplet: element.tuplet ? true : false
};
var lyricsList = [];
try {
if (typeof element.lyrics === "function") {
lyricsList = element.lyrics() || [];
} else if (element.lyrics) {
// Could be an array or object
lyricsList = element.lyrics;
}
} catch (e) {
console.log("Error reading lyrics property: " + e);
}
// Fallback: check segment annotations if no lyrics found directly
if ((!lyricsList || lyricsList.length === 0) && element.parent) {
try {
var segment = element.parent;
if (segment.annotations) {
for (var a = 0; a < segment.annotations.length; a++) {
var ann = segment.annotations[a];
if (ann && (ann.type === Element.LYRICS || ann.name === "Lyrics") && ann.track === element.track) {
// Ensure it's treated as an array
if (!Array.isArray(lyricsList)) lyricsList = [];
lyricsList.push(ann);
}
}
}
} catch (e) {
console.log("Error reading segment annotations: " + e);
}
}
if (lyricsList && lyricsList.length > 0) {
base.lyrics = [];
for (var l = 0; l < lyricsList.length; l++) {
var lyr = lyricsList[l];
if (lyr && lyr.text) {
base.lyrics.push({
text: lyr.text,
no: lyr.no !== undefined ? lyr.no : (lyr.verse !== undefined ? lyr.verse : 0),
syllabic: lyr.syllabic !== undefined ? lyr.syllabic : 0
});
}
}
}
if (element.name === "Chord") {
base.notes = [];
var notesObj = element.notes || {};
var keys = Object.keys(notesObj);
for (var k = 0; k < keys.length; k++) {
var note = notesObj[keys[k]];
base.notes.push({
pitchMidi: note.pitch,
tpc: note.tpc,
pitchName: getTpcName(note.tpc)
});
}
}
return base;
}
// ========================================
// CORE OPERATIONS
// ========================================
function undo() {
return executeWithUndo(function() {
cmd("undo");
return { success: true, message: "Undo successful" };
});
}
function goToBeginningOfScore(params) {
var response = initCursorState();
return {
success: true,
message: response,
currentSelection: selectionState,
currentScore: params && (params.verbose !== "false" && params.verbose !== false) ? getScoreSummary() : null
};
}
function processSequence(params) {
if (!curScore) return { error: "No score open" };
if (!params.sequence) return { error: "No sequence specified" };
var validCommands = [
"getScore", "addNote", "addRest", "addTuplet", "appendMeasure", "deleteSelection",
"getCursorInfo", "goToMeasure", "nextElement", "prevElement", "nextStaff", "prevStaff",
"selectCurrentMeasure", "processSequence", "insertMeasure", "goToFinalMeasure",
"goToBeginningOfScore", "setTimeSignature", "addLyrics", "addInstrument",
"setStaffMute", "setInstrumentSound", "setTempo"
];
try {
for (var i = 0; i < params.sequence.length; i++) {
var command = params.sequence[i];
if (!validCommands.includes(command.action)) {
throw new Error("Invalid command: " + command.action);
}
processCommand(command);
}
return { success: true, message: "Sequence processed", currentSelection: selectionState };
} catch (e) {
return { error: e.toString() };
}
}
// ========================================
// NAVIGATION FUNCTIONS
// ========================================
function syncStateToSelection() {
if (!curScore) return { error: "No score open" };
try {
var selection = curScore.selection;
var startSegment = selection.startSegment;
var endSegment = selection.endSegment;
if (startSegment && endSegment) {
var cursor = createCursor({
startTick: startSegment.tick,
startStaff: selection.startStaff
});
var elementsMap = {};
for (var st = selection.startStaff; st < selection.endStaff; st++) {
elementsMap[`staff${st}`] = [];
}
var currentSegment = startSegment;
while (currentSegment && currentSegment.tick < endSegment.tick) {
for (var s = selection.startStaff; s < selection.endStaff; s++) {
for (var v = 0; v < 4; v++) {
var track = s * 4 + v;
var el = currentSegment.elementAt(track);
if (el) {
var processed = processElement(el);
if (processed) {
processed.voice = v;
processed.startTick = currentSegment.tick;
elementsMap[`staff${s}`].push(processed);
}
}
}
}
currentSegment = currentSegment.next;
}
selectionState = {
startStaff: selection.startStaff,
endStaff: selection.endStaff,
startTick: startSegment.tick,
elements: elementsMap,
totalDuration: endSegment.tick - startSegment.tick
};
} else {
var c = createCursor();
if (c && c.element) {
var elElement = processElement(c.element);
elElement.startTick = c.tick;
var sStart = selection.startStaff || 0;
var singleMap = {};
singleMap[`staff${sStart}`] = [elElement];
selectionState = {
startStaff: sStart,
endStaff: sStart + 1,
startTick: c.tick,
elements: singleMap,
totalDuration: elElement.durationTicks
};
} else {
return { error: "No valid selection or cursor elements found" };
}
}
return { success: true, currentSelection: selectionState };
} catch (e) {
return { success: false, error: e.toString() };
}
}
function getCursorInfo(params) {
if (!curScore) return { error: "No score open" };
syncStateToSelection();
return {
success: true,
currentSelection: selectionState,
currentScore: params && (params.verbose !== "false" && params.verbose !== false) ? getScoreSummary() : null
};
}
function goToMeasure(params) {
var validation = validateParams(params, ["measure"]);
if (!validation.valid) return validation;
return executeWithUndo(function() {
var score = getScoreSummary();
if (params.measure < 1 || params.measure > score.measures.length) {
return { error: "Invalid measure number" };
}
var measureIdx = params.measure - 1;
var measure = score.measures[measureIdx];
var startTick = measure.startTick;
var endTick = (measureIdx + 1 < score.measures.length) ? score.measures[measureIdx + 1].startTick : curScore.lastSegment.tick;
curScore.selection.clear();
curScore.selection.selectRange(startTick, endTick, 0, curScore.nstaves);
var res = syncStateToSelection();
if (res.error) return res;
return { success: true, currentSelection: selectionState };
});
}
function nextElement(params) {
return executeWithUndo(function() {
syncStateToSelection();
var cursor = createCursor({
startTick: selectionState.startTick,
startStaff: selectionState.startStaff
});
var numElements = params && params.numElements || 1;
var success = true;
for (var i = 0; i < numElements && success; i++) {
success = cursor.next();
}
if (success) {
var element = processElement(cursor.element);
var startTick = cursor.tick;
var staffIdx = cursor.staffIdx;
// Check if we need to append a measure
if (startTick + element.durationTicks >= curScore.lastSegment.tick) {
cmd("append-measure");
}
curScore.selection.clear();
curScore.selection.selectRange(startTick, startTick + element.durationTicks, staffIdx, staffIdx + 1);
selectionState = {
startStaff: staffIdx,
endStaff: staffIdx + 1,
startTick: startTick,
elements: [element],
totalDuration: element.durationTicks
};
return { success: true, currentSelection: selectionState };
} else {
return { success: false, message: "End of score reached" };
}
});
}
function prevElement(params) {
return executeWithUndo(function() {
syncStateToSelection();
var cursor = createCursor({
startTick: selectionState.startTick,
startStaff: selectionState.startStaff
});
var endTick = cursor.tick;
var numElements = params && params.numElements || 1;
var success = true;
for (var i = 0; i < numElements && success; i++) {
success = cursor.prev();
}
if (success) {
var element = processElement(cursor.element);
var startTick = cursor.tick;
var staffIdx = cursor.staffIdx;
curScore.selection.clear();
curScore.selection.selectRange(startTick, endTick, staffIdx, staffIdx + 1);
selectionState = {
startStaff: staffIdx,
endStaff: staffIdx + 1,
startTick: startTick,
elements: [element],
totalDuration: endTick - startTick
};
return { success: true, currentSelection: selectionState };
} else {
return { success: false, message: "Beginning of score reached" };
}
});
}
function nextStaff(params) {
return executeWithUndo(function() {
syncStateToSelection();
if (selectionState.endStaff >= curScore.nstaves) {
return { success: false, message: "Already at last staff" };
}
var newStaff = selectionState.endStaff;
var cursor = createCursor({
startTick: selectionState.startTick,
startStaff: newStaff
});
var element = processElement(cursor.element);
curScore.selection.clear();
curScore.selection.selectRange(
selectionState.startTick,
selectionState.startTick + element.durationTicks,
newStaff,
newStaff + 1
);
selectionState = {
startStaff: newStaff,
endStaff: newStaff + 1,
startTick: selectionState.startTick,
elements: [element],
totalDuration: element.durationTicks
};
return { success: true, currentSelection: selectionState };
});
}
function prevStaff(params) {
return executeWithUndo(function() {
syncStateToSelection();
if (selectionState.startStaff <= 0) {
return { success: false, message: "Already at first staff" };
}
var newStaff = selectionState.startStaff - 1;
var cursor = createCursor({
startTick: selectionState.startTick,
startStaff: newStaff
});
var element = processElement(cursor.element);
curScore.selection.clear();
curScore.selection.selectRange(
selectionState.startTick,
selectionState.startTick + element.durationTicks,
newStaff,
newStaff + 1
);
selectionState = {
startStaff: newStaff,
endStaff: newStaff + 1,
startTick: selectionState.startTick,
elements: [element],
totalDuration: element.durationTicks
};
return { success: true, currentSelection: selectionState };
});
}
function goToFinalMeasure(params) {
return executeWithUndo(function() {
var cursor = createCursor({ startTick: 0 });
var count = 0;
var startTick = 0;
while (cursor.nextMeasure()) {
startTick = cursor.tick;
count++;
}
if (count === 0) {
return { success: false, message: "Already at the last measure" };
}
cursor.rewindToTick(startTick);
cursor.next();
var endTick = cursor.tick;
var staffIdx = cursor.staffIdx;
curScore.selection.clear();
curScore.selection.selectRange(startTick, endTick, staffIdx, staffIdx + 1);
selectionState = {
startStaff: staffIdx,
endStaff: staffIdx + 1,
startTick: startTick,
elements: [processElement(cursor.element)],
totalDuration: endTick - startTick
};
return { success: true, currentSelection: selectionState };
});
}
// ========================================
// SELECTION FUNCTIONS
// ========================================
function selectCurrentMeasure() {
return executeWithUndo(function() {
var cursor = createCursor({
startTick: selectionState.startTick || 0,
startStaff: selectionState.startStaff || 0
});
var currTick = cursor.tick;
var scoreSummary = getScoreSummary();
var measureIdx = scoreSummary.measures.filter(function(m) {
return m.startTick <= currTick;
}).length - 1;
if (measureIdx < 0) return { error: "Invalid cursor position" };
var measure = scoreSummary.measures[measureIdx];
var startTick = measure.startTick;
var endTick = (measureIdx + 1 < scoreSummary.measures.length) ? scoreSummary.measures[measureIdx + 1].startTick : curScore.lastSegment.tick;
curScore.selection.clear();
curScore.selection.selectRange(startTick, endTick, 0, curScore.nstaves);
var res = syncStateToSelection();
if (res.error) return res;
return { success: true, message: `Selected measure ${measureIdx + 1}`, currentSelection: selectionState };
});
}
function selectCustomRange(params) {
var validation = validateParams(params, ["startTick", "endTick", "startStaff", "endStaff"]);
if (!validation.valid) return validation;
return executeWithUndo(function() {
var startTick = params.startTick;
var endTick = params.endTick;
var startStaff = params.startStaff;
var endStaff = params.endStaff;
// Visual GUI snap
curScore.selection.clear();
curScore.selection.selectRange(startTick, endTick, startStaff, endStaff);
var elementsMap = {};
for (var st = startStaff; st <= endStaff; st++) {
elementsMap[`staff${st}`] = [];
}
var c = createCursor({ startTick: 0, startStaff: startStaff });
c.rewind(0);
var currentSegment = c.segment;
while (currentSegment && currentSegment.tick < startTick) {
currentSegment = currentSegment.next;
}
while (currentSegment && currentSegment.tick < endTick) {
for (var s = startStaff; s <= endStaff; s++) {
for (var v = 0; v < 4; v++) {
var track = s * 4 + v;
var el = currentSegment.elementAt(track);
if (el) {
var processed = processElement(el);
if (processed) {
processed.voice = v;
processed.startTick = currentSegment.tick;
elementsMap[`staff${s}`].push(processed);
}
}
}
}
currentSegment = currentSegment.next;
}
selectionState = {
startStaff: startStaff,
endStaff: endStaff,
startTick: startTick,
elements: elementsMap,
totalDuration: endTick - startTick
};
return { success: true, message: "Custom range mapped", currentSelection: selectionState };
});
}
// ========================================
// NOTE & MUSIC OPERATIONS
// ========================================
function addNote(params) {
var validation = validateParams(params, ["pitch", "duration", "advanceCursorAfterAction"]);
if (!validation.valid) return validation;
if (!params.duration.numerator || !params.duration.denominator) {
return { error: "Duration must be specified as { numerator: int, denominator: int }" };
}
return executeWithUndo(function() {
syncStateToSelection();
var cursor = createCursor();
cursor.setDuration(params.duration.numerator, params.duration.denominator);
// Check if current position has a rest
var hasRest = selectionState.elements.some(function(element) {
return element.name === "Rest";
});
cursor.addNote(params.pitch, !hasRest);
cursor.rewindToTick(selectionState.startTick);
if (params.advanceCursorAfterAction) {
cursor.next();
}
var element = processElement(cursor.element);
var startTick = cursor.tick;
var staffIdx = cursor.staffIdx;
curScore.selection.clear();
curScore.selection.selectRange(startTick, startTick + element.durationTicks, staffIdx, staffIdx + 1);
selectionState = {
startStaff: staffIdx,
endStaff: staffIdx + 1,
startTick: startTick,
elements: [element],
totalDuration: element.durationTicks
};
return {
success: true,
message: "Note added with pitch " + params.pitch,
currentSelection: selectionState
};
});
}
function addRest(params) {
var validation = validateParams(params, ["duration", "advanceCursorAfterAction"]);
if (!validation.valid) return validation;
if (!params.duration.numerator || !params.duration.denominator) {
return { error: "Duration must be specified as { numerator: int, denominator: int }" };
}
return executeWithUndo(function() {
syncStateToSelection();
var cursor = createCursor();
cursor.setDuration(params.duration.numerator, params.duration.denominator);
cursor.addRest();
cursor.rewindToTick(selectionState.startTick);
if (params.advanceCursorAfterAction) {
cursor.next();
}
var element = processElement(cursor.element);
var startTick = cursor.tick;
var staffIdx = cursor.staffIdx;
curScore.selection.clear();
curScore.selection.selectRange(startTick, startTick + element.durationTicks, staffIdx, staffIdx + 1);
selectionState = {
startStaff: staffIdx,
endStaff: staffIdx + 1,
startTick: startTick,
elements: [element],
totalDuration: element.durationTicks
};
return { success: true, message: "Rest added", currentSelection: selectionState };
});
}
function addTuplet(params) {
var validation = validateParams(params, ["ratio", "duration", "advanceCursorAfterAction"]);
if (!validation.valid) return validation;
if (!params.ratio.numerator || !params.ratio.denominator ||
!params.duration.numerator || !params.duration.denominator) {
return { error: "Ratio and duration must be specified as { numerator: int, denominator: int }" };
}
return executeWithUndo(function() {
var cursor = createCursor();
cursor.setDuration(params.duration.numerator, params.duration.denominator);
var ratio = fraction(params.ratio.numerator, params.ratio.denominator);
var duration = fraction(params.duration.numerator, params.duration.denominator);
cursor.addTuplet(ratio, duration);
cursor.next();
if (params.advanceCursorAfterAction) {
cursor.next();
}
var element = processElement(cursor.element);
var startTick = cursor.tick;
var staffIdx = cursor.staffIdx;
selectionState = {
startStaff: staffIdx,
endStaff: staffIdx + 1,
startTick: startTick,
elements: [element],
totalDuration: element.durationTicks
};
return {
success: true,
message: "Tuplet " + params.ratio.numerator + ":" + params.ratio.denominator + " added",
currentSelection: selectionState
};
});
}
function addLyrics(params) {
if (!params.lyrics || !Array.isArray(params.lyrics) || params.lyrics.length === 0) {
return { error: "Lyrics must be specified as an array of strings" };
}
return executeWithUndo(function() {
syncStateToSelection();
var cursor = createCursor({
startTick: selectionState.startTick,
startStaff: selectionState.startStaff
});
var lyricsArray = params.lyrics.slice();
var verse = params.verse || 0;
var addedCount = 0;
var skippedCount = 0;
while (cursor.element && lyricsArray.length > 0) {
var element = cursor.element;
if (element.type === Element.CHORD || element.name === "Chord") {
var lyr = newElement(Element.LYRICS);
lyr.text = lyricsArray.shift();
lyr.verse = verse;
cursor.add(lyr);
addedCount++;
} else if (element.type === Element.REST || element.name === "Rest") {
skippedCount++;
}
if (!cursor.next()) break;
}
var finalElement = processElement(cursor.element) || selectionState.elements[0];
var finalTick = cursor.tick;
var staffIdx = cursor.staffIdx;
selectionState = {
startStaff: staffIdx,
endStaff: staffIdx + 1,
startTick: finalTick,
elements: [finalElement],
totalDuration: finalElement.durationTicks || selectionState.totalDuration
};
curScore.selection.clear();
curScore.selection.selectRange(finalTick, finalTick + (finalElement.durationTicks || 0), staffIdx, staffIdx + 1);
var message = `Added ${addedCount} lyrics`;
if (skippedCount > 0) message += `, skipped ${skippedCount} rests`;
if (lyricsArray.length > 0) message += `, ${lyricsArray.length} lyrics remaining`;
return {
success: true,
message: message,
addedCount: addedCount,
skippedCount: skippedCount,
remainingLyrics: lyricsArray,
currentSelection: selectionState
};
});
}
// ========================================
// MEASURE OPERATIONS
// ========================================
function appendMeasure(params) {
return executeWithUndo(function() {
var count = params && params.count || 1;
for (var i = 0; i < count; i++) {
cmd("append-measure");
}
return {
success: true,
message: count + " measure(s) appended",
currentSelection: selectionState
};
});
}
function insertMeasure(params) {
return executeWithUndo(function() {
cmd("insert-measure");
syncStateToSelection();
return {
success: true,
message: "Measure inserted",
currentSelection: selectionState
};
});
}
function deleteSelection(params) {
return executeWithUndo(function() {
if (params && params.measure) {
createCursor({ measure: params.measure });
}
cmd("delete");
return {
success: true,
message: "Selection deleted",
currentSelection: selectionState
};
});
}
// ========================================
// STAFF & INSTRUMENT OPERATIONS
// ========================================
function addInstrument(params) {
var validation = validateParams(params, ["instrumentId"]);
if (!validation.valid) return validation;
return executeWithUndo(function() {
curScore.appendPart(params.instrumentId);
return { success: true, message: "Instrument " + params.instrumentId + " added" };
});
}
function setStaffMute(params) {
var validation = validateParams(params, ["staff"]);
if (!validation.valid) return validation;
return executeWithUndo(function() {
var staff = curScore.staves && curScore.staves[params.staff] ||
(typeof curScore.staff === "function" ? curScore.staff(params.staff) : null);
if (staff) {
staff.invisible = Boolean(params.mute);