-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlyricsHelper.qml
2334 lines (2276 loc) · 111 KB
/
lyricsHelper.qml
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
//==============================================
// Lyrics Helper
// Copyright (©) 2021 Snake4Y5H
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2
// as published by the Free Software Foundation and appearing in
// the file LICENCE.GPL
//==============================================
import QtQuick 2.9
import QtQuick.Dialogs 1.2
import QtQuick.Controls 2.2
import QtQml 2.2
import MuseScore 3.0
import FileIO 3.0
import Qt.labs.folderlistmodel 2.2
import "zparkingb/selectionhelper.js" as SelHelper
MuseScore
{
menuPath: "Plugins.Lyrics Helper"
version: "3.0"
description: qsTr("A plugin intends to help input lyrics. It is designed for East Asian languages (monosyllabic languages like Sino-Tibetian languages) but also work for other language texts with workarounds.\nGithub Page: https://github.com/SnakeAmadeus/lyricsHelper\nby Snake4y5h")
pluginType: "dock"
dockArea: "Right"
implicitHeight: controls.implicitHeight * 1.5
implicitWidth: controls.implicitWidth
//@replaceMode indicates whether replacing the existed lyrics when encountering a lyrics conflict. default = true
property alias replaceMode : replaceModeCheckBox.checked;
//@previewSoundMode decides whether preview note's sound when cursor advances. default = true
property alias previewSoundMode: previewSoundModeCheckBox.checked;
//@maximumUndoStep decides the max amount of actions that is done by lyricsHelper can be undone. default = 50
property alias maximumUndoSteps: maximumUndoStepsSpinBox.value;
//@skipTiedNotesMode decides whether the cursor advancing while inputing lyrics treat tied notes as one note or multiple notes. default = false
property alias skipTiedNotesMode: skipTiedNotesModeCheckBox.checked;
property var lrc: String("");
property var lrcCursor: [0];
//helper toString() function for @lrcCursor
function lrcCursorToString(c) {if(c.length == 1) return c[0]; else return c[0] + "-" + c[1];}
//helper parse() function that parses the string format of toString()
function lrcCursorParse(c) {if(c.split('-').length == 1) return [parseInt(c)]; else return [parseInt(c.split('-')[0]),parseInt(c.split('-')[1])];}
//helper clone() that clones a copy of lrcCursor
function lrcCursorClone(c) {return c.slice();}
//@ptSize is the alias of currently displayed lyrics' font point size
property alias ptSize: lrcDisplay.font.pointSize;
//@hyphenatedMode decides whether the single unit of lyrics selection is between whitespaces or (whitespaces and hyphens.) default = false
property alias hyphenatedMode: hyphenatedModeToggle.checked;
property var separator: [' '];
function isSeparator(s) {for(var i = 0; i < separator.length; i++) {if (s == separator[i]) return i.toString();} return false;}
//decides which line of lyrics is going to input.
property var lyricsLineNum: 0;
property var isFirstRun: true;
onRun: {}
FileIO
{
id: myFileLyrics
onError: console.log("Failed to read lyrics file: " + myFileLyrics.source);
}
FileDialog
{
id: openLrcDialog
title: qsTr("Please choose a .txt or .lrc file")
nameFilters: ["lyrics files (*.txt *.lrc)"]
onAccepted:
{
var filename = openLrcDialog.fileUrl;
acceptFile(filename);
}
}
FileDialog
{
id: lrcExportDialog
function saveFile(fileUrl, text)
{
var request = new XMLHttpRequest();
request.open("PUT", fileUrl, false);
request.send(text);
return request.status;
}
function getPath(fileUrl) {
for(var i = fileUrl.length - 1; i >= 0 ;i--) {if(fileUrl.charAt(i) == '/') return fileUrl.substring(0,i);}}
title: qsTr("Save As...")
nameFilters: ["lyrics files (*.txt *.lrc)"]
selectExisting: false
onAccepted: saveFile(lrcExportDialog.fileUrl, lrcEdit.text);
}
function acceptFile(filename) //helper function that reads a file for widget openLrcDialog and fileDrop
{
if(filename)
{
//console.log("You chose: " + filename)
myFileLyrics.source = filename;
//behaviors after reading the text file
lyricSource.text = qsTr("Current File: ") + myFileLyrics.source.slice(8); //trim path name for better view
lyricSource.horizontalAlignment = Text.AlignLeft;
acceptLyrics(myFileLyrics.read());
//for japaneseToKana backup its before converting lyrics
if(japaneseToKana.hasJapanese(lrc)) japaneseToKana.lrcBackup = lrc;
}
}
property var lrcOriginalCopy: "";
function acceptLyrics(text)
{
//update lyrics text to the display:
lrc = text.replace(/ +/g, ' ');
lrcDisplay.wrap();
lrcDisplay.width = lrcDisplayScrollView.width;
if(lrcCursor.length == 1) lrcCursor = [0]; else {lrcCursor = [0,1]; expandCharToWord(0);}//reset @lrcCursor
prevChar(); nextChar(); //forcefully skip all the whitespaces in the file head.
inputButtons.enabled = true; //recover input buttons' availability
texteditButtons.enableLrcDisplay();
//check the language of lyrics, see if they are convertable in specific language.
hyphenation.enabled = hyphenation.hasLatinAlphabet(lrc);
hyphenation.text = hyphenation.enabled ? hyphenation.deafultText : hyphenation.langNotFoundText;
japaneseToKana.enabled = japaneseToKana.hasJapanese(lrc);
japaneseToKana.text = japaneseToKana.enabled ? japaneseToKana.deafultText : japaneseToKana.langNotFoundText;
//if its plugin's first run, prompt user how to adjust lyics verse lines
if(isFirstRun)
{
lyricsLineNumIndicatorGrid.visible = true;
lyricsLineNumIndicator.tooltip = qsTr(" (Scroll Mouse Here to Adjust)")
lyricsLineNumIndicator.downArrow = "▼ "; lyricsLineNumIndicator.upArrow = " ▲";
lyricsLineNumAdjust.updateLyricsLineDisplay();
lyricsLineNumScroll.enabled = true; lyricsLineNumAdjust.enabled = true;
lyricsLineNumIndicatorPrompt.start();
isFirstRun = false;
}
//clean vertical increment cache
lrcDisplay.displayPositionMapCache = {};
getDisplayPositionMap();
//clean undo stack
undo_stack = [];
updateDisplay();
}
//Functionality: click on lyricSource to auto load a text file to the lyricsHelper
//that contains the current score's name, in the same path as the current score
property var curScorePath : "";
property var curScoreFileName : "";
property var curScoreName : "";
function autoLoadLyrics()
{
var scorePath = curScore.path.replace(/\\/g, '/');
if(scorePath.charAt(0) == '/') scorePath = scorePath.substring(1);
myFileScore.source = "file:///" + scorePath; //in some MuseScore's languages context, the os.sep is \ instead of / idk why
console.log("autoLoadLyrics(): Current Score is: " + myFileScore.source);
curScoreFileName = myFileScore.source.split('/').pop();
curScorePath = myFileScore.source.slice(0,myFileScore.source.lastIndexOf(curScoreFileName));
curScoreName = curScoreFileName.split('.')[0];
searchTxtFolderListModel.folder = curScorePath;
curScorePath = curScorePath.slice(8);
lyricSource.horizontalAlignment = Text.AlignHCenter;
lyricSource.text = qsTr("Auto Loading Lyrics...");
searchTxtDelayRunning.start();
}
FileIO //FileIO stores the path of the current score
{
id: myFileScore
onError: console.log("Failed to read Score: " + myFileScore.source);
}
FolderListModel //FolderListModel assists autoLoadLyrics() to search .txt files in the specified folder
{
id: searchTxtFolderListModel
property var tempLrcCursor : [];
function searchTxt()
{
tempLrcCursor = lrcCursor;
for(var i = 0; i < searchTxtFolderListModel.count; i++)
if(searchTxtFolderListModel.get(i, "fileName").split('.').pop() == "txt")
if (searchTxtFolderListModel.get(i, "fileName").toLowerCase().includes(curScoreName.toLowerCase())) //make it non-case-sensitive
{acceptFile(searchTxtFolderListModel.get(i, "fileURL")); return true;}
//in case nothing was found:
lyricSource.text = qsTr("Couldn't find any .txt file contains\nthe Current Score's name in the same path.");
autoReadLyricsFailedMessage.start();
}
}
//Functionality: Drag&Drop lyrics text file to the plugin
//workarounds for DropArea validates file extensions because the DropArea.keys were not functioning properly
//Reference: https://stackoverflow.com/a/28800328
MouseArea
{
anchors.fill: controls
hoverEnabled: true
enabled: !fileDrop.enabled
onContainsMouseChanged: fileDrop.enabled = true
}
DropArea
{
id: fileDrop
anchors.fill: controls
onEntered:
{
if(drag.urls.length == 1)
if(drag.urls[0].split('.').pop() == "txt")
return;
drag.accept();
fileDrop.enabled = false
}
onDropped:
{
var filename = Qt.resolvedUrl(drop.urls[0]);
acceptFile(filename);
}
}
function getSelectedTicks() //get ticks of current selected segements, modified from https://musescore.org/en/node/293025
{
var minpos = 2147483647;
var maxpos = 0;
var seen = 0;
var end = "";
if (curScore.selection && curScore.selection.elements &&
curScore.selection.elements.length) {
var elts = curScore.selection.elements;
//console.log("operating on selection: " + elts.length);
for (var idx = 0; idx < elts.length; ++idx) {
var e = elts[idx];
while (e) {
if (e.type == Element.SCORE) {
console.log("child of score");
} else if (e.type == Element.PAGE) {
console.log("child of page");
} else if (e.type == Element.SYSTEM) {
console.log("child of system");
} else if (e.type == Element.MEASURE) {
console.log("child of measure");
} else if (e.type != Element.SEGMENT) {
e = e.parent;
continue;
}
break;
}
if (!e || e.type != Element.SEGMENT) {
//console.log("#" + idx + " skipped, " + "no segment as parent");
continue;
}
//console.log("#" + idx + " at " + e.tick);
if (e.tick < seen) {
//console.log("below " + seen + ", ignoring");
continue;
}
seen = e.tick ? 1 : 0;
if (e.tick < minpos)
minpos = e.tick;
if (e.tick > maxpos)
maxpos = e.tick;
}
}
var cursor = curScore.newCursor();
cursor.rewind(Cursor.SELECTION_START);
if (cursor.segment) {
//console.log("operating on cursor at " + cursor.tick);
seen = cursor.tick ? 1 : 0;
if (cursor.tick < minpos)
minpos = cursor.tick;
if (cursor.tick > maxpos)
maxpos = cursor.tick;
cursor.rewind(Cursor.SELECTION_END);
if (!cursor.tick) {
/* until end of the score */
cursor.rewind(Cursor.SELECTION_START);
while (cursor.next())
/* nothing */;
end = " (end of score)";
console.log("EOS at " + cursor.tick);
} else
console.log("cursor until " + cursor.tick);
var csrmax = cursor.tick - 1;
if (csrmax > seen) {
if (csrmax < minpos)
minpos = csrmax;
if (csrmax > maxpos)
maxpos = csrmax;
}
}
if (minpos == 2147483647)
{
alert.text = "could not find position";
return;
}
else if (maxpos <= minpos)
return minpos + end;
else
{
alert.text = "from " + minpos + " to " + maxpos + end;
return;
}
alert.open();
}
function getSelectedCursor() //move the cursor to the ticks from getSelectedTicks() and check if user selections are wack
{
//First, get current selected note (Uses: https://github.com/lgvr123/musescore-durationeditor/blob/master/zparkingb/selectionhelper.js)
var selection = SelHelper.getNotesFromSelection();
console.log("getSelectedCursor(): Current Selection is " + nameElementType(selection));
//check if selection is empty or not a single note
if (!selection || (selection.length == 0))
{
console.log("getSelectedCursor(): You ain't select nothing");
return false;
}
//console.log(selection.length);
if (selection.length != 1)
{
console.log("getSelectedCursor(): Current Selection Must Be a Single Note!");
return false;
}
//extract the first element of the selection and move the cursor onto it.
var cursor = curScore.newCursor();
cursor.track = selection[0].track;
cursor.inputStateMode = 1;
cursor.rewindToTick(getSelectedTicks()); //move cursor's to the ticks of selection.
//console.log(cursor.tick);
return cursor;
}
//helper function that returns a string of currently selected lyrics
function getSelectedLyric() {if(lrcCursor.length == 1) return lrc.charAt(lrcCursor[0]); else return lrc.substring(lrcCursor[0],lrcCursor[1]);}
//helper function that returns the note's lyrics object at cursor's position with specified verse line. If not found @return false.
function getNoteLyrics(cursor, verseLine)
{
if(cursor.element.lyrics.length == 0) return false;
for(var i = 0; i < cursor.element.lyrics.length; i++)
if(cursor.element.lyrics[i].verse == verseLine) return cursor.element.lyrics[i];
return false;
}
//core function for the "Add Syllable" button
function addSyllable(cursor)
{
//fill in the lyrics
if(cursor)
{
console.log("-----------addSyllable() start----------");
//in order to prevent crashing and bugs, let's create a "probing" cursor first to detect EOF before adding the lyrics
var nextCursor = cursor; nextCursor.next();
if(nextCursor.element == null) //if reaches the score EOF
{
cursor = getSelectedCursor();
if(getNoteLyrics(cursor,lyricsLineNum)) //if there already been lyrcis on the next element, do nothing and deselect
{
console.log("addSyllable(): EOF detected, you can't add more lyrics");
curScore.selection.clear();
curScore.endCmd();
return false;
}
else //if no lyrics on the current note, add it but no future cursor is forwarded.
{
var character = getSelectedLyric();
var fill = newElement(Element.LYRICS);
fill.text = character;
fill.verse = lyricsLineNum;
curScore.startCmd();
console.log("addSyllable(): current character = " + fill.text);
cursor.element.add(fill);
addHyphen(cursor);
pushToUndoStack(cursor, "addSyllable()");
curScore.endCmd();
nextChar();
updateDisplay();
return true;
}
}
//if probing cursor passed the check, proceed to the main body of the function
var cursor = getSelectedCursor(); //if no EOF are found, override the probing cursor with the normal cursor
var character = getSelectedLyric();
var fill = newElement(Element.LYRICS);
fill.text = character;
fill.verse = lyricsLineNum;
//wrap the actions in startCmd() and endCmd() for real-time reactions from the score.
//Sepcial Thanks to Jojo-Schmitz https://musescore.org/en/node/326916
curScore.startCmd();
console.log("addSyllable(): current character = " + fill.text);
var tempTick = cursor.tick;
if(getNoteLyrics(cursor,lyricsLineNum)) //if replaceMode is ON, replace the existed character
{
console.log("addSyllable(): conflicted lyrics detected!");
if(replaceMode == 1)
{
removeElement(getNoteLyrics(cursor,lyricsLineNum));
}
else
{
curScore.endCmd();
return false;
}
}
if(isInsideMelismaLine(cursor)) //if replaceMode is ON, and selection is inside a melisma line, cut the line and add the character
{
console.log("addSyllable(): conflicted melisma line detected!");
if(replaceMode == 1)
{
var checkLength = 0;
do
{
cursor.prev();
checkLength += durationTo64(cursor.element.duration);
}while(durationTo64(getNoteLyrics(cursor,lyricsLineNum).lyricTicks) == 0)
getNoteLyrics(cursor,lyricsLineNum).lyricTicks = fraction(checkLength, 64);
}
else
{
curScore.endCmd();
return false;
}
}
cursor.rewindToTick(tempTick);
if((cursor.element.notes[0].tieBack != null || cursor.element.notes[0].tieForward != null) && skipTiedNotesMode) //if selected note is inside a tie, jump to the begining of the tie
{
curScore.selection.select(cursor.element.notes[0].firstTiedNote);
cursor = getSelectedCursor();
}
cursor.element.add(fill);
addHyphen(cursor);
pushToUndoStack(cursor, "addSyllable()");
cursor.next();
console.log("addSyllable(): Next Selection is " + nextCursor.element.type);
//if the next element is not a note
if(cursor.element.type != 93)
{
var exceptionType = cursor.element.type;
if(exceptionType == 25) //if the next element is a rest.
{
while(cursor.element.type != 93) // wind forward until detecting a valid note
{
cursor.next();
console.log("addSyllable(): Rest detected, move to next selection: " + nameElementType(cursor.element) + " at " + cursor.tick);
if(cursor.element == null)
{
console.log("addSyllable(): EOF detected, close the lyrics input process");
cursor.rewindToTick(tempTick);//corner case: tail of score are rests:
if(getNoteLyrics(cursor,lyricsLineNum)) removeElement(getNoteLyrics(cursor,lyricsLineNum));
curScore.selection.clear();
curScore.endCmd();
return false;//encounters the EOF, immediately shut down
}
}
}
}
var nextNote = cursor.element.notes[0];
//if the next note is a tied note
if((nextNote.tieBack != null) && skipTiedNotesMode)
{
curScore.selection.select(nextNote.lastTiedNote);
console.log("addSyllable(): Tied Note detected, move to tied note's tail at " + cursor.tick);
cursor.next();
if(cursor.element == null)//corner case: the element after the tail of the tied note is score EOF, deselect and shut down.
{
console.log("addSyllable(): EOF detected, you can't add more lyrics");
curScore.selection.clear();
curScore.endCmd();
return false;
}
if(cursor.element.type != 93) //corner case: the element after the tail of the tied note is a rest
{
var exceptionType = cursor.element.type;
if(exceptionType == 25) //if the next element is a rest.
{
while(cursor.element.type != 93) // wind forward until detecting a valid note
{
cursor.next();
console.log("addSyllable(): Rest detected, move to next selection: " + nameElementType(cursor.element) + " at " + cursor.tick);
if(nextCursor.element == null)
{
console.log("addSyllable(): EOF detected, close the lyrics input process");
//corner corner case = = : after-tail of tied notes's elements are rests and also extend to the EOF:
curScore.selection.clear();
curScore.endCmd();
return false;//encounters the EOF, immediately shut down
}
}
}
}
}
curScore.selection.select(cursor.element.notes[0]);//move selection to the next note
if (previewSoundMode == 1) playCursor(cursor);
curScore.endCmd();
//move the lyrics cursor to the next character
nextChar();
updateDisplay();
console.log("------------addSyllable() end-------------");
return true;
}
}
//core function for the "Extend Melisma" button
function addMelisma(cursor)
{
if(cursor)
{
console.log("-----------addMelisma() start----------");
//MuseScore's Lyrics' Melisma was manipulated by the lyrics.lyricTicks property, which is a property of Ms::PluginAPI::Element
//Because the lyrics Object was wrapped in Ms::PluginAPI::Element, so the cursor.element.lyrics's type is actually Ms::PluginAPI::Element, instead of a lyrics object
//There is no direct access to the object of Lyrics' members as shown in the libmscore/lyrics.h
//The definition of this lyrics.lyricTicks is the sum of note values from *begining* of the first note to the *begining* of the last note.
//So the calculation rule of the length of Melisma line will be from the selected note to the last note that has lyrics under it.
//Move the cursor backward, Add up the note value of [start note, end note); if rests are other wack occurred, abort the operation.
var tempTick = cursor.tick; //backup cursor's original position
var melismaLength = 0;
//things need to be checked for the current selected note to avoid glitches
//if the skipTiedNotesMode is ON, then:
//check if the selected note is in the middle of the tie that has lyric on the first tied note, give users the option to decide whether treat tied notes as one note or not
if((cursor.element.notes[0].tieBack != null || cursor.element.notes[0].tieForward != null) && skipTiedNotesMode)
{
curScore.selection.select(cursor.element.notes[0].firstTiedNote);
cursor = getSelectedCursor();
if(getNoteLyrics(cursor,lyricsLineNum))
{
console.log("addMelisma(): Middle of the tie detected, do nothing");
cursor.rewindToTick(tempTick);
curScore.selection.select(cursor.element.notes[0]);
return false;
}
cursor.rewindToTick(tempTick);
curScore.selection.select(cursor.element.notes[0]);
}
//check if the current note already has lyrics, it will cause conflicts in this case
if(getNoteLyrics(cursor,lyricsLineNum))
{
if(replaceMode == 1)//depends on whether replace mode is ON or OFF. If ON, current lyrics will be dropped and become melisma line
{
console.log("addMelisma(): Lyrics conflict detected, drop existed lyrics");
removeElement(getNoteLyrics(cursor,lyricsLineNum));
}
else
{
console.log("addMelisma(): Lyrics conflict detected, do nothing"); return false;
}
}
//other things need to be checked for the prev note to avoid glitches
cursor.prev();
if(cursor.element == null) //check if reach the filehead
{
console.log("addMelisma(): Filehead detected, do nothing"); return false;
}
if(cursor.element.type == 25) //if the prev element is a rest.
{
console.log("addMelisma(): Rest detected, do nothing"); return false;
}
cursor.next(); //finish checking
//Start searching for the last note that has lyrics
do
{
cursor.prev();
if(cursor.element == null) //check if reach the filehead
{
console.log("addMelisma(): Filehead detected, do nothing"); return false;
}
if(cursor.element.type == 25) //if the prev element is a rest.
{
console.log("addMelisma(): Rest detected, do nothing"); return false;
}
melismaLength += durationTo64(cursor.element.duration);//duration to 64 for more convenient calculation
} while(!getNoteLyrics(cursor,lyricsLineNum))
melismaLength = fraction(melismaLength, 64); //64 to duration
curScore.startCmd();
getNoteLyrics(cursor,lyricsLineNum).lyricTicks = melismaLength;
console.log("addMelisma(): Final Melisma Length: " + getNoteLyrics(cursor,lyricsLineNum).lyricTicks.str);
cursor.rewindToTick(tempTick);
cursor.next();
//if reaches the score EOF
if(cursor.element == null)
{
console.log("addMelisma(): EOF detected, close the lyrics input process");
curScore.selection.clear();
curScore.endCmd();
return false;
}
//if the next element is not a note
if(cursor.element.type == 25) //if the next element is a rest.
{
while(cursor.element.type != 93) // wind forward until detecting a valid note
{
cursor.next();
console.log("addMelisma(): Rest detected, move to next selection: " + nameElementType(cursor.element) + " at " + cursor.tick);
if(cursor.element == null)
{
console.log("addMelisma(): EOF detected, close the lyrics input process");
cursor.rewindToTick(tempTick);//corner case: tail of score are rests:
curScore.selection.clear();
curScore.endCmd();
return false;//encounters the EOF, immediately shut down
}
}
}
curScore.selection.select(cursor.element.notes[0]);//move selection to the next note
if (previewSoundMode == 1) playCursor(cursor);
curScore.endCmd();
console.log("------------addMelisma() end-------------");
return true;
}
}
//core function for the "Concatenate Synalepha" button
function addSynalepha(cursor)
{
if (cursor)
{
var tempTick = cursor.tick;
var character = getSelectedLyric();
//if current notes has lyrics already, concatenate the character to the original one right away.
if(getNoteLyrics(cursor,lyricsLineNum))
{
curScore.startCmd();
console.log("addSynalepha(): character to be added: " + character);
var concatenated = getNoteLyrics(cursor,lyricsLineNum).text + character;
getNoteLyrics(cursor,lyricsLineNum).text = concatenated;
nextChar();
updateDisplay();
pushToUndoStack(cursor, "addSynalepha()");
curScore.endCmd();
return true;
}
//in the case of current selected note has no lyrics but the pervious has lyrics (MOST LIKELY it's in the middle of the editing),
//add Synalepha to the previous character
if(!getNoteLyrics(cursor,lyricsLineNum))
{
do
{
cursor.prev();
if(cursor.element == null) //check if reach the filehead, dump the character to the original selection
{
console.log("addSynalepha(): Filehead detected, dump character " + character + " to the original selected note");
curScore.startCmd();
var fill = newElement(Element.LYRICS);
fill.text = character;
fill.voice = cursor.voice;
cursor.rewindToTick(tempTick);
cursor.element.add(fill);
pushToUndoStack(cursor, "addSynalepha()");
nextChar();
updateDisplay();
curScore.endCmd();
return true;
}
} while(cursor.element.type != 93) //if no notes were found before the selection, cursor will eventually reach the filehead.
//assume we found a note
if(getNoteLyrics(cursor,lyricsLineNum))
{
curScore.startCmd();
console.log("addSynalepha(): character to be added: " + character);
var concatenated = getNoteLyrics(cursor,lyricsLineNum).text + character;
getNoteLyrics(cursor,lyricsLineNum).text = concatenated;
pushToUndoStack(cursor, "addSynalepha()");
nextChar();
updateDisplay();
curScore.endCmd();
return true;
}
else //if we found a note but that note has no lyrics ()
{
var tempTick2 = cursor.tick; //backup cursor's position before calling isInsideMelismaLine(cursor)
//if that note has no lyrics but inside a melisma line, dump the character to the begining of the melisma line
if(isInsideMelismaLine(cursor))
{
while(durationTo64(getNoteLyrics(cursor,lyricsLineNum).lyricTicks) == 0) {cursor.prev();}
curScore.startCmd();
console.log("addSynalepha(): Note inside a melisma line detected, character to be added at the begining of melisma line: " + character);
var concatenated = getNoteLyrics(cursor,lyricsLineNum).text + character;
getNoteLyrics(cursor,lyricsLineNum).text = concatenated;
pushToUndoStack(cursor, "addSynalepha()");
nextChar();
updateDisplay();
curScore.endCmd();
return true;
}
//if that note is inside a tied note, dump the character to the begining of the tie
cursor.rewindToTick(tempTick2);
if((cursor.element.notes[0].tieBack != null || cursor.element.notes[0].tieForward != null) && skipTiedNotesMode)
{
curScore.startCmd();
curScore.selection.select(cursor.element.notes[0].firstTiedNote);
cursor = getSelectedCursor();
if(!getNoteLyrics(cursor,lyricsLineNum))
{
console.log("addSynalepha(): Note inside a tie detected, character to be dumped at the begining of the tie: " + character);
var fill = newElement(Element.LYRICS);
fill.text = character;
fill.voice = cursor.voice;
cursor.element.add(fill);
}
else
{
console.log("addSynalepha(): Note inside a tie detected, character to be added at the begining of the tie: " + character);
var concatenated = getNoteLyrics(cursor,lyricsLineNum).text + character;
getNoteLyrics(cursor,lyricsLineNum).text = concatenated;
}
nextChar();
updateDisplay();
cursor.rewindToTick(tempTick);
curScore.selection.select(cursor.element.notes[0]);
pushToUndoStack(cursor, "addSynalepha()");
curScore.endCmd();
return true;
}
//if that note is neither inside melisma line nor inside a tie, dump the character to the original selection
console.log("addSynalepha(): Prev note is neither inside melisma line nor inside a tie, dump " + character + " to the original selected note");
curScore.startCmd();
var fill = newElement(Element.LYRICS);
fill.text = character;
fill.voice = cursor.voice;
cursor.rewindToTick(tempTick);
cursor.element.add(fill);
nextChar();
updateDisplay();
pushToUndoStack(cursor, "addSynalepha()");
curScore.endCmd();
return true;
}
}
}
}
//core function for "hyphenated mode". The way that MuseScore's lyrics hyphens work is by the element.lyrics[0].syllabic property.
//start syllable of a hyphenated word, syllabic = 1
//middle syllable of a hyphenated word, syllabic = 3
//end syllable of a hyphenated word, syllabic = 2
//for example, the word Sep-tem-ber, the syllabic number of "Sep" will be 1, "tem" will be 3, "ber" will be 2
function addHyphen(cursor)
{
function findhyphenationNum()
{
if(lrcCursor[1] >= lrc.length - 1) return 0;
if(lrcCursor[0] == 0)
{
if(lrc.charAt(lrcCursor[1]) == '-') return 1;
else return 0;
}
var leftBound = lrc.charAt(lrcCursor[0] - 1);
var rightBound = lrc.charAt(lrcCursor[1]);
if(((leftBound == ' ') || (leftBound == '\n')) && (rightBound == '-')) return 1;
if((leftBound == '-') && (rightBound == '-')) return 3;
if((leftBound == '-') && ((rightBound == ' ') || (rightBound == '\n'))) return 2;
return 0;
}
if((lrcCursor.length == 2) && cursor)
{
var hyphenationNum = findhyphenationNum();
getNoteLyrics(cursor,lyricsLineNum).syllabic = hyphenationNum;
}
}
//helper function, check if a note is inside a melisma line
function isInsideMelismaLine(cursor)
{
var checkLength = 0;
do
{
cursor.prev();
if(cursor.element == null) return false;
if(cursor.element.type != 93) return false;
checkLength += durationTo64(cursor.element.duration);
} while(!getNoteLyrics(cursor,lyricsLineNum))
var melismaLength = durationTo64(getNoteLyrics(cursor,lyricsLineNum).lyricTicks)
if(melismaLength == 0) return false;
if(melismaLength < checkLength) return false;
return true;
}
function playCursor(cursor) //plays the note's sound at cursor, Special Thanks to Sammik's idea of using cmd("prev-chord") & cmd("next-chord") as workarounds : https://musescore.org/en/node/327715
{
cursor.prev();
if(cursor.element == null) //if cursor is at the first note of the score
{
cmd("prev-chord");
cursor.next(); //restores cursor's position
return;
}
if(cursor.element.type != 93) // if previous element is a rest
{
cmd("prev-chord");
cmd("next-chord");
cursor.next();
return;
}
//if previous element is a note, in order to prevent playing the sound of previous note, use cursor to select that note.
curScore.selection.select(cursor.element.notes[0]);
cmd("next-chord");
cursor.next();
return;
}
function durationTo64(duration) { return 64 * duration.numerator / duration.denominator;} //helper function for converting duration to 64 for addMelisma()
function convertLineBreak(x) { return x.replace(/\n/g, "<br />"); } //special thanks to @Jack-Works for wrapping linebreaks in HTML
function convertWhiteSpace(x) { return x.replace(/\s/g, " "); } //convert whitespaces in HTML
function lrcCursorToWrappedLrcCursor(c)
{
const wlrc = lrcDisplay.wrappedText;
//i1: the lrcCursor in lrc; i2: the lrcCursor in lrcDisplay.wrappedText (wlrc)
//n1: num of non-'\n' chars from lrc.substring(0, i1 + 1); n2: num of non-'\n' chars from wlrc.substring(0, i1 + 1)
const i1 = c;
const isLrcCursorRightBound = (lrc.charAt(i1) == '\n'); //if lrc.charAt(i1) is a linebreak, it has to be the right boundary of lrcCursor range selection (lrcCursor[1])
if(isLrcCursorRightBound) while(lrc.charAt(i1) == '\n' && i1 > 0) i1 -= 1; //snap i1 to the nearest char first
var i2 = i1;
while (wlrc.charAt(i2) == '\n' && i2 < wlrc.length) i2 += 1; //skip the lrcCursor in @wlrc to the nearest non-'\n' char
const n1 = lrc.substring(0, i1 + 1).replace(/\n/g,"").length;
var n2 = wlrc.substring(0, i2 + 1).replace(/\n/g,"").length;
while(i2 < wlrc.length /*prevent dead loops*/ && (n2 < n1))
{
i2 += 1;
if(wlrc.charAt(i2) != '\n') n2 += 1;
}
//if lrc.charAt(i1) is '\n', then wlrc.charAt(i2) has to be '\n' in order to let display include the char at L-boundary
if(isLrcCursorRightBound) while(wlrc.charAt(i2) != '\n' && i2 < wlrc.length) i2 += 1;
return i2;
}
function wrappedLrcCursorToLrcCursor(c)
{ //reversed logic of lrcCursorToWrappedLrcCursor(c)
const wlrc = lrcDisplay.wrappedText;
const i2 = c;
var i1 = (i2 > lrc.length) ? lrc.length - 1 : i2;
while (lrc.charAt(i1) == '\n' && i1 > 0) i1 -= 1; //skip the lrcCursor in @lrc to the nearest non-'\n' char
const n2 = wlrc.substring(0, i2 + 1).replace(/\n/g,"").length;
var n1 = lrc.substring(0, i1 + 1).replace(/\n/g,"").length;
while(i1 > 0 /*prevent dead loops*/ && n1 > n2)
{
if(lrc.charAt(i1) != '\n') n1 -= 1;
i1 -= 1;
}
while(lrc.charAt(i1) == '\n' && i1 > 0) i1 -= 1;
return i1;
}
function updateDisplay() //update display to lrcDisplay.text
{
if(isOnlyContainsSeparator()) {lrcDisplay.text = qsTr("Error: your lyrics file only contains\nwhitespaces or separators like \'-\'!"); return false;}
var temp = [lrcCursor];
if(lrcCursor.length == 1) lrcCursor = [lrcCursorToWrappedLrcCursor(lrcCursor[0])];
else if(lrcCursor.length == 2) lrcCursor = [lrcCursorToWrappedLrcCursor(lrcCursor[0]), lrcCursorToWrappedLrcCursor(lrcCursor[1])];
const wlrc = lrcDisplay.wrappedText;
if(lrcCursor.length == 1) //if the selected text is single char (normal case)
{
if(lrcCursor[0] == 0)
{
lrcDisplay.text = convertLineBreak("<b>" + wlrc.slice(0,1) + "</b>" + "<font color=\"grey\">" + wlrc.slice(1) + "</font>");
}
else if(lrcCursor[0] == wlrc.length - 1)
{
lrcDisplay.text = convertLineBreak("<font color=\"grey\">" + wlrc.slice(0, lrcCursor[0]) + "</font>" + "<b>" + wlrc.slice(lrcCursor[0]) + "</b>");
}
else
{
lrcDisplay.text = convertLineBreak("<font color=\"grey\">" + wlrc.slice(0,lrcCursor[0]) + "</font>" + "<b>" + wlrc.slice(lrcCursor[0], lrcCursor[0] + 1) + "</b>" + "<font color=\"grey\">" + wlrc.slice(lrcCursor[0] + 1) + "</font>");
}
}
else if(lrcCursor.length == 2) //if the selected text is more than one char (like in hyphenated mode)
{
if(lrcCursor[1] == 1)
{
lrcDisplay.text = convertLineBreak("<b>" + wlrc.slice(0,1) + "</b>" + "<font color=\"grey\">" + wlrc.slice(lrcCursor[1]) + "</font>");
}
else if(lrcCursor[1] >= wlrc.length - 1)
{
lrcDisplay.text = convertLineBreak("<font color=\"grey\">" + wlrc.slice(0, lrcCursor[0]) + "</font>" + "<b>" + wlrc.slice(lrcCursor[0]) + "</b>");
}
else
{
if(lrcCursor[0] == lrcCursor[1])
lrcDisplay.text = convertLineBreak("<font color=\"grey\">" + wlrc.slice(0,lrcCursor[0]) + "</font>" + "<b>" + wlrc.charAt(lrcCursor[0]) + "</b>" + "<font color=\"grey\">" + wlrc.slice(lrcCursor[1]) + "</font>");
else
lrcDisplay.text = convertLineBreak("<font color=\"grey\">" + wlrc.slice(0,lrcCursor[0]) + "</font>" + "<b>" + wlrc.slice(lrcCursor[0], lrcCursor[1]) + "</b>" + "<font color=\"grey\">" + wlrc.slice(lrcCursor[1]) + "</font>");
}
}
//refresh the height of lrcDisplayMenuMouseArea, add averageLineHeight because the ScrollView's height value is slightly shorter than what it seems like
lrcDisplayMenuMouseArea.height = (lrcDisplay.height > lrcDisplayScrollView.height ?
(lrcDisplayScrollView.height + Math.ceil(averageLineHeight)) : lrcDisplay.height);
lrcCursor = temp[0];
}
//Basic Lyrics Selection Functions:
function isOnlyContainsSeparator(text) //helper function to check if lyrics only contain \n and separators to avoid infinate loops
{
for(var i = 0; i < lrc.length; i++) {if((lrc.charAt(i)) != '\n' && !isSeparator(lrc.charAt(i))) return false;}
return true;
}
function getNextAvailableCharPos(text, pos, direction) //from the @lrcCursor, searching the position of next non-'\n',-whitespace, or -separator char in the lyrics
{
for(var i = pos + direction; i != pos; i += direction)
{
if((direction == 1) && (i >= text.length)) i = 0;
if((direction == -1) && (i < 0)) i = text.length - 1;
if ((text.charAt(i)) == '\n' || isSeparator(text.charAt(i))) continue; else return i;
}
}
function getNextSeparatorPos(text, pos, direction) //from the @lrcCursor, searching the position of next '\n', whitespace, or separator in the lyrics
{
for(var i = pos + direction; i != pos; i += direction)
{
if((direction == 1) && (i >= text.length)) return i;
if((direction == -1) && (i < 0)) return -1;
if((text.charAt(i)) != '\n' && !isSeparator(text.charAt(i))) continue; else return i;
}
}
function expandCharToWord(charPos) //selects the word that selected character belongs to
{
//if the the char that is to expand is a '\n' or separator, find the next available char first then expand.
if ((lrc.charAt(charPos)) == '\n' || isSeparator(lrc.charAt(charPos))) charPos = getNextAvailableCharPos(lrc, charPos, 1);
lrcCursor[0] = getNextSeparatorPos(lrc, charPos, -1) + 1;
lrcCursor[1] = getNextSeparatorPos(lrc, charPos, 1);
}
function nextChar() //advancing the @lrcCursor forward by skipping the @seperator to the next selection
{
if(lrcCursor.length == 1) lrcCursor[0] = getNextAvailableCharPos(lrc, lrcCursor[0], 1); //if the selected text is single char (normal case)
else if(lrcCursor.length == 2) //if the selected text is more than one char (like in hyphenated mode)
expandCharToWord(getNextAvailableCharPos(lrc, lrcCursor[1], 1));
}
function prevChar() //stepping the @lrcCursor back by a word or syllable, same structure as the nextChar() above
{
if(lrcCursor.length == 1) lrcCursor[0] = getNextAvailableCharPos(lrc, lrcCursor[0], -1); //if the selected text is single char (normal case)
else if(lrcCursor.length == 2) //if the selected text is more than one char (like in hyphenated mode)
expandCharToWord(getNextAvailableCharPos(lrc, lrcCursor[0], -1));
}
//@lineHeights: the vertical height of each line (in px), use to locate user clicked character's line number
//@separatorsWidth: the horizontal width of each separator (in px) like ' ' and '-'
//@newlinePositions: the index of all line breaks '\n', used for searching user clicked character in the specific line
//use getDisplayPositionMap() to forcefully resize the invisible lrcDisplayDummy and use its height to store the pixel line heights
//for later use of findChar(x,y) that finds user clicked char by forcefully resize the lrcDisplayDummy until it reaches the x,y position
//This is a very cheesy solution but worked pretty well.
property var lineHeights: []
property var separatorsWidth: []
property var newlinePositions: [0]
property var averageLineHeight: 0;
function getDisplayPositionMap()
{
separatorsWidth = [];
//calculates all separators' horizontal width
lrcDisplayDummy.text = convertLineBreak("1");
for(var i = 0; i < separator.length; i++)
{
lrcDisplayDummy.text = convertLineBreak("1");
var before = lrcDisplayDummy.width;
lrcDisplayDummy.text = convertLineBreak("1" + separator[i] + "1");
separatorsWidth.push(lrcDisplayDummy.width - (2*before));
}
console.log("Current separators: " + separator + ". separatorsWidth: " + separatorsWidth);
lineHeights = []; newlinePositions = [];
var lines = lrcDisplay.wrappedText.split(/(\n)/).filter(function(e){return e;});
var mergedLines = [];
for(var i = 0; i < lines.length; i++)
{
if(lines[i] == "\n" && mergedLines.length /*avoid empty stack*/ != 0
&& /*if last line end with linebreak*/!/\n$/.test(mergedLines[mergedLines.length - 1]))
{ mergedLines[mergedLines.length - 1] = mergedLines[mergedLines.length - 1] + lines[i]; continue; }
else mergedLines.push(lines[i]);
}
lines = mergedLines;
for(var i = 0, indexOfI = 0; i < lines.length; i++)
{
lrcDisplayDummy.text = lines[i].replace(/\n/g, '');
lineHeights.push(lrcDisplayDummy.height);
newlinePositions.push(indexOfI);
indexOfI += lines[i].length;
}
averageLineHeight = lineHeights.reduce(function(acc, val) { return acc + val; }, 0) / (lineHeights.length);
console.log("lineHeights: " + lineHeights + ", averageLineHeight: " + averageLineHeight);
console.log("newlinePositions: " + newlinePositions);
lrcDisplay.cache(ptSize);
}
function hasNonLatinChar(s) { return /^[A-z\u00C0-\u00ff]|[,.\/#!$%\^&\*;:{}=\-_`~()]+$/.test(s); }
function hasOnlyLatinChar(s) { return /[A-z\u00C0-\u00ff]|[,.\/#!$%\^&\*;:{}=\-_`~()]+$/.test(s); }
function seperateLatinAndNonLatin(wordlist) //helper function that further separates the word wordlist into English words and non-English characters
{
var separated = [];
for(var i = 0; i < wordlist.length; i++)
{
if(!(hasNonLatinChar(wordlist[i]))) //if the word contains non-Latin letters
for(var j = 0; j < wordlist[i].length; j++)
{ //if the character is non-latin letters, identify this character as a single word.
if(!(hasOnlyLatinChar(wordlist[i].charAt(j))))
separated.push(wordlist[i].charAt(j));
else //if the character is latin letters, check if the last pushed word is latin letters only
{
if(separated.length != 0)
{