#
# 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
#
#
# The class for a drawing
#

import sys
import math

import layer
import point
import segment
import circle
import ccircle
import hcline
import vcline
import acline
import cline
import leader
import polyline
import style
import linetype
import tolerance
import intersections
import dimension
import color
import text
import units
import options
import globals
import baseobject
import entity

class Image(entity.Entity):
    """The class representing a CAD drawing.

This class contains all the interface-neutral parts of
a drawing. An image is essentially a collection of Layer
objects, plus the bits needed to store the colors, linetypes,
and styles used in a drawing.

Each instance has several attributes:

active_layer: The currently active Layer
top_layer: The initial Layer in the Image
scale: The scale factor of the Image

The following methods are available for each instance:

{get/set}Scale(): Get/Set the current scale factor.
hasColor(): See if a color is already in use in the drawing.
addColor(): Add a Color to the set available for objects in the drawing.
hasLinetype(): See if a Linetype is found in the drawing.
addLinetype(): Add a Linetype to the set available for objects in the drawing.
hasStyle(): See if a Style is in the drawing.
addStyle(): Add a Style to the set available for objects in the drawing.
{get/set}ActiveLayer(): Get/Set the currently active Layer.
addChildLayer(): Make one Layer object a child of another.
addLayer(): Make one Layer object a child of the active Layer's parent.
delLayer(): Remove a Layer from the image.
hasPoint(): Find a Point object in the drawing.
findPoint(): Find a Point object in the drawing.
mapPoint(): Find objects in the drawing where at some location.
addObject(): Add an object to the drawing.
delObject(): Delete an object from the drawing.
getObject(): Return an object with a specific entity ID
selectObject(): Store a references to an object in the drawing.
deselectObject(): Release a reference to a stored object.
getSelectedObjects(): Retrieve all the selected objects.
clearSelectedObjets(): Release all references to selected objects.
hasSelection(): Return whether the image has an active selection.
getExtents(): Find the size of the drawing.
{get/set}Option(): Retrieve/Store an option used in the drawing.
{get/set}Filename(): Get/Set the filename for this image.
getImageEntities(): Get all the instances of certain image-wide object.
{get/set}Units(): Get/Set the basic length unit in the image.
scaleLength(): Return a linear distance in millimeters.
    """

    messages = {
    'scale_changed' : True,
    'added_object' : True,
    'deleted_object' : True,
    'added_layer' : True,
    'deleted_layer' : True
    }
    def __init__(self, **kw):
        """Instatiate a Image object.

Image()

There are no parameters used to create the object.
        """
        entity.Entity.__init__(self, **kw)
        _top = layer.Layer(u'TopLayer')
        _top.setParent(self)
        self.__top_layer = _top
        self.__active_layer = _top
        _top.connect('modified', self, Image.layerModified)
        _log = layer.LayerLog(_top)
        _top.setLog(_log)
        self.__scale = 1.0
        self.__styles = []
        self.__dimstyles = []
        self.__textstyles = []
        self.__linetypes = []
        self.__colors = baseobject.TypedDict(keytype=color.Color)
        self.__units = units.Unit(units.MILLIMETERS)
        self.__options = baseobject.TypedDict(keytype=str) # miscellaneous options
        self.__fonts = baseobject.TypedDict(keytype=str) # font names
        self.__selected = {}
        self.__filename = None
        self.__busy = False
        self.__undo = []
        self.__redo = []
        self.__delhist = {}
        self.__action = 0L
        add_defaults(self)

    def __contains__(self, obj):
        """Define if an object is in the Drawing.

Defining this method allows the use of "in" type test.
        """
        _res = False
        if isinstance(obj, style.Style):
            _res = obj in self.__styles
        elif isinstance(obj, linetype.Linetype):
            _res = obj in self.__linetypes
        elif isinstance(obj, color.Color):
            _res = obj in self.__colors
        elif isinstance(obj, dimension.DimStyle):
            _res = obj in self.__dimstyles
        elif isinstance(obj, text.TextStyle):
            _res = obj in self.__textstyles
        else:
            _layers = [self.__top_layer]
            while (len(_layers)):
                _layer = _layers.pop()
                _res = obj in _layer
                if _res:
                    break
                _layers.extend(_layer.getSublayers())
        return _res

    def close(self):
        """Release all the entities stored in the drawing

close()
        """
        print "in image::close()"
        del self.__styles[:]
        self.__colors.clear()
        del self.__linetypes[:]
        del self.__dimstyles[:]
        del self.__textstyles[:]
        self.__options.clear()
        self.__fonts.clear()
        _layers = []
        _sublayers = [self.__top_layer]
        while(len(_sublayers)):
            _layer = _sublayers.pop()
            _layers.append(_layer)
            _sublayers.extend(_layer.getSublayers())
        _layers.reverse()
        for _layer in _layers:
            print "closing layer " + _layer.getName()
            _layer.clear()
            _layer.setParentLayer(None)
            _layer.setParent(None)

    def addChildLayer(self, l, p=None):
        """Add a child Layer of the active Layer.

addChildLayer(l [, p])

There is a one required argument:

l: The child Layer

There is one optional argument:

p: The new parent Layer of the child

The default parent is the currently active layer.

The child layer cannot be a layer found when moving
up from the new parent layer to the topmost layer.
        """
        _child = l
        if not isinstance(_child, layer.Layer):
            raise TypeError, "Invalid child argument: " + `_child`
        _pl = p
        if _pl is None:
            _pl = self.__active_layer
        if not isinstance(_pl, layer.Layer):
            raise TypeError, "Invalid parent argument: " + `_pl`
        if _child is _pl:
            raise ValueError, "Child and parent layers identical."
        _layer = _pl
        _tpl = _pl.getParentLayer()
        while _tpl is not None:
            _layer = _tpl
            if _tpl is _child:
                raise ValueError, "Child layer found in parent chain"
            _tpl = _tpl.getParentLayer()
        if _layer is not self.__top_layer:
            raise ValueError, "Parent layer not found in drawing"
        _child.setParentLayer(_pl)
        _parent = _child.getParent()
        if _parent is None or _parent is not self:
            _child.setParent(self)
        _log = _child.getLog()
        if _log is None:
            _log = layer.LayerLog(_child)
            _child.setLog(_log)
        _child.connect('modified', self, Image.layerModified)
        self.__active_layer = _child
        self.sendMessage('added_layer', _layer, _pl)

    def addLayer(self, l):
        """Add a new Layer as a child of the active Layer's parent.

addLayer(l)

If the active layer is the topmost Layer in the drawing, the Layer
is added as a child Layer to that Layer. Otherwise, the new layer
is added and is a sibling to the active Layer.
        """
        _layer = l
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid new Layer: " + `_layer`
        _pl = self.__active_layer.getParentLayer()
        if _pl is None:
            _pl = self.__top_layer
        if _layer is _pl:
            raise ValueError, "Child and parent layers identical."
        _lp = _layer.getParentLayer()
        if _lp is not None: # see if layer already in drawing ...
            _l = _pl
            _pl = _l.getParentLayer()
            while _pl is not None:
                if _layer is _pl:
                    raise ValueError, "Layer found in parent chain."
                _l = _pl
        _layer.setParentLayer(_pl)
        _parent = _layer.getParent()
        if _parent is None or _parent is not self:
            _layer.setParent(self)
        self.__active_layer = _layer
        _log = _layer.getLog()
        if _log is None:
            _log = layer.LayerLog(_layer)
            _layer.setLog(_log)
        _layer.connect('modified', self, Image.layerModified)
        self.sendMessage('added_layer', _layer, _pl)

    def delLayer(self, l):
        """Remove a Layer from the drawing.

delLayer(l)

A Layer object cannot be removed until its children are
either deleted or moved to another Layer.

The topmost Layer in a drawing cannot be deleted.
        """
        _layer = l
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid Layer object: " + `_layer`
        _l = _layer
        _pl = _l.getParentLayer()
        while _pl is not None:
            _l = _pl
            _pl = _pl.getParentLayer()
        if _l is not self.__top_layer:
            raise ValueError, "Layer not found in drawing: " + `_layer`
        _pl = _layer.getParentLayer()
        if _pl is not None:
            if not _pl.hasSublayers():
                raise ValueError, "Layer not in parent sublayer: " + `_layer`
            if _layer not in _pl.getSublayers():
                raise ValueError, "Layer not in parent sublayers: " + `_layer`
            if not _layer.hasSublayers():
                _layer.setParentLayer(None)
                _layer.setParent(None)
            _layer.disconnect(self)
            self.sendMessage('deleted_layer', _layer, _pl)

    def hasLayer(self, l):
        """Return whether or not a layer is in a drawing.

hasLayer(l)
        """
        _layer = l
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid layer: " + `_layer`
        _flag = False
        _l = _layer
        _p = _l.getParentLayer()
        while _p is not None:
            _l = _p
            _p = _p.getParentLayer()
        if _l is self.__top_layer:
            _flag = True
        return _flag

    def getActiveLayer(self):
        """Return the active Layer in the drawing.

getActiveLayer()

The active Layer is the Layer to which any new objects will
be stored.
        """
        return self.__active_layer

    def setActiveLayer(self, l=None):
        """Set the active Layer in the Image.

setActiveLayer(l)

The the Layer "l" to be the active Layer in the drawing. If
the function is called without arguments, the topmost Layer
in the drawing is set to the active layer.
        """
        _layer = l
        if _layer is None:
            _layer = self.__top_layer
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid active Layer: " + `_layer`
        if _layer is not self.__top_layer:
            _l = _layer
            _p = _l.getParentLayer()
            while _p is not None:
                _l = _p
                _p = _p.getParentLayer()
            if _l is not self.__top_layer:
                raise ValueError, "Layer not found in image: " + `_layer`
            _parent = _layer.getParentLayer()
            if not _parent.hasSublayers():
                raise ValueError, "Layer not in parent sublayer: " + `_layer`
            if _layer not in _parent.getSublayers():
                raise ValueError, "Layer not in parent sublayers: " + `_layer`
        self.__active_layer = _layer

    active_layer = property(getActiveLayer, setActiveLayer,
                            None, "Image active Layer object.")

    def getTopLayer(self):
        """Return the top Layer of the image

getTopLayer()
        """
        return self.__top_layer

    top_layer = property(getTopLayer, None, None, "Image top Layer.")

    def getScale(self):
        """Return the image's scale factor.

getScale()
        """
        return self.__scale

    def setScale(self, scale):
        """Set the image's scale factor.

setScale(scale)

The scale must be a float greater than 0.
        """
        _s = scale
        if not isinstance(_s, float):
            _s = float(scale)
        if _s < 1e-10:
            raise ValueError, "Invalid scale factor: %g" % _s
        _os = self.__scale
        if abs(_os - _s) > 1e-10:
            self.__scale = _s
            self.sendMessage('scale_changed', _os)
            self.modified()

    scale = property(getScale, setScale, None, "Image scale factor.")

    def canParent(self, obj):
        """Test if an Entity can be the parent of another Entity.

canParent(obj)

This method overrides the Entity::canParent() method. An Image can
be the parent of Layer entities only.
        """
        return isinstance(obj, layer.Layer)
    
    def getImageEntities(self, entity):
        """Return all the entities of a particular type

getImageEntities(entity)

The argument "entity" should be one of the following:
color, linetype, style, font, dimstyle, or textstyle
        """
        if entity == "color":
            _objs = self.__colors.keys()
            _objs.sort()
        elif entity == "linetype":
            _objs = self.__linetypes[:]
        elif entity == "style":
            _objs = self.__styles[:]
        elif entity == "font":
            _objs = self.__fonts.keys()
        elif entity == "dimstyle":
            _objs = self.__dimstyles[:]
        elif entity == "textstyle":
            _objs = self.__textstyles[:]
        else:
            raise ValueError, "Invalid image entity: " + `entity`
        return _objs

    def addColor(self, c):
        """Add a Color object to the drawing.

addColor(c)
        """
        if not isinstance(c, color.Color):
            raise TypeError, "Invalid Color for addition: " + `c`
        if c not in self.__colors:
            self.__colors[c] = True # maybe count entities ?

    def hasColor(self, c):
        """Check if a Color already exists in the drawing.

hasColor(c)
        """
        _c = c
        if not isinstance(_c, color.Color):
            _c = color.Color(c)
        return _c in self.__colors

    def getColor(self, c):
        """
        """
        _c = c
        if not isinstance(_c, color.Color):
            _c = color.Color(c)
        return globals.colors.setdefault(_c, _c)
    
    def addLinetype(self, lt):
        """Add a Linetype to the drawing.

addLinetype(lt)
        """
        if not isinstance(lt, linetype.Linetype):
            raise TypeError, "Invalid Linetype for addition: " + `lt`
        if lt not in self.__linetypes:
            self.__linetypes.append(lt)

    def hasLinetype(self, lt):
        """Check if a Linetype already exists in the drawing.

hasLinetype(lt)
        """
        if not isinstance(lt, linetype.Linetype):
            raise TypeError, "Invalid Linetype for testing: " + `lt`
        return lt in self.__linetypes

    def getLinetype(self, lt):
        """
        """
        if not isinstance(lt, linetype.Linetype):
            raise TypeError, "Invalid Linetype: " + `lt`
        return globals.linetypes.setdefault(lt, lt)
    
    def addStyle(self, s):
        """Add a Style to the drawing.

addStyle(s)
        """
        if not isinstance(s, style.Style):
            raise TypeError, "Invalid Style for addtion: " + `s`
        if s not in self.__styles:
            _col = s.getColor()
            if _col not in self.__colors:
                self.__colors[_col] = True
            _lt = s.getLinetype()
            if _lt not in self.__linetypes:
                self.__linetypes.append(_lt)
            self.__styles.append(s)

    def hasStyle(self, s):
        """Check if a Style already exists within the drawing.

hasStyle(s)
        """
        _s = s
        if not isinstance(_s, style.Style):
            _s = style.Style(s)
        return _s in self.__styles

    def addDimStyle(self, ds):
        """Add a DimStyle to the drawing

addDimStyle(ds)
        """
        if not isinstance(ds, dimension.DimStyle):
            raise TypeError, "Invalid DimStyle for addtion: " + `ds`
        if ds not in self.__dimstyles:
            _col = ds.getValue('DIM_COLOR')
            if _col is not None and _col not in self.__colors:
                self.__colors[_col] = True
            _col = ds.getValue('DIM_PRIMARY_FONT_COLOR')
            if _col is not None and _col not in self.__colors:
                self.__colors[_col] = True
            _col = ds.getValue('DIM_SECONDARY_FONT_COLOR')
            if _col is not None and _col not in self.__colors:
                self.__colors[_col] = True
            _family = ds.getValue('DIM_PRIMARY_FONT_FAMILY')
            if _family is not None and _family not in self.__fonts:
                self.__fonts[_family] = 1
            _family = ds.getValue('DIM_SECONDARY_FONT_FAMILY')
            if _family is not None and _family not in self.__fonts:
                self.__fonts[_family] = 1

    def hasDimStyle(self, ds):
        """Check if a DimStyle already exists within the drawing.

hasDimStyle(ds)
        """
        if not isinstance(ds, dimension.DimStyle):
            raise TypeError, "Invalid DimStyle object: " + `ds`
        return ds in self.__dimstyles

    def getDimStyle(self, name=None, dsdict=None):
        if name is not None:
            for _ds in globals.dimstyles:
                if _ds.getName() == name:
                    return _ds
        elif dsdict is None:
            pass
        return None
                
    def addTextStyle(self, ts):
        """Add a TextStyle to the drawing.

addTextStyle(ts)
        """
        if not isinstance(ts, text.TextStyle):
            raise TypeError, "Invalid TextStyle for addtion: " + str(ts)
        if ts not in self.__textstyles:
            _color = ts.getColor()
            if _color not in self.__colors:
                self.__colors[_color] = True
            _family = ts.getFamily()
            if _family in self.__fonts:
                self.__fonts[_family] = 1

    def hasTextStyle(self, ts):
        """Return whether or not a TextStyle is already in an image.

hasTextStyle(ts)
        """
        if not isinstance(ts, text.TextStyle):
            raise TypeError, "Invalid TextStyle: " + str(ts)
        return ts in self.__textstyles

    def addFont(self, family):
        """Store the usage of a font in the image.

addFont(family)

Invoking this method does not set the current text font to
the value used in this function. That must be done with setOption().
        """
        if not isinstance(family, str):
            raise TypeError, "Invalid font family name: " + `family`
        self.__fonts[family] = 1

    def getUnits(self):
        """Return the currently selected unit.

getUnits()
        """
        return self.__units.getUnit()

    def setUnits(self, unit):
        """Set the basic unit for the image.

setUnits(unit)

The available choices for the units are defined in the units.py file.
        """
        self.__units.setUnit(unit)

    units = property(getUnits, setUnits, None,
                     "Linear dimensional units for the image.")

    def scaleLength(self, l):
        """Convert some distance to a value in millimeters.

scaleLength(l)

The argument "l" should be a float equal or greater than 0.0.
        """
        _l = l
        if not isinstance(_l, float):
            _l = float(l)
        if _l < 0.0:
            raise ValueError, "Invalid scaling length: %g" % _l
        return self.__units.toMillimeters(_l)

    def findPoint(self, x, y, tol=tolerance.TOL):
        """Return a Point object found at the x-y coordinates.

findPoint(self, x, y [,tol])

The function has two required arguments

x: A float representing the x-coordinate
y: A float representing the y-coordinate

The optional argument "tol" gives a distance between the
existing objects and the "x" and "y" arguments. The default
value is 1e-10.

This method returns a tuple of two objects, the first
object is a Point object, and the second object is a
boolean True/False value indicating if the point is an
exisiting point in the active layer or a newly created
point.

If there were no Point objects found within the tolerance
supplied, the Point object in the tuple is 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)
        _test_point = point.Point(_x, _y)
        _new_pt = False
        _active_layer = self.__active_layer
        _pt = _active_layer.find('point', _x, _y, _t)
        if _pt is None:
            _objs = []
            _ptmap = {}
            _layers = [self.__top_layer]
            while len(_layers):
                _layer = _layers.pop()
                if _layer is not _active_layer:
                    _lp = _layer.find('point', _x, _y, _t)
                    if _lp is not None:
                        _pt = _lp.clone()
                        _new_pt = True
                        break
                _stop = False
                for _obj, _map_pt in _layer.mapPoint(_test_point, _t, None):
                    if isinstance(_obj, dimension.Dimension):
                        continue
                    if len(_objs):
                        for _tobj in _objs:
                            _ints = intersections.find_intersections(_tobj, _obj)
                            _count = len(_ints)
                            if _count == 1:
                                _stop = True
                                _x, _y = _ints[0]
                                _pt = point.Point(_x, _y)
                                _new_pt = True
                                break
                            elif _count == 2:
                                _stop = True
                                _tx, _ty = _test_point.getCoords()
                                _x1, _y1 = _ints[0]
                                _d1 = math.hypot((_tx - _x1), (_ty - _y1))
                                _x2, _y2 = _ints[1]
                                _d2 = math.hypot((_tx - _x2), (_ty - _y2))
                                if _d1 < _d2:
                                    _pt = point.Point(_x1, _y1)
                                else:
                                    _pt = point.Point(_x2, _y2)
                                _new_pt = True
                                break
                            else:
                                pass # this should handle _count > 2
                    _ptmap[_obj] = _map_pt
                    _objs.append(_obj)
                if _stop:
                    break
                _layers.extend(_layer.getSublayers())
            if _pt is None: # need to use one of the mapped points ...
                _min_sep = None
                _map_obj = None
                for _obj in _ptmap:
                    _sep = _ptmap[_obj] - _test_point
                    if _min_sep is None or _sep < _min_sep:
                        _map_obj = _obj
                if _map_obj is not None:
                    _pt = _ptmap[_map_obj]
                    _new_pt = True
        return _pt, _new_pt

    def hasPoint(self, x, y, tol=tolerance.TOL, map=True):
        """Return a Point object found at the x-y coordinates.

hasPoint(self, x, y [,tol, map])

The function has two required arguments

x: A float representing the x-coordinate
y: A float representing the y-coordinate

The optional argument "tol" gives a distance between the
existing objects and the "x" and "y" arguments. The default
value is 1e-10.

The map argument is by default True. Passing the
argument as False will skip the attempt to place
an xy coordinate on objects.

The function returns a Point object - either an existing
Point in the currently active Layer, or a new Point based
on the location of a Point object in another layer. The
returned point can be stored in the active Layer.

If there were no Point objects found within the tolerance
supplied, the 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)
        _test_point = point.Point(_x,_y)
        if map is not True and map is not False:
            raise ValueError,  "Invalid map value: " + `map`
        _active_layer = self.__active_layer
        _sp = _active_layer.find('point', _x, _y, _t)
        if _sp is None:
            _layers = [self.__top_layer]
            while (len(_layers)):
                _layer = _layers.pop()
                if _layer is not _active_layer:
                    _lp = _layer.find('point', _x, _y, _t)
                    if _lp is not None:
                        _sp = _lp.clone()
                        break
                _layers.extend(_layer.getSublayers())
        if _sp is None and map:
            _objdict = self.mapPoint(_x, _y, _t)
            _tuplist = []
            if len(_objdict):
                _count = len(_objdict)
                for _layer in _objdict:
                    _tuplist = _tuplist + _objdict[_layer]
                if len(_tuplist) == 1:
                    _sp = _tuplist[0][1]
                else:
                    _obj1 = _tuplist[0][0]
                    _obj2 = _tuplist[1][0]
                    _ints = intersections.find_intersections(_obj1, _obj2)
                    _count = len(_ints)
                    if _count == 0:
                        _sp = _tuplist[0][1] # arbitrary choice ...
                    elif _count == 1:
                        _x, _y = _ints[0]
                        _sp = point.Point(_x, _y)
                    elif _count == 2:
                        _tx, _ty = _test_point.getCoords()
                        _x1, _y1 = _ints[0]
                        _d1 = math.hypot((_tx - _x1), (_ty - _y1))
                        _x2, _y2 = _ints[1]
                        _d2 = math.hypot((_tx - _x2), (_ty - _y2))
                        if _d1 < _d2:
                            _sp = point.Point(_x1, _y1)
                        else:
                            _sp = point.Point(_x2, _y2)
                    else: # need to handle 3 or more intersection points
                        pass
        return _sp

    def mapPoint(self, x, y, tol, count=2):
        """Return a set of Layers with objects found at the (x,y) location

mapPoint(self, x, y, tol[, count])

This method has three required arguments:

x: A float representing the x-coordinate
y: A float representing the y-coordinate
tol: A positive float giving the maximum distance between the
     x and y coordinates and the projected points of the objects

There is a single optional argument:

count: The maximum number of objects to retrieve in any layer. The
       default value of objects is 2.

Setting "count" to either None or a negative value will result
in the maximum number of objects as unlimited.

The function returns a dict object, with each key being
a Layer object where some objects were found, and the
value being a list of some tuples. Read the doc-string
info for the layer::mapPoint() method for details regarding
the tuple(s) in the list.

If any objects in the currently active layer are identified, no
other layers in the drawing will be examined.

If there were no objects found within the tolerance
supplied, the function returns an empty dict.
        """
        _x = x
        if not isinstance(_x, float):
            _x = float(x)
        _y = y
        if not isinstance(_y, float):
            _y = float(y)
        _t = tolerance.toltest(tol)
        _count = count
        if _count is None:
            _count = sys.maxint
        else:
            if not isinstance(_count, int):
                _count = int(count)
            if _count < 0: # What if _count == 0 ???
                _count = sys.maxint
        _tp = point.Point(_x, _y)
        _active_layer = self.__active_layer
        _objdict = {}
        _hits = _active_layer.mapPoint(_tp, _t, _count)
        if len(_hits):
            _objdict[_active_layer] = _hits
        else:
            _layers = [self.__top_layer]
            while len(_layers):
                _layer = _layers.pop()
                if _layer is not _active_layer:
                    _hits = _layer.mapPoint(_tp, _t, _count)
                    if len(_hits):
                        _objdict[_layer] = _hits
                _layers.extend(_layer.getSublayers())
        return _objdict

    def layerModified(self, l, *args):
        _lid = l.getID()
        _data = self.__undo
        _i = self.__action
        if len(_data) == _i:
            _data.insert(_i, (_lid,))
        else:
            _t = _data[_i] + (_lid, )
            _data[_i] = _t

    def printStack(self, undo):
        if undo:
            print "Image undo list:"
            _stack = self.__undo
        else:
            print "Image redo list:"
            _stack = self.__redo
        print "length: %d" % len(_stack)
        for _data in _stack:
            print _data
        
    def canUndo(self):
        return len(self.__undo) > 0

    def canRedo(self):
        return len(self.__redo) > 0
    
    def undo(self):
        # print "Image::undo() ..."
        if len(self.__undo):
            _layers = {}
            _act = list(self.__undo.pop())
            # print _act
            # print "undo length: %d" % len(self.__undo)
            self.__redo.append(_act[:])
            self.__action = len(self.__undo)
            _act.reverse()
            self.ignore('modified')
            try:
                for _lid in _act:
                    _layer = _layers.get(_lid)
                    if _layer is None:
                        _layer = self.getObject(_lid)
                        if _layer is None:
                            raise ValueError, "Layer missing: id=%d" % _lid
                        _layers[_lid] = _layer
                    _layer.undo()
            finally:
                self.receive('modified')

    def redo(self):
        # print "Image::redo() ..."
        if len(self.__redo):
            _layers = {}
            _act = list(self.__redo.pop())
            self.__action = len(self.__undo)
            #
            # wrap all the redo() actions within a
            # startAction()/endAction block - this will
            # ensure that all the 'modified' messages the
            # redo operations generate will be stored in
            # a single tuple in the undo list
            #
            self.startAction()
            try:
                for _lid in _act:
                    _layer = _layers.get(_lid)
                    if _layer is None:
                        _layer = self.getObject(_lid)
                        if _layer is None:
                            raise ValueError, "Layer missing: id=%d" % _lid
                        _layers[_lid] = _layer
                    _layer.redo()
            finally:
                self.endAction()
            
    def addObject(self, obj, l=None):
        """Add an object to the Drawing.

addObject(obj [, l])

There is one required argument:

obj: The thing to be added

There is one optional argument:

l: The layer that will hold the object

By default, the currently active layer holds the object.
        """
        _layer = l
        _check = True
        if _layer is None:
            _layer = self.__active_layer
            _check = False
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid Layer argument: " + `_layer`
        if _check:
            _l = _layer
            _p = _l.getParentLayer()
            while _p is not None:
                _l = _p
                _p = _p.getParentLayer()
            if _l is not self.__top_layer:
                raise ValueError, "Layer not found in drawing: " + `_layer`
            _parent = _layer.getParentLayer()
            if _parent is not None:
                if not _parent.hasSublayers():
                    raise ValueError, "Layer not a sublayer of parent: " + `_layer`
                if _layer not in _parent.getSublayers():
                    raise ValueError, "Layer not a sublayer of parent: " + `_layer`
        _layer.addObject(obj)

    def delObject(self, obj, l=None):
        """Remove an object from the Drawing.

delObject(obj [, l])

There is one required argument:

obj: The thing to be added

There is one optional argument:

l: The layer holding the object.

By default, the currently active layer holds the object.
        """
        _layer = l
        _check = True
        if _layer is None:
            _layer = self.__active_layer
            _check = False
        if not isinstance(_layer, layer.Layer):
            raise TypeError, "Invalid Layer argument: " + `_layer`
        if _check:
            _l = _layer
            _p = _l.getParentLayer()
            while _p is not None:
                _l = _p
                _p = _p.getParentLayer()
            if _l is not self.__top_layer:
                raise ValueError, "Layer not found in drawing: " + `_layer`
            _parent = _layer.getParentLayer()
            if _parent is not None:
                if not _parent.hasSublayers():
                    raise ValueError, "Layer not in parent layer sublayers: " + `_layer`
                if _layer not in _parent.getSublayers():
                    raise ValueError, "Layer not in parent layer sublayers: " + `_layer`
        _layer.delObject(obj)

    def getObject(self, eid):
        """Retrieve an object with a specified ID.

getObject(eid)

Argument eid is an entity ID. If an object with an ID of
that specified is found, the object is returned. Otherwise
this method returns None.
        """
        _layers = [self.__top_layer]
        while len(_layers):
            _layer = _layers.pop()
            if _layer.getID() == eid:
                return _layer
            _obj = _layer.getObject(eid)
            if _obj is not None:
                return _obj
            _layers.extend(_layer.getSublayers())
        return None

    def findLayerWithObj(self, oid):
        """Retrieve the layer containing an object

findLayerWithObj(oid)

Argument oid is the entityID. If no layer is found with
the entity ID this method returns None
        """
        _layers = [self.__top_layer]
        while len(_layers):
            _layer = _layers.pop()
            if _layer.hasObject(oid):
                return _layer
            _layers.extend(_layer.getSublayers())
        return None

    def startAction(self):
        if self.__busy:
            raise ValueError, "Image already in busy state"
        self.__busy = True

    def endAction(self):
        if not self.__busy:
            raise ValueError, "Image not in busy state"
        self.__busy = False
        self.__action = self.__action + 1

    def inAction(self):
        return self.__busy
    
    def getAction(self):
        return self.__action

    action = property(getAction, None, None, "Action value.")

    def findLayerWithObject(self, obj):
        """Find which layer holds a particular entity.

findLayerWithObject(obj)

This method returns the layer that the object is store in.
If the object is not found in any layer this method returns
None.
        """
        _layers = []
        _layers.append(self.__top_layer)
        while len(_layers):
            _layer = _layers.pop(0)
            if obj in _layer:
                return _layer
            _layers.extend(_layer.getSublayers())
        return None

    def selectObject(self, lyr, obj):
        """Store a reference to an object found in a layer.

selectObject(lyr, obj)

The argument "obj" is one of the objects stored in the layer "lyr".
Storing an object with selectObject() is the means by which objects
can be copied or modified.
        """
        if not isinstance(lyr, layer.Layer):
            raise TypeError, "Invalid layer: " + `lyr`
        if obj not in lyr:
            raise ValueError, "Object not found in layer: " + `obj`
        if not self.__selected.has_key(lyr):
            self.__selected[lyr] = []
        _objlist = self.__selected[lyr]
        _flag = True
        for _i in range(len(_objlist)):
            if obj is _objlist[_i]:
                _flag = False
                break
        if _flag:
            _objlist.append(obj)

    def deselectObject(self, lyr, obj):
        """Remove any occurance of an object found in a layer.

unselectObject(lyr, obj)

If the object isn't found as already selected a ValueError is returned.
        """
        if not isinstance(lyr, layer.Layer):
            raise TypeError, "Invalid layer: " + `lyr`
        if not self.__selected.has_key(lyr):
            raise ValueError, "No objects stored from layer: " + `lyr`
        _idx = None
        _objlist = self.__selected[lyr]
        for _i in range(len(_objlist)):
            _sobj = _objlist[_i]
            if _sobj is obj:
                _idx = _i
                break
        if _idx is None:
            raise ValueError, "Invalid object for deselection: " + `obj`
        del _objlist[_idx]
        if len(_objlist) == 0:
            del self.__selected[lyr]

    def getSelectedObjects(self):
        """Return all the currently selected objects.

getSelectedObjects()

Invoking this method releases the objects from being selected.
        """
        _objs = []
        for _layer in self.__selected:
            _objlist = self.__selected[_layer]
            for _obj in _objlist:
                _objs.append((_layer, _obj))
        self.__selected.clear()
        return _objs

    def clearSelectedObjects(self):
        """Empty the list list of selected objects.

clearSelectedObjects()
        """
        self.__selected.clear()

    def hasSelection(self):
        """Return whether or not there are selected objects in the drawing.

hasSelection()
        """
        return len(self.__selected) > 0

    def getExtents(self):
        """Return the coordinates of a window holding the whole drawing

getExtents()

The function will return a tuple of the format:

(xmin, ymin, xmax, ymax)

Each value will be a float.
        """
        _xmin = None
        _ymin = None
        _xmax = None
        _ymax = None
        _set = False
        _layers = [self.__top_layer]
        while (len(_layers)):
            _layer = _layers.pop()
            if _layer.isVisible():
                _set = True
                _xmn, _ymn, _xmx, _ymx = _layer.getBoundary()
                if _xmin is None or _xmn < _xmin:
                    _xmin = _xmn
                if _ymin is None or _ymn < _ymin:
                    _ymin = _ymn
                if _xmax is None or _xmx > _xmax:
                    _xmax = _xmx
                if _ymax is None or _ymx > _ymax:
                    _ymax = _ymx
            _layers.extend(_layer.getSublayers())
        if _set: # make sure the values are different
            if abs(_xmax - _xmin) < 1e-10:
                _xmin = _xmin - 1.0
                _xmax = _xmax + 1.0
            if abs(_ymax - _ymin) < 1e-10:
                _ymin = _ymin - 1.0
                _ymax = _ymax + 1.0
        else:
            _xmin = -1.0
            _ymin = -1.0
            _xmax = 1.0
            _ymax = 1.0
        return (_xmin, _ymin, _xmax, _ymax)

    def getOption(self, key):
        """Return the value of an option set in the drawing.

getOption(key)

Return the value of the option associated with the string "key".
If there is no option found for that key, return None.
        """
        if not isinstance(key, str):
            raise TypeError, "Invalid key: " + `key`
        if key in self.__options:
            _val = self.__options[key]
        elif key in globals.prefs:
            _val = globals.prefs[key]
        else:
            _val = None
        return _val

    def setOption(self, key, value):
        """Set an option in the drawing.

setOption(key, value)

Argument "key" must be a string, and argument "value" can
any type of object. Using the same key twice will result on
the second value overwriting the first.
        """
        #
        # test_option will raise an exception for invalid values ...
        #
        _valid = options.test_option(key, value)
        _gval = None
        _set = False
        _gkey = True
        if key in globals.prefs:
            _gval = globals.prefs[key]
        #
        # check that the new value is different from that stored
        # in the global preferences
        #
        if key == 'UNITS':
            self.setUnits(value)
        elif key == 'DIM_STYLE':
            assert _gval is not None, "Key %s not i globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_FONT_FAMILY':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_FONT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_FONT_WEIGHT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_FONT_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_FONT_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_PRECISION':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_UNITS':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_LEADING_ZERO':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_PRIMARY_TRAILING_DECIMAL':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_FONT_FAMILY':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_FONT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_FONT_WEIGHT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_FONT_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_FONT_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_PRECISION':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_UNITS':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_LEADING_ZERO':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_SECONDARY_TRAILING_DECIMAL':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_OFFSET':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_EXTENSION':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_POSITION':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_ENDPOINT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'DIM_ENDPOINT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'DIM_DUAL_MODE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'RADIAL_DIM_PRIMARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'RADIAL_DIM_PRIMARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'RADIAL_DIM_SECONDARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'RADIAL_DIM_SECONDARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'RADIAL_DIM_DIA_MODE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'ANGULAR_DIM_PRIMARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'ANGULAR_DIM_PRIMARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'ANGULAR_DIM_SECONDARY_PREFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'ANGULAR_DIM_SECONDARY_SUFFIX':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'TEXT_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'FONT_FAMILY':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'FONT_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'FONT_WEIGHT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'FONT_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'FONT_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'CHAMFER_LENGTH':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'FILLET_RADIUS':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'LINE_STYLE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'LINE_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'LINE_TYPE':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'LINE_THICKNESS':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        elif key == 'HIGHLIGHT_POINTS':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'INACTIVE_LAYER_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'BACKGROUND_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'SINGLE_POINT_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'MULTI_POINT_COLOR':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'AUTOSPLIT':
            assert _gval is not None, "Key %s not in globals." % key
            if value != _gval: _set = True
        elif key == 'LEADER_ARROW_SIZE':
            assert _gval is not None, "Key %s not in globals." % key
            if abs(value - _gval) > 1e-10: _set = True
        else: # other or possibly untested option
            _gkey = False
            print "non-global key: %s" % key
            if _valid: _set = True
        #
        # if the new value will be stored in the options dictionary
        # we do more tests on the values of certain keys
        #
        if _set:
            if (key == 'LINE_COLOR' or
                key == 'FONT_COLOR' or
                key == 'BACKGROUND_COLOR' or
                key == 'INACTIVE_LAYER_COLOR' or
                key == 'SINGLE_POINT_COLOR' or
                key == 'MULTI_POINT_COLOR' or
                key == 'DIM_COLOR' or
                key == 'DIM_PRIMARY_FONT_COLOR' or
                key == 'DIM_SECONDARY_FONT_COLOR'):
                if value in globals.colors:
                    _color = globals.colors[value]
                    if _color is not value:
                        print "%s: color duplicated: %s" % (key,  str(_color))
                        self.setOption(key, _color)
                        return
                else:
                    globals.colors[value] = value
                if value not in self.__colors:
                    self.__colors[value] = True
            elif key == 'LINE_STYLE':
                self.setOption('LINE_COLOR', _color)
                self.setOption('LINE_TYPE', value.getLinetype())
                self.setOption('LINE_THICKNESS', value.getThickness())
                if value not in self.__styles:
                    self.__styles.append(value)
            elif key == 'LINE_TYPE':
                if value not in self.__linetypes:
                    self.__linetypes.append(value)
            elif key == 'DIM_STYLE':
                for _opt in value.getOptions():
                    _optval = value.getValue(_opt)
                    self.setOption(_opt, _optval)
                if value not in self.__dimstyles:
                    self.__dimstyles.append(value)
            elif key == 'TEXT_STYLE':
                self.setOption('FONT_COLOR', value.getColor())
                self.setOption('FONT_SIZE', value.getSize())
                self.setOption('FONT_WEIGHT', value.getWeight())
                self.setOption('FONT_STYLE', value.getStyle())
                self.setOption('FONT_FAMILY',  value.getFamily())
            elif (key == 'FONT_FAMILY' or
                  key == 'DIM_PRIMARY_FONT_FAMILY' or
                  key == 'DIM_SECONDARY_FONT_FAMILY'):
                if value not in self.__fonts:
                    self.__fonts[value] = 1
            else: # other or possibly untested option
                pass
            self.__options[key] = value
        else:
            if _gkey and key in self.__options: # use the global value
                del self.__options[key]

    def setFilename(self, fname):
        """Set the filename for this image.

setFilename(fname)

The filename will be where the system will save
the data in this file.
        """
        self.__filename = fname

    def getFilename(self):
        """Return the filename for this image.

getFilename()
        """
        return self.__filename

    filename = property(getFilename, setFilename, None, "Image filename.")

    def sendsMessage(self, m):
        if m in Image.messages:
            return True
        return entity.Entity.sendsMessage(self, m)

#
# provide some default colors, linetypes, and styles
# for an image
#

def add_defaults(image):
    # red = color.Color(255,0,0)
    # image.addColor(red)
    # green = color.Color(0,255,0)
    # image.addColor(green)
    # blue = color.Color(0,0,255)
    # image.addColor(blue)
    # violet = color.Color(255,0,255)
    # image.addColor(violet)
    # yellow = color.Color(255,255,0)
    # image.addColor(yellow)
    # cyan = color.Color(0,255,255)
    # image.addColor(cyan)
    # white = color.Color(255,255,255)
    # image.addColor(white)
    # black = color.Color(0,0,0)
    # image.addColor(black)
    _sstyle = globals.prefs['STANDARD_STYLE']
    _dstyle = globals.prefs['DEFAULT_STYLE']
    _styles = globals.prefs['STYLES']
    _set_style = False
    for _style in _styles:
        _istyle = _style.clone()
        image.addStyle(_istyle)
        _name = _style.getName()
        if _name == _dstyle:
            image.setOption('LINE_STYLE', _istyle)
            _set_style = True
    if not _set_style:
        image.setOption('LINE_STYLE', _sstyle)

    #
    # standard colors
    #
    # _colors = globals.prefs['COLORS']
    # for _color in _colors:
        # image.addColor(_color.clone())
    #
    # standard linetypes
    #
    _linetypes = globals.prefs['LINETYPES']
    for _linetype in _linetypes:
        image.addLinetype(_linetype.clone())

    #
    # standards styles
    #
    # solid = linetype.Linetype('Solid')
    # dash1 = linetype.Linetype('Dash1', [4,1])
    # dash2 = linetype.Linetype('Dash2', [8,2])
    # dash3 = linetype.Linetype('Dash3', [12,2])
    # dash4 = linetype.Linetype('Dash4', [10,2,2,2])
    # dash5 = linetype.Linetype('Dash5', [15,5,5,5])
    # st = style.Style('Solid White Line', solid, white, 1)
    # image.addStyle(st)
    # image.setOption('LINE_STYLE', st)
    # st = style.Style('Solid Black Line', solid, black, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Red Line', dash1, red, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Green Line', dash1, green, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Blue Line', dash1, blue, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Yellow Line', dash2, yellow, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Violet Line', dash2, violet, 1)
    # image.addStyle(st)
    # st = style.Style('Dashed Cyan Line', dash2, cyan, 1)
    # image.addStyle(st)

    _dsopts = {}
    for _opt in dimension.dimstyle_defaults:
        _val = dimension.dimstyle_defaults[_opt]
        if (_opt == 'DIM_COLOR' or
            _opt == 'DIM_PRIMARY_FONT_COLOR' or
            _opt == 'DIM_SECONDARY_FONT_COLOR'):
            _val = _val.clone()
        _dsopts[_opt] = _val
    _ds = dimension.DimStyle('Default DimStyle', _dsopts)
    image.addDimStyle(_ds)

    _dstyle = globals.prefs['DEFAULT_DIMSTYLE']
    _dname = None
    if _dstyle is not None:
        _dname = _dstyle.getName()
    _dimstyles = globals.prefs['DIMSTYLES']
    _set_style = False
    for _dimstyle in _dimstyles:
        image.addDimStyle(_dimstyle)
        _name = _dimstyle.getName()
        if _dname is not None and _name == _dname:
            image.setOption('DIM_STYLE', _dimstyle)
            _set_style = True
    if not _set_style:
        # print "setting DIM_STYLE to default _ds ..."
        image.setOption('DIM_STYLE', _ds)
        for _opt in _ds.getOptions():
            _val = str(_ds.getValue(_opt))
            # print "opt: %s; value: %s" % (_opt, _val)

    _ts = text.TextStyle('default')
    image.addTextStyle(_ts)
    _tstyle = globals.prefs['DEFAULT_TEXTSTYLE']
    _tname = None
    if _tstyle is not None:
        _tname = _tstyle.getName()
    _textstyles = globals.prefs['TEXTSTYLES']
    _set_style = False
    for _textstyle in _textstyles:
        image.addTextStyle(_textstyle)
        _name = _textstyle.getName()
        if _tname is not None and _name == _tname:
            image.setOption('TEXT_STYLE', _textstyle)
            _set_style = True
    if not _set_style:
        image.setOption('TEXT_STYLE', _ts)
    #
    # these will override what the style has set
    #
    # image.setOption('FONT_FAMILY', globals.prefs['FONT_FAMILY'])
    # image.setOption('FONT_SIZE', globals.prefs['FONT_SIZE'])
    # image.setOption('FONT_STYLE', globals.prefs['FONT_STYLE'])
    # image.setOption('FONT_WEIGHT', globals.prefs['FONT_WEIGHT'])
    # _font_color = globals.prefs['FONT_COLOR'].clone()
    # image.setOption('FONT_COLOR', _font_color)
    # image.setOption('CHAMFER_LENGTH', globals.prefs['CHAMFER_LENGTH'])
    # image.setOption('FILLET_RADIUS', globals.prefs['FILLET_RADIUS'])

    image.setUnits(globals.prefs['UNITS'])
    # image.setOption('HIGHLIGHT_POINTS', globals.prefs['HIGHLIGHT_POINTS'])

    # image.setOption('INACTIVE_LAYER_COLOR', globals.prefs['INACTIVE_LAYER_COLOR'])
    # image.setOption('AUTOSPLIT', globals.prefs['AUTOSPLIT'])
    # image.setOption('LEADER_ARROW_SIZE', globals.prefs['LEADER_ARROW_SIZE'])
