# -*- coding: ISO-8859-1 -*-
""" capellaScript -- 08.11.2005 Andreas Herzog
>>> PageObjectMaster

    Das Skript positioniert PageObject-Texte.|
    |
    
    |
    Version 1.0a |
    |
    Achtung: Wirklich zentriert, linksbündig oder rechtsbündig ist der Text nur dann, wenn er auch so ausgerichtet ist!
    
    |
    Beachte: Automatische Ausrichtung funktioniert nur bei Einfachtexten.

        |

<<<
# Version 1.0: Ursprungsversion
# Version 1.0a: Absturz bei korrupten Textfeldern wird abgefangen, Fehlerkorrektur

"""

import xml.dom
import string

def latin1_e(u):
    return u.encode('Latin-1')
def latin1_d(u):
    return u.decode('Latin-1')

from xml.dom.minidom import NodeList

SeitenMassen = [['DinA4 Hochformat',210,297],['DinA4 Querformat',297,210]]


# 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(content):
	
    global AktionHor, AktionVer, SeitenBreite, SeitenHoehe, UserX, UserY, OldX, OldY

    SeitenMassenNamen = []
    i=0
    
    while i < len(SeitenMassen):
    	SeitenMassenNamen += SeitenMassen[i]
    	i += 1
    	
    SeitenMassenBox = ComboBox(SeitenMassenNamen,width = 20,value=0)
    
    labelInhalt = Label('Inhalt des PageObjektes:', width = 40)
    labelText = Label(str(content),  padding = 8, value=0, width=40) 
    labelUserX = Label('Eigene X-Koordinate',  padding = 8, value=0) 
    labelUserY = Label('Eigene Y-Koordinate',  padding = 8, value=0) 

    AktionHorRadio = Radio(['unverändert','linksbündig', 'mittig','rechtsbündig','eigene Angaben:'],text='Horizontale Position', value=0) 
    AktionVerRadio = Radio(['unverändert','eigene Angaben:'],text='Vertikale Position', value=0)     
    UserXEdit = Edit(str(OldX),min=-1000.00000, max=1000.00000, width=5)
    UserYEdit = Edit(str(OldY),min=-1000.00000, max=1000.00000, width=5)
    HBox0 = HBox([labelText],text='Inhalt des PageObjektes')
    HBox1 = HBox([AktionHorRadio,AktionVerRadio],padding = 4)
    HBox2 = HBox([labelUserX,UserXEdit],padding = 4)
    HBox3 = HBox([labelUserY,UserYEdit],padding = 4)
   
    vbox1= VBox([SeitenMassenBox,HBox0,HBox1,HBox2,HBox3], padding = 8)
    dlg = Dialog('Bitte wählen: ', vbox1)
	
    if dlg.run():
    	AktionHor = AktionHorRadio.value()
    	AktionVer = AktionVerRadio.value()
    	SeitenMass = SeitenMassenBox.value()
    	SeitenHoehe = SeitenMassen[SeitenMass][2] 
    	SeitenBreite = SeitenMassen[SeitenMass][1] 
    	UserX = UserXEdit.value()
    	UserY = UserYEdit.value()
       	return True
    else:
        return False

def getDialogValues2(content):
	
    global AktionHor, AktionVer, SeitenBreite, SeitenHoehe, UserX, UserY, OldX, OldY

    SeitenMassenNamen = []
    i=0
    
    while i < len(SeitenMassen):
    	SeitenMassenNamen += SeitenMassen[i]
    	i += 1
    	
    SeitenMassenBox = ComboBox(SeitenMassenNamen,width = 20,value=0)
    
    labelInhalt = Label('Inhalt des PageObjektes:', width = 40)
    labelText = Label(str(content),  padding = 8, value=0, width=40) 
    labelUserX = Label('Eigene X-Koordinate',  padding = 8, value=0) 
    labelUserY = Label('Eigene Y-Koordinate',  padding = 8, value=0) 
 
    AktionHorRadio = Radio(['unverändert','eigene Angaben:'],text='Horizontale Position', value=0) 
    AktionVerRadio = Radio(['unverändert','eigene Angaben:'],text='Vertikale Position', value=0)     
    UserXEdit = Edit(str(OldX),min=0.00000, max=1000.00000, width=5)
    UserYEdit = Edit(str(OldY),min=0.00000, max=1000.00000, width=5)
    HBox0 = HBox([labelText],text='Inhalt des PageObjektes')
    HBox1 = HBox([AktionHorRadio,AktionVerRadio],padding = 4)
    HBox2 = HBox([labelUserX,UserXEdit],padding = 4)
    HBox3 = HBox([labelUserY,UserYEdit],padding = 4)
   
    vbox1= VBox([SeitenMassenBox,HBox0,HBox1,HBox2,HBox3], padding = 8)
    dlg = Dialog('Bitte wählen: ', vbox1)
	
    if dlg.run():
    	AktionHor = AktionHorRadio.value()
    	AktionVer = AktionVerRadio.value()
    	SeitenMass = SeitenMassenBox.value()
    	SeitenHoehe = SeitenMassen[SeitenMass][2] 
    	SeitenBreite = SeitenMassen[SeitenMass][1] 
    	UserX = UserXEdit.value()
    	UserY = UserYEdit.value()
       	return True
    else:
        return False
        
def getContent(text):

	for content in text.getElementsByTagName('content'):
		if content.hasChildNodes(): 
			ObjectContent = latin1_e(content.firstChild.nodeValue)
		else:
			ObjectContent = ''
	
	return ObjectContent
												
def isItalic(text):
	TextItalic = 'false'
	
	for font in text.getElementsByTagName('font'):
		if font.hasAttribute('italic'):
			TextItalic = font.getAttribute('italic')
	if TextItalic == 'false':
		return False
	if TextItalic == 'true':
		return True

            
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 setHor(text,x):
	text.setAttribute('x',str(x))

def setVer(text,y):
	text.setAttribute('y',str(y))

def Test(text):
	messageBox('Test',str(text))
			

def changeDoc(score):
	global AktionHor,AktionVer, SeitenHoehe, SeitenBreite, UserX, UserY, OldX, OldY
	
	
	for pages in score.getElementsByTagName('pages'):
		RandLinks = string.atoi(pages.getAttribute('left'))
		RandRechts = string.atoi(pages.getAttribute('right'))
		RandOben = string.atoi(pages.getAttribute('top'))
		RandUnten = string.atoi(pages.getAttribute('bottom'))

	
	for pageObjects in score.getElementsByTagName('pageObjects'):
		for drawObj in pageObjects.getElementsByTagName('drawObj'):
			for text in drawObj.getElementsByTagName('text'):
				
				content = getContent(text)
				OldX = text.getAttribute('x')
				OldY = text.getAttribute('y')
				
 				if getDialogValues1(content):
 					if AktionHor == 1:
 						x = 0
 						setHor(text,x)
  					if AktionHor == 2:
 						x = str(((SeitenBreite/1.8)-((RandLinks+RandRechts)/1.8))/2)
 						setHor(text,x)		
 					if AktionHor == 3:
 						x = str((SeitenBreite/1.8)-((RandLinks+RandRechts)/1.8))
 						setHor(text,x)	
 					if AktionHor == 4:	
 						x = UserX
 						setHor(text,x)	
 							
 					if AktionVer == 1:
 						y = UserY
 						setVer(text,y)	
	
 				else:
 					return		

			i=1
			for richText in drawObj.getElementsByTagName('richText'):
				
				content = 'Textfeld Nr.' + str(i)
				OldX = text.getAttribute('x')
				OldY = text.getAttribute('Y')				
 				if getDialogValues2(content):
 					if AktionHor == 1:
 						x = UserX
 						setHor(richText,x)	
 					if AktionVer == 1:
 						y = UserY
 						setVer(richText,y)	
 					
	
 				else:
 					return		
 				i+=1
		    		
	        		
# 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("Pageobjekte positionieren")
	tempInput = tempfile.mktemp('.capx')
	tempOutput = tempfile.mktemp('.capx')
	activeScore().write(tempInput)
	ScoreChange(tempInput, tempOutput)
	activeScore().read(tempOutput)
	os.remove(tempInput)
	os.remove(tempOutput)

