from AppKit import *
from Foundation import *

import time
import math

__all__ = ["Glyphs", "niceName", "GetFile", "GSMOVE", "GSLINE", "GSCURVE", "GSOFFCURVE", "GSSHARP", "GSSMOOTH", "divideCurve", "distance", "addPoints", "substractPoints"]






##################################################################################
#
#
#
#           GSApplication
#
#
#
##################################################################################


Glyphs = NSApplication.sharedApplication() #GlyphsPy()

GSApplication.currentDocument = property(lambda self: NSDocumentController.sharedDocumentController().currentDocument())

def OpenFont(Path):
	URL = NSURL.URLWithString_(Path)
	return NSDocumentController.sharedDocumentController().openDocumentWithContentsOfURL_display_error_(URL, True, None)
	
GSApplication.open = property(lambda self: OpenFont())

GSMOVE = 17
GSLINE = 1
GSCURVE = 35
GSOFFCURVE = 65
GSSHARP = 0
GSSMOOTH = 4096

# Reverse lookup for __repr__
constants = {
	17: 'GSMOVE',
	1: 'GSLINE',
	35: 'GSCURVE',
	65: 'GSOFFCURVE',
	0: 'GSSHARP',
	4096: 'GSSMOOTH',
}

'''
Constants
=========

GSMOVE = 17

GSLINE = 1

GSCURVE = 35

GSOFFCURVE = 65

GSSHARP = 0

GSSMOOTH = 4096


'''

GSElement.x = property(lambda self: self.valueForKey_("position").pointValue().x,
	lambda self, value: self.setPosition_(NSMakePoint(value, self.valueForKey_("position").pointValue().x)))

GSElement.y = property(lambda self: self.valueForKey_("position").pointValue().y,
	lambda self, value: self.setPosition_(NSMakePoint(value, self.valueForKey_("position").pointValue().y)))


##################################################################################
#
#
#
#           P R O X I E S
#
#
#
##################################################################################


class Proxy(object):
	def __init__(self, owner):
		self._owner = owner
	def __repr__(self):
		"""Return list-lookalike of representation string of objects"""
		string = []
		for i in range(len(self)):
			currItem = self[i]
			string.append("%s" % (currItem))
		return "(%s)" % (', '.join(string))


class AppDocumentProxy (Proxy):
	"""The list of documents."""
	#NSDocumentController.sharedDocumentController().documents()
	def __getitem__(self, Key):
		if type(Key) is int:
			if Key < 0:
				Key = self.__len__() + Key
			return NSDocumentController.sharedDocumentController().documents().objectAtIndex_(Key)
		else:
			raise(KeyError)
	def __len__(self):
		return NSDocumentController.sharedDocumentController().documents().count()
GSDocument.font = property(lambda self: self.valueForKey_("font"), 
						   lambda self, value: self.setFont_(value))

GSApplication.documents = property(lambda self: AppDocumentProxy(self))

def Glyphs__repr__(self):
	return '<Glyphs.app>'
GSApplication.__repr__ = Glyphs__repr__;

# by Yanone
GSApplication.font = property(lambda self: NSDocumentController.sharedDocumentController().currentDocument().font)

# by Yanone
def AllFonts():
	fonts = []
	for d in NSDocumentController.sharedDocumentController().documents():
		fonts.append(d.font)
	return fonts
GSApplication.fonts = property(lambda self: AllFonts())




class FontGlyphsProxy (Proxy):
	"""The list of glyphs. You can access it with the index or the glyph name.
	Usage: 
		Font.glyphs[index]
		Font.glyphs[name]
		for glyph in Font.glyphs:
		...
	"""
	def __getitem__(self, Key):
		if type(Key) is int:
			if Key < 0:
				Key = self.__len__() + Key
			return self._owner.glyphAtIndex_(Key)
		else:
			return self._owner.glyphForName_(Key)
	def __setitem__(self, Key, Glyph):
		if type(Key) is int:
			self._owner.removeGlyph_( self._owner.glyphAtIndex_(Key) )
			self._owner.addGlyph_(Glyph)
		else:
			self._owner.removeGlyph_( self._owner.glyphForName_(Key) )
			self._owner.addGlyph_(Glyph)
	def __delitem__(self, Key):
		if type(Key) is int:
			self._owner.removeGlyph_( self._owner.glyphAtIndex_(Key) )
		else:
			self._owner.removeGlyph_( self._owner.glyphForName_(Key) )
	def __iter__(self):
		for index in range(self._owner.countOfGlyphs()):
			yield self._owner.glyphAtIndex_(index)
	def __contains__(self, item):
		return self._owner.indexOfGlyph_(item) < (self._owner.count() * 2) #indexOfGlyph_ returns NSNotFound which is some very big number
		
	def keys(self):
		return self._owner.pyobjc_instanceMethods.glyphs().valueForKeyPath_("@unionOfObjects.name")
	def values(self):
		return self._owner.pyobjc_instanceMethods.glyphs()
	def items(self):
		return self._owner.pyobjc_instanceMethods.glyphs()
	def has_key(self, Key):
		return self._owner.glyphForName_(Key) != None
	def append(self, Glyph):
		self._owner.addGlyph_(Glyph)
	def __len__(self):
		return self._owner.count()


class FontFontMasterProxy (Proxy):
	def __getitem__(self, Key):
		if type(Key) is int:
			if Key < 0:
				Key = self.__len__() + Key
			return self._owner.fontMasterAtIndex_(Key)
		elif type(Key) is str:
			return self._owner.fontMasterForId_(Key)
		else:
			raise(KeyError)
	def __setitem__(self, Key, FontMaster):
		if type(Key) is int:
			self._owner.replaceFontMasterAtIndex_withFontMaster_(Key, FontMaster)
		elif type(Key) is str:
			OldFontMaster = self._owner.fontMasterForId_(Key)
			self._owner.removeFontMaster_(OldFontMaster)
			return self._owner.addFontMaster_(FontMaster)
	def __delitem__(self, Key):
		if type(Key) is int:
			return self._owner.removeFontMasterAtIndex_(Key)
		else:
			OldFontMaster = self._owner.fontMasterForId_(Key)
			return self._owner.removeFontMaster_(OldFontMaster)
	def __iter__(self):
		for index in range(self._owner.countOfFontMasters()):
			yield self._owner.fontMasterAtIndex_(index)
	def __len__(self):
		return self._owner.countOfFontMasters()


class FontInstancesProxy (Proxy):
	def __getitem__(self, Key):
		if type(Key) is int:
			if Key < 0:
				Key = self.__len__() + Key
			return self._owner.instanceAtIndex_(Key)
		else:
			raise(KeyError)
	def __setitem__(self, Key, Class):
		if type(Key) is int:
			self._owner.replaceObjectInInstancesAtIndex_withObject_(Key, Class)
	def __delitem__(self, Key):
		if type(Key) is int:
			return self._owner.removeObjectFromInstancesAtIndex_(Key)
	def __iter__(self):
		for index in range(self._owner.countOfInstances()):
			yield self._owner.instanceAtIndex_(index)
	def append(self, Class):
		 # print "append Class", Class
		#NewClass = GSClass.alloc().init()
		self._owner.addClass_(Class)
	def __len__(self):
		return self._owner.countOfInstances()



class FontClassesProxy (Proxy):
	def __getitem__(self, Key):
		if type(Key) is int:
			if Key < 0:
				Key = self.__len__() + Key
			return self._owner.objectInClassesAtIndex_(Key)
		else:
			raise(KeyError)
	def __setitem__(self, Key, Class):
		if type(Key) is int:
			self._owner.replaceObjectInClassesAtIndex_withObject_(Key, Class)
	def __delitem__(self, Key):
		if type(Key) is int:
			return self._owner.removeObjectFromClassesAtIndex_(Key)
	def __iter__(self):
		for index in range(self._owner.countOfClasses()):
			yield self._owner.objectInClassesAtIndex_(index)
	def append(self, Class):
		 # print "append Class", Class
		#NewClass = GSClass.alloc().init()
		self._owner.addClass_(Class)
	def __len__(self):
		return self._owner.countOfClasses()



class FontFeaturesProxy (Proxy):
	def __getitem__(self, Key):
		if type(Key) is int:
			if Key < 0:
				Key = self.__len__() + Key
			return self._owner.featureAtIndex_(Key)
		else:
			raise(KeyError)
	def __setitem__(self, Key, Feature):
		if type(Key) is int:
			self._owner.replaceFeatureAtIndex_withFeature_(Key, Feature)
	def __delitem__(self, Key):
		if type(Key) is int:
			return self._owner.removeFeatureAtIndex_(Key)
		else:
			raise(KeyError)
	def __iter__(self):
		for index in range(self._owner.featuresCount()):
			yield self._owner.featureAtIndex_(index)
	def append(self, Feature):
		#print "append", Node
		self._owner.addFeature_(Feature)

	def __len__(self):
		return self._owner.featuresCount()
	def text(self):
		LineList = []
		for Feature in self._owner.pyobjc_instanceMethods.features():
			LineList.append("feature ")
			LineList.append(Feature.name)
			LineList.append(" {\n")
			LineList.append("    "+Feature.code)
			LineList.append("\n} ")
			LineList.append(Feature.name)
			LineList.append(" ;\n")
		return "".join(LineList)


class FeatureSubstitutionsProxy (Proxy):
	def __getitem__(self, Key):
		if type(Key) is int:
			if Key < 0:
				Key = self.__len__() + Key
			return self._owner.objectInSubstitutionsAtIndex_(Key)
		else:
			raise(KeyError)
	def __setitem__(self, Key, Class):
		if type(Key) is int:
			self._owner.replaceObjectInSubstitutionsAtIndex_withObject_(Key, Class)
	def __delitem__(self, Key):
		if type(Key) is int:
			return self._owner.removeObjectFromSubstitutionsAtIndex_(Key)
		else:
			raise(KeyError)
	def append(self, Substitution):
		 # print "append Class", Class
		#NewClass = GSClass.alloc().init()
		self._owner.addSubstitution_(Substitution)
	def __len__(self):
		return self._owner.countOfSubstitutions()



class LayersIterator:
	def __init__(self, owner):
		self.curInd = 0
		self._owner = owner
	def __iter__(self):
		return self
	def next(self):
		if self._owner.parent:
			if self.curInd >= self._owner.countOfLayers():
				raise StopIteration
			if self.curInd < self._owner.parent.countOfFontMasters():
				FontMaster = self._owner.parent.fontMasterAtIndex_(self.curInd)
				Item = self._owner.layerForKey_(FontMaster.id)
			else:
				ExtraLayerIndex = self.curInd - self._owner.parent.countOfFontMasters()
				Index = 0
				ExtraLayer = None
				while ExtraLayerIndex >= 0:
					ExtraLayer = self._owner.pyobjc_instanceMethods.layers().objectAtIndex_(Index)
					if ExtraLayer.layerId != ExtraLayer.associatedMasterId:
						ExtraLayerIndex = ExtraLayerIndex - 1
					Index = Index + 1
				Item = ExtraLayer
			self.curInd += 1
			return Item
		return None

class GlyphLayerProxy (Proxy):
	def __getitem__(self, Key):
			if type(Key) is int:
				if Key < 0:
					Key = self.__len__() + Key
				if self._owner.parent and Key < self._owner.parent.countOfFontMasters():
					FontMaster = self._owner.parent.fontMasterAtIndex_(Key)
					return self._owner.layerForKey_(FontMaster.id)
				else:
					ExtraLayerIndex = Key - self._owner.parent.countOfFontMasters()
					Index = 0
					ExtraLayer = None
					while ExtraLayerIndex >= 0:
						ExtraLayer = self._owner.pyobjc_instanceMethods.layers().objectAtIndex_(Index)
						if ExtraLayer.layerId != ExtraLayer.associatedMasterId:
							ExtraLayerIndex = ExtraLayerIndex - 1
						Index = Index + 1
					return ExtraLayer
			else:
				return self._owner.layerForKey_(Key)
	def __setitem__(self, Key, Layer):
		if type(Key) is int and self._owner.parent:
			FontMaster = self._owner.parent.fontMasterAtIndex_(Key)
			return self._owner.setLayer_forKey_(Layer, FontMaster.id)
		else:
			return self._owner.setLayer_forKey_(Layer, Key)
	def __delitem__(self, Key):
		if type(Key) is int and self._owner.parent:
			FontMaster =  self._owner.parent.fontMasterAtIndex_(Key)
			return self._owner.removeLayerForKey_(FontMaster.id)
		else:
			return self._owner.removeLayerForKey_(Key)
	def __iter__(self):
		return LayersIterator(self._owner)
	def __len__(self):
		return self._owner.pyobjc_instanceMethods.layers().count()
		


class LayerComponentsProxy (Proxy):
	def __getitem__(self, i):
		return self._owner.componentAtIndex_(i)
	def __setitem__(self, i, Component):
		self._owner.setComponent_atIndex_(Component, i)
	def __delitem__(self, i):
		self._owner.removeComponentAtIndex_(i)
	def __iter__(self):
		for index in range(self._owner.componentCount()):
			yield self._owner.componentAtIndex_(index)
	def append(self, Component):
		self._owner.addComponent_(Component)
	def __len__(self):
		return self._owner.componentCount()
		

		
class LayerGuideLinesProxy (Proxy):
	def __getitem__(self, i):
		return self._owner.guideLineAtIndex_(i)
	def __setitem__(self, i, Component):
		self._owner.setGuideLine_atIndex_(Component, i)
	def __delitem__(self, i):
		self._owner.removeGuideLineAtIndex_(i)
	def __iter__(self):
		for index in range(self._owner.guideLineCount()):
			yield self._owner.guideLineAtIndex_(index)
	def append(self, GuideLine):
		self._owner.addGuideLine_(GuideLine)
	def __len__(self):
		return self._owner.guideLineCount()


class LayerHintsProxy (Proxy):
	def __getitem__(self, i):
		return self._owner.hintAtIndex_(i)
	def __setitem__(self, i, Component):
		self._owner.setHint_atIndex_(Component, i)
	def __delitem__(self, i):
		self._owner.removeObjectFromHintsAtIndex_(i)
	def __iter__(self):
		for index in range(self._owner.countOfHints()):
			yield self._owner.hintAtIndex_(index)
	def append(self, GuideLine):
		self._owner.addHint_(GuideLine)
	def __len__(self):
		return self._owner.countOfHints()
	

class LayerAnchorsProxy (Proxy):
	"""layer.anchors is a dict!!!"""
	def __getitem__(self, Key):
		if type(Key) is str:
			return self._owner.anchorForName_(Key)
		else:
			raise TypeError
	def __setitem__(self, Key, Anchor):
		#print "__setitem__", i, Node
		if type(Key) is str:
			Anchor.setName_(Key)
			self._owner.addAnchor_(Anchor)
		else:
			raise TypeError
	def __delitem__(self, Key):
		#print "__delitem__", i
		if type(Key) is str:
			self._owner.removeAnchorWithName_(Key)
		else:
			raise TypeError
	def __iter__(self):
		for Anchor in self._owner.pyobjc_instanceMethods.anchors().items():
			yield Anchor
	# def append(self, Anchor):
	# 	#print "append", Node
	# 	self._owner.addAnchor_(Anchor)
	
	def keys(self):
		return self._owner.pyobjc_instanceMethods.anchors().allKeys()
	def __len__(self):
		#print "count"
		return self._owner.anchorCount()



class LayerPathsProxy (Proxy):
	def __getitem__(self, Key):
		if Key < 0:
			Key = self._owner.pathCount() + Key
		return self._owner.pathAtIndex_(Key)
	def __setitem__(self, i, Path):
		self._owner.setPath_atIndex_(Path, i)
	def __delitem__(self, i):
		self._owner.removePathAtIndex_(i)
	def __iter__(self):
		for index in range(self._owner.pathCount()):
			yield self._owner.pathAtIndex_(index)
	def append(self, Path):
		self._owner.addPath_(Path)
	def __len__(self):
		return self._owner.pathCount()
				



class PathNodesProxy (Proxy):
	def __getitem__(self, i):
		#print "__getitem__", i
		return self._owner.nodeAtIndex_(i)
	def __setitem__(self, i, Node):
		#print "__setitem__", i, Node
		self._owner.setNode_atIndex_(Node, i)
	def __delitem__(self, i):
		#print "__delitem__", i
		self._owner.removeNodeAtIndex_(i)
	def __iter__(self):
		for index in range(self._owner.countOfNodes()):
			yield self._owner.nodeAtIndex_(index)
	def append(self, Node):
		#print "append", Node
		self._owner.addNode_(Node)
	def __len__(self):
		return self._owner.countOfNodes()






##################################################################################
#
#
#
#           GSFont
#
#
#
##################################################################################

		
'''
:mod:`GSFont`
===============================================================================

Implementation of the font object. This object is host to the :class:`Masters <GSFontMaster>` used for interpolation. Even when no interpolation is involved, for the sake of object model consistency there will still be one master and one instance representing a single font.

Also, the :class:`Glyphs <GSGlyph>` are attached to the Font object right here, not one level down to the masters. The different master's glyphs are available as :class:`Layers <GSLayer>` attached to the :class:`Glyph <GSGlyph>` objects which are attached here.

.. class:: GSFont

**Properties**

.. autosummary::

	masters
	instances
	glyphs
	classes
	features
	copyright
	designer
	designerURL
	manufacturer
	manufacturerURL
	versionMajor
	versionMinor
	date
	familyName
	upm
	note
	kerning
	userData
	gridLength
	disablesNiceNames
	customParameters

**Functions**

.. autosummary::

	kerningForPair()
	setKerningForPair()
	removeKerningForPair()

----------
Properties
----------

'''


def Font__new__(typ, *args, **kwargs):
	return GSFont.alloc().init()
GSFont.__new__ = Font__new__;

def Font__init__(self):
	pass
GSFont.__init__ = Font__init__;

def Font__repr__(self):
	return "<GSFont \"%s\" v%s.%s with %s masters and %s instances>" % (self.familyName, self.versionMajor, self.versionMinor, len(self.masters), len(self.instances))
GSFont.__repr__ = Font__repr__;



GSFont.parent = property(lambda self: self.valueForKey_("parent"))

GSFont.masters = property(lambda self: FontFontMasterProxy(self))
'''.. attribute:: masters
	Collection of :class:`GSFontMaster <GSFontMaster>`.
	:type: list'''

GSFont.instances = property(lambda self: FontInstancesProxy(self))
'''.. attribute:: instances
	Collection of :class:`GSInstance <GSInstance>`.
	:type: list'''

GSFont.glyphs = property(lambda self: FontGlyphsProxy(self))
'''.. attribute:: glyphs
	Collection of :class:`GSGlyph <GSGlyph>`. Returns a list, but you may also call glyphs using index or glyph name as key.
	.. code-block:: python
		print font.glyphs['A']
		<GSGlyph "A" with 4 layers>
	.. code-block:: python
		print font.glyphs[20]
		<GSGlyph "Aacute" with 2 layers>
	:type: list, dict'''
GSFont.classes = property(lambda self: FontClassesProxy(self))
'''.. attribute:: classes
	Collection of :class:`GSClass <GSClass>` objects, representing OpenType glyph classes.
	:type: list'''
GSFont.features = property(lambda self: FontFeaturesProxy(self))
'''.. attribute:: features
	Collection of :class:`GSFeature <GSFeature>` objects, representing OpenType features.
	:type: list'''
GSFont.copyright = property(lambda self: self.valueForKey_("copyright"), lambda self, value: self.setValue_forKey_(value, "copyright"))
'''.. attribute:: copyright
	:type: unicode'''
GSFont.designer = property(lambda self: self.valueForKey_("designer"), lambda self, value: self.setValue_forKey_(value, "designer"))
'''.. attribute:: designer
	:type: unicode'''
GSFont.designerURL = property(lambda self: self.valueForKey_("designerURL"), lambda self, value: self.setValue_forKey_(value, "designerURL"))
'''.. attribute:: designerURL
	:type: unicode'''
GSFont.manufacturer = property(lambda self: self.valueForKey_("manufacturer"), lambda self, value: self.setValue_forKey_(value, "manufacturer"))
'''.. attribute:: manufacturer
	:type: unicode'''
GSFont.manufacturerURL = property(lambda self: self.valueForKey_("manufacturerURL"), lambda self, value: self.setValue_forKey_(value, "manufacturerURL"))
'''.. attribute:: manufacturerURL
	:type: unicode'''
GSFont.versionMajor = property(lambda self: self.valueForKey_("versionMajor"), lambda self, value: self.setValue_forKey_(value, "versionMajor"))
'''.. attribute:: versionMajor
	:type: int'''
GSFont.versionMinor = property(lambda self: self.valueForKey_("versionMinor"), lambda self, value: self.setValue_forKey_(value, "versionMinor"))
'''.. attribute:: versionMinor
	:type: int'''
GSFont.date = property(lambda self: self.valueForKey_("date"), lambda self, value: self.setValue_forKey_(value, "date"))
'''.. attribute:: date
	:type: NSDate'''
GSFont.familyName = property(lambda self: self.valueForKey_("familyName"), 
							 lambda self, value: self.setFamilyName_(value))
'''.. attribute:: familyName
	Family name of the typeface.
	:type: string'''
GSFont.upm = property(lambda self: self.valueForKey_("unitsPerEm"))
'''.. attribute:: upm
	Units per Em
	:type: int'''
GSFont.note = property(lambda self: self.valueForKey_("note"), 
							 lambda self, value: self.setValue_forKey_(value, "note"))
'''.. attribute:: note
	:type: string'''
GSFont.kerning = property(lambda self: self.valueForKey_("kerning"), lambda self, value: self.setKerning_(value))
'''.. attribute:: kerning
	A multi-level dictionary. The first level's key is the :class:`GSFontMaster <GSFontMaster>`.id (each master has its own kerning), the second level's key is the :class:`GSGlyph <GSGlyph>`.id or class id (@MMK_L_XX), the third level's key is again a glyph id or class id (@MMK_R_XX). The values are the actual kerning values.
	
	To set a value, is is better to use the method Font.setKerningForPair(). This ensures a better data integrety (and is faster).
	:type: dict, int
'''
GSFont.userData = property(lambda self: self.pyobjc_instanceMethods.userData(), lambda self, value: self.setUserData_(value))
'''.. attribute:: userData
	A dictionary to store user data. Use a unique Key and only use object that can be stored in a Property list (string, list, dict, numbers, NSData) otherwise the date will not be recoverable from the saved file.
	:type: dict'''
GSFont.disablesNiceNames = property(lambda self: self.valueForKey_("disablesNiceNames").boolValue(), lambda self, value: self.setValue_forKey_(value, "disablesNiceNames"))
'''.. attribute:: disablesNiceNames
	Corresponds to the "Don't use nice names" setting from the Info dialogue.
	:type: bool'''
GSFont.customParameters = property(lambda self: self.valueForKey_("fontInfoDict"), lambda self, value: self.setValue_forKey_(value, "fontInfoDict"))
'''.. attribute:: customParameters
	A dictionary of custom parameters
	:type: dict'''
GSFont.gridLength = property(lambda self: self.valueForKey_("gridLength").intValue(), lambda self, value: self.setValue_forKey_(value, "gridLength"))
'''.. attribute:: gridLength
	Corresponds to the "Grid spacing" setting from the Info dialogue. When set to 0, point positions may contains float values.
	:type: int'''

GSFont.selectedLayers = property(lambda self: self.parent.selectedLayers())
'''.. attribute:: selectedLayers
	Returns a list of all currently selected Layers in the active Tab
	:type: list'''
'''
---------
Functions
---------
'''


def kerningForPair(self, FontMasterID, LeftKeringId, RightKerningId ):
	if not LeftKeringId[0] == '@':
		LeftKeringId = self.glyphs[LeftKeringId].id
	if not RightKerningId[0] == '@':
		RightKerningId = self.glyphs[RightKerningId].id
	return self.kerningForFontMasterID_LeftKey_RightKey_(FontMasterID, LeftKeringId, RightKerningId)
GSFont.kerningForPair = kerningForPair
'''.. function:: kerningForPair(FontMasterId, LeftKey, RightKey)
	
	This returns the kerning value for the two specified glyphs (LeftKey or RightKey is the glyphname) or a kerning group key (@MMK_X_XX).
	
	:param FontMasterId: The id of the FontMaster
	:type FontMasterId: str
	:param LeftKey: either a glyph name or a class name
	:type LeftKey: str
	:param RightKey: either a glyph name or a class name
	:type RightKey: str
	:return: The kerning value
	:rtype: float'''

def setKerningForPair(self, FontMasterID, LeftKeringId, RightKerningId, Value):
	if not LeftKeringId[0] == '@':
		LeftKeringId = self.glyphs[LeftKeringId].id
	if not RightKerningId[0] == '@':
		RightKerningId = self.glyphs[RightKerningId].id
	self.setKerningForFontMasterID_LeftKey_RightKey_Value_(FontMasterID, LeftKeringId, RightKerningId, Value)
GSFont.setKerningForPair = setKerningForPair
'''.. function:: setKerningForPair(FontMasterId, LeftKey, RightKey, Value)
	
	This sets the kerning for the two specified glyphs (LeftKey or RightKey is the glyphname) or a kerning group key (@MMK_X_XX).
	
	:param FontMasterId: The id of the FontMaster
	:type FontMasterId: str
	:param LeftKey: either a glyph name or a class name
	:type LeftKey: str
	:param RightKey: either a glyph name or a class name
	:type RightKey: str
	:param Value: kerning value
	:type Value: float'''

def removeKerningForPair(self, FontMasterID, LeftKeringId, RightKerningId):
	if not LeftKeringId[0] == '@':
		LeftKeringId = self.glyphs[LeftKeringId].id
	if not RightKerningId[0] == '@':
		RightKerningId = self.glyphs[RightKerningId].id
	self.removeKerningForFontMasterID_LeftKey_RightKey_(FontMasterID, LeftKeringId, RightKerningId)
GSFont.removeKerningForPair = removeKerningForPair
'''.. function:: removeKerningForPair(FontMasterId, LeftKey, RightKey)
	
	Removes the kerning for the two specified glyphs (LeftKey or RightKey is the glyphname) or a kerning group key (@MMK_X_XX).
	
	:param FontMasterId: The id of the FontMaster
	:type FontMasterId: str
	:param LeftKey: either a glyph name or a class name
	:type LeftKey: str
	:param RightKey: either a glyph name or a class name
	:type RightKey: str'''






##################################################################################
#
#
#
#           GSFontMaster
#
#
#
##################################################################################


'''

:mod:`GSFontMaster`
===============================================================================

Implementation of the master object. This corresponds more or less with the "Masters" pane in the Font Info.

In Glyphs.app the glyphs of each master are reachable not here, but as :class:`Layers <GSLayer>` attached to the :class:`Glyphs <GSGlyph>` attached to the :class:`Font <GSFont>` object. See info graphic on top for better understanding.

.. class:: GSFontMaster

'''

def FontMaster__new__(typ, *args, **kwargs):
	return GSFontMaster.alloc().init()
GSFontMaster.__new__ = FontMaster__new__;

def FontMaster__init__(self):
	pass
GSFontMaster.__init__ = FontMaster__init__;

def FontMaster__repr__(self):
	return "<GSFontMaster \"%s\" width %s weight %s>" % (self.name, self.widthValue, self.weightValue)
GSFontMaster.__repr__ = FontMaster__repr__;

'''

.. autosummary::

	name
	id
	weight
	width
	weightValue
	widthValue
	custom
	customValue
	ascender
	capHeight
	xHeight
	descender
	italicAngle
	verticalStems
	horizontalStems
	alignmentZones
	guideLines
	userData
	customParameters

----------
Properties
----------

'''

GSFontMaster.id = property(lambda self: self.valueForKey_("id"), lambda self, value: self.setId_(value))
'''.. attribute:: id
	Used to identify :class:`GSLayer <Layer>` in the Glyph
	:type: unicode'''
GSFontMaster.name = property(lambda self: self.valueForKey_("name"), lambda self, value: self.setName_(value))
'''.. attribute:: name
	:type: string'''
GSFontMaster.weight = property(lambda self: self.valueForKey_("weight"), lambda self, value: self.setValue_forKey_(value, "weight"))
'''.. attribute:: weight
	:type: string'''
GSFontMaster.width = property(lambda self: self.valueForKey_("width"), lambda self, value: self.setValue_forKey_(value, "width"))
'''.. attribute:: width
	:type: string'''
GSFontMaster.weightValue = property(lambda self: self.valueForKey_("weightValue"), lambda self, value: self.setValue_forKey_(value, "weightValue"))
'''.. attribute:: weightValue
	Values for interpolation in design space.
	:type: float'''
GSFontMaster.widthValue = property(lambda self: self.valueForKey_("widthValue"), lambda self, value: self.setValue_forKey_(value, "widthValue"))
'''.. attribute:: widthValue
	Values for interpolation in design space.
	:type: float'''
GSFontMaster.custom = property(lambda self: self.valueForKey_("custom"), lambda self, value: self.setValue_forKey_(value, "custom"))
'''.. attribute:: custom
	:type: string'''
GSFontMaster.customValue = property(lambda self: self.valueForKey_("customValue"), lambda self, value: self.setValue_forKey_(value, "customValue"))
'''.. attribute:: customValue
	Values for interpolation in design space.'''
GSFontMaster.ascender = property(lambda self: self.valueForKey_("ascender"), lambda self, value: self.setValue_forKey_(value, "ascender"))
'''.. attribute:: ascender
	:type: float'''
GSFontMaster.capHeight = property(lambda self: self.valueForKey_("capHeight"), lambda self, value: self.setValue_forKey_(value, "capHeight"))
'''.. attribute:: capHeight
	:type: float'''
GSFontMaster.xHeight = property(lambda self: self.valueForKey_("xHeight"), lambda self, value: self.setValue_forKey_(value, "xHeight"))
'''.. attribute:: xHeight
	:type: float'''
GSFontMaster.descender = property(lambda self: self.valueForKey_("descender"), lambda self, value: self.setValue_forKey_(value, "descender"))
'''.. attribute:: descender
	:type: float'''
GSFontMaster.italicAngle = property(lambda self: self.valueForKey_("italicAngle"), lambda self, value: self.setValue_forKey_(value, "italicAngle"))
'''.. attribute:: italicAngle
	:type: float'''
GSFontMaster.verticalStems = property(lambda self: self.valueForKey_("verticalStems"), lambda self, value: self.setValue_forKey_(value, "verticalStems"))
'''.. attribute:: verticalStems
	List of vertical stem values
	:type: list'''
GSFontMaster.horizontalStems = property(lambda self: self.valueForKey_("horizontalStems"), lambda self, value: self.setValue_forKey_(value, "horizontalStems"))
'''.. attribute:: horizontalStems
	List of horizontal stem values
	:type: list'''
GSFontMaster.alignmentZones = property(lambda self: self.valueForKey_("alignmentZones"), lambda self, value: self.setValue_forKey_(value, "alignmentZones"))
'''.. attribute:: alignmentZones
	Collection of :class:`GSAlignmentZone <GSAlignmentZone>`.
	:type: list'''
GSFontMaster.guideLines = property(lambda self: self.valueForKey_("guideLines"), lambda self, value: self.setValue_forKey_(value, "guideLines"))
'''.. attribute:: guideLines
	Collection of :class:`GSGuideLine <GSGuideLine>`.
	:type: list'''
GSFontMaster.userData = property(lambda self: self.valueForKey_("userData"), lambda self, value: self.setValue_forKey_(value, "userData"))
'''.. attribute:: userData
	A dictionary to store user data. Use a unique Key and only use object that can be stored in a Property list (string, list, dict, numbers, NSData) otherwise the date will not be recoverable from the saved file.
	:type: dict'''
GSFontMaster.customParameters = property(lambda self: self.valueForKey_("customParameters"), lambda self, value: self.setValue_forKey_(value, "customParameters"))
'''.. attribute:: customParameters
	A dictionary of custom parameters
	:type: dict'''










##################################################################################
#
#
#
#           GSInstance
#
#
#
##################################################################################


'''

:mod:`GSInstance`
===============================================================================

Implementation of the instance object. This corresponds more or less with the "Instances" pane in the Font Info.

.. class:: GSInstance

'''

def Instance__new__(typ, *args, **kwargs):
	return GSInstance.alloc().init()
GSInstance.__new__ = Instance__new__;

def Instance__init__(self):
	pass
GSInstance.__init__ = Instance__init__;

def Instance__repr__(self):
	return "<GSInstance \"%s\" width %s weight %s>" % (self.name, self.widthValue, self.weightValue)
GSInstance.__repr__ = Instance__repr__;


'''
.. autosummary::

	active
	name
	weight
	width
	weightValue
	widthValue
	isItalic
	isBold
	linkStyle
	customParameters

----------
Properties
----------

'''

GSInstance.active = property(lambda self: self.valueForKey_("active"), lambda self, value: self.setValue_forKey_(value, "active"))
'''.. attribute:: active
	:type: bool'''
GSInstance.name = property(lambda self: self.valueForKey_("name"), lambda self, value: self.setName_(value))
'''.. attribute:: name
	:type: string'''
GSInstance.weight = property(lambda self: self.valueForKey_("weightClass"), lambda self, value: self.setValue_forKey_(value, "weightClass"))
'''.. attribute:: weight
	:type: string'''
GSInstance.width = property(lambda self: self.valueForKey_("widthClass"), lambda self, value: self.setValue_forKey_(value, "widthClass"))
'''.. attribute:: width
	:type: string'''
GSInstance.weightValue = property(lambda self: self.valueForKey_("interpolationWeight"), lambda self, value: self.setValue_forKey_(value, "interpolationWeight"))
'''.. attribute:: weightValue
	Values for interpolation in design space.
	:type: float'''
GSInstance.widthValue = property(lambda self: self.valueForKey_("interpolationWidth"), lambda self, value: self.setValue_forKey_(value, "interpolationWidth"))
'''.. attribute:: widthValue
	Values for interpolation in design space.
	:type: float'''
GSInstance.isItalic = property(lambda self: self.valueForKey_("isItalic"), lambda self, value: self.setValue_forKey_(value, "isItalic"))
'''.. attribute:: isItalic
	Italic flag for style linking
	:type: bool'''
GSInstance.isBold = property(lambda self: self.valueForKey_("isBold"), lambda self, value: self.setValue_forKey_(value, "isBold"))
'''.. attribute:: isBold
	Bold flag for style linking
	:type: bool'''
GSInstance.linkStyle = property(lambda self: self.valueForKey_("linkStyle"), lambda self, value: self.setValue_forKey_(value, "linkStyle"))
'''.. attribute:: linkStyle
	Linked style
	:type: string'''
GSInstance.customParameters = property(lambda self: self.valueForKey_("customParameters"), lambda self, value: self.setValue_forKey_(value, "customParameters"))
'''.. attribute:: customParameters
	A dictionary of custom parameters
	:type: dict'''












##################################################################################
#
#
#
#           GSClass
#
#
#
##################################################################################

'''
:mod:`GSClass`
===============================================================================

Implementation of the class object. It is used to implement OpenType classes in the font infos

.. class:: GSClass

Properties

.. autosummary::

	name
	code
	automatic

----------
Properties
----------

'''

def Class__new__(typ, *args, **kwargs):
	return GSClass.alloc().init()
GSClass.__new__ = Class__new__;

def Class__init__(self):
	pass
GSClass.__init__ = Class__init__;

def Class__repr__(self):
	return "<GSClass \"%s\">" % (self.name)
GSClass.__repr__ = Class__repr__;

GSClass.name = property(lambda self: self.valueForKey_("name"), 
							 lambda self, value: self.setName_(value))
'''.. attribute:: name
	The Class name
	:type: unicode'''
GSClass.code = property(lambda self: self.valueForKey_("code"), 
							 lambda self, value: self.setCode_(value))
'''.. attribute:: code
	A String with space seperated glyph names.
	:type: unicode
'''
GSClass.automatic = property(lambda self: self.valueForKey_("automatic").boolValue(), 
							 lambda self, value: self.setAutomatic_(value))
'''.. attribute:: automatic
	Auto-generate this class
	:type: bool
'''










##################################################################################
#
#
#
#           GSFeature
#
#
#
##################################################################################

'''

:mod:`GSFeature`
===============================================================================

Implementation of the feature object. It is used to implement OpenType Features in the Font Info.

.. class:: GSFeature([tag])
	
	:param tag: The feature name
	
Properties

.. autosummary::

	name
	code
	automatic
	
Functions

.. autosummary::

	update
	

----------
Properties
----------

'''


def Feature__new__(typ, *args, **kwargs):
	#print "new", args, kwargs
	return GSFeature.alloc().init()
GSFeature.__new__ = Feature__new__;

def Feature__init__(self, tag = None ):
	if (tag):
		self.setName_(tag)
GSFeature.__init__ = Feature__init__;

def Feature__repr__(self):
	return "<GSFeature \"%s\">" % (self.name)
GSFeature.__repr__ = Feature__repr__;

GSFeature.name = property(lambda self: self.valueForKey_("name"), 
								 lambda self, value: self.setName_(value))
'''.. attribute:: name
	The feature name
	:type: unicode'''
#GSFeature.substitutions = property(lambda self: FeatureSubstitutionsProxy(self))

#GSFeature.flag = property(lambda self: self.valueForKey_("flag"), 
#								 lambda self, value: self.setFlag_(value))
GSFeature.code = property(lambda self: self.valueForKey_("code"), 
								 lambda self, value: self.setCode_(value))
'''.. attribute:: code
	The Feature code in Adobe FDK syntax.
	:type: unicode'''
GSFeature.automatic = property(lambda self: self.valueForKey_("automatic").boolValue(), 
								 lambda self, value: self.setAutomatic_(value))
'''.. attribute:: automatic
	Auto-generate this feature
	:type: bool
'''

'''

---------
Functions
---------


'''

'''.. function:: update()
	
	Calls the automatic feature code generator for this feature.
	
	:return: None
'''











##################################################################################
#
#
#
#           GSSubstitution
#
#
#
##################################################################################


"""

############ NOCH NICHT DOKUMENTIERT WEIL NOCH NICHT AUSGEREIFT ############ 

"""


def Substitution__new__(typ, *args, **kwargs):
	return GSSubstitution.alloc().init()
GSSubstitution.__new__ = Substitution__new__;

def Substitution__init__(self):
	pass
GSSubstitution.__init__ = Substitution__init__;


GSSubstitution.source = property(lambda self: self.valueForKey_("back"), 
								 lambda self, value: self.setBack_(value))
GSSubstitution.source = property(lambda self: self.valueForKey_("source"), 
								 lambda self, value: self.setSource_(value))
GSSubstitution.forward = property(lambda self: self.valueForKey_("fwd"), 
								 lambda self, value: self.setFwd_(value))

GSSubstitution.target = property(lambda self: self.valueForKey_("target"), 
								 lambda self, value: self.setTarget_(value))
GSSubstitution.languageTag = property(lambda self: self.valueForKey_("languageTag"), 
								 lambda self, value: self.setLanguageTag_(value))
GSSubstitution.scriptTag = property(lambda self: self.valueForKey_("scriptTag"), 
								 lambda self, value: self.setScriptTag_(value))











##################################################################################
#
#
#
#           GSGlyph
#
#
#
##################################################################################

'''


:mod:`GSGlyph`
===============================================================================

Implementation of the glyph object

.. class:: GSGlyph([name])
	
	:param name: The glyph name

.. autosummary::

	parent
	layers
	name
	unicode
	id
	category
	subCategory
	script
	leftKerningGroup
	rightKerningGroup
	leftMetricsKey
	rightMetricsKey
	export
	color
	note
	

----------
Properties
----------
	
'''

def Glyph__new__(typ, *args, **kwargs):
	return GSGlyph.alloc().init()
GSGlyph.__new__ = Glyph__new__;

def Glyph__init__(self, name=None):
	if name and isinstance(name, str):
		self.setName_(name)
GSGlyph.__init__ = Glyph__init__;

def Glyph__repr__(self):
	return "<GSGlyph \"%s\" with %s layers>" % (self.name, len(self.layers))
GSGlyph.__repr__ = Glyph__repr__;

GSGlyph.parent = property(			lambda self: self.valueForKey_("parent"),
									lambda self, value: self.setParent_(value)) 
'''.. attribute:: parent
	Reference to the :class:`Font <GSFont>` object.
	:type: GSFont'''
GSGlyph.layers = property(			lambda self: GlyphLayerProxy(self))

'''.. attribute:: layers
	The layers of the glyph, collection of :class:`GSLayer <GSLayer>` objects. You can access them either by index or by :class:`GSFontMaster <GSFontMaster>`.id.
	:type: list, dict'''
GSGlyph.name = property(			lambda self: str(self.valueForKey_("name")),
									lambda self, value: self.setName_(value))
'''.. attribute:: name
	The name of the glyph. It will be converted to a "nice name" (afii10017 to A-cy) (you can disable this behavior in font info or the app preference)
	:type: unicode'''
GSGlyph.unicode = property(			lambda self: str(self.valueForKey_("unicode")))
'''.. attribute:: unicode
	It will be automatically set; Read only.
	:type: unicode'''
GSGlyph.id = property(				lambda self: str(self.valueForKey_("id")),
									lambda self, value: self.setId_(value))
'''.. attribute:: id
	An unique identifierer for each glyph
	:type: unicode'''
GSGlyph.category = property(		lambda self: self.valueForKey_("category"))
'''.. attribute:: category
	The category of the glyph. e.g. 'Letter', 'Symbol'
	:type: unicode'''
GSGlyph.subCategory = property(		lambda self: self.valueForKey_("subCategory"))
'''.. attribute:: subCategory
	The subCategory of the glyph. e.g. 'Uppercase', 'Math'
	:type: unicode'''
GSGlyph.script = property(			lambda self: self.valueForKey_("script"))
'''.. attribute:: script
	The script of the glyph, e.g. 'Latin', 'Arabic'.
	:type: unicode'''
GSGlyph.leftKerningGroup = property(lambda self: self.valueForKey_("leftKerningGroup"), 
									lambda self, value: self.setLeftKerningGroup_(value))
'''.. attribute:: leftKerningGroup
	The leftKerningGroup of the glyph. All glyphs with the same text in the kerning group end up in the same kerning class.
	:type: unicode'''
GSGlyph.rightKerningGroup = property(lambda self: self.valueForKey_("rightKerningGroup"), 
									lambda self, value: self.setRightKerningGroup_(value))
'''.. attribute:: rightKerningGroup
	The rightKerningGroup of the glyph. All glyphs with the same text in the kerning group end up in the same kerning class.
	:type: unicode'''
GSGlyph.leftMetricsKey =  property(	lambda self: self.valueForKey_("leftMetricsKey"), 
									lambda self, value: self.setLeftMetricsKey_(value))
'''.. attribute:: leftMetricsKey
	The leftMetricsKey of the glyph. This is a reference to another glyph by name. It is used to synchronize the metrics with the linked glyph.
	:type: unicode'''
GSGlyph.rightMetricsKey = property(	lambda self: self.valueForKey_("rightMetricsKey"), 
									lambda self, value: self.setRightMetricsKey_(value))
'''.. attribute:: rightMetricsKey
	The rightMetricsKey of the glyph. This is a reference to another glyph by name. It is used to synchronize the metrics with the linked glyph.
	:type: unicode'''
GSGlyph.export =		  property( lambda self: self.valueForKey_("export").boolValue(), 
									lambda self, value: self.setExport_(value))

'''.. attribute:: export
	Glyphs should export upon font generation
	:type: bool'''
GSGlyph.color =			  property( lambda self: self.valueForKey_("colorIndex"), 
									lambda self, value: self.setColorIndex_(value))
'''.. attribute:: color
	Color marking of glyph in UI
	:type: int'''
GSGlyph.note =			  property( lambda self: self.valueForKey_("note"), 
									lambda self, value: self.setNote_(value))
'''.. attribute:: note
	:type: unicode'''










##################################################################################
#
#
#
#           GSLayer
#
#
#
##################################################################################


'''

:mod:`GSLayer`
===============================================================================

Implementation of the layer object

.. class:: GSLayer()

**Properties**

.. autosummary::
	
	parent
	name
	associatedMasterId
	layerId
	components
	guideLines
	hints
	anchors
	paths
	LSB
	RSB
	width

**Functions**

.. autosummary::
	
	decomposeComponents
	compareString
	connectAllOpenPaths
	copyDecomposedLayer
	syncMetrics
	correctPathDirection

----------
Properties
----------

	
	'''

def Layer__new__(typ, *args, **kwargs):
	return GSLayer.alloc().init()
GSLayer.__new__ = Layer__new__;

def Layer__init__(self):
	pass
GSLayer.__init__ = Layer__init__;

def Layer__repr__(self):
	return "<GSLayer \"%s\">" % (self.name)
GSLayer.__repr__ = Layer__repr__;

GSLayer.parent = property(			lambda self: self.valueForKey_("parent"),
									lambda self, value: self.setParent_(value)) 
'''.. attribute:: parent
	Reference to the :class:`Glyph <GSGlyph>` object.
	:type: GSGlyph'''
GSLayer.name = property(			lambda self: self.valueForKey_("name"),
									lambda self, value: self.setName_(value)) 
'''.. attribute:: name
	Name of layer
	:type: unicode'''

GSLayer.associatedMasterId = property(lambda self: self.valueForKey_("associatedMasterId"),
									lambda self, value: self.setAssociatedMasterId_(value)) 
'''.. attribute:: associatedMasterId
	The ID of the :class:`FontMaster <GSFontMaster>` this layer belongs to.
	:type: unicode'''
GSLayer.layerId = property(lambda self: self.valueForKey_("layerId"),
									  lambda self, value: self.setLayerId_(value)) 
'''.. attribute:: layerId
	The layer key is used to access the layer in the :class:`glyphs <GSGlyph>` layer dictionary.
	
	For master layers this should be the id of the :class:`FontMaster <GSFontMaster>`.
	It could look like this: "FBCA074D-FCF3-427E-A700-7E318A949AE5"
	:type: unicode'''

GSLayer.components = property(lambda self: LayerComponentsProxy(self))
'''.. attribute:: components
	Collection of :class:`GSComponent <GSComponent>` objects
	:type: list'''


GSLayer.guideLines = property(lambda self: LayerGuideLinesProxy(self))
'''.. attribute:: guideLines
	List of :class:`GSGuideLine <GSGuideLine>` objects.
	:type: list'''

GSLayer.hints = property(lambda self: LayerHintsProxy(self),
						 lambda self, value: self.setHints_(value))
'''.. attribute:: hints
	List of :class:`GSHint <GSHint>` objects.
	:type: list'''

GSLayer.anchors = property(lambda self: LayerAnchorsProxy(self))
'''.. attribute:: anchors
	Dictionary of :class:`GSAnchor <GSAnchor>` objects. The name of the anchor is the key, the :class:`GSAnchor <GSAnchor>` is the value.
	
	.. code-block:: python

		for name, anchor in layer.anchors:
			print name, anchor
		ogonek <GSAnchor "ogonek" x=630.0 y=0.0>
	

	:type: dict'''

#GSGlyph.name = property(lambda self: str(self.valueForKey_("name")),
#						lambda self, value: self.setName_(value))

GSLayer.paths = property(	lambda self: LayerPathsProxy(self))
'''.. attribute:: paths
	List of :class:`GSPath <GSPath>` objects.
	:type: list'''
GSLayer.LSB = property(		lambda self: self.valueForKey_("LSB").floatValue(),
							lambda self, value: self.setLSB_(float(value)))
'''.. attribute:: LSB
	Left side bearing
	:type: float'''
GSLayer.RSB = property(		lambda self: self.valueForKey_("RSB").floatValue(),
							lambda self, value: self.setRSB_(float(value)))
'''.. attribute:: RSB
	Right side bearing
	:type: float'''
GSLayer.width = property(	lambda self: self.valueForKey_("width").floatValue(),
							lambda self, value: self.setWidth_(float(value)))
'''.. attribute:: width
	Glyph width
	:type: float'''


'''

---------
Functions
---------

.. function:: decomposeComponents()
	
	Decomposes all components of the layer at once.

.. function:: compareString()
	
	Returns a string representing the outline structure of the glyph, for compatibility comparison.

	:return: The comparison string

	:rtype: string

.. function:: connectAllOpenPaths()
	
	Closes all open paths when end points are further than 1 unit away from each other.


.. function:: copyDecomposedLayer()
	
	Returns a copy of the layer with all components already decomposed.

	:return: A new layer object

	:rtype: :class:`GSLayer <GSLayer>`

.. function:: syncMetrics()
	
	Take over LSB and RSB from linked glyph.

.. function:: correctPathDirection()
	
	Corrects the path direction.


	
'''








##################################################################################
#
#
#
#           GSAnchor
#
#
#
##################################################################################

'''

:mod:`GSAnchor`
===============================================================================

Implementation of the anchor object.

.. class:: Anchor([name, pt])
	
	:param name: the name of the anchor
	:param pt: the position of the anchor

.. autosummary::
	
	position
	name
	

----------
Properties
----------

'''


def Anchor__new__(typ, *args, **kwargs):
	return GSAnchor.alloc().init()
GSAnchor.__new__ = Anchor__new__;

def Anchor__init__(self, name = None, pt = None):
	if pt:
		self.setPosition_(pt)
	if name:
		self.setName_(name)
GSAnchor.__init__ = Anchor__init__;

def Anchor__repr__(self):
	return "<GSAnchor \"%s\" x=%s y=%s>" % (self.name, self.position.pointValue().x, self.position.pointValue().y)
GSAnchor.__repr__ = Anchor__repr__;

GSAnchor.position = property(		lambda self: self.valueForKey_("position"),
								lambda self, value: self.setPosition_(value))
'''.. attribute:: position
	The position of the anchor
	:type: NSPoint'''

GSAnchor.name = property(		lambda self: self.valueForKey_("name"),
								lambda self, value: self.setName_(value))
'''.. attribute:: name
	The name of the anchor
	:type: unicode'''









##################################################################################
#
#
#
#           GSComponent
#
#
#
##################################################################################


'''

:mod:`GSComponent`
===============================================================================

.. class:: GSComponent(glyph [, pt] )
	
	Implementation of the component object.
	
	:param glyph: a glyph object or the glyph name
	:param pt: the position of the component

**Properties**

.. autosummary::
	
	position
	componentName
	component
	transform
	bounds
	
**Functions**

.. autosummary::
	
	decompose

	
----------
Properties
----------

	'''

def Component__new__(typ, *args, **kwargs):
	return GSComponent.alloc().init()
GSComponent.__new__ = Component__new__;

def Component__init__(self, glyph, pt = None):
	"""
	transformation: transform matrix as list of numbers
	"""
	if pt:
		self.setPosition_(pt)
	if glyph:
		if isinstance(glyph, str):
			# print "glyph:", glyph
			self.setComponentName_(glyph)
		elif isinstance(name, "GSGlyph"):
			self.setComponent_(glyph)
GSComponent.__init__ = Component__init__;

def Component__repr__(self):
	return "<GSComponent \"%s\" x=%s y=%s>" % (self.componentName, self.position.pointValue().x, self.position.pointValue().y)
GSComponent.__repr__ = Component__repr__;


GSComponent.position = property(lambda self: self.valueForKey_("position"),
									 lambda self, value: self.setPosition_(value))
'''.. attribute:: position
	The Position of the component.
	:type: NSPoint'''
GSComponent.componentName = property(lambda self: self.valueForKey_("componentName"),
									 lambda self, value: self.setComponentName_(value))
'''.. attribute:: componentName
	The glyph name the component is pointing to.
	:type: unicode'''
GSComponent.component = property(	 lambda self: self.valueForKey_("component"))
'''.. attribute:: component
	The :class:`GSGlyph <GSGlyph>` the component is pointing to. This is read only. Set the componentName to the glyph name.
	:type: :class:`GSGlyph <GSGlyph>`
'''
GSComponent.transform = property(	 lambda self: self.transformStruct(),
									 lambda self, value: self.setTransformStruct(value))
'''.. attribute:: transform
	
	:type: NSAffineTransformStruct'''
GSComponent.bounds = property(	 lambda self: self.pyobjc_instanceMethods.bounds() )
'''.. attribute:: bounds
	
	Bounding box of the component, read only
	
	:type: NSRect'''


'''

----------
Functions
----------

'''

'''.. function:: decompose()
	
	Decomposes the component
'''






##################################################################################
#
#
#
#           GSPath
#
#
#
##################################################################################


'''

:mod:`GSPath`
===============================================================================

Implementation of the path object.

.. class:: GSPath

**Properties**

.. autosummary::
	
	parent
	nodes
	segments
	closed
	direction
	bounds
	
**Functions**

.. autosummary::
	
	reverse

----------
Properties
----------

	
'''


def Path__new__(typ, *args, **kwargs):
	return GSPath.alloc().init()
GSPath.__new__ = Path__new__;

def Path__init__(self):
	pass
GSPath.__init__ = Path__init__;

def Path__repr__(self):
	return "<GSPath %s nodes and %s segments>" % (len(self.nodes), len(self.segments))
GSPath.__repr__ = Path__repr__;

GSPath.parent = property(		lambda self: self.valueForKey_("parent"),
								lambda self, value: self.setParent_(value)) 
'''.. attribute:: parent
	Reference to the :class:`Glyph <GSGlyph>` object.
	:type: GSGlyph'''

GSPath.nodes = property(		lambda self: PathNodesProxy(self))
'''.. attribute:: nodes
	A list of :class:`GSNode <GSNode>` objects
	:type: list'''
	
GSPath.segments = property(		lambda self: self.valueForKey_("segments"),
						 		lambda self, value: self.setSegments_(value))
'''.. attribute:: segments
	A list of segments as NSPoint objects. Two objects represent a line, four represent a courve. Start point of the segment is included.
	:type: list'''

GSPath.closed = property(		lambda self: self.valueForKey_("closed").boolValue(),
						 		lambda self, value: self.setValue_forKey_(value, "closed"))
'''.. attribute:: closed
	Returnes True if the the path is closed
	:type: bool'''
GSPath.direction = property(		lambda self: self.valueForKey_("direction"))
'''.. attribute:: direction
	Path direction. -1 for counter clockwise, 1 for clockwise.
	:type: int'''
GSPath.bounds = property(	 lambda self: self.pyobjc_instanceMethods.bounds() )
'''.. attribute:: bounds
	Bounding box of the component, read only
	:type: NSRect'''

								
'''

----------
Functions
----------

.. function:: reverse()
	
	Reverses the path direction
'''








##################################################################################
#
#
#
#           GSNode
#
#
#
##################################################################################

'''

:mod:`GSNode`
===============================================================================

Implementation of the node object.

.. class:: GSNode([pt, type])
	
	:param pt: The position of the node.
	:param type: The type of the node, GSLINE, GSCURVE or GSOFFCURVE

.. autosummary::
	
	position
	type
	connection

----------
Properties
----------

	'''



def Node__new__(typ, *args, **kwargs):
	return GSNode.alloc().init()
GSNode.__new__ = Node__new__;

def Node__init__(self, pt = None, type = None):
	if pt:
		self.setPosition_(pt)
	if type:
		self.setType_(type)
GSNode.__init__ = Node__init__;

def Node__repr__(self):
	return "<GSNode x=%s y=%s %s %s>" % (self.position.pointValue().x, self.position.pointValue().y, constants[self.type], constants[self.connection])
GSNode.__repr__ = Node__repr__;


GSNode.position = property(			lambda self: self.valueForKey_("position"),
								lambda self, value: self.setPosition_(value))
'''.. attribute:: position
	The position of the node.
	:type: NSPoint'''

GSNode.type = property(			lambda self: self.valueForKey_("type"),
								lambda self, value: self.setType_(value))
'''.. attribute:: type
	The type of the node, GSLINE, GSCURVE or GSOFFCURVE
	:type: int'''
GSNode.connection = property(	lambda self: self.valueForKey_("connection"),
								lambda self, value: self.setConnection_(value))
'''.. attribute:: connection
	The type of the connection, GSSHARP or GSSMOOTH
	:type: int'''










##################################################################################
#
#
#
#           GSGuideLine
#
#
#
##################################################################################


'''

:mod:`GSGuideLine`
===============================================================================

Implementation of the guide line object.

.. class:: GSGuideLine

.. autosummary::
	
	position
	angle
	

----------
Properties
----------

	'''


def GuideLine__new__(typ, *args, **kwargs):
	return GSGuideLine.alloc().init()
GSGuideLine.__new__ = GuideLine__new__;

def GuideLine__init__(self):
	pass
GSGuideLine.__init__ = GuideLine__init__;

def GuideLine__repr__(self):
	return "<GSGuideLine x=%s y=%s angle=%s>" % (self.position.pointValue().x, self.position.pointValue().y, self.angle)
GSGuideLine.__repr__ = GuideLine__repr__;

GSGuideLine.position = property(			lambda self: self.valueForKey_("position"),
								lambda self, value: self.setPosition_(value))
'''.. attribute:: position
	The position of the node.
	:type: NSPoint'''
GSGuideLine.angle = property(lambda self: self.valueForKey_("angle").floatValue(),
								lambda self, value: self.setAngle_(float(value)))
'''.. attribute:: angle
	Angle
	:type: int'''







##################################################################################
#
#
#
#           GSHint
#
#
#
##################################################################################


'''

:mod:`GSHint`
===============================================================================

Implementation of the hint object.

.. class:: GSHint

.. autosummary::
	
	originNode
	targetNode
	ghost
	horizontal

----------
Properties
----------

	'''


def Hint__new__(typ, *args, **kwargs):
	return GSHint.alloc().init()
GSHint.__new__ = Hint__new__;

def Hint__init__(self):
	pass
GSHint.__init__ = Hint__init__;

def Hint__repr__(self):
	if self.ghost != 0:
		return "<GSHint origin=(%s,%s) ghost=%s>" % (self.originNode.position.pointValue().x, self.originNode.position.pointValue().y, self.ghost)
	else:
		return "<GSHint origin=(%s,%s) target=(%s,%s) horizontal=%s>" % (self.originNode.position.pointValue().x, self.originNode.position.pointValue().y, self.targetNode.position.pointValue().x, self.targetNode.position.pointValue().y, self.horizontal)
GSHint.__repr__ = Hint__repr__;

GSHint.originNode = property(			lambda self: self.valueForKey_("originNode"),
								lambda self, value: self.setOriginNode_(value))
'''.. attribute:: originNode
	The the first node this hint is attached to.
	:type: GSNode'''
GSHint.targetNode = property(			lambda self: self.valueForKey_("targetNode"),
								lambda self, value: self.setTargetNode_(value))
'''.. attribute:: targetNode
	The the second node this hint is attached to. In case of a ghost hint this value will be empty.
	:type: GSNode'''
GSHint.ghost = property(			lambda self: self.valueForKey_("ghost"),
								lambda self, value: self.setGhost_(value))
'''.. attribute:: ghost
	-1 for a top ghost hint, 1 for a bottom ghost hint or 0 if it's not a ghost hint.
	:type: int'''
GSHint.horizontal = property(			lambda self: self.valueForKey_("horizontal").boolValue(),
								lambda self, value: self.setHorizontal_(value))
'''.. attribute:: horizontal
	True if hint is horizontal, False if vertical.
	:type: bool'''










'''

Methods
=======

.. autosummary::

	niceName()
	divideCurve()
	distance()
	addPoints()
	substractPoints()
	GetFile()

	'''




def niceName(Name):
	return GSGlyphsInfo.niceGlpyhNameForName_(Name)
'''.. function:: niceName(Name)
	
	Converts the Name in a readable name. (converts "uni01D1" in "Ocaron")
	
	:param Name: A glyph name
	:return: The converted Name.
	:rtype: string'''
	
def divideCurve(P0, P1, P2, P3, t):
	#NSPoint Q0, Q1, Q2, R0, R1;
	Q0x = P0[0] + ((P1[0]-P0[0])*t);
	Q0y = P0[1] + ((P1[1]-P0[1])*t);
	Q1x = P1[0] + ((P2[0]-P1[0])*t);
	Q1y = P1[1] + ((P2[1]-P1[1])*t);
	Q2x = P2[0] + ((P3[0]-P2[0])*t);
	Q2y = P2[1] + ((P3[1]-P2[1])*t);
	R0x = Q0x + ((Q1x-Q0x)*t);
	R0y = Q0y + ((Q1y-Q0y)*t);
	R1x = Q1x + ((Q2x-Q1x)*t);
	R1y = Q1y + ((Q2y-Q1y)*t);
	
	#NSPoint S;
	Sx = R0x + ((R1x-R0x)*t);
	Sy = R0y + ((R1y-R0y)*t);
	#	S: neuer Punkt
	#	R0: Anker 2 zu S
	#	Q0: Anker 1 zu S
	#	R1: Anker  zu N2
	#	Q2: Anker  zu N2
	return (P0, NSMakePoint(Q0x, Q0y), NSMakePoint(R0x, R0y), NSMakePoint(Sx, Sy), NSMakePoint(R1x, R1y), NSMakePoint(Q2x, Q2y), P3)
	#*(q2) = R0;
	#*(q3) = S ;
	#*(r1) = R1;
	#*(r2) = Q2;
	#*(r3) = P3;
'''.. function:: divideCurve(P0, P1, P2, P3, t)
	
	Divides the curve using the De Casteljau's algorithm.
	
	:param P0: The Start point of the Curve (NSPoint)
	:param P1: The first off curve point
	:param P2: The second off curve point
	:param P3: The End point of the Curve
	:param t: The time paramter
	:return: A list of points that represent two curves. (Q0, Q1, Q2, Q3, R1, R2, R3). Note that the "middle" point is only returned once.
	:rtype: list'''
	
	
def distance(P1, P2):
	return math.hypot(P1[0] - P2[0], P1[1] - P2[1])
'''.. function:: distance(P0, P1)
	
	calculates the distance between two NSPoints
	
	:param P0: a NSPoint
	:param P1: another NSPoint
	:return: The distance
	:rtype: float'''
	
	
def addPoints(P1, P2):
	return NSMakePoint(P1[0] + P2[0], P1[1] + P2[1])
'''.. function:: addPoints(P1, P2)
	
	Add the points.

	:param P0: a NSPoint
	:param P1: another NSPoint
	:return: The sum of both points
	:rtype: NSPoint'''
	
	
def substractPoints(P1, P2):
	return NSMakePoint(P1[0] - P2[0], P1[1] - P2[1])
'''.. function:: substractPoints(P1, P2)
	
	Subtracts the points.
	
	:param P0: a NSPoint
	:param P1: another NSPoint
	:return: The substractzed point
	:rtype: NSPoint'''
	
def scalePoint(P, scalar):
	return NSMakePoint(P[0] * scalar, P[1] * scalar)
'''.. function:: scalePoint(P, scalar)
	
	Scaled a point.

	:param P: a NSPoint
	:param scalar: The Multiplier
	:return: The multiplied point
	:rtype: NSPoint
'''

def GetFile(message=None, allowsMultipleSelection=False, filetypes=None):
	if filetypes is None:
		filetypes = []
	Panel = NSOpenPanel.openPanel().retain()
	Panel.setCanChooseFiles_(True)
	Panel.setCanChooseDirectories_(False)
	Panel.setAllowsMultipleSelection_(allowsMultipleSelection)
	Panel.setAllowedFileTypes_(filetypes)
	pressedButton = Panel.runModalForTypes_(filetypes)
	if pressedButton == NSOKButton:
		if allowsMultipleSelection:
			return Panel.filenames()
		else:
			return Panel.filename()
	return None
'''.. function:: GetFile(message=None, filetypes = None, selectFolders = True, selectFiles = True)
	
	Opens a file chooser dialog.
	
	:param message:
	:param filestypes:
	:param selectFolders:
	:param selectFiles:
	:return: The selected file or None
	:rtype: unicode
'''

def GetFolder(message=None, allowsMultipleSelection=False):
	Panel = NSOpenPanel.openPanel().retain()
	Panel.setCanChooseFiles_(False)
	Panel.setCanChooseDirectories_(True)
	Panel.setAllowsMultipleSelection_(allowsMultipleSelection)
	pressedButton = Panel.runModalForTypes_([])
	if pressedButton == NSOKButton:
		if allowsMultipleSelection:
			return Panel.filenames()
		else:
			return Panel.filename()
	return None
'''.. function:: GetFolder(message=None, allowsMultipleSelection = False)
	
	Opens a folder chooser dialog.
	
	:param message:
	:param allowsMultipleSelection:
	:return: The selected folder or None
	:rtype: unicode
'''
