# -*- coding: ISO-8859-1 -*-
""" capellaScript
>>> 
Stichnoten einfügen
<<<
"""
# 27.11.2004 Hartmut Lemmel

from xml.dom.minidom import parse

def getElement(parent, *children):
     """ liefert Kind/Enkel/Urenkel..., z.B. parent.child0.child1.child2... """
     p = parent
     for c in children:
         found = 0
         for n in p.childNodes:
             if n.nodeType == parent.ELEMENT_NODE and n.tagName == c:
                 p = n
                 found = 1
                 break
         if not found: return 0
     return p
def getElements(parent):
     list=[]
     for n in parent.childNodes:
             if n.nodeType == parent.ELEMENT_NODE:
                 list.append(n)
     return list


from caplib.capDOM import ScoreChange
import tempfile

class ScoreChange(ScoreChange):  
    def changeScore(self, score):
      global sy,st,vo,no,ivoice
      sys=score.getElementsByTagName('system')[sy]
      staff=sys.getElementsByTagName('staff')[st]
      voice=staff.getElementsByTagName('voice')[vo]
      notes=getElements(voice.getElementsByTagName('noteObjects')[0])
      cuevoice=self.doc.createElement('voice')
      voices=getElement(staff,'voices')
      voices.appendChild(cuevoice)
      cuenotes=self.doc.createElement('noteObjects')
      cuevoice.appendChild(cuenotes)
      # voice,notes: Stimme der Cursorposition (externes Skript)
      # ivoice: Stimme der Cursorposition (internes Skript)
      # cuevoice,cuenotes: neu erzeugte Stimme für Stichnoten
      for n in range(no):
        obj=notes[n]
        if obj.tagName=='chord' or obj.tagName=='rest':
          dur=getElement(obj,'duration')
          if dur.getAttribute('noDuration')!='true':
              rest=self.doc.createElement('rest')
              cuenotes.appendChild(rest)
              rest.appendChild(dur.cloneNode(1))
              disp=self.doc.createElement('display')
              rest.appendChild(disp)
              disp.setAttribute('small','true')
              disp.setAttribute('invisible','true')
        else:
          cuenotes.appendChild(obj.cloneNode(1))
          
      filename=getUserDataDir()+'cuenotes.tmp'
      obj = getElement(parse(filename),'noteObjects')
      if obj:
        for text in obj.getElementsByTagName('content'):
          if text.firstChild:                     
                      str=text.firstChild.nodeValue
                      str=str.encode('Latin-1')    # unicode -> string
                      #messageBox("test",str)
                      str=str.decode('string_escape')  # escape-codierung rückgängig
                      #messageBox("test",str)
                      str=str.decode('Latin-1')    # string -> unicode (?)
                      text.firstChild.nodeValue=str
          
        for n in obj.childNodes:
          if n.nodeType == obj.ELEMENT_NODE:
            cuenotes.appendChild(n)

if activeScore():
    sel = curSelection()
    if sel <> 0:
        activeScore().registerUndo("Stichnoten einfügen")

        global sy,st,vo,no,ivoice
        (sy,st,vo,no) = sel[0]
        isys = activeScore().system(sy)
        istaff = isys.staff(st)
        ivoice = istaff.voice(vo)
        
        tempInput = tempfile.mktemp('.capx')
        tempOutput = tempfile.mktemp('.capx')
        activeScore().write(tempInput)

        ScoreChange(tempInput, tempOutput)

        activeScore().read(tempOutput)
        os.remove(tempInput)
        os.remove(tempOutput)

