forked from bbloomf/jgabc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jgabc.full.js
3841 lines (3768 loc) · 131 KB
/
jgabc.full.js
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
String.prototype.repeat = function(num){return new Array(num+1).join(this);};
String.prototype.reverse = function(){return this.split('').reverse().join('');};
HTMLTextAreaElement.prototype.selectAndScroll = function(start,end,onlyUp) {
var text = this.value;
var txtBox = this;
setTimeout(function(){
if(text != txtBox.value) return;
var scrollTop = txtBox.scrollTop;
var extra = ''
if(onlyUp) {
var $txtBox = $(txtBox);
var lineHeight = parseFloat($txtBox.css('line-height'));
if(isNaN(lineHeight)) lineHeight = 1.2 * parseFloat($txtBox.css('font-size'));
var rows = Math.floor($txtBox.height() / lineHeight);
extra = '\n'.repeat(rows-1);
}
txtBox.value = text.slice(0,end) + extra;
txtBox.scrollTop = txtBox.scrollHeight;
txtBox.value = text;
txtBox.setSelectionRange(start,end);
if(((txtBox.scrollTop - scrollTop) * (onlyUp? -1 : 1)) < 0) txtBox.scrollTop = scrollTop;
})
}
if(!String.prototype.trimRight) String.prototype.trimRight = function(){return this.replace(/\s+$/,'');};
var gabcSettings={trimStaff:true,showSyllableEditorOnHover:true,showSyllableEditorOnClick:true};
var uuid;
// lower-staff ext: 0xe1, upper: 0xe2
var _indicesChar = {
flat: [0xE0F1,0xe340,0xE0F2,0xe341,0xE0F3,0xe342,0xE0F4,0xe343,0xE0F5,0xe344,0xE0F6,0xe345,0xE0F7],
natural: [0xE0F9,0xe346,0xE0FA,0xe347,0xE0FB,0xe348,0xE0FC,0xe349,0xE0FD,0xe34A,0xE0FE,0xe34B,0xE0FF],
flat_line: 0xe340, // these only exist for lines (bdfhjl)
natural_line: 0xe346,
punctum: 0xE103,
diamond: 0xE113,
virga: 0xE123,
v: 0xE123,
leftVirga: 0xE133,
quilisma: 0xE143,
w: 0xE143,
bottomPartPodatus: 0xE154,
topPartPodatus: 0xE163,
podatus: [
null,
0xE173,
0xE183,
0xE194,
0xe1a3
],
o: 0xe1b3,
O: 0xe1c3,
diamond_tilde: 0xe1d3,
">": 0xe1e3,
"<": 0xe1f3,
upper_tilde: 0xe203,
lower_tilde: 0xe213,
porrectus: [
null,
0xe223,
0xe233,
0xe243,
0xe253
],
r: 0xe273,
s: 0xe283,
custos: 0xe2a3,
'+': 0xe2a3,
dot: 0xe2b3,
apos: 0xe2c2, //ichtus
ictus: 0xe2c2,
ictus_above:0xe2c5,
ictus_below:0xe2c2,
underscore: 0xe2d2,
episema: 0xe2d2,
episema_below:0xe2d2,
episema_above:0xe2d5,
underscore_longer: 0xe2e2,
episema_longer: 0xe2e2,
clivis: [
null,
0xe303,
0xe313,
0xe323,
0xe333
],
accent_above_staff: 0xe34c, // four different heights
connecting_line: [
undefined,
undefined,
0xe703,
0xe713,
0xe723,
0xe733
],
decorative_line: [
undefined,
0xe743,
0xe753,
0xe763,
0xe773,
0xe783
]
};
var vCodes = {
Abar: 'a',
Vbar: 'v',
Rbar: 'r'
};
// var _indicesLig = {
// flat: 'b', // these only exist for spaces (acegikm)
// natural: 'a', // ditto
// punctum: 'p',
// diamond: 'n',
// virga: 'v',
// v: 'v',
// leftVirga: 'c',
// quilisma: 'q',
// w: 'q',
// podatus: 'P',
// bottomPartPodatus: 0xE154,
// topPartPodatus: 'P',
// o: 'o',
// O: 'O',
// diamond_tilde: 'N',
// ">": 'L',
// "<": 'k',
// upper_tilde: 'K',
// lower_tilde: 'l',
// porrectus: 'R',
// r: 'w',
// s: 's',
// custos: 'u',
// '+': 'u',
// dot: '.',
// apos: 'I', //ichtus
// ictus: 'I',
// ictus_above: 'I',
// ictus_below: 'i',
// underscore: 'H',
// episema: 'H',
// episema_above: 'H',
// episema_below: 'h',
// underscore_longer: 0xe2e2,
// episema_longer: 0xe2e2,
// clivis: 'C',
// accent_above_staff: '~', // four different heights
// connecting_line: 'x',
// decorative_line: 'X'
// };
var fontclass = "goudy"
// var _neumeLig=function(a,b){
// if(arguments.length<2)return"";
// if(typeof(a)!=="string") {
// if(arguments.length==2 && typeof(a)=="number"){
// return _neumeChar(a,b);
// }
// return"";
// }
// var result='';
// var i=1;
// while(i<arguments.length){
// result += _ci[arguments[i++]];
// }
// return result + a;
// }
var _neumeChar=function(a,b){
if(arguments.length<2)return"";
var base=a;
var a,b;
a=parseInt(b);
b=0;
if(typeof(base)=='object'){
if(arguments.length>2)b=parseInt(arguments[2]);
base=base[Math.abs(b-a)];
if(arguments.length==2)a=0;
}
return String.fromCharCode(base + a);
}
// var _clefSpanLig=function(tone){
// var line = parseInt(tone.clef.slice(-1),10);
// var num=line*2-1;
// var extra="";
// if(tone.clef.length==3) {
// extra += neume(indices.flat,num+1) + "-";
// }
// return make('tspan',String(num) + (tone.index==2? "d" : "f") + "-" + extra);
// }
var _clefSpanChar=function(tone,minDy){
var result,
line = parseInt(tone.clef.slice(-1),10),
dy = 0,
curChar;
if(tone.index == 2) {
curChar = "d-";
dy = 2 - line;
} else {
curChar = "f-";
dy = 3 - line;
}
if(tone.clef.length==3) {
curChar += neume(indices.flat,4) + "-";
}
dy *= spaceheight;
minDy[0] = Math.min(minDy[0],dy);
result=make('tspan',curChar);
result.setAttribute('dy', dy);
return result;
}
var _ci=['B','A','0','1','2','3','4','5','6','7','8','9','Z'];
var staffheight = 48;
var spaceheight = staffheight / 4;
var notewidth = staffheight / 6;
var spaceBetweenNeumes = notewidth;
var slashSpace = staffheight/20;
var verticalSpace = staffheight/4;
var fontsize = spaceheight*3/2;
var spaceWidth = spaceheight * 3/4;
var staffoffset = Math.ceil(staffheight - spaceheight/2);
var svgns = "http://www.w3.org/2000/svg";
var xlinkns="http://www.w3.org/1999/xlink";
var staffInFont = false;
var fontExt='ttf';
var fontExtS='svg#webfont';
var fontFormat="truetype";
var fontFormatS="svg";
var filenameCaeciliae = "Caeciliae-" + (staffInFont? "Regular." : "Staffless.")+fontExt;
var filenameCaeciliaeS = "Caeciliae-" + (staffInFont? "Regular." : "Staffless.")+fontExtS;
var filenameCaeciliaePrint = "Caeciliae-" + (staffInFont? "Regular" : "Staffless")+"-Print."+fontExt;
var localCaeciliae = "Caeciliae" + (staffInFont? "" : " Staffless");
var familyCaeciliae = "Caeciliae" + (staffInFont? "" : " Staffless");
var styleCaeciliae = "font-family: '"+familyCaeciliae+"'; font-size:" + staffheight + "px;";
var styleCaeciliaeSvg="font-family: '"+familyCaeciliae+" SVG'; font-size:" + staffheight + "px;";
var styleGoudy = "font-family: 'Crimson Text';" + " font-size: " + fontsize + "px;";
var styleFont="@font-face {font-family: '"+familyCaeciliae+"'; font-weight: normal; font-style: normal;src: local('"+localCaeciliae+"'); src: url('"+filenameCaeciliae+"') format('"+fontFormat+"')}"
+ "@font-face {font-family: '"+familyCaeciliae+" SVG'; font-weight: normal; font-style: normal;src: url('"+filenameCaeciliaeS+"') format('"+fontFormatS+"')}"
+ "@font-face {font-family: '"+familyCaeciliae+" Print'; font-weight: normal; font-style: normal;src: url('"+filenameCaeciliaePrint+"') format('"+fontFormat+"')}"
+ "@font-face { font-family: 'Crimson Text'; src: url('fonts/crimson-bold-webfont.woff2') format('woff2'), url('fonts/crimson-bold-webfont.woff') format('woff'); font-weight: bold; font-style: normal; }"
+ "@font-face { font-family: 'Crimson Text'; src: url('fonts/crimson-italic-webfont.woff2') format('woff2'), url('fonts/crimson-italic-webfont.woff') format('woff'); font- weight: normal; font-style: italic; }"
+ "@font-face { font-family: 'Crimson Text'; src: url('fonts/crimson-roman-webfont.woff2') format('woff2'), url('fonts/crimson-roman-webfont.woff') format('woff'); font- weight: normal; font-style: normal; }";
var svgWidth;
var _svg,svg;
var textElem;
var codea = 'a'.charCodeAt(0);
var codem = codea + 12;
var codeA = 'A'.charCodeAt(0);
var codeM = codeA + 12;
var regexLatinLongPenult = /([ao]e|au|[aeiouyāēīōūȳăĕĭŏŭäëïöüÿ])(?!([bcdgkpt][rl]|qu|[bcdfghjklmnprstvy])[aeiouyāēīōūȳăĕĭŏŭäëïöüÿ])((?:[bcdfghjklmnprstvy]{2,}|[xz])(?:[ao]e|au|[aeiouyāēīōūȳăĕĭŏŭäëïöüÿ])[bcdfghjklmnprstvxyz]*)$/i;
var regexTranslate=/translate\((-?\d+(?:\.\d+)?)(?:[,\s]\s*(-?\d+(?:.\d+)?))?\)/;
var regexTranslateG=/translate\((-?\d+(?:\.\d+)?)(?:[,\s]\s*(-?\d+(?:.\d+)?))?\)/g;
var regexHeaderEnd=/(?:^|\n)%%\s?\n/;
var regexOuter = /((([^\(\r\n]+)($|\())|\()([^\)]*)($|\))(?:(\s+)|(?=(?:\([^\)]*\))+(\s*))|)/g;
var regexTag = /<(\/)?(\w+)>/i;
var regexSqBrackets = /\[([^\]]*)(?:\]|$)/;
var regexTags= /(<\w+>)(.*?)(?:(<\/\1>)|$)/i;
var regexTagsSp = /<sp>([^<]*)<\/sp>/gi;
var spSubstitutions = {
"'ae": 'ǽ',
"'æ": 'ǽ',
"ae": 'æ',
"oe": 'œ',
"'œ": 'œ',
"'oe": 'œ',
"AE": 'Æ',
"OE": 'Œ',
"Ae": 'Æ',
"Oe": 'Œ',
"V/": 'V',
"R/": 'R',
"A/": 'A'
};
String.prototype.replaceSpTags = function(){
return this.replace(regexTagsSp,function(s){
var tmp = s.slice(4,-5);
return spSubstitutions[tmp]||tmp;
});
}
var regexInner = /[!\/ ,;:`]+|(([^\)!\/ ,;:`\[]+)(\[[^\]]*(?:$|\]))?)+/g;
var rog = {
syl:3,
gabc:5,
whitespace:7
}
var linkSelector="";
var linkDownloadSelector="";
var setPdfLinkSelector=function(sel){
linkSelector=sel;
};
var onDragStart=function(e){
console.info(e);
e.originalEvent.dataTransfer.setData("DownloadURL",this.getAttribute("data-downloadurl"));
};
var setGabcLinkSelector=function(sel){
linkDownloadSelector=sel;
$(sel).bind("dragstart",onDragStart);
};
var regexToneModifiers = /(')|(\.{1,2})|(_{1,4}0?)/g
var regexTones = new RegExp("([/ ,;:`]+)|((?:[fF]|[cC][bB]?)[1-4])|(?:(-)?(([A-M])|([a-m]))(([Vv]{1,3})|(s{1,3})|((<)|(>)|(~))|(w)|(o)|(O)|((x)|(y))|(q)|((R)|(r0)|(r(?![1-5])))|(r[1-5])|(\\+))?((?:" + regexToneModifiers.source.replace(/\((?!\?:)/g,"(?:") + ")*)(?:\\[([^\\]]*)(?:]|$))?|(z0))","g");
// /([\/ ,;:`]+)|([cfCF][1-4])|(?:(-)?(([A-M])|([a-m]))(([Vv]{1,3})|(s{1,3})|((<)|(>)|(~))|(w)|(o)|(O)|((x)|(y))|(q)|((R)|(r0)|(r(?![1-5])))|(r[1-5]))?((?:(?:')|(?:\.{1,2})|(?:(?:_0?){1,4}))*)|(z0))|\[([^\]]*)(?:\]|$) )*)|(z0))|\[([^\]]*)(?:\]|$)
// /([\/ ,;:`]+)|([cfCF][1-4])|(?:(-)?(([A-M])|([a-m]))(([Vv]{1,3})|(s{1,3})|((<)|(>)|(~))|(w)|(o)|(O)|((x)|(y))|(q)|((R)|(r0)|(r(?![1-5])))|(r[1-5]))?((?:(?:')|(?:\.{1,2})|(?:(?:_0?){1,4}))*)|(z0))|\[([^\]]*)(?:\]|$)
var regexTonesSpliceIndex=27;
var regexToneModifiersCount = 4;
var rtg = {
whitespace: 1,
clef: 2,
initioDebilis: 3,
tone: 4,
toneUpper: 5, // diamond
toneLower: 6,
noteType: 7, // (([Vv]{1,3})|(s{1,3})|((<)|(>)|(~))|(w)|([oO])|([xy])|(q)]|(R|r0|r(?![1-5]))|(r[1-5])|(\+))
virga: 8, // [Vv]{1,3}
stropha: 9, // s{1,3}
liquescentia: 10, // [<>~]
ascendingLiquescentia: 11, // <
descendingLiquescentia: 12, // >
diminutiveLiquescentia: 13, // ~
quilisma: 14, // w
oriscus: 15, // o
oriscusReverse: 16, // O
accidental: 17, // [xy]
flat: 18, // x
natural: 19, // y
q: 20, // q
lineaPunctum: 22, // R
lineaPunctumCavum: 23, // r0
punctumCavum: 24, // r
rNumber: 25, // r[1-5]
custos: 26, // \+
ictus: 27, // (')
dot: 28, // (\.{1,2})
episema: 29, // ((?:_0?)){1,4})
bracketed: 30, // [text]
autoCustos: 31 // z0
};
//var regexVowel = /(?:[cgq]u(?=[aeiouyáéëíóúýæœ])|[iy])?([aá]u|[ao][eé]?|[aeiouyáéëíóúýæœ])/i;
//var regexVowel = /(?:[cgq]u(?=[aeiouyáéëíóúýæœ])|[iy])?([aá]u|[ao][eé]?|[aeiouyáéëíóúýæœ])/i;
var regexVowel = /(?:[cgq]u|[iy])?([aeiouyáäąéëęíïóöúüýÿǽæœ́œ]+)/i;
var transforms = [['/',' ',',',';',':','`',''],
["'",'_','+',';','|',',',''],
[/\//g,/ /g,/,/g,/;/g,/:/g,/`/g,/!/g]];
var abcs = {};
var _defs = null;
var defText = null;
var _defText = null;
var defChant = null;
var masks = [];
var selectedPunctum=-1;
var selectedNeume=-1;
var selectedPunctumTag=null;
var selectedNeumeTag=null;
var selectedNeumeTextTag=null;
var syllableGabcIndex = -1;
var syllableGabcPrefix='';
var syllableGabcSuffix='';
var syllableGabcOriginalLength=0;
var syllableTextIndex = -1;
var syllableTextPrefix='';
var syllableTextSuffix='';
var syllableTextOriginalLength=0;
var syllableTextTag=null;
var syllableOffsetCorrection = {};
var _timeoutGabcUpdate = null;
var _minUpdateInterval = 1700;
var _heightCorrection = 0;
var utf8_bom=String.fromCharCode(0xEF)+String.fromCharCode(0xBB)+String.fromCharCode(0xBF);
function encode_utf8( s )
{
return utf8_bom+unescape( encodeURIComponent( s ) );
}
function decode_utf8( s )
{
return decodeURIComponent( escape( s ) );
}
function Header(text){
if(typeof(text)!='string') text='';
this.comments=[];
this.cValues={};
this.original='';
var match=text.match(regexHeaderEnd);
if(match){
var txtHeader = this.original = text.slice(0,match.index+match[0].length);
var lines = txtHeader.split(/\r?\n/g);
for(var i=0; i<lines.length; ++i){
var line=lines[i],
match = regexHeaderLine.exec(line);
if(match){
if(this[match[1]]) {
var arrayName=match[1]+'Array';
if(!this[arrayName]){
this[arrayName] = [this[match[1]]];
}
this[arrayName].push(match[2]);
} else {
this[match[1]]=match[2];
}
} else if((match = regexHeaderComment.exec(line))){
if(line!='%%'){
match = regexHeaderLine.exec(line.slice(1));
if(match){
this.cValues[match[1]]=match[2];
} else {
this.comments[i]=line;
}
}
}
}
}
}
Header.prototype.toString = function(){
var result=[];
for(key in this){
if(key=='length' || key=='original' || key=='comments' || key=='cValues' || (typeof this[key])!="string")continue;
var array = this[key+'Array'];
if(array) {
for(var i=0; i<array.length; ++i) {
result.push(key + ': ' + array[i] + ';');
}
} else {
result.push(key + ': ' + this[key] + ';');
}
}
for(key in this.cValues){
if(key.length==0 || !this.cValues.hasOwnProperty(key))continue;
result .push('%'+key + ': ' + this.cValues[key] + ';');
}
for(i in this.comments){
if(!this.comments.hasOwnProperty(i)) continue;
try{
result.splice(i,0,this.comments[i]);
} catch(e){}
}
return result.join('\n') + '\n%%\n';
};
function getHeaderLen(text){
var match=text.match(regexHeaderEnd);
if(match){
return match.index+match[0].length;
} else {
return 0;
}
}
var regexHeaderLine = /^([\w-_]+):\s*([^;\r\n]*)(?:;|$)/i;
var regexHeaderComment = /^%.*/;
function getHeader(text){
return new Header(text);
}
function updateLinks(text){
var header=getHeader(text);
if(header){
text = text.slice(header.original.length);
} else {
header = '%%\n';
}
if(linkSelector){
$(linkSelector).attr("href","http://gregorio.gabrielmass.com/cgi/process.pl?gregtext="
+ window.escape(header+text) + "&gregfontselect=17&gregtextfontselect=12&greginitialselect=43&gregspaceselect=7mm&gregredselect=N&greglinethickselect=10&gregpaperselect=letterpaper&gregfaceselect=libertine&gregcropselect=N");
}
try {
if(linkDownloadSelector){
var utf8=encode_utf8(header+text);
var url="data:text/plain;charset=utf8;base64,"+btoa(utf8);
var filename = header.name||"Untitled";
if(!filename.match(/\.gabc$/))filename += ".gabc";
$(linkDownloadSelector).attr("charset","UTF-8")
.attr("href",url)
.attr("data-downloadurl","text/plain:"+filename+":"+url);
}
} catch(e) {
}
return [header,text];
}
var gabcProcessTime = 0;
var _nextUpdate = new Date().getTime();
var dontUpdateChant = false;
var otherElements = [];
function updateChant(text, svg, dontDelay) {
var originalSvg = svg;
var $svg = $(svg);
if(!$svg.is('svg')) {
$svg = $svg.find('svg');
if(!$svg.length) {
$svg = $(_svg).clone().appendTo(svg);
}
svg = $svg[0];
}
if(svg != _svg && otherElements.indexOf(svg)<0 && originalSvg){
otherElements.push(originalSvg);
}
if(dontUpdateChant || !text)return;
var gtext=updateLinks(text);
if(_timeoutGabcUpdate) clearTimeout(_timeoutGabcUpdate);
if(!dontDelay) {
var delay = gabcProcessTime+100;
_timeoutGabcUpdate = setTimeout(function() {updateChant(text,svg,true);},delay);
return;
}
_nextUpdate = new Date().getTime() + 100 + gabcProcessTime;
var startTime=new Date();
text=gtext;
_timeoutGabcUpdate = null;
var old = $(svg).find(">g")[0];
if(!old) return;
var top=[0];
var newElem = getChant(text,svg,old,top);
//svg.replaceChild(newElem,old);
var height = newElem.getBBox().height + top[0] + _heightCorrection - _defText.getExtentOfChar("q").height;
$(svg).height(height);
//svg.setAttribute('height',height);
if(svg.parentNode.tagName.match(/span/i)){
$(svg).css('width',newElem.getBBox().width);
}
gabcProcessTime = new Date() - startTime;
console.info("Update chant time: " + gabcProcessTime);// + "; height: " + _ht + "; correction: "+_heightCorrection);
if(gabcProcessTime > 3000) gabcProcessTime=3000;
}
function make(tag,innerText,attributes) {
var result=document.createElementNS(svgns,tag);
if(innerText)result.appendChild(document.createTextNode(innerText));
if(attributes) {
switch(typeof(attributes)) {
case 'string':
result.setAttribute('class',attributes);
break;
case 'object':
for(a in attributes){
result.setAttribute(a,attributes[a]);
}
break;
}
}
return result;
}
var _txtWidths={};
//returns the width of txt.
// txt can be a string, array of TagInfo objects, or a TSpan tag object.
// if txt is not a string, clas and special can be an index and length to get the width of a substring.
function textWidth(txt,clas,special) {
var i=0;
var len=undefined;
if(txt.length===0)return 0;
if(typeof(clas)=="number" && typeof(special)=="number"){
i=clas;
len=special;
clas='goudy';
special=undefined;
if(len===0)return 0;
}
var dt=special?_defText:defText;
if($.isArray(txt)){
var tw;
var key;
if(txt.length==1 && txt[0].tags.length==0) {
txt = txt[0].text;
if(txt.length==0) return 0;
if(clas==undefined)clas="";
if(i==0 && !len && (key=clas+","+txt) && (tw=_txtWidths[key])) return tw;
} else {
if(i==0 && !len && (key=JSON.stringify(txt)) && (tw=_txtWidths[key])) return tw;
$(dt).empty();
var wid=0;
var idx=0;
txt.forEach(function(e){
var tmp=e.span();
dt.appendChild(tmp);
var sIndex=Math.max(i,idx);
var txtLen = tmp.textContent.length;
var tlen=Math.min(idx+txtLen,i+(len||1000000))-sIndex;
sIndex-=idx;
idx+=txtLen;
try {
if(tlen>0&&sIndex>=0)wid+=tmp.getSubStringLength(sIndex,tlen);
} catch(exception){
console.warn(exception);
}
});
if(key)_txtWidths[key]=wid||dt.getComputedTextLength();
return wid;
}
} else if(typeof(txt)=="object") {
if(txt.childNodes.length==1) {
var temp=txt.firstChild;
var key=$(temp).attr("class").replace(new RegExp('(?:^|\\s)'+fontclass+'(?:\\s|$)|\\s+$','g'),'') + "," + temp.textContent;
var tw=_txtWidths[key];
if(tw)return tw;
}
//txt is a span object hopefully
$(dt).empty().append($(txt).clone());
var wid=dt.getComputedTextLength();
if(key)_txtWidths[key]=wid;
return wid;
}
if(clas)dt.setAttribute("class", clas);
$(dt).text(txt.replace(/ /g,'\u00a0'));
var wid=dt.getSubStringLength(i, len||txt.length);
if(key)_txtWidths[key]=wid;
return wid;
}
function useWidth(use,idx,len) {
if(use.tagName.match(/^use$/i))use = document.getElementById(use.getAttribute('href').slice(1));
if(typeof(idx)=="undefined"){
return getChantWidth(use.textContent);
} else {
// Go through the tspan elements until we get to idx.
var id=0;
var tmp='';
var mostRecent='';
var result=[];
for(var i = 0; i < use.childNodes.length; ++i){
var cNode = use.childNodes[i];
if(id>=idx ){
if(result.length==0 && getChantWidth(cNode.textContent)<=2){
tmp = tmp.slice(0,0-mostRecent.length);
} else mostRecent='';
result.push(getChantWidth(tmp));
if(result.length==2)return result;
tmp=mostRecent;
idx += len;
}
tmp += cNode.textContent;
mostRecent=cNode.textContent;
id+=1;
}
result.push(getChantWidth(tmp));
return result;
}
}
function getChantWidth(text) {
defChant.textContent=text;
return defChant.getComputedTextLength();
}
function selectGabc(start,len,svg){
var e = $('#' + $(svg).parent().attr('for'));
if(e.length==0) e = $('#editor');
start+=getHeaderLen(e.val());
if(e.is(':visible')){
e=e[0];
} else {
e = $("#hymngabc")[0];
var i=0,j;
for(j in _hymnGabcMap){
if(!_hymGabcMap.hasOwnProperty(j)) continue;
if(j>start)break;
i=_hymnGabcMap[j] + start - j;
}
start = i;
}
if(len == -1) {
var m = $(e).val().slice(start).match(/^[^) ]*/);
len = m[0].length;
}
e.select(start,len);
e.selectionStart=start;
e.selectionEnd=start+len;
}
function getTagsFrom(txt){
var tm,r=[];
while(tm = regexTag.exec(txt)) {
r.push(tm[2]);
var lastIndex = tm.index + tm[0].length;
if(tm.index == 0)
txt = txt.slice(tm[0].length);
else txt = txt.slice(0,tm.index) + txt.slice(lastIndex);
}
return r;
}
function tagsForText(txtArray,activeTags){
if(typeof(txtArray)=="string")txtArray=[txtArray];
var result=[];
var txt=txtArray[0];
if(!activeTags)activeTags=[];
var tm;
while(tm = regexTag.exec(txt)) {
var temp=txt.slice(0,tm.index);
if(temp.length>0)result.push(new TagInfo(temp,activeTags));
if(tm[1] != "/") {
if(activeTags.indexOf(tm[2]) < 0) {
activeTags.push(tm[2]);
}
}
else {
var idx = activeTags.indexOf(tm[2]);
if(idx>=0)activeTags.splice(idx,1);
}
var lastIndex = tm.index + tm[0].length;
txt = txt.slice(lastIndex);
}
txtArray[0]=txt;
return result;
}
function TagInfo(txt,tags) {
this.tags = $.merge([],tags||[]);
this.text = txt.replace(/ /g,'\u00a0'); //(\u00a0 == nbsp)
if(tags && tags.indexOf('v')>=0){
this.span = this.spanV;
this.spans = [];
var txt='';
var strings = this.text.match(/\\[^\\\s]*|[^\\]+/g);
for(var i=0; i<strings.length; ++i) {
var s = strings[i];
if(s[0] == '\\') {
s = s.slice(1);
var code = vCodes[s];
if(code) {
this.spans.push({txt:code});
txt += code;
continue;
}
}
this.spans.push(s);
txt += s;
}
this.text = txt;
}
};
TagInfo.prototype.span = function(){
var result=make('tspan',this.text, fontclass + ' ' + this.tags.join(" "));
return result;
};
TagInfo.prototype.spanV = function(){
var c = fontclass + " " + this.tags.join(" ");
var result = make('tspan','',c);
for(var i=0; i<this.spans.length; ++i) {
var s = this.spans[i];
switch(typeof(s)) {
case 'object':
result.appendChild(make('tspan',s.txt,'versiculum'));
break;
case 'string':
result.appendChild(document.createTextNode(s));
break;
}
}
return result;
}
//This function will update the height and y offset of the staff once there is no more chant to be put on it, based on htone and ltone
var finishStaff=function(curStaff){
var result=curStaff.parentNode;
var line = parseInt(curStaff.id.match(/\d+$/)[0]);
var staffInfo=curStaff.info;
var ltone=staffInfo.ltone;
var htone=staffInfo.htone;
ltone = (3 - ltone);
ltone = (ltone <= 0)? 0 : ((ltone * spaceheight)/2);
htone = (htone - 9);
htone = (htone <= 0)? 0 : ((htone * spaceheight)/2);
var y = Math.ceil(0.1*staffheight + fontsize + ltone + htone);
staffInfo.vOffset = staffInfo.y;
if(staffInfo.txtInitial)staffInfo.txtInitial.setAttribute('y',y + staffInfo.y);
if(staffInfo.txtAnnotation)staffInfo.txtAnnotation.setAttribute('y',staffInfo.y+Math.ceil(htone)-25);
staffInfo.eText.setAttribute("y",y);
staffInfo.eTrans.setAttribute('y',y+fontsize);
staffInfo.eText.setAttribute("transform", "translate("+staffInfo.x+","+staffInfo.vOffset+")");
staffInfo.eText.setAttribute("class", "system"+line);
staffInfo.eTrans.setAttribute("transform", "translate("+staffInfo.x+","+staffInfo.vOffset+")");
staffInfo.eTrans.setAttribute("class", "system"+line);
if(result){
var $result = $(result);
$result.append($result.children('text'));
result.appendChild(staffInfo.eText);
result.appendChild(staffInfo.eTrans);
}
if(staffInfo.eTrans.childNodes.length>0){
y += fontsize;
}
if(htone>0) {
staffInfo.vOffset += htone;
if(line==0) {
var heightCorrection = 0;
$(curStaff).children("[id^=neume]").each(function(){
heightCorrection = Math.min(heightCorrection,this.neume.info.mindy);
});
_heightCorrection = heightCorrection + htone;
}
curStaff.setAttribute("transform","translate("+staffInfo.x+", " + (staffInfo.y + htone) + ")");
}
return y;
}
//This function will trim the width of the staff to lign up with the last element on it.
var trimStaff=function(curStaff,width){
var x;
var staffUse=$(curStaff).find("use[href=#staff]");
if(width){
x = width;
} else {
var lastUse=$(curStaff).find("[id^=neume]:last");
var lastText=$(curStaff.parentNode).find("[id^=neumetext]:last");
href=lastUse.attr("href");
if(href) {
if(!/\:$/.exec(href))return;
} else if(!/\|$/.exec(lastUse.text()))return;
var neumeId = /\d+$/.exec(lastUse.prop('id'))[0];
var textId = /\d+$/.exec(lastText.prop('id'))[0];
if(textId > neumeId)return;
x=parseFloat(lastUse.attr("x"));
var transform=lastUse.attr("transform");
var m = regexTranslate.exec(transform);
if(m && m[1])x += parseFloat(m[1]);
x += lastUse[0].neume.wChant;
}
var scale="scale("+x+",1)";
staffUse.attr("transform",function(index,transform){
return transform.replace(/scale\([^\)]*\)/,scale);
});
}
var justifyLine=function(curStaff,useNeumeX,justCommit){
var currentX=0;
var x2=0;
var words=curStaff.words;
if(!justCommit){
var endSpace=2*spaceBetweenNeumes;
x2=svgWidth - curStaff.info.x - endSpace;
var lastUse,lastTspan;
var i=words.length-1;
while(i>=0 && !(lastUse && lastTspan)){
var cWord=words[i--];
var j=cWord.length-1;
while(j>=0 && !(lastUse && lastTspan)){
var tag=cWord[j--];
if(!lastUse && tag.tagName.match(/^use|text$/i) && tag.neume){
lastUse = tag;
continue;
} else if(!lastTspan && tag.tagName.match(/^tspan$/i)){
lastTspan=tag;
continue;
}
}
}
if(lastUse){
if(useNeumeX) {
currentX = lastUse.neume.x + (lastUse.neume.transformX || 0);
} else {
currentX=parseFloat($(lastUse).attr("x"));
var transform=useNeumeX?lastUse.neume.transform : $(lastUse).attr("transform");
var m = regexTranslate.exec(transform);
if(m && m[1])currentX += parseFloat(m[1]);
}
currentX += lastUse.neume.wChant;
}
if(lastTspan){
var tmpX;
if(useNeumeX && lastTspan.neume){
tmpX=lastTspan.neume.x;
} else {
tmpX=parseFloat($(lastTspan).attr("x"));
tmpX += textWidth(lastTspan) - endSpace;
}
currentX=Math.max(currentX,tmpX);
// console.info(tmpX==currentX?lastTspan:lastUse);
}
}
if(justCommit || currentX>0){
var extraSpace=x2-currentX;
var len=words.length-1;
var delta=extraSpace/len;
if(justCommit || extraSpace>0) {
while(len>=0){
words[len].forEach(function(o){
if(o.neume)o.neume.justifyOffset=Math.round(extraSpace);
if($(o).attr("transform")) {
if(useNeumeX && o.neume)$(o).attr("x", o.neume.x);
$(o).attr("transform",function(e,cv){
return "translate("+Math.round(extraSpace + (o.neume&&o.neume.transformX||0))+")";
});
} else {
$(o).attr("x",function(e,cv){
return (useNeumeX? o.neume.x : (cv?parseFloat(cv):0)) + Math.round(extraSpace);
});
}
});
extraSpace -= delta;
--len;
}
}
}
}
var addCustos=function(staff,cneume,justify,custosXoffset) {
var tone = cneume.info.ftone;
var neumeText = neume(indices.custos,tone);
var t = staff.custos;
if(t){
t.textContent = neumeText;
if(staff.custosLedger)try{staff.removeChild(staff.custosLedger);delete staff.custosLedger;}catch(e){}
} else {
t = make('text',neumeText);
t.setAttribute('class',defChant.getAttribute('class'));
t.setAttribute('y',0);
}
if(justify || typeof(justify)=="undefined"){
justifyLine(staff,typeof(cneume.x)!='undefined');
justify=true;
}
var x2=justify? svgWidth - staff.info.x - (staffheight/15) : custosXoffset;
t.setAttribute('x',x2);
staff.appendChild(t);
staff.custos=cneume.custos=t;
var ledgerAbove=tone>10;
var ledgerBelow=tone<2;
if(ledgerAbove||ledgerBelow)staff.custosLedger=cneume.custosLedger=insertLedger(ledgerAbove,staff,t,true);
}
function relayoutChant(svg, width){
width = svgWidth = width || svg.parentNode.clientWidth;
var $svg = $(svg),
$svgg = $svg.children('g'),
$tmp = $svg.find('#commentary'),
x = 0,
xChantMin = 0,
staffI = 0,
neumeI = 0,
$staff = $svg.find('#system'+staffI),
curStaff = $staff[0],
$neume,
$text,
$trans,
$all,
staffInfo = $staff[0].info,
cneume,
pneume,
$lastText,
needCustos,
defs = $svg.find("defs")[0],
extraHeight = staffInfo.y,
offset,
curWord = [],
curSyl,
currentUse,
words = [],
maxX = width - staffInfo.x - spaceBetweenNeumes;
tagsBetweenText = [];
svg = $svg[0];
staffInfo.ltone = 3;
staffInfo.htone = 10;
if($tmp.length)$tmp.attr('x',width-$tmp[0].getComputedTextLength());
while(true){
pneume = cneume;
$lastText = $text;
$neume = $svgg.find('#neume'+neumeI);
$text = $svgg.find('#neumetext'+neumeI);
$trans = $svgg.find('#neumetrans'+neumeI);
cneume = $neume[0]? $neume[0].neume : ($text[0]? $text[0].neume : {match:{}});
delete cneume.custos;
var $mask = $svgg.find('#neumemask'+neumeI);
$all = $().add($neume).add($text).add($trans).add($mask);
curSyl = $all.toArray();
currentUse = $neume.toArray().concat($mask.toArray());
var hasLedgers = false;
for(i in cneume.ledgers){
if(!cneume.ledgers.hasOwnProperty(i)) continue;
hasLedgers = true;
break;
}
offset = cneume.offset || 0;
if($all.length == 0) {
break;
}
xChantMin += Math.min(0,offset);
if(cneume.wChant > 0 && (x < xChantMin || !$text.length)) {
x = xChantMin;
} else if(pneume.lastOnLineHyphen){
$(pneume.lastOnLineHyphen).remove();
delete pneume.lastOnLineHyphen;
}
var nextXTextMin = $text.length?
x + cneume.wText + Math.max(Math.floor(offset),0)
: nextXTextMin||0;
if(cneume.match[7]&&cneume.match.index>0)nextXTextMin+=5;
var nextXChantMin = x + cneume.wChant + (cneume.spaceBeforeNextNeume || spaceBetweenNeumes) - Math.min(offset,0);
var lastX;
cneume.x = x;
if(Math.max(nextXTextMin, nextXChantMin) > maxX){
var clef = lastClefBeforeNeume(neumeI,svg);
var wClef = clef? clef.wChant : 0;
if($lastText.length && !pneume.lastOnLineHyphen && !$lastText.text().slice(-1).match(/-|\s/)){
pneume.lastOnLineHyphen = new TagInfo('-').span();
$lastText.append(pneume.lastOnLineHyphen);
}
nextXTextMin -= x;