How to open MIDI-file and get events in a list? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to open MIDI-file and get events in a list? (/thread-28545.html) |
How to open MIDI-file and get events in a list? - philipbergwerf - Jul-23-2020 I am planning to make a program that converts a midi file to a readable piano-roll editor. I worked on the design for like more than a year(!) and after a lot of drawing by hand, I want to just make it... I want the program to open a midi file and render every line for me. I am not very experienced in programming but I already made a lead-sheet program so I know about using libriarys/basic knowledge but this seems really hard to me... def projectName(): print('PianoScript') def projectGoal(): print('MIDI to specifically-designed-piano-roll-for-reading-and-playing-piano converter')The Questions:
RE: How to open MIDI-file and get events in a list? - j.crater - Jul-30-2020 Hello, due to new hobbies, the project you are working with sounds really interesting to me! That said, the questions you posed are very broad. it's too much to take on all at once, in one thread (especially #3). 1. I need to open a midi-file and get all midi events in a python list. How do I do that? Have you tried anything? Have you searched online for examples of how other people do it? On your project building path, you will have a lot of searching and experimenting to do. This is just one example of it, so you better start tackling it on your own and get used to the process. We can of course help with specific coding questions, tips, correcting errors... 2. I am looking for the best python libriary for midifiles and I think that MIDIUtil is the best. Am I right(I hope someone with more experience in python and MIDI can help me)? The subject you are dealing with is very specific. This is a general Python forum, so chances are you will find better suited audience for this question in a music-software community. Unfortunately I can't answer this question either. 3. How would you start with a project like this? Now this question is very broad. There are articles written on the subject of software writing. Given that you asked a question like this, start with something smaller. Either a basic project, like a calculator (just an example, there are many options). Or you might prefer to start with implementing a little sub-part of your project idea. Such as reading midi files, storing the data in a list, displaying it in the console as the music is played, or so... This way you will build experience and get a feel of how coding process works. Then you can gradually move on with bigger ideas. Since your project idea (really cool one!) is not a straightforward coding exercise. Sooner or later you will start using modules and packages. When you become familiar with them, you may start looking at your project design and translate the specifications/diagrams into modules, functions, classes... which your program will be made of. Again, if you have specific questions, feel free to ask. Good luck! RE: How to open MIDI-file and get events in a list? - philipbergwerf - Aug-01-2020 Thank you for the kind words! Yes I made the diagram leadsheet with my first python program.. I learned already that i am asking too quickly, indeed first try to solve on your own. Currently, I am on the point where my (midi)program can open and display midi events on the staff! (maybe you can recognize the piece from the screenshot;)) I will ask if I have specific questions! RE: How to open MIDI-file and get events in a list? - j.crater - Nov-30-2020 Hello, how has the project been progressing? Have you gotten stuck at any point? Could this be Moonlight Sonata by LWB? :) RE: How to open MIDI-file and get events in a list? - philipbergwerf - Jan-09-2021 (Nov-30-2020, 09:31 PM)j.crater Wrote: Hello, how has the project been progressing? Have you gotten stuck at any point? Ah way too late sorry... But I am continuing this project and changed the direction. I created a music scripting language/lilypond-like application where you can enter music through text and the program renders the score. RE: How to open MIDI-file and get events in a list? - j.crater - Jan-14-2021 This sounds impressive! I sure am interested to see the result. So feel free to share some screenshots or even snippets in the Code Sharing forum RE: How to open MIDI-file and get events in a list? - philipbergwerf - Mar-25-2021 (Jan-14-2021, 07:45 PM)j.crater Wrote: This sounds impressive! I sure am interested to see the result. So feel free to share some screenshots or even snippets in the Code Sharing forumCurrently it growed to the next level :) Now the moonlight sonata looks like this: (since I cannot post images on this forum directly I will post the current code and the save file which you can open :) ### IMPORTS ### from tkinter import PhotoImage, Tk, Text, PanedWindow, Canvas, Scrollbar, Menu, filedialog, END, messagebox, simpledialog, EventType, colorchooser import platform, subprocess, os, datetime, sys ### GUI ### #colors _bg = '#aaaaaa' #d9d9d9 papercolor = '#fefff0' midinotecolor = '#dddddd' # Root root = Tk() root.title('PianoScript') scrwidth = root.winfo_screenwidth() scrheight = root.winfo_screenheight() root.geometry(f"{int(scrwidth / 1.5)}x{int(scrheight / 1.25)}+{int(scrwidth / 6)}+{int(scrheight / 12)}") # PanedWindow paned = PanedWindow(root, relief='flat', sashwidth=20, sashcursor='arrow', orient='h', bg=_bg) paned.pack(fill='both', expand=1) # Left Panel leftpanel = PanedWindow(paned, relief='flat', width=1350) paned.add(leftpanel) # Right Panel rightpanel = PanedWindow(paned, sashwidth=15, sashcursor='arrow', relief='flat') paned.add(rightpanel) # Canvas canvas = Canvas(leftpanel, bg=_bg, relief='flat') canvas.place(relwidth=1, relheight=1) vbar = Scrollbar(canvas, orient='vertical', width=20, relief='flat', bg=_bg) vbar.pack(side='right', fill='y') vbar.config(command=canvas.yview) canvas.configure(yscrollcommand=vbar.set) hbar = Scrollbar(canvas, orient='horizontal', width=20, relief='flat', bg=_bg) hbar.pack(side='bottom', fill='x') hbar.config(command=canvas.xview) canvas.configure(xscrollcommand=hbar.set) # linux zoom def bbox_offset(bbox): x1, y1, x2, y2 = bbox return (x1-40, y1-40, x2+40, y2+40) def scrollD(event): canvas.yview('scroll', int(event.y/200), 'units') #canvas.configure(scrollregion=bbox_offset(canvas.bbox("all"))) def scrollU(event): canvas.yview('scroll', -abs(int(event.y/200)), 'units') #canvas.configure(scrollregion=bbox_offset(canvas.bbox("all"))) def zoomerP(event): canvas.scale("all", event.x, event.y, 1.1, 1.1) canvas.configure(scrollregion=bbox_offset(canvas.bbox("all"))) def zoomerM(event): canvas.scale("all", event.x, event.y, 0.9, 0.9) canvas.configure(scrollregion=bbox_offset(canvas.bbox("all"))) canvas.bind("<5>", scrollD) canvas.bind("<4>", scrollU) canvas.bind("<1>", zoomerP) canvas.bind("<3>", zoomerM) if platform.system() == 'Darwin': def _on_mousewheel(event): canvas.yview_scroll(-1*(event.delta), "units") canvas.bind("<MouseWheel>", _on_mousewheel) textw = Text(rightpanel, foreground='black', background=_bg, insertbackground='red') textw.place(relwidth=1, relheight=1) textw.focus_set() fontsize = 16 textw.configure(font=('Terminal', fontsize)) # openfiledialog try: try: root.tk.call('tk_getOpenFile', '-foobarbaz') except TclError: pass root.tk.call('set', '::tk::dialog::file::showHiddenBtn', '0') root.tk.call('set', '::tk::dialog::file::showHiddenVar', '0') except: pass fscreen = 0 def fullscreen(s): print('fullscreen') global fscreen if fscreen == 1: root.wm_attributes('-fullscreen', 0) fscreen = 0 else: root.wm_attributes('-fullscreen', 1) fscreen = 1 return ### MAIN CODE ### ########################################################################## ## File management ## ########################################################################## starttemplate = '''// titles: ~title{title} ~composer{composer} ~copyright{copyright} // settings: ~mpline{6} ~scale{150} ~systemspace{90} // measure mapping: ~meas{4/4 4 36} // music: // ~hand{R} _1 ~hand{L} _1 ''' file = textw.get('1.0', END + '-1c') filepath = '' def new_file(): print('new_file') global filepath if get_file() > '': save_quest() textw.delete('1.0', END) textw.insert('1.0', starttemplate, 'r') root.title('PianoScript - New') filepath = 'New' render('q') return def open_file(): print('open_file') global filepath save_quest() f = filedialog.askopenfile(parent=root, mode='rb', title='Open', filetypes=[("PianoScript files","*.pnoscript")]) if f: filepath = f.name root.title(f'PianoScript - {filepath}') textw.delete('1.0', END) textw.insert('1.0', f.read()) render('q') return def save_file(): print('save_file') if filepath == 'New': save_as() return else: f = open(filepath, 'w') f.write(get_file()) f.close() def save_as(): global filepath f = filedialog.asksaveasfile(mode='w', parent=root, filetypes=[("PianoScript files","*.pnoscript")]) if f: f.write(get_file()) f.close() filepath = f.name root.title(f'PianoScript - {filepath}') return def quit_editor(): print('quit_editor') save_quest() root.destroy() def save_quest(): if messagebox.askyesno('Wish to save?', 'Do you wish to save the current file?'): save_file() else: return def get_file(): global file file = textw.get('1.0', END + '-1c') return file def def_score_settings(): ''' This function opens the preferences(default score settings) inside the GUI text editor ''' save_quest() confexst = path.exists("config.ini") print(confexst) ########################################################################## ## Tools ## ########################################################################## def strip_file_from_comments(f): fl = '' for i in f.split('\n'): find = i.find('//') if find >= 0: i = i[:find] fl += i+'\n' else: fl += i+'\n' f = '' for i in fl.split('\n'): if i == '': pass else: f += i+'\n' return f def duration_converter(string): # converts duration string to length in 'pianotick' format. calc = '' for i in string: if i == 'W': calc += '1024' if i == 'H': calc += '512' if i == 'Q': calc += '256' if i == 'E': calc += '128' if i == 'S': calc += '64' if i == 'T': calc += '32' if i == '+': calc += '+' if i == '-': calc += '-' if i == '*': calc += '*' if i == '/': calc += '/' if i == '(': calc += '(' if i == ')': calc += ')' if i == '.': calc += '.' if i in ['0','1','2','3','4','5','6','7','8','9']: calc += i dur = None try: dur = eval(calc) except SyntaxError: print(f'wrong duration: {string}') return return dur def string2pitch(string): pitchdict = { # Oct 0 'a0':1, 'A0':2, 'b0':3, # Oct 1 'c1':4, 'C1':5, 'd1':6, 'D1':7, 'e1':8, 'f1':9, 'F1':10, 'g1':11, 'G1':12, 'a1':13, 'A1':14, 'b1':15, # Oct 2 'c2':16, 'C2':17, 'd2':18, 'D2':19, 'e2':20, 'f2':21, 'F2':22, 'g2':23, 'G2':24, 'a2':25, 'A2':26, 'b2':27, # Oct 3 'c3':28, 'C3':29, 'd3':30, 'D3':31, 'e3':32, 'f3':33, 'F3':34, 'g3':35, 'G3':36, 'a3':37, 'A3':38, 'b3':39, # Oct 4 'c4':40, 'C4':41, 'd4':42, 'D4':43, 'e4':44, 'f4':45, 'F4':46, 'g4':47, 'G4':48, 'a4':49, 'A4':50, 'b4':51, # Oct 5 'c5':52, 'C5':53, 'd5':54, 'D5':55, 'e5':56, 'f5':57, 'F5':58, 'g5':59, 'G5':60, 'a5':61, 'A5':62, 'b5':63, # Oct 6 'c6':64, 'C6':65, 'd6':66, 'D6':67, 'e6':68, 'f6':69, 'F6':70, 'g6':71, 'G6':72, 'a6':73, 'A6':74, 'b6':75, # Oct 7 'c7':76, 'C7':77, 'd7':78, 'D7':79, 'e7':80, 'f7':81, 'F7':82, 'g7':83, 'G7':84, 'a7':85, 'A7':86, 'b7':87, # Oct 8 'c8':88 } ret = pitchdict[string] return ret def barline_pos_list(gridlist): barlinepos = [0] for grid in gridlist: cntr = 0 for i in range(grid[2]): nxtbarln = barlinepos[-1] + grid[0] barlinepos.append(nxtbarln) return barlinepos def newline_pos_list(gridlist, mpline): gridlist = barline_pos_list(gridlist) linelist = [0] cntr = 0 for barline in range(len(gridlist)): try: cntr += mpline[barline] except IndexError: cntr += mpline[-1] try: linelist.append(gridlist[cntr]) except IndexError: linelist.append(gridlist[-1]) break if linelist[-1] == linelist[-2]: linelist.remove(linelist[-1]) linelist.pop(0) return linelist def staff_height(mn, mx): ''' This function returns the height of a staff based on the lowest and highest note. ''' staffheight = 0 if mx >= 81: staffheight = 225 if mx >= 76 and mx <= 80: staffheight = 190 if mx >= 69 and mx <= 75: staffheight = 165 if mx >= 64 and mx <= 68: staffheight = 130 if mx >= 57 and mx <= 63: staffheight = 105 if mx >= 52 and mx <= 56: staffheight = 70 if mx >= 45 and mx <= 51: staffheight = 45 if mx >= 40 and mx <= 44: staffheight = 10 if mx < 40: staffheight = 10 if mn >= 33 and mn <= 39: staffheight += 35 if mn >= 28 and mn <= 32: staffheight += 60 if mn >= 21 and mn <= 27: staffheight += 95 if mn >= 16 and mn <= 20: staffheight += 120 if mn >= 9 and mn <= 15: staffheight += 155 if mn >= 4 and mn <= 8: staffheight += 180 if mn >= 1 and mn <= 3: staffheight += 195 return staffheight def draw_staff_lines(y, mn, mx): ''' 'y' takes the y-position of the uppper line of the staff. 'mn' and 'mx' take the lowest and highest note in the staff so the function can draw the needed lines. ''' def draw3Line(y): x = 70 canvas.create_line(x, y, x+printareawidth, y, width=2) canvas.create_line(x, y+10, x+printareawidth, y+10, width=2) canvas.create_line(x, y+20, x+printareawidth, y+20, width=2) def draw2Line(y): x = 70 canvas.create_line(x, y, x+printareawidth, y, width=0.5) canvas.create_line(x, y+10, x+printareawidth, y+10, width=0.5) def drawDash2Line(y): x = 70 canvas.create_line(x, y, x+printareawidth, y, width=1, dash=(6,6)) canvas.create_line(x, y+10, x+printareawidth, y+10, width=1, dash=(6,6)) keyline = 0 staffheight = 0 if mx >= 81: draw3Line(0+y) draw2Line(35+y) draw3Line(60+y) draw2Line(95+y) draw3Line(120+y) draw2Line(155+y) draw3Line(180+y) keyline = 215 if mx >= 76 and mx <= 80: draw2Line(0+y) draw3Line(25+y) draw2Line(60+y) draw3Line(85+y) draw2Line(120+y) draw3Line(145+y) keyline = 180 if mx >= 69 and mx <= 75: draw3Line(0+y) draw2Line(35+y) draw3Line(60+y) draw2Line(95+y) draw3Line(120+y) keyline = 155 if mx >= 64 and mx <= 68: draw2Line(0+y) draw3Line(25+y) draw2Line(60+y) draw3Line(85+y) keyline = 120 if mx >= 57 and mx <= 63: draw3Line(0+y) draw2Line(35+y) draw3Line(60+y) keyline = 95 if mx >= 52 and mx <= 56: draw2Line(0+y) draw3Line(25+y) keyline = 60 if mx >= 45 and mx <= 51: draw3Line(0+y) keyline = 35 drawDash2Line(keyline+y) if mn >= 33 and mn <= 39: draw3Line(keyline+25+y) if mn >= 28 and mn <= 32: draw3Line(keyline+25+y) draw2Line(keyline+60+y) if mn >= 21 and mn <= 27: draw3Line(keyline+25+y) draw2Line(keyline+60+y) draw3Line(keyline+85+y) if mn >= 16 and mn <= 20: draw3Line(keyline+25+y) draw2Line(keyline+60+y) draw3Line(keyline+85+y) draw2Line(keyline+120+y) if mn >= 9 and mn <= 15: draw3Line(keyline+25+y) draw2Line(keyline+60+y) draw3Line(keyline+85+y) draw2Line(keyline+120+y) draw3Line(keyline+145+y) if mn >= 4 and mn <= 8: draw3Line(keyline+25+y) draw2Line(keyline+60+y) draw3Line(keyline+85+y) draw2Line(keyline+120+y) draw3Line(keyline+145+y) draw2Line(keyline+180+y) if mn >= 1 and mn <= 3: draw3Line(keyline+25+y) draw2Line(keyline+60+y) draw3Line(keyline+85+y) draw2Line(keyline+120+y) draw3Line(keyline+145+y) draw2Line(keyline+180+y) canvas.create_line(70, keyline+205+y, 70+printareawidth, keyline+205+y, width=2) def draw_paper(y): #canvas.create_rectangle(55, 55+y, 55+paperwidth, 55+paperheigth+y, fill='black', outline='') canvas.create_rectangle(40, 50+y, 40+paperwidth, 50+paperheigth+y, fill=papercolor, outline='') #canvas.create_rectangle(70, 70+y, 70+printareawidth, 70+printareaheight+y, fill='', outline='blue') ### noteheads ### def black_key_right(x, y): # center coordinates, radius x0 = x y0 = y - 5 x1 = x + 5 y1 = y + 5 canvas.create_line(x0,y-20, x0,y, width=2) canvas.create_oval(x0, y0, x1, y1, outline='black', fill='black') def black_key_right_bf(x, y): # center coordinates, radius x0 = x y0 = y - 5 x1 = x - 10 y1 = y + 5 canvas.create_line(x0,y-20, x0,y, width=2) canvas.create_oval(x0, y0, x1, y1, outline='black', fill='black') def white_key_right_dga(x, y): # center coordinates, radius x0 = x y0 = y - 5 x1 = x + 10 y1 = y + 5 canvas.create_line(x0,y-20, x0,y, width=2) canvas.create_oval(x0, y0, x1, y1, outline="black", width=2, fill='white') def white_key_right_cefb(x, y): # center coordinates, radius x0 = x y0 = y - 3.5 x1 = x + 10 y1 = y + 3.5 canvas.create_line(x0,y-20, x0,y, width=2) canvas.create_oval(x0, y0, x1, y1, outline="black", width=2, fill='white') def black_key_left(x, y): # center coordinates, radius x0 = x y0 = y - 5 x1 = x + 5 y1 = y + 5 canvas.create_line(x0,y+20, x0,y, width=2) canvas.create_oval(x0, y0, x1, y1, outline='black', fill='black') # point canvas.create_oval(x0+3, y0+4, x1-3, y1-4, outline='white', fill='white') # point #canvas.create_polygon(x, y+5, x+10, y, x, y-5, outline='black', fill='black') # triangle #canvas.create_polygon(x, y+5, x+5, y, x, y-5, outline='black', fill='black') # diamond #canvas.create_oval(x0+3, y0+4, x1-3, y1-4, outline='', fill='white') def black_key_left_bf(x, y): # center coordinates, radius x0 = x y0 = y - 5 x1 = x - 10 y1 = y + 5 canvas.create_line(x0,y+20, x0,y, width=2) # canvas.create_polygon(x, y, x+5, y+5, x+10, y, x+5, y-5, outline='black', fill='black') # triangle #canvas.create_oval(x0-3, y0+4, x1+3, y1-4, outline='', fill='white') def white_key_left_dga(x, y): # center coordinates, radius x0 = x y0 = y - 5 x1 = x + 10 y1 = y + 5 canvas.create_line(x0,y+20, x0,y, width=2) canvas.create_oval(x0, y0, x1, y1, outline="black", width=2, fill='white') # point canvas.create_oval(x0+4, y0+4, x1-4, y1-4, outline="", fill='black') # point #canvas.create_polygon(x, y, x+5, y+5, x+10, y, x+5, y-5, outline="black", width=2, fill='white') # diamond #canvas.create_polygon(x, y+5, x+10, y, x, y-5, outline="black", width=2, fill='white') # triangle #canvas.create_oval(x0+4, y0+4, x1-4, y1-4, outline="", fill='black') def white_key_left_cefb(x, y): # center coordinates, radius x0 = x y0 = y - 3.5 x1 = x + 10 y1 = y + 3.5 canvas.create_line(x0,y+20, x0,y, width=2) canvas.create_oval(x0, y0, x1, y1, outline="black", width=2, fill='white') # point canvas.create_oval(x0+4, y0+4.5, x1-4, y1-4.5, outline="", fill='black') # point #canvas.create_polygon(x, y, x+5, y+3.5, x+10, y, x+5, y-3.5, outline="black", width=2, fill='white') # diamond #canvas.create_polygon(x, y+3.5, x+10, y, x, y-3.5, outline="black", width=2, fill='white') # triangle #canvas.create_oval(x0+4, y0+4.5, x1-4, y1-4.5, outline="", fill='black') def note_stop(x, y): x += 3.5 canvas.create_line(x-7,y-5, x, y, x-7,y+5, width=2, smooth=1) # orginal klavarscribo design #canvas.create_line(x,y, x,y+5, x,y+5, x,y-5, x,y-5, x,y, x,y, x-5,y+5, x-5,y+5, x,y, x,y, x-5,y-5, fill='black', width=1.5) # maybe the pianoscript design #canvas.create_line(x, y-10, x, y+10, fill='black', width=1.5, dash=3) def note_y_pos(note, mn, mx, cursy): ''' This function returns the position of c4 relative to 'cursy'(the y axis staff cursor) ''' if mx >= 81: c4 = 230 if mx >= 76 and mx <= 80: c4 = 195 if mx >= 69 and mx <= 75: c4 = 170 if mx >= 64 and mx <= 68: c4 = 135 if mx >= 57 and mx <= 63: c4 = 110 if mx >= 52 and mx <= 56: c4 = 75 if mx >= 45 and mx <= 51: c4 = 50 if mx >= 40 and mx <= 44: c4 = 15 if mx < 40: c4 = 15 return (cursy + c4) + (40 - note) * 5 def draw_note_active(x1, x2, y, linenr): x1 = event_x_pos(x1, linenr) x2 = event_x_pos(x2, linenr) canvas.create_rectangle(x1, y-5, x2, y+5, fill=midinotecolor, outline='')#e3e3e3 canvas.create_line(x2, y-5, x2, y+5, width=2) def event_x_pos(pos, linenr): newlinepos = newline_pos_list(grid, mpline) newlinepos.insert(0, 0) linelength = newlinepos[linenr] - newlinepos[linenr-1] factor = printareawidth / linelength pos = pos - newlinepos[linenr-1] xpos = pos * factor + 70 return xpos def prepare_file(string, startbracket, endbracket, replace): def replacer(s, newstring, index, nofail=False): # raise an error if index is outside of the string if not nofail and index not in range(len(s)): raise ValueError("index outside given string") # if not erroring, but the index is still not in the correct range.. if index < 0: # add it to the beginning return newstring + s if index > len(s): # add it to the end return s + newstring # insert the new string between "slices" of the original return s[:index] + newstring + s[index + 1:] findex = -1 for sym in string: findex += 1 if sym == startbracket: rindex = findex for i in string[findex+1:]: rindex += 1 if i == endbracket: break else: string = replacer(string, replace, rindex) return string def repeat_dot(x, y): # center coordinates, radius x0 = x y0 = y - 5 x1 = x + 5 y1 = y + 5 canvas.create_oval(x0, y0, x1, y1, outline='black', fill='black') def addmeas_processor(string): def measure_length(tsig, tickperquarter): tsig = tsig.split('/') w = 0 n = int(tsig[0]) d = int(tsig[1]) if d < 4: w = (n * d) / (d / 2) if d == 4: w = (n * d) / d if d > 4: w = (n * d) / (d * 2) return int(tickperquarter * w) string = string.split() length = measure_length(string[0], 256) grid = string[1] amount = string[2] return length, grid, amount def continuation_dot(x, y): x0 = x - 2 y0 = y - 2 x1 = x + 2 y1 = y + 2 canvas.create_oval(x0, y0, x1, y1, fill='black', outline='black') def create_mp_list(string): string = string.split(' ') lst = [] for i in string: lst.append(eval(i)) return lst def restart_program(): """Restarts the current program. Note: this function does not return. Any cleanup action (like saving data) must be done before calling this function.""" save_quest() python = sys.executable os.execl(python, python, * sys.argv) #----------------- # MAIN #----------------- ## score variables ## # titles: title = '' subtitle = '' composer = '' copyright = '' # settings: mpline = 4 systemspacing = 90 scale = 150 titlespace = 60 fillpage = 300 # fillpagetreshold printtitle = 1 printcomposer = 1 printcopyright = 1 measurenumbering = 1 # music: grid = [] msg = [] pagespace = [] scale_S = scale/100 ## constants ## paperheigth = 1123.0723781388479 * (scale_S) # a4 210x297 mm paperwidth = 794.0915805022156 * (scale_S) marginsx = 40 * (scale_S) marginsy = 60 * (scale_S) printareawidth = paperwidth - marginsx printareaheight = paperheigth - marginsy renderno = 0 def render(x): global scale_S, renderno, pagespace, title, subtitle, composer, copyright, mpline, systemspacing, scale, grid, msg, paperheigth, paperwidth, marginsy, marginsx, printareaheight, printareawidth, printtitle, printcomposer, printcopyright, measurenumbering grid = [] msg = [] title = '' subtitle = '' composer = '' copyright = '' pagespace = [] mpline = 4 systemspacing = 90 scale = 150 titlespace = 60 def reading(): global scale_S, renderno, pagespace, title, subtitle, composer, copyright, mpline, systemspacing, scale, grid, msg, paperheigth, paperwidth, marginsy, marginsx, printareaheight, printareawidth, printtitle, printcomposer, printcopyright, measurenumbering file = strip_file_from_comments(get_file()) msgprep = [] # read commands cmdstring = file index = -1 for sym in cmdstring: index += 1 if sym == '~': try: cmdname = '' cmdstr = '' for i in cmdstring[index+1:]: if i == '{': break else: cmdname += i for i in cmdstring[index+1+len(cmdname)+1:]: if i == '}': break else: cmdstr += i msgprep.append([index, cmdname, cmdstr]) except: pass # read music musicstring = prepare_file(file, '~', '}', ' ') index = -1 for sym in musicstring: index += 1 # note if sym in ['a', 'A', 'b', 'c', 'C', 'd', 'D', 'e', 'f', 'F', 'g', 'G']: if musicstring[index+1] in ['0', '1', '2', '3', '4', '5', '6', '7', '8']: if musicstring[index+2] == '-': msgprep.append([index, 'note', string2pitch(musicstring[index]+musicstring[index+1]), 'bound']) else: msgprep.append([index, 'note', string2pitch(musicstring[index]+musicstring[index+1]), 'loose']) # split if sym == '=': msgprep.append([index, 'split']) # cursor if sym == '_': dig = '' for i in musicstring[index+1:]: if i in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']: dig += i else: if dig == '': msgprep.append([index, 'cursor', 0]) break else: msgprep.append([index, 'cursor', eval(dig)]) break # durations if sym == 'W': if musicstring[index+1] == '.' and not musicstring[index+2] == '.': msgprep.append([index, 'dur', 'W*1.5']) elif musicstring[index+1] == '.' and musicstring[index+2] == '.': msgprep.append([index, 'dur', 'W*1.75']) else: msgprep.append([index, 'dur', 'W']) if sym == 'H': if musicstring[index+1] == '.' and not musicstring[index+2] == '.': msgprep.append([index, 'dur', 'H*1.5']) elif musicstring[index+1] == '.' and musicstring[index+2] == '.': msgprep.append([index, 'dur', 'H*1.75']) else: msgprep.append([index, 'dur', 'H']) if sym == 'Q': if musicstring[index+1] == '.' and not musicstring[index+2] == '.': msgprep.append([index, 'dur', 'Q*1.5']) elif musicstring[index+1] == '.' and musicstring[index+2] == '.': msgprep.append([index, 'dur', 'Q*1.75']) else: msgprep.append([index, 'dur', 'Q']) if sym == 'E': if musicstring[index+1] == '.' and not musicstring[index+2] == '.': msgprep.append([index, 'dur', 'E*1.5']) elif musicstring[index+1] == '.' and musicstring[index+2] == '.': msgprep.append([index, 'dur', 'E*1.75']) else: msgprep.append([index, 'dur', 'E']) if sym == 'S': if musicstring[index+1] == '.' and not musicstring[index+2] == '.': msgprep.append([index, 'dur', 'S*1.5']) elif musicstring[index+1] == '.' and musicstring[index+2] == '.': msgprep.append([index, 'dur', 'S*1.75']) else: msgprep.append([index, 'dur', 'S']) if sym == 'T': if musicstring[index+1] == '.' and not musicstring[index+2] == '.': msgprep.append([index, 'dur', 'T*1.5']) elif musicstring[index+1] == '.' and musicstring[index+2] == '.': msgprep.append([index, 'dur', 'T*1.75']) else: msgprep.append([index, 'dur', 'T']) # rest if sym == 'r': msgprep.append([index, 'rest']) # sort messages on index to ensure the order msgprep = sorted(msgprep, key=lambda x: x[0]) #default values for events hand = 'R' duration = 256 cursor = 0 for event in msgprep: # titles if event[1] == 'title': title = event[2] if event[1] == 'composer': composer = event[2] if event[1] == 'copyright': copyright = event[2] # invisible note if event[1] == 'invis': try: note = string2pitch(event[2]) msg.append([index, 'invis', cursor, 'dummy', note, hand]) except: ... # printtitle if event[1] == 'printtitle': try: val = eval(event[2]) printtitle = val except: ... # printcomposer if event[1] == 'printcomposer': try: val = eval(event[2]) printcomposer = val except: ... # printcopyright if event[1] == 'printcopyright': try: val = eval(event[2]) printcopyright = val except: ... # measurenumbering if event[1] == 'measurenumbering': try: val = eval(event[2]) measurenumbering = val except: ... # addmeas if event[1] == 'meas': length, grids, amount = addmeas_processor(event[2]) grid.append([length, eval(grids), eval(amount)]) # bpm if event[1] == 'bpm': msg.append([index, 'bpm', cursor, event[2]]) # hand if event[1] == 'hand': hand = event[2] # mpline if event[1] == 'mpline': try: mpline = create_mp_list(event[2]) except: pass # systemspace if event[1] == 'systemspace': try: systemspacing = eval(event[2]) except: pass # scale if event[1] == 'scale': scale = eval(event[2]) scale_S = scale/100 paperheigth = root.winfo_fpixels('1m') * 297 * (scale_S) # a4 210x297 mm paperwidth = root.winfo_fpixels('1m') * 210 * (scale_S) marginsx = 40 * (scale_S) marginsy = 60 * (scale_S) printareawidth = paperwidth - marginsx printareaheight = paperheigth - marginsy # cursor if event[1] == 'cursor': if event[2] == 0: cursor -= duration else: try: cursor = barline_pos_list(grid)[event[2]-1] except IndexError: print('ERROR: cursor out of range; try increasing the measure amount') # duration if event[1] == 'dur': duration = duration_converter(event[2]) # note if event[1] == 'note': msg.append([event[0], 'note', cursor, cursor+duration, event[2], hand, event[3]]) cursor += duration # rest if event[1] == 'rest': cursor += duration # split if event[1] == 'split': notes = [] time = 0 for i in reversed(msg): if i[1] == 'note' and notes == []: notes.append(i[4]) time = i[2] if i[1] == 'note' and i[2] == time: notes.append(i[4]) elif i[1] == 'note' and i[2] != time: break for i in notes: msg.append([event[0], 'split', cursor, cursor+duration, i]) cursor += duration # bar (all bartypes) if event[1] == 'bar': if event[2] == '|:': msg.append([event[0], 'bgn_rpt', cursor]) if event[2] == ':|': msg.append([event[0], 'end_rpt', cursor-0.1]) if event[2] == '|': msg.append([event[0], 'barline', cursor]) if event[2] == ';': msg.append([event[0], 'smalldash', cursor]) if event[2] == '[': msg.append([event[0], 'bgn_hook', cursor]) if event[2] == ']': msg.append([event[0], 'end_hook', cursor-0.1]) # text (all types) if event[1] == 'text': if event[2] == 'f': msg.append([event[0], 'dynamic', cursor, event[2]]) elif event[2] == 'ff': msg.append([event[0], 'dynamic', cursor, event[2]]) elif event[2] == 'fff': msg.append([event[0], 'dynamic', cursor, event[2]]) elif event[2] == 'ffff': msg.append([event[0], 'dynamic', cursor, event[2]]) elif event[2] == 'p': msg.append([event[0], 'dynamic', cursor, event[2]]) elif event[2] == 'pp': msg.append([event[0], 'dynamic', cursor, event[2]]) elif event[2] == 'ppp': msg.append([event[0], 'dynamic', cursor, event[2]]) elif event[2] == 'pppp': msg.append([event[0], 'dynamic', cursor, event[2]]) elif event[2] == 'mf': msg.append([event[0], 'dynamic', cursor, event[2]]) elif event[2] == 'mf': msg.append([event[0], 'dynamic', cursor, event[2]]) else: msg.append([event[0], 'text', cursor, event[2]]) if event[1] == 'textB': msg.append([event[0], 'textB', cursor, event[2]]) if event[1] == 'textI': msg.append([event[0], 'textI', cursor, event[2]]) #adding barline messages with correct begin time for barline in barline_pos_list(grid): msg.insert(0, ['index', 'barline', barline]) # adding grid messages icount = -1 cursor = 0 grdpart = [] for i in grid: oldpos = 0 for add in range(i[2]): length = i[0] divide = i[1] if divide == 0: divide = 1 amount = i[1] for line in range(amount): gridpart = length / divide time = cursor + (gridpart * (line+1)) grdpart.append(['dashline', time]) cursor += length for barline in grdpart: msg.insert(0, ['index', 'dash', barline[1]]) # sort on starttime of event to get the barlines in the right order msg.sort(key=lambda x: x[2]) ## placing messages in lists of 'lines' ## newlinepos = newline_pos_list(grid, mpline) mem = 0 msgs = msg msg = [] bottpos = 0 for newln in newlinepos: hlplst = [] for note in msgs: if note[2] >= bottpos and note[2] < newln: hlplst.append(note) msg.append(hlplst) bottpos = newln ## fitting the 'lines' into pages ## lineheight = [] for line in msg: notelst = [] for note in line: if note[1] == 'note' or note[1] == 'split' or note[1] == 'invis': notelst.append(note[4]) else: pass try: lineheight.append(staff_height(min(notelst), max(notelst))) except ValueError: lineheight.append(10) msgs = msg msg = [] cursy = 40 * (scale_S) pagelist = [] icount = 0 resspace = 0 for line, height in zip(msgs, lineheight): icount += 1 cursy += height + systemspacing if icount == len(lineheight):#if this is the last iteration if cursy <= printareaheight: pagelist.append(line) msg.append(pagelist) resspace = printareaheight - cursy pagespace.append(resspace) break elif cursy > printareaheight: msg.append(pagelist) pagelist = [] pagelist.append(line) msg.append(pagelist) pagespace.append(resspace) cursy = 0 resspace = printareaheight - cursy pagespace.append(resspace) break else: pass else: if cursy <= printareaheight:#does fit on paper pagelist.append(line) resspace = printareaheight - cursy elif cursy > printareaheight:#does not fit on paper msg.append(pagelist) pagelist = [] pagelist.append(line) cursy = 0 cursy += height + systemspacing pagespace.append(resspace) else: pass reading() def drawing(): canvas.delete('all') def paper(): counter = 0 cursy = 0 for page in msg: counter += 1 draw_paper(cursy) if printcopyright == 1: canvas.create_text(80, cursy+20+paperheigth, text=f'page {counter} of {len(msg)} | {title} | {copyright} - PianoScript sheet', anchor='w', font=("Courier", 16, "normal")) #canvas.create_rectangle(70, cursy+5+paperheigth, 70+printareawidth, cursy+35+paperheigth) cursy += paperheigth + 50 if printtitle == 1: canvas.create_text(70, 90, text=title, anchor='w', font=("Courier", 20, "normal")) if printcomposer == 1: canvas.create_text(70+printareawidth, 90, text=composer, anchor='e', font=("Courier", 20, "normal")) #canvas.create_line(10, 400, 10, 400+pagespace[1]) def note_active(): cursy = 90 + titlespace lcounter = 0 pcounter = 0 for page in msg: pcounter += 1 for line in page: lcounter += 1 #create linenotelist linenotelist = [] for note in line: if note[1] == 'note' or note[1] == 'split' or note[1] == 'invis': linenotelist.append(note[4]) if linenotelist: minnote = min(linenotelist) maxnote = max(linenotelist) else: minnote = 40 maxnote = 44 staffheight = staff_height(minnote, maxnote) for note in line: if note[1] == 'note': draw_note_active(note[2], note[3], note_y_pos(note[4], minnote, maxnote, cursy), lcounter) prevnote = note[3] if note[1] == 'split': draw_note_active(note[2]-10, note[3], note_y_pos(note[4], minnote, maxnote, cursy), lcounter) continuation_dot(event_x_pos(note[2], lcounter)+5, note_y_pos(note[4], minnote, maxnote, cursy)) if len(page) == 1: cursy += staffheight + systemspacing + (pagespace[pcounter-1] / (len(page))) elif pagespace[pcounter-1] < fillpage: cursy += staffheight + systemspacing + (pagespace[pcounter-1] / (len(page)-1)) elif pagespace[pcounter-1] >= fillpage: cursy += staffheight + systemspacing cursy = (paperheigth+50) * pcounter + 100 def barlines_and_text(): cursy = 90 + titlespace pcounter = 0 lcounter = 0 bcounter = 0 for page in msg: pcounter += 1 for line in page: lcounter += 1 #create linenotelist linenotelist = [] for note in line: if note[1] == 'note' or note[1] == 'split' or note[1] == 'invis': linenotelist.append(note[4]) if linenotelist: maxnote = max(linenotelist) minnote = min(linenotelist) else: maxnote = 44 minnote = 40 staffheight = staff_height(minnote, maxnote) for note in line: if note[1] == 'barline': bcounter += 1 canvas.create_line(event_x_pos(note[2], lcounter), cursy, event_x_pos(note[2], lcounter), cursy+staffheight, width=2) if measurenumbering == 1: canvas.create_text(event_x_pos(note[2]+12.5, lcounter), cursy-20, text=bcounter, anchor='w', font=('Terminal', 14, 'normal')) if note[1] == 'bgn_rpt': canvas.create_line(event_x_pos(note[2], lcounter), cursy, event_x_pos(note[2], lcounter), cursy+staffheight+40, width=2) repeat_dot(event_x_pos(note[2], lcounter)+5, cursy+staffheight+15) repeat_dot(event_x_pos(note[2], lcounter)+5, cursy+staffheight+30) if note[1] == 'end_rpt': canvas.create_line(event_x_pos(note[2], lcounter), cursy, event_x_pos(note[2], lcounter), cursy+staffheight+40, width=2) repeat_dot(event_x_pos(note[2], lcounter)-12.5, cursy+staffheight+15) repeat_dot(event_x_pos(note[2], lcounter)-12.5, cursy+staffheight+30) if note[1] == 'bgn_hook': canvas.create_line(event_x_pos(note[2], lcounter), cursy, event_x_pos(note[2], lcounter), cursy+staffheight+40, event_x_pos(note[2], lcounter), cursy+staffheight+40, event_x_pos(note[2], lcounter)+80, cursy+staffheight+40, width=2) if note[1] == 'end_hook': canvas.create_line(event_x_pos(note[2], lcounter), cursy, event_x_pos(note[2], lcounter), cursy+staffheight+40, event_x_pos(note[2], lcounter), cursy+staffheight+40, event_x_pos(note[2], lcounter)-80, cursy+staffheight+40, width=2) if note[1] == 'textB': canvas.create_text(event_x_pos(note[2], lcounter)+10, cursy+staffheight+25, text=note[3], anchor='w', font='Helvetica 18 bold') if note[1] == 'textI': canvas.create_text(event_x_pos(note[2], lcounter)+10, cursy+staffheight+25, text=note[3], anchor='w', font='Helvetica 18 italic') if note[1] == 'text': canvas.create_text(event_x_pos(note[2], lcounter)+10, cursy+staffheight+25, text=note[3], anchor='w', font='Helvetica 18') if note[1] == 'bpm': canvas.create_text(event_x_pos(note[2], lcounter)+10, cursy+staffheight+25, text=f'bpm = {note[3]}', anchor='w', font='Helvetica 18') canvas.create_line(70+printareawidth, cursy, 70+printareawidth, cursy+staffheight, width=2) if lcounter == len(newline_pos_list(grid, mpline)): canvas.create_line(70+printareawidth, cursy, 70+printareawidth, cursy+staffheight, width=5) if len(page) == 1: cursy += staffheight + systemspacing + (pagespace[pcounter-1] / (len(page))) elif pagespace[pcounter-1] < fillpage: cursy += staffheight + systemspacing + (pagespace[pcounter-1] / (len(page)-1)) elif pagespace[pcounter-1] >= fillpage: cursy += staffheight + systemspacing cursy = (paperheigth+50) * pcounter + 100 def staff(): cursy = 90 + titlespace pcounter = 0 lcounter = 0 for page in msg: pcounter += 1 for line in page: lcounter += 1 #create linenotelist linenotelist = [] for note in line: if note[1] == 'note' or note[1] == 'split' or note[1] == 'invis': linenotelist.append(note[4]) if linenotelist: maxnote = max(linenotelist) minnote = min(linenotelist) else: maxnote = 44 minnote = 40 draw_staff_lines(cursy, minnote, maxnote) #canvas.create_text(25, cursy+5, text=lcounter) staffheight = staff_height(minnote, maxnote) if len(page) == 1: cursy += staffheight + systemspacing + (pagespace[pcounter-1] / (len(page))) elif pagespace[pcounter-1] < fillpage: cursy += staffheight + systemspacing + (pagespace[pcounter-1] / (len(page)-1)) elif pagespace[pcounter-1] >= fillpage: cursy += staffheight + systemspacing cursy = (paperheigth+50) * pcounter + 100 def note_start(): black = [2, 5, 7, 10, 12, 14, 17, 19, 22, 24, 26, 29, 31, 34, 36, 38, 41, 43, 46, 48, 50, 53, 55, 58, 60, 62, 65, 67, 70, 72, 74, 77, 79, 82, 84, 86] white_dga = [6,11,13,18,23,25,30,35,37,42,47,49,54,59,61,66,71,73,78,83,85,88] white_be = [3,8,15,20,27,32,39,44,51,56,63,68,75,80,87] # possible typos white_cf = [1,4,9,16,21,28,33,40,45,52,57,64,69,76,81] # possible typos cursy = 90 + titlespace pcounter = 0 lcounter = 0 for page in msg: pcounter += 1 for line in page: lcounter += 1 # create max/min note variables for line linenotelist = [] for note in line: if note[1] == 'note' or note[1] == 'split' or note[1] == 'invis': linenotelist.append(note[4]) if linenotelist: minnote = min(linenotelist) maxnote = max(linenotelist) else: minnote = 40 maxnote = 44 staffheight = staff_height(minnote, maxnote) notelst = [] for note in line: if note[1] == 'note': notelst.append(note) notelst.sort(key=lambda x: x[0]) old_x = 0 old_y = 0 boundloose = 0 for note in notelst: if note[1] == 'note': #note_stop(event_x_pos(note[3], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)) if note[4] in white_dga: if note[5] == 'R': white_key_right_dga(event_x_pos(note[2], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)) for dot in notelst: if round(dot[2], 0) < round(note[2], 0) and round(dot[3], 0) > round(note[2], 0) and dot[5] == 'R': continuation_dot(event_x_pos(note[2], lcounter)+5, note_y_pos(dot[4], minnote, maxnote, cursy)) elif note[5] == 'L': white_key_left_dga(event_x_pos(note[2], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)) for dot in notelst: if round(dot[2], 0) < round(note[2], 0) and round(dot[3], 0) > round(note[2], 0) and dot[5] == 'L': continuation_dot(event_x_pos(note[2], lcounter)+5, note_y_pos(dot[4], minnote, maxnote, cursy)) else: pass if note[4] in white_cf: if note[5] == 'R': white_key_right_cefb(event_x_pos(note[2], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)-1.5) for dot in notelst: if round(dot[2], 0) < round(note[2], 0) and round(dot[3], 0) > round(note[2], 0) and dot[5] == 'R': continuation_dot(event_x_pos(note[2], lcounter)+5, note_y_pos(dot[4], minnote, maxnote, cursy)) elif note[5] == 'L': white_key_left_cefb(event_x_pos(note[2], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)-1.5) for dot in notelst: if round(dot[2], 0) < round(note[2], 0) and round(dot[3], 0) > round(note[2], 0) and dot[5] == 'L': continuation_dot(event_x_pos(note[2], lcounter)+5, note_y_pos(dot[4], minnote, maxnote, cursy)) else: pass if note[4] in white_be: if note[5] == 'R': white_key_right_cefb(event_x_pos(note[2], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)+1.5) for dot in notelst: if round(dot[2], 0) < round(note[2], 0) and round(dot[3], 0) > round(note[2], 0) and dot[5] == 'R': continuation_dot(event_x_pos(note[2], lcounter)+5, note_y_pos(dot[4], minnote, maxnote, cursy)) elif note[5] == 'L': white_key_left_cefb(event_x_pos(note[2], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)+1.5) for dot in notelst: if round(dot[2], 0) < round(note[2], 0) and round(dot[3], 0) > round(note[2], 0) and dot[5] == 'L': continuation_dot(event_x_pos(note[2], lcounter)+5, note_y_pos(dot[4], minnote, maxnote, cursy)) else: pass for note in notelst: if note[1] == 'note': if note[4] in black: if note[5] == 'R': black_key_right(event_x_pos(note[2], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)) for dot in notelst: if round(dot[2], 0) < round(note[2], 0) and round(dot[3], 0) > round(note[2], 0) and dot[5] == 'R': continuation_dot(event_x_pos(note[2], lcounter)+5, note_y_pos(dot[4], minnote, maxnote, cursy)) elif note[5] == 'L': black_key_left(event_x_pos(note[2], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)) for dot in notelst: if round(dot[2], 0) < round(note[2], 0) and round(dot[3], 0) > round(note[2], 0) and dot[5] == 'L': continuation_dot(event_x_pos(note[2], lcounter)+5, note_y_pos(dot[4], minnote, maxnote, cursy)) else: pass if boundloose == 1: if note[5] == 'R': canvas.create_line(old_x, old_y, event_x_pos(note[2], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)-20, width=3) elif note[5] == 'L': canvas.create_line(old_x, old_y, event_x_pos(note[2], lcounter), note_y_pos(note[4], minnote, maxnote, cursy)+20, width=3) if note[6] == 'bound': boundloose = 1 old_x = event_x_pos(note[2], lcounter) if note[5] == 'R': old_y = note_y_pos(note[4], minnote, maxnote, cursy)-20 elif note[5] == 'L': old_y = note_y_pos(note[4], minnote, maxnote, cursy)+20 else: pass elif note[6] == 'loose': boundloose = 0 else: pass if len(page) == 1: cursy += staffheight + systemspacing + (pagespace[pcounter-1] / (len(page))) elif pagespace[pcounter-1] < fillpage: cursy += staffheight + systemspacing + (pagespace[pcounter-1] / (len(page)-1)) elif pagespace[pcounter-1] >= fillpage: cursy += staffheight + systemspacing cursy = (paperheigth+50) * pcounter + 100 def grid_lines(): cursy = 90 + titlespace pcounter = 0 lcounter = 0 for page in msg: pcounter += 1 for line in page: lcounter += 1 # create max/min note variables for line linenotelist = [] for note in line: if note[1] == 'note' or note[1] == 'split' or note[1] == 'invis': linenotelist.append(note[4]) if linenotelist: minnote = min(linenotelist) maxnote = max(linenotelist) else: minnote = 40 maxnote = 44 staffheight = staff_height(minnote, maxnote) for gridline in line: if gridline[1] == 'dash': canvas.create_line(event_x_pos(gridline[2], lcounter), cursy, event_x_pos(gridline[2], lcounter), cursy+staffheight, dash=(6, 6)) if gridline[1] == 'smalldash': canvas.create_line(event_x_pos(gridline[2], lcounter), cursy+(staffheight*0.20), event_x_pos(gridline[2], lcounter), cursy+staffheight-(staffheight*0.20), dash=(2, 2)) if len(page) == 1: cursy += staffheight + systemspacing + (pagespace[pcounter-1] / (len(page))) elif pagespace[pcounter-1] < fillpage: cursy += staffheight + systemspacing + (pagespace[pcounter-1] / (len(page)-1)) elif pagespace[pcounter-1] >= fillpage: cursy += staffheight + systemspacing cursy = (paperheigth+50) * pcounter + 100 # function order paper() note_active() barlines_and_text() staff() grid_lines() note_start() drawing() renderno += 1 canvas.create_text(20, 20, text='render: '+str(renderno)) canvas.configure(scrollregion=bbox_offset(canvas.bbox("all"))) return len(msg) #------------------ # EXPORT FUNCTIONS #------------------ def exportPS(): print('exportPS') f = filedialog.asksaveasfile(mode='w', parent=root, filetypes=[("Postscript","*.ps")], initialfile=title) if f: name = f.name[:-3] counter = 0 for export in range(render('q')): counter += 1 print('printing page ', counter) canvas.postscript(file=f"{name} p{counter}.ps", colormode='gray', x=40, y=50+(export*(paperheigth+50)), width=paperwidth, height=paperheigth, rotate=False) os.remove(f.name) else: pass return def exportPDF(): print('exportPDF') f = filedialog.asksaveasfile(mode='w', parent=root, filetypes=[("pdf file","*.pdf")], initialfile=title, initialdir='~/Desktop') if f: n = render('q') pslist = [] for rend in range(n): canvas.postscript(file=f"tmp{rend}.ps", x=40, y=50+(rend*(paperheigth+50)), width=paperwidth, height=paperheigth, rotate=False) process = subprocess.Popen(["ps2pdfwr", "-sPAPERSIZE=a4", "-dFIXEDMEDIA", "-dEPSFitPage", f"tmp{rend}.ps"]) process.wait() os.remove(f"tmp{rend}.ps") pslist.append(f"tmp{rend}.pdf") cmd = 'pdfunite ' for i in range(len(pslist)): cmd += pslist[i] + ' ' cmd += f'"{f.name}"' process = subprocess.Popen(cmd, shell=True) process.wait() for x in pslist: os.remove(x) return else: return # Menu menubar = Menu(root, relief='flat', bg=_bg) root.config(menu=menubar) fileMenu = Menu(menubar, tearoff=0) fileMenu.add_command(label='new', command=new_file) fileMenu.add_command(label='open', command=open_file) fileMenu.add_command(label='save', command=save_file) fileMenu.add_command(label='save as', command=save_as) fileMenu.add_separator() submenu = Menu(fileMenu, tearoff=0) submenu.add_command(label="postscript", command=exportPS) submenu.add_command(label="pdf (linux only)", command=exportPDF) fileMenu.add_cascade(label='export', menu=submenu, underline=0) fileMenu.add_separator() fileMenu.add_command(label="Preferences", underline=0, command=def_score_settings) fileMenu.add_command(label="Refresh app", underline=0, command=restart_program) fileMenu.add_separator() fileMenu.add_command(label="Exit", underline=0, command=quit_editor) menubar.add_cascade(label="Menu", underline=0, menu=fileMenu) def autosave(): root.after(60000, autosave) if filepath == 'New': return save_file() new_file() autosave() root.bind('<Key>', render) root.bind('<F11>', fullscreen) root.mainloop()moonlight.pnoscript: //titles: ~title{Moonlight Sonata} ~composer{L. Beethoven} ~copyright{public license 2021} //grid: ~meas{4/4 4 69} //settings: ~mpline{5} ~systemspace{70} //music: // M1-20 // { ~hand{R} _1 ~text{4/4}~dur{Q/3}G3C4e4 G3C4e4 G3C4e4 G3C4e4 _2 G3C4e4 G3C4e4 G3C4e4 G3C4e4 _3 a3C4e4 a3C4e4 a3d4F4 a3d4F4 _4 G3c4F4 G3C4e4 G3C4D4 F3c4D4 _5 e3G3C4 G3C4e4 G3C4e4 G3C4e4 Q_ ~dur{E+S}G4 SG4 __; _6 ~dur{Q/3}G3D4F4 G3D4F4 G3D4F4 G3D4F4 _6 ~dur{H+Q}G4 ~dur{E+S}G4 SG4 _6 QrrrEr; _7 ~dur{Q/3}G3C4e4 G3C4e4 a3C4F4 a3C4F4 _7 HG4 a4 _8 ~dur{Q/3}G3b3e4 G3b3e4 a3b3D4 a3b3D4 _8 HG4 QF4 b4 _9 ~dur{Q/3}G3b3e4 G3b3e4 G3b3e4 G3b3e4 _9 ~dur{Q/3*2}e4 _10 ~dur{Q/3}g3b3e4 g3b3e4 g3b3e4 g3b3e4 Q_ ~dur{E+S}g4 Sg4 __; _11 ~dur{Q/3}g3b3f4 g3b3f4 g3b3f4 g3b3f4 _11 ~dur{H+Q}g4 ~dur{E+S}g4 Sg4 __; _12 ~dur{Q/3}g3c4e4 g3b3e4 g3C4e4 F3C4e4 _12 ~dur{H+Q}g4 QF4 _13 ~dur{Q/3}F3b3d4 F3b3d4 g3b3C4 e3b3C4 _13 HF4 Qg4 e4 _14 ~dur{Q/3}F3b3d4 F3b3d4 F3A3C4 F3A3C4 _14 HF4 F4 _15 ~dur{Q/3}b3d4F4 b3d4F4 b3D4F4 b3D4F4 _15 Qb3 r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in a list? - j.crater - May-29-2021 Hey, sorry about late response, haven't been around much. I didn't setup a venv with Tkinter. But I can tell you got the lines of code count up pretty well! Do you have a github account for the project? |