-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTWHelper.py
3290 lines (3011 loc) · 132 KB
/
TWHelper.py
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
#!/usr/bin/env python3
# TEST: Implement abcnotation, possibly as tab format
# https://abcnotation.com/qtunes#early
# http://www.nigelgatherer.com/tunes/abc/abc1.html
# https://abcnotation.com/blog/2010/01/31/how-to-understand-abc-the-basics/
# TODO: should we use repeats if possible (will lengthen rows)
# TODO: reauthor tabs for max 60 or 72 beats
# TODO: finish WIP tunes
# BUG: not sure is still present: if play is disabled in songlistWin but song is playing, the new song will also play for remaining duration
# TODO: remove lineair tabs?
# TODO: Check ornaments as played on YT by TeamRecorder https://www.youtube.com/watch?v=vydCZ-HosQc
# TODO: Check if 'delay=delay2beatUpdate(beatUpdate)' serves a purpose in 'def setBeatUpdate()'
# BUG : Repeats in abc (e.g. 55.abc) not processed correctly
# BUG : Sometimes playing lets TWHelper believe we edited.... should we make a play only mode (disabling all editing)?
# TODO: replace .tb extension with .tab extension
# BUG: Cannot enter f# in MS Windows
# TODO README.md > does double click in windows on py file really start
# TODO: Make mobile e.g. using Kivy (https://kivy.org/)
# TODO: Make new linux distributable
# TODO: Make windows installer
# DONE: Toggle key to make cursor advance after new note is entered of stay (added indicator to cursor)
# DONE: play note on entering new / editing existing note
# DONE: using keyboard moving one row below, wil play all notes from 0 to new note instead of only new note under cursor
# DONE: cursor does not reset to beat 0 on load
# DONE: songlistWin is always on top, instead it follows window order of TWHelper itself
# DONE: load from full visible list of all available tb and abc files
# seperator between abc and tab files
# DONE: load at % of toolbar (so users can set zoom once at startup to accomodate for their screen width)
# DONE: make vertical ruler at 4*3*5=60 beats? (48/60/72 are dividable by 3 and 4)
# DONE: help/shortcut dock at right like songlist
# DONE: key down does not navigate songlistWin - to getting this to working
# DONE: Click note not only plays flute but also another instrument
# fixed in def initTabScroll(fromBeat=0) by changing prevCursorPlay=-1 to prevCursorPlay=fromBeat-1
# DONE: printscreen icon
# DONE: tab should also stop/pause play
# DONE: make last part of repeatable section skipable on last repeat
# DONE: Make tongue decorator also play as such
# DONE: Play triplets
# Implemented with decorator [alt-3] to shorten note
# DONE: Load abc files
# Implemented with warnings for unsupported features
# DONE: if abc repeats across multiple lines remove the line endings between
# DONE: implemented attribution fields (composer, transcriver) and signature to tab files
# to be displayed in footer
# DONE: replace bpm value as first line of tb file with 'bpm:'-field
# DONE: Display tabs/tune with
# - key
# - bpm https://www.musictheoryacademy.com/how-to-read-sheet-music/tempo/
# - time signatures: not needed e.g. 3/4 which denotes that quarter notes gets beat and there are 3 beats per measure
# Implemented in footer
# DONE: Closure of tune/page / mark last note to play
# Not needed, footer only below last tab line:
# DONE: Custom text fields on page right/bottom aligned
# by using negative x and y values in tab file
# DONE: Accents: staccato (. short/detached), tenuto (-, long attached)
# iImplemented as decorations
# DONO: hide splash on user action (mouse/key)
# NODO: Ornaments: Should we (be able to) switch between classical symbols for ornaments/decorations and my symbols?
# https://hellomusictheory.com/learn/ornaments/ (most important ones)
# https://en.wikipedia.org/wiki/List_of_ornaments (full list)
# https://www.tradschool.com/en/about-irish-music/ornamentation-in-irish-music/ (tin whistle)
# NODO: Accents: staccato (. short/detached), accent (> hard), marcato (^ stac+acc), tenuto (-, long attached)
# Can be implemented like decorations
# Should both, accent and decoration, be possible for each note?
# NODO: Should we be able to download abc from internet?
# FOR EACH RELEASE
# TODO: pip3 freeze >requirements.txt
# TODO: make packages
# 1) 'pyinstaller TWHelper.py' see https://pyinstaller.readthedocs.io/en/stable/usage.html#using-pyinstaller
# 2) copy resources/screenshots/tabs folder to dist folder
# 3) copy libfluidsynth.so.* and libfluidsynth64.dll to dist folder
import traceback
import os
from sys import platform
import re
from datetime import datetime
import time
import copy
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from tkinter.messagebox import Message
from pyscreenshot import grab
from PIL import Image
from tooltip import CreateToolTip
import splash
#GLOBALS
scriptpath= os.path.realpath(__file__)
scriptdir = os.path.dirname(scriptpath)
tabdir = os.path.join(scriptdir,"tabs")
abcdir = os.path.join(scriptdir,"abc")
icondir = os.path.join(scriptdir,"resources/icons")
sf2dir = os.path.join(scriptdir,"resources/sf2")
screenshotdir=os.path.join(scriptdir,"screenshots")
helpdir = os.path.join(scriptdir,"resources")
lastdir = tabdir
lasttype = ".tb"
# check for fluidsynth
fluidsynthLoaded=False
fs=None
try:
import fluidsynth #pip3 install pyFluidSynth
fluidsynthLoaded=True
fs=fluidsynth.Synth()
except Exception as e:
print (f"Error on import fluidsynth:{e}")
traceback.print_exc()
import helpWin
import infoDialog
import songlistWin
# Show experimental message
expShown=False # works because we only have 1 experimental feature (play decos)
def experimental():
global expShown
if expShown: return
infoDialog.show(win,title= "Experimental",
message="This feature is experimental and \nprobably will not work properly.",
timeout=2000)
expShown=True
# Show splash screen on startup
def showSplash():
# Calc some values to center splash on screen
mw=win.winfo_width()
mh=win.winfo_height()
sw=700
sh=400
sx=win.winfo_x()+int((mw-sw)/2)
sy=win.winfo_y()+int((mh-sh)/2)
dims=f"{sw}x{sh}+{sx}+{sy}"
# Show splash
splash.show(win,"Tin Whistle Helper",
#"___________________________________________________________________________________\n"+
#"\n"+
"Version : alpha version\n"+
"Homepage : https://github.com/NardJ/Tin-Whistle-Helper\n"+
"License : Attribution-NonCommercial-ShareAlike 2.0 Generic (CC BY-NC-SA 4.0)\n"+
"___________________________________________________________________________________\n"+
"\n"+
"Made using:\n"+
" Python3 (https://www.python.org/downloads/)\n"+
" PyScreenshot (https://github.com/ponty/pyscreenshot)\n"+
" Pillow (https://github.com/python-pillow/Pillow)\n"+
" PyFluidSynth (https://github.com/nwhitehead/pyfluidsynth)\n"+
" FluidSynth (https://github.com/FluidSynth/fluitsynth)\n"+
"___________________________________________________________________________________\n"+
"\n"+
"Disclaimer: \n"+
" This is an alpha version and for testing purposes only.\n"+
" It is not ready for daily use. You will encounter bugs and may \n"+
" loose work. The functionality of the next version may differ.\n"+
" Tab files created with this version may not load in the next release.",
dims,5000)
# vars for fluidsynth
sfFlute=None
sfMetro=None
chnFlute=None
chnMetro=None
# setup fluidsynth with whistle and metro sound
def initPlayer():
#https://www.fluidsynth.org/api/LoadingSoundfonts.html
#https://github.com/nwhitehead/pyfluidsynth
global sfFlute, sfMetro,chnFlute,chnMetro
# check if fluidsynth could be loaded
if not fluidsynthLoaded: return
# select appropriate driver
if "linux" in platform:
fs.start(driver="alsa")
if platform=="win32":
fs.start(driver="dsound")
if platform=="darwin":#OS X
print ("OS X is not yet supported. Please contact me (https://github.com/NardJ/Tin-Whistle-Helper) to add support.")
quit()
# load instruments
#soundfontpath = os.path.join(scriptdir,"SynthThik.sf2")
soundfontpath = os.path.join(sf2dir,"198-WSA percussion kit.SF2")
sfMetro = fs.sfload(soundfontpath)
chnMetro= 1
fs.program_select(chnMetro, sfMetro, 0, 0)
soundfontpath = os.path.join(sf2dir,"Tin_Whistle_AIR.sf2")
sfFlute = fs.sfload(soundfontpath)
chnFlute= 0
fs.program_select(chnFlute, sfFlute, 0, 0)
# define notes, decos, seperators which can be used in tabs
octL=5
octM=6
octH=7
noteNrsHigh= {'d':octM*12+2,'d#':octM*12+3,'e':octM*12+4,'f':octM*12+5,'f#':octM*12+6,'g':octM*12+7,'g#':octM*12+8,'a':octM*12+9,'a#':octM*12+10,'b':octM*12+11,'c':octM*12+12,'c#':octM*12+13,
'D':octH*12+2,'D#':octH*12+3,'E':octH*12+4,'F':octH*12+5,'F#':octH*12+6,'G':octH*12+7,'G#':octH*12+8,'A':octH*12+9,'A#':octH*12+10,'B':octH*12+11,'C':octH*12+12,'C#':octH*12+13,}
noteNrsLow = {'d':octL*12+2,'d#':octL*12+3,'e':octL*12+4,'f':octL*12+5,'f#':octL*12+6,'g':octL*12+7,'g#':octL*12+8,'a':octL*12+9,'a#':octL*12+10,'b':octL*12+11,'c':octL*12+12,'c#':octL*12+13,
'D':octM*12+2,'D#':octM*12+3,'E':octM*12+4,'F':octM*12+5,'F#':octM*12+6,'G':octM*12+7,'G#':octM*12+8,'A':octM*12+9,'A#':octM*12+10,'B':octM*12+11,'C':octM*12+12,'C#':octM*12+13,}
noteNrs = noteNrsHigh
oldNoteNr = 0
noteIDs = ['d','d#','e','f','f#','g','g#','a','a#','b','c','c#','D','D#','E','E#','F','F#','G','G#','A','A#','B','C','C#']
eot = 'eot'
sepIDs = ['|',',',eot]
restIDs = ['_']
decoIDs = ['<','^', '>', '=', '@', '~', '\\','/','-','*',':','t']
repID = 'rep'
# define colors for foreground (tabs and text) and background
colors=['blue', 'purple3', '#00BBED','red','DeepPink3','magenta','orange','gold','brown','green','gray39','black',]
backcolors=['#7BDAFF','#FFC6F4','#CeF1Fd','#ffC0C0','#F7A8Db','#f1Bbf1','#FeE59a','#FFFFDE','#D3B4B4','#A0FdA0','#D4D4D4','#FFFFFF']
# vars to store tabs page
win=None
tabs=[]
title=""
footer=""
textColor='black'
backColor='#FFFFDE'
texts=[]
# file vars for current tabs page
filename=None
filepath=None
# set some vars needed for drawing tabs
notes={ 'd' :(1,1,1,1,1,1,''),
'e' :(1,1,1,1,1,0,''),
'f#':(1,1,1,1,0,0,''),
'g' :(1,1,1,0,0,0,''),
'a' :(1,1,0,0,0,0,''),
'b' :(1,0,0,0,0,0,''),
'c#':(0,0,0,0,0,0,''),
'D' :(0,1,1,1,1,1,'+'),
'E' :(1,1,1,1,1,0,'+'),
'F#':(1,1,1,1,0,0,'+'),
'G' :(1,1,1,0,0,0,'+'),
'A' :(1,1,0,0,0,0,'+'),
'B' :(1,0,0,0,0,0,'+'),
'C#':(0,1,1,0,0,0,'+'),
'_' :(0,0,0,0,0,0,''),#rest
'd#':(1,1,1,1,1,2,''),
'f' :(1,1,1,1,2,0,''),
'g#':(1,1,2,0,0,0,''),
'a#':(1,0,1,1,1,1,''),
'c' :(0,1,1,0,0,0,''),
'D#':(1,1,1,1,1,2,'+'),
'F' :(1,1,1,1,2,0,'+'),
'G#':(1,1,0,1,1,0,'+'),#not sure if we need harder blow '+'
'A#':(1,0,1,0,0,0,'+'),#not sure if we need harder blow '+'
'C' :(2,0,0,0,0,0,''),
}
minBeatsize=10
maxBeatsize=60
DEFBEATSIZE=16
beatsize=DEFBEATSIZE
barInterval=1.2*beatsize
holeInterval=1.5*beatsize
xOffset=beatsize
yOffset=beatsize
beatCursor=0
titleHeight=40
winDims=[1118+26+15+16,800]
tabDims=[0,0]
# switch between high and low D-whistle octaves
def setLowHigh():
global noteNrs
if playing:
win.varLow.set(noteNrs==noteNrsLow)
return
noteNrs=noteNrsLow if win.varLow.get() else noteNrsHigh
# play a note
normalVol=96
def startNote(noteId):
if not fluidsynthLoaded: return
global oldNoteNr
if noteId in noteNrs:
noteNr=noteNrs[noteId]
fs.noteon(0, noteNr,normalVol)
oldNoteNr=noteNr
#print (f"On : {noteId}")
# stop a playing note
def endNote(noteId=None):
if not fluidsynthLoaded: return
noteNr=oldNoteNr if noteId==None else noteNrs[noteId]
fs.noteoff(0, noteNr)
#print (f"Off: {noteId}")
# play the metronome tick sound
def startTick():
if not fluidsynthLoaded: return
noteNr=12*9+2
fs.noteoff(1, noteNr)
fs.noteon(1, noteNr,127)
# destroy fluidsynth instance on closing this program
def closePlayer():
if not fluidsynthLoaded: return
fs.delete()
# helper to capatilize each word in title
def capTitle():
global title
title=" ".join([word.capitalize() for word in title.split(" ")])
# discard all tabs and start with a new tabs file
def newFile():
global beatCursor,tabs,bpm,title,backColor,filename
if len(oldTabs)>0:
ret=messagebox.askyesno("Discard changes?","You have unsaved changes.\nDiscard and start new file?")
if ret==False:return
bpm=120
win.bpm.set(f"{bpm:3}")
title="New File"
filename=f"{title}.tb"
tabs.clear()
texts.clear()
beatCursor=0
tabColor=colors[2]
backColor='#FFFFDE'
beat=0
for i in range (4):
tabs.append([beat,'_',1,'','green',beat,0,beat])
beat+=1
tabs.append([beat,',',0,'','green',beat,0,beat])
beat+=1
for i in range (4):
tabs.append([beat,'_',1,'','green',beat,0,beat])
beat+=1
win.title(f"Tin Whistle Helper - {title}")
calcTabDims()
recalcBeats()
drawBars(True)
# calc the beat to play the note and to display the note also the col (tabCol), row (tabRow) and linear pos (tabLin)
def recalcBeats():
beat,tabRow,tabCol,tabLin=0,0,0,0
for idx,tab in enumerate(tabs):
#[beat,name,dur,style,tabColor,tabCol,tabRow,tabLin]=tab
[_,name,dur,style,tabColor,_,_,_]=tab
#print (f"{idx:2}> ({tabCol},{tabRow}) {tab}")
tabs[idx]=[beat,name,dur,style,tabColor,tabCol,tabRow,tabLin]
#print (f"{' '}> {tabs[idx]}")
#calc new beat, col, row and lin
if name==eot:
tabRow+=1
tabCol=0
else:
beat+=dur
tabCol+=max(1,dur)
tabLin+=max(1,dur)
# return nr rows in this tabs file
def nrTabRows():
if len(tabs)==0: return 0
return tabs[-1][6]+1
# return idx of first tab in tabs[] on specified row
def rowStart(rowNr):
for idx in range(len(tabs)):
if tabs[idx][6]==rowNr: return idx
# return idx of last tab in tabs[] on specified row
def rowEnd(rowNr):
for idx in range(len(tabs)-1,-1,-1):
if tabs[idx][6]==rowNr: return idx
# remove seperators (| or blank space) on row
# which may get introduces on reformatting page (insert or delete row end) we may
def stripSeps():
#strips all seps at beginning of each row
for rowNr in range(nrTabRows()):
firstRowIdx=rowStart(rowNr)
if firstRowIdx!=None: # if row is present
firstRowTab=tabs[firstRowIdx]
if firstRowTab[1] in sepIDs: tabs.pop(firstRowIdx)
#strips all seps at end of each row
for rowNr in range(nrTabRows()):
lastRowIdx=rowEnd(rowNr)
if lastRowIdx!=None: # if row is present
lastRowIdx-=1 # last is eot, we want to strip seps just before eot
lastRowTab=tabs[lastRowIdx]
if lastRowTab[1] in sepIDs and lastRowTab[1]!=eot: tabs.pop(lastRowIdx)
# return if a repeat symbol if found between two positions in tabs[]
def hasRepeats(fromIdx=0,toIdx=-1):
if toIdx==-1: toIdx=len(tabs)
for idx in range(fromIdx,toIdx):
if tabs[idx][1][0]=='}': return True
return False
# return (first) repeat start ('{'-symbol) between two positions in tabs[]
def firstRepeat(fromIdx=0,toIdx=-1):
if toIdx==-1: toIdx=len(tabs)
for idx in range(fromIdx,toIdx):
if tabs[idx][1][0]=='{': return idx
# return repeat closure('}'-symbol) between two positions in tabs[]
def getRepeatMatchIdx(fromIdx,toIdx=-1):
m=tabs[fromIdx][1][0]
if m=='{':
if toIdx==-1: toIdx=len(tabs)
level=1
for idx in range(fromIdx+1,toIdx):
if tabs[idx][1][0]=='{': level+=1
if tabs[idx][1][0]=='}':
level-=1
if level==0: return idx
elif m=='}':
if toIdx==-1: toIdx=-1
level=1
for idx in range(fromIdx-1,toIdx,-1):
if tabs[idx][1][0]=='}': level+=1
if tabs[idx][1][0]=='{':
level-=1
if level==0: return idx
# unroll repeated section with
def unrollRepeats(fromIdx=0,toIdx=-1):
global tabs
if toIdx==-1: toIdx=len(tabs)
#find first repeat
startIdx=firstRepeat(fromIdx,toIdx)
#proceed if repeats found
if not startIdx: return
oldTabs.append(copy.deepcopy(tabs))
endIdx=getRepeatMatchIdx(startIdx,toIdx)
# first remove all child repeats
subIdx=firstRepeat(startIdx+1,toIdx)
#print (f"start:{startIdx} end:{endIdx} sub:{subIdx} {subIdx!=None}")
while subIdx!=None:
unrollRepeats(subIdx)
subIdx=firstRepeat(startIdx+1,toIdx)
# next unroll repeat
nrRepeats=int(tabs[startIdx][1][1])
newTabs=tabs[:startIdx]
postTabs=tabs[endIdx+1:] if endIdx+1<len(tabs) else []
unrollTabs=tabs[startIdx+1:endIdx]
for i in range(nrRepeats):
newTabs+=unrollTabs
newTabs+=postTabs
tabs=newTabs
# redraw
recalcBeats()
drawBars(True)
# return previous tab which has duration / can be played (so note or rest)
def gotoPrevBeat(idx):
global beatCursor
if idx>len(tabs):idx=len(tabs)
pidx=idx
pdur=0
beat=beatCursor
while pdur==0 and idx>0:
pidx-=1
beat,_,pdur,_,_,_,_,_=tabs[pidx]
beatCursor=beat
return pidx
# load file with extension .tb (internal file format)
def loadFileTab(tfilename=None,tfilepath=None):
global tabs,bpm,title,footer,filename,filepath
global textColor,backColor,texts
# if we received only filename we build filepath
if tfilepath==None:
tfilepath=os.path.join(tabdir,tfilename)
if not os.path.isfile(tfilepath): return
# start fresh tabs page
tabs.clear()
initBars()#20)
tabColor=colors[2]
backColor='#FFFFDE'
beat,tabRow,tabCol,tabLin=0,0,0,0 #just placeholders, real values will be calculated after loading by recalcBeats
#print (f"filename:{filename}|")
# read file
filepath=tfilepath
filename=os.path.basename(tfilepath)
with open(tfilepath,'r',encoding='utf-8') as reader:
lines=reader.readlines()
#remove comments and empty lines
for idx in range(len(lines)-1,-1,-1):
line=lines[idx].strip()
if len(line)==0: lines=lines[:idx]+lines[idx+1:]
elif line[0]=='#':lines=lines[:idx]+lines[idx+1:]
#read bpm
bpm=120
try:
bpm=int(lines[0])
lines=lines[1:]
print (f"Old format...bpm {bpm} found on first line")
except Exception as e:
print ("Assume new format.")
#process all lines
signature=""
transcriber=""
composer=""
texts.clear()
for line in lines: # go line by line
line=line.strip() # remove leading and trailing spaces and eol chars
if len(line)>0: # ignore empty lines
# process metadata of tune
if ':' in line: # read colors and text to display
colIdx=line.index(':')
cmd=line[:colIdx]
val=line[colIdx+1:]
#cmd,val=line.split(':')
cmd=cmd.strip()
if cmd=='bpm':
bpm=int(val)
print (f"New format... bpm {bpm} found.")
if cmd=="signature" :signature=val
if cmd=="transcriber":transcriber=val
if cmd=="composer" :composer=val
vals=val.split(",")
for idx in range(len(vals)): vals[idx]=vals[idx].strip()
if cmd=='color': textColor=vals[0]
if cmd=='back' : backColor=vals[0]
if cmd=='text' : texts.append(vals)
# process note data of tune
else:
line=line.replace(' ',' , , ') # tripple space is visual space between tabs
line=line.replace(' ',' , ') # double space is visual space between tabs
while ' ' in line:
line=line.replace(' ','') # more spaces are removed visual space between tabs
notes=line.split(" ")
notesfound=False
firstIdx=len(tabs)
tabCol=0
#print (f"line:'{line}\'")
for note in notes:
if note in colors:
tabColor=note
else:
#print (f"note:'{note}'")
name=note[0]
if len(note)>1:
if note[1]=='#': name+='#'
dur=1+note.count('.')
style=''
if len(note)>1:
if note[-1] in decoIDs:#'^>=@~/\\-':
style = note[-1]
if name in (noteIDs+restIDs+sepIDs) or name in ('{','}','?'):#['a','b','c','c#','d','e','f#','g','A','B','C#','D','E','F#','G','_','|',',']:
if name in sepIDs: dur=0 #('|',','): dur=0
if name in ('{','}','?'): name,dur=note,0
tabs.append([beat,name,dur,style,tabColor,tabCol,tabRow,tabLin])
#print (tabs)
notesfound=True
else:
print (f"Rejected: [{note}] {[beat,name,dur,style,tabColor,tabCol,tabRow,tabLin]}")
if notesfound: # ignore lines with only color
name=eot
dur=0
style=''
tabs.append([beat,name,dur,style,tabColor,tabCol,tabRow,tabLin])
# set title of window, footer
win.title(f"Tin Whistle Helper - {os.path.basename(tfilepath).split('.')[0]}")
title=os.path.basename(tfilepath).split('.')[0].replace("_"," ")
capTitle()
footer=f"Key: D BPM: {bpm}"
if signature: footer+= f" Signature: {signature}"
if composer: footer+= f" Composer: {composer}"
if transcriber:footer+=f" Transcriber: {transcriber}"
# set bpm
win.bpm.set(f"{bpm:3}")
maxMetroMult()
# calculate play order of tabs and display positions on page
recalcBeats()
# calculate size of page
calcTabDims()
# load file with extension .abc (common text file format for traditional music)
def loadFileABC(tfilename=None,tfilepath=None):
# Reference Guide to ABC: https://abcnotation.com/wiki/abc:standard:v2.1
# http://www.lesession.co.uk/abc/abc_notation.htm
# http://www.lesession.co.uk/abc/abc_notation_part2.htm
# https://editor.drawthedots.com/
# http://www.nigelgatherer.com/tunes/abc/abc4.html
global tabs,bpm,title,filename,filepath,footer
global textColor,backColor,texts
# if we received only filename we build filepath
if tfilepath==None:
tfilepath=os.path.join(abcdir,tfilename)
if not os.path.isfile(tfilepath): return
# start fresh tabs page
tabs.clear()
texts.clear()
initBars()#20)
tabColor=colors[2]
backColor='#FFFFDE'
beat,tabRow,tabCol,tabLin=0,0,0,0 #just placeholders, real values will be calculated after loading by recalcBeats
# read file
filepath=tfilepath
filename=os.path.basename(tfilepath)
# set default title
title=os.path.basename(tfilepath).split('.')[0].replace("_"," ")
capTitle()
#read file
with open(tfilepath,'r',encoding='utf-8') as reader:
lines=reader.readlines()
#remove comments and empty lines
for idx in range(len(lines)-1,-1,-1):
line=lines[idx].strip()
if len(line)==0: lines=lines[:idx]+lines[idx+1:]
elif line[0]=='%':lines=lines[:idx]+lines[idx+1:]
#join lines ending in \
nlines=[]
currline='\\'
for line in lines:
if currline[-1:]=='\\':
currline=currline[:-1]+line.strip()
if currline[-1:]!='\\':
nlines.append(currline)
currline='\\'
lines=nlines
#split in header and content
for idx,line in enumerate(lines):
if line[0:2]=='K:':
header=lines[:idx+1]
body=lines[idx+1:]
exit
#read header
headeritems=['X:','T:','C:','L:','M:','K:','R:']
baseNoteLength=''
notesForBeat=''
signature=''
composer=''
transcriber=''
bpm=240
for line in header: # go line by line
line=line.strip() # remove leading and trailing spaces and eol chars
colIdx=line.index(':')
cmd=line[:colIdx]
val=line[colIdx+1:]
#cmd,val=line.split(':')
cmd=cmd.strip()
val=val.strip()
# each tune should start with an X: field, followed by a T: field and the header then ends at the K: field.
if cmd=='X' : pass # reference number (song part in file)
if cmd=='T' : title=val # title of song
if cmd=='C' : composer=val# composer of song
if cmd=='Z' : transcriber=val# composer of song
if cmd=='Q' :
if '/' in val: bpm=240
elif '=' in val: bpm=240
elif int(val)>60: bpm=int(val)
if cmd=='L' : # length of note without elongation or shortening e.g. 'c'
baseNoteLength=int(val[2])
if cmd=='M' : # Meter of song e.g. 6/8 or C for common time
# 3/4 denotes that quarter notes gets beat and
# there are 3 beats per measure
# measures are seperated with | 'note' and not automatically
if val=='C': val='4/4'
if val=='C|': val='2/2'
signature=val
noteForBeat=int(val[2])
if cmd=='R' : pass #val # Rythm of song e.g. Jig,Reel,Waltz
#print {"Jig":6/8,"Reel":4/4,"Waltz":3/4}[val]
if cmd=='K' : # Key of song
if val!='D':
contImport=tk.messagebox.askokcancel("Wrong key",
"Tune not of key D. Do you want to ignore and continue import?",
default='ok',icon='warning')
if not contImport:
newFile()
return
#ignore rest
#replace / without number by /2
for idx1,line in enumerate(body):
ln=len(line)
idx2=0
while idx2<ln:
#for idx2,char in enumerate(line):
char=line[idx2]
if char=='/' and line[idx2+1] not in ['0','1','2','3','4','5','6','7','8','9']:
print (f"oldline:{line}")
line=line[:idx2+1]+"2"+line[idx2+1:]
ln+=1
print (f"newline:{line}")
body[idx1]=line
idx2+=1
#check max divisor to get minimal note length to display
maxdiv=1
for line in body:
for idx,char in enumerate(line):
if char=='/':
div=int(line[idx+1])
if div>maxdiv: maxdiv=div
# set bpm
if baseNoteLength!='' and notesForBeat!='':
bpm=bpm*(baseNoteLength/noteForBeat)
win.bpm.set(f"{bpm:3}")
maxMetroMult()
#win.metromult.set(f"")
# build footer
footer=f"Key: D BPM: {bpm}"
if signature: footer+= f" Signature: {signature}"
if composer: footer+= f" Composer: {composer}"
if transcriber:footer+=f" Transcriber: {transcriber}"
#prelimenary refactoring of body
#0) remove strings between tunes
nbody=[]
for line in body:
l=""
intext=False
for c in line:
if c=='"': intext= not intext
elif not intext: l+=c
nbody.append(l)
body=nbody
#1) remove line endings between repeated sections
# (for automatic page scrolling repeats should be 1 row)
nbody=[]
inrep=False
l=""
for line in body:
o='' # hold previous char
for c in line:
if (o+c)=='|:': inrep= True
if (o+c)==':|': inrep= False
o=c # store previous char
l+=c #add prev char to l
if not inrep:
nbody.append(l)
l=""
body=nbody
#2) replace '::' abreviation by ':||:'
body=[line.replace('::',':| |:') for line in body]
#3) check for unsupported section indicators e.g. '[1'
if any('[' in line for line in body):
contImport=tk.messagebox.askokcancel("Ignore unsupported feature?",
"Repeated sections found. Do you want to ignore and continue import?",
default='ok',icon='warning')
if contImport:
body=[re.sub('\[\d','',line) for line in body]
#print (body)
else:
return
#4) check for unsupported tune property changes and lyrics e.g. Q,L,M,R,K and w:
nbody=[]
fndU=False
for line in body:
if line[:2] in ['Q:','L:','M:','R:','K:']:
fndU=True
else:
nbody.append(line)
if fndU:
contImport=tk.messagebox.askokcancel("Ignore unsupported feature?",
"Mid-tune change of property (Q/L/M/R/K) found. Do you want to ignore and continue import?",
default='ok',icon='warning')
if contImport:
body=nbody
else:
newFile()
return
#5) check for unsupported triplets
if any('(3' in line for line in body) or any('(2' in line for line in body) or any('(4' in line for line in body):
contImport=tk.messagebox.askokcancel("Ignore unsupported feature?",
"Duplets/Triplets/Quads found. Do you want to ignore and continue import?",
default='ok',icon='warning')
if contImport:
body=[line.replace('(3','') for line in body]
body=[line.replace('(2','') for line in body]
body=[line.replace('(4','') for line in body]
else:
newFile()
return
#6) remove notes between {}
if any('{' in line for line in body) or any('}' in line for line in body):
contImport=tk.messagebox.askokcancel("Ignore sub note groups?",
"Ornaments / grace note groups found. Do you want to ignore and continue import?",
default='ok',icon='warning')
if contImport:
body=[re.sub('\{.*?\}','',line) for line in body]
else:
newFile()
return
#7) check for note elongation indicators e.g. '<' and '>'
if any('<' in line for line in body) or any('>' in line for line in body):
contImport=tk.messagebox.askokcancel("Ignore unsupported feature?",
"Note elongation/shortening found. Do you want to ignore and continue import?",
default='ok',icon='warning')
if contImport:
#body=[line.replace('<','') for line in body]
#body=[line.replace('>','') for line in body]
pass # we can now handle this after processing tabs
else:
newFile()
return
#8) remove lyrics
nbody=[]
fndU=False
for line in body:
if line[:2] != 'w:':
nbody.append(line)
body=nbody
#9) replace double spaces, ending ']'/'||' and strip leading/trailing spaces and /r/n
for idx,line in enumerate(body):
while ' ' in line:
line=line.replace(' ',' ')
line=line.replace(']','')
line=line.replace('||','')
body[idx]=line.strip()
#10) replace / without number by /2
body=[re.sub('/(\D)',r'/2\1',line) for line in body]
#print ("---")
#print ("Refactored:")
#for line in body:
# print (body)
#print ("---")
#quit()
#read body/notes
noteitems=['c','d','e','f','g','a','b','C','D','E','F','G','A','B','z','Z']
groupitems=['|:',':|','|',':','{','}','?']
decos=['.'] # . staccato
preitems=['^', '=', '_','~']+decos
postitems=['/','1','2','3','4','5','6','7','8', ]
#no spaces between adjecent pre and note , note and post
for line in body:
line=line.strip()
#print (f"{line=}")
# extract valid items from refactored body
nline=[]
idx=0
while idx<len(line):
fnd=False
for item in (preitems+noteitems+postitems+groupitems+['>','<']):
if line[idx:idx+len(item)]==item:
nline.append(item)
idx+=len(item)
fnd=True
exit
if not fnd: idx+=1
#print (f"{nline=}")
notes=[]
# groups items in note groups of note itself,pre and post indicators
for idx in range(len(nline)):
if nline[idx] not in (preitems+noteitems+postitems+['>','<']):
notes.append([nline[idx]])
#group notes with pre and post items
if nline[idx] in (noteitems+['>','<']):
mgroup=[]
mgroup.append(nline[idx])
#find start of group
groupFrom=idx
for jdx in range(idx-1,-1,-1):
if nline[jdx] not in preitems: break
mgroup.append(nline[jdx])
#find end of group
groupTo=idx+1
for jdx in range(idx+1,len(nline)):
if nline[jdx] not in postitems: break
mgroup.append(nline[jdx])
notes.append(mgroup)
#print (f"{notes=}")
# replace some info
for gdx,group in enumerate(notes):
for idx,note in enumerate(group):
# replace c and f by c# and f#
if note in "cCfF":
group.append('^')
# replace abc notation for sharp/flat by internal indicators
note=note.replace('^','#')
note=note.replace('=','')
if note == '_': return # not supported
if note.isupper():
note=note[0].lower()
elif note.islower() and note!='c':
note=note.upper()
# replace |: by {2 and :| by }2
note=note.replace('|:','{2')
note=note.replace(':|','}2')
notes[gdx][idx]=note
# turn note info into tabs
notesfound=False
firstIdx=len(tabs)
tabCol=0
for notegroup in notes:
#print (f"note:'{note}'")
name=notegroup[0]
if name=='Z': name='_'
if '#' in notegroup: name=name+'#'
# make duration
multdur=1
for i in range(10):
if f"{i}" in notegroup:
multdur=i
break
if '/' in notegroup: dur=maxdiv/int(multdur)
else: dur=maxdiv*int(multdur)
if name in groupitems: dur=0
# decos
style=''
if name in decos:
# ornnaments are not encouraged in abc: http://trillian.mit.edu/~jc/music/abc/ABC-FAQ.html
# if present they are included as notes and not as ornament type indicators
pass
# store notes
if name=='_':
#print ('rest')
pass
if name in (noteIDs+restIDs+sepIDs) or name[0] in ('{','}','?') or name in ['>','<']:#['a','b','c','c#','d','e','f#','g','A','B','C#','D','E','F#','G','_','|',',']:
tabs.append([beat,name,dur,style,tabColor,tabCol,tabRow,tabLin])
notesfound=True
else:
print (f"Rejected: [{note}] {[beat,name,dur,style,tabColor,tabCol,tabRow,tabLin]}")
if notesfound: # ignore lines with only color
name=eot
dur=0
style=''
tabs.append([beat,name,dur,style,tabColor,tabCol,tabRow,tabLin])
# process note elongation and shortening '>','<'
#print (f"{tabs=}")
for idx,tab in enumerate(tabs):
beat,name,dur,style,tabColor,tabCol,tabRow,tabLin=tab
if name == '<':
tabs[idx-1][2]=tabs[idx-1][2]/2
tabs[idx+1][2]=tabs[idx+1][2]*1.5
tabs.pop(idx)
if name == '>':
tabs[idx-1][2]=tabs[idx-1][2]*1.5
tabs[idx+1][2]=tabs[idx+1][2]/2
tabs.pop(idx)
#print (f"{tabs=}")
#quit()
# set title
win.title(f"Tin Whistle Helper - {os.path.basename(tfilepath).split('.')[0]}")
# calculate play order of tabs and display positions on page
recalcBeats()
# calculate size of page
calcTabDims()
# save file to internal .tb format
def saveFileTab(tfilename=None,tfilepath=None):
global title,filename,filepath
if tfilepath==None:
tfilepath=os.path.join(tabdir,tfilename)
if not os.path.isfile(tfilepath): return
# save tfilepath to global var filename
filepath=tfilepath
filename=os.path.basename(tfilepath)
# retreive title from file name
title=os.path.basename(tfilepath).split('.')[0].replace("_"," ")
capTitle()
# save tabs page to file
drawBars(True)
eol='\n'
try:
with open(tfilepath,'w',encoding='utf-8') as writer:
writer.write(f"# {title}{eol}")
writer.write(f"# made with TWHelper{eol}")