-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathScoreTimeCode.qml
More file actions
703 lines (575 loc) · 17 KB
/
Copy pathScoreTimeCode.qml
File metadata and controls
703 lines (575 loc) · 17 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
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import MuseScore
import Muse.UiComponents
//=============================================================================
// MuseScore 4.4+
//
// Score Timecode
// A plugin to display the time passed throughout the score
//
// (C) 2025 Phil Kan
// PitDad Music. All Rights Reserved. GPL3 License.
//
// To Do
// - Better Layout of buttons
//
// Change History
// v1.0 - Initial development
//
//=============================================================================
MuseScore
{
version: "1.0"
title: "Score Timecode"
description: "This plug-in adds text to each measure to display the elapsed time in minutes, seconds, and milliseconds."
pluginType: "dialog"
thumbnailName: "ScoreTimecodeIcon.png"
implicitHeight: 350;
implicitWidth: 300;
//=============================================================================
// configuration options.
//
// These can be set in the Main UI
property var offsetTimeText: "00:00.000"; // seconds.milliseconds
property var offsetTime: 0.0
property var excludeFirstMeasure: false;
property var alwaysIncludeMinutes: false;
property var italicText: false;
property var boldText: false;
property var borderText: false;
property var underlineText: false;
property var aboveText: false
//=============================================================================
// Main UI Layout
//
SystemPalette { id: palette; colorGroup: SystemPalette.Active }
GridLayout
{
id: scoreTimeMainLayout
columns: 2
rowSpacing: 0
anchors.fill: parent
anchors.leftMargin: 5
anchors.rightMargin: 5
RowLayout
{
id: offsetRow
Layout.columnSpan:2
Label
{
id: offsetTimeLabel
font.bold: true
color: palette.text
text: "Offset time"
}
Item
{
id: offsetSpacerItem
Layout.fillWidth: true
}
TextField
{
id: offsetTimeField
text: offsetTimeText
Layout.maximumWidth:100
horizontalAlignment: TextInput.AlignRight
Layout.alignment: Qt.AlignRight
validator: RegularExpressionValidator { regularExpression: /^((\d{1,2}):(\d{1,2}).(\d{1,3}))$/ }
}
}
Label
{
id: offsetTimeDescription
Layout.columnSpan:2
font.italic: true
color: palette.text
text: "Time code at which to start in mins:secs:millisecs.\nDefault: 00:00.000"
}
CheckBox
{
id: excludeFirstMeasureCheckbox
Layout.columnSpan:2
text: "Exclude the first measure"
checked: excludeFirstMeasure
onClicked: {
excludeFirstMeasure = !excludeFirstMeasure;
}
}
CheckBox
{
id: alwaysIncludeMinuteCheckbox
Layout.columnSpan:2
text: "Always include minutes"
checked: alwaysIncludeMinutes
onClicked: {
alwaysIncludeMinutes = !alwaysIncludeMinutes;
}
}
Label
{
id: styleLabel
Layout.columnSpan: 2
Layout.topMargin: 10
color: palette.text
text: "Style:"
}
RowLayout
{
id: styleRow
Layout.columnSpan: 2
Layout.leftMargin: 10
Layout.rightMargin: 10
width:parent.width
RoundButton
{
id: boldButton
radius: 5
text: "B"
font.bold: true
palette.buttonText: palette.text
checkable: true
checked: boldText
onClicked: {
boldText = !boldText;
}
}
RoundButton
{
id: italicButton
radius: 5
text: "I"
font.italic: true
palette.buttonText: palette.text
checkable: true
checked: italicText
onClicked: {
italicText = !italicText;
}
}
RoundButton
{
id: underlineButton
radius: 5
text: "U"
font.underline: true
palette.buttonText: palette.text
checkable: true
checked: underlineText
onClicked: {
underlineText = !underlineText;
}
}
RoundButton
{
id: borderButton
radius: 5
text: "[0]"
palette.buttonText: palette.text
checkable: true
checked: borderText
onClicked: {
borderText = !borderText;
}
}
SpinBox
{
id: fontSizeSpinBox
from: 1
value: 9
to: 99
editable: true
palette.buttonText: palette.text
property string suffix: "pt"
validator: RegularExpressionValidator { regularExpression: /\D*(-?\d*\.?\d*)\D*/ }
textFromValue: function(value, locale) {
return Number(value).toLocaleString(locale, 'f', 0) + suffix
}
valueFromText: function(text, locale) {
let re = /\D*(-?\d*\.?\d*)\D*/
return Number.fromLocaleString(locale, re.exec(text)[1])
}
}
}
ButtonGroup
{
id: positionGroup
}
ButtonGroup
{
id: textStyleGroup
}
RowLayout
{
id: positionRow
Layout.columnSpan: 2
Layout.leftMargin: 10
Layout.rightMargin: 10
RoundButton
{
id: aboveButton
radius: 5
text: "Above"
palette.buttonText: palette.text
checkable: true
ButtonGroup.group: positionGroup
}
RoundButton
{
id: belowButton
radius: 5
text: "Below"
palette.buttonText: palette.text
checkable: true
checked: true
ButtonGroup.group: positionGroup
}
Item
{
id: positionRowSpacerItem
Layout.fillWidth: true
}
RoundButton
{
id: quotesButton
radius: 5
text: "0'00.000"
palette.buttonText: palette.text
checkable: true
ButtonGroup.group: textStyleGroup
Layout.alignment: Qt.AlignRight
}
RoundButton
{
id: colonsButton
radius: 5
text: "00:00.000"
palette.buttonText: palette.text
checkable: true
checked:true
ButtonGroup.group: textStyleGroup
}
}
Row
{
id: buttonsRow
Layout.columnSpan: 2
spacing: 5
topPadding: 10
rightPadding: 10
bottomPadding: 5
RoundButton
{
id: applyButton
text: qsTranslate("PrefsDialogBase", "Apply")
font.bold: true
palette.buttonText: palette.text
radius: 5
onClicked: addScoreTimes()
}
RoundButton
{
id: aboutButton
text: "About"
palette.buttonText: palette.text
radius: 5
onClicked: aboutDialog.open()
}
}
}
//=============================================================================
// About Dialog
property string aboutDialogText: "
<h3>Score Timecode</h3>
<p>
A MuseScore Studio plugin that adds the elapsed time in seconds to each measure
</p>
<p>
GPLv3 License <br>
(C) 2025 Phil Kan <br>
PitDad Music. All Rights Reserved.
</p>
</p>
Details available on <a href='https://github.com/philxan/ScoreTimecode'>Github</a>
"
property string linkText: "https://github.com/philxan/ScoreTimecode"
Dialog {
id: aboutDialog
title: "About Score Timecode"
anchors.centerIn: parent
palette.buttonText: palette.text
standardButtons: Dialog.Ok
implicitWidth: Math.round(parent.width * 90 / 100)
implicitHeight: Math.round(parent.height * 90 / 100)
contentItem: Column {
Rectangle {
id: aboutContentRectangle
color: "#ffffff"
width: aboutDialog.contentItem.width
height: aboutDialog.contentItem.height
Text {
id: aboutTextControl
text: aboutDialogText
anchors.fill: parent
anchors.margins: 20
onLinkActivated: Qt.openUrlExternally(linkText)
wrapMode: Text.Wrap
textFormat: Text.StyledText
MouseArea
{
anchors.fill: parent
acceptedButtons: Qt.NoButton // we don't want to eat clicks on the Text
cursorShape: parent.hoveredLink ? Qt.PointingHandCursor : Qt.ArrowCursor
}
}
}
}
}
function displayError(message)
{
errorDialog.text = message;
errorDialog.open();
}
//=============================================================================
// errorDialog
MessageDialog
{
id: errorDialog
visible: false
title: "Score Times"
text: ""
onAccepted: {
close();
}
}
//=============================================================================
onRun:
{
if ((mscoreMajorVersion < 4) || ((mscoreMajorVersion == 4 && mscoreMinorVersion < 4 )))
{
versionError.open()
(typeof(quit) === 'undefined' ? Qt.quit : quit)()
return;
}
setDefaults();
}
//=============================================================================
function addScoreTimes()
{
if (!validateOffsetTime())
{
console.log("Error: Invalid Offset Time.")
displayError("Error: The entered Offset Time is invalid.");
return;
}
var cursor = getCursor();
if (!cursor.segment ) // no selection
{
console.log("Error: Nothing is selected.")
displayError("Error: Nothing is selected.\nPlease select one staff of bars with chords");
return;
}
if (curScore.selection.endStaff - curScore.selection.startStaff > 1)
{
console.log("Error: More than one staff selected")
displayError("Error: More than one staff is selected\nPlease select only one staff, with chords");
return;
}
var endTick = getEndTick(cursor);
// what ticks are the tempo changes
var changes = getTickTempoChanges(cursor, endTick)
var tickChanges = objectKeys(changes);
var changesKey = 0;
var currentTempo = changes[tickChanges[changesKey]]; // the first tempo
var startTick = cursor.tick;
var lastMeasureTick = startTick;
var nextChangeTick = -1;
var nextChangeTempo = -1;
changesKey++;
if (changesKey < tickChanges.length)
{
nextChangeTick = tickChanges[changesKey];
nextChangeTempo = changes[nextChangeTick];
}
curScore.startCmd()
var lastMeasureSeconds = offsetTime;
if (!excludeFirstMeasure)
{
addTimeText(cursor, formatTime(lastMeasureSeconds)) // first one is always at the offsetTime
}
cursor.nextMeasure()
while ((cursor.tick != 0) && (cursor.tick < endTick))
{
var measureSeconds = 0;
// a tempo change occured somewhere in the previous measure
if ((lastMeasureTick <= nextChangeTick) && (nextChangeTick < cursor.tick))
{
// do it multiple times, in case there is more than one change!
while ((lastMeasureTick <= nextChangeTick) && (nextChangeTick < cursor.tick))
{
// calculate from the lastMeasureTick, to the tempo change at the old tempo
measureSeconds = lastMeasureSeconds + (nextChangeTick - lastMeasureTick) / (currentTempo * division);
// tempo change!
currentTempo = nextChangeTempo
// add the time from the change, to the current tick, at the new tempo
measureSeconds = measureSeconds + ((cursor.tick - nextChangeTick) / (currentTempo * division));
// update the nextChangeTick & Tempo
changesKey++;
if (changesKey < tickChanges.length)
{
nextChangeTick = tickChanges[changesKey];
nextChangeTempo = changes[nextChangeTick];
}
else
{
nextChangeTick = -1;
}
}
}
else
{
// no tempo change encountered, so a lot easier to calculate!
measureSeconds = lastMeasureSeconds + (cursor.tick - lastMeasureTick) / (currentTempo * division);
}
addTimeText(cursor, formatTime(measureSeconds))
lastMeasureSeconds = measureSeconds;
lastMeasureTick = cursor.tick;
cursor.nextMeasure()
}
curScore.endCmd()
}
//=============================================================================
//
// returns an object of tick:tempo
// - tick: where the tempo change occurs
// - tempo: the number of quarternotes per second
// e.g a 4/4 tempo of 60 will return a "tempo" of 1, 120 -> 2 etc.
//
function getTickTempoChanges(cursor, endTick)
{
var result = {}
var startTick = cursor.tick
// find the ticks where the tempo is different
var currentTempo = 0;
while (cursor.tick < endTick)
{
if (cursor.tempo != currentTempo)
{
result[cursor.tick] = cursor.tempo
currentTempo = cursor.tempo
}
if (!cursor.next()) break;
}
cursor.rewindToTick(startTick)
return result;
}
//=============================================================================
//
// returns the provided time in seconds as a string of "mm:ss.hhhh"
//
function formatTime(seconds)
{
var minutes = Math.floor(seconds / 60);
seconds = seconds - (minutes*60);
var secondsPart = Math.floor(seconds);
secondsPart = (((minutes > 0 || alwaysIncludeMinutes) && secondsPart < 10) ? "0" : "") + secondsPart;
seconds = seconds - Math.floor(seconds);
var milliseconds = Math.round(seconds * 1000)
while (milliseconds.toString().length < 3) milliseconds = "0" + milliseconds;
var result = secondsPart + "." + milliseconds + '"';
if (minutes > 0 || alwaysIncludeMinutes)
{
result = minutes
+ (colonsButton.checked ? ":" : "'")
+ result;
}
return result;
}
//=============================================================================
//
function addTimeText(cursor, timeString)
{
var text = newElement(Element.STAFF_TEXT)
text.text = timeString;
text.fontSize = fontSizeSpinBox.value
text.fontStyle = (boldText ? 1 : 0) // MS::FontStyle.Bold
+ (italicText ? 2 : 0) // MS::FontStyle.Italic
+ (underlineText ? 4 : 0); // MS::FontStyle.Underline
text.frameType = (borderText ? 1 : 0); // MS::FrameType.SQUARE
text.placement = aboveButton.checked ? Placement.ABOVE : Placement.BELOW
cursor.add(text);
}
//=============================================================================
function validateOffsetTime()
{
// try to parse the offsetTimeText into mm:ss:t[ttt]
// set the offsetTime value to the seconds representation
offsetTimeText = offsetTimeField.text
offsetTime = 0;
// Parse a offsetTimeText in format "MM:SS.HHH" (minutes:seconds:milliseconds)
try
{
// Check if it matches the format
var regex = /^((\d{1,2}):(\d{1,2}).(\d{1,3}))$/;
var timeStamp = offsetTimeText.match(regex);
if (!timeStamp) return false;
var minutes = parseInt(timeStamp[2]);
var seconds = parseInt(timeStamp[3]);
var millis = parseInt(timeStamp[4]);
if (millis < 10) millis *= 10; // 5 -> 50
if (millis < 100) millis *= 10; // 50 -> 500
// Validate ranges
if (seconds >= 60) {
return false;
}
// Calculate total seconds
offsetTime = (minutes * 60) + seconds + (millis / 1000);
}
catch (e)
{
return false;
}
return true;
}
//=============================================================================
function objectKeys(obj)
{
var result = []
for (var key in obj)
{
result.push(key)
}
return result;
}
//=============================================================================
function getCursor()
{
var cursor = curScore.newCursor()
cursor.staffIdx = 0;
cursor.voice = 0;
cursor.rewind(Cursor.SELECTION_START);
return cursor;
}
//=============================================================================
function getEndTick(cursor)
{
cursor.rewind(Cursor.SELECTION_END);
var endStaff = cursor.staffIdx;
var endTick;
if (cursor.tick == 0) {
// this happens when the selection includes the last measure of the score.
// rewind(Cursor.SELECTION_END) goes behind the last segment (where there's none) and sets tick=0
endTick = curScore.lastSegment.tick;
} else {
endTick = cursor.tick;
}
cursor.rewind(Cursor.SELECTION_START);
return endTick;
}
//=============================================================================
function setDefaults()
{
elapsedTime = 0.0;
}
}