#
# Copyright (c) 2002, 2003, 2004, 2005, 2006 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
#
#
# code to handle moving objects
#

from PythonCAD.Generic.point import Point
from PythonCAD.Generic.segment import Segment
from PythonCAD.Generic.circle import Circle
from PythonCAD.Generic.arc import Arc
from PythonCAD.Generic.hcline import HCLine
from PythonCAD.Generic.vcline import VCLine
from PythonCAD.Generic.acline import ACLine
from PythonCAD.Generic.segjoint import Chamfer, Fillet
from PythonCAD.Generic.cline import CLine
from PythonCAD.Generic.ccircle import CCircle
from PythonCAD.Generic.leader import Leader
from PythonCAD.Generic.polyline import Polyline
from PythonCAD.Generic.text import TextBlock
from PythonCAD.Generic.dimension import Dimension
from PythonCAD.Generic.dimension import LinearDimension
from PythonCAD.Generic.dimension import AngularDimension
from PythonCAD.Generic.layer import Layer
from PythonCAD.Generic import util

def _adjust_dimensions(layer, point, newpoint):
    _users = point.getUsers()
    for _uref in _users:
        _user = _uref()
        if _user is not None:
            if isinstance(_user, Dimension):
                if isinstance(_user, LinearDimension):
                    _l1, _l2 = _user.getDimLayers()
                    _p1, _p2 = _user.getDimPoints()
                    if _l1 is layer and _p1 is point:
                        _user.setP1(layer, newpoint)
                    elif _l2 is layer and _p2 is point:
                        _user.setP2(layer, newpoint)
                elif isinstance(_user, AngularDimension):
                    _vl, _l1, _l2 = _user.getDimLayers()
                    _vp, _p1, _p2 = _user.getDimPoints()
                    if _vl is layer and _vp is point:
                        _user.setVertexPoint(layer, newpoint)
                    elif _l1 is layer and _p1 is point:
                        _user.setP1(layer, newpoint)
                    elif _l2 is layer and _p2 is point:
                        _user.setP2(layer, newpoint)
                else:
                    raise TypeError, "Unknown dimension type: " + `type(_user)`

def _most_used(plist):
    _pmax = plist.pop()
    _max = _pmax.countUsers()
    for _pt in plist:
        _count = _pt.countUsers()
        if _count > _max:
            _max = _count
            _pmax = _pt
    return _pmax

def _used_by(obj, plist):
    _objpt = None
    for _pt in plist:
        for _uref in _pt.getUsers():
            _user = _uref()
            if _user is not None and _user is obj:
                _objpt = _pt
                break
        if _objpt is not None:
            break
    return _objpt
    
def _old_move_segment(layer, segment, dx, dy):
    _p1, _p2 = segment.getEndpoints()
    _x, _y = _p1.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np1 = Point(_nx, _ny)
        layer.addObject(_np1)
    else:
        _np1 = _most_used(_pts)
    _adjust_dimensions(layer, _p1, _np1)
    _x, _y = _p2.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np2 = Point(_nx, _ny)
        layer.addObject(_np2)
    else:
        _np2 = _most_used(_pts)
    _adjust_dimensions(layer, _p2, _np2)
    segment.setP1(_np1)
    segment.setP2(_np2)
    layer.delObject(_p1)
    layer.delObject(_p2)

def _old_move_arc(layer, arc, dx, dy):
    _cp = arc.getCenter()
    _x, _y = _cp.getCoords()
    _ep1, _ep2 = arc.getEndpoints()
    _pts = layer.find('point', _ep1[0], _ep1[1])
    _lp1 = _used_by(arc, _pts)
    assert _lp1 is not None, "Lost arc first endpoint"
    _pts = layer.find('point', _ep2[0], _ep2[1])
    _lp2 = _used_by(arc, _pts)
    assert _lp2 is not None, "Lost arc second endpoint"
    _nx = _x + dx
    _ny = _y + dy
    _pts = layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _ncp = Point(_nx, _ny)
        layer.addObject(_ncp)
    else:
        _ncp = _most_used(_pts)
    for _ep in arc.getEndpoints():
        _ex, _ey = _ep
        _nx = _ex + dx
        _ny = _ey + dy
        _pts = layer.find('point', _nx, _ny)
        if len(_pts) == 0:
            _lp = Point(_nx, _ny)
            layer.addObject(_lp)
        else:
            _lp = _most_used(_pts)
        _lp.storeUser(arc)
    arc.setCenter(_ncp)        
    _adjust_dimensions(layer, _cp, _ncp)
    layer.delObject(_cp)
    _lp1.freeUser(arc)
    layer.delObject(_lp1)
    _lp2.freeUser(arc)
    layer.delObject(_lp2)

def _old_move_circle(layer, circle, dx, dy): # moves circle and ccircles
    _cp = circle.getCenter()
    _x, _y = _cp.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _ncp = Point(_nx, _ny)
        layer.addObject(_ncp)
    else:
        _ncp = _most_used(_pts)
    _adjust_dimensions(layer, _cp, _ncp)
    circle.setCenter(_ncp)
    layer.delObject(_cp)

def _old_move_leader(layer, leader, dx, dy):
    _p1, _p2, _p3 = leader.getPoints()
    _x, _y = _p1.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np1 = Point(_nx, _ny)
        layer.addObject(_np1)
    else:
        _np1 = _most_used(_pts)
    _adjust_dimensions(layer, _p1, _np1)
    _x, _y = _p2.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np2 = Point(_nx, _ny)
        layer.addObject(_np2)
    else:
        _np2 = _most_used(_pts)
    _adjust_dimensions(layer, _p2, _np2)
    _x, _y = _p3.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np3 = Point(_nx, _ny)
        layer.addObject(_np3)
    else:
        _np3 = _most_used(_pts)
    _adjust_dimensions(layer, _p3, _np3)
    leader.setP1(_np1)
    leader.setP2(_np2)
    leader.setP3(_np3)
    layer.delObject(_p1)
    layer.delObject(_p2)
    layer.delObject(_p3)

def _old_move_polyline(layer, polyline, dx, dy):
    _pts = polyline.getPoints()
    _npts = []
    for _pt in _pts:
        _x, _y = _pt.getCoords()
        _nx = _x + dx
        _ny = _y + dy
        _pts = layer.find('point', _nx, _ny)
        if len(_pts) == 0:
            _np = Point(_nx, _ny)
            layer.addObject(_np)
        else:
            _np = _most_used(_pts)
        _adjust_dimensions(layer, _pt, _np)
        _npts.append(_np)
    for _i in range(len(_npts)):
        polyline.setPoint(_i, _npts[_i])
    for _pt in _pts:
        layer.delObject(_pt)

def _old_move_segjoint(layer, segjoint, dx, dy):
    _s1, _s2 = segjoint.getSegments()
    _old_move_segment(layer, _s1, dx, dy)
    _old_move_segment(layer, _s2, dx, dy)

def _old_move_spcline(layer, spcline, dx, dy):
    _p = spcline.getLocation()
    _x, _y = _p.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np = Point(_nx, _ny)
        layer.addObject(_np)
    else:
        _np = _most_used(_pts)
    _adjust_dimensions(layer, _p, _np)
    spcline.setLocation(_np)
    layer.delObject(_p)

def _old_move_cline(layer, cline, dx, dy):
    _p1, _p2 = cline.getKeypoints()
    _x, _y = _p1.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np1 = Point(_nx, _ny)
        layer.addObject(_np1)
    else:
        _np1 = _most_used(_pts)
    _adjust_dimensions(layer, _p1, _np1)
    _x, _y = _p2.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np2 = Point(_nx, _ny)
        layer.addObject(_np2)
    else:
        _np2 = _most_used(_pts)
    _adjust_dimensions(layer, _p2, _np2)
    cline.setP1(_np1)
    cline.setP2(_np2)
    layer.delObject(_p1)
    layer.delObject(_p2)

def _old_move_dimension(dim, dx, dy):
    _x, _y = dim.getLocation()
    _nx = _x + dx
    _ny = _y + dy
    dim.setLocation(_nx, _ny)

def _can_move(obj, objdict):
    for _uref in obj.getUsers():
        _user = _uref()
        if _user is not None and id(_user) not in objdict:
            return False
    return True

def _copy_spcline(obj, objdict, dx, dy):
    _lp = obj.getLocation()
    _pid = id(_lp)
    _layer = obj.getParent()
    _x, _y = _lp.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = _layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np = Point(_nx, _ny)
        _layer.addObject(_np)
    else:
        _np = _most_used(_pts)
    obj.setLocation(_np)
    _adjust_dimensions(_layer, _lp, _np)
    _layer.delObject(_lp)
    if _pid not in objdict or objdict[_pid]:
        objdict[_pid] = False

def _move_spcline(obj, objdict, dx, dy):
    if isinstance(obj, HCLine):
        _objtype = 'HCLine'
    elif isinstance(obj, VCLine):
        _objtype = 'VCLine'
    elif isinstance(obj, ACLine):
        _objtype = 'ACLine'
    else:
        raise TypeError, "Unexpected object type: " + `type(obj)`
    _layer = obj.getParent()
    if _layer is None:
        raise RuntimeError, "%s parent is None" % _objtype
    _lp = obj.getLocation()
    if _lp.getParent() is not _layer:
        raise RuntimeError, "%s/point parent object conflict!" % _objtype
    if _can_move(_lp, objdict):
        _pid = id(_lp)
        if _pid in objdict:
            if objdict[_pid]:
                _lp.move(dx, dy)
        else:
            obj.move(dx, dy)
        if _pid not in objdict or objdict[_pid]:
            objdict[_pid] = False
    else:
        _copy_spcline(obj, objdict, dx, dy)

def _copy_polyline(obj, objdict, dx, dy):
    _pts = obj.getPoints()
    _mp = {}
    for _pt in _pts:
        _pid = id(_pt)
        _mp[_pid] = False
    if _can_move(obj, objdict):
        for _pt in _pts:
            _pid = id(_pt)
            if ((_can_move(_pt, objdict)) and
                ((_pid not in objdict) or
                 (_pid in objdict and objdict[_pid]))):
                _mp[_pid] = True
    _layer = obj.getParent()
    for _i in range(len(_pts)):
        _pt = _pts[_i]
        _pid = id(_pt)
        if _mp[_pid]:
            _pt.move(dx, dy)
        else:
            _x, _y = _pt.getCoords()
            _nx = _x + dx
            _ny = _y + dy
            _lpts = _layer.find('point', _nx, _ny)
            if len(_lpts) == 0:
                _np = Point(_nx, _ny)
                _layer.addObject(_np)
            else:
                _np = _most_used(_lpts)
            obj.setPoint(_i, _np)                
            _adjust_dimensions(_layer, _pt, _np)
            _layer.delObject(_pt)
        if _pid not in objdict or objdict[_pid]:
            objdict[_pid] = False

def _move_polyline(obj, objdict, dx, dy):
    _pts = obj.getPoints()
    _layer = obj.getParent()
    if _layer is None:
        raise RuntimeError, "Polyline parent is None"
    for _pt in _pts:
        if _pt.getParent() is not _layer:
            raise RuntimeError, "Polyline/point parent object conflict!"
    _use_move = _can_move(obj, objdict)
    if _use_move:
        for _pt in _pts:
            if not _can_move(_pt, objdict):
                _use_move = False
                break
    if _use_move:
        _objmove = True
        _seen = False
        _used = True
        for _pt in _pts:
            _pid = id(_pt)
            if _pid in objdict:
                _seen = True
                if not objdict[_pid]:
                    _used = False
            if _seen and not _used:
                _objmove = False
                break
        if _objmove:
            obj.move(dx, dy)
        else:
            for _pt in _pts:
                _pid = id(_pt)
                if ((_pid not in objdict) or
                    (_pid in objdict and objdict[_pid])):
                    _pt.move(dx, dy)
        for _pt in _pts:
            _pid = id(_pt)
            if _pid not in objdict or objdict[_pid]:
                objdict[_pid] = False
    else:
        _copy_polyline(obj, objdict, dx, dy)

def _copy_leader(obj, objdict, dx, dy):
    _p1, _p2, _p3 = obj.getPoints()
    _p1id = id(_p1)
    _p2id = id(_p2)
    _p3id = id(_p3)
    _mp1 = _mp2 = _mp3 = False
    if _can_move(obj, objdict):
        _mp1 = ((_can_move(_p1, objdict)) and
                ((_p1id not in objdict) or
                 (_p1id in objdict and objdict[_p1id])))
        _mp2 = ((_can_move(_p2, objdict)) and
                ((_p2id not in objdict) or
                 (_p2id in objdict and objdict[_p2id])))
        _mp3 = ((_can_move(_p3, objdict)) and
                ((_p3id not in objdict) or
                 (_p3id in objdict and objdict[_p3id])))
    _layer = obj.getParent()
    if _mp1:
        _p1.move(dx, dy)
    else:
        _x, _y = _p1.getCoords()
        _nx = _x + dx
        _ny = _y + dy
        _pts = _layer.find('point', _nx, _ny)
        if len(_pts) == 0:
            _np = Point(_nx, _ny)
            _layer.addObject(_np)
        else:
            _np = _most_used(_pts)
        obj.setP1(_np)
        _adjust_dimensions(_layer, _p1, _np)
        _layer.delObject(_p1)
    if _mp2:
        _p2.move(dx, dy)
    else:
        _x, _y = _p2.getCoords()
        _nx = _x + dx
        _ny = _y + dy
        _pts = _layer.find('point', _nx, _ny)
        if len(_pts) == 0:
            _np = Point(_nx, _ny)
            _layer.addObject(_np)
        else:
            _np = _most_used(_pts)
        obj.setP2(_np)
        _adjust_dimensions(_layer, _p2, _np)
        _layer.delObject(_p2)
    if _mp3:
        _p3.move(dx, dy)
    else:
        _x, _y = _p3.getCoords()
        _nx = _x + dx
        _ny = _y + dy
        _pts = _layer.find('point', _nx, _ny)
        if len(_pts) == 0:
            _np = Point(_nx, _ny)
            _layer.addObject(_np)
        else:
            _np = _most_used(_pts)
        obj.setP3(_np)
        _adjust_dimensions(_layer, _p3, _np)
        _layer.delObject(_p3)
    if _p1id not in objdict or objdict[_p1id]:
        objdict[_p1id] = False
    if _p2id not in objdict or objdict[_p2id]:
        objdict[_p2id] = False
    if _p3id not in objdict or objdict[_p3id]:
        objdict[_p3id] = False

def _move_leader(obj, objdict, dx, dy):
    _p1, _p2, _p3 = obj.getPoints()
    _layer = obj.getParent()
    if _layer is None:
        raise RuntimeError, "Leader parent is None"
    if _p1.getParent() is not _layer:
        raise RuntimeError, "Leader/P1 parent object conflict!"
    if _p2.getParent() is not _layer:
        raise RuntimeError, "Leader/P2 parent object conflict!"
    if _p3.getParent() is not _layer:
        raise RuntimeError, "Leader/P3 parent object conflict!"
    if ((_can_move(obj, objdict)) and
        (_can_move(_p1, objdict)) and
        (_can_move(_p2, objdict)) and
        (_can_move(_p3, objdict))):
        _p1id = id(_p1)
        _p2id = id(_p2)
        _p3id = id(_p3)
        if ((_p1id in objdict and objdict[_p1id] and
             _p2id in objdict and objdict[_p2id] and
             _p3id in objdict and objdict[_p3id]) or
            (_p1id not in objdict and
             _p2id not in objdict and
             _p3id not in objdict)):
            obj.move(dx, dy)
        else:
            if ((_p1id not in objdict) or
                (_p1id in objdict and objdict[_p1id])):
                _p1.move(dx, dy)
            if ((_p2id not in objdict) or
                (_p2id in objdict and objdict[_p2id])):
                _p2.move(dx, dy)
            if ((_p3id not in objdict) or
                (_p3id in objdict and objdict[_p3id])):
                _p3.move(dx, dy)
        if _p1id not in objdict or objdict[_p1id]:
            objdict[_p1id] = False
        if _p2id not in objdict or objdict[_p2id]:
            objdict[_p2id] = False
        if _p3id not in objdict or objdict[_p3id]:
            objdict[_p3id] = False
    else:
        _copy_leader(obj, objdict, dx, dy)

def _adjust_endpoint(arc, pt, objdict, dx, dy):
    _layer = arc.getParent()
    if pt.getParent() is not _layer:
        raise RuntimeError, "Arc/Endpoint parent object conflict!"
    _pid = id(pt)
    _users = []
    for _uref in pt.getUsers():
        _user = _uref()
        if _user is not None:
            _users.append(_user)
    if len(_users) == 1 and _users[0] is arc:
        if ((_pid not in objdict) or
            (_pid in objdict and objdict[_pid])):
            pt.move(dx, dy)
    else:
        pt.freeUser(arc)
        _x, _y = pt.getCoords()
        _nx = _x + dx
        _ny = _y + dy
        _pts = _layer.find('point', _nx, _ny)
        if len(_pts) == 0:
            _np = Point(_nx, _ny)
            _layer.addObject(_np)
        else:
            _np = _most_used(_pts)
        _np.storeUser(arc)
        _adjust_dimensions(_layer, pt, _np)
        _layer.delObject(pt)
    if _pid not in objdict or objdict[_pid]:
        objdict[_pid] = False
    
def _copy_arc(obj, objdict, dx, dy):
    _cp = obj.getCenter()
    _pid = id(_cp)
    _layer = obj.getParent()
    _ep1, _ep2 = obj.getEndpoints()
    _pts = _layer.find('point', _ep1[0], _ep1[1])
    _lp1 = _used_by(obj, _pts)
    if _lp1 is None:
        raise RuntimeError, "Lost Arc first endpoint: " + str(_ep1)
    _adjust_endpoint(obj, _lp1, objdict, dx, dy)
    _pts = _layer.find('point', _ep2[0], _ep2[1])
    _lp2 = _used_by(obj, _pts)
    if _lp2 is None:
        raise RuntimeError, "Lost Arc second endpoint: " + str(_ep2)
    _adjust_endpoint(obj, _lp2, objdict, dx, dy)
    _x, _y = _cp.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = _layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np = Point(_nx, _ny)
        _layer.addObject(_np)
    else:
        _np = _most_used(_pts)
    obj.setCenter(_np)
    _adjust_dimensions(_layer, _cp, _np)
    _layer.delObject(_cp)
    if _pid not in objdict or objdict[_pid]:
        objdict[_pid] = False

def _move_arc(obj, objdict, dx, dy):
    _layer = obj.getParent()
    if _layer is None:
        raise RuntimeError, "Arc parent is None"
    _cp = obj.getCenter()    
    if _cp.getParent() is not _layer:
        raise RuntimeError, "Arc/center parent object conflict!"
    if ((_can_move(obj, objdict)) and
        (_can_move(_cp, objdict))):
        _ep1, _ep2 = obj.getEndpoints()
        _pts = _layer.find('point', _ep1[0], _ep1[1])
        _lp1 = _used_by(obj, _pts)
        if _lp1 is None:
            raise RuntimeError, "Lost Arc first endpoint: " + str(_ep1)
        _adjust_endpoint(obj, _lp1, objdict, dx, dy)
        _pts = _layer.find('point', _ep2[0], _ep2[1])
        _lp2 = _used_by(obj, _pts)
        if _lp2 is None:
            raise RuntimeError, "Lost Arc second endpoint: " + str(_ep2)
        _adjust_endpoint(obj, _lp2, objdict, dx, dy)
        _pid = id(_cp)
        if _pid in objdict:
            if objdict[_pid]:
                _cp.move(dx, dy)
        else:
            obj.move(dx, dy)
            
        if _pid not in objdict or objdict[_pid]:
            objdict[_pid] = False
    else:
        _copy_arc(obj, objdict, dx, dy)

def _copy_circ_ccirc(obj, objdict, dx, dy):
    _cp = obj.getCenter()
    _pid = id(_cp)
    _layer = obj.getParent()
    _x, _y = _cp.getCoords()
    _nx = _x + dx
    _ny = _y + dy
    _pts = _layer.find('point', _nx, _ny)
    if len(_pts) == 0:
        _np = Point(_nx, _ny)
        _layer.addObject(_np)
    else:
        _np = _most_used(_pts)
    obj.setCenter(_np)
    _adjust_dimensions(_layer, _cp, _np)
    _layer.delObject(_cp)
    if _pid not in objdict or objdict[_pid]:
        objdict[_pid] = False

def _move_circle(obj, objdict, dx, dy):
    if isinstance(obj, Circle):
        _objtype = 'Circle'
    elif isinstance(obj, CCircle):
        _objtype = 'CCircle'
    else:
        raise TypeError, "Unexpected object type: " + `type(obj)`
    _layer = obj.getParent()
    if _layer is None:
        raise RuntimeError, "%s parent is None" % _objtype
    _cp = obj.getCenter()    
    if _cp.getParent() is not _layer:
        raise RuntimeError, "%s/center parent object conflict!" % _objtype
    if ((_can_move(obj, objdict)) and
        (_can_move(_cp, objdict))):
        _pid = id(_cp)
        if _pid in objdict:
            if objdict[_pid]:
                _cp.move(dx, dy)
        else:
            obj.move(dx, dy)
        if _pid not in objdict or objdict[_pid]:
            objdict[_pid] = False
    else:
        _copy_circ_ccirc(obj, objdict, dx, dy)

def _copy_seg_cline(obj, objdict, dx, dy):
    if isinstance(obj, Segment):
        _p1, _p2 = obj.getEndpoints()
    elif isinstance(obj, CLine):
        _p1, _p2 = obj.getKeypoints()
    else:
        raise TypeError, "Unexpected object type: " + `type(obj)`
    _p1id = id(_p1)
    _p2id = id(_p2)
    _mp1 = _mp2 = False
    if _can_move(obj, objdict):
        _mp1 = ((_can_move(_p1, objdict)) and
                ((_p1id not in objdict) or
                 (_p1id in objdict and objdict[_p1id])))
        _mp2 = ((_can_move(_p2, objdict)) and
                ((_p2id not in objdict) or
                 (_p2id in objdict and objdict[_p2id])))
    _layer = obj.getParent()
    if _mp1:
        _p1.move(dx, dy)
    else:
        _x, _y = _p1.getCoords()
        _nx = _x + dx
        _ny = _y + dy
        _pts = _layer.find('point', _nx, _ny)
        if len(_pts) == 0:
            _np = Point(_nx, _ny)
            _layer.addObject(_np)
        else:
            _np = _most_used(_pts)
        obj.setP1(_np)
        _adjust_dimensions(_layer, _p1, _np)
        _layer.delObject(_p1)
    if _mp2:
        _p2.move(dx, dy)
    else:
        _x, _y = _p2.getCoords()
        _nx = _x + dx
        _ny = _y + dy
        _pts = _layer.find('point', _nx, _ny)
        if len(_pts) == 0:
            _np = Point(_nx, _ny)
            _layer.addObject(_np)
        else:
            _np = _most_used(_pts)
        obj.setP2(_np)
        _adjust_dimensions(_layer, _p2, _np)
        _layer.delObject(_p2)
    if _p1id not in objdict or objdict[_p1id]:
        objdict[_p1id] = False
    if _p2id not in objdict or objdict[_p2id]:
        objdict[_p2id] = False
        
def _move_seg_cline(obj, objdict, dx, dy):
    if isinstance(obj, Segment):
        _p1, _p2 = obj.getEndpoints()
        _objtype = 'Segment'
    elif isinstance(obj, CLine):
        _p1, _p2 = obj.getKeypoints()
        _objtype = 'CLine'
    else:
        raise TypeError, "Unexpected object type: " + `type(obj)`
    _layer = obj.getParent()
    if _layer is None:
        raise RuntimeError, "%s parent is None" % _objtype
    if _p1.getParent() is not _layer:
        raise RuntimeError, "%s/P1 parent object conflict!" % _objtype
    if _p2.getParent() is not _layer:
        raise RuntimeError, "%s/P2 parent object conflict!" % _objtype
    if ((_can_move(obj, objdict)) and
        (_can_move(_p1, objdict)) and
        (_can_move(_p2, objdict))):
        _p1id = id(_p1)
        _p2id = id(_p2)
        if ((_p1id in objdict and objdict[_p1id] and
             _p2id in objdict and objdict[_p2id]) or
            (_p1id not in objdict and
             _p2id not in objdict)):
            obj.move(dx, dy)
        else:
            if ((_p1id not in objdict) or
                (_p1id in objdict and objdict[_p1id])):
                _p1.move(dx, dy)
            if ((_p2id not in objdict) or
                (_p2id in objdict and objdict[_p2id])):
                _p2.move(dx, dy)
        if _p1id not in objdict or objdict[_p1id]:
            objdict[_p1id] = False
        if _p2id not in objdict or objdict[_p2id]:
            objdict[_p2id] = False
    else:
        _copy_seg_cline(obj, objdict, dx, dy)

def move_objects(objs, dx, dy):
    """Move a list of objects.

move_objects(objs, dx, dy)

objs: A list or tuple containing the objects to move.
dx: The displacement along the x-axis
dy: The displacement along the y-axis
    """
    if not isinstance(objs, (list, tuple)):
        raise TypeError, "Invalid object list/tuple: " + `type(objs)`
    _dx = util.get_float(dx)
    _dy = util.get_float(dy)
    if abs(_dx) > 1e-10 or abs(_dy) > 1e-10:
        _objdict = {}
        _fillets = []
        for _obj in objs:
            _objdict[id(_obj)] = True
        for _obj in objs:
            _oid = id(_obj)
            if _objdict[_oid]:
                if isinstance(_obj, Point):
                    _obj.move(_dx, _dy)
                    for _uref in _obj.getUsers():
                        _user = _uref()
                        if _user is not None:
                            _uid = id(_user)
                            if _uid in _objdict:
                                _objdict[_uid] = False
                elif isinstance(_obj, (Segment, CLine)):
                    _move_seg_cline(_obj, _objdict, _dx, _dy)
                elif isinstance(_obj, (Circle, CCircle)):
                    _move_circle(_obj, _objdict, _dx, _dy)
                elif isinstance(_obj, Arc):
                    _move_arc(_obj, _objdict, _dx, _dy)
                elif isinstance(_obj, Leader):
                    _move_leader(_obj, _objdict, _dx, _dy)
                elif isinstance(_obj, Polyline):
                    _move_polyline(_obj, _objdict, _dx, _dy)
                elif isinstance(_obj, (TextBlock, Dimension)):
                    _obj.move(_nx, _ny)
                elif isinstance(_obj, (HCLine, VCLine, ACLine)):
                    _move_spcline(_obj, _objdict, _dx, _dy)
                elif isinstance(_obj, (Chamfer, Fillet)):
                    _s1, _s2 = _obj.getSegments()
                    if id(_s1) not in _objdict or id(_s2) not in _objdict:
                        _layer = _obj.getParent()
                        _layer.delObject(_obj)
                    if isinstance(_obj, Fillet):
                        _fillets.append(_obj)
                else:
                    print "Unexpected entity type: " + `type(_obj)`
            _objdict[_oid] = False
        for _obj in _fillets:
            _obj._calculateCenter() # FIXME

def old_move_objects(layer, objlist, dx, dy):
    """Move objects in a layer.

move_objects(layer, objlist, dx, dy)

layer; The layer in which all the objects are located
objlist: The list of objects to move. This argument must be a list
dx: The displacement along the x-axis
dy: The displacement along the y-axis
    """
    if not isinstance(layer, Layer):
        raise TypeError, "Invalid layer: " + str(layer)
    if not isinstance(objlist, list):
        raise TypeError, "Invalid object list: " + str(objlist)
    _dx = util.get_float(dx)
    _dy = util.get_float(dy)
    if abs(_dx) < 1e-10 and abs(_dy) < 1e-10:
        return
    _objlist = []
    _objdict = {}
    for _obj in objlist:
        _lobj = layer.findObject(_obj)
        if _lobj is not _obj:
            raise ValueError, "Object not found in layer: " + str(_obj)
        _objdict[id(_obj)] = True
        _objlist.append(_obj)
    for _obj in _objlist:
        if isinstance(_obj, Segment):
            _p1, _p2 = _obj.getEndpoints()
            _pid = id(_p1)
            if _pid in _objdict:
                _objdict[_pid] = False
            _pid = id(_p2)
            if _pid in _objdict:
                _objdict[_pid] = False
        elif isinstance(_obj, (Circle, Arc, CCircle)):
            _cp = _obj.getCenter()
            _cpid = id(_cp)
            if _cpid in _objdict:
                _objdict[_cpid] = False
            if isinstance(_obj, Arc):
                for _ep in _obj.getEndpoints():
                    _lp = layer.find('point', _ep[0], _ep[1])
                    if _lp is None:
                        raise ValueError, "Lost arc endpoint: " + str(_ep)
                    _pid = id(_lp)
                    if _pid in _objdict:
                        _objdict[_pid] = False
        elif isinstance(_obj, (HCLine, VCLine, ACLine)):
            _p = _obj.getLocation()
            _pid = id(_p)
            if _pid in _objdict:
                _objdict[_pid] = False
        elif isinstance(_obj, CLine):
            _p1, _p2 = _obj.getKeypoints()
            _pid = id(_p1)
            if _pid in _objdict:
                _objdict[_pid] = False
            _pid = id(_p2)
            if _pid in _objdict:
                _objdict[_pid] = False
        elif isinstance(_obj, (Leader, Polyline)):
            for _pt in _obj.getPoints():
                _pid = id(_pt)
                if _pid in _objdict:
                    _objdict[_pid] = False
        elif isinstance(_obj, (Chamfer, Fillet)):
            _s1, _s2 = _obj.getSegments()
            _sid = id(_s1)
            if _sid in _objdict:
                _objdict[_sid] = False
            _p1, _p2 = _s1.getEndpoints()
            _pid = id(_p1)
            if _pid in _objdict:
                _objdict[_pid] = False
            _pid = id(_p2)
            if _pid in _objdict:
                _objdict[_pid] = False
            _sid = id(_s2)
            if _sid in _objdict:
                _objdict[_sid] = False
            _p1, _p2 = _s2.getEndpoints()
            _pid = id(_p1)
            if _pid in _objdict:
                _objdict[_pid] = False
            _pid = id(_p2)
            if _pid in _objdict:
                _objdict[_pid] = False
        else:
            pass
    for _obj in _objlist:
        if _objdict[id(_obj)]:
            if isinstance(_obj, Point):
                _obj.move(_dx, _dy)
            elif isinstance(_obj, Segment):
                _old_move_segment(layer, _obj, _dx, _dy)
            elif isinstance(_obj, Arc):
                _old_move_arc(layer, _obj, _dx, _dy)
            elif isinstance(_obj, (Circle, CCircle)):
                _old_move_circle(layer, _obj, _dx, _dy)
            elif isinstance(_obj, Leader):
                _old_move_leader(layer, _obj, _dx, _dy)
            elif isinstance(_obj, Polyline):
                _old_move_polyline(layer, _obj, _dx, _dy)
            elif isinstance(_obj, (Chamfer, Fillet)):
                _old_move_segjoint(layer, _obj, _dx, _dy)
            elif isinstance(_obj, (HCLine, VCLine, ACLine)):
                _old_move_spcline(layer, _obj, _dx, _dy)
            elif isinstance(_obj, CLine):
                _old_move_cline(layer, _obj, _dx, _dy)
            elif isinstance(_obj, Dimension):
                _old_move_dimension(_obj, _dx, _dy)
            elif isinstance(_obj, TextBlock):
                _x, _y = _obj.getLocation()
                _nx = _x + _dx
                _ny = _y + _dy
                _obj.setLocation(_nx, _ny)
            else:
                pass
