#
# Copyright (c) 2002, 2003, 2004 Art Haas
#
# This file is part of PythonCAD.
#
# PythonCAD is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# PythonCAD is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PythonCAD; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#
# arc class
#

from __future__ import generators

import math

import style
import util
import graphicobject
import entity
import linetype
import color
import point
import tolerance
import quadtree

_dtr = math.pi/180.0
_rtd = 180.0/math.pi

class Arc(graphicobject.GraphicObject):
    """A class for Arcs.

An Arc has four attributes:

center: A Point object
radius: The Arc's radius
start_angle: The start angle
end_angle: The end angle

An Arc has the following methods:

{get/set}Center(): Get/Set the center Point of an Arc.
{get/set}Radius(): Get/Set the radius of an Arc.
{get/set}StartAngle(): Get/Set the starting angle of an Arc.
{get/set}EndAngle(): Get/Set the end angle of an arc
move(): Move the Arc.
length(): Return the length of an Arc.
area(): Return the area of an Arc.
mapPoint(): Find the nearest Point on the Arc to some other Point.
mapCoords(): Find the nearest Point on the Arc to a coordinate pair.
inRegion(): Returns whether or not a Arc can be seen in a bounded area.
clone(): Return an indentical copy of a Arc.
    """

    __defstyle = style.Style(u'Default Arc Style',
                            linetype.Linetype(u'Solid', None),
                            color.Color(0xffffff),
                            1.0)

    messages = {
        'moved' : True,
        'center_changed' : True,
        'radius_changed' : True,
        'start_angle_changed' : True,
        'end_angle_changed' : True
        }

    def __init__(self, center, radius, start_angle, end_angle,
                 st=None, lt=None, col=None, th=None, **kw):
        """Initialize a Arc.

Arc(center, radius, start_angle, end_angle)

The center should be a Point, or a two-entry tuple of floats,
and the radius should be a float greater than 0.
        """
        _cp = center
        if not isinstance(_cp, point.Point):
            _cp = point.Point(center)
        _r = radius
        if not isinstance(_r, float):
            _r = float(radius)
        if not _r > 0.0:
            raise ValueError, "Invalid radius: %g" % _r
        _st = st
        _sa = util.make_c_angle(start_angle)
        _ea = util.make_c_angle(end_angle)
        if _st is None:
            _st = Arc.__defstyle
        graphicobject.GraphicObject.__init__(self, _st, lt, col, th, **kw)
        self.__radius = _r
        self.__sa = _sa
        self.__ea = _ea
        self.__center = _cp
        _cp.connect('moved', self, Arc.movePoint)
        _cp.storeUser(self)

    def __eq__(self, obj):
        """Compare a Arc to another for equality.
        """
        if not isinstance(obj, Arc):
            return False
        _val = False
        if obj is self:
            _val = True
        else:
            if ((self.__center == obj.getCenter()) and
                (abs(self.__radius - obj.getRadius()) < 1e-10) and
                (abs(self.__sa - obj.getStartAngle()) < 1e-10) and
                (abs(self.__ea - obj.getEndAngle()) < 1e-10)):
                    _val = True
        return _val

    def __ne__(self, obj):
        """Compare a Arc to another for inequality.
        """
        if not isinstance(obj, Arc):
            return True
        _val = True
        if obj is self:
            _val = False
        else:
            if ((self.__center == obj.getCenter()) and
                (abs(self.__radius - obj.getRadius()) < 1e-10) and
                (abs(self.__sa - obj.getStartAngle()) < 1e-10) and
                (abs(self.__ea - obj.getEndAngle()) < 1e-10)):
                    _val = False
        return _val

    def getValues(self):
        _pids = entity.Entity.getValues(self)
        _gv = self.getGraphicValues(Arc.__defstyle)
        return ('arc', _pids, _gv, self.__center.getID(), self.__radius,
                self.__sa, self.__ea)

    def getCenter(self):
        """Return the center Point of the Arc.

getCenter()
        """
        return self.__center

    def setCenter(self, c):
        """Set the center Point of the Arc.

setCenter(c)

The argument must be a Point or a tuple containing
two float values.
        """
        if self.isLocked():
            raise RuntimeError, "Setting center not allowed - object locked."
        _cp = self.__center
        if not isinstance(c, point.Point):
            raise TypeError, "Invalid center point: " + `c`
        if _cp is not c:
            _cp.disconnect(self)
            _cp.freeUser(self)
            self.__center = c
            self.sendMessage('center_changed', _cp)
            c.connect('moved', self, Arc.movePoint)
            c.storeUser(self)
            if abs(_cp.x - c.x) > 1e-10 or abs(_cp.y - c.y) > 1e-10:
                self.sendMessage('moved', _cp.x, _cp.y, self.__radius,
                                 self.__sa, self.__ea)
            self.modified()

    center = property(getCenter, setCenter, None, "Arc center")

    def getRadius(self):
        """Return the radius of the the Arc.

getRadius()
        """
        return self.__radius

    def setRadius(self, radius):
        """Set the radius of the Arc.

setRadius(radius)

The argument must be float value greater than 0.
        """
        if self.isLocked():
            raise RuntimeError, "Setting radius not allowed - object locked."
        _r = radius
        if not isinstance(_r, float):
            _r = float(radius)
        if not _r > 0.0:
            raise ValueError, "Invalid radius: %g" % _r
        _cr = self.__radius
        if abs(_cr - _r) > 1e-10:
            self.__radius = _r
            self.sendMessage('radius_changed', _cr)
            _cx, _cy = self.__center.getCoords()
            self.sendMessage('moved', _cx, _cy, _cr, self.__sa, self.__ea)
            self.modified()

    radius = property(getRadius, setRadius, None, "Arc radius")

    def getStartAngle(self):
        """Return the start_angle for the Arc.

getStartAngle()
        """
        return self.__sa

    def setStartAngle(self, angle):
        """Set the start_angle for the Arc.

setStartAngle(angle)

The argument angle should be a float.
        """
        if self.isLocked():
            raise RuntimeError, "Setting start angle not allowed - object locked."
        _sa = self.__sa
        _angle = util.make_c_angle(angle)
        if abs(_sa - _angle) > 1e-10:
            self.__sa = _angle
            self.sendMessage('start_angle_changed', _sa)
            _cx, _cy = self.__center.getCoords()
            self.sendMessage('moved', _cx, _cy, self.__radius, _sa, self.__ea)
            self.modified()

    start_angle = property(getStartAngle, setStartAngle, None,
                           "Start angle for the Arc.")

    def getEndAngle(self):
        """Return the end_angle for the Arc.

getEndAngle()
        """
        return self.__ea

    def setEndAngle(self, angle):
        """Set the end_angle for the Arc.

setEndAngle(angle)

The argument angle should be a float.
        """
        if self.isLocked():
            raise RuntimeError, "Setting end angle not allowed - object locked."
        _ea = self.__ea
        _angle = util.make_c_angle(angle)
        if abs(_ea - _angle) > 1e-10:
            self.__ea = _angle
            self.sendMessage('end_angle_changed', _ea)
            _cx, _cy = self.__center.getCoords()
            self.sendMessage('moved', _cx, _cy, self.__radius, self.__sa, _ea)
            self.modified()

    end_angle = property(getEndAngle, setEndAngle, None,
                         "End angle for the Arc.")

    def getAngle(self):
        """Return the angular sweep of the Arc.

getAngle()
        """
        _sa = self.__sa
        _ea = self.__ea
        if abs(_ea - _sa) < 1e-10:
            _angle = 360.0
        elif _ea > _sa:
            _angle = _ea - _sa
        else:
            _angle = 360.0 - _sa + _ea
        return _angle

    def throughAngle(self, angle):
        """Return True if an arc passes through some angle

throughAngle(angle)

The argument angle should be a float value. This method returns
True if the arc exists at that angle, otherwise the method returns False.
        """
        _angle = angle
        if not isinstance(_angle, float):
            _angle = float(angle)
        _angle = math.fmod(_angle, 360.0)
        if _angle < 0.0:
            _angle = _angle + 360.0
        _sa = self.__sa
        _ea = self.__ea
        _val = True
        if abs(_sa - _ea) > 1e-10:
            if _sa > _ea:
                if _angle > _ea and _angle < _sa:
                    _val = False
            else:
                if _angle > _ea or _angle < _sa:
                    _val = False
        return _val

    def getEndpoints(self):
        """Return where the two endpoints for the arc-segment lie.

getEndpoints(self)

This function returns two tuples, each containing the x-y coordinates
of the arc endpoints. The first tuple corresponds to the endpoint at
the start_angle, the second to the endpoint at the end_angle.
        """
        _cx, _cy = self.__center.getCoords()
        _r = self.__radius
        _sa = self.__sa
        _sax = _cx + _r * math.cos(_sa * _dtr)
        _say = _cy + _r * math.sin(_sa * _dtr)
        _ea = self.__ea
        _eax = _cx + _r * math.cos(_ea * _dtr)
        _eay = _cy + _r * math.sin(_ea * _dtr)
        return (_sax, _say), (_eax, _eay)

    def length(self):
        """Return the length of the Arc.

length()
        """
        return 2.0 * math.pi * self.__radius * (self.getAngle()/360.0)

    def area(self):
        """Return the area enclosed by the Arc.

area()
        """
        return math.pi * pow(self.__radius, 2) * (self.getAngle()/360.0)

    def move(self, dx, dy):
        """Move a Arc.

move(dx, dy)

The first argument gives the x-coordinate displacement,
and the second gives the y-coordinate displacement. Both
values should be floats.
        """
        if self.isLocked():
            raise RuntimeError, "Setting radius not allowed - object locked."
        _dx = dx
        if not isinstance(_dx, float):
            _dx = float(dx)
        _dy = dy
        if not isinstance(_dy, float):
            _dy = float(dy)
        if abs(_dx) > 1e-10 or abs(_dy) > 1e-10:
            _x, _y = self.__center.getCoords()
            self.ignore('moved')
            self.__center.move(_dx, _dy)
            self.receive('moved')
            self.sendMessage('moved', _x, _y, self.__radius,
                             self.__sa, self.__ea)
            self.modified()


    def mapCoords(self, x, y, tol=tolerance.TOL):
        """Return the nearest Point on the Arc to a coordinate pair.

mapCoords(x, y[, tol])

The function has two required arguments:

x: A Float value giving the x-coordinate
y: A Float value giving the y-coordinate

There is a single optional argument:

tol: A float value equal or greater than 0.0

This function is used to map a possibly near-by coordinate pair to
an actual Point on the Arc. If the distance between the actual
Point and the coordinates used as an argument is less than the tolerance,
the actual Point is returned. Otherwise, this function returns None.
        """
        _x = x
        if not isinstance(_x, float):
            _x = float(x)
        _y = y
        if not isinstance(_y, float):
            _y = float(y)
        _t = tolerance.toltest(tol)
        _cx, _cy = self.__center.getCoords()
        _r = self.__radius
        _dist = math.hypot((_x - _cx), (_y - _cy))
        if abs(_dist - _r) < _t:
            _angle = _rtd * math.atan2((_y - _cy),(_x - _cx))
            if _angle < 0.0:
                _angle = _angle + 360.0
            if self.throughAngle(_angle):
                _xoff = _r * math.cos(_angle)
                _yoff = _r * math.sin(_angle)
                return (_cx + _xoff), (_cy + _yoff)
        return None

    def inRegion(self, xmin, ymin, xmax, ymax, fully=False):
        """Return whether or not an Arc exists within a region.

inRegion(xmin, ymin, xmax, ymax[, fully])

The first four arguments define the boundary. The optional
fifth argument fully indicates whether or not the Arc
must be completely contained within the region or just pass
through it.
        """
        _xmin = xmin
        if not isinstance(_xmin, float):
            _xmin = float(xmin)
        _ymin = ymin
        if not isinstance(_ymin, float):
            _ymin = float(ymin)
        _xmax = xmax
        if not isinstance(_xmax, float):
            _xmax = float(xmax)
        if _xmax < _xmin:
            raise ValueError, "Illegal values: xmax < xmin"
        _ymax = ymax
        if not isinstance(_ymax, float):
            _ymax = float(ymax)
        if _ymax < _ymin:
            raise ValueError, "Illegal values: ymax < ymin"
        if fully is not True and fully is not False:
            raise ValueError, "Invalid flag: " + `fully`
        _xc, _yc = self.__center.getCoords()
        _r = self.__radius
        #
        # cheap test to see if arc cannot be in region
        #
        _axmin, _aymin, _axmax, _aymax = self.getBounds()
        if ((_axmin > _xmax) or
            (_aymin > _ymax) or
            (_axmax < _xmin) or
            (_aymax < _ymin)):
            return False
        _val = False
        _bits = 0
        #
        # calculate distances from center to region boundary
        #
        if abs(_xc - _xmin) < _r: _bits = _bits | 1 # left edge
        if abs(_xc - _xmax) < _r: _bits = _bits | 2 # right edge
        if abs(_yc - _ymin) < _r: _bits = _bits | 4 # bottom edge
        if abs(_yc - _ymax) < _r: _bits = _bits | 8 # top edge
        if _bits == 0:
            #
            # circle must be visible - the center is in
            # the region and is more than the radius from
            # each edge
            #
            _val = True
        else:
            #
            # calculate distance to corners of region
            #
            if math.hypot((_xc - _xmin), (_yc - _ymax)) < _r:
                _bits = _bits | 0x10 # upper left
            if math.hypot((_xc - _xmax), (_yc - _ymin)) < _r:
                _bits = _bits | 0x20 # lower right
            if math.hypot((_xc - _xmin), (_yc - _ymin)) < _r:
                _bits = _bits | 0x40 # lower left
            if math.hypot((_xc - _xmax), (_yc - _ymax)) < _r:
                _bits = _bits | 0x80 # upper right
            #
            # if all bits are set then distance from circle center
            # to region endpoints is less than radius - circle
            # entirely outside the region
            #
            _val = not ((_bits == 0xff) or fully)
            #
            # if the test value is still true, check that the
            # arc boundary can overlap with the region
            #
            if _val:
                _sa = self.__sa
                _ea = self.__ea
                _xs = _xc + (_r * math.cos(_sa * _dtr))
                _ys = _yc + (_r * math.sin(_sa * _dtr))
                _xe = _xc + (_r * math.cos(_ea * _dtr))
                _ye = _xc + (_r * math.sin(_ea * _dtr))
                _axmin = min(_xc, _xs, _xe)
                if self.throughAngle(180.0):
                    _axmin = _xc - _r
                if _axmin > _xmax:
                    return False
                _aymin = min(_yc, _ys, _ye)
                if self.throughAngle(270.0):
                    _aymin = _yc - _r
                if _aymin > _ymax:
                    return False
                _axmax = max(_xc, _xs, _xe)
                if self.throughAngle(0.0):
                    _axmax = _xc + _r
                if _axmax < _xmin:
                    return False
                _aymax = max(_yc, _ys, _ye)
                if self.throughAngle(90.0):
                    _aymax = _yc + _r
                if _aymax < _ymin:
                    return False
        return _val

    def getBounds(self):
        _xc, _yc = self.__center.getCoords()
        _r = self.__radius
        _sa = self.__sa
        _ea = self.__ea
        _xs = _xc + (_r * math.cos(_sa * _dtr))
        _ys = _yc + (_r * math.sin(_sa * _dtr))
        _xe = _xc + (_r * math.cos(_ea * _dtr))
        _ye = _yc + (_r * math.sin(_ea * _dtr))
        _xmin = min(_xc, _xs, _xe)
        _ymin = min(_yc, _ys, _ye)
        _xmax = max(_xc, _xs, _xe)
        _ymax = max(_yc, _ys, _ye)
        if self.throughAngle(0.0):
            _xmax = _xc + _r
        if self.throughAngle(90.0):
            _ymax = _yc + _r
        if self.throughAngle(180.0):
            _xmin = _xc - _r
        if self.throughAngle(270.0):
            _ymin = _yc - _r
        return _xmin, _ymin, _xmax, _ymax

    def movePoint(self, p, *args):
        _alen = len(args)
        if _alen < 2:
            raise ValueError, "Invalid argument count: %d" % _alen
        _x = args[0]
        if not isinstance(_x, float):
            _x = float(args[0])
        _y = args[1]
        if not isinstance(_y, float):
            _y = float(args[1])
        _cp = self.__center
        if p is not _cp:
            raise ValueError, "Point is not arc center: " + `p`
        _x, _y = _cp.getCoords()
        self.sendMessage('moved', _x, _y, self.__radius, self.__sa, self.__ea)
        self.modified()

    def clone(self):
        """Create an identical copy of a Arc

clone()
        """
        _cp = self.__center.clone()
        _r = self.__radius
        _sa = self.__sa
        _ea = self.__ea
        _st = self.getStyle()
        _lt = self.getLinetype()
        _col = self.getColor()
        _th = self.getThickness()
        return Arc(_cp, _r, _sa, _ea, _st, _lt, _col, _th)

    def sendsMessage(self, m):
        if m in Arc.messages:
            return True
        return graphicobject.GraphicObject.sendsMessage(self, m)


#
# static functions for Arc class
#

    def test_angle(s, e, a):
        """Returns if an angle lies between the start and end angle of an arc.

test_angle(s, e, a)

The arguments are:

s: arc start angle
e: arc end angle
a: angle being tested
        """
        _val = False
        if ((abs(e - s) < 1e-10) or
            ((s > e) and
             ((s <= a <= 360.0) or (0.0 <= a <= e))) or
            (s <= a <= e)):
            _val = True
        return _val

    test_angle = staticmethod(test_angle)

#
# Quadtree Arc storage
#

class ArcQuadtree(quadtree.Quadtree):
    def __init__(self):
        quadtree.Quadtree.__init__(self)

    def getNodes(self, *args):
        _alen = len(args)
        if _alen != 4:
            raise ValueError, "Expected 4 arguments, got %d" % _alen
        _axmin, _aymin, _axmax, _aymax = args
        if not isinstance(_axmin, float):
            _axmin = float(args[0])
        if not isinstance(_aymin, float):
            _aymin = float(args[1])
        if not isinstance(_axmax, float):
            _axmax = float(args[2])
        if not isinstance(_aymax, float):
            _aymax = float(args[3])
        if not _axmax > _axmin:
            raise ValueError, "xmax not greater than xmin"
        if not _aymax > _aymin:
            raise ValueError, "ymax not greater than ymin"
        _nodes = [self.getTreeRoot()]
        while len(_nodes):
            _node = _nodes.pop()
            _xmin, _ymin, _xmax, _ymax = _node.getBoundary()
            if ((_axmin > _xmax) or
                (_axmax < _xmin) or
                (_aymin > _ymax) or
                (_aymax < _ymin)):
                continue
            if _node.hasSubnodes():
                _xmid = (_xmin + _xmax)/2.0
                _ymid = (_ymin + _ymax)/2.0
                _ne = _nw = _sw = _se = True
                if _axmax < _xmid: # arc on left side
                    _ne = _se = False
                if _axmin > _xmid: # arc on right side
                    _nw = _sw = False
                if _aymax < _ymid: # arc below
                    _nw = _ne = False
                if _aymin > _ymid: # arc above
                    _sw = _se = False
                if _ne:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NENODE))
                if _nw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NWNODE))
                if _sw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SWNODE))
                if _se:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SENODE))
            else:
                yield _node

    def addObject(self, obj):
        if not isinstance(obj, Arc):
            raise TypeError, "Invalid Arc object: " + `obj`
        if obj in self:
            return
        _bounds = self.getTreeRoot().getBoundary()
        _xmin = _ymin = _xmax = _ymax = None
        _axmin, _aymin, _axmax, _aymax = obj.getBounds()
        _resize = False
        if _bounds is None: # first node in tree
            _resize = True
            _xmin = _axmin - 1.0
            _ymin = _aymin - 1.0
            _xmax = _axmax + 1.0
            _ymax = _aymax + 1.0
        else:
            _xmin, _ymin, _xmax, _ymax = _bounds
            if _axmin < _xmin:
                _xmin = _axmin - 1.0
                _resize = True
            if _axmax > _xmax:
                _xmax = _axmax + 1.0
                _resize = True
            if _aymin < _ymin:
                _ymin = _aymin - 1.0
                _resize = True
            if _aymax > _ymax:
                _ymax = _aymax + 1.0
                _resize = True
        if _resize:
            self.resize(_xmin, _ymin, _xmax, _ymax)
        for _node in self.getNodes(_axmin, _aymin, _axmax, _aymax):
            _xmin, _ymin, _xmax, _ymax = _node.getBoundary()
            if obj.inRegion(_xmin, _ymin, _xmax, _ymax):
                _node.addObject(obj)
        quadtree.Quadtree.addObject(self, obj)
        obj.connect('moved', self, ArcQuadtree.moveArc)

    def old_addObject(self, obj):
        if not isinstance(obj, Arc):
            raise TypeError, "Invalid Arc object: " + `obj`
        if obj in self:
            return
        _x, _y = obj.getCenter().getCoords()
        _node = self.getTreeRoot()
        _bounds = _node.getBoundary()
        _xmin = _ymin = _xmax = _ymax = None
        _axmin, _aymin, _axmax, _aymax = obj.getBounds()
        _resize = False
        if _bounds is None: # first node in tree
            _resize = True
            _xmin = _axmin - 1.0
            _ymin = _aymin - 1.0
            _xmax = _axmax + 1.0
            _ymax = _aymax + 1.0
        else:
            _xmin, _ymin, _xmax, _ymax = _bounds
            if _axmin < _xmin:
                _xmin = _axmin - 1.0
                _resize = True
            if _axmax > _xmax:
                _xmax = _axmax + 1.0
                _resize = True
            if _aymin < _ymin:
                _ymin = _aymin - 1.0
                _resize = True
            if _aymax > _ymax:
                _ymax = _aymax + 1.0
                _resize = True
        if _resize:
            self.resize(_xmin, _ymin, _xmax, _ymax)
            _node = self.getTreeRoot()
        _nodes = []
        _nodes.append(_node)
        while len(_nodes):
            _node = _nodes.pop()
            _xmin, _ymin, _xmax, _ymax = _node.getBoundary()
            if ((_axmin > _xmax) or
                (_axmax < _xmin) or
                (_aymin > _ymax) or
                (_aymax < _ymin)):
                continue
            if _node.hasSubnodes():
                _xmid = (_xmin + _xmax)/2.0
                _ymid = (_ymin + _ymax)/2.0
                _ne = _nw = _sw = _se = True
                if _axmax < _xmid: # arc on left side
                    _ne = _se = False
                if _axmin > _xmid: # arc on right side
                    _nw = _sw = False
                if _aymax < _ymid: # arc below
                    _nw = _ne = False
                if _aymin > _ymid: # arc above
                    _sw = _se = False
                if _ne:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NENODE))
                if _nw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NWNODE))
                if _sw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SWNODE))
                if _se:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SENODE))
            else:
                if obj.inRegion(_xmin, _ymin, _xmax, _ymax):
                    _node.addObject(obj)
        quadtree.Quadtree.addObject(self, obj)
        obj.connect('moved', self, ArcQuadtree.moveArc)

    def delObject(self, obj):
        if obj not in self:
            return
        _axmin, _aymin, _axmax, _aymax = obj.getBounds()
        _pdict = {}
        for _node in self.getNodes(_axmin, _aymin, _axmax, _aymax):
            _node.delObject(obj) # arc may not be in the node ...
            _parent = _node.getParent()
            if _parent is not None:
                _pid = id(_parent)
                if _pid not in _pdict:
                    _pdict[_pid] = _parent
        quadtree.Quadtree.delObject(self, obj)
        obj.disconnect(self)
        for _parent in _pdict.values():
            self.purgeSubnodes(_parent)

    def old_delObject(self, obj):
        if obj not in self:
            return
        _x, _y = obj.getCenter().getCoords()
        _xmin = _ymin = _xmax = _ymax = None
        _axmin, _aymin, _axmax, _aymax = obj.getBounds()
        _pdict = {}
        _nodes = []
        _nodes.append(self.getTreeRoot())
        while len(_nodes):
            _node = _nodes.pop()
            _xmin, _ymin, _xmax, _ymax = _node.getBoundary()
            if ((_axmin > _xmax) or
                (_axmax < _xmin) or
                (_aymin > _ymax) or
                (_aymax < _ymin)):
                continue
            if _node.hasSubnodes():
                _xmid = (_xmin + _xmax)/2.0
                _ymid = (_ymin + _ymax)/2.0
                _ne = _nw = _sw = _se = True
                if _axmax < _xmid: # arc on left side
                    _ne = _se = False
                if _axmin > _xmid: # arc on right side
                    _nw = _sw = False
                if _aymax < _ymid: # arc below
                    _nw = _ne = False
                if _aymin > _ymid: # arc above
                    _sw = _se = False
                if _ne:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NENODE))
                if _nw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NWNODE))
                if _sw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SWNODE))
                if _se:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SENODE))
            else:
                _node.delObject(obj) # arc may not be in the node ...
                _parent = _node.getParent()
                if _parent is not None:
                    _pid = id(_parent)
                    if _pid not in _pdict:
                        _pdict[_pid] = _parent
        quadtree.Quadtree.delObject(self, obj)
        obj.disconnect(self)
        for _parent in _pdict.values():
            self.purgeSubnodes(_parent)

    def find(self, *args):
        _alen = len(args)
        if _alen < 5:
            raise ValueError, "Invalid argument count: %d" % _alen
        _x = args[0]
        if not isinstance(_x, float):
            _x = float(args[0])
        _y = args[1]
        if not isinstance(_y, float):
            _y = float(args[1])
        _r = args[2]
        if not isinstance(_r, float):
            _r = float(args[2])
        _sa = args[3]
        if not isinstance(_sa, float):
            _sa = float(args[3])
        _ea = args[4]
        if not isinstance(_ea, float):
            _ea = float(args[4])
        _t = tolerance.TOL
        if _alen > 5:
            _t = tolerance.toltest(args[5])
        if not len(self):
            return None
        _axmin = _x - _r
        _axmax = _x + _r
        _aymin = _y - _r
        _aymax = _y + _r
        _nodes = []
        _nodes.append(self.getTreeRoot())
        _adict = {}
        _bailout = False
        _arc = None
        while len(_nodes):
            _node = _nodes.pop()
            _xmin, _ymin, _xmax, _ymax = _node.getBoundary()
            if ((_axmin > _xmax) or
                (_axmax < _xmin) or
                (_aymin > _ymax) or
                (_aymax < _ymin)):
                continue
            if _node.hasSubnodes():
                _xmid = (_xmin + _xmax)/2.0
                _ymid = (_ymin + _ymax)/2.0
                _ne = _nw = _sw = _se = True
                if _axmax < (_xmid - _t): # arc on left side
                    _ne = _se = False
                if _axmin > (_xmid + _t): # arc on right side
                    _nw = _sw = False
                if _aymax < (_ymid - _t): # arc below
                    _nw = _ne = False
                if _aymin > (_ymid + _t): # arc above
                    _sw = _se = False
                if _ne:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NENODE))
                if _nw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NWNODE))
                if _sw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SWNODE))
                if _se:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SENODE))
            else:
                for _a in _node.getObjects():
                    _aid = id(_a)
                    if _aid not in _adict:
                        _ax, _ay = _a.getCenter().getCoords()
                        if ((abs(_ax - _x) < _t) and (abs(_ay - _y) < _t)):
                            _ar = _a.getRadius()
                            if abs(_ar - _r) < _t:
                                _asa = _a.getStartAngle()
                                _aea = _a.getEndAngle()
                                if abs(_asa - _sa) < 1e-10 and abs(_aea - _ea) < 1e-10:
                                    _bailout = True
                                    _arc = _a
                                break
                        _adict[_aid] = True
            if _bailout:
                break
        return _arc

    def moveArc(self, obj, *args):
        if obj not in self:
            raise ValueError, "Arc not stored in Quadtree: " + `obj`
        _alen = len(args)
        if _alen < 5:
            raise ValueError, "Invalid argument count: %d" % _alen
        _x = args[0]
        if not isinstance(_x, float):
            _x = float(args[0])
        _y = args[1]
        if not isinstance(_y, float):
            _y = float(args[1])
        _r = args[2]
        if not isinstance(_r, float):
            _r = float(args[2])
        _sa = args[3]
        if not isinstance(_sa, float):
            _sa = float(args[3])
        _ea = args[4]
        if not isinstance(_ea, float):
            _ea = float(args[4])
        _sax = _x + _r * math.cos(_sa * _dtr)
        _say = _y + _r * math.sin(_sa * _dtr)
        _eax = _x + _r * math.cos(_ea * _dtr)
        _eay = _y + _r * math.sin(_ea * _dtr)
        _axmin = min(_x, _sax, _eax)
        if ((abs(_sa - 180.0) < 1e-10) or
            (abs(_ea - 180.0) < 1e-10) or
            ((_sa < _ea) and (_sa < 180.0 < _ea)) or
            ((_ea < _sa) and (_sa < 180.0))):
            _axmin = _x - _r
        _axmax = max(_x, _sax, _eax)
        if ((abs(_sa) < 1e-10) or
            (abs(_ea) < 1e-10) or
            ((_sa > _ea) and (_ea > 0.0))):
            _axmax = _x + _r
        _aymin = min(_y, _say, _eay)
        if ((abs(_sa - 270.0) < 1e-10) or
            (abs(_ea - 270.0) < 1e-10) or
            ((_sa < _ea) and (_sa < 270.0 < _ea)) or
            ((_ea < _sa) and (_sa < 270.0))):
            _axmin = _x - _r
        _aymax = max(_y, _say, _eay)
        if ((abs(_sa - 90.0) < 1e-10) or
            (abs(_ea - 90.0) < 1e-10) or
            ((_sa < _ea) and (_sa < 90.0 < _ea)) or
            ((_ea < _sa) and (_sa < 90.0))):
            _axmin = _x + _r
        for _node in self.getNodes(_axmin, _aymin, _axmax, _aymax):
            _node.delObject(obj) # arc may not be in node ...
        quadtree.Quadtree.delObject(self, obj)
        obj.disconnect(self)
        self.addObject(obj)

    def old_moveArc(self, obj, *args):
        if obj not in self:
            raise ValueError, "Arc not stored in Quadtree: " + `obj`
        _alen = len(args)
        if _alen < 5:
            raise ValueError, "Invalid argument count: %d" % _alen
        _x = args[0]
        if not isinstance(_x, float):
            _x = float(args[0])
        _y = args[1]
        if not isinstance(_y, float):
            _y = float(args[1])
        _r = args[2]
        if not isinstance(_r, float):
            _r = float(args[2])
        _sa = args[3]
        if not isinstance(_sa, float):
            _sa = float(args[3])
        _ea = args[4]
        if not isinstance(_ea, float):
            _ea = float(args[4])
        _axmin = _x - _r
        _axmax = _x + _r
        _aymin = _y - _r
        _aymax = _y + _r
        _nodes = []
        _nodes.append(self.getTreeRoot())
        while len(_nodes):
            _node = _nodes.pop()
            _xmin, _ymin, _xmax, _ymax = _node.getBoundary()
            if ((_axmin > _xmax) or
                (_axmax < _xmin) or
                (_aymin > _ymax) or
                (_aymax < _ymin)):
                continue
            if _node.hasSubnodes():
                _xmid = (_xmin + _xmax)/2.0
                _ymid = (_ymin + _ymax)/2.0
                _ne = _nw = _sw = _se = True
                if _axmax < _xmid: # arc on left side
                    _ne = _se = False
                if _axmin > _xmid: # arc on right side
                    _nw = _sw = False
                if _aymax < _ymid: # arc below
                    _nw = _ne = False
                if _aymin > _ymid: # arc above
                    _sw = _se = False
                if _ne:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NENODE))
                if _nw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.NWNODE))
                if _sw:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SWNODE))
                if _se:
                    _nodes.append(_node.getSubnode(quadtree.QTreeNode.SENODE))
            else:
                _node.delObject(obj) # arc may not be in node ...
        quadtree.Quadtree.delObject(self, obj)
        obj.disconnect(self)
        self.addObject(obj)

    def getClosest(self, x, y, tol=tolerance.TOL):
        _x = x
        if not isinstance(_x, float):
            _x = float(x)
        _y = y
        if not isinstance(_y, float):
            _y = float(y)
        _t = tolerance.toltest(tol)
        _arc = _tsep = None
        _bailout = False
        _adict = {}
        _nodes = []
        _nodes.append(self.getTreeRoot())
        while len(_nodes):
            _node = _nodes.pop()
            _xmin, _ymin, _xmax, _ymax = _node.getBoundary()
            if ((_x < (_xmin - _t)) or
                (_x > (_xmax + _t)) or
                (_y < (_ymin - _t)) or
                (_y > (_ymax + _t))):
                continue
            if _node.hasSubnodes():
                _nodes.extend(_node.getSubnodes())
            else:
                for _a in _node.getObjects():
                    _aid = id(_a)
                    if _aid not in _adict:
                        _ap = _a.mapCoords(_x, _y, _t)
                        if _ap is not None:
                            _ax, _ay = _ap
                            _sep = math.hypot((_ax - _x), (_ay - _y))
                            if _tsep is None:
                                _tsep = _sep
                                _arc = _a
                            else:
                                if _sep < _tsep:
                                    _tsep = _sep
                                    _arc = _a
                            if _sep < 1e-10 and _arc is not None:
                                _bailout = True
                                break
            if _bailout:
                break
        return _arc

    def getInRegion(self, xmin, ymin, xmax, ymax):
        _xmin = xmin
        if not isinstance(_xmin, float):
            _xmin = float(xmin)
        _ymin = ymin
        if not isinstance(_ymin, float):
            _ymin = float(ymin)
        _xmax = xmax
        if not isinstance(_xmax, float):
            _xmax = float(xmax)
        if _xmax < _xmin:
            raise ValueError, "Illegal values: xmax < xmin"
        _ymax = ymax
        if not isinstance(_ymax, float):
            _ymax = float(ymax)
        if _ymax < _ymin:
            raise ValueError, "Illegal values: ymax < ymin"
        _arcs = []
        if not len(self):
            return _arcs
        _nodes = []
        _nodes.append(self.getTreeRoot())
        _adict = {}
        while len(_nodes):
            _node = _nodes.pop()
            if _node.hasSubnodes():
                for _subnode in _node.getSubnodes():
                    _sxmin, _symin, _sxmax, _symax = _subnode.getBoundary()
                    if ((_sxmin > _xmax) or
                        (_symin > _ymax) or
                        (_sxmax < _xmin) or
                        (_symax < _ymin)):
                        continue
                    _nodes.append(_subnode)
            else:
                for _arc in _node.getObjects():
                    _aid = id(_arc)
                    if _aid not in _adict:
                        if _arc.inRegion(_xmin, _ymin, _xmax, _ymax):
                            _arcs.append(_arc)
                        _adict[_aid] = True
        return _arcs

#
# Arc history class
#

class ArcLog(graphicobject.GraphicObjectLog):
    def __init__(self, a):
        if not isinstance(a, Arc):
            raise TypeError, "Invalid arc: " + `a`
        graphicobject.GraphicObjectLog.__init__(self, a)
        a.connect('center_changed' ,self, ArcLog.centerChange)
        a.connect('radius_changed', self, ArcLog.radiusChange)
        a.connect('start_angle_changed', self, ArcLog.saChange)
        a.connect('end_angle_changed', self, ArcLog.eaChange)

    def radiusChange(self, a, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _r = args[0]
        if not isinstance(_r, float):
            _r = float(args[0])
        self.saveUndoData('radius_changed', _r)

    def centerChange(self, a, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _old = args[0]
        if not isinstance(_old, point.Point):
            raise TypeError, "Invalid old center point: " + `_old`
        _oid = _old.getID()
        self.saveUndoData('center_changed', _oid)

    def saChange(self, a, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _sa = args[0]
        if not isinstance(_sa, float):
            _sa = float(args[0])
        self.saveUndoData('sa_change', _sa)

    def eaChange(self, a, *args):
        _alen = len(args)
        if _alen < 1:
            raise ValueError, "Invalid argument count: %d" % _alen
        _ea = args[0]
        if not isinstance(_ea, float):
            _ea = float(args[0])
        self.saveUndoData('ea_change', _ea)

    def execute(self, undo, *args):
        if undo is not True and undo is not False:
            raise ValueError, "Invalid undo value: " + str(undo)
        _alen = len(args)
        if _alen == 0:
            raise ValueError, "No arguments to execute()"
        _a = self.getObject()
        _cp = _a.getCenter()
        _op = args[0]
        if _op == 'center_changed':
            if _alen < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _oid = args[1]
            _cid = _cp.getID()
            if undo:
                self.saveRedoData('center_changed', _cid)
                self.ignore('center_changed')
                try:
                    _parent = _a.getParent()
                    if _parent is None:
                        raise ValueError, "Arc has no parent - cannot undo"
                    _op = _parent.getObject(_oid)
                    if _op is None or not isinstance(_op, point.Point):
                        raise ValueError, "Center point missing: id=%d" % _oid
                    _x1, _y1 = _cp.getCoords()
                    _a.startUndo(True)
                    try:
                        _a.setCenter(_op)
                    finally:
                        _a.endUndo()
                    if (abs(_op.x - _x1) > 1e-10 or
                        abs(_op.y - _y1) > 1e-10):
                        _a.sendMessage('moved', _x1, _y1, _a.getRadius(),
                                       _a.getStartAngle(), _a.getEndAngle())
                finally:
                    self.receive('center_changed')
            else:
                self.saveUndoData('center_changed', _cid)
                _parent = _a.getParent()
                if _parent is None:
                    raise ValueError, "Arc has no parent - cannot undo"
                _op = _parent.getObject(_oid)
                if _op is None or not isinstance(_op, point.Point):
                    raise ValueError, "Center point missing: id=%d" % _oid
                _ep1, _ep2 = _a.getEndpoints()
                _ep = _parent.find('point', _ep1[0], _ep1[1])
                assert _ep is not None, "Arc endpoint not found in layer"
                _ep.freeUser(_a)
                _ep = _parent.find('point', _ep2[0], _ep2[1])
                assert _ep is not None, "Arc endpoint not found in layer"
                _ep.freeUser(_a)
                self.ignore('center_changed')
                try:
                    _a.setCenter(_op)
                finally:
                    self.receive('center_changed')
        elif _op == 'radius_changed':
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _r = args[1]
            if not isinstance(_r, float):
                _r = float(args[1])
            _cr = _a.getRadius()
            if undo:
                self.saveUndoData('radius_changed', _cr)
            else:
                self.saveRedoData('radius_changed', _cr)
            self.ignore('radius_changed')
            try:
                if undo:
                    _a.startUndo(True)
                    try:
                        _a.setRadius(_r)
                    finally:
                        _a.endUndo()
                    if abs(_r - _cr) > 1e-10:
                        _a.sendMessage('moved', _cp.x, _cp.y, _cr,
                                       _a.getStartAngle(), _a.getEndAngle())
                else:
                    _a.setRadius(_r)
            finally:
                self.receive('radius_changed')
        elif _op == 'sa_change':
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _sa = args[1]
            if not isinstance(_sa, float):
                _sa = float(args[1])
            _csa = _a.getStartAngle()
            if undo:
                self.saveUndoData('sa_change', _csa)
            else:
                self.saveRedoData('sa_change', _csa)
            self.ignore('start_angle_changed')
            try:
                if undo:
                    _a.startUndo(True)
                    try:
                        _a.setStartAngle(_sa)
                    finally:
                        _a.endUndo()
                    if abs(_csa - _sa) > 1e-10:
                        _a.sendMessage('moved', _cp.x, _cp.y, _a.getRadius(),
                                       _csa, _a.getEndAngle())
                else:
                    _a.setStartAngle(_sa)
            finally:
                self.receive('start_angle_changed')
        elif _op == 'ea_change':
            if len(args) < 2:
                raise ValueError, "Invalid argument count: %d" % _alen
            _ea = args[1]
            if not isinstance(_ea, float):
                _ea = float(args[1])
            _cea = _a.getEndAngle()
            if undo:
                self.saveUndoData('ea_change', _cea)
            else:
                self.saveRedoData('ea_change', _cea)
            self.ignore('end_angle_changed')
            try:
                if undo:
                    _a.startUndo(True)
                    try:
                        _a.setEndAngle(_ea)
                    finally:
                        _a.endUndo()
                    if abs(_cea - _ea) > 1e-10:
                        _a.sendMessage('moved', _cp.x, _cp.y, _a.getRadius(),
                                       _a.getStartAngle(), _cea)
                else:
                    _a.setEndAngle(_ea)
            finally:
                self.receive('end_angle_changed')
        else:
            raise ValueError, "Unexpected operation: %s" % _op
