# -*- coding: ISO-8859-1 -*-
""" capellaScript -- 01.11.2005 Andreas Herzog
>>> Oktaviano

    Das Skript wandelt oktavierende Schlüssel in normale Schlüssel um und kann die Soundausgabe für die jeweilige Zeile entsprechend anpassen.

    |
    |
    Version 1.0a  |
    
    |
    

        |

<<<

# Version 1.0: Ursprungsversion
# Version 1.0a: fehlerrevidierte Version
"""

import xml.dom
import string


from xml.dom.minidom import NodeList

# doc = [] # parentNode von score

def latin1_e(u):
    return u.encode('Latin-1')
def latin1_d(u):
    return u.decode('Latin-1')
    
 
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 Aktion, KoepfeAnpassen, SoundAnpassen

    KoepfeAnpassenCheck = CheckBox('Kopfhöhe anpassen', value=0)
    SoundAnpassenCheck = CheckBox('Soundausgabe anpassen', value=0)
    
    AktionRadio = Radio(['hochoktavierende Schlüssel beseitigen','hochoktavierenden Schlüssel setzen','tiefoktavierende Schlüssel beseitigen','tiefoktavierenden Schlüssel setzen'], text = 'Aktion', value = 0)
   
  
    vbox00= VBox([AktionRadio, KoepfeAnpassenCheck,SoundAnpassenCheck], padding = 4)
    dlg = Dialog('Bitte wählen: ', vbox00)

	
    if dlg.run():

        KoepfeAnpassen = KoepfeAnpassenCheck.value()
        SoundAnpassen = SoundAnpassenCheck.value()
        Aktion = AktionRadio.value()

       	return True
    else:
        return False

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 Test(text):
	messageBox('Test',str(text))

def changeTranspose(staffLayout, oktaven):
	for sound in staffLayout.getElementsByTagName('sound'):
		transpose = 0
		if sound.getAttribute('transpose') <> '':
			transpose += string.atoi(sound.getAttribute('transpose'))
					
		if (Aktion == 1) or (Aktion == 2):
			transpose -= 12
		if (Aktion == 0) or (Aktion == 3):
			transpose += 12
		#Test(transpose)
		sound.setAttribute('transpose',str(transpose))			

def changeClefs(voice):
	for clefSign in voice.getElementsByTagName('clefSign'):
		clef = clefSign.getAttribute('clef')
		if clef == 'treble':
			clef = 'G2'
		if clef == 'tenor':
			clef = 'C4'	
		if clef == 'bass':
			clef = 'F4'	
		if clef == 'alto':
			clef = 'C3'
												
		if len(clef) > 2:
			if (clef[2] == '+') and (Aktion == 0):
				clefSign.setAttribute('clef',clef[0:2])
			if (clef[2] == '-') and (Aktion == 2):
				clefSign.setAttribute('clef',clef[0:2])						
		
		if len(clef) < 3:
			if (Aktion == 1):
				#Test((clef+'+'))
				clefSign.setAttribute('clef',(clef+'+'))
			if (Aktion == 3):
				clefSign.setAttribute('clef',(clef+'-'))
				
def changeHeads(voice):
	for head in voice.getElementsByTagName('head'):
		headpitch = head.getAttribute('pitch')
		if (Aktion == 1) or (Aktion == 2):
			headpitchInt = string.atoi(headpitch[1]) +1
		if (Aktion == 0) or (Aktion == 3):
			headpitchInt = string.atoi(headpitch[1]) -1

		headpitch = headpitch[0] + str(headpitchInt)
		head.setAttribute('pitch',headpitch)

				    
def changeDoc(score):
	global Transposition, Aktion, KoepfeAnpassen, SoundAnpassen
	
	sel = getCursor()
	if sel == None:
        #
		return
	else:
		if getDialogValues1():
		
			system = score.getElementsByTagName('system')[sel[0]]
			staff = system.getElementsByTagName('staff')[sel[1]]
			layout = staff.getAttribute('layout')
			for staffLayout in score.getElementsByTagName('staffLayout'):
				if staffLayout.getAttribute('description') == layout:
					if SoundAnpassen == 1:
						changeTranspose(staffLayout,0)

			for system in score.getElementsByTagName('system'):
				for staff in system.getElementsByTagName('staff'):
					if staff.getAttribute('layout') == layout:
						for voice in staff.getElementsByTagName('voice'):
							changeClefs(voice)
							if KoepfeAnpassen == 1:
								changeHeads(voice)


	        		
# Hauptprogramm:

from caplib.capDOM import ScoreChange
import tempfile

class ScoreChange(ScoreChange):
	
	def changeScore(self, score):
		
	
		global doc, Schriftart, Schriftgrad, Schriftzeichen, Schrifthoehe, Schriftweite, VertikaleKorrektur
		

		doc = score.parentNode  
		changeDoc(score)
		
		
        

if activeScore():
	
	activeScore().registerUndo("Oktavierende Schlüssel bearbeiten")
	tempInput = tempfile.mktemp('.capx')
	tempOutput = tempfile.mktemp('.capx')
	activeScore().write(tempInput)
	ScoreChange(tempInput, tempOutput)
	activeScore().read(tempOutput)
	os.remove(tempInput)
	os.remove(tempOutput)

