# -*- coding: ISO-8859-1 -*-
""" capellaScript -- 12.10.2005 Andreas Herzog
>>> Rhythmusnotation

    Mit diesem Skript kann die Schriftart capella-Rhythmusnotation angesteuert werden.|
    |
    Damit das Skript vernünftig funktioniert muss die Schriftart capella-Rhythmusnotation.ttf installiert werden, in der capella.dat als Stil angemeldet werden und unter Extras-Optionen-Allgemein als Stil ausgewählt werden.
    ||
    Version 1.0    |
    
    |
    
        |

<<<

# Version 1.0 = Ursprungsversion
# Version 1.0a= minimale Erweiterung der Bundbezeichnungen
# Version 1.0b= minimale Veränderung der Saitenbezeichnungen 

"""

import xml.dom
import string


from xml.dom.minidom import NodeList


RegisterDarstellung = [' ','Rückschlag','Abschlag','Rückschlag a.S. ','Abschlag a.S.','Bass-Attack ','Brushing','Dämpfer l.H.','Hammering','Pulling','Rasguado','Slide','Flageolett','Wechselbass','Power Chord']
RegisterCode = [[' ','1.2','-2','1','capella-Rhythmusnotation'],['Z','1.0','-2.5','12','capella-Rhythmusnotation'],['Y','1.0','-2.5','12','capella-Rhythmusnotation'],[chr(162),'1.0','-2.5','12','capella-Rhythmusnotation'],[chr(160),'1.0','-2.5','12','capella-Rhythmusnotation'],[chr(161),'1.0','-2.5','12','capella-Rhythmusnotation'],[chr(164),'1.0','-2.5','12','capella-Rhythmusnotation'],[chr(163),'1.0','-2.35','12','capella-Rhythmusnotation'],['H','1.0','-2.5','5','TimesNewRoman'],['P','1.0','-2.5','5','TimesNewRoman'],['RAS','1.0','-2.5','5','TimesNewRoman'],['SL','1.0','-2.5','5','TimesNewRoman'],['Flag','1.0','-2.5','5','TimesNewRoman'],['WB','1.0','-2.5','5','TimesNewRoman'],['PC','1.0','-2.5','5','TimesNewRoman']]
KlammerCode = [['(      ','1.4','-2.8','6'],['    )','0.9','-2.8','6']]
Kopfformen = ['','square','crossCircle','crossCircle','crossCircle','triangle','diamond','none','none','none']
KopfBezeichnungen = ['nicht ändern','Rhythmik-Schlag', 'Dämpf-Schlag','Stopp-Schlag','Rasgueado-Stop-Dämpfer','Dämpfer flache Hand','halber / ganzer Balken','schlanker Balken','Slide','Saite/Bund:']
Abstaende = ['1.2','1.4','1.5','1.6','1.8']
KorrekturWerte = ['-1.0','-0.5','0','0.5','1.0']
Schluesselarten = ['kein Schlüssel','Diskant','Bass','Alle','Zentrum','Saiten:']
ArtikulationsArten = ['ohne','Staccato','Tenuto','Staccato+Tenuto','normaler Akzent','starker Akzent','weicher Schlag','schwerer Schlag']
ArtikulationCode= [['','','',''],['.','0.33','-4.46','19'],['-','1.03125','-4.15','17'],[['.','0.33','-4.78','19'],['-','1.03125','-4.15','17']],[chr(202),'0.94','-4.45','15'],[chr(203),'0.94','-4.45','15'],[chr(204),'0.94','-4.4','15'],['=','0.94','-4.0','7']]
SchluesselZahlen=['1/2','2/3','3/4','4/5','5/6']
KlammerAbstaende = ['0','0.3','0.4','0.5','0.6']
SaitenBezeichnungen = ['E','A','D','g','h','e']
BundBezeichnungen = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21']

# doc = [] # parentNode von score

def latin1_e(u):
    return u.encode('Latin-1')
def latin1_d(u):
    return u.decode('Latin-1')
    
class settings:
    def __init__(self):
        self.Leer = 0   
        
  
     
defaults = settings()
dlgSet = settings()

options = ScriptOptions() 
opt = options.get()

def Test(text):
	messageBox('Test',str(text))

class settings:
    def __init__(self):
    	self.AbstandRegister = 1.6
    	self.Kopfform=1
    	self.AutoAnpassen = 0
    	self.KlammerAbstand = 0

def getOptions():
    global AbstandRegister, Kopfform, AutoAnpassen, KlammerAbstand
    
    AbstandRegister	= eval(opt.get('AbstandRegister',str(AbstandRegister)))
    Kopfform = eval(opt.get('Kopfform',str(Kopfform)))
    AutoAnpassen = eval(opt.get('AutoAnpassen',str(AutoAnpassen)))
    KlammerAbstand = eval(opt.get('KlammerAbstand',str('KlammerAbstand')))

def setOptions():
    global dlgSet

    opt.update(dict(AbstandRegister= str(AbstandRegister),
	   				Kopfform = str(Kopfform),
	   				AutoAnpassen = str(AutoAnpassen),
	   				KlammerAbstand = str(KlammerAbstand)
	   				
                    ))
                

    options.set(opt)
    
def setScoreStyle(score):  
	infoTags = 0
	commentTags = 0  
	newStyle = latin1_d('<style> Rhythmusnotation </style>')   ### Zuweisung an einer Stelle
	for info in score.getElementsByTagName('info'):
		infoTags = 1
		for comment in info.getElementsByTagName('comment'):                            # falls Kommentar vorhanden
			commentTags = 1
			comment1 = comment.firstChild
			content = comment1.nodeValue
			start1 = string.find(content,'<style>')                                 # 1.Abschnitt des Kommentars bis zur vorhandenen Stil-Anweisung
			start2 = string.find(content,'</style>')                                # 2.Abschnitt des Kommentars ab der vorhandenen Stil-Anweisung
			length = len(content)
			comment.parentNode.removeChild(comment)                                 # Löschen des bisherigen Kommentars
			comment2= addNewElementNode(info,'comment')
			if start1 > -1:
				textNode = doc.createTextNode(content[:start1] + newStyle + content[(start2+8):]) # Generierung des neuen Kommentars bei vorhandener Stil-Anweisung
			if start1 == -1:
				textNode = doc.createTextNode(content + newStyle)                                                                 # Generierung des neuen Kommentars bei bisher fehlender Stil-Anweisung
			comment2.appendChild(textNode)
			if commentTags == 0:                                                            # falls kein Kommentar vorhanden
				commentNew = addNewElementNode(info,'comment')
				textNodeNew = doc.createTextNode(newStyle)
				commentNew.appendChild(textNodeNew)
	if infoTags == 0:                                      									# falls keine Informationen zur Partitur bisher vorliegen
			infoNew = doc.createElement('info')                           
			score.insertBefore(infoNew, score.firstChild)            
			commentNew = addNewElementNode(infoNew,'comment')
			textNodeNew = doc.createTextNode(newStyle)
			commentNew.appendChild(textNodeNew)

	return True    
	
def addElementNode(el,tagName):
    # add new Node to el if Node "tagName" does not exist
    # otherwise return the existing Node
    global doc
    childs = el.childNodes
    for n in range(childs.length):
        if childs[n].nodeType ==childs[n].ELEMENT_NODE and childs[n].tagName == tagName:
            return childs[n]
    newChild = doc.createElement(tagName)
    el.appendChild(newChild)
    return newChild
    

def addNewElementNode(el,tagName):
    # add new Node with tagName "tagName" to el 
    global doc
    newChild = doc.createElement(tagName)
    el.appendChild(newChild)
    return newChild

    
def getDialogValues1():
	
    global NurLoeschen,Register1,Register2,Register3, Register4
    global KlammerAuf1,KlammerAuf2, KlammerAuf3, KlammerAuf4, KlammerZu1, KlammerZu2, KlammerZu3, KlammerZu4
    global SingleLine, Kopfform, RhythmusnotationAbstaende, Korrektur, AbstandRegister, KorrekturWert, Kopfform, Glissando
    global Schluessel, SchluesselZahl,Artikulation, InfoComment, AutoAnpassen, KlammerAbstand
    global SaitenNummer, BundNummer
    

    lableer1 = Label('    ', width = 2)
    lableer2 = Label('       ', width = 2)
    lableer3 = Label('    ', width = 0)
    
    lableerKlein = Label('  ',width = 2)
    lab0 = Label('Abstände:', width = 4)
    labKorrektur = Label('Horizontale Korrektur:            ', width = 4)
    labAbstand =   Label('Abstände zwischen Zeichen:', width = 4)
    
    NurLoeschenCheck = CheckBox('Nur Elemente dieses Skripts löschen!', value=0)
    SingleLineCheck = CheckBox('1-Linien-Zeile', value=1)
    InfoCommentCheck = CheckBox('Style Rhythmusnotation mit Partitur verknüpfen', value=1)
    GlissandoRadio = Radio(['normaler Hals','Arpeggio-Hals','kein Hals'],text='Hals', value=Glissando)
    radKopfform =  Radio(KopfBezeichnungen,  padding = 8, value=Kopfform)
    
    KorrekturRadio = Radio(KorrekturWerte, value=KorrekturWert, width=40)
    
    KlammerAuf1Check = CheckBox('(', value=KlammerAuf1)
    KlammerAuf2Check = CheckBox('(', value=KlammerAuf2)
    KlammerAuf3Check = CheckBox('(', value=KlammerAuf3)
    KlammerAuf4Check = CheckBox('(', value=KlammerAuf4)
        
    KlammerZu1Check = CheckBox(')', value=KlammerZu1)
    KlammerZu2Check = CheckBox(')', value=KlammerZu2)
    KlammerZu3Check = CheckBox(')', value=KlammerZu3)
    KlammerZu4Check = CheckBox(')', value=KlammerZu4)

    
    KlammerBox1 = HBox([KlammerAuf1Check,KlammerZu1Check], padding = 8)
    KlammerBox2 = HBox([KlammerAuf2Check,KlammerZu2Check], padding = 8)
    KlammerBox3 = HBox([KlammerAuf3Check,KlammerZu3Check], padding = 8)
    KlammerBox4 = HBox([KlammerAuf4Check,KlammerZu4Check], padding = 8)   
    
    Spalte1Box = ComboBox(RegisterDarstellung, value=Register1, width=11)
    Spalte2Box = ComboBox(RegisterDarstellung, value=Register2, width=11)
    Spalte3Box = ComboBox(RegisterDarstellung, value=Register3, width=11)
    Spalte4Box = ComboBox(RegisterDarstellung, value=Register4, width=11)    
    
    
    AbstandRegisterRadio = Radio(Abstaende, value=AbstandRegister, width=40)
    AbstandKlammerRadio = Radio(KlammerAbstaende, value=KlammerAbstand, width=40)
    AutoAnpassenCheck = CheckBox('Notenhöhe automatisch anpassen', value=AutoAnpassen)
    
    vbox10 = VBox([Spalte1Box, KlammerBox1], padding = 3)
    vbox20 = VBox([Spalte2Box, KlammerBox2], padding = 3)
    vbox30 = VBox([Spalte3Box, KlammerBox3], padding = 3)
    vbox40 = VBox([Spalte4Box, KlammerBox4], padding = 3)
    
    hbox10 = HBox([vbox10], padding = 16, text = '1.Spalte')
    hbox20 = HBox([vbox20], padding = 16, text = '2.Spalte')
    hbox30 = HBox([vbox30], padding = 16, text = '3.Spalte')
    hbox40 = HBox([vbox40], padding = 16, text = '4.Spalte')
    
    SchluesselRadio = Radio(Schluesselarten ,value=Schluessel, width=40)
    SchluesselBox = ComboBox(SchluesselZahlen, value=0, width=10)
    ArtikulationsRadio = Radio(ArtikulationsArten, text='Artikulation setzen',value=Artikulation, width=40)
    SaitenBox = ComboBox(SaitenBezeichnungen, value=SaitenNummer, width=5)
    BundBox = ComboBox(BundBezeichnungen, value=BundNummer, width=5)
 
    hbox11= HBox([lableerKlein, SchluesselBox],padding = 0)
    hbox12= HBox([lableerKlein, SaitenBox, BundBox],padding = 0)
    vbox11 = VBox([SchluesselRadio,hbox11],padding = 8)
    hbox11 = HBox([vbox11],text='Schlüssel einfügen', padding = 0)
    vbox13 = VBox([radKopfform,hbox12], padding = 0) 
    hbox13 = HBox([vbox13],text='Kopfform', padding = 0)  
    hbox14 = HBox([ArtikulationsRadio,hbox11], padding = 4)	
    vbox14 = VBox([hbox14,InfoCommentCheck,AutoAnpassenCheck], padding = 4)
        
    hbox21 = HBox([AbstandRegisterRadio, lableer1], text = 'Zeichenabstand',padding = 4)
    hbox22 = HBox([KorrekturRadio], text = 'Korrekturwert',padding = 4)
    hbox23 = HBox([AbstandKlammerRadio,lableer2], text = 'Klammerabstand',padding = 4)
    hbox24 = HBox([lableer3, SingleLineCheck], padding=0) 
    vbox24 = VBox([GlissandoRadio,hbox24 ], padding = 8)
    
    hbox01 = HBox([hbox10, hbox20, hbox30, hbox40], text = 'Schlagsymbole',padding = 8)
    hbox02 = HBox([hbox21,hbox22,hbox23,vbox24],padding = 8)
    hbox03 = HBox([hbox13,vbox14], padding = 8)

    
    dialogbox= VBox([hbox01,hbox02, hbox03], padding = 12)
    
    dlg = Dialog('Bitte wählen: ', dialogbox)

	
    if dlg.run():
    	NurLoeschen = NurLoeschenCheck.value()
    	Register1 = Spalte1Box.value()
    	Register2 = Spalte2Box.value()
    	Register3 = Spalte3Box.value()
    	Register4 = Spalte4Box.value()
    	KlammerAuf1 = KlammerAuf1Check.value()
    	KlammerAuf2 = KlammerAuf2Check.value()
    	KlammerAuf3 = KlammerAuf3Check.value()
    	KlammerAuf4 = KlammerAuf4Check.value()
    	KlammerZu1 = KlammerZu1Check.value()
    	KlammerZu2 = KlammerZu2Check.value()
    	KlammerZu3 = KlammerZu3Check.value()
    	KlammerZu4 = KlammerZu4Check.value()

    	SingleLine = SingleLineCheck.value()
    	KorrekturWert = KorrekturRadio.value()
    	AbstandRegister = AbstandRegisterRadio.value()
    	Glissando = GlissandoRadio.value()
    	Schluessel = SchluesselRadio.value()
    	Artikulation = ArtikulationsRadio.value()
    	SchluesselZahl = SchluesselBox.value()
    	InfoComment = InfoCommentCheck.value()
    	AutoAnpassen = AutoAnpassenCheck.value()
    	KlammerAbstand = AbstandKlammerRadio.value()
    	SaitenNummer = SaitenBox.value()
    	BundNummer = BundBox.value()

    	Kopfform = radKopfform.value()

       	return True
    else:
        return False

def getDialogValues2():
	global Schluessel, SchluesselZahl
    
	lableerKlein = Label('  ',width = 2)
	lableer = Label('                        ', width = 4)
        
	Schluesselarten[0] = 'Schlüssel löschen'   
	SchluesselBox = ComboBox(SchluesselZahlen, value=SchluesselZahl, width=10)
	SchluesselRadio = Radio(Schluesselarten,value=Schluessel, width=40)
	SchluesselZahl = SchluesselBox.value()
    
	hbox1= HBox([lableerKlein, SchluesselBox],padding = 0)
	vbox1 = VBox([SchluesselRadio,hbox1],padding = 8) 
	hbox1 = HBox([vbox1],text='Schlüssel einfügen', padding = 0)   
	vbox2= VBox([hbox1 ], padding = 12)
    
	dlg = Dialog('Bitte wählen: ', vbox2)
	
	if dlg.run():
		Schluessel = SchluesselRadio.value()
		SchluesselZahl=SchluesselBox.value()
		return True
	else:
		return False
        
def getValueOfString(input, standard, Fehler):
	Fehler = 0
	i = 0
	while i < len(input):
		if input[i] in ['0','1','2','3','4','5','6','7','8','9','.','-','+']:
    			eins=1
    		else:
    			Fehler = 1
    		i+=1
    	if Fehler == 0:
    		output= string.atof(input)
    	if Fehler == 1:
    		messageBox('Fehler', Fehler)
    		output=standard
	return output
        
def newText(drawObjects,  width, height, contents, fontheight,IndexTag, face):
	global Gruppierung, FontGroesse, LineWidth, StrichAbstand
	Gruppierung = 0
	
	if Gruppierung == 0:
		drawObj = addNewElementNode(drawObjects,'drawObj')
	
 	if Gruppierung == 1:
 		groupDrawObj = addElementNode(drawObjects,'drawObj')
		group = addElementNode(groupDrawObj,'group')	
		drawObj = addNewElementNode(group,'drawObj')
		
	text = addElementNode(drawObj,'text')	
		
	text.setAttribute('x',width)
	text.setAttribute('y',height)

	content = addNewElementNode(text,'content')
	textNode = doc.createTextNode(latin1_d(contents))
	#messageBox('Test', contents)
	content.appendChild(textNode)
	text.setAttribute('align','center')
	GraficalTag = '56294-25'+IndexTag
	basic = addElementNode(drawObj,'basic')							
	basic.setAttribute('tag',GraficalTag)
	
	if Gruppierung == 1:
		basic = addElementNode(groupDrawObj,'basic')							
		basic.setAttribute('tag','56294-2500')    
	font = addNewElementNode(text,'font')
	font.setAttribute('face',face)
	font.setAttribute('color','')
	font.setAttribute('height',fontheight)
	font.setAttribute('charSet','1')
	
	font.setAttribute('pitchAndFamily','2')	 

	return text

def newLine(drawObjects,width1, width2, height1, height2, lineWidth, tag):
	drawObj = addNewElementNode(drawObjects,'drawObj')
	line = addNewElementNode(drawObj,'line')
	line.setAttribute('x1',str(width1))  
	line.setAttribute('x2',str(width2))
	line.setAttribute('y1',str(height1))
	line.setAttribute('y2',str(height2))
	line.setAttribute('lineWidth',str(0.05 * lineWidth))
	basic = addElementNode(line,'basic')
	GraficalTag = '56294-25'+tag							
	basic.setAttribute('tag',GraficalTag)
	
	return line

def newWavyLine(drawObjects,width1, width2, height1, height2, waveLen, tag):
	drawObj = addNewElementNode(drawObjects,'drawObj')
	wavyline = addNewElementNode(drawObj,'wavyLine')
	wavyline.setAttribute('x1',str(width1))  
	wavyline.setAttribute('x2',str(width2))
	wavyline.setAttribute('y1',str(height1))
	wavyline.setAttribute('y2',str(height2))
	wavyline.setAttribute('waveLen',str(waveLen))
	wavyline.setAttribute('fullWaves','false')
	basic = addElementNode(wavyline,'basic')
	GraficalTag = '56294-25'+tag							
	basic.setAttribute('tag',GraficalTag)
	
	return wavyline

def newEllipse(drawObjects,width1, width2, height1, height2, tag):
	drawObj = addNewElementNode(drawObjects,'drawObj')
	ellipse = addNewElementNode(drawObj,'ellipse')
	ellipse.setAttribute('x1',str(width1))  
	ellipse.setAttribute('x2',str(width2))
	ellipse.setAttribute('y1',str(height1))
	ellipse.setAttribute('y2',str(height2))
	basic = addElementNode(drawObj,'basic')
	GraficalTag = '56294-25'+tag							
	basic.setAttribute('tag',GraficalTag)
	
	return ellipse

def newTriangle(drawObjects,width1, width2, width3, height1, height2,height3, tag):
	drawObj = addNewElementNode(drawObjects,'drawObj')
	triangle = addNewElementNode(drawObj,'polygon')
	triangle.setAttribute('filled','true')
	points = addNewElementNode(triangle,'points')
	point2 = addNewElementNode(points,'point')
	point3 = addNewElementNode(points,'point')
	point4 = addNewElementNode(points,'point')
	point2.setAttribute('x',str(width1))  
	point3.setAttribute('x',str(width2))
	point4.setAttribute('x',str(width3))	
	point2.setAttribute('y',str(height1))
	point3.setAttribute('y',str(height2))
	point4.setAttribute('y',str(height3))	

	basic = addElementNode(drawObj,'basic')
	GraficalTag = '56294-25'+tag							
	basic.setAttribute('tag',GraficalTag)
	
	
	return triangle
	
def getContent(chord):															# Holt die Werte einer eventuell bestehende Generalbass-
	global Register1, Register2, Register3, Register4	 						# bezifferung zurück
	global KlammerAuf1, KlammerAuf2, KlammerAuf3, KlammerAuf4, KlammerZu1, KlammerZu2, KlammerZu3, KlammerZu4
	global AbstandRegister, Korrektur, KorrekturWert, Kopfform, Glissando, Artikulation, KlammerAbstand
	global SaitenNummer, BundNummer
	
	
	for head in chord.getElementsByTagName('head'):
		shape = head.getAttribute('shape')
		if shape == 'square':
			Kopfform = 1
		if shape == 'crossCircle':
			Kopfform = 2

	Abstandx1 = -1000
	Abstandx2 = -1000
	for drawObj in chord.getElementsByTagName('drawObj'):
		tag = '0'	
		for content in drawObj.getElementsByTagName('content'):
			ObjectContent = latin1_e(content.firstChild.nodeValue)
			
		for basic in drawObj.getElementsByTagName('basic'):
			tag = basic.getAttribute('tag')

		for text in drawObj.getElementsByTagName('text'):
			Textx = text.getAttribute('x')

		NurZeichen = []
		element = 0
		for elements in RegisterCode:
			NurZeichen.append(RegisterCode[element][0])
			
			element +=1
		if tag == '56294-2501':
			Kopfform = 3
		if tag == '56294-2502':
			Kopfform = 4		
		if tag == '56294-2503':
			Kopfform = 5
		if tag == '56294-2504':
			Kopfform = 6								
		if tag == '56294-2505':
			Kopfform = 7
		if tag == '56294-2506':
			Kopfform = 8					
		if tag == '56294-2507':
			SaitenNummer = SaitenBezeichnungen.index(str(ObjectContent[0]))	
			BundNummer = BundBezeichnungen.index(str(ObjectContent[1:]))			
			Kopfform = 9
		if tag == '56294-2509':
			Glissando = 1		

				
		if tag == '56294-2560':
			Register1 = NurZeichen.index(str(ObjectContent))
			Abstandx1 = round(string.atof(Textx),2)-string.atof(RegisterCode[Register1][1])
			KlammerAbstand = 0
			Korrektur = Abstandx1
			
		if tag == '56294-2561':
			Register1 = NurZeichen.index(str(ObjectContent))
			Abstandx1 = round(string.atof(Textx),2)-string.atof(RegisterCode[Register1][1])
			KlammerAbstand = 1	
			Korrektur = Abstandx1
			
		if tag == '56294-2562':
			Register1 = NurZeichen.index(str(ObjectContent))
			Abstandx1 = round(string.atof(Textx),2)-string.atof(RegisterCode[Register1][1])
			KlammerAbstand = 2		
			Korrektur = Abstandx1
			
		if tag == '56294-2563':
			Register1 = NurZeichen.index(str(ObjectContent))
			Abstandx1 = round(string.atof(Textx),2)-string.atof(RegisterCode[Register1][1])
			KlammerAbstand = 3	
			Korrektur = Abstandx1
			
		if tag == '56294-2564':
			Register1 = NurZeichen.index(str(ObjectContent))
			Abstandx1 = round(string.atof(Textx),2)-string.atof(RegisterCode[Register1][1])
			KlammerAbstand = 4
			Korrektur = Abstandx1
				
		if tag == '56294-2521':
			Register2 = NurZeichen.index(str(ObjectContent))
			Abstandx2 = round(string.atof(Textx),2)-string.atof(RegisterCode[Register2][1])
			

		if tag == '56294-2512':
			KlammerAuf1 = 1
		if tag == '56294-2513':
			KlammerZu1 = 1	
					
		if tag == '56294-2521':
			Register2 = NurZeichen.index(str(ObjectContent))
			Abstandx2 = round(string.atof(Textx),2)-string.atof(RegisterCode[Register2][1])
							
		if tag == '56294-2522':
			KlammerAuf2 = 1
		if tag == '56294-2523':
			KlammerZu2 = 1	
			
		if tag == '56294-2531':
			Register3 = NurZeichen.index(str(ObjectContent))
		if tag == '56294-2532':
			KlammerAuf3 = 1
		if tag == '56294-2533':
			KlammerZu3 = 1		
					
		if tag == '56294-2541':
			Register4 = NurZeichen.index(str(ObjectContent))
		if tag == '56294-2542':
			KlammerAuf4 = 1
		if tag == '56294-2543':
			KlammerZu4 = 1		
		
		if tag == '56294-2551':
			Artikulation = 1	
		if tag == '56294-2552':
			Artikulation = 2		
		if tag == '56294-2553':
			Artikulation = 3		
		if tag == '56294-2554':
			Artikulation = 4		
		if tag == '56294-2555':
			Artikulation = 5		
		if tag == '56294-2556':
			Artikulation = 6
		if tag == '56294-2557':
			Artikulation = 7			
		if tag == '56294-2558':
			Artikulation = 8			
		
	if (Abstandx1<> -1000) and (Abstandx2<>-1000):
		#Test(str(Abstandx2-Abstandx1-string.atof(KlammerAbstaende[KlammerAbstand])*(KlammerZu1+KlammerAuf2)))
		if (str(Abstandx2-Abstandx1-string.atof(KlammerAbstaende[KlammerAbstand])*(KlammerZu1+KlammerAuf2))) in Abstaende:
			AbstandRegister = Abstaende.index(str(Abstandx2-Abstandx1-string.atof(KlammerAbstaende[KlammerAbstand])*(KlammerZu1+KlammerAuf2)))	

	
	if (str(Korrektur)) in KorrekturWerte:
		KorrekturWert = KorrekturWerte.index(str(Korrektur))
	
	for stem in chord.getElementsByTagName('stem'):
		stemVisible = stem.getAttribute('invisible')
		#Test(stemVisible)
		if stemVisible == 'true':
			if Glissando <> 1:
				Glissando = 2

def getKey(rest):
	global Schluessel, SchluesselZahl
	
	for drawObj in rest.getElementsByTagName('drawObj'):
		tag = '0'	
		for basic in drawObj.getElementsByTagName('basic'):
			tag = basic.getAttribute('tag')
		if tag == '56294-2571':
			Schluessel = 1
		if tag == '56294-2572':
			Schluessel = 2
		if tag == '56294-2573':
			Schluessel = 3
		if tag == '56294-2574':
			Schluessel = 4		
		if tag == '56294-2575':
			Schluessel = 5	
		if tag == '56294-2576':
			for content in basic.parentNode.getElementsByTagName('content'):
				ObjectContent = latin1_e(content.firstChild.nodeValue)	
				SchluesselZahl = string.atoi(ObjectContent)-1
			
																		
def changeHead(chord):
	global Kopfform
	drawObjects = chord.getElementsByTagName('drawObjects')[0]
	for head in chord.getElementsByTagName('head'):
		if Kopfform > 0:
			head.setAttribute('shape', Kopfformen[Kopfform])
			
	if Kopfform == 3:
		line01 = newLine(drawObjects,-0.125,2.125,-2.15,-2.15,3,'01')
	if Kopfform == 4:
		text02 = newText(drawObjects, '1.03', '-1.78', 'RAS', '5','02', 'Arial')
		for font in text02.getElementsByTagName('font'):
			font.setAttribute('weight','700')
	if Kopfform == 7:
		text05 = newText(drawObjects, '0', '0', 'î', '18','05', 'capella-Rhythmusnotation')
		text05.setAttribute('align','left')
	if Kopfform == 8:
		text06 = newText(drawObjects, '0', '0', 'ó', '18','06', 'capella-Rhythmusnotation')
		text06.setAttribute('align','left')
	if Kopfform == 9:
		text07 = newText(drawObjects, '-0.1', '-0.2', (SaitenBezeichnungen[SaitenNummer] + BundBezeichnungen[BundNummer]), '8','07', 'TimesNewRoman')
		text07.setAttribute('align','left')


def changeStem(chord):
	drawObjects = chord.getElementsByTagName('drawObjects')[0]
	if Glissando == 2:
		stem = addElementNode(chord,'stem')
		stem.setAttribute('invisible','true')
	if Glissando == 1:
		wavyline09 = newWavyLine(drawObjects, 0.1,0.1,0,3.5,42,'09')
		stem = addElementNode(chord,'stem')
		stem.setAttribute('invisible','true')
		beam = addElementNode(chord,'beam')
		beam.setAttribute('group','split')
	if Glissando == 0:
		stem = addElementNode(chord,'stem')
		stem.setAttribute('invisible','false')

def createKey(rest):
	restDrawObjects = addNewElementNode(rest,'drawObjects')
	if Schluessel == 1:
		triangle82 = newTriangle(restDrawObjects,0.1875,0.75,-0.34375,-1.15625,-0.21875,-0.21875,'82')
		ellipse7x= newEllipse(restDrawObjects,-1.2,1.6,1.4,-1.4,'71')
	if Schluessel == 2:
		triangle83 = newTriangle(restDrawObjects,0.1875,0.75,-0.34375,1.15625,0.21875,0.21875,'83')
		ellipse7x= newEllipse(restDrawObjects,-1.2,1.6,1.4,-1.4,'72')
	if Schluessel == 3:
		triangle82 = newTriangle(restDrawObjects,0.1875,0.75,-0.34375,-1.15625,-0.21875,-0.21875,'82')
		triangle83 = newTriangle(restDrawObjects,0.1875,0.75,-0.34375,1.15625,0.21875,0.21875,'83')
		ellipse7x= newEllipse(restDrawObjects,-1.2,1.6,1.4,-1.4,'73')
	if Schluessel == 4:
		triangle84 = newTriangle(restDrawObjects,-0.46875,0.5,0.5,0,0.6,-0.6,'83')		
		ellipse7x= newEllipse(restDrawObjects,-1.2,1.6,1.4,-1.4,'74')				
	if Schluessel == 5:
		ellipse7x= newEllipse(restDrawObjects,-1.2,1.6,1.4,-1.4,'75')
		ellipse7x.setAttribute('filled','true')
		ellipse7x.setAttribute('fillColor','FFFFFF')
		line77a = newLine(restDrawObjects,0.1875,0.1875,-1.375,1.4,4,'77')
		line77b = newLine(restDrawObjects,1.2,1.2,-0.98,0.98,2,'77')
		line77c = newLine(restDrawObjects,1.25,1.25,-0.9,0.9,2,'77')
		text76a = newText(restDrawObjects,'-0.4375','0.5',str(SchluesselZahl+2),'6','76','TimesNewRoman')
		text77a = newText(restDrawObjects,'0.75','0.5',str(SchluesselZahl+1),'6','77','TimesNewRoman')
		

def changeKey(chord):
	if Schluessel <> 0:
		noteObjects = chord.parentNode
		newRest = addNewElementNode(noteObjects,'rest')
		durationRest = addNewElementNode(newRest,'duration')
		durationRest.setAttribute('base','1/4')
		durationRest.setAttribute('noDuration','true')
		displayRest = addNewElementNode(newRest,'display')
		displayRest.setAttribute('invisible','true')
		
		createKey(newRest)
		noteObjects.insertBefore(newRest,chord)	

def changeArticulation(chord):
	drawObjects = addElementNode(chord,'drawObjects')
	#Test(Artikulation)
	if Artikulation == 1:
		Articulation51 = newText(drawObjects,ArtikulationCode[Artikulation][1],ArtikulationCode[Artikulation][2],ArtikulationCode[Artikulation][0],ArtikulationCode[Artikulation][3],'51','capella-Rhythmusnotation') 
	if Artikulation == 2:
		Articulation52 = newText(drawObjects,ArtikulationCode[Artikulation][1],ArtikulationCode[Artikulation][2],ArtikulationCode[Artikulation][0],ArtikulationCode[Artikulation][3],'52','capella-Rhythmusnotation') 
	if Artikulation == 3:
		Articulation53a = newText(drawObjects,ArtikulationCode[Artikulation][0][1],ArtikulationCode[Artikulation][0][2],ArtikulationCode[Artikulation][0][0],ArtikulationCode[Artikulation][0][3],'53','capella-Rhythmusnotation') 
		Articulation53b = newText(drawObjects,ArtikulationCode[Artikulation][1][1],ArtikulationCode[Artikulation][1][2],ArtikulationCode[Artikulation][1][0],ArtikulationCode[Artikulation][1][3],'53','capella-Rhythmusnotation') 
	if Artikulation == 4:
		Articulation54 = newText(drawObjects,ArtikulationCode[Artikulation][1],ArtikulationCode[Artikulation][2],ArtikulationCode[Artikulation][0],ArtikulationCode[Artikulation][3],'54','capella-Rhythmusnotation') 
	if Artikulation == 5:
		Articulation55 = newText(drawObjects,ArtikulationCode[Artikulation][1],ArtikulationCode[Artikulation][2],ArtikulationCode[Artikulation][0],ArtikulationCode[Artikulation][3],'55','capella-Rhythmusnotation') 
	if Artikulation == 6:
		Articulation56 = newText(drawObjects,ArtikulationCode[Artikulation][1],ArtikulationCode[Artikulation][2],ArtikulationCode[Artikulation][0],ArtikulationCode[Artikulation][3],'56','capella-Rhythmusnotation') 
	if Artikulation == 7:
		Articulation57 = newText(drawObjects,ArtikulationCode[Artikulation][1],ArtikulationCode[Artikulation][2],ArtikulationCode[Artikulation][0],ArtikulationCode[Artikulation][3],'57','TimesNewRoman') 
		
	
def handleNotes(score, voice, chord):
    global Register1, Kopfform, AutoAnpassen
    
    if AutoAnpassen == 1:
	    i = 0														
	    for head in chord.getElementsByTagName('head'):
	    	if i > 0:
	    		head.parentNode.removeChild(head)
	    	i+=1
	    
	    chord.getElementsByTagName('head')[0].setAttribute('pitch','B5')
    
    for drawObjects in chord.getElementsByTagName('drawObjects'):					# Alle drawObj mit tag == GraficalTag löschen
          for drawObj in drawObjects.childNodes:
             if drawObj.nodeType == drawObj.ELEMENT_NODE and drawObj.tagName == 'drawObj':
             	for basic in drawObj.getElementsByTagName('basic'):
                     if basic.hasAttribute('tag') and basic.getAttribute('tag') == '56294-2500':
                        drawObjects.removeChild(drawObj)
              
    for drawObjects in chord.getElementsByTagName('drawObjects'):					# Alle drawObj mit tag == GraficalTag löschen
         for drawObj in drawObjects.childNodes:
             if drawObj.nodeType == drawObj.ELEMENT_NODE and drawObj.tagName == 'drawObj':
            	for basic in drawObj.getElementsByTagName('basic'):
                     if basic.hasAttribute('tag') and basic.getAttribute('tag')[0:8] == '56294-25':
                        drawObjects.removeChild(drawObj)     	
         	  		  	               
         if drawObjects.getElementsByTagName('drawObj').length == 0:					# Wenn drawObjects keine Elemente mehr enthält, dann löschen  
             drawObjects.parentNode.removeChild(drawObjects)

    drawObjs = chord.getElementsByTagName('drawObjs')
       			

    if NurLoeschen == 0:     
        
        drawObjects = addElementNode(chord,'drawObjects')				# Notennamen
        Korrektur = string.atof(KorrekturWerte[KorrekturWert])
        if Kopfform == 4:
        	RegisterCode[1][3] = '10'
        	RegisterCode[1][2] = '-2.8'   
        	RegisterCode[2][3] = '10'
        	RegisterCode[2][2] = '-2.7'
        	RegisterCode[3][3] = '10'
        	RegisterCode[3][2] = '-2.7'   
        	RegisterCode[4][3] = '8'
        	RegisterCode[4][2] = '-2.7'   
        
        KlammerAnzahl = 0	 
        KlammerKorrektur = string.atof(KlammerAbstaende[KlammerAbstand])       	
        
        FirstTag = '6' + str(KlammerAbstand)
        
        if KlammerAuf1 == 1:
        	KlammerAuf12=newText(drawObjects, str(Korrektur + string.atof(KlammerCode[0][1])),KlammerCode[0][2], KlammerCode[0][0], KlammerCode[0][3],'12','TimesNewRoman')
        text11 = newText(drawObjects, str(Korrektur + string.atof(RegisterCode[Register1][1])), RegisterCode[Register1][2], RegisterCode[Register1][0],RegisterCode[Register1][3], FirstTag, RegisterCode[Register1][4])	
        if KlammerZu1 == 1:
        	KlammerZu13=newText(drawObjects, str(Korrektur + string.atof(KlammerCode[1][1])),KlammerCode[1][2], KlammerCode[1][0], KlammerCode[1][3],'13','TimesNewRoman')	
        	Korrektur = Korrektur + KlammerKorrektur 
        	
        if KlammerAuf2 == 1:
        	Korrektur = Korrektur + KlammerKorrektur
        	KlammerAuf22=newText(drawObjects, str(Korrektur + string.atof(KlammerCode[0][1])+string.atof(Abstaende[AbstandRegister])),KlammerCode[0][2], KlammerCode[0][0], KlammerCode[0][3],'22','TimesNewRoman')         	
        text21 = newText(drawObjects, str(Korrektur + string.atof(RegisterCode[Register2][1])+string.atof(Abstaende[AbstandRegister])), RegisterCode[Register2][2], RegisterCode[Register2][0],RegisterCode[Register2][3], '21', RegisterCode[Register2][4])		
    	if KlammerZu2 == 1:
        	KlammerAuf23=newText(drawObjects, str(Korrektur + string.atof(KlammerCode[1][1])+string.atof(Abstaende[AbstandRegister])),KlammerCode[1][2], KlammerCode[1][0], KlammerCode[1][3],'23','TimesNewRoman')
        	Korrektur = Korrektur + KlammerKorrektur        

        if KlammerAuf3 == 1:
        	Korrektur = Korrektur + KlammerKorrektur
        	KlammerAuf32=newText(drawObjects, str(Korrektur + string.atof(KlammerCode[0][1])+string.atof(Abstaende[AbstandRegister])+string.atof(Abstaende[AbstandRegister])),KlammerCode[0][2], KlammerCode[0][0], KlammerCode[0][3],'32','TimesNewRoman')
        text31 = newText(drawObjects, str(Korrektur + string.atof(RegisterCode[Register3][1])+string.atof(Abstaende[AbstandRegister])+string.atof(Abstaende[AbstandRegister])), RegisterCode[Register3][2], RegisterCode[Register3][0],RegisterCode[Register3][3], '31', RegisterCode[Register3][4])	   	
    	if KlammerZu3 == 1:
        	KlammerAuf33=newText(drawObjects, str(Korrektur + string.atof(KlammerCode[1][1])+string.atof(Abstaende[AbstandRegister])+string.atof(Abstaende[AbstandRegister])),KlammerCode[1][2], KlammerCode[1][0], KlammerCode[1][3],'33','TimesNewRoman')
        	Korrektur = Korrektur + KlammerKorrektur 
        
        if KlammerAuf4 == 1:
        	Korrektur = Korrektur + KlammerKorrektur
        	KlammerAuf42=newText(drawObjects, str(Korrektur + string.atof(KlammerCode[0][1])+string.atof(Abstaende[AbstandRegister])+string.atof(Abstaende[AbstandRegister])+string.atof(Abstaende[AbstandRegister])),KlammerCode[0][2], KlammerCode[0][0], KlammerCode[0][3],'42','TimesNewRoman')
        text41 = newText(drawObjects, str(Korrektur + string.atof(RegisterCode[Register4][1])+string.atof(Abstaende[AbstandRegister])+string.atof(Abstaende[AbstandRegister])+string.atof(Abstaende[AbstandRegister])), RegisterCode[Register4][2], RegisterCode[Register4][0],RegisterCode[Register4][3], '41', RegisterCode[Register3][4])		     	
    	if KlammerZu4 == 1:
        	KlammerAuf43=newText(drawObjects, str(Korrektur + string.atof(KlammerCode[1][1])+string.atof(Abstaende[AbstandRegister])+string.atof(Abstaende[AbstandRegister])+string.atof(Abstaende[AbstandRegister])),KlammerCode[1][2], KlammerCode[1][0], KlammerCode[1][3],'43','TimesNewRoman')
        	Korrektur = Korrektur + KlammerKorrektur
        	
    	changeHead(chord)
    	changeStem(chord)
    	changeKey(chord)
    	changeArticulation(chord)

def handleRest(rest):
    global Register1, Kopfform
															
    for drawObjects in rest.getElementsByTagName('drawObjects'):					# Alle drawObj mit tag == GraficalTag löschen
          for drawObj in drawObjects.childNodes:
             if drawObj.nodeType == drawObj.ELEMENT_NODE and drawObj.tagName == 'drawObj':
             	for basic in drawObj.getElementsByTagName('basic'):
                     if basic.hasAttribute('tag') and basic.getAttribute('tag') == '56294-2500':
                        drawObjects.removeChild(drawObj)
              
    for drawObjects in rest.getElementsByTagName('drawObjects'):					# Alle drawObj mit tag == GraficalTag löschen
         for drawObj in drawObjects.childNodes:
             if drawObj.nodeType == drawObj.ELEMENT_NODE and drawObj.tagName == 'drawObj':
            	for basic in drawObj.getElementsByTagName('basic'):
                     if basic.hasAttribute('tag') and basic.getAttribute('tag')[0:8] == '56294-25':
                        drawObjects.removeChild(drawObj)     	
         	  		  	               
         if drawObjects.getElementsByTagName('drawObj').length == 0:					# Wenn drawObjects keine Elemente mehr enthält, dann löschen  
             drawObjects.parentNode.removeChild(drawObjects)
    createKey(rest)

                        
def getCursor():
    sel = curSelection()
    result = None
    if sel == 0:
        messageBox('Fehler', 'keine aktive Partitur')
        return result
    #if sel[0] != sel[1]:
    #    messageBox('Fehler', 'Markierung ist nicht leer')
    #    return result
    result = sel[0]
    return result

def getElementObjects(objList):  # returns a List
    newList = NodeList()
    for n in range(objList.length):
        if objList[n].nodeType == objList[n].ELEMENT_NODE:
            newList.append(objList[n])
    return newList



def makeSingleLine(score,layoutName):
	global SingleLine
	
	for staffLayout in score.getElementsByTagName('staffLayout'):
		if layoutName == staffLayout.getAttribute('description'):
			if SingleLine == 1:
				for notation in staffLayout.getElementsByTagName('notation'):
					notation.setAttribute('notelines','1')

    

def getNoteLength(note):
	for duration in note.getElementsByTagName('duration'):
		notelength = duration.getAttribute('base')
	return notelength

def changeDoc(score):
	global Leer,Register1, Register2, Register3, Register4
	global KlammerAuf1, KlammerAuf2, KlammerAuf3, KlammerAuf4, KlammerZu1, KlammerZu2, KlammerZu3, KlammerZu4
	global AbstandRegister, SingleLine, Notenwert, Abstaende, Korrektur,KorrekturWert, Kopfform, Glissando
	global Schluessel, Artikulation, AutoAnpassen, KlammerAbstand, SaitenNummer, BundNummer
	
	Kopfform=1
	Leer = 0
	Register1 = 0
	Register2 = 0
	Register3 = 0
	Register4 = 0
	KlammerAuf1 = 0
	KlammerAuf2 = 0
	KlammerAuf3 = 0
	KlammerAuf4 = 0
	KlammerZu1 = 0
	KlammerZu2 = 0
	KlammerZu3 = 0
	KlammerZu4 = 0
	AbstandRegister = 2
	KorrekturWert = 2
	SingleLine = 0
	Korrektur = 0
	Glissando = 0
	Schluessel = 0
	Artikulation = 0
	AutoAnpassen = 0
	KlammerAbstand = 0
	SaitenNummer = 0
	BundNummer = 0
	getOptions()
	sel = getCursor()
	if sel == None:
        #
		return
	else:
		system = score.getElementsByTagName('system')[sel[0]]
		staff = system.getElementsByTagName('staff')[sel[1]]
		voice = staff.getElementsByTagName('voice')[sel[2]]
		noteObject = voice.getElementsByTagName('noteObjects')[0]

		layoutName = staff.getAttribute('layout')
		

		objList = getElementObjects(noteObject.childNodes)
		if objList.length <= sel[3]:
			return

        
		obj = objList[sel[3]]
		if obj.tagName == 'chord':
			Notenwert = getNoteLength(obj)

			getContent(obj)
			if getDialogValues1():
				handleNotes(score, voice, obj)
				makeSingleLine(score, layoutName)
				setOptions()
				if InfoComment == 1:
					setScoreStyle(score)	
		if obj.tagName == 'rest':
			getKey(obj)
			if getDialogValues2():
				if Schluessel <> 0:
					handleRest(obj)
				if Schluessel == 0:
					obj.parentNode.removeChild(obj)



		
# Hauptprogramm:

from caplib.capDOM import ScoreChange
import tempfile

class ScoreChange(ScoreChange):
	
	def changeScore(self, score):
	   global doc
	   doc = score.parentNode  
	   changeDoc(score)
		
        

if activeScore():
	
	activeScore().registerUndo("Finger- und Fußsätze")
	tempInput = tempfile.mktemp('.capx')
	tempOutput = tempfile.mktemp('.capx')
	activeScore().write(tempInput)
	ScoreChange(tempInput, tempOutput)
	activeScore().read(tempOutput)
	os.remove(tempInput)
	os.remove(tempOutput)

