PythonCAD-DS1-R37/ 0000755 0001750 0001750 00000000000 11307677001 013153 5 ustar matteo matteo PythonCAD-DS1-R37/PKG-INFO 0000644 0001750 0001750 00000000401 11307677001 014243 0 ustar matteo matteo Metadata-Version: 1.0
Name: PythonCAD
Version: DS1-R37
Summary: CAD built from Python
Home-page: http://www.pythoncad.org/
Author: Art Haas,Matteo Boscolo
Author-email: ahaas@airmail.net,Euro_ii@libero.it
License: GPL
Description: UNKNOWN
Platform: UNKNOWN
PythonCAD-DS1-R37/INSTALL 0000644 0001750 0001750 00000003170 11307666657 014224 0 ustar matteo matteo Installation
============
The installation of PythonCAD is a two-step process. First,
execute the setup.py script
$ python setup.py install
This command will install the files in the "Generic" and
"Interface" directories into the Python library directory.
You may need to be root to do this on your machine.
Next, copy the file "gtkpycad.py" into one of the directories
in your PATH. Commonly this will be "/usr/local/bin", or
"/usr/bin".
At this point you should be able to invoke the gtkpycad.py
file at a prompt:
$ gtkpycad.py
After a few seconds, the application should start.
Work has begun on making PythonCAD offer native language
support. Translation files are in the 'po/' subdirectory.
The '.po' file needs to be converted to a '.mo' file, a
job for the 'msgfmt' program. Once the '.mo' file has
been generated, it should be copied into the appropriate
'locale' directory for your system and the user environment
adjusted to access the correct locale. For the time being
the installation of these files requires much manual work;
as more translations appear it is hoped the installation
of the '.mo' files will become more automated.
Problems
========
If something doesn't work, there are a couple of things to
check. For the sake of a few examples, pretend that the
python installation is in "/usr" and Python-2.2.X is installed,
so the site-packages directory is "/usr/lib/python2.2/site-packages",
and the python binary is "/usr/bin/python". Also pretend that
the "gtkpycad.py" file is copied into "/usr/bin".
Does "/usr/bin/gtkpycad.py" have the execute bits set? If
not, do a "chmod a+x /usr/bin/gtkpycad.py" to set these bits.
PythonCAD-DS1-R37/gtkpycad.py 0000755 0001750 0001750 00000023311 11307666732 015347 0 ustar matteo matteo #!/usr/bin/env python
#
# Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 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
#
#
# main routine to start GTK-based pycad
#
import getopt
import sys
import os
import pygtk
pygtk.require('2.0')
import gtk
import gettext
gettext.install('PythonCAD')
from PythonCAD.Generic import globals
from PythonCAD.Generic import imageio
from PythonCAD.Generic import fileio
from PythonCAD.Generic import selections
from PythonCAD.Generic import preferences
from PythonCAD.Generic import color
from PythonCAD.Generic import linetype
from PythonCAD.Generic import style
from PythonCAD.Generic import segment
from PythonCAD.Generic import circle
from PythonCAD.Generic import arc
from PythonCAD.Generic import leader
from PythonCAD.Generic import polyline
from PythonCAD.Generic import segjoint
from PythonCAD.Generic import conobject
from PythonCAD.Generic import baseobject
from PythonCAD.Generic import graphicobject
from PythonCAD.Generic import dimension
from PythonCAD.Generic import text
from PythonCAD.Generic import units
from PythonCAD.Interface.Gtk import gtkinit
def _initialize_booleans():
globals.prefs['HIGHLIGHT_POINTS'] = True
globals.prefs['AUTOSPLIT'] = False
def _initialize_sizes():
globals.prefs['CHAMFER_LENGTH'] = 1.0
globals.prefs['FILLET_RADIUS'] = 1.0
globals.prefs['FILLET_TWO_TRIM_MODE'] = 'b'
globals.prefs['UNITS'] = units.MILLIMETERS
globals.prefs['LEADER_ARROW_SIZE'] = 1.0
def _initialize_image_colors():
_color = color.get_color(80, 140, 210) # blueish/purpleish
globals.prefs['INACTIVE_LAYER_COLOR'] = _color
_color = color.get_color(0, 0, 0) # black
globals.prefs['BACKGROUND_COLOR'] = _color
_color = color.get_color(255, 255, 0) # yellow
globals.prefs['SINGLE_POINT_COLOR'] = _color
_color = color.get_color(0, 255, 255) # cyan
globals.prefs['MULTI_POINT_COLOR'] = _color
def _initialize_styles():
_style = graphicobject.GraphicObject.getDefaultStyle()
globals.prefs['LINE_STYLE'] = _style
globals.prefs['LINE_COLOR'] = _style.getColor()
globals.prefs['LINE_TYPE'] = _style.getLinetype()
globals.prefs['LINE_THICKNESS'] = _style.getThickness()
#
# set this style as the class default for the "real" drawing entities
#
segment.Segment.setDefaultStyle(_style)
circle.Circle.setDefaultStyle(_style)
arc.Arc.setDefaultStyle(_style)
leader.Leader.setDefaultStyle(_style)
polyline.Polyline.setDefaultStyle(_style)
segjoint.SegJoint.setDefaultStyle(_style)
segjoint.Chamfer.setDefaultStyle(_style)
segjoint.Fillet.setDefaultStyle(_style)
#
# define and set a construction line style
#
_color = color.get_color(0xff, 0, 0) # red
_lt = linetype.Linetype(u'Construction Lines', [2, 2])
_style = style.Style(u'Construction Objects', _lt, _color, 0.0)
conobject.ConstructionObject.setDefaultStyle(_style)
#
# define and add the default text style and use values in the
# text style to define various global key/value pairs
#
_ts = text.TextBlock.getDefaultTextStyle()
globals.prefs['TEXT_STYLE'] = _ts
globals.prefs['FONT_COLOR'] = _ts.getColor()
globals.prefs['FONT_WEIGHT'] = _ts.getWeight()
globals.prefs['FONT_STYLE'] = _ts.getStyle()
globals.prefs['FONT_FAMILY'] = _ts.getFamily()
globals.prefs['TEXT_SIZE'] = _ts.getSize()
globals.prefs['TEXT_ANGLE'] = _ts.getAngle()
globals.prefs['TEXT_ALIGNMENT'] = _ts.getAlignment()
#
# define and add the default dimension style and use the
# values in that style to define various global preference
# key/value pairs
#
_ds = dimension.Dimension.getDefaultDimStyle()
globals.dimstyles.append(_ds)
globals.prefs['DIM_STYLE'] = _ds
for _key in _ds.getOptions():
_value = _ds.getOption(_key)
globals.prefs[_key] = _value
def _initialize_linetypes():
_lt = linetype.Linetype(u'Solid') # solid
globals.linetypes[_lt] = _lt
_lt = linetype.Linetype(u'Dash1', [4, 1]) # dashed line
globals.linetypes[_lt] = _lt
_lt = linetype.Linetype(u'Dash2', [8, 2]) # dashed line
globals.linetypes[_lt] = _lt
_lt = linetype.Linetype(u'Dash3', [12, 2]) # dashed line
globals.linetypes[_lt] = _lt
_lt = linetype.Linetype(u'Dash4', [10, 2, 2, 2]) # dashed line
globals.linetypes[_lt] = _lt
_lt = linetype.Linetype(u'Dash5', [15, 5, 5, 5]) # dashed line
globals.linetypes[_lt] = _lt
def _initialize_colors():
_color = color.Color(255, 0, 0) # red
globals.colors[_color] = _color
_color = color.Color(0, 255, 0) # green
globals.colors[_color] = _color
_color = color.Color(0, 0, 255) # blue
globals.colors[_color] = _color
_color = color.Color(255, 0, 255) # violet
globals.colors[_color] = _color
_color = color.Color(255, 255, 0) # yellow
globals.colors[_color] = _color
_color = color.Color(0, 255, 255) # cyan
globals.colors[_color] = _color
_color = color.Color(255, 255, 255) # white
globals.colors[_color] = _color
_color = color.Color(0, 0, 0) # black
globals.colors[_color] = _color
def _inizialize_snap():
"""
Inizialize Global Snap Erray
"""
globals.snapOption={'mid':True,'point':True,'end':True,'intersection':True,
'origin':False,'perpendicular':False,'tangent':False,'center':True}
def _initialize_globals():
#
# define globals
#
globals.imagelist = []
globals.prefs = {}
globals.colors = baseobject.TypedDict(color.Color, color.Color)
globals.linetypes = baseobject.TypedDict(linetype.Linetype, linetype.Linetype)
globals.dimstyles = []
globals.selectobj = selections.Selection()
_initialize_colors()
_initialize_linetypes()
_initialize_styles()
_initialize_image_colors()
_initialize_sizes()
_initialize_booleans()
_inizialize_snap()
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "hv", ["help", "version"])
except getopt.GetoptError, e:
sys.stderr.write("Error: %s\n" % e)
sys.exit(1)
for o, a in opts:
if o in ("-h", "--help"):
sys.stdout.write("No help yet! Sorry ...\n")
sys.exit()
if o in ("-v", "--version"):
sys.stdout.write("PythonCAD - DS1 - Release 37 Alfa \n")
sys.exit()
#
# add graphic methods to classes
#
gtkinit.add_graphic_methods()
#
# load up global and user preferences
#
_initialize_globals()
preferences.initialize_prefs()
preferences.load_global_prefs()
_user_flag = globals.prefs['USER_PREFS']
if _user_flag:
preferences.load_user_prefs()
#
# open any drawings passed as arguments. This code needs
# to be much more robust ...
#
assert 'BACKGROUND_COLOR' in globals.prefs, "BACKGROUND_COLOR missing"
_background = globals.prefs['BACKGROUND_COLOR']
from PythonCAD.Interface.Gtk.gtkimage import GTKImage
from PythonCAD.Generic.image import Image, ImageLog
for _arg in args:
if os.path.exists(_arg):
sys.stdout.write("Opening '%s'\n" % _arg)
try:
_imfile = fileio.CompFile(_arg, "r")
except IOError, _e:
sys.stderr.write("Can't open '%s'! %s" % (_arg, _e))
continue
_image = Image()
try:
try:
imageio.load_image(_image, _imfile)
finally:
_imfile.close()
_log = ImageLog(_image)
_image.setLog(_log)
_fname = os.path.realpath(_arg)
_image.setFilename(_fname)
_gtkimage = GTKImage(_image)
_window = _gtkimage.getWindow()
_window.set_title(os.path.basename(_fname))
globals.imagelist.append(_image)
if _image.getOption('BACKGROUND_COLOR') == _background:
_image.setOption('BACKGROUND_COLOR', _background)
_window.show_all()
_gtkimage.fitImage()
except StandardError, _e:
sys.stderr.write("Failed loading '%s'! %s" % (_arg, _e))
else:
sys.stderr.write("Can't find file '%s' - Skipping ...\n" % _arg)
if not len(globals.imagelist):
_image = Image()
_gtkimage = GTKImage(_image)
_log = ImageLog(_image)
_image.setLog(_log)
globals.imagelist.append(_image)
_image.setOption('BACKGROUND_COLOR', _background)
_gtkimage.window.show_all()
gtk.main()
if __name__ == '__main__':
_major, _minor, _micro = gtk.pygtk_version
if ((_major < 2) and
(_minor < 100) and #
(_micro < 16)):
print """
The PyGTK version you are using needs to be upgraded to
a newer version. Changes in the PyGTK code have required
the addition of some compatibility code in PythonCAD,
but these changes are temporary and will be removed in
a future PythonCAD release. Please upgrade your PyGTK
module to version 1.99.16 (at least), or retrieve and
build the PyGTK module from the CVS archive.
"""
main()
PythonCAD-DS1-R37/gtkpycad.png 0000644 0001750 0001750 00000001100 11307666732 015470 0 ustar matteo matteo PNG
IHDR 0 0 W sRGB bKGD pHYs ~ tIMEp*tO IDATh혱N0ҔcPG5Xydx@1;p!4?K;˝ D"H$j u+Vb}UNHJXXg$#ªdζjɼם,j">,|%ȷ甸~&/b(qswOR , "(UI];vzݦEI1QxD:K$3+A2U}\Jh|g84+jmjϑ| UuN<9; h .CeV0Ok+
ϠbEe\2Nq8]@g-GdI[EÌ6yl]Jmm/p9D.tNϱs'F,Mayfu.+YwOt
H$Oϓ˫xdO IENDB` PythonCAD-DS1-R37/README 0000644 0001750 0001750 00000007243 11307666657 014060 0 ustar matteo matteo Introduction
============
PythonCAD is an open-source CAD package built designed
around Python. As such, it aims to be a fully scriptable
and customizable CAD program. It is initially designed
to run under Linux, one of the BSD flavors, or Unix.
Using an established, powerful, and expressive language
like Python as the core of the program saves an enormous
amount of work for developers and, for users who are
already familiar with Python, you don't have to try and
learn a new language if you want to extend or customize
the code. If you've never written Python code before,
there are extensive resources available for you. A good
place to start is at the Python home page ...
http://www.python.org
Goals
=====
The primary design goal is to provide a good CAD package.
The open-source world has been moving steadily from providing
superior tools for proprietary systems (i.e. GCC), to
world-class operating systems (i.e. Linux), and has advanced
remarkably in providing complete desktop environments (GNOME
and KDE). It is hoped that PythonCAD will grow to be an
excellent addition to the desktop programs now available
for users of open-source software.
A design goal with the program code is to keep the user
interface completely separated from the back end or generic
code. In doing so, it should be possible for developers to
write code porting PythonCAD to their chosen interface with
less work. The initial release is written using GTK-2.0 as the
interface (utilizing the PyGTK library). The addition of
a front end utilizing the Py-Objc bindings on Mac OS X and
Cocoa demonstrates that this approach of separating the
interface from the core program is a viable approach of
application design. It is hoped that interfaces for GNOME,
QT, KDE, and other packages will eventually be added to
PythonCAD.
A second code design goal is to write a powerful graphical
program without writing much, if any, C or C++ code. The Python
language frees the programmer from many of the difficulties
that are associated with C (memory allocation, buffer handling,
etc.) or C++ code (i.e. compiler and platform issues). No
language is perfect, but it is hoped that PythonCAD can
demonstrate that choosing Python as the primary language
for development provides good performance, ease of maintenance,
and a fun language to work with.
Requirements
============
Python: Version 2.2 at a minimum, with the zlib module. At the
time of the thirtieth release the final 2.2 based release is
2.2.3, the (final?) 2.3 release is 2.3.5, and the latest 2.4
release is 2.4.2. PythonCAD should run without problem in any
of the releases. There are as yet no plans to raise the minimum
Python release to the 2.3 series.
PyGTK-2.0: Version 1.99.16 at least, with version 2.0 recommended.
The PyGTK developers have released PyGTK-2.6, which has support
for more features in the latest GTK code. The PyGTK-2.4 release
as well as the PyGTK-2.2 release work also, but these releases
are tied to older GTK releases and are consequently in maintenance
mode (at best).
GTK and its dependencies: It is strongly recommended
to use the latest release of GTK, Pango, ATK, and Glib. At the
thirtieth PythonCAD release, GTK is at version 2.8.16, Pango
is version 1.12.0, ATK is release 1.11.3, and Glib is release 2.10.1.
The fifteenth release of PythonCAD offered a native Cocoa interface
utilizing the Py-Objc bridge for Mac OS X users. Unfortunately
the developer maintaining the Cocoa interface is no longer able to
do so, and current PythonCAD releases do not work with the Py-Objc
bindings. Developers wishing to pick up this code and maintain
it would be welcomed.
License
=======
PythonCAD is distributed under the terms of the
GNU General Public License (GPL).
PythonCAD-DS1-R37/pythoncad.xsd 0000644 0001750 0001750 00000035415 11307666657 015713 0 ustar matteo matteo
Schema for PythonCAD drawing files
Author: Art Haas(ahaas@airmail.net)
PythonCAD-DS1-R37/pythoncad.desktop 0000644 0001750 0001750 00000000257 11307666732 016554 0 ustar matteo matteo [Desktop Entry]
Name=PyCAD
Comment=PythonCAD
Icon=gtkpycad
Exec=pythoncad
Terminal=false
Type=Application
X-Desktop-File-Install-Version=0.3
Categories=Office;X-Red-Hat-Base;
PythonCAD-DS1-R37/NEWS 0000644 0001750 0001750 00000025026 11307674556 013673 0 ustar matteo matteo NEWS
====
Release DS1-R37, Sep 22, 2009:
* New Mantainer Matteo Boscolo
* New Repository in www.Sourceforge.net/projects/pythoncad
* New Pan & Dynamic Zoom(Need to improve Performance ->R38)
* New Snap System (With One shot snap :point/tangent/perpendicular/midpoint/endpoint)
* New Dynamic Cursor shape changing with snap
* New Fillet Two lines.
* Fix wrong positions in copy&paste Command
* New Abaut Dialog
* Bug fixes and code improvements
Release DS1-R36, May 12, 2007:
* Windows preferences saved to "env['APPDATA']/PythonCAD" directory
* Bug fixes and code improvements
Release DS1-R35, December 19, 2006:
* Global preferences now set via 'Edit'->'Preferences' menu, and
the values are saved to $HOME/.pythoncad/prefs.py file.
* Image preferences now adjustable via 'Draw'->'Set' menu commands
* Bug fixes and code improvments
Release DS1-R34, August 3, 2006:
* Additional display speedups and redraw fixes
* Entities can now be rotated around arbitrary points
* Cairo drawing routines used for entity drawing if available
* Bug fixes and code improvements
Release DS1-R33, July 7, 2006:
* Inclusion of 'gettext' module for Native Language Support
* Reworked display code greatly improving interface responsiveness
* Interface code now relies solely on messaging system for interaction
with core interface-neutral code
* Spanish translation provided by Miguel Angel Barcena Rodriguez
* Bug fixes and code improvements
Release DS1-R32, May 25, 2006:
* Fix autosplitting code to not rely on initial setting in preferences
file and not disable autosplitting on a layer after first execution
where global AUTOSPLIT is False
* Fix typo in new split code
* Bug fixes
Release DS1-R31, May 19, 2006:
* Default style values for classes now settable at runtime
* Entity splitting code reworked
* Automatic entity splitting at newly added point now available
* Bug fixes and code improvements
Release DS1-R30, March 21, 2006:
* Stop using weakref module in Subpart class
* Rework again code for transferring entities between layers
* Bug fixes and code improvements
Release DS1-R29, March 3, 2006:
* Simplified Dimension __init__() methods
* Reworked entity deletion and transfer code
* RadialDimension toggling of diameter display now available from menu
* AngularDimension inversion now availabe from menu
* Bug fixes and code improvements
Release DS1-R28, February 2, 2006:
* Reworked entity modification code allows for both 'select->act' and
'act->select' modes of operation.
* Reworked entity movement code.
* Attributes of Dimension DimString entities can be adjusted individually,
plus the missing ability to adjust their color has been added.
* Warning cleanup for running PythonCAD under recent PyGTK releases.
* Bug fixes and code improvements
Release DS1-R27, December 6, 2005:
* Selecting an entity will cause it to be drawn in a special color.
* Deselecting a selected entity action added to 'Edit' menu.
* Bug fixes and code improvements.
Release DS1-R26, October 21, 2005:
* Horizontal and Vertical stretch now accept keyboard input to define
the stretch distance
* Dual x/y move operation accepts keyboard input to define distances
* Dual x/y stretch operation added
* PostScript output adjustments improving conformance to Adobe standards
* Quadtree reworking to permit storage of equivalent entities
* Menus have added mnemonics to permit menu selection via keyboard
* Bug fixes and code improvements
Release DS1-R25, May 26, 2005:
* Fix several compatibility issues for running on older PyGTK releases
* Clean up GTK event handling code to better match GTK expectations
* Bug fixes and code improvements
Release DS1-R24, April 29, 2005:
* Entity drawing improvements via draw()/erase() methods
* Use of gtk.Action and gtk.ActionGroup classes for building menus
* Bug fixes and code improvements
Release DS1-R23, March 18, 2005:
* Improve scripting and entry box evaluation
* Replace deprecated values from PyGTK
* Bug fixes and code improvements
Release DS1-R22, January 26, 2005:
* Use new gtk.ComboBox and gtk.ColorDialog widgets if available.
* Add missing ability to paste TextBlock objects
* Bug fixes and code improvements
Release DS1-R21, January 11, 2005:
* File saving and restoration of locked and visibility status
* Undo/Redo code improvements
* Bug fixes and code improvements
Release DS1-R20, December 21, 2004:
* Numerous Undo/Redo improvements
* Simplified and refined file storage code
* Bug fixes and code improvements
Release DS1-R19, November 13, 2004:
* Fix file-save bug for drawings with text entities.
* Add 'showpage' to PostScript output.
Release DS1-R18, November 12, 2004:
* Dimension printing improvements
* Undo/Redo data storage improvements
* Deleted entity re-creation improvements
* Bug fixes and code improvements
* RPM packaging contributions from D. Scott Barninger
Release DS1-R17, October 3, 2004:
* Printing!!!
* Significant improvements in modifying entities
* Undo/Redo improvements
* Greatly improved text support
* Significant code improvements in dimension and text code
* Miscellaneous bug fixes and code improvements
Release DS1-R16, June 16, 2004:
* Fixes for Cocoa interface
* Bug fix in SegJoints for Chamfers and Fillets
Release DS1-R15, June 15, 2004:
* Added Cocoa-based front end
* Undo/Redo improvements
* Layer addition and deletion bug fixes
* Miscellaneous bug fixes
Release DS1-R14, May 26, 2004:
* Undo/Redo improvements
* Fix file save bug regression
* Fix broken handling of drawing tangent circles
* Fix quadtree errors for angled construction lines
* Miscelleanous bug fixes and code improvements
Release DS1-R13, April 28, 2004:
* Undo/Redo added
* Many deprecated methods removed
* Drawings are now stored with the background color and inactive layer color
* Point colors can be adjusted
* Bug fixes and code improvements
Release DS1-R12, February 24, 2004:
* Subpart classes now store weak references to objects
* xrange() -> range() conversion
* Many deprecated methods removed
* Conversion of most entities to a new message-sending design
similar to that of QT's signals/slots
* New class hierarchy allows for entites to be locked and hidden
* Quadtrees used for storing most entities in a drawing.
* Bug fixes and code improvements.
Release DS1-R11, December 30, 2003:
* More Python 2.3 fixes
* Reworked file saving to avoid using mutable objects as dictionary keys
* Major improvements in with transferring objects between layers
* Bug fixes and code improvments
Release DS1-R10, October 14, 2003:
* Python 2.3 fixes
* Entity clipping changes
* DWG reading code added - no reading of DWG files yet
* Adding diameter display option for radial dimensions
* Bug fixes and code improvemnts
Release DS1-R9, July 29, 2003:
* Rework internal option handling
* Rework internal storage of colors, linetypes, linestyles
* Tangent calculation fixes
* Intersection fixes when testing for points
* Fix improper user of mutable variables as hash keys.
* Bug fixes and code improvements
Release DS1-R8, June 24, 2003:
* Intersection code changed to return intersection points as tuples.
* Leader line arrow size and dimension endpoint size now settable
through preference dialogs and preference file
* Saving to existing files now shows a dialog to allow the operation
to be cancelled.
* Polygon drawing tool added.
* Unified preferences dialog box and increased preference setting
options and abilities.
* Begin the rework of drawing options internal handling.
* Bug fixes and code improvements
Release DS1-R7, June 3, 2003:
* Tangent Construction Circle creation:
- Tangent to a single construction line or construction circle
- Tangent to two construction lines or a construction line and
construction circle
* Tangent construction line creation between two construction circles
* Parallel construction line creation simplified
* First iteration of a command-line mode for working in a drawing
* File format changes to make the files easier to understand
* Large code cleanup by moving interface-neutral code to the "Generic"
subdirectory
* Many new methods added to drawing entities (i.e. layer.bindObject())
* Reworked object splitting code - polylines can now be split
* Assorted bug fixes and code improvements
Release DS1-R6, May 4, 2003:
* Text can now be stored in a drawing
* New Polyline entity available - this is essentially a set of
connected Segment elements.
* Mirroring objects around a construction line is now available.
* Interface neutral code moved from Interface/Gtk to Generic. More
of this should be done in upcoming releases.
* Internal reworking of Tool objects, and the creation/modification
of entities from the UI. The Tool changes should make the code
clearer and simpler to write, as well as move more code from the
interface specific directory to the generic directory.
* Assorted bug fixes and code improvements
Release DS1-R5, March 28, 2003:
* The reading of a global and user preferences file is implemented
* Many changes in anticipation of hatching - hatching itself is
still not available though
* Several new methods added for searching for objects at a specific
location and of a specific size.
* Dimension endpoint markers now displayed
* Added leader lines
* Filenames are now saved with a '.gz' to indicate they are gzipped
* Added adjustable sizes to dimension end points
* Assorted bug fixes and code improvements
Release DS1-R4, February 24, 2003:
* Split many Layer routines into smaller, private methods
* Bugs found and fixed in Layer due to method splitting metioned above
* Big improvements in drawing dimensions
* Linear Dimensioning added
* Angular Dimensioning added
* Saved files now only contain used colors, linetypes, styles
* Interactive feedback when creating dimensions and arcs
* Assorted bug fixes and code improvements
Release DS1-R3, January 30, 2003:
* Added drawing tangent and perpendicular construction lines
* Added splitting of segments, circles, and arcs
* Line thickness is drawn for "real" entities
* More code modified to current standards
* Added more doc strings
* Rewrote most of the intersection calculation code
* Bug fixes and code improvements
Release DS1-R2, January 11, 2003:
* Add layer deletion and clearing.
* Add setting current entity attributes from "Draw" menu.
* Fix changing attributes from "Modify" menu.
* Don't write empty placeholder tags in files.
* Many doc strings added.
* Modify a few routines to adhere to the current code standards.
* Add the ability to transfer objects between layers.
* Add a web page for keeping track of needed development features,
enhancements, and wish list ideas.
December 18, 2002:
The first release! Basic drawing functionality works, rudimentary
editing exists, and that's about it.
PythonCAD-DS1-R37/COPYING 0000644 0001750 0001750 00000043131 11307666657 014227 0 ustar matteo matteo GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program 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.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.
PythonCAD-DS1-R37/Mac_OS_X_Read_Me.txt 0000644 0001750 0001750 00000001424 11307666657 016700 0 ustar matteo matteo To run the OS X Native front-end as a double-clickable .app:
1) Download and install the Python-Objective C bridge.
http://pyobjc.sf.net/
2) Open a terminal window (in Applications->Utilities->Terminal)
3) Change to the directory where this readme file is located
(ie, if it's on your desktop in a "PythonCad" folder, type
'cd ~/Desktop/PythonCad' in the Terminal.
4) Type "python buildapp.py --semi-standalone build" in the terminal window.
5) The PythonCad.app will be located in the newly created "build" directory.
Drag it to wherever you usually keep your applications.
I make no guarantee this will work on OS X 10.2. It might, it
might not. If you can't get it to work, send an e-mail. If
it doesn't work but you figure out how to fix it, send an-email.
Enjoy.
PythonCAD-DS1-R37/setup.py 0000644 0001750 0001750 00000001222 11307676756 014702 0 ustar matteo matteo #!/usr/bin/env python
#
# Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 Art Haas
# Copyright (c) 2009 Matteo Boscolo
#
# Install pythoncad using the distutils method
#
from distutils.core import setup
setup(name="PythonCAD",
version="DS1-R37",
description="CAD built from Python",
author="Art Haas,Matteo Boscolo",
author_email="ahaas@airmail.net,Euro_ii@libero.it",
url="http://www.pythoncad.org/",
license="GPL",
packages=['PythonCAD',
'PythonCAD/Generic',
'PythonCAD/Interface',
'PythonCAD/Interface/Cocoa',
'PythonCAD/Interface/Gtk'],
)
PythonCAD-DS1-R37/buildapp.py 0000644 0001750 0001750 00000001366 11307666657 015352 0 ustar matteo matteo from bundlebuilder import buildapp
from plistlib import Plist, Dict
plist = Plist(
CFBundleDocumentTypes = [
Dict(
CFBundleTypeExtensions = ["xml", "xml.gz", "*"],
CFBundleTypeName = "XML File",
CFBundleTypeRole = "Editor",
NSDocumentClass = "ImageDocument",
),
Dict(
CFBundleTypeExtensions = ["dwg"],
CFBundleTypeName = "DWG File",
CFBundleTypeRole = "Viewer",
NSDocumentClass = "ImageDocument",
),
]
)
buildapp(
mainprogram = "PythonCad.py",
resources = ["PythonCAD/Interface/Cocoa/MainMenu.nib", "PythonCAD/Interface/Cocoa/ImageDocument.nib", "PythonCAD", "prefs.py"],
nibname = "MainMenu",
plist = plist,
)
PythonCAD-DS1-R37/TODO 0000644 0001750 0001750 00000003436 11307666657 013670 0 ustar matteo matteo Things to add to PythonCAD, shortcomings to address, feature
requests, and reminders can go in this file.
Development:
* Replace GTKImage class with ImageView/ImageWindow classes.
* Write the DWG/DXF->PythonCAD data conversion routines to
utilize the DWG/DXF reading code so that files in those
formats can be loaded within PythonCAD.
* Enhance messaging system error handling - a tough problem
currently "solved" by a try/except block that merely prints
out the Exception
* Consolidate various routines in the Image and Layer classes
used for searching and testing entity existence.
* Utilize the Entity parent/child relationship info in the
Interface code more - a getParent() call will specify the
Layer an entity is stored in, which could replace various
find-and-test queries currently performed.
* Rewrite entity moving routines to utilize the move() methods
on the entities when possible. Also re-examine the issue
of moving the users of a Point entity (i.e. if the center point
of a circle is selected and moved, but the circle itself was
not selected, should the circle be moved or not?) [DONE]
* Make use of scaling - provide some sort of interface for
adjusting the scale, use the scale value when calculating
dimensions, etc.
* Make the selection/modifications routines consistent with regard
to the order of entity selection and operation - either select
entities before executing an operation or select an operation
to perform and then select entities on which to apply the
action. [DONE, mostly]
* Allow for the user preferences to be stored when the 'Preferences'
dialog is adjusted. The current behavior regarding handling of the
user preferences is not consistent with most other applications.
Possibly split the preferences up to be those applicable to all
Images and then an per-Image dialog?
PythonCAD-DS1-R37/PythonCAD/ 0000755 0001750 0001750 00000000000 11307677001 014744 5 ustar matteo matteo PythonCAD-DS1-R37/PythonCAD/Interface/ 0000755 0001750 0001750 00000000000 11307677001 016644 5 ustar matteo matteo PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/ 0000755 0001750 0001750 00000000000 11307677001 017371 5 ustar matteo matteo PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkedit.py 0000644 0001750 0001750 00000043560 11307666732 021417 0 ustar matteo matteo #
# Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 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
#
#
# handle cut, copy, paste, selections, etc
#
import pygtk
pygtk.require('2.0')
import gtk
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.cline import CLine
from PythonCAD.Generic.ccircle import CCircle
from PythonCAD.Generic.dimension import LinearDimension
from PythonCAD.Generic.dimension import HorizontalDimension
from PythonCAD.Generic.dimension import VerticalDimension
from PythonCAD.Generic.dimension import RadialDimension
from PythonCAD.Generic.dimension import AngularDimension
from PythonCAD.Generic.dimension import DimString
from PythonCAD.Generic import text
import PythonCAD.Generic.globals
def select_region_end_cb(gtkimage, widget, event, tool):
# print "called select_region_end_callback()"
_image = gtkimage.getImage()
_x2, _y2 = _image.getCurrentPoint()
_y1 = tool.popObject()
_x1 = tool.popObject()
_xmin = min(_x1, _x2)
_xmax = max(_x1, _x2)
_ymin = min(_y1, _y2)
_ymax = max(_y1, _y2)
tool.delHandler("motion_notify")
_active_layer = _image.getActiveLayer()
_objs = _active_layer.objsInRegion(_xmin, _ymin, _xmax, _ymax)
if len(_objs):
_image.sendMessage('group_action_started')
try:
for _obj in _objs:
_image.selectObject(_obj)
finally:
_image.sendMessage('group_action_ended')
gtkimage.setPrompt(_('Click on the items you want to select.'))
select_mode_init(gtkimage)
def select_motion_notify(gtkimage, widget, event, tool):
_tx, _ty = tool.getLocation()
_px, _py = gtkimage.coordToPixTransform(_tx, _ty)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_xmin = min(_xc, _px)
_ymin = min(_yc, _py)
_rw = abs(_xc - _px)
_rh = abs(_yc - _py)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _rw, _rh)
tool.setCurrentPoint(_x, _y)
_xmin = min(_x, _px)
_ymin = min(_y, _py)
_rw = abs(_x - _px)
_rh = abs(_y - _py)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _rw, _rh)
return True
def select_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
# print "x: %g; y: %g" % (_x, _y)
_active_layer = _image.getActiveLayer()
_pts = _active_layer.find('point', _x, _y, _tol)
if len(_pts) > 0:
_image.sendMessage('group_action_started')
try:
for _pt in _pts:
_image.selectObject(_pt)
finally:
_image.sendMessage('group_action_ended')
else:
_objs = []
for _tb in _active_layer.getLayerEntities('text'):
# print "testing tb: " + `_tb`
_tx, _ty = _tb.getLocation()
# print "tx: %g; ty: %g" % (_tx, _ty)
_bounds = _tb.getBounds()
if _bounds is not None:
# print "has bounds ..."
_w, _h = _bounds
_align = _tb.getAlignment()
if _align == text.TextStyle.ALIGN_LEFT:
_txmin = _tx
_txmax = _tx + _w
elif _align == text.TextStyle.ALIGN_CENTER:
_off = _w/2.0
_txmin = _tx - _off
_txmax = _tx + _off
elif _align == text.TextStyle.ALIGN_RIGHT:
_txmin = _tx - _w
_txmax = _tx
else:
raise ValueError, "Unexpected alignment: %d" % _align
_tymin = _ty - _h
_tymax = _ty
# print "txmin: %g" % _txmin
# print "tymin: %g" % _tymin
# print "txmax: %g" % _txmax
# print "tymax: %g" % _tymax
if _txmin < _x < _txmax and _tymin < _y < _tymax:
_objs.append(_tb)
for _obj, _pt in _active_layer.mapPoint((_x, _y), _tol):
_objs.append(_obj)
if len(_objs):
_image.sendMessage('group_action_started')
try:
for _obj in _objs:
_image.selectObject(_obj)
finally:
_image.sendMessage('group_action_ended')
else:
# print "no objects ..."
gtkimage.setPrompt(_('Click on another point to select the region.'))
gc = gtkimage.getGC()
gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
gc.set_function(gtk.gdk.INVERT)
tool.setLocation(_x, _y)
tool.pushObject(_x)
tool.pushObject(_y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", select_region_end_cb)
def select_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the items you want to select.'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", select_button_press_cb)
def deselect_region_end_cb(gtkimage, widget, event, tool):
# print "called deselect_region_end_callback()"
_image = gtkimage.getImage()
_x2, _y2 = _image.getCurrentPoint()
_y1 = tool.popObject()
_x1 = tool.popObject()
_xmin = min(_x1, _x2)
_xmax = max(_x1, _x2)
_ymin = min(_y1, _y2)
_ymax = max(_y1, _y2)
tool.delHandler("motion_notify")
_active_layer = _image.getActiveLayer()
_objs = _active_layer.objsInRegion(_xmin, _ymin, _xmax, _ymax)
if len(_objs):
_sobjs = {}
for _obj in _image.getSelectedObjects(False):
if _obj.getParent() is _active_layer:
_sobjs[id(_obj)] = True
_image.sendMessage('group_action_started')
try:
for _obj in _objs:
if id(_obj) in _sobjs:
_image.deselectObject(_obj)
finally:
_image.sendMessage('group_action_ended')
gtkimage.setPrompt(_('Click on the items you want to deselect.'))
deselect_mode_init(gtkimage)
def deselect_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
# print "x: %g; y: %g" % (_x, _y)
_active_layer = _image.getActiveLayer()
_objs = []
for _obj in _image.getSelectedObjects(False):
if _obj.getParent() is _active_layer:
if isinstance(_obj, Point):
if abs(_obj.x - _x) < _tol and abs(_obj.y - _y) < _tol:
_objs.append(_obj)
elif isinstance(_obj, text.TextBlock):
_tx, _ty = _obj.getLocation()
_bounds = _obj.getBounds()
if _bounds is not None:
_w, _h = _bounds
_align = _obj.getAlignment()
if _align == text.TextStyle.ALIGN_LEFT:
_txmin = _tx
_txmax = _tx + _w
elif _align == text.TextStyle.ALIGN_CENTER:
_off = _w/2.0
_txmin = _tx - _off
_txmax = _tx + _off
elif _align == text.TextStyle.ALIGN_RIGHT:
_txmin = _tx - _w
_txmax = _tx
else:
raise ValueError, "Unexpected alignment: %d" % _align
_tymin = _ty - _h
_tymax = _ty
if _txmin < _x < _txmax and _tymin < _y < _tymax:
_objs.append(_obj)
elif _obj.mapCoords(_x, _y, _tol) is not None:
_objs.append(_obj)
else:
pass
if len(_objs):
_image.sendMessage('group_action_started')
try:
for _obj in _objs:
_image.deselectObject(_obj)
finally:
_image.sendMessage('group_action_ended')
else:
gtkimage.setPrompt(_('Click on another point to select the region.'))
gc = gtkimage.getGC()
gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
gc.set_function(gtk.gdk.INVERT)
tool.setLocation(_x, _y)
tool.pushObject(_x)
tool.pushObject(_y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", deselect_region_end_cb)
def deselect_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the items you want to deselect.'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", deselect_button_press_cb)
def paste_button_press_cb(gtkimage, widget, event, tool):
# print "called paste_button_press_cb()"
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
# print "x: %g; y: %g" % (_x, _y)
_active_layer = _image.getActiveLayer()
_objs = PythonCAD.Generic.globals.selectobj.getObjects()
_objmap = {}
_image.startAction()
try:
_midx, _midy = determine_center(_objs)
_dx, _dy = _x - _midx, _y - _midy
for _obj in _objs:
if isinstance(_obj, Point):
if not _objmap.has_key('point'):
_objmap['point'] = {}
_pt = Point(_obj.getx() + _dx, _obj.gety() + _dy)
_ept = _active_layer.findObject(_pt)
if _ept is None:
_active_layer.addObject(_pt)
_objmap['point'][_obj] = _pt
else:
_objmap['point'][_obj] = _ept
elif isinstance(_obj, Segment):
if not _objmap.has_key('segment'):
_objmap['segment'] = {}
_cseg = _obj.clone()
_cseg.move(_dx, _dy)
_eseg = _active_layer.findObject(_cseg)
if _eseg is None:
_p1, _p2 = _cseg.getEndpoints()
_ep = _active_layer.findObject(_p1)
if _ep is None:
_active_layer.addObject(_p1)
else:
_cseg.setP1(_ep)
_ep = _active_layer.findObject(_p2)
if _ep is None:
_active_layer.addObject(_p2)
else:
_cseg.setP2(_ep)
_active_layer.addObject(_cseg)
else:
_objmap['segment'][_obj] = _eseg
elif isinstance(_obj, (Circle, Arc, CCircle)):
_cc = _obj.clone()
_cc.move(_dx, _dy)
_ec = _active_layer.findObject(_cc)
if _ec is None:
_cp = _cc.getCenter()
_ep = _active_layer.findObject(_cp)
if _ep is None:
_active_layer.addObject(_cp)
else:
_cc.setLocation(_ep)
_active_layer.addObject(_cc)
elif isinstance(_obj, (HCLine, VCLine, ACLine)):
_ccl = _obj.clone()
_ccl.move(_dx, _dy)
_ecl = _active_layer.findObject(_ccl)
if _ecl is None:
_lp = _ccl.getLocation()
_ep = _active_layer.findObject(_lp)
if _ep is None:
_active_layer.addObject(_lp)
else:
_ccl.setLocation(_ep)
_active_layer.addObject(_ccl)
elif isinstance(_obj, CLine):
_ccl = _obj.clone()
_ccl.move(_dx, _dy)
_ecl = _active_layer.findObject(_ccl)
if _ecl is None:
_p1, _p2 = _ccl.getKeypoints()
_ep = _active_layer.findObject(_p1)
if _ep is None:
_active_layer.addObject(_p1)
else:
_ccl.setP1(_ep)
_ep = _active_layer.findObject(_p2)
if _ep is None:
_active_layer.addObject(_p2)
else:
_ccl.setP2(_ep)
_active_layer.addObject(_ccl)
elif isinstance(_obj, LinearDimension):
#these checks were wrongly placed and seem unecessary...
#keep them here just in case...
#if _active_layer.findObject(_obj) is None:
#_l1, _l2 = _obj.getDimLayers()
#if _image.hasLayer(_l1) and _image.hasLayer(_l2):
_p1, _p2 = _obj.getDimPoints()
dimpoint1 = Point(_p1.getx() + _dx, _p1.gety() + _dy)
dimpoint2 = Point(_p2.getx() + _dx, _p2.gety() + _dy)
dimx, dimy = _obj.getLocation()
#check if points already exist in drawing
_ep = _active_layer.findObject(dimpoint1)
if _ep is None:
_active_layer.addObject(dimpoint1)
else:
dimpoint1 = _ep
_ep = _active_layer.findObject(dimpoint2)
if _ep is None:
_active_layer.addObject(dimpoint2)
else:
dimpoint2 = _ep
_ds = _obj.getDimStyle()
if isinstance(_obj, HorizontalDimension):
_dtype = HorizontalDimension
elif isinstance(_obj, VerticalDimension):
_dtype = VerticalDimension
else:
_dtype = LinearDimension
_dim = _dtype(dimpoint1, dimpoint2, dimx + _dx, dimy + _dy,_ds)
_active_layer.addObject(_dim)
elif isinstance(_obj, RadialDimension):
if _active_layer.findObject(_obj) is None:
_lyr = _obj.getDimLayer()
if _image.hasLayer(_lyr):
_dc = _obj.getDimCircle()
_ds = _obj.getDimStyle()
_dim = RadialDimension(_lyr, _dc, _x, _y, _ds)
_active_layer.addObject(_dim)
elif isinstance(_obj, AngularDimension):
if _active_layer.findObject(_obj) is None:
_cl, _l1, _l2 = _obj.getDimLayers()
if (_image.hasLayer(_cl) and
_image.hasLayer(_l1) and
_image.hasLayer(_l2)):
_cp, _p1, _p2 = _obj.getDimPoints()
_ds = _obj.getDimStyle()
_dim = AngularDimension(_cl, _cp, _l1, _p1, _l2, _p2, _x, _y, _ds)
_active_layer.addObject(_dim)
elif isinstance(_obj, text.TextBlock):
_ntb = _obj.clone()
_origpos = _obj.getLocation()
_ntb.setLocation(_origpos[0] + _dx, _origpos[1] + _dy)
_active_layer.addObject(_ntb)
else:
print "Unexpected type for pasting: " + `type(_obj)`
finally:
_image.endAction()
def paste_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click where you want to paste the objects'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", paste_button_press_cb)
def determine_center(_objectarray):
#determine "center" of n points - simplest method: average values of
#coordinates of center points of each object
_sumx, _sumy, _objectnumber = 0, 0, 0
for _obj in _objectarray:
_objectnumber += 1
if isinstance(_obj, Point):
_sumx += _obj.getx()
_sumy += _obj.gety()
elif isinstance(_obj, Segment):
_x, _y = _obj.getMiddlePoint()
_sumx += _x
_sumy += _y
elif isinstance(_obj, (Circle, Arc, CCircle)):
_center = _obj.getCenter()
_sumx += _center.getx()
_sumy += _center.gety()
elif isinstance(_obj, (HCLine, VCLine, ACLine)):
_center = _obj.getLocation()
_sumx += _center.getx()
_sumy += _center.gety()
elif isinstance(_obj, CLine):
_midpoint = _obj.getMiddlePoint()
_sumx += _midpoint.getx()
_sumy += _midpoint.gety()
elif isinstance(_obj, LinearDimension):
#linear dimensions don't count since they are connected to another
#object
_objectnumber -= 1
#elif isinstance(_obj, RadialDimension):
#elif isinstance(_obj, AngularDimension):
elif isinstance(_obj, text.TextBlock):
_location = _obj.getLocation()
_sumx += _location[0]
_sumy += _location[1]
elif isinstance(_obj, DimString):
_objectnumber -= 1
else:
print "Unexpected type for center determination: " + `type(_obj)`
_objectnumber -= 1
return _sumx / _objectnumber, _sumy / _objectnumber
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkconobjs.py 0000644 0001750 0001750 00000064357 11307666732 022136 0 ustar matteo matteo #
# Copyright (c) 2002, 2003, 2004, 2006, 2007 Art Haas
#
# 2009 Matteo Boscolo
#
# 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 event handling bits for construction lines
# and circles
#
import math
import pygtk
pygtk.require('2.0')
import gtk
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.cline import CLine
from PythonCAD.Generic.ccircle import CCircle
from PythonCAD.Generic.color import Color
from PythonCAD.Generic import util
from PythonCAD.Interface.Gtk import gtkentities
from PythonCAD.Generic import snap
from PythonCAD.Generic.pyGeoLib import Vector
# horizontal construction lines
#
def hcline_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setPoint,_tol,_snapArray)
gtkentities.create_entity(gtkimage)
def hcline_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_val = util.get_float(eval(_text, gtkimage.image.getImageVariables()))
tool.setPoint(0.0, _val)
gtkentities.create_entity(gtkimage)
def hcline_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_("Click in the drawing area or enter 'y' coordinate:"))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", hcline_mode_init)
_tool.setHandler("button_press", hcline_button_press_cb)
_tool.setHandler("entry_event", hcline_entry_event_cb)
#
# vertical construction lines
#
def vcline_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setPoint,_tol,_snapArray)
gtkentities.create_entity(gtkimage)
def vcline_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_val = util.get_float(eval(_text, gtkimage.image.getImageVariables()))
tool.setPoint(_val, 0.0)
gtkentities.create_entity(gtkimage)
def vcline_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_("Click in the drawing area or enter 'x' coordinate:"))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", vcline_mode_init)
_tool.setHandler("button_press", vcline_button_press_cb)
_tool.setHandler("entry_event", vcline_entry_event_cb)
#
# common functions for for acline, cline, and ccircle objects
#
def make_tuple(text, gdict):
_tpl = eval(text, gdict)
if not isinstance(_tpl, tuple):
raise TypeError, "Invalid tuple: " + `type(_tpl)`
if len(_tpl) != 2:
raise ValueError, "Invalid tuple: " + str(_tpl)
return _tpl
#
# angled construction lines
#
def acline_motion_notify_cb(gtkimage, widget, event, tool):
_segs = []
_ax, _ay = tool.getPoint().point.getCoords()
_pax, _pay = gtkimage.coordToPixTransform(_ax, _ay)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_segs.append((_pax, _pay, _xc, _yc))
_snapArray={'perpendicular':False,'tangent':False}
snap.setDinamicSnap(gtkimage,tool.setLocation,_snapArray)
tool.setCurrentPoint(_x, _y)
_segs.append((_pax, _pay, _x, _y))
widget.window.draw_segments(_gc, _segs)
return True
def acline_entry_make_angle(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_angle = util.make_angle(eval(_text, gtkimage.image.getImageVariables()))
tool.setAngle(_angle)
gtkentities.create_entity(gtkimage)
def acline_entry_make_pt(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setPoint(_x, _y)
tool.setHandler("button_press", acline_second_button_press_cb)
tool.setHandler("entry_event", acline_entry_make_angle)
tool.setHandler("motion_notify", acline_motion_notify_cb)
gtkimage.setPrompt(_('Enter the angle or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
def acline_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setLocation,_tol,_snapArray)
gtkentities.create_entity(gtkimage)
return True
def acline_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setPoint,_tol,_snapArray)
tool.setHandler("button_press", acline_second_button_press_cb)
tool.setHandler("entry_event", acline_entry_make_angle)
tool.setHandler("motion_notify", acline_motion_notify_cb)
gtkimage.setPrompt(_('Enter the angle or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def acline_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter a Point'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", acline_mode_init)
_tool.setHandler("button_press", acline_first_button_press_cb)
_tool.setHandler("entry_event", acline_entry_make_pt)
#
# two point construction line
#
def cline_motion_notify_cb(gtkimage, widget, event, tool):
_segs = []
_x1, _y1 = tool.getFirstPoint().point.getCoords()
_px1, _py1 = gtkimage.coordToPixTransform(_x1, _y1)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_segs.append((_px1, _py1, _xc, _yc))
_snapArray={'perpendicular':False,'tangent':False}
snap.setDinamicSnap(gtkimage,tool.setSecondPoint,_snapArray)
tool.setCurrentPoint(_x, _y)
_segs.append((_px1, _py1, _x, _y))
widget.window.draw_segments(_gc, _segs)
return True
def cline_second_entry_make_pt(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setSecondPoint(_x, _y)
gtkentities.create_entity(gtkimage)
def cline_first_entry_make_pt(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setFirstPoint(_x, _y)
tool.setHandler("button_press", cline_second_button_press_cb)
tool.setHandler("motion_notify", cline_motion_notify_cb)
tool.setHandler("entry_event", cline_second_entry_make_pt)
gtkimage.setPrompt(_('Enter the second Point or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
def cline_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setSecondPoint,_tol,_snapArray)
gtkentities.create_entity(gtkimage)
return True
def cline_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setFirstPoint,_tol,_snapArray)
tool.setHandler("button_press", cline_second_button_press_cb)
tool.setHandler("entry_event", cline_second_entry_make_pt)
tool.setHandler("motion_notify", cline_motion_notify_cb)
gtkimage.setPrompt(_('Enter the second point or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def cline_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter a Point'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", cline_mode_init)
_tool.setHandler("button_press", cline_first_button_press_cb)
_tool.setHandler("entry_event", cline_first_entry_make_pt)
#
# construction circles
#
def ccircle_cpmode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter a Point'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", gtkentities.circle_center_button_press_cb)
_tool.setHandler("entry_event", gtkentities.circle_point_entry_event_cb)
_tool.setHandler("initialize", ccircle_cpmode_init)
#
# two-point construction circle
#
def ccircle_tpmode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter a Point'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", gtkentities.circle_tp_first_button_press_cb)
_tool.setHandler("entry_event", gtkentities.circle_tp_first_entry_event_cb)
_tool.setHandler("initialize", ccircle_tpmode_init)
#
# perpendicular construction line creation
#
def perp_cline_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_pt,_pc=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
_active_layer = _image.getActiveLayer()
_hits = _active_layer.mapPoint((_pt,_pc), _tol, 1)
if len(_hits):
_obj, _lp = _hits[0]
_pcl = None
if isinstance(_obj, Segment):
_p1, _p2 = _obj.getEndpoints()
_p1x, _p1y = _p1.getCoords()
_p2x, _p2y = _p2.getCoords()
if abs(_p1x - _p2x) < 1e-10: # vertical
_pcl = HCLine(_lp)
elif abs(_p1y - _p2y) < 1e-10: # horizontal
_pcl = VCLine(_lp)
else:
_slope = (180.0/math.pi) * math.atan2((_p2y - _p1y),
(_p2x - _p1x)) + 90.0
_pcl = ACLine(_lp, _slope)
elif isinstance(_obj, (Circle, Arc, CCircle)):
_cp = _obj.getCenter()
_pcl = CLine(_cp, _lp)
elif isinstance(_obj, HCLine):
_pcl = VCLine(_lp)
elif isinstance(_obj, VCLine):
_pcl = HCLine(_lp)
elif isinstance(_obj, ACLine):
_angle = _obj.getAngle()
if abs(_angle) < 1e-10: # horizontal
_pcl = VCLine(_lp)
elif abs(abs(_angle) - 90.0) < 1e-10: # vertical
_pcl = HCLine(_lp)
else:
_slope = _angle + 90.0
_pcl = ACLine(_lp, _slope)
elif isinstance(_obj, CLine):
_p1, _p2 = _obj.getKeypoints()
_p1x, _p1y = _p1.getCoords()
_p2x, _p2y = _p2.getCoords()
if abs(_p1x - _p2x) < 1e-10: # vertical
_pcl = HCLine(_lp)
elif abs(_p1y - _p2y) < 1e-10: # horizontal
_pcl = VCLine(_lp)
else:
_slope = (180.0/math.pi) * math.atan2((_p2y - _p1y),
(_p2x - _p1x)) + 90.0
_pcl = ACLine(_lp, _slope)
else:
pass
_image.startAction()
try:
if _lp.getParent() is None:
_active_layer.addObject(_lp)
if _pcl is not None:
_active_layer.addObject(_pcl)
finally:
_image.endAction()
return True
def perpendicular_cline_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the object you want a perpendicular to'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", perp_cline_button_press_cb)
#
# tangent cline creation
#
def tangent_cline_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'tangent':False}
_pt=snap.getOnlySnap(_image,_tol,_snapArray)
if _pt is not None:
_x, _y = _pt.point.getCoords()
_layer = _image.getActiveLayer()
_rtd = 180.0/math.pi
_cobj = None
_angle = None
_circleEnt=_pt.entity
if isinstance(_circleEnt,(CCircle,Circle,Arc)):
_cp=_circleEnt.getCenter()
_rad = _circleEnt.getRadius()
_v=Vector(_cp,_pt.point).Mag()
_v.Mult(_rad)
_vectPoint=_v.Point()
_x,_y=(_vectPoint+_cp)
_cx,_cy=_cp.getCoords()
if abs(math.hypot((_x - _cx), (_y - _cy)) - _rad) < 1e-10:
_cobj = _circleEnt
_angle = _rtd * math.atan2((_y - _cy), (_x - _cx))
if _angle < 0.0:
_angle = _angle + 360.0
_pt=Point(_x,_y)
if _cobj is not None:
_image.startAction()
try:
if _pt:
_layer.addObject(_pt)
if (abs(_angle) < 1e-6 or
abs(_angle - 180.0) < 1e-6 or
abs(_angle - 360.0) < 1e-6):
_tcl = VCLine(_pt)
elif (abs(_angle - 90.0) < 1e-6 or
abs(_angle - 270.0) < 1e-6):
_tcl = HCLine(_pt)
else:
_slope = _angle + 90.0
_tcl = ACLine(_pt, _slope)
_layer.addObject(_tcl)
finally:
_image.endAction()
return True
def tangent_cline_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the circle object you want a tangent to'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", tangent_cline_button_press_cb)
#
# parallel offset mode
#
def parallel_refpt_button_press_cb(gtkimage, widget, event, tool):
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
tool.setReferencePoint(_x, _y)
_init_func = tool.getHandler("initialize")
_image.startAction()
try:
tool.create(gtkimage.image)
finally:
_image.endAction()
_init_func(gtkimage)
return True
def parallel_conline_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol, 1)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
for _obj, _pt in _objdict[_active_layer]:
if isinstance(_obj, (HCLine, VCLine, ACLine, CLine)):
tool.setConstructionLine(_obj)
tool.setHandler("button_press", parallel_refpt_button_press_cb)
gtkimage.setPrompt(_('Click on the side to place the new construction line.'))
def parallel_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_snp=snap.getSnapPoint(_image,_tol,_snapArray)
_x,_y=_snp.point.getCoords()
print "Debug: " + str(tool.getLocation())
_x1, _y1 = tool.getLocation()
_offset = math.hypot((_x - _x1), (_y - _y1))
tool.setOffset(_offset)
tool.setHandler("button_press", parallel_conline_button_press_cb)
gtkimage.setPrompt(_('Click on the reference construction line.'))
return True
def parallel_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x1,_y1=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
tool.setLocation(_x1,_y1)
tool.setHandler("button_press", parallel_second_button_press_cb)
tool.delHandler("entry_event")
gtkimage.setPrompt(_('Click another point to define the offset distance.'))
return True
def parallel_entry_event(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_dist = util.get_float(eval(_text, gtkimage.image.getImageVariables()))
tool.setOffset(_dist)
tool.delHandler("entry_event")
tool.setHandler("button_press", parallel_conline_button_press_cb)
gtkimage.setPrompt(_('Click on the reference construction line.'))
def parallel_offset_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Enter the distance or click in the drawing area.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", parallel_offset_mode_init)
_tool.setHandler("button_press", parallel_first_button_press_cb)
_tool.setHandler("entry_event", parallel_entry_event)
#
# construction circle tangent to a construction line
#
def ccircle_single_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
tool.setLocation(_x, _y)
gtkentities.create_entity(gtkimage)
return True
def ccircle_single_motion_notify_cb(gtkimage, widget, event, tool):
_gc = gtkimage.getGC()
_upp = gtkimage.getUnitsPerPixel()
_rect = tool.getPixelRect()
if _rect is not None:
_xmin, _ymin, _width, _height = _rect
widget.window.draw_arc(_gc, False, _xmin, _ymin, _width, _height,
0, 360*64)
_ix, _iy = gtkimage.image.getCurrentPoint()
tool.setLocation(_ix, _iy)
_cx, _cy = tool.getCenter()
_radius = tool.getRadius()
_pcx, _pcy = gtkimage.coordToPixTransform(_cx, _cy)
_pr = int(_radius/_upp)
_xmin = _pcx - _pr
_ymin = _pcy - _pr
_width = _height = _pr * 2
tool.setPixelRect(_xmin, _ymin, _width, _height)
widget.window.draw_arc(_gc, False, _xmin, _ymin, _width, _height,
0, 360*64)
return True
def ccircle_single_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'tangent':True}
ent=snap.getOnlySnap(_image,_tol,_snapArray).entity
if ent is not None:
_active_layer = _image.getActiveLayer()
if isinstance(ent, (HCLine, VCLine, ACLine, CLine, CCircle)):
tool.setConstructionLine(ent)
tool.setHandler("button_press", ccircle_single_second_button_press_cb)
tool.setHandler("motion_notify", ccircle_single_motion_notify_cb)
gtkimage.setPrompt(_('Click where the circle should be drawn.'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def tangent_ccircle_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the construction object used for tangency.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", tangent_ccircle_mode_init)
_tool.setHandler("button_press", ccircle_single_first_button_press_cb)
#
# construction circle between two construction lines
#
def two_cline_set_circle_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
tool.setLocation(_x, _y)
gtkentities.create_entity(gtkimage)
def two_cline_motion_notify_cb(gtkimage, widget, event, tool):
_gc = gtkimage.getGC()
_upp = gtkimage.getUnitsPerPixel()
_rect = tool.getPixelRect()
if _rect is not None:
_xmin, _ymin, _width, _height = _rect
widget.window.draw_arc(_gc, False, _xmin, _ymin, _width, _height,
0, 360*64)
_ix, _iy = gtkimage.image.getCurrentPoint()
tool.setLocation(_ix, _iy)
_radius = tool.getRadius()
if _radius > 0.0:
_cx, _cy = tool.getCenter()
_pcx, _pcy = gtkimage.coordToPixTransform(_cx, _cy)
_pr = int(_radius/_upp)
_xmin = _pcx - _pr
_ymin = _pcy - _pr
_width = _height = _pr * 2
tool.setPixelRect(_xmin, _ymin, _width, _height)
widget.window.draw_arc(_gc, False, _xmin, _ymin, _width, _height,
0, 360*64)
return True
def two_cline_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol, 1)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
_first_conobj = tool.getFirstConObject()
for _obj, _pt in _objdict[_active_layer]:
if _obj is _first_conobj:
continue
if isinstance(_obj, (HCLine, VCLine, ACLine, CLine)):
tool.setHandler("button_press", two_cline_set_circle_cb)
tool.setHandler("motion_notify", two_cline_motion_notify_cb)
tool.setSecondConObject(_obj)
gtkimage.setPrompt(_('Click where you want the tangent circle to be.'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def two_cline_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol, 1)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
for _obj, _pt in _objdict[_active_layer]:
if isinstance(_obj, (HCLine, VCLine, ACLine, CLine, CCircle)):
tool.setHandler("button_press", two_cline_second_button_press_cb)
tool.setFirstConObject(_obj)
gtkimage.setPrompt(_('Click on the second construction line for tangency.'))
return True
def two_cline_tancc_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the first construction line or construction circle for tangency.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", two_cline_tancc_mode_init)
_tool.setHandler("button_press", two_cline_first_button_press_cb)
#
# tangent lines around two circles
#
def two_ccircle_tangent_cb(gtkimage, widget, event, tool):
_x, _y = gtkimage.image.getCurrentPoint()
tool.setLocation(_x, _y)
gtkentities.create_entity(gtkimage)
def _draw_two_circle_tangents(gtkimage, tool):
_tanpts = tool.getTangentPoints()
assert len(_tanpts), "No tangent points defined!"
_gc = gtkimage.getGC()
_da = gtkimage.getDA()
#
# adjust the GC to draw the temporary segments in
# a distinctive manner
#
_gc.set_line_attributes(1, gtk.gdk.LINE_DOUBLE_DASH,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
_gc.set_dashes(0, [3, 3])
_tempcolor = Color('#ffff99') # yellowish color
_color = gtkimage.getColor(_tempcolor)
_gc.set_foreground(_color)
_gc.set_function(gtk.gdk.COPY)
#
_segs = []
for _set in _tanpts:
_x1, _y1, _x2, _y2 = _set
# print "x1: %g; y1: %g" % (_x1, _y1)
# print "x2: %g; y2: %g" % (_x2, _y2)
_px1, _py1 = gtkimage.coordToPixTransform(_x1, _y1)
_px2, _py2 = gtkimage.coordToPixTransform(_x2, _y2)
_segs.append((_px1, _py1, _px2, _py2))
_da.window.draw_segments(_gc, _segs)
def two_circle_tangent_second_button_press_cb(gtkimage, widget, event, tool):
# print "in second_button_press_cb() ..."
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol, 1)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
for _obj, _pt in _objdict[_active_layer]:
if isinstance(_obj, CCircle):
tool.setHandler("button_press", two_circle_tangent_second_button_press_cb)
tool.setSecondCCircle(_obj)
if tool.hasTangentPoints():
_draw_two_circle_tangents(gtkimage, tool)
gtkimage.setPrompt(_('Click on the segment to keep.'))
tool.setHandler("button_press", two_ccircle_tangent_cb)
else:
tool.reset()
two_circle_tangent_line_mode_init(gtkimage, tool)
return True
def two_circle_tangent_first_button_press_cb(gtkimage, widget, event, tool):
# print "in first_button_press_cb() ..."
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol, 1)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
for _obj, _pt in _objdict[_active_layer]:
if isinstance(_obj, CCircle):
tool.setHandler("button_press", two_circle_tangent_second_button_press_cb)
tool.setFirstCCircle(_obj)
gtkimage.setPrompt(_('Click on the second construction circle.'))
return True
def two_circle_tangent_line_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the first construction circle.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", two_circle_tangent_line_mode_init)
_tool.setHandler("button_press", two_circle_tangent_first_button_press_cb)
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkimage.py 0000644 0001750 0001750 00000146735 11307666732 021564 0 ustar matteo matteo #
# Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 Art Haas
# Copyright (c) 2009 Matteo Boscolo
# 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 GTK code for displaying a drawing
#
from __future__ import division
import math
import types
import warnings
import pygtk
pygtk.require('2.0')
import gtk
import gobject
from PythonCAD.Interface.Gtk import gtkdimension
from PythonCAD.Interface.Gtk import gtktext
from PythonCAD.Interface.Gtk import gtkactions
from PythonCAD.Generic.image import Image
from PythonCAD.Generic.point import Point
from PythonCAD.Generic.conobject import ConstructionObject
from PythonCAD.Generic.color import Color
from PythonCAD.Generic.layer import Layer
from PythonCAD.Generic import tools
from PythonCAD.Generic import globals
from PythonCAD.Generic import keywords
from PythonCAD.Generic import prompt
from PythonCAD.Interface.Gtk import gtkshell
#
# Global variables
#
_debug = False ## SDB debug stuff
globals.gtkcolors = {}
globals.gtklinetypes = {}
class GTKImage(object):
"""
The GTK wrapping around an Image
The GTKImage class is derived from the Image class, so it shares all
the attributes and methods of that class. The GTKImage class has the
following addtional methods:
close(): Close a GTKImage.
getWindow(): Get the GTK Window used in the GTKImage.
getEntry(): Get the GTK Entry used in the GTKImage.
getDA(): Get the GTK Drawing Area used in the GTKImage.
{get/set}Pixmap(): Get/Set the GTK Pixmap used in the GTKImage.
{get/set}Prompt(): Get/Set the prompt.
{get/set}Tool(): Get/Set the tool used for working in the GTKImage.
{get/set}UnitsPerPixel(): Get/Set this display parameter.
{get/set}View(): Get/Set the current view seen in the GTKImage.
getTolerance(): Get the current drawing tolerance.
{get/set}GC(): Get/Set the graphic context used in the GTKImage.
{get/set}Point(): Get/Set the current coordinates of the tool.
{get/set}Size(): Get/Set the size of the drawing area.
pixToCoordTransform(): Convert pixels to x/y coordinates.
coordToPixTransform(): Convert x/y coordinates to pixels.
refresh(): Redraw the screen using the current pixmap.
redraw(): Recalculate the visible entities and redraw the screen.
addGroup(): Add a new ActionGroup to the GTKImage.
getGroup(): Retrieve an ActionGroup from the GTKImage.
deleteGroup(): Remove an ActionGroup from the GTKImage.
"""
#
# class variables
#
from PythonCAD.Interface.Gtk import gtkentities
from PythonCAD.Interface.Gtk import gtkconobjs
from PythonCAD.Interface.Gtk import gtkmodify
from PythonCAD.Interface.Gtk import gtkmirror
from PythonCAD.Interface.Gtk import gtkprinting
from PythonCAD.Interface.Gtk import gtkedit
__inittool = {
tools.PasteTool : gtkedit.paste_mode_init,
tools.SelectTool : gtkedit.select_mode_init,
tools.DeselectTool : gtkedit.deselect_mode_init,
tools.PointTool : gtkentities.point_mode_init,
tools.SegmentTool : gtkentities.segment_mode_init,
tools.RectangleTool: gtkentities.rectangle_mode_init,
tools.CircleTool : gtkentities.circle_center_mode_init,
tools.TwoPointCircleTool : gtkentities.circle_tp_mode_init,
tools.ArcTool : gtkentities.arc_center_mode_init,
tools.ChamferTool : gtkentities.chamfer_mode_init,
tools.FilletTool: gtkentities.fillet_mode_init,
tools.FilletTwoLineTool: gtkentities.fillet_two_line_mode_init,
tools.LeaderTool : gtkentities.leader_mode_init,
tools.PolylineTool : gtkentities.polyline_mode_init,
tools.PolygonTool : gtkentities.polygon_mode_init,
tools.HCLineTool : gtkconobjs.hcline_mode_init,
tools.VCLineTool : gtkconobjs.vcline_mode_init,
tools.ACLineTool : gtkconobjs.acline_mode_init,
tools.CLineTool : gtkconobjs.cline_mode_init,
tools.PerpendicularCLineTool: gtkconobjs.perpendicular_cline_mode_init,
tools.TangentCLineTool : gtkconobjs.tangent_cline_mode_init,
tools.CCircleTangentLineTool : gtkconobjs.two_circle_tangent_line_mode_init,
tools.ParallelOffsetTool : gtkconobjs.parallel_offset_mode_init,
tools.CCircleTool : gtkconobjs.ccircle_cpmode_init,
tools.TwoPointCCircleTool : gtkconobjs.ccircle_tpmode_init,
tools.TangentCCircleTool : gtkconobjs.tangent_ccircle_mode_init,
tools.TwoPointTangentCCircleTool : gtkconobjs.two_cline_tancc_mode_init,
tools.TextTool : gtktext.text_add_init,
tools.HorizontalMoveTool : gtkmodify.move_horizontal_init,
tools.VerticalMoveTool : gtkmodify.move_vertical_init,
tools.MoveTool : gtkmodify.move_twopoint_init,
tools.HorizontalStretchTool : gtkmodify.stretch_horizontal_init,
tools.VerticalStretchTool : gtkmodify.stretch_vertical_init,
tools.StretchTool : gtkmodify.stretch_xy_init,
tools.TransferTool : gtkmodify.transfer_object_init,
tools.RotateTool : gtkmodify.rotate_init,
tools.SplitTool : gtkmodify.split_object_init,
tools.DeleteTool : gtkmodify.delete_mode_init,
tools.MirrorTool : gtkmirror.mirror_mode_init,
tools.ZoomTool : gtkmodify.zoom_init,
tools.LinearDimensionTool : gtkdimension.linear_mode_init,
tools.HorizontalDimensionTool : gtkdimension.horizontal_mode_init,
tools.VerticalDimensionTool : gtkdimension.vertical_mode_init,
tools.RadialDimensionTool : gtkdimension.radial_mode_init,
tools.AngularDimensionTool : gtkdimension.angular_mode_init,
tools.PlotTool : gtkprinting.plot_mode_init,
tools.ZoomPan : gtkmodify.zoomPan_init,
}
def __init__(self, image):
debug_print("Initialized another GTKImage class instance...")
if not isinstance(image, Image):
raise TypeError, "Invalid Image type: " + `type(image)`
self.__image = image
self.__window = gtk.Window()
self.__window.set_title(image.filename)
self.__window.set_icon_from_file("gtkpycad.png")
self.__window.connect("destroy", self.__destroyEvent)
self.__window.connect("event", self.__windowEvent)
self.__window.connect("key_press_event", self.__keyPressEvent)
#
# Zooming Moving global Variable Definition
#
self.__StartZooming= False
self.__StartMoving = False
self.StopMove=False
self._activateSnap=False
_width = min(1024, int(0.8 * float(gtk.gdk.screen_width())))
_height = min(768, int(0.8 * float(gtk.gdk.screen_height())))
self.__window.set_default_size(_width, _height)
main_vbox = gtk.VBox(False, 2)
main_vbox.set_border_width(2)
self.__window.add(main_vbox)
#
# accelerators
#
self.__accel = gtk.AccelGroup()
self.__window.add_accel_group(self.__accel)
#
# menu bar
#
self.__mb = gtk.MenuBar()
main_vbox.pack_start(self.__mb, False, False)
#
# action group dictionary
#
self.__groups = {}
#
# fixme - try to rework code to avoid this import ...
#
from PythonCAD.Interface.Gtk.gtkmenus import fill_menubar
fill_menubar(self.__mb, self)
#
# drawing window has Horizontal Pane:
# left side: stuff for layer display
# right side: drawing area
#
pane = gtk.HPaned()
main_vbox.pack_start(pane)
frame1 = gtk.Frame()
pane.pack1(frame1, True, False)
pane.set_position(100)
#
# layer display stuff
#
_ld = gtkshell.LayerDisplay(self.__image, self.__window)
frame1.add(_ld.getWindow())
self.__layerdisplay = _ld
#
# drawing area
#
self.__disp_width = None
self.__disp_height = None
self.__units_per_pixel = 1.0
self.__da = gtk.DrawingArea()
black = gtk.gdk.color_parse('black')
self.__da.modify_fg(gtk.STATE_NORMAL, black)
self.__da.modify_bg(gtk.STATE_NORMAL, black)
pane.pack2(self.__da, True, False)
self.__da.set_flags(gtk.CAN_FOCUS)
self.__da.connect("event", self.__daEvent)
self.__da.connect("expose_event", self.__exposeEvent)
self.__da.connect("realize", self.__realizeEvent)
self.__da.connect("configure_event", self.__configureEvent)
# self.__da.connect("focus_in_event", self.__focusInEvent)
# self.__da.connect("focus_out_event", self.__focusOutEvent)
self.__da.set_events(gtk.gdk.EXPOSURE_MASK |
gtk.gdk.LEAVE_NOTIFY_MASK |
gtk.gdk.BUTTON_PRESS_MASK |
gtk.gdk.BUTTON_RELEASE_MASK |
gtk.gdk.ENTER_NOTIFY_MASK|
gtk.gdk.LEAVE_NOTIFY_MASK|
gtk.gdk.KEY_PRESS_MASK |
gtk.gdk.KEY_RELEASE_MASK |
gtk.gdk.FOCUS_CHANGE_MASK |
gtk.gdk.POINTER_MOTION_MASK)
lower_hbox = gtk.HBox(False, 2)
main_vbox.pack_start(lower_hbox, False, False)
self.__prompt = gtk.Label(_('Enter Command:'))
lower_hbox.pack_start(self.__prompt, False, False)
#
# where the action is taking place
#
self.__coords = gtk.Label('(0,0)')
lower_hbox.pack_end(self.__coords, False, False)
self.__image.setCurrentPoint(0.0, 0.0)
#
# command entry area
#
self.__entry = gtk.Entry()
main_vbox.pack_start(self.__entry, False, False)
self.__entry.connect("activate", self.__entryEvent)
#
# the Pixmap, GraphicContext, and CairoContext for the drawing
#
self.__pixmap = None
self.__gc = None
self.__ctx = None
self.__refresh = True
#
# the viewable region and tolerance in the drawing
#
self.__xmin = None
self.__ymin = None
self.__xmax = None
self.__ymax = None
self.__tolerance = 1e-10
#
# establish message connections
#
_image = self.__image
_image.connect('selected_object', self.__selectedObject)
_image.connect('deselected_object', self.__deselectedObject)
_image.connect('option_changed', self.__optionChanged)
_image.connect('current_point_changed', self.__currentPointChanged)
_image.connect('active_layer_changed', self.__activeLayerChanged)
_image.connect('added_child', self.__imageAddedChild)
_image.connect('removed_child', self.__imageRemovedChild)
_image.connect('group_action_started', self.__groupActionStarted)
_image.connect('group_action_ended', self.__groupActionEnded)
_image.connect('units_changed', self.__imageUnitsChanged)
_image.connect('tool_changed', self.__imageToolChanged)
_layers = [_image.getTopLayer()]
while len(_layers):
_layer = _layers.pop()
_layer.connect('added_child', self.__layerAddedChild)
_layer.connect('removed_child', self.__layerRemovedChild)
for _child in _layer.getChildren():
_child.connect('refresh', self.__refreshObject)
_child.connect('change_pending', self.__objChangePending)
_child.connect('change_complete', self.__objChangeComplete)
_layers.extend(_layer.getSublayers())
#------------------------------------------------------------------
def close(self):
"""Release the entites stored in the drawing.
close()
"""
self.__layerdisplay.close()
self.__layerdisplay = None
_image = self.__image
_image.close()
_image.disconnect(self)
_log = _image.getLog()
if _log is not None:
_log.detatch()
_image.setLog(None)
_image.finish()
self.__window.destroy()
self.__window = None
self.__da = None
self.__entry = None
self.__accel = None
self.__mb = None
self.__pixmap = None
self.__gc = None
#------------------------------------------------------------------
def __destroyEvent(self, widget, data=None):
"""
Destroy event
"""
if self.__image.isSaved()== False:
from PythonCAD.Interface.Gtk.gtkmenus import file_quit_cb
file_quit_cb(None,self)
self.close()
for _i in xrange(len(globals.imagelist)):
_gimage = globals.imagelist[_i]
if self.__image is _gimage:
del globals.imagelist[_i]
if not len(globals.imagelist):
gtk.main_quit()
break
return False
#------------------------------------------------------------------
def __keyPressEvent(self, widget, event, data=None):
#print "__keyPressEvent()"
_entry = self.__entry
if _entry.is_focus():
return False
_tool = self.__image.getTool()
if _tool is not None and _tool.hasHandler('entry_event'):
_entry.grab_focus()
return _entry.event(event)
return False
#------------------------------------------------------------------
def __windowEvent(self, widget, event, data=None):
_type = event.type
debug_print("__windowEvent: Event type: %d" % _type)
if _type == gtk.gdk.BUTTON_PRESS:
_button = event.button
debug_print("BUTTON_PRESS: %d" % _button)
elif _type == gtk.gdk.BUTTON_RELEASE:
_button = event.button
debug_print("BUTTON_RELEASE: %d" % _button)
elif _type == gtk.gdk.KEY_PRESS:
debug_print("KEY_PRESS")
if event.keyval == gtk.keysyms.Escape:
debug_print("Got escape key")
self.reset()
self._activateSnap=False
return True
elif _type == gtk.gdk.KEY_RELEASE:
debug_print("KEY_RELEASE")
else:
pass
return False
#------------------------------------------------------------------
def __entryEvent(self, widget, data=None):
#
# The error handling in this function needs work, and probably
# a rethink as how the commands are implemented is in order. Perhaps
# the command set should be stored in the image's global dictionary?
#
debug_print("__entryEvent()")
_entry = self.__entry
_text = _entry.get_text().strip()
if len(_text):
_text = _text.lower()
if _text == 'end' or _text == 'stop':
_entry.delete_text(0,-1)
self.reset()
else:
_tool = self.__image.getTool()
if _tool is not None and _tool.hasHandler("entry_event"):
_handler = _tool.getHandler("entry_event")
try:
_handler(self, widget, _tool)
except StandardError, e:
print "exception called: " + str(e)
else:
_cmds = keywords.defaultglobals
_entry.delete_text(0,-1)
# print "text is '%s'" % _text
if _text in _cmds:
# print "valid command"
_opt = _cmds[_text]
# print "opt: '%s'" % _opt
_tooltype = prompt.lookup(_opt)
# print "cmd: '%s'" % _cmd
if _tooltype is not None:
self.__image.setTool(_tooltype())
else:
# print "Calling exec for '%s'" % _text
# print "Command Error; See http://www.pythoncad.org/commands.html for reference page."
try:
exec _text in self.__image.getImageVariables()
except:
print "error executing '%s' " % _text
#
# set the focus back to the DisplayArea widget
#
self.__da.grab_focus()
return False
#------------------------------------------------------------------
def __exposeEvent(self, widget, event, data=None):
# print "__exposeEvent()"
_pixmap = self.__pixmap
_x, _y, _w, _h = event.area
_gc = widget.get_style().fg_gc[widget.state]
widget.window.draw_drawable(_gc, _pixmap, _x, _y, _x, _y, _w, _h)
return True
#------------------------------------------------------------------
def __realizeEvent(self, widget, data=None):
_win = widget.window
_width, _height = _win.get_size()
self.setSize(_width, _height)
widget.set_size_request(100,100)
_gc = _win.new_gc()
_gc.set_exposures(True)
self.setGC(_gc)
#------------------------------------------------------------------
def __configureEvent(self, widget, event, data=None):
_win = widget.window
_width, _height = _win.get_size()
_disp_width, _disp_height = self.getSize()
if _disp_width != _width or _disp_height != _height:
self.setSize(_width, _height)
_pixmap = gtk.gdk.Pixmap(_win, _width, _height)
_gc = widget.get_style().fg_gc[widget.state]
_pixmap.draw_rectangle(_gc, True, 0, 0, _width, _height)
self.setPixmap(_pixmap)
if hasattr(_pixmap, 'cairo_create'):
self.__ctx = _pixmap.cairo_create()
_xmin = self.__xmin
_ymin = self.__ymin
if _xmin is None or _ymin is None:
_xmin = 1.0
_ymin = 1.0
_upp = self.__units_per_pixel
self.setView(_xmin, _ymin, _upp)
return True
#------------------------------------------------------------------
def __daEvent(self, widget, event, data=None):
_rv = False
_type = event.type
debug_print("__daEvent(): Event type: %d" % _type)
_tool = self.__image.getTool()
if _type==31:
debug_print("if 31")
if event.direction == gtk.gdk.SCROLL_UP:
debug_print("BUTTON_PRESSS CROLL_UP")
self.ZoomIn()
if event.direction == gtk.gdk.SCROLL_DOWN:
debug_print("BUTTON_PRESSS SCROLL_DOWN")
self.ZoomOut()
if _type == 12:
debug_print("if 12")
if _type == gtk.gdk.BUTTON_PRESS:
debug_print("gtk.gdk.BUTTON_PRESS")
self.setToolpoint(event)
_button = event.button
if _button == 1:
if _tool is not None and _tool.hasHandler("button_press"):
_rv = _tool.getHandler("button_press")(self, widget,
event, _tool)
debug_print("__Move BUTTON_PRESS")
self.__Move(widget, event)
elif _type == gtk.gdk.BUTTON_RELEASE:
debug_print("gtk.gdk.BUTTON_RELEASE")
self.setToolpoint(event)
_button = event.button
if _button == 1:
if _tool is not None and _tool.hasHandler("button_release"):
_rv =_tool.getHandler("button_release")(self, widget,
event, _tool)
debug_print("__Move BUTTON_RELEASE")
self.__Move(widget, event)
elif _type == gtk.gdk.MOTION_NOTIFY:
debug_print("gtk.gdk.MOTION_NOTIFY")
self.setToolpoint(event)
if _tool is not None and _tool.hasHandler("motion_notify"):
_rv = _tool.getHandler('motion_notify')(self, widget,
event, _tool)
debug_print("__Move MOTION_NOTIFY")
self.__MakeMove(widget,event)
self.__ActiveSnapEvent(widget,event)
elif _type == gtk.gdk.KEY_PRESS:
debug_print("In __daEvent(), got key press!")
_key = event.keyval
if (_key == gtk.keysyms.Page_Up or
_key == gtk.keysyms.Page_Down or
_key == gtk.keysyms.Left or
_key == gtk.keysyms.Right or
_key == gtk.keysyms.Up or
_key == gtk.keysyms.Down):
debug_print("Got Arrow/PageUp/PageDown key")
#KeyMoveDrawing(_key) # Matteo Boscolo 12-05-2009
pass # handle moving the drawing in some fashion ...
elif _key == gtk.keysyms.Escape:
debug_print("Got escape key")
self.reset()
_rv = True
elif _tool is not None and _tool.hasHandler("key_press"):
debug_print("gtk.gdk.MOTION_NOTIFY")
_rv = _tool.getHandler("key_press")(self, widget,
event, _tool)
else:
debug_print("ELSE")
_entry = self.__entry
_entry.grab_focus()
if _key == gtk.keysyms.Tab:
_rv = True
else:
_rv = _entry.event(event)
elif _type == gtk.gdk.ENTER_NOTIFY:
debug_print("gtk.gdk.ENTER_NOTIFY")
self.setToolpoint(event)
_rv = True
elif _type == gtk.gdk.LEAVE_NOTIFY:
debug_print("gtk.gdk.LEAVE_NOTIFY")
self.setToolpoint(event)
_rv = True
else:
debug_print("Got type %d" % _type)
pass
return _rv
def KeyMoveDrawing(self,key):
"""Make A Move when the user press arrows keys"""
self.__MovmentStep=10 #This mast be a global settings that the user can change
actualStep=self.__MovmentStep
actualX=self.__activeX
actualY=self.__activeY
newX=actualX
newY=actualY
if (key == gtk.keysyms.Page_Up):
print("ZoomUp")
if (key == gtk.keysyms.Page_Down):
print("ZoomDown")
if (key == gtk.keysyms.Left):
newX=actualX-actualStep
newY=actualY
if (key == gtk.keysyms.Right):
newX=actualX+actualStep
newY=actualY
if (key == gtk.keysyms.Up):
newX=actualX
newY=actualY+actualStep
if (key == gtk.keysyms.Down):
newX=actualX
newY=actualY-actualStep
self.MoveFromTo(actualX,actualY,newX,newY)
#------------------------------------------------------------------
def __focusInEvent(self, widget, event, data=None):
debug_print("in GTKImage::__focusInEvent()")
return False
#------------------------------------------------------------------
def __focusOutEvent(self, widget, event, data=None):
debug_print("in GTKImage::__focusOutEvent()")
return False
#------------------------------------------------------------------
def __selectedObject(self, img, *args):
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_obj = args[0]
if _debug:
print "Selected object: " + `_obj`
_parent = _obj.getParent()
if _parent.isVisible() and _obj.isVisible():
_color = Color('#ff7733') # FIXME color should be adjustable
_obj.draw(self, _color)
self.__refresh = True
#------------------------------------------------------------------
def __deselectedObject(self, img, *args):
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_obj = args[0]
if _debug:
print "Deselected object: " + `_obj`
_parent = _obj.getParent()
if _parent.isVisible() and _obj.isVisible():
_obj.draw(self)
self.__refresh = True
#------------------------------------------------------------------
def __optionChanged(self, img, *args):
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_opt = args[0]
if _debug:
print "Option changed: '%s'" % _opt
if _opt == 'BACKGROUND_COLOR':
_bc = self.__image.getOption('BACKGROUND_COLOR')
_col = gtk.gdk.color_parse(str(_bc))
self.__da.modify_fg(gtk.STATE_NORMAL, _col)
self.__da.modify_bg(gtk.STATE_NORMAL, _col)
self.redraw()
elif (_opt == 'HIGHLIGHT_POINTS' or
_opt == 'INACTIVE_LAYER_COLOR' or
_opt == 'SINGLE_POINT_COLOR' or
_opt == 'MULTI_POINT_COLOR'):
self.redraw()
else:
pass
#------------------------------------------------------------------
def __currentPointChanged(self, img, *args):
_x, _y = self.__image.getCurrentPoint()
self.__coords.set_text("%.4f, %.4f" % (_x, _y))
#------------------------------------------------------------------
def __activeLayerChanged(self, img, *args):
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_prev_layer = args[0]
self.drawLayer(_prev_layer)
_active_layer = self.__image.getActiveLayer()
self.drawLayer(_active_layer)
self.refresh()
#
def getImage(self):
"""Return the Image being displayed.
getImage()
"""
return self.__image
image = property(getImage, None, None, "Displayed Image")
#------------------------------------------------------------------
def getAccel(self):
"""Return the gtk.AccelGroup in the GTKImage.
getAccel()
"""
return self.__accel
accel = property(getAccel, None, None, "Accel group in the GTKImage.")
#------------------------------------------------------------------
def getWindow(self):
"""Return a handle to the gtk.Window in the GTKImage.
getWindow()
"""
return self.__window
window = property(getWindow, None, None, "Main GTK Window for a GTKImage.")
#------------------------------------------------------------------
def getEntry(self):
"""Return a handle to the gtk.Entry in the GTKImage.
getEntry()
"""
return self.__entry
entry = property(getEntry, None, None, "Entry box for a GTKImage.")
#------------------------------------------------------------------
def getDA(self):
"""Return the gtk.DrawingArea in the GTKImage.
getDA()
"""
return self.__da
da = property(getDA, None, None, "DrawingArea for a GTKImage.")
#------------------------------------------------------------------
def getPixmap(self):
"""Return the Pixmap for the GTKImage.
getPixmap()
"""
return self.__pixmap
#------------------------------------------------------------------
def setPixmap(self, pixmap):
"""Set the Pixmap for the GTKImage.
setPixmap(pixmap)
"""
self.__pixmap = pixmap
pixmap = property(getPixmap, setPixmap, None, "Pixmap for a GTKImage.")
#------------------------------------------------------------------
def getPrompt(self):
"""Return the current prompt string.
getPrompt()
"""
return self.__prompt.get_label()
#------------------------------------------------------------------
def setPrompt(self, p):
"""Set the current prompt string.
setPrompt(p)
"""
if not isinstance(p, types.StringTypes):
raise TypeError, "Invalid prompt type: " + `type(p)`
self.__prompt.set_text(p)
prompt = property(getPrompt, setPrompt, None, "Prompt string.")
#------------------------------------------------------------------
def setTool(self, tool):
"""Replace the tool in the image with a new Tool.
setTool(tool)
The argument 'tool' should be an instance of a Tool object.
"""
warnings.warn("Method setTool() is deprecated - use getImage().setTool()", stacklevel=2)
self.__image.setTool(tool)
#------------------------------------------------------------------
def getTool(self):
"""Return the current Tool used in the drawing.
getTool()
"""
warnings.warn("Method getTool() is deprecated - use getImage().getTool()", stacklevel=2)
return self.__image.getTool()
tool = property(getTool, None, None, "Tool for adding/modifying entities.")
#------------------------------------------------------------------
def getUnitsPerPixel(self):
"""Return the current value of units/pixel.
getUnitsPerPixel()
"""
return self.__units_per_pixel
#------------------------------------------------------------------
def setUnitsPerPixel(self, upp):
"""Set the current value of units/pixel.
setUnitsPerPixel(upp)
The argument 'upp' should be a positive float value.
"""
_upp = upp
if not isinstance(_upp, float):
_upp = float(upp)
if _upp < 1e-10:
raise ValueError, "Invalid scale value: %g" % _upp
self.__units_per_pixel = _upp
self.__tolerance = _upp * 5.0
#------------------------------------------------------------------
def setView(self, xmin, ymin, scale=None):
"""Set the current visible area in a drawing.
setView(xmin, ymin[, scale])
xmin: Minimum visible x-coordinate
ymin: Minimum visible y-coordinate
The optional argument 'scale' defaults to the current
value of units/pixel (set with getUnitsPerPixel() method.)
This value must be a positive float.
"""
_xmin = xmin
if not isinstance(_xmin, float):
_xmin = float(xmin)
_ymin = ymin
if not isinstance(_ymin, float):
_ymin = float(ymin)
_scale = scale
if _scale is None:
_scale = self.__units_per_pixel
if not isinstance(_scale, float):
_scale = float(scale)
if _scale < 1e-10:
raise ValueError, "Invalid scale value: %g" % _scale
_xmax = _xmin + (_scale * self.__disp_width)
_ymax = _ymin + (_scale * self.__disp_height)
_recalc = False
if abs(_scale - self.__units_per_pixel) > 1e-10:
self.__units_per_pixel = _scale
_recalc = True
self.__tolerance = self.__units_per_pixel * 5.0
self.__xmin = _xmin
self.__ymin = _ymin
self.__xmax = _xmax
self.__ymax = _ymax
if _recalc:
self.calcTextWidths()
self.redraw()
def calcTextWidths(self):
"""Calculate the width of the text strings in the Image.
calcTextWidths()
"""
_layers = [self.__image.getTopLayer()]
while len(_layers):
_layer = _layers.pop()
for _tblock in _layer.getLayerEntities('text'):
gtktext.set_textblock_bounds(self, _tblock)
for _dim in _layer.getLayerEntities('linear_dimension'):
_ds1, _ds2 = _dim.getDimstrings()
gtktext.set_textblock_bounds(self, _ds1)
if _dim.getDualDimMode():
gtktext.set_textblock_bounds(self, _ds2)
for _dim in _layer.getLayerEntities('horizontal_dimension'):
_ds1, _ds2 = _dim.getDimstrings()
gtktext.set_textblock_bounds(self, _ds1)
if _dim.getDualDimMode():
gtktext.set_textblock_bounds(self, _ds2)
for _dim in _layer.getLayerEntities('vertical_dimension'):
_ds1, _ds2 = _dim.getDimstrings()
gtktext.set_textblock_bounds(self, _ds1)
if _dim.getDualDimMode():
gtktext.set_textblock_bounds(self, _ds2)
for _dim in _layer.getLayerEntities('radial_dimension'):
_ds1, _ds2 = _dim.getDimstrings()
gtktext.set_textblock_bounds(self, _ds1)
if _dim.getDualDimMode():
gtktext.set_textblock_bounds(self, _ds2)
for _dim in _layer.getLayerEntities('angular_dimension'):
_ds1, _ds2 = _dim.getDimstrings()
gtktext.set_textblock_bounds(self, _ds1)
if _dim.getDualDimMode():
gtktext.set_textblock_bounds(self, _ds2)
_layers.extend(_layer.getSublayers())
def getView(self):
"""Return the current visible area in a drawing.
getView()
This method returns a tuple with four float values:
(xmin, ymin, xmax, ymax)
If the view has never been set, each of these values
will be None.
"""
return (self.__xmin, self.__ymin, self.__xmax, self.__ymax)
view = property(getView, setView, None, "The visible area in a drawing.")
def getTolerance(self):
"""Return the current drawing tolerance.
getTolerance()
"""
return self.__tolerance
tolerance = property(getTolerance, None, None, "Drawing tolerance.")
def getGC(self):
"""Return the GraphicContext allocated for the GTKImage.
getGC()
"""
return self.__gc
def setGC(self, gc):
"""Set the GraphicContext for the GTKImage.
setGC(gc)
"""
if not isinstance(gc, gtk.gdk.GC):
raise TypeError, "Invalid GC object: " + `gc`
if self.__gc is None:
self.__gc = gc
gc = property(getGC, None, None, "GraphicContext for the GTKImage.")
def getCairoContext(self):
"""Return the CairoContext allocated for the GTKImage.
getCairoContext()
"""
return self.__ctx
ctx = property(getCairoContext, None, None, "CairoContext for the GTKImage.")
def getSize(self):
"""Return the size of the DrawingArea window.
getSize()
"""
return (self.__disp_width, self.__disp_height)
def setSize(self, width, height):
"""Set the size of the DrawingArea window.
setSize(width, height)
"""
_width = width
if not isinstance(_width, int):
_width = int(width)
if _width < 0:
raise ValueError, "Invalid drawing area width: %d" % _width
_height = height
if not isinstance(_height, int):
_height = int(height)
if _height < 0:
raise ValueError, "Invalid drawing area height: %d" % _height
self.__disp_width = _width
self.__disp_height = _height
def setToolpoint(self, event):
_x = event.x
_y = event.y
_tx, _ty = self.pixToCoordTransform(_x, _y)
self.__image.setCurrentPoint(_tx, _ty)
def addGroup(self, group):
"""Add an ActionGroup to the GTKImage.
addGroup(group)
Argument 'group' must be either an instance of either
gtk.Action gtk.stdAction.
"""
if not isinstance(group, gtk.ActionGroup):
if not isinstance(gtkactions.stdActionGroup):
raise TypeError, "Invalid group type: " + `type(group)`
self.__groups[group.get_name()] = group
def getGroup(self, name):
"""Return an ActionGroup stored in the GTKImage.
getGroup(name)
Argument 'name' should be the name of the ActionGroup. This method
will return None if no group by that name is stored.
"""
return self.__groups.get(name)
def deleteGroup(self, name):
"""Remove an ActionGroup stored in the GTKImage.
deleteGroup(name)
Argument 'name' should be the name of the ActionGroup to be removed.
"""
if name in self.__groups:
del self.__groups[name]
def pixToCoordTransform(self, xp, yp):
"""Convert from pixel coordinates to x-y coordinates.
pixToCoordTransform(xp, yp)
The function arguments are:
xp: pixel x value
yp: pixel y value
The function returns a tuple holding two float values
"""
_upp = self.__units_per_pixel
_xc = self.__xmin + (xp * _upp)
_yc = self.__ymax - (yp * _upp)
return (_xc, _yc)
#------------------------------------------------------------------
def coordToPixTransform(self, xc, yc):
"""Convert from x-y coordinates to pixel coordinates
coordToPixTransform(xc, yc)
The function arguments are:
xc: x coordinate
yp: y coordinate
The function returns a tuple holding two integer values
"""
_upp = self.__units_per_pixel
_xp = int((xc - self.__xmin)/_upp)
_yp = int((self.__ymax - yc)/_upp)
return _xp, _yp
#------------------------------------------------------------------
def getColor(self, c):
"""Return an allocated color for a given Color object.
getColor(c)
Argument 'c' must be a Color object. This method will return an
allocated color.
"""
if not isinstance(c, Color):
raise TypeError, "Invalid Color object: " + `type(c)`
_color = globals.gtkcolors.get(c)
if _color is None:
# _r = int(round(65535.0 * (c.r/255.0)))
# _g = int(round(65535.0 * (c.g/255.0)))
# _b = int(round(65535.0 * (c.b/255.0)))
# _color = self.__da.get_colormap().alloc_color(_r, _g, _b)
_color = self.__da.get_colormap().alloc_color(str(c))
globals.gtkcolors[c] = _color
return _color
#------------------------------------------------------------------
def fitImage(self):
"""Redraw the image so all entities are visible in the window.
fitImage()
"""
_fw = float(self.__disp_width)
_fh = float(self.__disp_height)
_xmin, _ymin, _xmax, _ymax = self.__image.getExtents()
_xdiff = abs(_xmax - _xmin)
_ydiff = abs(_ymax - _ymin)
_xmid = (_xmin + _xmax)/2.0
_ymid = (_ymin + _ymax)/2.0
_xs = _xdiff/_fw
_ys = _ydiff/_fh
if _xs > _ys:
_scale = _xs * 1.05 # make it a little larger
else:
_scale = _ys * 1.05 # make it a little larger
_xm = _xmid - (_fw/2.0) * _scale
_ym = _ymid - (_fh/2.0) * _scale
self.setView(_xm, _ym, _scale)
#------------------------------------------------------------------
def refresh(self):
"""This method does a screen refresh.
refresh()
If entities in the drawing have been added, removed, or
modified, use the redraw() method.
"""
_da = self.__da
if (_da.flags() & gtk.MAPPED):
# print "refreshing ..."
_gc = _da.get_style().fg_gc[gtk.STATE_NORMAL]
_gc.set_function(gtk.gdk.COPY)
_da.queue_draw()
#------------------------------------------------------------------
def redraw(self):
"""
This method draws all the objects visible in the window.
"""
_da = self.__da
if (_da.flags() & gtk.MAPPED):
if _debug:
print "Redrawing image"
_xmin = self.__xmin
_ymin = self.__ymin
_xmax = self.__xmax
_ymax = self.__ymax
_gc = _da.get_style().fg_gc[gtk.STATE_NORMAL]
self.__pixmap.draw_rectangle(_gc, True, 0, 0,
self.__disp_width, self.__disp_height)
_active_layer = self.__image.getActiveLayer()
_layers = [self.__image.getTopLayer()]
while (len(_layers)):
_layer = _layers.pop()
if _layer is not _active_layer:
self.drawLayer(_layer)
_layers.extend(_layer.getSublayers())
self.drawLayer(_active_layer)
#
# redraw selected entities
#
_color = Color('#ff7733')
for _obj in self.__image.getSelectedObjects(False):
_obj.draw(self, _color)
self.refresh()
#------------------------------------------------------------------
def drawLayer(self, l):
if not isinstance(l, Layer):
raise TypeError, "Invalid layer type: " + `type(l)`
if l.getParent() is not self.__image:
raise ValueError, "Layer not found in Image"
if l.isVisible():
_col = self.__image.getOption('INACTIVE_LAYER_COLOR')
if l is self.__image.getActiveLayer():
_col = None
_cobjs = []
_objs = []
_pts = []
for _obj in l.objsInRegion(self.__xmin, self.__ymin, self.__xmax, self.__ymax):
if _obj.isVisible():
if isinstance(_obj, Point):
_pts.append(_obj)
elif isinstance(_obj, ConstructionObject):
_cobjs.append(_obj)
else:
_objs.append(_obj)
for _obj in _cobjs:
_obj.draw(self, _col)
for _obj in _pts:
_obj.draw(self, _col)
for _obj in _objs:
_obj.draw(self, _col)
#------------------------------------------------------------------
def ZoomIn(self,scaleFactor=None):
_xmin, _ymin, _xmax, _ymax = self.getView()
if(scaleFactor==None):
_scale = self.getUnitsPerPixel()
else:
_scale=scaleFactor
_xdiff = abs(_xmax - _xmin)
_ydiff = abs(_ymax - _ymin)
_xmin = (_xmin + _xmax)/2.0 - _xdiff/4.0
_ymin = (_ymin + _ymax)/2.0 - _ydiff/4.0
self.setView(_xmin, _ymin, (_scale/2))
#------------------------------------------------------------------
def ZoomOut(self,scaleFactor=None):
_xmin, _ymin, _xmax, _ymax = self.getView()
if(scaleFactor==None):
_scale = self.getUnitsPerPixel()
else:
_scale=scaleFactor
_xdiff = abs(_xmax - _xmin)
_ydiff = abs(_ymax - _ymin)
_xmin = (_xmin + _xmax)/2.0 - _xdiff
_ymin = (_ymin + _ymax)/2.0 - _ydiff
self.setView(_xmin, _ymin, (_scale * 2))
#------------------------------------------------------------------
def reset(self):
"""
Set the image to an initial drawing state.
"""
_tool = self.__image.getTool()
if _tool is None:
#
# If _tool is None, deselect any selected objects in view.
# This way, if you are currently using a tool, then the
# first time you hit escape, you just clear the tool.
# The second time clears all selections.
debug_print("Entered reset")
if _tool is None:
debug_print(".....This is second time to be in reset")
self.__image.clearSelectedObjects()
self.__image.setTool()
self.redraw()
self.setPrompt(_('Enter command'))
#
# Entity drawing operations
#
def __drawObject(self, obj, col=None):
# print "__drawObject()"
_col = col
if self.__xmin is None:
return
_xmin, _ymin, _xmax, _ymax = self.getView()
if obj.inRegion(_xmin, _ymin, _xmax, _ymax):
_image = self.__image
if _col is None:
if obj.getParent() is not _image.getActiveLayer():
_col = _image.getOption('INACTIVE_LAYER_COLOR')
obj.draw(self, _col)
self.__refresh = True
def __eraseObject(self, obj):
# print "__eraseObject()"
_xmin, _ymin, _xmax, _ymax = self.getView()
if self.__xmin is None:
return
if obj.inRegion(_xmin, _ymin, _xmax, _ymax):
obj.erase(self)
self.__refresh = True
def __imageAddedChild(self, obj, *args):
# print "__imageAddedChild()"
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_layer = args[0]
if not isinstance(_layer, Layer):
raise TypeError, "Unexpected child type: " + `type(_layer)`
_layer.connect('added_child', self.__layerAddedChild)
_layer.connect('removed_child', self.__layerRemovedChild)
def __layerAddedChild(self, obj, *args):
# print "__layerAddedChild()"
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_child = args[0] # need some verification test here ...
_child.connect('refresh', self.__refreshObject)
_child.connect('change_pending', self.__objChangePending)
_child.connect('change_complete', self.__objChangeComplete)
if _child.isVisible() and obj.isVisible():
self.__drawObject(_child)
def __imageRemovedChild(self, obj, *args):
# print "__imageRemovedChild()"
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_layer = args[0]
if not isinstance(_layer, Layer):
raise TypeError, "Unexpected child type: " + `type(_layer)`
_layer.disconnect(self)
def __layerRemovedChild(self, obj, *args):
# print "__layerRemovedChild()"
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_child = args[0] # need some verification test here ...
if _child.isVisible() and obj.isVisible():
self.__eraseObject(_child)
_child.disconnect(self)
def __groupActionStarted(self, obj, *args):
# print "__groupActionStarted()"
self.__refresh = False
def __groupActionEnded(self, obj, *args):
# print "__groupActionEnded()"
if self.__refresh:
self.refresh()
else:
self.__refresh = True
def __imageUnitsChanged(self, obj, *args):
# print "__imageUnitsChanged()"
self.redraw()
def __imageToolChanged(self, obj, *args):
_tool = self.__image.getTool()
if _tool is not None:
_init = GTKImage.__inittool.get(type(_tool))
if _init is not None:
_init(self)
def __objChangePending(self, obj, *args):
# print "__objChangePending()" + `obj`
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_change = args[0]
if (obj.isVisible() and
obj.getParent().isVisible() and
_change != 'added_user' and
_change != 'removed_user'):
self.__eraseObject(obj)
def __objChangeComplete(self, obj, *args):
# print "__objChangeComplete()" + `obj`
if obj.isVisible() and obj.getParent().isVisible():
self.__drawObject(obj)
def __refreshObject(self, obj, *args):
# print "__refreshObject()"
_col = None
if not obj.isVisible() or not obj.getParent().isVisible():
_col = self.__image.getOption('BACKGROUND_COLOR')
self.__drawObject(obj, _col)
#++ Matteo Boscolo
def __Move(self, widget, event):
"""
set the Global Variable for controlling the zoom and moving
of the drawing
"""
if(self.StopMove):
return
_type = event.type
_button = event.button
if(_button==3):
if(_type==4):
self.__activeX=event.x
self.__activeY=event.y
self.__StartMoving = True
if(_type==7):
self.__StartMoving = False
if(_button==2):
if(_type==4):
self.__StartZooming = True
if(_type==7):
self.__StartZooming= False
def __MakeMove(self, widget, event):
if(self.__StartZooming):
ActiveScale = self.getUnitsPerPixel()
midX=abs(self.__xmin-self.__xmax)/2
midY=abs(self.__ymin-self.__ymax)/2
if(self.__activeY>event.y):
ActiveScale=ActiveScale*1.05
#self.setView(midX,midY,ActiveScale)
self.ZoomScale(ActiveScale)
elif(self.__activeYxTo):
self.__xmin=self.__xmin+deltaX
self.__xmax=self.__xmax+deltaX
else:
self.__xmin=self.__xmin-deltaX
self.__xmax=self.__xmax-deltaX
if(yFrom>yTo):
self.__ymin=self.__ymin-deltaY
self.__ymax=self.__ymax-deltaY
else:
self.__ymin=self.__ymin+deltaY
self.__ymax=self.__ymax+deltaY
self.redraw()
def ZoomScale(self,scale):
"""
Make a drawing zoom of the scale quantity
"""
_fw = float(self.__disp_width)
_fh = float(self.__disp_height)
_xdiff = abs(self.__xmax-self.__xmin)
_ydiff = abs(self.__ymax-self.__ymin)
_xmid = (self.__xmin + self.__xmax)/2.0
_ymid = (self.__ymin + self.__ymax)/2.0
_xm = _xmid - (_fw/2.0) * scale
_ym = _ymid - (_fh/2.0) * scale
self.setView(_xm, _ym, scale)
def StartPanImage(self):
"""
Start Pan Image
"""
self.StopMove=True
self.__StartMoving=True
def StopPanImage(self):
"""
Stop Pan Operation
"""
self.StopMove=False
self.__StartMoving=False
def isPan(self):
"""
Return the active pan status
"""
return self.StopMove
def setCursor(self,drwArea,snObject):
"""
active Snap cursor shape
"""
_win=drwArea.get_parent_window()
if snObject is None or snObject.entity is None:
_snapCursor=gtk.gdk.Cursor(gtk.gdk.TOP_LEFT_ARROW)
else:
_snapCursor=snObject.cursor
_win.set_cursor(_snapCursor)
def __ActiveSnapEvent(self,drwArea,event):
"""
Snap Event
"""
cursor=None
if(self._activateSnap):
_sobj=self.__image.snapProvider.getSnap(self.__tolerance,globals.snapOption)
self.setCursor(drwArea,_sobj)
else:
self.setCursor(drwArea,None)
def activateSnap(self):
"""
Activate the snap functionality
"""
self._activateSnap=True
#-- Matteo Boscolo
#------------------------------------------------------------------
def debug_print(string):
if _debug is True:
print "SDB Debug: " + string
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkmenus.py 0000644 0001750 0001750 00000320134 11307674165 021613 0 ustar matteo matteo #
# Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 Art Haas
#
# This file is part of PythonCAD.
#
# PythonCAD is free software; you can redistribute it and/or modify
# it under the termscl_bo 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
#
#
################################################################
#
# This file contains the GTK Menu building code
#
################################################################
import os
import stat
import sys
_debug = False
if _debug:
try:
import gc
gc.set_debug(gc.DEBUG_LEAK)
except ImportError:
pass
import pygtk
pygtk.require('2.0')
import gtk
import gtk.keysyms
from PythonCAD.Interface.Gtk.gtkimage import GTKImage
from PythonCAD.Interface.Gtk import gtkentities
from PythonCAD.Interface.Gtk import gtkprefs
from PythonCAD.Interface.Gtk import gtkmodify
from PythonCAD.Interface.Gtk import gtktext
from PythonCAD.Interface.Gtk import gtkprinting
from PythonCAD.Interface.Gtk import gtkactions
from PythonCAD.Generic import globals
from PythonCAD.Generic import fileio
from PythonCAD.Generic import imageio
from PythonCAD.Generic import tools
from PythonCAD.Generic import plotfile
from PythonCAD.Generic import text
from PythonCAD.Generic import graphicobject
from PythonCAD.Generic import dimension
from PythonCAD.Generic import extFormat
from PythonCAD.Generic.image import Image
from PythonCAD.Interface.Gtk import gtkdimprefs
from PythonCAD.Interface.Gtk import gtktextprefs
from PythonCAD.Interface.Gtk import gtkstyleprefs
from PythonCAD.Interface.Gtk import gtkDialog
if not hasattr(gtk, 'Action'):
gtk.Action = gtkactions.stdAction
gtk.ActionGroup = gtkactions.stdActionGroup
select_menu = [
('SelectAllPoints', 'point',_('_Points')),
('SelectAllSegments','segment',_('_Segments')),
('SelectAllCircles','circle',_('_Circles')),
('SelectAllArcs','arc',_('_Arcs')),
('SelectAllLeaders','leader',_('_Leaders')),
('SelectAllPolylines','polyline',_('_Polylines')),
('SelectAllChamfers','chamfer',_('Cha_mfers')),
('SelectAllFillets','fillet',_('_Fillets')),
(None, None, None),
('SelectAllHCLines','hcline',_('_HCLines')),
('SelectAllVCLines','vcline',_('_VCLines')),
('SelectAllACLines','acline',_('_ACLines')),
('SelectAllCLines','cline',_('C_Lines')),
('SelectAllCCircles','ccircle',_('CCircles')),
(None, None, None),
('SelectAllTextBlocks','textblock',_('TextBlocks')),
(None, None, None),
('SelectAllLDims','linear_dimension',_('Linear Dim.')),
('SelectAllHDims','horizontal_dimension',_('Horiz. Dim.')),
('SelectAllVDims','vertical_dimension',_('Vert. Dim.')),
('SelectAllRDims','radial_dimension',_('Radial Dim.')),
('SelectAllADims','angular_dimension',_('Angular Dim.')),
]
#############################################################################
#
# callbacks for the menu items
#
#############################################################################
def file_new_cb(menuitem, data=None):
_image = Image()
_gtkimage = GTKImage(_image)
_background = globals.prefs['BACKGROUND_COLOR']
_image.setOption('BACKGROUND_COLOR', _background)
globals.imagelist.append(_image)
_gtkimage.window.show_all()
#------------------------------------------------------------
def file_open_cb(menuitem, gtkimage):
_open = False
_fname = None
_dialog = gtk.FileChooserDialog(title=_('Open File ...'),
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_OK),
action=gtk.FILE_CHOOSER_ACTION_OPEN)
while not _open:
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_fname = _dialog.get_filename()
if os.path.isdir(_fname):
_fname += "/"
_dialog.set_filename(_fname)
_response = _dialog.run()
else:
_open = True
else:
break
_dialog.destroy()
if _open:
_image = Image()
try:
_handle = fileio.CompFile(_fname, "r")
try:
imageio.load_image(_image, _handle)
finally:
_handle.close()
except (IOError, OSError), e:
_errmsg = "Error opening '%s' : %s'" % (_fname, e)
_error_dialog(gtkimage, _errmsg)
return
except StandardError, e:
_errmsg = "Non-system error opening '%s' : %s'" % (_fname, e)
_error_dialog(gtkimage, _errmsg)
return
globals.imagelist.append(_image)
_image.setFilename(_fname)
_gtkimage = GTKImage(_image)
_window = _gtkimage.getWindow()
_window.set_title(os.path.basename(_fname))
_window.show_all()
_gtkimage.fitImage()
#------------------------------------------------------------
def file_close_cb(menuitem, gtkimage):
"""
Close the application
"""
for _i in xrange(len(globals.imagelist)):
_image = globals.imagelist[_i]
if _image is gtkimage.image:
if _image.isSaved()==False:
print "ask for saving" #implement it matteo boscolo
_log = _image.getLog()
if _log is not None:
_log.detatch()
del globals.imagelist[_i]
gtkimage.window.destroy()
if not len(globals.imagelist):
gtk.main_quit()
break
#------------------------------------------------------------
def _error_dialog(gtkimage, errmsg):
_window = gtkimage.getWindow()
_dialog = gtk.MessageDialog( _window,
gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_CLOSE,
errmsg)
_dialog.run()
_dialog.destroy()
#------------------------------------------------------------
def _save_file(gtkimage, filename):
_image = gtkimage.getImage()
_image.save()
#------------------------------------------------------------
def _writecopy(src, dst):
if sys.platform == 'win32':
_rmode = 'rb'
_wmode = 'wb'
else:
_rmode = 'r'
_wmode = 'w'
_from = file(src, _rmode)
try:
_to = file(dst, _wmode)
try:
while True:
_data = _from.read(8192)
if _data == '':
break
_to.write(_data)
finally:
_to.close()
finally:
_from.close()
#------------------------------------------------------------
def _save_file_by_copy(gtkimage, filename):
_image = gtkimage.getImage()
_abs = os.path.abspath(filename)
_bname = os.path.basename(_abs)
if _bname.endswith('.gz'):
_bname = _bname[:-3]
_newfile = _abs + '.new'
_handle = fileio.CompFile(_newfile, "w", truename=_bname)
try:
imageio.save_image(_image, _handle)
finally:
_handle.close()
_backup = _abs + '~'
if os.path.exists(_abs):
_writecopy(_abs, _backup)
try:
_writecopy(_newfile, _abs)
except:
_writecopy(_backup, _abs)
raise
os.unlink(_newfile)
if _image.getFilename() is None:
_image.setFilename(_abs)
#------------------------------------------------------------
def _get_filename_and_save(gtkimage, fname=None):
_window = gtkimage.getWindow()
_fname = fname
if _fname is None:
_fname = _window.get_title()
_dialog = gtk.FileChooserDialog(title=_('Save As ...'),
buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_OK),
action=gtk.FILE_CHOOSER_ACTION_SAVE)
_dialog.set_filename(_fname)
_response = _dialog.run()
_save = False
if _response == gtk.RESPONSE_OK:
_save = True
_fname = _dialog.get_filename()
if _fname == "":
_fname = 'Untitled.xml'
if not _fname.endswith('.xml.gz'):
if not _fname.endswith('.xml'):
_fname = _fname + '.xml'
#
# if the filename already exists see that the user
# really wants to overwrite it ...
#
# test for the filename + '.gz'
#
if _fname.endswith('.xml.gz'):
_gzfile = _fname
else:
_gzfile = _fname + '.gz'
if os.path.exists(_gzfile):
_save = False
_dialog2 = gtk.Dialog(_('Overwrite Existing File'), _window,
gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 10)
_hbox.set_border_width(10)
_dialog2.vbox.pack_start(_hbox, False, False, 0)
_stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_QUESTION,
gtk.ICON_SIZE_DIALOG)
_hbox.pack_start(_stock, False, False, 0)
_label = gtk.Label(_('File already exists. Delete it?'))
_hbox.pack_start(_label, False, False, 0)
_dialog2.show_all()
_response = _dialog2.run()
if _response == gtk.RESPONSE_OK:
_save = True
_dialog2.destroy()
_dialog.destroy()
if _save:
# print "name: " + _gzfile
gtkimage.image.setFilename(_gzfile)
_window.set_title(os.path.basename(_gzfile))
try:
_save_file(gtkimage, _gzfile)
except (IOError, OSError), _e:
_errmsg = "Error saving '%s' : %s'" % (_gzfile, _e)
_error_dialog(gtkimage, _errmsg)
except StandardError, _e:
_errmsg = "Non-system error saving '%s' : %s'" % (_gzfile, _e)
_error_dialog(gtkimage, _errmsg)
#------------------------------------------------------------
def file_save_cb(menuitem, gtkimage):
_fname = gtkimage.image.getFilename()
if _fname is None:
_get_filename_and_save(gtkimage)
else:
try:
_save_file(gtkimage, _fname)
except (IOError, OSError), _e:
_errmsg = "Error saving '%s' : %s'" % (_fname, _e)
_error_dialog(gtkimage, _errmsg)
except StandardError, _e:
_errmsg = "Non-system error saving '%s' : %s'" % (_fname, _e)
_error_dialog(gtkimage, _errmsg)
#------------------------------------------------------------
def file_save_as_cb(menuitem, gtkimage):
_fname = gtkimage.image.getFilename()
if _fname is None:
_fname = gtkimage.getWindow().get_title()
_get_filename_and_save(gtkimage, _fname)
#------------------------------------------------------------
def file_save_layer_cb(menuitem, gtkimage):
# print "called file_save_layer_cb()"
active = gtkimage.image.getActiveLayer()
layer_name = active.getName()
dialog = gtk.FileSelection("Save Layer As ...")
dialog.set_transient_for(gtkimage.getWindow())
dialog.set_filename(layer_name)
response = dialog.run()
if response == gtk.RESPONSE_OK:
fname = dialog.get_filename()
print "Saving layer as '%s'" % fname
#
# fixme - add the layer saving code ...
#
dialog.destroy()
#------------------------------------------------------------
def file_print_screen_cb(menuitem, gtkimage):
_plot = plotfile.Plot(gtkimage.image)
_xmin, _ymin, _xmax, _ymax = gtkimage.getView()
_plot.setBounds(_xmin, _ymin, _xmax, _ymax)
gtkprinting.print_dialog(gtkimage, _plot)
#------------------------------------------------------------
def file_print_cb(menuitem, gtkimage):
_tool = tools.PlotTool()
gtkimage.getImage().setTool(_tool)
#------------------------------------------------------------
def file_quit_cb(menuitem, gtkimage):
_image=gtkimage.getImage()
if _image.isSaved()==False:
_res=gtkDialog._yesno_dialog(gtkimage,"File Unsaved, Wold You Like To Save ?")
if gtk.RESPONSE_ACCEPT == _res:
file_save_cb(None, gtkimage)
gtk.main_quit()
#------------------------------------------------------------
def _select_all_cb(menuitem, gtkimage):
_group = gtkimage.getGroup('Edit')
if _group is not None:
_layer = gtkimage.image.getActiveLayer()
for _action, _entity, _menuitem in select_menu:
if _action is None: continue
_act = _group.get_action(_action)
if _act is not None:
_act.set_property('sensitive',
_layer.getEntityCount(_entity) > 0)
#------------------------------------------------------------
def edit_undo_cb(menuitem, gtkimage):
gtkimage.image.doUndo()
gtkimage.redraw()
#------------------------------------------------------------
def edit_redo_cb(menuitem, gtkimage):
gtkimage.image.doRedo()
gtkimage.redraw()
#------------------------------------------------------------
def edit_copy_cb(menuitem, gtkimage):
for _obj in gtkimage.image.getSelectedObjects():
if _obj.getParent() is not None:
globals.selectobj.storeObject(_obj)
#------------------------------------------------------------
def edit_cut_cb(menuitem, gtkimage):
_image = gtkimage.getImage()
_image.startAction()
try:
for _obj in _image.getSelectedObjects():
globals.selectobj.storeObject(_obj)
#
# check that the object parent is not None - if it
# is then the object was deleted as a result of the
# deletion of an earlier object (i.e. dimension)
#
_layer = _obj.getParent()
if _layer is not None:
_layer.delObject(_obj)
finally:
_image.endAction()
#------------------------------------------------------------
def edit_paste_cb(menuitem, gtkimage):
_tool = tools.PasteTool()
gtkimage.getImage().setTool(_tool)
#------------------------------------------------------------
def edit_select_cb(menuitem, gtkimage):
_tool = tools.SelectTool()
gtkimage.getImage().setTool(_tool)
#------------------------------------------------------------
def edit_deselect_cb(menuitem, gtkimage):
_tool = tools.DeselectTool()
gtkimage.getImage().setTool(_tool)
#------------------------------------------------------------
def select_all_objects_cb(menuitem, ge):
_gtkimage, _entity = ge
_image = _gtkimage.getImage()
_active_layer = _image.getActiveLayer()
_image.sendMessage('group_action_started')
try:
for _obj in _active_layer.getLayerEntities(_entity):
_image.selectObject(_obj)
finally:
_image.sendMessage('group_action_ended')
def units_cb(menuitem, gtkimage):
gtkentities.set_units_dialog(gtkimage)
def toggle_cb(menuitem, gtkimage):
gtkentities.set_toggle_dialog(gtkimage)
def prefs_cb(menuitem, gtkimage):
gtkprefs.prefs_dialog(gtkimage)
def colors_cb(menuitem, gtkimage):
gtkentities.set_colors_dialog(gtkimage)
def sizes_cb(menuitem, gtkimage):
gtkentities.set_sizes_dialog(gtkimage)
def style_cb(menuitem, gtkimage):
gtkstyleprefs.style_dialog(gtkimage, globals.prefs['STYLES'],
globals.prefs['LINETYPES'])
def textstyle_cb(menuitem, gtkimage):
gtkimage.activateSnap()
gtktextprefs.textstyle_dialog(gtkimage, globals.prefs['TEXTSTYLES'])
def dimstyle_cb(menuitem, gtkimage):
gtkimage.activateSnap()
gtkdimprefs.dimstyle_dialog(gtkimage, globals.prefs['DIMSTYLES'])
def draw_point_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.PointTool()
gtkimage.getImage().setTool(_tool)
def draw_segment_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.SegmentTool()
gtkimage.getImage().setTool(_tool)
def draw_rectangle_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.RectangleTool()
gtkimage.getImage().setTool(_tool)
def draw_circle_center_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.CircleTool()
gtkimage.getImage().setTool(_tool)
def draw_circle_tp_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.TwoPointCircleTool()
gtkimage.getImage().setTool(_tool)
def draw_arc_center_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.ArcTool()
gtkimage.getImage().setTool(_tool)
def draw_hcl_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.HCLineTool()
gtkimage.getImage().setTool(_tool)
def draw_vcl_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.VCLineTool()
gtkimage.getImage().setTool(_tool)
def draw_acl_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.ACLineTool()
gtkimage.getImage().setTool(_tool)
def draw_cl_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.CLineTool()
gtkimage.getImage().setTool(_tool)
def draw_perpendicular_cline_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.PerpendicularCLineTool()
gtkimage.getImage().setTool(_tool)
def draw_tangent_cline_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.TangentCLineTool()
gtkimage.getImage().setTool(_tool)
def draw_tangent_two_ccircles_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.CCircleTangentLineTool()
gtkimage.getImage().setTool(_tool)
def draw_poffset_cline_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.ParallelOffsetTool()
gtkimage.getImage().setTool(_tool)
def draw_ccirc_cp_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.CCircleTool()
gtkimage.getImage().setTool(_tool)
def draw_ccirc_tp_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.TwoPointCCircleTool()
gtkimage.getImage().setTool(_tool)
def draw_tangent_single_conobj_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.TangentCCircleTool()
gtkimage.getImage().setTool(_tool)
def draw_tangent_two_conobjs_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.TwoPointTangentCCircleTool()
gtkimage.getImage().setTool(_tool)
def draw_chamfer_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.ChamferTool()
gtkimage.getImage().setTool(_tool)
def draw_fillet_cb(menuitem, gtkimage):
"""
Start Point fillet comand
"""
gtkimage.activateSnap()
_tool = tools.FilletTool()
gtkimage.getImage().setTool(_tool)
def draw_fillet_two_cb(menuitem, gtkimage):
"""
Start two line fillet comand
"""
_tool = tools.FilletTwoLineTool()
gtkimage.getImage().setTool(_tool)
def draw_leader_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.LeaderTool()
gtkimage.getImage().setTool(_tool)
def draw_polyline_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.PolylineTool()
gtkimage.getImage().setTool(_tool)
def _get_polygon_side_count(gtkimage):
gtkimage.activateSnap()
_sides = 0
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Polygon Sides'), _window,
gtk.DIALOG_MODAL,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 10)
_hbox.set_border_width(10)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_stock = gtk.image_new_from_stock(gtk.STOCK_DIALOG_QUESTION,
gtk.ICON_SIZE_DIALOG)
_hbox.pack_start(_stock, False, False, 0)
_label = gtk.Label(_('Number of sides:'))
_hbox.pack_start(_label, False, False, 0)
_adj = gtk.Adjustment(3, 3, 3600, 1, 1, 1) # arbitrary max ...
_sb = gtk.SpinButton(_adj)
_sb.set_numeric(True)
_hbox.pack_start(_sb, True, True, 0)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_sides = _sb.get_value()
_dialog.destroy()
return _sides
def draw_polygon_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_sides = _get_polygon_side_count(gtkimage)
if _sides > 0:
_tool = tools.PolygonTool()
_tool.setSideCount(_sides)
gtkimage.getImage().setTool(_tool)
def draw_ext_polygon_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_sides = _get_polygon_side_count(gtkimage)
if _sides > 0:
_tool = tools.PolygonTool()
_tool.setExternal()
_tool.setSideCount(_sides)
gtkimage.getImage().setTool(_tool)
def draw_set_style_cb(menuitem, gtkimage):
gtkentities.set_active_style(gtkimage)
def draw_set_linetype_cb(menuitem, gtkimage):
gtkentities.set_active_linetype(gtkimage)
def draw_set_color_cb(menuitem, gtkimage):
gtkentities.set_active_color(gtkimage)
def draw_set_thickness_cb(menuitem, gtkimage):
gtkentities.set_line_thickness(gtkimage)
def draw_text_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_text = gtktext.text_add_dialog(gtkimage)
if _text is not None:
_tool = tools.TextTool()
_tool.setText(_text)
gtkimage.getImage().setTool(_tool)
def move_horizontal_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.HorizontalMoveTool()
gtkimage.getImage().setTool(_tool)
def move_vertical_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.VerticalMoveTool()
gtkimage.getImage().setTool(_tool)
def move_twopoint_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.MoveTool()
gtkimage.getImage().setTool(_tool)
def stretch_horiz_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.HorizontalStretchTool()
gtkimage.getImage().setTool(_tool)
def stretch_vert_cb(menuitem, gtkimage):
_tool = tools.VerticalStretchTool()
gtkimage.getImage().setTool(_tool)
def stretch_twopoint_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.StretchTool()
gtkimage.getImage().setTool(_tool)
def transfer_object_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.TransferTool()
gtkimage.getImage().setTool(_tool)
def rotate_object_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.RotateTool()
gtkimage.getImage().setTool(_tool)
def split_object_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.SplitTool()
gtkimage.getImage().setTool(_tool)
def mirror_object_cb(menuitem, gtkimage):
gtkimage.activateSnap()
_tool = tools.MirrorTool()
gtkimage.getImage().setTool(_tool)
def delete_cb(menuitem, gtkimage):
_tool = tools.DeleteTool()
gtkimage.getImage().setTool(_tool)
def change_style_cb(menuitem, gtkimage):
_st = gtkmodify.change_style_dialog(gtkimage)
if _st is not None:
_tool = tools.GraphicObjectTool()
_tool.setAttribute('setStyle')
_tool.setValue(_st)
_tool.setObjtype(graphicobject.GraphicObject)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_style_init(gtkimage)
def change_color_cb(menuitem, gtkimage):
_color = gtkmodify.change_color_dialog(gtkimage)
if _color is not None:
_tool = tools.GraphicObjectTool()
_tool.setAttribute('setColor')
_tool.setValue(_color)
_tool.setObjtype(graphicobject.GraphicObject)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_color_init(gtkimage)
def change_linetype_cb(menuitem, gtkimage):
_lt = gtkmodify.change_linetype_dialog(gtkimage)
if _lt is not None:
_tool = tools.GraphicObjectTool()
_tool.setAttribute('setLinetype')
_tool.setValue(_lt)
_tool.setObjtype(graphicobject.GraphicObject)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_linetype_init(gtkimage)
def change_thickness_cb(menuitem, gtkimage):
_t = gtkmodify.change_thickness_dialog(gtkimage)
if _t is not None:
_tool = tools.GraphicObjectTool()
_tool.setAttribute('setThickness')
_tool.setValue(_t)
_tool.setObjtype(graphicobject.GraphicObject)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_thickness_init(gtkimage)
def change_textblock_style_cb(menuitem, gtkimage):
_st = gtkmodify.change_textblock_style_dialog(gtkimage, 'FONT_STYLE')
if _st is not None:
_tool = tools.TextTool()
_tool.setAttribute('setStyle')
_tool.setValue(_st)
_tool.setObjtype(text.TextBlock)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_textblock_style_init(gtkimage)
def change_textblock_weight_cb(menuitem, gtkimage):
_w = gtkmodify.change_textblock_weight_dialog(gtkimage, 'FONT_WEIGHT')
if _w is not None:
_tool = tools.TextTool()
_tool.setAttribute('setWeight')
_tool.setValue(_w)
_tool.setObjtype(text.TextBlock)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_textblock_weight_init(gtkimage)
def change_textblock_alignment_cb(menuitem, gtkimage):
_align = gtkmodify.change_textblock_alignment_dialog(gtkimage, 'TEXT_ALIGNMENT')
if _align is not None:
_tool = tools.TextTool()
_tool.setAttribute('setAlignment')
_tool.setValue(_align)
_tool.setObjtype(text.TextBlock)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_textblock_alignment_init(gtkimage)
def change_textblock_size_cb(menuitem, gtkimage):
_size = gtkmodify.change_textblock_size_dialog(gtkimage, 'TEXT_SIZE')
if _size is not None:
_tool = tools.TextTool()
_tool.setAttribute('setSize')
_tool.setValue(_size)
_tool.setObjtype(text.TextBlock)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_textblock_size_init(gtkimage)
def change_textblock_family_cb(menuitem, gtkimage):
_family = gtkmodify.change_textblock_family_dialog(gtkimage, 'FONT_FAMILY')
if _family is not None:
_tool = tools.TextTool()
_tool.setAttribute('setFamily')
_tool.setValue(_family)
_tool.setObjtype(text.TextBlock)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_textblock_family_init(gtkimage)
def change_textblock_color_cb(menuitem, gtkimage):
_color = gtkmodify.change_textblock_color_dialog(gtkimage, 'FONT_COLOR')
if _color is not None:
_tool = tools.TextTool()
_tool.setAttribute('setColor')
_tool.setValue(_color)
_tool.setObjtype(text.TextBlock)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_textblock_color_init(gtkimage)
def change_dim_endpoint_cb(menuitem, gtkimage):
_et = gtkmodify.change_dim_endpoint_dialog(gtkimage)
if _et is not None:
_tool = tools.EditDimensionTool()
_tool.setAttribute('setEndpointType')
_tool.setValue(_et)
_tool.setObjtype(dimension.Dimension)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dim_endpoint_init(gtkimage)
def change_dim_endpoint_size_cb(menuitem, gtkimage):
_es = gtkmodify.change_dim_endpoint_size_dialog(gtkimage)
if _es is not None:
_tool = tools.EditDimensionTool()
_tool.setAttribute('setEndpointSize')
_tool.setValue(_es)
_tool.setObjtype(dimension.Dimension)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dim_endpoint_size_init(gtkimage)
def change_dim_offset_cb(menuitem, gtkimage):
_offset = gtkmodify.change_dim_offset_dialog(gtkimage)
if _offset is not None:
_tool = tools.EditDimensionTool()
_tool.setAttribute('setOffset')
_tool.setValue(_offset)
_tool.setObjtype(dimension.Dimension)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dim_offset_init(gtkimage)
def change_dim_extension_cb(menuitem, gtkimage):
_ext = gtkmodify.change_dim_extension_dialog(gtkimage)
if _ext is not None:
_tool = tools.EditDimensionTool()
_tool.setAttribute('setExtension')
_tool.setValue(_ext)
_tool.setObjtype(dimension.Dimension)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dim_extension_init(gtkimage)
def change_dim_dual_mode_cb(menuitem, gtkimage):
_ddm = gtkmodify.change_dim_dual_mode_dialog(gtkimage)
if _ddm is not None:
_tool = tools.EditDimensionTool()
_tool.setAttribute('setDualDimMode')
_tool.setValue(_ddm)
_tool.setObjtype(dimension.Dimension)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dim_dual_mode_init(gtkimage)
def change_dim_dual_mode_offset_cb(menuitem, gtkimage):
_dmo = gtkmodify.change_dim_dual_mode_offset_dialog(gtkimage)
if _dmo is not None:
_tool = tools.EditDimensionTool()
_tool.setAttribute('setDualModeOffset')
_tool.setValue(_dmo)
_tool.setObjtype(dimension.Dimension)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dim_dual_mode_offset_init(gtkimage)
def change_dim_thickness_cb(menuitem, gtkimage):
_t = gtkmodify.change_dim_thickness_dialog(gtkimage)
if _t is not None:
_tool = tools.EditDimensionTool()
_tool.setAttribute('setThickness')
_tool.setValue(_t)
_tool.setObjtype(dimension.Dimension)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dim_thickness_init(gtkimage)
def change_dim_color_cb(menuitem, gtkimage):
_color = gtkmodify.change_dim_color_dialog(gtkimage)
if _color is not None:
_tool = tools.EditDimensionTool()
_tool.setAttribute('setColor')
_tool.setValue(_color)
_tool.setObjtype(dimension.Dimension)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dim_color_init(gtkimage)
def _change_dimstring_style_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setStyle')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dimstr_style_init(gtkimage)
def change_dim_primary_style_cb(menuitem, gtkimage):
_st = gtkmodify.change_textblock_style_dialog(gtkimage, 'DIM_PRIMARY_FONT_STYLE')
if _st is not None:
_change_dimstring_style_cb(gtkimage, _st, True)
def change_dim_secondary_style_cb(menuitem, gtkimage):
_st = gtkmodify.change_textblock_style_dialog(gtkimage, 'DIM_SECONDARY_FONT_STYLE')
if _st is not None:
_change_dimstring_style_cb(gtkimage, _st, False)
def _change_dimstring_family_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setFamily')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dimstr_family_init(gtkimage)
def change_dim_primary_family_cb(menuitem, gtkimage):
_family = gtkmodify.change_textblock_family_dialog(gtkimage, 'DIM_PRIMARY_FONT_FAMILY')
if _family is not None:
_change_dimstring_family_cb(gtkimage, _family, True)
def change_dim_secondary_family_cb(menuitem, gtkimage):
_family = gtkmodify.change_textblock_family_dialog(gtkimage, 'DIM_SECONDARY_FONT_FAMILY')
if _family is not None:
_change_dimstring_family_cb(gtkimage, _family, False)
def _change_dimstring_weight_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setWeight')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dimstr_weight_init(gtkimage)
def change_dim_primary_weight_cb(menuitem, gtkimage):
_weight = gtkmodify.change_textblock_weight_dialog(gtkimage, 'DIM_PRIMARY_FONT_WEIGHT')
if _weight is not None:
_change_dimstring_weight_cb(gtkimage, _weight, True)
def change_dim_secondary_weight_cb(menuitem, gtkimage):
_weight = gtkmodify.change_textblock_weight_dialog(gtkimage, 'DIM_SECONDARY_FONT_WEIGHT')
if _weight is not None:
_change_dimstring_weight_cb(gtkimage, _weight, False)
def _change_dimstring_size_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setSize')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dimstr_size_init(gtkimage)
def change_dim_primary_size_cb(menuitem, gtkimage):
_size = gtkmodify.change_textblock_size_dialog(gtkimage, 'DIM_PRIMARY_TEXT_SIZE')
if _size is not None:
_change_dimstring_size_cb(gtkimage, _size, True)
def change_dim_secondary_size_cb(menuitem, gtkimage):
_size = gtkmodify.change_textblock_size_dialog(gtkimage, 'DIM_SECONDARY_TEXT_SIZE')
if _size is not None:
_change_dimstring_size_cb(gtkimage, _size, False)
def _change_dimstring_color_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setColor')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dimstr_color_init(gtkimage)
def change_dim_primary_color_cb(menuitem, gtkimage):
_color = gtkmodify.change_textblock_color_dialog(gtkimage, 'DIM_PRIMARY_FONT_COLOR')
if _color is not None:
_change_dimstring_color_cb(gtkimage, _color, True)
def change_dim_secondary_color_cb(menuitem, gtkimage):
_color = gtkmodify.change_textblock_color_dialog(gtkimage, 'DIM_SECONDARY_FONT_COLOR')
if _color is not None:
_change_dimstring_color_cb(gtkimage, _color, False)
def _change_dimstring_alignment_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setAlignment')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dimstr_alignment_init(gtkimage)
def change_dim_primary_alignment_cb(menuitem, gtkimage):
_align = gtkmodify.change_textblock_alignment_dialog(gtkimage, 'DIM_PRIMARY_TEXT_ALIGNMENT')
if _align is not None:
_change_dimstring_alignment_cb(gtkimage, _align, True)
def change_dim_secondary_alignment_cb(menuitem, gtkimage):
_align = gtkmodify.change_textblock_alignment_dialog(gtkimage, 'DIM_SECONDARY_TEXT_ALIGNMENT')
if _align is not None:
_change_dimstring_alignment_cb(gtkimage, _align, False)
def _change_dimstring_prefix_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setPrefix')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
def change_ldim_pds_prefix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_prefix_dialog(gtkimage, 'DIM_PRIMARY_PREFIX')
if _text is not None:
_change_dimstring_prefix_cb(gtkimage, _text, True)
gtkmodify.change_ldimstr_prefix_init(gtkimage)
def change_ldim_sds_prefix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_prefix_dialog(gtkimage, 'DIM_SECONDARY_PREFIX')
if _text is not None:
_change_dimstring_prefix_cb(gtkimage, _text, False)
gtkmodify.change_ldimstr_prefix_init(gtkimage)
def change_rdim_pds_prefix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_prefix_dialog(gtkimage, 'RADIAL_DIM_PRIMARY_PREFIX')
if _text is not None:
_change_dimstring_prefix_cb(gtkimage, _text, True)
gtkmodify.change_rdimstr_prefix_init(gtkimage)
def change_rdim_sds_prefix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_prefix_dialog(gtkimage, 'RADIAL_DIM_SECONDARY_PREFIX')
if _text is not None:
_change_dimstring_prefix_cb(gtkimage, _text, False)
gtkmodify.change_rdimstr_prefix_init(gtkimage)
def change_adim_pds_prefix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_prefix_dialog(gtkimage, 'ANGULAR_DIM_PRIMARY_PREFIX')
if _text is not None:
_change_dimstring_prefix_cb(gtkimage, _text, True)
gtkmodify.change_adimstr_prefix_init(gtkimage)
def change_adim_sds_prefix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_prefix_dialog(gtkimage, 'ANGULAR_DIM_SECONDARY_PREFIX')
if _text is not None:
_change_dimstring_prefix_cb(gtkimage, _text, False)
gtkmodify.change_adimstr_prefix_init(gtkimage)
def _change_dimstring_suffix_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setSuffix')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
def change_ldim_pds_suffix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_suffix_dialog(gtkimage, 'DIM_PRIMARY_SUFFIX')
if _text is not None:
_change_dimstring_suffix_cb(gtkimage, _text, True)
gtkmodify.change_ldimstr_suffix_init(gtkimage)
def change_ldim_sds_suffix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_suffix_dialog(gtkimage, 'DIM_SECONDARY_SUFFIX')
if _text is not None:
_change_dimstring_suffix_cb(gtkimage, _text, False)
gtkmodify.change_ldimstr_suffix_init(gtkimage)
def change_rdim_pds_suffix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_suffix_dialog(gtkimage, 'RADIAL_DIM_PRIMARY_SUFFIX')
if _text is not None:
_change_dimstring_suffix_cb(gtkimage, _text, True)
gtkmodify.change_rdimstr_suffix_init(gtkimage)
def change_rdim_sds_suffix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_suffix_dialog(gtkimage, 'RADIAL_DIM_SECONDARY_SUFFIX')
if _text is not None:
_change_dimstring_suffix_cb(gtkimage, _text, False)
gtkmodify.change_rdimstr_suffix_init(gtkimage)
def change_adim_pds_suffix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_suffix_dialog(gtkimage, 'ANGULAR_DIM_PRIMARY_SUFFIX')
if _text is not None:
_change_dimstring_suffix_cb(gtkimage, _text, True)
gtkmodify.change_adimstr_suffix_init(gtkimage)
def change_adim_sds_suffix_cb(menuitem, gtkimage):
_text = gtkmodify.change_dimstr_suffix_dialog(gtkimage, 'ANGULAR_DIM_SECONDARY_SUFFIX')
if _text is not None:
_change_dimstring_suffix_cb(gtkimage, _text, False)
gtkmodify.change_adimstr_suffix_init(gtkimage)
def _change_dimstring_precision_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setPrecision')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dimstr_precision_init(gtkimage)
def change_dim_primary_precision_cb(menuitem, gtkimage):
_prec = gtkmodify.change_dimstr_precision_dialog(gtkimage, 'DIM_PRIMARY_PRECISION')
if _prec is not None:
_change_dimstring_precision_cb(gtkimage, _prec, True)
def change_dim_secondary_precision_cb(menuitem, gtkimage):
_prec = gtkmodify.change_dimstr_precision_dialog(gtkimage, 'DIM_SECONDARY_PRECISION')
if _prec is not None:
_change_dimstring_precision_cb(gtkimage, _prec, False)
def _change_dimstring_units_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setUnits')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dimstr_units_init(gtkimage)
def change_dim_primary_units_cb(menuitem, gtkimage):
_unit = gtkmodify.change_dimstr_units_dialog(gtkimage, 'DIM_PRIMARY_UNITS')
if _unit is not None:
_change_dimstring_units_cb(gtkimage, _unit, True)
def change_dim_secondary_units_cb(menuitem, gtkimage):
_unit = gtkmodify.change_dimstr_units_dialog(gtkimage, 'DIM_SECONDARY_UNITS')
if _unit is not None:
_change_dimstring_units_cb(gtkimage, _unit, False)
def _change_dimstring_print_zero_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setPrintZero')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dimstr_print_zero_init(gtkimage)
def change_dim_primary_print_zero_cb(menuitem, gtkimage):
_flag = gtkmodify.change_dimstr_print_zero_dialog(gtkimage, 'DIM_PRIMARY_LEADING_ZERO')
if _flag is not None:
_change_dimstring_print_zero_cb(gtkimage, _flag, True)
def change_dim_secondary_print_zero_cb(menuitem, gtkimage):
_flag = gtkmodify.change_dimstr_print_zero_dialog(gtkimage, 'DIM_SECONDARY_LEADING_ZERO')
if _flag is not None:
_change_dimstring_print_zero_cb(gtkimage, _flag, False)
def _change_dimstring_print_decimal_cb(gtkimage, val, flag):
_tool = tools.EditDimStringTool()
_tool.setAttribute('setPrintDecimal')
_tool.setValue(val)
_tool.setPrimary(flag)
_tool.setObjtype(dimension.DimString)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_dimstr_print_decimal_init(gtkimage)
def change_dim_primary_print_decimal_cb(menuitem, gtkimage):
_flag = gtkmodify.change_dimstr_print_decimal_dialog(gtkimage, 'DIM_PRIMARY_TRAILING_DECIMAL')
if _flag is not None:
_change_dimstring_print_decimal_cb(gtkimage, _flag, True)
def change_dim_secondary_print_decimal_cb(menuitem, gtkimage):
_flag = gtkmodify.change_dimstr_print_decimal_dialog(gtkimage, 'DIM_SECONDARY_TRAILING_DECIMAL')
if _flag is not None:
_change_dimstring_print_decimal_cb(gtkimage, _flag, False)
def change_rdim_dia_mode_cb(menuitem, gtkimage):
_tool = tools.EditDimensionTool()
_tool.setObjtype(dimension.RadialDimension)
gtkimage.getImage().setTool(_tool)
gtkmodify.change_rdim_dia_mode_init(gtkimage)
def change_adim_invert_cb(menuitem, gtkimage):
_tool = tools.EditDimensionTool()
_tool.setObjtype(dimension.AngularDimension)
gtkimage.getImage().setTool(_tool)
gtkmodify.invert_adim_init(gtkimage)
def zoom_cb(menuitem, gtkimage):
_tool = tools.ZoomTool()
gtkimage.getImage().setTool(_tool)
def zoom_in_cb(menuitem, gtkimage):
#_xmin, _ymin, _xmax, _ymax = gtkimage.getView()
#_scale = gtkimage.getUnitsPerPixel()
#_xdiff = abs(_xmax - _xmin)
#_ydiff = abs(_ymax - _ymin)
#_xmin = (_xmin + _xmax)/2.0 - _xdiff/4.0
#_ymin = (_ymin + _ymax)/2.0 - _ydiff/4.0
#gtkimage.setView(_xmin, _ymin, (_scale/2.0))
ActiveScale = gtkimage.getUnitsPerPixel()
ActiveScale = ActiveScale*0.5 #This Value here could be a global variable to put in the application option
gtkimage.ZoomScale(ActiveScale)
def zoom_out_cb(menuitem, gtkimage):
#_xmin, _ymin, _xmax, _ymax = gtkimage.getView()
#_scale = gtkimage.getUnitsPerPixel()
#_xdiff = abs(_xmax - _xmin)
#_ydiff = abs(_ymax - _ymin)
#_xmin = (_xmin + _xmax)/2.0 - _xdiff
#_ymin = (_ymin + _ymax)/2.0 - _ydiff
#gtkimage.setView(_xmin, _ymin, (_scale * 2.0))
ActiveScale = gtkimage.getUnitsPerPixel()
ActiveScale = ActiveScale*2 #This Value here could be a global variable to put in the application option
gtkimage.ZoomScale(ActiveScale)
def zoom_fit_cb(menuitem, gtkimage):
gtkimage.fitImage()
def zoom_pan_cb(menuitem, gtkimage):
_tool = tools.ZoomPan()
gtkimage.getImage().setTool(_tool)
def oneShotMidSnap(menuitem, gtkimage):
"""
Activate one shot snap mid
"""
gtkimage.image.snapProvider.setOneTemporarySnap('mid')
def oneShotEndSnap(menuitem, gtkimage):
"""
Activate one shot snap end
"""
gtkimage.image.snapProvider.setOneTemporarySnap('end')
def oneShotIntersectionSnap(menuitem, gtkimage):
"""
Activate one shot snap intersection
"""
gtkimage.image.snapProvider.setOneTemporarySnap('intersection')
def oneShotOriginSnap(menuitem, gtkimage):
"""
Activate one shot snap origin
"""
gtkimage.image.snapProvider.setOneTemporarySnap('origin')
def oneShotPerpendicularSnap(menuitem, gtkimage):
"""
Activate one shot snap Perpendicular
"""
gtkimage.image.snapProvider.setOneTemporarySnap('perpendicular')
def oneShotTangentSnap(menuitem, gtkimage):
"""
Activate one shot snap Tangent
"""
gtkimage.image.snapProvider.setOneTemporarySnap('tangent')
def oneShotPointSnap(menuitem, gtkimage):
"""
Activate one shot snap Point
"""
gtkimage.image.snapProvider.setOneTemporarySnap('point')
def oneShutCenterSnap(menuitem, gtkimage):
"""
Activate one shut snap Center
"""
gtkimage.image.snapProvider.setOneTemporarySnap('center')
def dimension_linear_cb(menuitem, gtkimage):
_tool = tools.LinearDimensionTool()
gtkimage.getImage().setTool(_tool)
def dimension_horizontal_cb(menuitem, gtkimage):
_tool = tools.HorizontalDimensionTool()
gtkimage.getImage().setTool(_tool)
def dimension_vertical_cb(menuitem, gtkimage):
_tool = tools.VerticalDimensionTool()
gtkimage.getImage().setTool(_tool)
def dimension_radial_cb(menuitem, gtkimage):
_tool = tools.RadialDimensionTool()
gtkimage.getImage().setTool(_tool)
def dimension_angular_cb(menuitem, gtkimage):
_tool = tools.AngularDimensionTool()
gtkimage.getImage().setTool(_tool)
def get_focus_widget_cb(menuitem, gtkimage):
_widget = gtkimage.getWindow().get_focus()
print "Focus widget: " + str(_widget)
def get_undo_stack_cb(menuitem, gtkimage):
_layer = gtkimage.image.getActiveLayer()
_log = _layer.getLog()
if _log is not None:
_log.printUndoData()
def get_redo_stack_cb(menuitem, gtkimage):
_layer = gtkimage.image.getActiveLayer()
_log = _layer.getLog()
if _log is not None:
_log.printRedoData()
def get_image_undo_cb(menuitem, gtkimage):
gtkimage.image.printStack(True)
def get_image_redo_cb(menuitem, gtkimage):
gtkimage.image.printStack(False)
def collect_garbage_cb(menuitem, gtkimage):
if 'gc' in sys.modules:
_lost = gc.collect()
print "%d lost objects: " % _lost
def _debug_cb(action, *args):
print "_debug_cb()"
print "action: " + `action`
print "args: " + str(args)
_group = action.get_property('action-group')
if _group is not None:
for _act in _group.list_actions():
_name = _act.get_name()
print "Action name: %s" % _name
def _std_cb(action, *args):
print "_std_cb()"
_name = action.get_name()
print "Action name: %s" % _name
def _add_accelerators(action, menuitem, accelgroup):
_path = action.get_accel_path()
if _path is not None:
_data = gtk.accel_map_lookup_entry(_path)
if _data is not None:
_k, _m = _data
if gtk.accelerator_valid(_k, _m):
menuitem.add_accelerator('activate', accelgroup,
_k, _m, gtk.ACCEL_VISIBLE)
def show_abaut_cb(menuitem, gtkimage):
"""
CallBack action for the about menu
"""
import PythonCAD.Interface.Gtk.gtkDialog as dialog
dialog.abautDialog()
#############################################################################
#
# Menu item definitions -- These define the individual menu items,
# and the actions taken (callbacks invoked) when they are selected.
#
#############################################################################
###################### File menu ##########################
def _file_menu_init(menuitem, gtkimage):
_group = gtkimage.getGroup('File')
if _group is not None:
_act = _group.get_action('SaveLayerAs')
if _act is not None:
_act.set_property('sensitive', False)
#------------------------------------------------------------
def _make_file_menu(actiongroup, gtkimage):
_accel = gtkimage.accel
_menu = gtk.Menu()
#
_act = gtk.Action('New', _('_New'), None, gtk.STOCK_NEW)
_act.connect('activate', file_new_cb)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('Open', _('_Open'), None, gtk.STOCK_OPEN)
_act.connect('activate', file_open_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('Close', _('_Close'), None, gtk.STOCK_CLOSE)
_act.connect('activate', file_close_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('Save', _('_Save'), None, gtk.STOCK_SAVE)
_act.connect('activate', file_save_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('SaveAs', _('Save _As ...'), None, None)
_act.connect('activate', file_save_as_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('SaveLayerAs', _('Save _Layer As ...'), None, None)
_act.connect('activate', file_save_layer_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('PrintScreen', _('Print Screen'), None, None)
_act.connect('activate', file_print_screen_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('Print', _('_Print'), None, gtk.STOCK_PRINT)
_act.connect('activate', file_print_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, 'P')
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('Quit', _('_Quit'), None, gtk.STOCK_QUIT)
_act.connect('activate', file_quit_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
return _menu
####################### Edit menu ###########################
def _edit_menu_init(menuitem, gtkimage):
_group = gtkimage.getGroup('Edit')
if _group is not None:
_image = gtkimage.getImage()
_act = _group.get_action('Undo')
if _act is not None:
_act.set_property('sensitive', _image.canUndo())
_act = _group.get_action('Redo')
if _act is not None:
_act.set_property('sensitive', _image.canRedo())
_act = _group.get_action('Cut')
if _act is not None:
_act.set_property('sensitive', _image.hasSelection())
_act = _group.get_action('Copy')
if _act is not None:
_act.set_property('sensitive', _image.hasSelection())
_act = _group.get_action('Paste')
if _act is not None:
_act.set_property('sensitive', globals.selectobj.hasObjects())
_act = _group.get_action('Select')
if _act is not None:
_act.set_property('sensitive', _image.getActiveLayer().hasEntities())
_act = _group.get_action('SelectAll')
if _act is not None:
_act.set_property('sensitive', _image.getActiveLayer().hasEntities())
_act = _group.get_action('Deselect')
if _act is not None:
_act.set_property('sensitive', _image.hasSelection())
#############################################################################
# Edit -> select all submenu
#############################################################################
def _make_select_all_menu(actiongroup, gtkimage):
_accel = gtkimage.accel
_menu = gtk.Menu()
for _action, _entity, _menuitem in select_menu:
if _action is not None:
_act = gtk.Action(_action, _menuitem, None, None)
_act.connect('activate', select_all_objects_cb,
(gtkimage, _entity))
_act.set_accel_group(_accel)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
else:
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
return _menu
#############################################################################
# Edit menu
#############################################################################
def _make_edit_menu(actiongroup, gtkimage):
_accel = gtkimage.accel
_menu = gtk.Menu()
#
_act = gtk.Action('Undo', _('_Undo'), None, gtk.STOCK_UNDO)
_act.connect('activate', edit_undo_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, 'Z')
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('Redo', _('_Redo'), None, gtk.STOCK_REDO)
_act.connect('activate', edit_redo_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, 'Z')
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('Cut', _('Cut'), None, gtk.STOCK_CUT)
_act.connect('activate', edit_cut_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('Copy', _('Copy'), None, gtk.STOCK_COPY)
_act.connect('activate', edit_copy_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('Paste', _('Paste'), None, gtk.STOCK_PASTE)
_act.connect('activate', edit_paste_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('Select', _('_Select'), None, None)
_act.connect('activate', edit_select_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('SelectAll', _('Select _All'), None, None)
_act.connect('activate', _select_all_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_submenu = _make_select_all_menu(actiongroup, gtkimage)
_item.set_submenu(_submenu)
_menu.append(_item)
#
_act = gtk.Action('Deselect', _('_Deselect'), None, None)
_act.connect('activate', edit_deselect_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('Prefs', _('_Preferences'), None, gtk.STOCK_PREFERENCES)
_act.connect('activate', prefs_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
return _menu
#############################################################################
# Draw -> basic sub-menu
#############################################################################
def _make_draw_basic_menu(actiongroup, gtkimage):
# _accel = gtkimage.accel
_menu = gtk.Menu()
#
_act = gtk.Action('Points', _('_Point'), None, None)
_act.connect('activate', draw_point_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('Segments', _('_Segment'), None, None)
_act.connect('activate', draw_segment_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('Rectangles', _('_Rectangle'), None, None)
_act.connect('activate', draw_rectangle_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('Circles', _('_Circle'), None, None)
_act.connect('activate', draw_circle_center_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('CirclesTwoPoints', _('Circle (_2 Pts)'), None, None)
_act.connect('activate', draw_circle_tp_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('Arcs', _('_Arc'), None, None)
_act.connect('activate', draw_arc_center_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
#############################################################################
# Draw -> lines sub-menu
#############################################################################
def _make_draw_conlines_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('HCLines', _('_Horizontal'), None, None)
_act.connect('activate', draw_hcl_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('VCLines', _('_Vertical'), None, None)
_act.connect('activate', draw_vcl_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ACLines', _('_Angled'), None, None)
_act.connect('activate', draw_acl_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('CLines', _('_Two-Point'), None, None)
_act.connect('activate', draw_cl_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('PerpConLines', _('Per_pendicular'), None, None)
_act.connect('activate', draw_perpendicular_cline_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ParallelConLines', _('Para_llel'), None, None)
_act.connect('activate', draw_poffset_cline_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('TangentConLines', _('_Tangent'), None, None)
_act.connect('activate', draw_tangent_cline_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('TangentTwoCirclesConLines', _('Tangent _2 Circ'),
None, None)
_act.connect('activate', draw_tangent_two_ccircles_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
#############################################################################
# Draw -> concentric circles sub-menu
#############################################################################
def _make_draw_concircs_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('CCircles', _('_Center Pt.'), None, None)
_act.connect('activate', draw_ccirc_cp_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('CCirclesTwoPoints', _('_Two Pts.'), None, None)
_act.connect('activate', draw_ccirc_tp_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('CCircleTangentSingle', _('_Single Tangency'),
None, None)
_act.connect('activate', draw_tangent_single_conobj_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('CCircleTangentDual', _('_Dual Tangency'), None, None)
_act.connect('activate', draw_tangent_two_conobjs_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
#############################################################################
# Draw set style sub-menu
#############################################################################
def _make_draw_set_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
# _act = gtk.Action('SetStyle', _('_Style'), None, None)
# _act.connect('activate', draw_set_style_cb, gtkimage)
# actiongroup.add_action(_act)
# _menu.append(_act.create_menu_item())
#
# _act = gtk.Action('SetLinetype', _('_Linetype'), None, None)
# _act.connect('activate', draw_set_linetype_cb, gtkimage)
# actiongroup.add_action(_act)
# _menu.append(_act.create_menu_item())
#
# _act = gtk.Action('SetColor', _('_Color'), None, None)
# _act.connect('activate', draw_set_color_cb, gtkimage)
# actiongroup.add_action(_act)
# _menu.append(_act.create_menu_item())
#
# _act = gtk.Action('SetThickness', _('_Thickness'), None, None)
# _act.connect('activate', draw_set_thickness_cb, gtkimage)
# actiongroup.add_action(_act)
# _menu.append(_act.create_menu_item())
#
# _item = gtk.SeparatorMenuItem()
# _item.show()
# _menu.append(_item)
#
_act = gtk.Action('SetImageColors', _('_Colors'), None, None)
_act.connect('activate', colors_cb, gtkimage)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('SetImageSizes', _('_Sizes'), None, None)
_act.connect('activate', sizes_cb, gtkimage)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('SetGraphicsStyle', _('_Style'), None, None)
_act.connect('activate', style_cb, gtkimage)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('SetTextStyle', _('_TextStyle'), None, None)
_act.connect('activate', textstyle_cb, gtkimage)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('SetDimStyle', _('_DimStyle'), None, None)
_act.connect('activate', dimstyle_cb, gtkimage)
_item = _act.create_menu_item()
_menu.append(_item)
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('SetImageOps', _('_Display'), None, None)
_act.connect('activate', toggle_cb, gtkimage)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('SetImageUnits', _('_Units'), None, None)
_act.connect('activate', units_cb, gtkimage)
_item = _act.create_menu_item()
_menu.append(_item)
#
return _menu
#############################################################################
# Draw-> Fillet sub menu . .
#############################################################################
def _make_draw_fillets_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('PointFillet', _('_Point..'), None, None)
_act.connect('activate', draw_fillet_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('TwoLineFillet', _('_Two Line'), None, None)
_act.connect('activate', draw_fillet_two_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
return _menu
#############################################################################
# Draw . . . .
#############################################################################
def _make_add_new_menu(actiongroup, gtkimage):
#
# These currently do nothing but are present to encourage
# the development of code to make the ability to add and
# save new styles and linetypes in drawings ...
#
_menu = gtk.Menu()
#
_act = gtk.Action('AddStyle', _('Style'), None, None)
_act.set_property('sensitive', False)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('AddLinetype', _('Linetype'), None, None)
_act.set_property('sensitive', False)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
#############################################################################
# Top level draw menu
#############################################################################
def _make_draw_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('Basic', _('_Basic'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_draw_basic_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_act = gtk.Action('ConLines', _('Con. _Lines'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_draw_conlines_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_act = gtk.Action('ConCircs', _('Con. _Circs.'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_draw_concircs_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_act = gtk.Action('Chamfers', _('Cha_mfer'), None, None)
_act.connect('activate', draw_chamfer_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('Fillets', _('_Fillets'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_draw_fillets_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('Leaders', _('Lea_der'), None, None)
_act.connect('activate', draw_leader_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('Polylines', _('_Polyline'), None, None)
_act.connect('activate', draw_polyline_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('InternalPolygon', _('Poly_gon (Int.)'), None, None)
_act.connect('activate', draw_polygon_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ExternalPolygon', _('Polygon (E_xt.)'), None, None)
_act.connect('activate', draw_ext_polygon_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('Textblocks', _('_Text'), None, None)
_act.connect('activate', draw_text_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('SetProperties', _('_Set ...'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_draw_set_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('AddNew', _('Add _New ...'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_add_new_menu(actiongroup, gtkimage))
_menu.append(_item)
#
return _menu
#############################################################################
# Modify -> move sub-menu
#############################################################################
def _make_modify_move_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('MoveHoriz', _('_Horizontal'), None, None)
_act.connect('activate', move_horizontal_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('MoveVert', _('_Vertical'), None, None)
_act.connect('activate', move_vertical_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('MoveTwoPt', _('_Two-Point Move'), None, None)
_act.connect('activate', move_twopoint_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
#############################################################################
# Modify -> stretch sub-menu
#############################################################################
def _make_modify_stretch_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('StretchHoriz', _('_Horizontal'), None, None)
_act.connect('activate', stretch_horiz_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('StretchVert', _('_Vertical'), None, None)
_act.connect('activate', stretch_vert_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('StretchTwoPt', _('_Two-Point Stretch'), None, None)
_act.connect('activate', stretch_twopoint_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
#############################################################################
# Modify -> change sub-sub-menu
#############################################################################
def _make_change_text_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('ChangeTextBlockFamily', _('_Family'), None, None)
_act.connect('activate', change_textblock_family_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeTextBlockWeight', _('_Weight'), None, None)
_act.connect('activate', change_textblock_weight_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeTextBlockStyle', _('_Style'), None, None)
_act.connect('activate', change_textblock_style_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeTextBlockColor', _('_Color'), None, None)
_act.connect('activate', change_textblock_color_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeTextBlockSize', _('Si_ze'), None, None)
_act.connect('activate', change_textblock_size_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeTextBlockAlignment', _('_Alignment'), None, None)
_act.connect('activate', change_textblock_alignment_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
#############################################################################
# Modify -> change -> Dimension -> Primary DimString sub-sub-menu
#############################################################################
def _make_change_primary_dimstring_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('ChangePDimStringFamily', _('Family'), None, None)
_act.connect('activate', change_dim_primary_family_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringWeight', _('Weight'), None, None)
_act.connect('activate', change_dim_primary_weight_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringStyle', _('Style'), None, None)
_act.connect('activate', change_dim_primary_style_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringSize', _('Size'), None, None)
_act.connect('activate', change_dim_primary_size_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringColor', _('Color'), None, None)
_act.connect('activate', change_dim_primary_color_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringAlignment', _('Alignment'), None, None)
_act.connect('activate', change_dim_primary_alignment_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringPrefix', _('Prefix'), None, None)
_act.connect('activate', change_ldim_pds_prefix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringSuffix', _('Suffix'), None, None)
_act.connect('activate', change_ldim_pds_suffix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringPrecision', _('Precision'), None, None)
_act.connect('activate', change_dim_primary_precision_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringUnits', _('Units'), None, None)
_act.connect('activate', change_dim_primary_units_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringPrintZero', _('Print Zero'), None, None)
_act.connect('activate', change_dim_primary_print_zero_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangePDimStringPrintDecimal', _('Print Decimal'),
None, None)
_act.connect('activate', change_dim_primary_print_decimal_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
#############################################################################
# Modify -> change -> Dimension -> Secondary DimString sub-sub-menu
#############################################################################
def _make_change_secondary_dimstring_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('ChangeSDimStringFamily', _('Family'), None, None)
_act.connect('activate', change_dim_secondary_family_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringWeight', _('Weight'), None, None)
_act.connect('activate', change_dim_secondary_weight_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringStyle', _('Style'), None, None)
_act.connect('activate', change_dim_secondary_style_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringSize', _('Size'), None, None)
_act.connect('activate', change_dim_secondary_size_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringColor', _('Color'), None, None)
_act.connect('activate', change_dim_secondary_color_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringAlignment', _('Alignment'), None, None)
_act.connect('activate', change_dim_secondary_alignment_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringPrefix', _('Prefix'), None, None)
_act.connect('activate', change_ldim_sds_prefix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringSuffix', _('Suffix'), None, None)
_act.connect('activate', change_ldim_sds_suffix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringPrecision', _('Precision'), None, None)
_act.connect('activate', change_dim_secondary_precision_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringUnits', _('Units'), None, None)
_act.connect('activate', change_dim_secondary_units_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringPrintZero', _('Print Zero'), None, None)
_act.connect('activate', change_dim_secondary_print_zero_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeSDimStringPrintDecimal', _('Print Decimal'),
None, None)
_act.connect('activate', change_dim_secondary_print_decimal_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
def _make_change_rdim_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('ChangeRDimPDSPrefix', _('Primary Prefix'), None, None)
_act.connect('activate', change_rdim_pds_prefix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeRDimPDSSuffix', _('Primary Suffix'), None, None)
_act.connect('activate', change_rdim_pds_suffix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('ChangeRDimSDSPrefix', _('Secondary Prefix'), None, None)
_act.connect('activate', change_rdim_sds_prefix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeRDimSDSSuffix', _('Secondary Suffix'), None, None)
_act.connect('activate', change_rdim_sds_suffix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('ChangeRDimDiaMode', _('Dia. Mode'), None, None)
_act.connect('activate', change_rdim_dia_mode_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
def _make_change_adim_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('ChangeADimPDSPrefix', _('Primary Prefix'), None, None)
_act.connect('activate', change_adim_pds_prefix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeADimPDSSuffix', _('Primary Suffix'), None, None)
_act.connect('activate', change_adim_pds_suffix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('ChangeADimSDSPrefix', _('Secondary Prefix'), None, None)
_act.connect('activate', change_adim_sds_prefix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeADimSDSSuffix', _('Secondary Suffix'), None, None)
_act.connect('activate', change_adim_sds_suffix_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('ChangeADimInvert', _('Invert'), None, None)
_act.connect('activate', change_adim_invert_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
return _menu
#############################################################################
# Modify -> change -> dimension sub-sub-menu
#############################################################################
def _make_change_dimension_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('ChangeDimEndpointType', _('Endpoint _Type'), None, None)
_act.connect('activate', change_dim_endpoint_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeDimEndpointSize', _('Endpoint _Size'), None, None)
_act.connect('activate', change_dim_endpoint_size_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeDimOffset', _('_Offset Length'), None, None)
_act.connect('activate', change_dim_offset_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeDimExtension', _('E_xtension Length'), None, None)
_act.connect('activate', change_dim_extension_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeDimDualMode', _('_Dual Mode'), None, None)
_act.connect('activate', change_dim_dual_mode_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeDimDualModeOffset', _('Dual Mode O_ffset'),
None, None)
_act.connect('activate', change_dim_dual_mode_offset_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeDimThickness', _('_Thickness'), None, None)
_act.connect('activate', change_dim_thickness_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeDimColor', _('_Color'), None, None)
_act.connect('activate', change_dim_color_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('ChangePDimStrMenu', _('_Primary DimString'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_change_primary_dimstring_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_act = gtk.Action('ChangeSDimStrMenu', _('_Secondary DimString'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_change_secondary_dimstring_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_act = gtk.Action('ChangeRDimMenu', _('RadialDim ...'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_change_rdim_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_act = gtk.Action('ChangeADimMenu', _('AngularDim ...'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_change_adim_menu(actiongroup, gtkimage))
_menu.append(_item)
#
# _act = gtk.Action('ChangeDimPrimaryDS', '_Primary DimString', None, None)
# _act.connect('activate', change_primary_dim_cb, gtkimage)
# actiongroup.add_action(_act)
# _menu.append(_act.create_menu_item())
#
# _act = gtk.Action('ChangeDimSecondaryDS', '_Secondary DimString', None, None)
# _act.connect('activate', change_secondary_dim_cb, gtkimage)
# actiongroup.add_action(_act)
# _menu.append(_act.create_menu_item())
#
return _menu
#############################################################################
# Modify -> change sub-menu
#############################################################################
def _make_modify_change_menu(actiongroup, gtkimage):
_menu = gtk.Menu()
#
_act = gtk.Action('ChangeStyle', _('_Style'), None, None)
_act.connect('activate', change_style_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeLinetype', _('_Linetype'), None, None)
_act.connect('activate', change_linetype_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeColor', _('_Color'), None, None)
_act.connect('activate', change_color_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ChangeThickness', _('_Thickness'), None, None)
_act.connect('activate', change_thickness_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('ChangeTextMenu', _('Text_Block ...'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_change_text_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('ChangeDimMenu', _('_Dimension ...'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_change_dimension_menu(actiongroup, gtkimage))
_menu.append(_item)
#
return _menu
#############################################################################
# Initialize Modify -> change sub menu
#############################################################################
def _change_menu_init(menuitem, gtkimage):
# print "_change_menu_init()"
_group = gtkimage.getGroup('Modify')
if _group is not None:
_image = gtkimage.getImage()
_objlist = []
_active = _image.getActiveLayer()
_gflag = _tflag = _dflag = False
for _obj in _image.getSelectedObjects(False):
if isinstance(_obj, graphicobject.GraphicObject):
_goflag = True
continue
if isinstance(_obj, text.TextBlock):
_tflag = True
continue
if isinstance(_obj, dimension.Dimension):
_dflag = True
if _gflag and _tflag and _dflag:
break
if not _gflag or not _tflag or not _dflag:
for _obj in _active.getChildren():
if not _gflag and isinstance(_obj,
graphicobject.GraphicObject):
_gflag = True
continue
if not _tflag and isinstance(_obj, text.TextBlock):
_tflag = True
continue
if not _dflag and isinstance(_obj, dimension.Dimension):
_dflag = True
if _gflag and _tflag and _dflag:
break
_act = _group.get_action('ChangeStyle')
if _act is not None:
_act.set_property('sensitive', _gflag)
_act = _group.get_action('ChangeLinetype')
if _act is not None:
_act.set_property('sensitive', _gflag)
_act = _group.get_action('ChangeColor')
if _act is not None:
_act.set_property('sensitive', _gflag)
_act = _group.get_action('ChangeThickness')
if _act is not None:
_act.set_property('sensitive', _gflag)
_act = _group.get_action('ChangeTextMenu')
if _act is not None:
_act.set_property('sensitive', _tflag)
_act = _group.get_action('ChangeDimMenu')
if _act is not None:
_act.set_property('sensitive', _dflag)
#############################################################################
# Initialize top level modify menu -- this handles greying out non-active items.
#############################################################################
def _modify_menu_init(menuitem, gtkimage):
_group = gtkimage.getGroup('Modify')
if _group is not None:
_image = gtkimage.getImage()
_active = _image.getActiveLayer()
_act = _group.get_action('Move')
if _act is not None:
_act.set_property('sensitive', (_active.hasEntities() or
_image.hasSelection()))
_act = _group.get_action('Stretch')
if _act is not None:
_act.set_property('sensitive', _active.hasEntities())
_act = _group.get_action('Split')
if _act is not None:
_flag = ((_active.getEntityCount('segment') > 0) or
(_active.getEntityCount('circle') > 0) or
(_active.getEntityCount('arc') > 0) or
(_active.getEntityCount('polyline') > 0))
_act.set_property('sensitive', _flag)
_act = _group.get_action('Mirror')
if _act is not None:
_flag = ((_active.hasEntities() or _image.hasSelection()) and
((_active.getEntityCount('hcline') > 0) or
(_active.getEntityCount('vcline') > 0) or
(_active.getEntityCount('acline') > 0) or
(_active.getEntityCount('cline') > 0)))
_act.set_property('sensitive', _flag)
_act = _group.get_action('Transfer')
if _act is not None:
_flag = False
_layers = [_image.getTopLayer()]
while len(_layers):
_layer = _layers.pop()
if _layer is not _active:
_flag = _layer.hasEntities()
if _flag:
break
_layers.extend(_layer.getSublayers())
_act.set_property('sensitive', _flag)
_act = _group.get_action('Rotate')
if _act is not None:
_act.set_property('sensitive', (_active.hasEntities() or
_image.hasSelection()))
_act = _group.get_action('Delete')
if _act is not None:
_act.set_property('sensitive', _active.hasEntities())
_act = _group.get_action('Change')
if _act is not None:
_act.set_property('sensitive', (_image.hasSelection() or
_active.hasEntities()))
_act = _group.get_action('ZoomFit')
if _act is not None:
_act.set_property('sensitive', _active.hasEntities())
#############################################################################
# Top level modify menu
#############################################################################
def _make_modify_menu(actiongroup, gtkimage):
_accel = gtkimage.accel
_menu = gtk.Menu()
#
_act = gtk.Action('Move', _('_Move ...'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_modify_move_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_act = gtk.Action('Stretch', _('S_tretch ...'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_modify_stretch_menu(actiongroup, gtkimage))
_menu.append(_item)
#
_act = gtk.Action('Split', _('S_plit'), None, None)
_act.connect('activate', split_object_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('Mirror', _('_Mirror'), None, None)
_act.connect('activate', mirror_object_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('Transfer', _('Trans_fer'), None, None)
_act.connect('activate', transfer_object_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('Rotate', _('_Rotate'), None, None)
_act.connect('activate', rotate_object_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('Delete', _('_Delete'), None, None)
_act.connect('activate', delete_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_item = gtk.SeparatorMenuItem()
_item.show()
_menu.append(_item)
#
_act = gtk.Action('Change', _('_Change'), None, None)
_act.connect('activate', _change_menu_init, gtkimage)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_modify_change_menu(actiongroup, gtkimage))
_menu.append(_item)
return _menu
#############################################################################
# Initialize top level view menu -- this handles greying out non-active items.
#############################################################################
def _view_menu_init(menuitem, gtkimage):
_group = gtkimage.getGroup('View')
if _group is not None:
_image = gtkimage.getImage()
_active = _image.getActiveLayer()
_act = _group.get_action('ZoomFit')
if _act is not None:
_act.set_property('sensitive', _active.hasEntities())
#############################################################################
# Top level view menu
#############################################################################
def _make_view_menu(actiongroup, gtkimage):
_accel = gtkimage.accel
_menu = gtk.Menu()
#
_act = gtk.Action('ZoomIn', _('_Zoom In'), None, gtk.STOCK_ZOOM_IN)
_act.connect('activate', zoom_in_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('ZoomOut', _('Zoom _Out'), None, gtk.STOCK_ZOOM_OUT)
_act.connect('activate', zoom_out_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('ZoomFit', _('Zoom _Fit'), None, gtk.STOCK_ZOOM_FIT)
_act.connect('activate', zoom_fit_cb, gtkimage)
_act.set_accel_group(_accel)
actiongroup.add_action_with_accel(_act, None)
_item = _act.create_menu_item()
if isinstance(_act, gtkactions.stdAction):
_add_accelerators(_act, _item, _accel)
_menu.append(_item)
#
_act = gtk.Action('ZoomPan', _('Zoom _Pan'), None, None)
_act.connect('activate', zoom_pan_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
#
_act = gtk.Action('ZoomWindow', _('Zoom _Window'), None, None)
_act.connect('activate', zoom_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
return _menu
#############################################################################
# Initialize top level help menu -- this handles greying out non-active items.
#############################################################################
def _help_menu_init(menuitem, gtkimage):
return
#############################################################################
# Top level help menu
#############################################################################
def _make_help_menu(actiongroup, gtkimage):
_group = gtkimage.getGroup('Help')
_menu = gtk.Menu()
# Abaut
_act = gtk.Action('About', _('_About'), None, None)
_act.connect('activate', show_abaut_cb, gtkimage)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_menu.append(_item)
return _menu
#############################################################################
# Initialize top level snap menu -- this handles greying out non-active items.
#############################################################################
def _snap_menu_init(menuitem, gtkimage):
return
#############################################################################
# Top level snap menu
#############################################################################
def _make_snap_menu(actiongroup, gtkimage):
_group = gtkimage.getGroup('Snap')
_menu = gtk.Menu()
#
_act = gtk.Action('OneShotSnap', _('_One Shot Snap'), None, None)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_item.set_submenu(_make_snap_oneshot_menu(actiongroup, gtkimage))
_menu.append(_item)
return _menu
def _make_snap_oneshot_menu(actiongroup, gtkimage):
_group = gtkimage.getGroup('SnapOneShot')
_menu = gtk.Menu()
#
_act = gtk.Action('MidPoint', _('_Mid Point'), None, None)
_act.connect('activate', oneShotMidSnap, gtkimage)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('Point', _('_Point'), None, None)
_act.connect('activate', oneShotPointSnap, gtkimage)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('Center', _('_Center'), None, None)
_act.connect('activate', oneShutCenterSnap, gtkimage)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('EndPoint', _('_End Point'), None, None)
_act.connect('activate', oneShotEndSnap, gtkimage)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('IntersectionPoint', _('_Intersection Point'), None, None)
_act.connect('activate', oneShotIntersectionSnap, gtkimage)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('OriginPoint', _('_Origin Point'), None, None)
_act.connect('activate', oneShotOriginSnap, gtkimage)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('PerpendicularPoint', _('_Perpendicular Point'), None, None)
_act.connect('activate', oneShotPerpendicularSnap, gtkimage)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_menu.append(_item)
#
_act = gtk.Action('TangentPoint', _('_Tangent Point'), None, None)
_act.connect('activate', oneShotTangentSnap, gtkimage)
actiongroup.add_action(_act)
_item = _act.create_menu_item()
_menu.append(_item)
return _menu
#############################################################################
# Init top level Dimensions menu
#############################################################################
def _dimension_menu_init(menuitem, gtkimage):
_group = gtkimage.getGroup('Dimension')
if _group is not None:
_ldim = _hdim = _vdim = _rdim = _adim = False
_count = 0
_layers = [gtkimage.image.getTopLayer()]
for _layer in _layers:
_pc = _layer.getEntityCount('point')
if _pc > 0:
_count = _count + _pc
if _count > 1:
_ldim = _hdim = _vdim = True
if _count > 2:
_adim = True
if _layer.getEntityCount('circle') > 0:
_rdim = True
if _layer.getEntityCount('arc') > 0:
_rdim = _adim = True
if _ldim and _hdim and _vdim and _rdim and _adim:
break
_layers.extend(_layer.getSublayers())
_act = _group.get_action('Linear')
if _act is not None:
_act.set_property('sensitive', _ldim)
_act = _group.get_action('Horizontal')
if _act is not None:
_act.set_property('sensitive', _hdim)
_act = _group.get_action('Vertical')
if _act is not None:
_act.set_property('sensitive', _vdim)
_act = _group.get_action('Radial')
if _act is not None:
_act.set_property('sensitive', _rdim)
_act = _group.get_action('Angular')
if _act is not None:
_act.set_property('sensitive', _adim)
#############################################################################
# Top level Dimensions menu
#############################################################################
def _make_dimension_menu(actiongroup, gtkimage):
_accel = gtkimage.accel
_menu = gtk.Menu()
_act = gtk.Action('Linear', _('_Linear'), None, None)
_act.connect('activate', dimension_linear_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
_act = gtk.Action('Horizontal', _('_Horizontal'), None, None)
_act.connect('activate', dimension_horizontal_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
_act = gtk.Action('Vertical', _('_Vertical'), None, None)
_act.connect('activate', dimension_vertical_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
_act = gtk.Action('Radial', _('_Radial'), None, None)
_act.connect('activate', dimension_radial_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
_act = gtk.Action('Angular', _('_Angular'), None, None)
_act.connect('activate', dimension_angular_cb, gtkimage)
actiongroup.add_action(_act)
_menu.append(_act.create_menu_item())
return _menu
#############################################################################
# Fill out top menubar with menu items.
#############################################################################
def fill_menubar(mb, gtkimage):
if not isinstance(mb, gtk.MenuBar):
raise TypeError, "Invalid gtk.MenuBar object: " + `mb`
# File menu
_group = gtk.ActionGroup('File')
gtkimage.addGroup(_group)
_act = gtk.Action('FileMenu', _('_File'), None, None)
_group.add_action(_act)
_item = gtk.MenuItem()
_act.connect_proxy(_item)
_act.connect('activate', _file_menu_init, gtkimage)
_menu = _make_file_menu(_group, gtkimage)
_item.set_submenu(_menu)
mb.append(_item)
# Edit menu
_group = gtk.ActionGroup('Edit')
gtkimage.addGroup(_group)
_act = gtk.Action('EditMenu', _('_Edit'), None, None)
_group.add_action(_act)
_item = gtk.MenuItem()
_act.connect_proxy(_item)
_act.connect('activate', _edit_menu_init, gtkimage)
_menu = _make_edit_menu(_group, gtkimage)
_item.set_submenu(_menu)
mb.append(_item)
# Draw menu
_group = gtk.ActionGroup('Draw')
gtkimage.addGroup(_group)
_act = gtk.Action('DrawMenu', _('_Draw'), None, None)
_group.add_action(_act)
_item = gtk.MenuItem()
_act.connect_proxy(_item)
_menu = _make_draw_menu(_group, gtkimage)
_item.set_submenu(_menu)
mb.append(_item)
# Modifying
_group = gtk.ActionGroup('Modify')
gtkimage.addGroup(_group)
_act = gtk.Action('ModifyMenu', _('_Modify'), None, None)
_group.add_action(_act)
_item = gtk.MenuItem()
_act.connect_proxy(_item)
_act.connect('activate', _modify_menu_init, gtkimage)
_menu = _make_modify_menu(_group, gtkimage)
_item.set_submenu(_menu)
mb.append(_item)
# View
_group = gtk.ActionGroup('View')
gtkimage.addGroup(_group)
_act = gtk.Action('ViewMenu', _('_View'), None, None)
_group.add_action(_act)
_item = gtk.MenuItem()
_act.connect_proxy(_item)
_act.connect('activate', _view_menu_init, gtkimage)
_menu = _make_view_menu(_group, gtkimage)
_item.set_submenu(_menu)
mb.append(_item)
# Snap
_group = gtk.ActionGroup('Snap')
gtkimage.addGroup(_group)
_act = gtk.Action('SnapMenu', _('_Snap'), None, None)
_group.add_action(_act)
_item = gtk.MenuItem()
_act.connect_proxy(_item)
_act.connect('activate', _snap_menu_init, gtkimage)
_menu = _make_snap_oneshot_menu(_group, gtkimage)
_item.set_submenu(_menu)
mb.append(_item)
# Dimensioning
_group = gtk.ActionGroup('Dimension')
gtkimage.addGroup(_group)
_act = gtk.Action('DimensionMenu', _('Dime_nsions'), None, None)
_group.add_action(_act)
_item = gtk.MenuItem()
_act.connect_proxy(_item)
_act.connect('activate', _dimension_menu_init, gtkimage)
_menu = _make_dimension_menu(_group, gtkimage)
_item.set_submenu(_menu)
mb.append(_item)
# Help
_group = gtk.ActionGroup('Help')
gtkimage.addGroup(_group)
_act = gtk.Action('HelpMenu', _('_Help'), None, None)
_group.add_action(_act)
_item = gtk.MenuItem()
_act.connect_proxy(_item)
_act.connect('activate', _help_menu_init, gtkimage)
_menu = _make_help_menu(_group, gtkimage)
_item.set_submenu(_menu)
mb.append(_item)
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkprinting.py 0000644 0001750 0001750 00000025427 11307666732 022326 0 ustar matteo matteo #
# Copyright (c) 2004, 2006, 2007 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 for setting printing parameters
#
import pygtk
pygtk.require('2.0')
import gtk
import os
import tempfile
from PythonCAD.Generic.plotfile import Plot
from PythonCAD.Generic.printing import PSPlot
def _toggle_widgets_on(widget):
widget.set_sensitive(True)
def _toggle_widgets_off(widget):
widget.set_sensitive(False)
def _print_rb_cb(button, hbox):
if button.get_active():
hbox.foreach(_toggle_widgets_on)
else:
hbox.foreach(_toggle_widgets_off)
return True
def _error_dialog(gtkimage, errmsg):
_window = gtkimage.getWindow()
_dialog = gtk.MessageDialog(_window,
gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_ERROR,
gtk.BUTTONS_CLOSE,
errmsg)
_dialog.run()
_dialog.destroy()
def print_dialog(gtkimage, plot):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Printing Preferences'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_vbox = _dialog.vbox
#
_psplot = PSPlot(plot)
#
# options for all plots
#
_frame = gtk.Frame(_('Plot Options'))
_fvbox = gtk.VBox(False, 5)
_fvbox.set_border_width(5)
_frame.add(_fvbox)
_ccb = gtk.CheckButton(_('Print in Color'))
_fvbox.pack_start(_ccb, False, False, 5)
_icb = gtk.CheckButton(_('Print White as Black'))
_fvbox.pack_start(_icb, False, False, 5)
_lcb = gtk.CheckButton(_('Print in Landscape Mode'))
_fvbox.pack_start(_lcb, False, False, 5)
_hbox = gtk.HBox(False, 5)
_fvbox.pack_start(_hbox, True, True, 5)
_label = gtk.Label(_('Paper Size:'))
_hbox.pack_start(_label, False, False, 5)
_papersizes = _psplot.getPaperSizes()
_papersizes.sort()
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_size_widget = gtk.combo_box_new_text()
for _size in _papersizes:
_size_widget.append_text(_size)
_size_widget.set_active(0) # perhaps a global preferences value?
else:
_menu = gtk.Menu()
for _size in _papersizes:
_item = gtk.MenuItem(_size)
_menu.append(_item)
_size_widget = gtk.OptionMenu()
_size_widget.set_menu(_menu)
_size_widget.set_history(0) # perhaps a global preference value?
_hbox.pack_start(_size_widget, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
#
#
_label_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Print Destination'))
_fvbox = gtk.VBox(False, 5)
_fvbox.set_border_width(5)
_frame.add(_fvbox)
#
_phbox = gtk.HBox(False, 5)
_label = gtk.Label(_('Printer:'))
_label_size_group.add_widget(_label)
_phbox.pack_start(_label, False, False, 5)
_print_entry = gtk.Entry()
_print_entry.set_text("lp")
_phbox.pack_start(_print_entry, False, False, 5)
_fvbox.pack_start(_phbox, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_label = gtk.Label(_('File:'))
_label_size_group.add_widget(_label)
_label.set_sensitive(False)
_fhbox.pack_start(_label, False, False, 5)
_file_entry = gtk.Entry()
_file_entry.set_sensitive(False)
_fhbox.pack_start(_file_entry, False, False, 5)
_fvbox.pack_start(_fhbox, False, False, 5)
#
_hbox = gtk.HBox(False, 5)
_label = gtk.Label(_('Send print to ...'))
_label_size_group.add_widget(_label)
_hbox.pack_start(_label, False, False, 5)
_prb = gtk.RadioButton()
_prb.set_label(_('Printer'))
_prb.set_mode(True)
_prb.connect("toggled", _print_rb_cb, _phbox)
_hbox.pack_start(_prb, False, False, 5)
_frb = gtk.RadioButton(_prb)
_frb.set_label(_('File'))
_frb.set_mode(True)
_frb.connect("toggled", _print_rb_cb, _fhbox)
_hbox.pack_start(_frb, False, False, 5)
_fvbox.pack_start(_hbox, False, False, 5)
#
_vbox.pack_start(_frame, False, False, 5)
_dialog.show_all()
while True:
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
plot.setColorMode(_ccb.get_active())
plot.invertWhite(_icb.get_active())
plot.setLandscapeMode(_lcb.get_active())
plot.getPlotData()
if hasattr(gtk, 'ComboBox') and isinstance(_size_widget, gtk.ComboBox):
_idx = _size_widget.get_active()
elif isinstance(_size_widget, gtk.OptionMenu):
_idx = _sizewidget.get_history()
else:
raise TypeError, "Unexpected size_widget: " + `type(_size_widget)`
_psplot.setSize(_papersizes[_idx])
if _prb.get_active(): # send job out
try:
_f = tempfile.NamedTemporaryFile()
_fname = _f.name
try:
try:
_psplot.write(_f)
_cmd = "%s %s" %(_print_entry.get_text(), _fname)
try:
_res = os.system(_cmd)
if _res == 0:
break
else:
_msg = "Non-zero exit status from '%s': %d" % (_cmd, _res)
_error_dialog(gtkimage, _msg)
except StandardError, _err:
_msg = "Error executing command '%s': %s" % (_cmd, _err)
_error_dialog(gtkimage, _msg)
except StandardError, _err:
_msg = "Error writing '%s': %s" % (_fname, _err)
_error_dialog(gtkimage, _msg)
finally:
_f.close()
except StandardError, _err:
_msg = "Error creating temporary file %s" % _err
_error_dialog(gtkimage, _msg)
else:
_fname = _file_entry.get_text()
try:
_f = file(_fname, "w")
try:
_psplot.write(_f)
finally:
_f.close()
break
except StandardError, _err:
_msg = "Error writing to %s: %s" % (_fname, _err)
_error_dialog(gtkimage, _msg)
else:
break
_psplot.finish()
_dialog.destroy()
def _show_print_dialog(gtkimage, tool=None):
_plot = Plot(gtkimage.image)
_tool = gtkimage.getImage().getTool()
_x1, _y1 = _tool.getFirstCorner()
_x2, _y2 = _tool.getSecondCorner()
_xmin = min(_x1, _x2)
_ymin = min(_y1, _y2)
_xmax = max(_x1, _x2)
_ymax = max(_y1, _y2)
_plot.setBounds(_xmin, _ymin, _xmax, _ymax)
_tool.reset()
plot_mode_init(gtkimage)
gtkimage.refresh()
print_dialog(gtkimage, _plot)
def plot_motion_notify(gtkimage, widget, event, tool):
_tx, _ty = tool.getFirstCorner()
_px, _py = gtkimage.coordToPixTransform(_tx, _ty)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_xmin = min(_xc, _px)
_ymin = min(_yc, _py)
_rw = abs(_xc - _px)
_rh = abs(_yc - _py)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _rw, _rh)
tool.setCurrentPoint(_x, _y)
_xmin = min(_x, _px)
_ymin = min(_y, _py)
_rw = abs(_x - _px)
_rh = abs(_y - _py)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _rw, _rh)
return True
def _make_tuple(text, gdict):
_tpl = eval(text, gdict)
if not isinstance(_tpl, tuple):
raise TypeError, "Invalid tuple: " + `type(_tpl)`
if len(_tpl) != 2:
raise ValueError, "Invalid tuple: " + str(_tpl)
return _tpl
def plot_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_x, _y = _image.getClosestPoint(_x, _y, tolerance=_tol)
tool.setSecondCorner(_x, _y)
_show_print_dialog(gtkimage, tool)
return True
def plot_second_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = _make_tuple(_text, gtkimage.image.getImageVariables())
tool.setSecondCorner(_x, _y)
_show_print_dialog(gtkimage, tool)
def plot_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_x, _y = _image.getClosestPoint(_x, _y, tolerance=_tol)
tool.setFirstCorner(_x, _y)
gtkimage.setPrompt(_('Click in the drawing area or enter another point'))
tool.setHandler("button_press", plot_second_button_press_cb)
tool.setHandler("entry_event", plot_second_entry_event_cb)
tool.setHandler("motion_notify", plot_motion_notify)
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def plot_first_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = _make_tuple(_text, gtkimage.image.getImageVariables())
tool.setFirstCorner(_x, _y)
gtkimage.setPrompt(_('Click in the drawing area or enter another point'))
tool.setHandler("button_press", plot_second_button_press_cb)
tool.setHandler("entry_event", plot_second_entry_event_cb)
tool.setHandler("motion_notify", plot_motion_notify)
gtkimage.getGC().set_function(gtk.gdk.INVERT)
def plot_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter a point'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", plot_mode_init)
_tool.setHandler("button_press", plot_first_button_press_cb)
_tool.setHandler("entry_event", plot_first_entry_event_cb)
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkprefs.py 0000644 0001750 0001750 00000317142 11307666732 021611 0 ustar matteo matteo #
# Copyright (c) 2002, 2003, 2004, 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 for setting the preferences of an image
#
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import sys
from PythonCAD.Generic import globals
from PythonCAD.Generic.text import TextStyle
from PythonCAD.Generic import units
from PythonCAD.Generic.image import Image
from PythonCAD.Generic.color import get_color
from PythonCAD.Generic import preferences
from PythonCAD.Generic.dimension import Dimension
_font_styles = TextStyle.getStyleStrings()
_font_weights = TextStyle.getWeightStrings()
_text_align = TextStyle.getAlignmentStrings()
_dim_endpoints = Dimension.getEndpointTypeStrings()
_dim_positions = Dimension.getPositionStrings()
################################################################
#
# New and improved preferences code ...
#
################################################################
class Prefstate(object):
"""A class for storing and retriving preference values.
The Prefstate class stores references to the widgets used in
making the preference dialog screens. When the dialog is closed
the widgets stored in the Prefstate class are examined for their
values if the user wants to set new preference values.
The Prefstate class has the following methods:
{set/get}TreeView(): Set/Get a gtk.TreeView for the Prefstate instance.
{set/get}HBox(): Set/Get a gtk.HBox for the Prefstate instance.
{set/get}Container(): Set/Get a reference to a gtk.Container instance.
{set/get}PrefKey(): Set/Get a key used for storing preference widget sets.
{set/get}Widget(): Set/Get a keyed reference to a widget.
hasWidgetKey(): Test if a key is used to store a widget reference.
getWidgetKeys(): Return the keys used to refer to stored widgets.
{set/get}Image(): Set/Get the Image used for preference adjustment.
{set/get}Window(): Set/Get the gtk.Window displaying the preference dialog.
{set/get}Families(): Set/Get the font families for text selection screens
clear(): Clear all storage of widgets
"""
def __init__(self):
self.__tree_view = None
self.__hbox = None
self.__prefkeys = {}
self.__prefkey = None
self.__widgets = {}
self.__image = None
self.__window = None
self.__families = None
def setTreeView(self, treeview):
"""Store a reference to a TreeView widget.
setTreeView(treeview)
The argument 'treeview' must be a gtk.TreeView instance.
"""
if not isinstance(treeview, gtk.TreeView):
raise TypeError, "Invalid TreeView: " + `type(treeview)`
self.__tree_view = treeview
def getTreeView(self):
"""Return the stored TreeView widget.
getTreeView()
If no gtk.TreeView has been stored this method returns None.
"""
return self.__tree_view
def setHBox(self, hbox):
"""Store a reference to a gtk.HBox widget.
setHBox(hbox)
The argument 'hbox' must be a gtk.HBox instance.
"""
if not isinstance(hbox, gtk.HBox):
raise TypeError, "Invalid HBox: " + `type(hbox)`
self.__hbox = hbox
def getHBox(self):
"""Return the stored gtk.HBox.
getHBox()
If no gtk.HBox has been stored this method returns None.
"""
return self.__hbox
def setContainer(self, key, container):
"""Store a keyed reference to a gtk.Container instance.
setContainer(key, container)
Argument 'key' is a text string, and the container must be
an instance of gtk.Container.
"""
if not isinstance(container, gtk.Container):
raise TypeError, "Invalid container: " + `type(container)`
self.__prefkeys[key] = container
def getContainer(self, key):
"""Retrieve the gtk.Container referenced by a key.
getContainer(key)
If the key has been used to store a gtk.Container instance, the
stored container is returned. If not, None is returned.
"""
if key in self.__prefkeys:
_container = self.__prefkeys[key]
else:
_container = None
return _container
def setPrefKey(self, key):
"""Store a key representing a screenful of preference widgets.
setPrefKey(key)
Argument 'key' should be a string.
"""
if key not in self.__prefkeys:
raise ValueError, "No container stored for key."
self.__prefkey = key
def getPrefKey(self):
"""Return the current key giving the preference widget screen.
getPrefKey()
This method returns the key last set by setPrefKey(). If that method
has not been invoked None is returned.
"""
return self.__prefkey
def delPrefKey(self):
self.__prefkey = None
def setWidget(self, key, widget):
"""Store a widget reference in the Prefstate.
setWidget(key, widget)
Argument 'key' should be a string. Argument 'widget' must be an
instance of gtk.Widget. Trying to use the same key twice will
raise a ValueError exception.
"""
if not isinstance(widget, gtk.Widget):
raise TypeError, "Invalid widget: " + `type(widget)`
if key in self.__widgets:
raise ValueError, "Duplicate key: " + key
self.__widgets[key] = widget
def getWidget(self, key):
"""Return the widget associated with a key
getWidget(key)
Argument 'key' should be a string. Using a key that has not
been used with setWidget() results in a KeyError exception.
"""
return self.__widgets[key]
def hasWidgetKey(self, key):
"""Test if a key is used for widget association.
hasWidgetKey(key)
This method returns True if the key has already been used to
store a widget.
"""
return key in self.__widgets
def getWidgetKeys(self):
"""Return all the keys used to store widgets.
getWidgetKeys()
This method returns a list of strings.
"""
return self.__widgets.keys()
def setImage(self, image):
"""Store a reference to the image used for preference adjustment.
setImage(image)
Argument 'image' must be an instance of image.Image.
"""
if not isinstance(image, Image):
raise TypeError, "Invalid image: " + `type(image)`
self.__image = image
def getImage(self):
"""Retrieve the image used for this Prefstate instance.
getImage()
This method raises a ValueError exception if it is called before
setImage().
"""
if self.__image is None:
raise ValueError, "Image not set."
return self.__image
def setWindow(self, window):
"""Store a reference to a gtk.Window.
setWindow(window)
Argument 'window' must be an instance of gtk.Window.
"""
if not isinstance(window, gtk.Window):
raise TypeError, "Invalid window: " + `type(window)`
self.__window = window
def getWindow(self):
"""Return the stored window for the Prefstate instance.
getWindow()
This method raises a ValueError exception if it is invoked before
setWindow() has been called.
"""
if self.__window is None:
raise ValueError, "Window not set."
return self.__window
def setFamilies(self, families):
"""Store a list of font families.
setFamilies(families)
Argument 'families' should be a list.
"""
if not isinstance(families, list):
raise TypeError, "Invalid families list: " + `type(families)`
self.__families = families
def getFamilies(self):
"""Return the list of families stored in the Prefstate instance.
getFamilies()
If setFamilies() has not been called, this method returns None
"""
return self.__families
def clear(self):
"""Release all widget references.
clear()
This method should only be called once the usage of a Prefstate
instance is completed.
"""
self.__tree_view = None
self.__hbox = None
self.__prefkeys.clear()
self.__prefkey = None
self.__widgets.clear()
self.__image = None
self.__window = None
self.__families = None
def entry_activate(entry):
_text = entry.get_text()
entry.delete_text(0, -1)
if len(_text):
if _text == '-' or _text == '+':
sys.stderr.write("Incomplete value: '%s'\n" % _text)
else:
try:
_value = float(_text)
print "value: %g" % _value
except:
sys.stderr.write("Invalid float: '%s'\n" % _text)
else:
sys.stderr.write("Empty entry box.")
#
# use focus-out events to reset the value in entry boxes
# to their previous value if the entry box text is invalid
#
def _leader_entry_focus_out(entry, event, prefstate):
_text = entry.get_text()
if _text == '' or _text == '+':
entry.delete_text(0, -1)
_size = "%f" % globals.prefs['LEADER_ARROW_SIZE']
entry.set_text(_size)
return False
def _dim_offset_entry_focus_out(entry, event, prefstate):
_text = entry.get_text()
if _text == '' or _text == '+':
entry.delete_text(0, -1)
_size = "%f" % globals.prefs['DIM_OFFSET']
entry.set_text(_size)
return False
def _dim_marker_entry_focus_out(entry, event, prefstate):
_text = entry.get_text()
if _text == '' or _text == '+':
entry.delete_text(0, -1)
_size = "%f" % globals.prefs['DIM_ENDPOINT_SIZE']
entry.set_text(_size)
return False
def _dim_extlen_entry_focus_out(entry, event, prefstate):
_text = entry.get_text()
if _text == '' or _text == '+':
entry.delete_text(0, -1)
_size = "%f" % globals.prefs['DIM_EXTENSION']
entry.set_text(_size)
return False
def _thickness_entry_focus_out(entry, event, prefstate):
_text = entry.get_text()
if _text == '' or _text == '+':
entry.delete_text(0, -1)
_size = "%f" % globals.prefs['LINE_THICKNESS']
entry.set_text(_size)
return False
def _chamfer_entry_focus_out(entry, event, prefstate):
_text = entry.get_text()
if _text == '' or _text == '+':
entry.delete_text(0, -1)
_size = "%f" % globals.prefs['CHAMFER_LENGTH']
entry.set_text(_size)
return False
def _fillet_entry_focus_out(entry, event, prefstate):
_text = entry.get_text()
if _text == '' or _text == '+':
entry.delete_text(0, -1)
_size = "%f" % globals.prefs['FILLET_RADIUS']
entry.set_text(_size)
return False
def _textsize_entry_focus_out(entry, event, prefstate):
_text = entry.get_text()
if _text == '' or _text == '+':
entry.delete_text(0, -1)
_size = "%f" % globals.prefs['TEXT_SIZE']
entry.set_text(_size)
return False
def _dim_primary_textsize_entry_focus_out(entry, event, prefstate):
_text = entry.get_text()
if _text == '' or _text == '+':
entry.delete_text(0, -1)
_size = "%f" % globals.prefs['DIM_PRIMARY_TEXT_SIZE']
entry.set_text(_size)
return False
def _dim_secondary_textsize_entry_focus_out(entry, event, prefstate):
_text = entry.get_text()
if _text == '' or _text == '+':
entry.delete_text(0, -1)
_size = "%f" % globals.prefs['DIM_SECONDARY_TEXT_SIZE']
entry.set_text(_size)
return False
def entry_focus_out(entry, event):
_text = entry.get_text()
if _text == '-' or _text == '+':
entry.delete_text(0, -1)
return False
#
# color change button handlers
#
def _get_rgb_values(color):
if not isinstance(color, gtk.gdk.Color):
raise TypeError, "Unexpected color type: " + `type(color)`
_r = int(round((color.red/65535.0) * 255.0))
_g = int(round((color.green/65535.0) * 255.0))
_b = int(round((color.blue/65535.0) * 255.0))
return _r, _g, _b
def _select_background_color(button):
_da = button.get_child().get_child()
_color = _da.get_style().bg[gtk.STATE_NORMAL]
_dialog = gtk.ColorSelectionDialog(_('Choose New Color'))
_colorsel = _dialog.colorsel
_colorsel.set_previous_color(_color)
_colorsel.set_current_color(_color)
_colorsel.set_has_palette(True)
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_r, _g, _b = _get_rgb_values(_colorsel.get_current_color())
_str = "#%02x%02x%02x" % (_r, _g, _b)
_color = gtk.gdk.color_parse(_str)
_da.modify_bg(gtk.STATE_NORMAL, _color)
_dialog.destroy()
def _select_dimbar_color(button):
_da = button.get_child().get_child()
_color = _da.get_style().bg[gtk.STATE_NORMAL]
_dialog = gtk.ColorSelectionDialog(_('Set Dimension Bar Color'))
_colorsel = _dialog.colorsel
_colorsel.set_previous_color(_color)
_colorsel.set_current_color(_color)
_colorsel.set_has_palette(True)
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_r, _g, _b = _get_rgb_values(_colorsel.get_current_color())
_str = "#%02x%02x%02x" % (_r, _g, _b)
_color = gtk.gdk.color_parse(_str)
_da.modify_bg(gtk.STATE_NORMAL, _color)
_dialog.destroy()
def _select_font_color(button):
_da = button.get_child().get_child()
_color = _da.get_style().bg[gtk.STATE_NORMAL]
_dialog = gtk.ColorSelectionDialog(_('Set Font Color'))
_colorsel = _dialog.colorsel
_colorsel.set_previous_color(_color)
_colorsel.set_current_color(_color)
_colorsel.set_has_palette(True)
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_r, _g, _b = _get_rgb_values(_colorsel.get_current_color())
_str = "#%02x%02x%02x" % (_r, _g, _b)
_color = gtk.gdk.color_parse(_str)
_da.modify_bg(gtk.STATE_NORMAL, _color)
_dialog.destroy()
#
def _toggle_widgets_on(widget, checkbox):
if widget is not checkbox:
widget.set_sensitive(True)
def _toggle_widgets_off(widget, checkbox):
if widget is not checkbox:
widget.set_sensitive(False)
def _toggle_secondary_dim_opts(checkbox, vbox):
if checkbox.get_active():
vbox.foreach(_toggle_widgets_on, checkbox)
else:
vbox.foreach(_toggle_widgets_off, checkbox)
def move_cursor(entry):
entry.set_position(-1)
return False
def entry_insert_text(entry, new_text, new_text_length, position):
if (new_text.isdigit() or
new_text == '.' or
new_text == '+'):
_string = entry.get_text() + new_text[:new_text_length]
_hid = entry.get_data('handlerid')
_move = True
entry.handler_block(_hid)
try:
_pos = entry.get_position()
if _string == '+':
_pos = entry.insert_text(new_text, _pos)
else:
try:
_val = float(_string)
_pos = entry.insert_text(new_text, _pos)
except StandardError, e:
_move = False
sys.stdout.write("exception: '%s'\n" % e)
finally:
entry.handler_unblock(_hid)
if _move:
if hasattr(gobject, 'idle_add'):
gobject.idle_add(move_cursor, entry)
else:
gtk.idle_add(move_cursor, entry)
entry.stop_emission("insert-text")
def tree_select_cb(selection, prefstate):
if selection is not None:
_model, _iter = selection.get_selected()
if _iter is not None:
_hbox = prefstate.getHBox()
_prefkey = prefstate.getPrefKey()
if _prefkey is not None:
_old_container = prefstate.getContainer(_prefkey)
assert _old_container is not None, "No container: " + _prefkey
_pstring = _model.get_value(_iter, 1)
# print "second field: '%s'" % _pstring
_new_container = prefstate.getContainer(_pstring)
if _new_container is None:
if _pstring == 'dimensions':
_new_container = _make_dimension_opts(prefstate)
elif _pstring == 'linear':
_new_container = _make_linear_opts(prefstate)
elif _pstring == 'radial':
_new_container = _make_radial_opts(prefstate)
elif _pstring == 'angular':
_new_container = _make_angular_opts(prefstate)
elif _pstring == 'basic':
_new_container = _make_basic_opts(prefstate)
elif _pstring == 'sizes':
_new_container = _make_size_opts(prefstate)
elif _pstring == 'chamfers':
_new_container = None
elif _pstring == 'fillets':
_new_container = None
elif _pstring == 'text':
_new_container = _make_text_opts(prefstate)
elif _pstring == 'primary':
_new_container = _make_primary_opts(prefstate)
elif _pstring == 'secondary':
_new_container = _make_secondary_opts(prefstate)
elif _pstring == 'snap':
_new_container = _make_snap_opts(prefstate)
else:
print "unexpected string: '%s'" % _pstring
if _new_container is not None:
_frame = None
if _pstring == 'linear':
_frame = prefstate.getWidget('LINEAR_SECONDARY_FRAME')
elif _pstring == 'radial':
_frame = prefstate.getWidget('RADIAL_SECONDARY_FRAME')
elif _pstring == 'angular':
_frame = prefstate.getWidget('ANGULAR_SECONDARY_FRAME')
else:
pass
if _frame is not None:
_flag = True
if prefstate.hasWidgetKey('DIM_DUAL_MODE'):
_cb = prefstate.getWidget('DIM_DUAL_MODE')
_flag = _cb.get_active()
if _flag:
_frame.foreach(_toggle_widgets_on, _frame)
else:
_frame.foreach(_toggle_widgets_off, _frame)
if _prefkey is not None:
_old_container.hide_all()
_hbox.remove(_old_container)
_new_container.show_all()
prefstate.setContainer(_pstring, _new_container)
prefstate.setPrefKey(_pstring)
_hbox.pack_start(_new_container, True, True, 5)
#
# the second time a new container is shown it may not
# redraw completely - why?
#
_hbox.show_all()
def _make_dimension_opts(prefstate):
_vbox = gtk.VBox(False, 5)
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_IN)
_text = "%s" % _('General Dimension Options')
_label = gtk.Label(_text)
_label.set_use_markup(True)
_frame.add(_label)
_vbox.pack_start(_frame, False, False, 5)
_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
#
# options for dimension bars
#
_frame = gtk.Frame(_('Dimension Bar Options'))
_table = gtk.Table(5, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
_label = gtk.Label(_('Offset length:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_length = "%f" % globals.prefs['DIM_OFFSET']
_entry.set_text(_length)
if not prefstate.hasWidgetKey('DIM_OFFSET'):
prefstate.setWidget('DIM_OFFSET', _entry)
_entry.connect("activate", entry_activate)
_entry.connect("focus-out-event", _dim_offset_entry_focus_out, prefstate)
_handlerid = _entry.connect("insert-text", entry_insert_text)
_entry.set_data('handlerid', _handlerid)
_size_group.add_widget(_entry)
_table.attach(_entry, 1, 2, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_thbox = gtk.HBox(False)
_thbox.set_border_width(2)
_label = gtk.Label(_('The offset length is the distance between the dimension point and the start of the dimension bar.'))
_thbox.pack_start(_label, False, False)
_label.set_line_wrap(True)
_table.attach(_thbox, 0, 2, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
#
_label = gtk.Label(_('Extension length:'))
_table.attach(_label, 0, 1, 2, 3,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_length = "%f" % globals.prefs['DIM_EXTENSION']
_entry.set_text(_length)
if not prefstate.hasWidgetKey('DIM_EXTENSION'):
prefstate.setWidget('DIM_EXTENSION', _entry)
_entry.connect("activate", entry_activate)
_entry.connect("focus-out-event", _dim_extlen_entry_focus_out, prefstate)
_handlerid = _entry.connect("insert-text", entry_insert_text)
_entry.set_data('handlerid', _handlerid)
_size_group.add_widget(_entry)
_table.attach(_entry, 1, 2, 2, 3,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_thbox = gtk.HBox(False)
_thbox.set_border_width(2)
_label = gtk.Label(_('The extension length is the distance the dimension bars extend beyond the dimension crossbar/crossarc.'))
_label.set_line_wrap(True)
_thbox.pack_start(_label, False, False)
_table.attach(_thbox, 0, 2, 3, 4,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_fhbox = gtk.HBox(False, 5)
_label = gtk.Label(_('Dimension bar color:'))
_fhbox.pack_start(_label, False, False, 5)
_color = globals.prefs['DIM_COLOR']
_gtkcolor = gtk.gdk.color_parse(str(_color))
if hasattr(gtk, 'ColorButton'):
_button = gtk.ColorButton(color=_gtkcolor)
_button.set_title(_('Select Dimension Color'))
if not prefstate.hasWidgetKey('DIM_COLOR'):
prefstate.setWidget('DIM_COLOR', _button)
else:
_button = gtk.Button()
_bframe = gtk.Frame()
_bframe.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_bframe.set_border_width(5)
_button.add(_bframe)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_da.modify_bg(gtk.STATE_NORMAL, _gtkcolor)
if not prefstate.hasWidgetKey('DIM_COLOR'):
prefstate.setWidget('DIM_COLOR', _da)
_button.connect("clicked", _select_dimbar_color)
_bframe.add(_da)
_fhbox.pack_start(_button, False, False, 5)
_table.attach(_fhbox, 0, 2, 4, 5,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
#
# options for dimension text position
#
_frame = gtk.Frame(_('Dimension Text Position'))
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_frame.add(_fhbox)
_label = gtk.Label(_('Text Location at crossbar:'))
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_cur_pos = globals.prefs['DIM_POSITION']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_dim_positions)):
_name = _dim_positions[_i]
if _cur_pos == Dimension.getPositionFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_dim_positions)):
_name = _dim_positions[_i]
if _cur_pos == Dimension.getPositionFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_POSITION'):
prefstate.setWidget('DIM_POSITION', _widget)
_fhbox.pack_start(_widget, False, False, 0)
_vbox.pack_start(_frame, False, False, 5)
#
# options for dimension crossbar/crossarc markers
#
_frame = gtk.Frame(_('Dimension Crossbar Markers'))
_table = gtk.Table(2, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
_label = gtk.Label(_('Dimension marker:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.FILL,
gtk.FILL,
2, 2)
_idx = 0
_endpt = globals.prefs['DIM_ENDPOINT']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_dim_endpoints)):
_name = _dim_endpoints[_i]
if _endpt == Dimension.getEndpointTypeFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_dim_endpoints)):
_name = _dim_endpoints[_i]
if _endpt == Dimension.getEndpointTypeFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_ENDPOINT'):
prefstate.setWidget('DIM_ENDPOINT', _widget)
_table.attach(_widget, 1, 2, 0, 1,
gtk.FILL,
gtk.FILL,
2, 2)
#
_label = gtk.Label(_('Marker size:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.FILL,
gtk.FILL,
2, 2)
_entry = gtk.Entry()
_size = "%f" % globals.prefs['DIM_ENDPOINT_SIZE']
_entry.set_text(_size)
if not prefstate.hasWidgetKey('DIM_ENDPOINT_SIZE'):
prefstate.setWidget('DIM_ENDPOINT_SIZE', _entry)
_entry.connect("activate", entry_activate)
_entry.connect("focus-out-event", _dim_marker_entry_focus_out, prefstate)
_handlerid = _entry.connect("insert-text", entry_insert_text)
_entry.set_data('handlerid', _handlerid)
_size_group.add_widget(_entry)
_table.attach(_entry, 1, 2, 1, 2,
gtk.FILL,
gtk.FILL,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
return _vbox
def _make_primary_opts(prefstate):
_vbox = gtk.VBox(False, 2)
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_IN)
_text = "%s" % _('Primary Dimension Options')
_label = gtk.Label(_text)
_label.set_use_markup(True)
_frame.add(_label)
_vbox.pack_start(_frame, False, False, 5)
_frame = gtk.Frame(_('Units'))
_frame.set_border_width(2)
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(2)
_frame.add(_fhbox)
_label = gtk.Label(_('Primary dimension units:'))
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_units = units.get_all_units()
_cur_unit = globals.prefs['DIM_PRIMARY_UNITS']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_units)):
if _i == _cur_unit:
_idx = _i
_widget.append_text(_units[_i])
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_units)):
if _i == _cur_unit:
_idx = _i
_item = gtk.MenuItem(_units[_i])
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_PRIMARY_UNITS'):
prefstate.setWidget('DIM_PRIMARY_UNITS', _widget)
_fhbox.pack_start(_widget, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
#
_label_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_menu_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
#
_frame = gtk.Frame(_('Font Properties'))
_frame.set_border_width(2)
_fvbox = gtk.VBox(False, 5)
_fvbox.set_border_width(2)
_frame.add(_fvbox)
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Family:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_families = prefstate.getFamilies()
if _families is None:
_families = []
_window = prefstate.getWindow()
for _family in _window.get_pango_context().list_families():
_families.append(_family.get_name())
_families.sort()
prefstate.setFamilies(_families)
_idx = 0
_family = globals.prefs['DIM_PRIMARY_FONT_FAMILY']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_families)):
_f = _families[_i]
if _family == _f:
_idx = _i
_widget.append_text(_f)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_families)):
_f = _families[_i]
if _family == _f:
_idx = _i
_item = gtk.MenuItem(_f)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_PRIMARY_FONT_FAMILY'):
prefstate.setWidget('DIM_PRIMARY_FONT_FAMILY', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Style:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_style = globals.prefs['DIM_PRIMARY_FONT_STYLE']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_font_styles)):
_name = _font_styles[_i]
if _style == TextStyle.getStyleFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_font_styles)):
_name = _font_styles[_i]
if _style == TextStyle.getStyleFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_PRIMARY_FONT_STYLE'):
prefstate.setWidget('DIM_PRIMARY_FONT_STYLE', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Weight:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_weight = globals.prefs['DIM_PRIMARY_FONT_WEIGHT']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_font_weights)):
_name = _font_weights[_i]
if _weight == TextStyle.getWeightFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_font_weights)):
_name =_font_weights[_i]
if _weight == TextStyle.getWeightFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_PRIMARY_FONT_WEIGHT'):
prefstate.setWidget('DIM_PRIMARY_FONT_WEIGHT', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Alignment:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_align = globals.prefs['DIM_PRIMARY_TEXT_ALIGNMENT']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_text_align)):
_name = _text_align[_i]
if _align == TextStyle.getAlignmentFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_text_align)):
_name = _text_align[_i]
if _align == TextStyle.getAlignmentFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_PRIMARY_TEXT_ALIGNMENT'):
prefstate.setWidget('DIM_PRIMARY_TEXT_ALIGNMENT', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Size:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_entry = gtk.Entry()
_size = "%f" % globals.prefs['DIM_PRIMARY_TEXT_SIZE']
_entry.set_text(_size)
if not prefstate.hasWidgetKey('DIM_PRIMARY_TEXT_SIZE'):
prefstate.setWidget('DIM_PRIMARY_TEXT_SIZE', _entry)
_entry.connect("activate", entry_activate)
_entry.connect("focus-out-event",
_dim_primary_textsize_entry_focus_out,
prefstate)
_handlerid = _entry.connect("insert-text", entry_insert_text)
_entry.set_data('handlerid', _handlerid)
# _entry_size_group.add_widget(_entry)
_fhbox.pack_start(_entry, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(2)
_label = gtk.Label(_('Color:'))
_fhbox.pack_start(_label, False, False, 5)
_color = globals.prefs['DIM_PRIMARY_FONT_COLOR']
_gtkcolor = gtk.gdk.color_parse(str(_color))
if hasattr(gtk, 'ColorButton'):
_button = gtk.ColorButton(color=_gtkcolor)
_button.set_title(_('Select Primary Dimension Font Color'))
if not prefstate.hasWidgetKey('DIM_PRIMARY_FONT_COLOR'):
prefstate.setWidget('DIM_PRIMARY_FONT_COLOR', _button)
else:
_button = gtk.Button()
_bframe = gtk.Frame()
_bframe.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_bframe.set_border_width(5)
_button.add(_bframe)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_da.modify_bg(gtk.STATE_NORMAL, _gtkcolor)
if not prefstate.hasWidgetKey('DIM_PRIMARY_FONT_COLOR'):
prefstate.setWidget('DIM_PRIMARY_FONT_COLOR', _da)
_button.connect("clicked", _select_font_color)
_bframe.add(_da)
_fhbox.pack_start(_button, False, False, 5)
_fvbox.pack_start(_fhbox, True, True, 5)
_vbox.pack_start(_frame, False, False, 5)
#
_frame = gtk.Frame(_('Format Options'))
_frame.set_border_width(2)
_table = gtk.Table(3, 1, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
_cb = gtk.CheckButton(_('Print leading 0'))
_state = globals.prefs['DIM_PRIMARY_LEADING_ZERO']
_cb.set_active(_state)
if not prefstate.hasWidgetKey('DIM_PRIMARY_LEADING_ZERO'):
prefstate.setWidget('DIM_PRIMARY_LEADING_ZERO', _cb)
_table.attach(_cb, 0, 1, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_cb = gtk.CheckButton(_('Print trailing decimal point'))
_state = globals.prefs['DIM_PRIMARY_TRAILING_DECIMAL']
_cb.set_active(_state)
if not prefstate.hasWidgetKey('DIM_PRIMARY_TRAILING_DECIMAL'):
prefstate.setWidget('DIM_PRIMARY_TRAILING_DECIMAL', _cb)
_table.attach(_cb, 0, 1, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_thbox = gtk.HBox(False, 5)
_label = gtk.Label(_('Display precision:'))
_thbox.pack_start(_label, False, False, 5)
_prec = globals.prefs['DIM_PRIMARY_PRECISION']
_adj = gtk.Adjustment(_prec, 0, 15, 1, 1, 1)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(0)
_sb.set_numeric(True)
if not prefstate.hasWidgetKey('DIM_PRIMARY_PRECISION'):
prefstate.setWidget('DIM_PRIMARY_PRECISION', _sb)
_thbox.pack_start(_sb, False, False, 5)
_table.attach(_thbox, 0, 1, 2, 3,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
return _vbox
def _make_snap_opts(prefstate):
"""
Populate the left side of pref panel
"""
_vbox = gtk.VBox(False, 2)
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_IN)
#
# Headers
#
_text = "%s" % _('Snap Options')
_label = gtk.Label(_text)
_label.set_use_markup(True)
_frame.add(_label)
_vbox.pack_start(_frame, False, True, 5)
#
# Create Snap option Container
#
_snapFrame = gtk.Frame("Snap")
_snapFrame.set_shadow_type(gtk.SHADOW_IN)
verticalBoxItem=len(globals.snapOption)
snapFrameVbox = gtk.VBox(True, verticalBoxItem)
#
# Fill Up snap Options
#
for key in globals.snapOption.keys():
newButton=createButtonOption(key,globals.snapOption[key])
newButton.connect("clicked", changeSnapState, None)
snapFrameVbox.add(newButton)
#
# Fill Up snap Functionality
#
_vbox.pack_start(snapFrameVbox, False, False, 5)
_label.show()
_frame.show()
_vbox.show()
return _vbox
def changeSnapState(self, widget, data=None):
"""
Change the state of the Global variable button
"""
# todo capire come fare a cambiare
# globals.snapOption
# per il settaggio dei valori
#
ret=self.get_active()
if self.get_label() in globals.snapOption:
globals.snapOption[self.get_label()]=ret
return
def createButtonOption(key,state):
"""
Create a button that show the snap state
"""
button=gtk.ToggleButton(key)
button.set_active(state)
button.show()
return button
def _make_secondary_opts(prefstate):
_vbox = gtk.VBox(False, 2)
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_IN)
_text = "%s" % _('Secondary Dimension Options')
_label = gtk.Label(_text)
_label.set_use_markup(True)
_frame.add(_label)
_vbox.pack_start(_frame, True, True, 5)
#
# it would be good to allow the widgets to be used if
# the check box is active ...
#
_cb = gtk.CheckButton(_('Display secondary dimension text'))
_state = globals.prefs['DIM_DUAL_MODE']
_cb.set_active(_state)
_cb.connect("toggled", _toggle_secondary_dim_opts, _vbox)
if not prefstate.hasWidgetKey('DIM_DUAL_MODE'):
prefstate.setWidget('DIM_DUAL_MODE', _cb)
_vbox.pack_start(_cb, False, False, 5)
_frame = gtk.Frame(_('Units'))
_frame.set_border_width(2)
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(2)
_frame.add(_fhbox)
_label = gtk.Label(_('Secondary dimension units:'))
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_units = units.get_all_units()
_cur_unit = globals.prefs['DIM_SECONDARY_UNITS']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_units)):
if _i == _cur_unit:
_idx = _i
_widget.append_text(_units[_i])
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_units)):
if _i == _cur_unit:
_idx = _i
_item = gtk.MenuItem(_units[_i])
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_SECONDARY_UNITS'):
prefstate.setWidget('DIM_SECONDARY_UNITS', _widget)
_fhbox.pack_start(_widget, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
#
_label_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_menu_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
#
_frame = gtk.Frame(_('Font Properties'))
_frame.set_border_width(2)
_fvbox = gtk.VBox(False, 5)
_fvbox.set_border_width(2)
_frame.add(_fvbox)
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Family:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_families = prefstate.getFamilies()
if _families is None:
_families = []
_window = prefstate.getWindow()
for _family in _window.get_pango_context().list_families():
_families.append(_family.get_name())
_families.sort()
prefstate.setFamilies(_families)
_idx = 0
_family = globals.prefs['DIM_SECONDARY_FONT_FAMILY']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_families)):
_f = _families[_i]
if _family == _f:
_idx = _i
_widget.append_text(_f)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_families)):
_f = _families[_i]
if _family == _f:
_idx = _i
_item = gtk.MenuItem(_f)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_SECONDARY_FONT_FAMILY'):
prefstate.setWidget('DIM_SECONDARY_FONT_FAMILY', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Style:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_style = globals.prefs['DIM_SECONDARY_FONT_STYLE']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_font_styles)):
_name = _font_styles[_i]
if _style == TextStyle.getStyleFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_font_styles)):
_name = _font_styles[_i]
if _style == TextStyle.getStyleFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_SECONDARY_FONT_STYLE'):
prefstate.setWidget('DIM_SECONDARY_FONT_STYLE', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Weight:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_weight = globals.prefs['DIM_SECONDARY_FONT_WEIGHT']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_font_weights)):
_name = _font_weights[_i]
if _weight == TextStyle.getWeightFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_font_weights)):
_name = _font_weights[_i]
if _weight == TextStyle.getWeightFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_SECONDARY_FONT_WEIGHT'):
prefstate.setWidget('DIM_SECONDARY_FONT_WEIGHT', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Alignment:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_align = globals.prefs['DIM_SECONDARY_TEXT_ALIGNMENT']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_text_align)):
_name = _text_align[_i]
if _align == TextStyle.getAlignmentFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_text_align)):
_name = _text_align[_i]
if _align == TextStyle.getAlignmentFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DIM_SECONDARY_TEXT_ALIGNMENT'):
prefstate.setWidget('DIM_SECONDARY_TEXT_ALIGNMENT', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Size:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_entry = gtk.Entry()
_size = "%f" % globals.prefs['DIM_SECONDARY_TEXT_SIZE']
_entry.set_text(_size)
if not prefstate.hasWidgetKey('DIM_SECONDARY_TEXT_SIZE'):
prefstate.setWidget('DIM_SECONDARY_TEXT_SIZE', _entry)
_entry.connect("activate", entry_activate)
_entry.connect("focus-out-event",
_dim_secondary_textsize_entry_focus_out,
prefstate)
_handlerid = _entry.connect("insert-text", entry_insert_text)
_entry.set_data('handlerid', _handlerid)
# _entry_size_group.add_widget(_entry)
_fhbox.pack_start(_entry, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(2)
_label = gtk.Label(_('Color:'))
_fhbox.pack_start(_label, False, False, 5)
_color = globals.prefs['DIM_SECONDARY_FONT_COLOR']
_gtkcolor = gtk.gdk.color_parse(str(_color))
if hasattr(gtk, 'ColorButton'):
_button = gtk.ColorButton(color=_gtkcolor)
_button.set_title(_('Select Secondary Dimension Font Color'))
if not prefstate.hasWidgetKey('DIM_SECONDARY_FONT_COLOR'):
prefstate.setWidget('DIM_SECONDARY_FONT_COLOR', _button)
else:
_button = gtk.Button()
_bframe = gtk.Frame()
_bframe.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_bframe.set_border_width(5)
_button.add(_bframe)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_da.modify_bg(gtk.STATE_NORMAL, _gtkcolor)
if not prefstate.hasWidgetKey('DIM_SECONDARY_FONT_COLOR'):
prefstate.setWidget('DIM_SECONDARY_FONT_COLOR', _da)
_button.connect("clicked", _select_font_color)
_bframe.add(_da)
_fhbox.pack_start(_button, False, False, 5)
_fvbox.pack_start(_fhbox, True, True, 5)
_vbox.pack_start(_frame, False, False, 5)
_frame = gtk.Frame(_('Format Options'))
_frame.set_border_width(2)
_table = gtk.Table(3, 1, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
_cb = gtk.CheckButton(_('Print leading 0'))
_state = globals.prefs['DIM_SECONDARY_LEADING_ZERO']
_cb.set_active(_state)
if not prefstate.hasWidgetKey('DIM_SECONDARY_LEADING_ZERO'):
prefstate.setWidget('DIM_SECONDARY_LEADING_ZERO', _cb)
_table.attach(_cb, 0, 1, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_cb = gtk.CheckButton(_('Print trailing decimal point'))
_state = globals.prefs['DIM_SECONDARY_TRAILING_DECIMAL']
_cb.set_active(_state)
if not prefstate.hasWidgetKey('DIM_SECONDARY_TRAILING_DECIMAL'):
prefstate.setWidget('DIM_SECONDARY_TRAILING_DECIMAL', _cb)
_table.attach(_cb, 0, 1, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_thbox = gtk.HBox(False, 5)
_label = gtk.Label(_('Display precision:'))
_thbox.pack_start(_label, False, False, 5)
_prec = globals.prefs['DIM_SECONDARY_PRECISION']
_adj = gtk.Adjustment(_prec, 0, 15, 1, 1, 1)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(0)
_sb.set_numeric(True)
if not prefstate.hasWidgetKey('DIM_SECONDARY_PRECISION'):
prefstate.setWidget('DIM_SECONDARY_PRECISION', _sb)
_thbox.pack_start(_sb, False, False, 5)
_table.attach(_thbox, 0, 1, 2, 3,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
_cb = prefstate.getWidget('DIM_DUAL_MODE')
_cb.emit("toggled")
return _vbox
def _make_linear_opts(prefstate):
_vbox = gtk.VBox(False, 5)
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_IN)
_text = "%s" % _('Linear Dimension Options')
_label = gtk.Label(_text)
_label.set_use_markup(True)
_frame.add(_label)
_vbox.pack_start(_frame, False, False, 5)
_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Primary Dimension Text Options'))
_table = gtk.Table(2, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
_label = gtk.Label(_('Default prefix:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['DIM_PRIMARY_PREFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('DIM_PRIMARY_PREFIX'):
prefstate.setWidget('DIM_PRIMARY_PREFIX', _entry)
_table.attach(_entry, 1, 2, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_label = gtk.Label(_('Default suffix:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['DIM_PRIMARY_SUFFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('DIM_PRIMARY_SUFFIX'):
prefstate.setWidget('DIM_PRIMARY_SUFFIX', _entry)
_table.attach(_entry, 1, 2, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
_frame = gtk.Frame(_('Secondary Dimension Text Options'))
_table = gtk.Table(2, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
if not prefstate.hasWidgetKey('LINEAR_SECONDARY_FRAME'):
prefstate.setWidget('LINEAR_SECONDARY_FRAME', _frame)
_label = gtk.Label(_('Default prefix:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['DIM_SECONDARY_PREFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('DIM_SECONDARY_PREFIX'):
prefstate.setWidget('DIM_SECONDARY_PREFIX', _entry)
_table.attach(_entry, 1, 2, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_label = gtk.Label(_('Default suffix:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['DIM_SECONDARY_SUFFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('DIM_SECONDARY_SUFFIX'):
prefstate.setWidget('DIM_SECONDARY_SUFFIX', _entry)
_table.attach(_entry, 1, 2, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
return _vbox
def _make_radial_opts(prefstate):
_vbox = gtk.VBox(False, 5)
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_IN)
_text = "%s" % _('Radial Dimension Options')
_label = gtk.Label(_text)
_label.set_use_markup(True)
_frame.add(_label)
_vbox.pack_start(_frame, False, False, 5)
_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Primary Dimension Text Options'))
_table = gtk.Table(2, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
_label = gtk.Label(_('Default prefix:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['RADIAL_DIM_PRIMARY_PREFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('RADIAL_DIM_PRIMARY_PREFIX'):
prefstate.setWidget('RADIAL_DIM_PRIMARY_PREFIX', _entry)
_table.attach(_entry, 1, 2, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_label = gtk.Label(_('Default suffix:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['RADIAL_DIM_PRIMARY_SUFFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('RADIAL_DIM_PRIMARY_SUFFIX'):
prefstate.setWidget('RADIAL_DIM_PRIMARY_SUFFIX', _entry)
_table.attach(_entry, 1, 2, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
_frame = gtk.Frame(_('Secondary Dimension Text Options'))
_table = gtk.Table(2, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
if not prefstate.hasWidgetKey('RADIAL_SECONDARY_FRAME'):
prefstate.setWidget('RADIAL_SECONDARY_FRAME', _frame)
_label = gtk.Label(_('Default prefix:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['RADIAL_DIM_SECONDARY_PREFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('RADIAL_DIM_SECONDARY_PREFIX'):
prefstate.setWidget('RADIAL_DIM_SECONDARY_PREFIX', _entry)
_table.attach(_entry, 1, 2, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_label = gtk.Label(_('Default suffix:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['RADIAL_DIM_SECONDARY_SUFFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('RADIAL_DIM_SECONDARY_SUFFIX'):
prefstate.setWidget('RADIAL_DIM_SECONDARY_SUFFIX', _entry)
_table.attach(_entry, 1, 2, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
_cb = gtk.CheckButton(_('Show diametrical dimension value'))
_state = globals.prefs['RADIAL_DIM_DIA_MODE']
_cb.set_active(_state)
if not prefstate.hasWidgetKey('RADIAL_DIM_DIA_MODE'):
prefstate.setWidget('RADIAL_DIM_DIA_MODE', _cb)
_vbox.pack_start(_cb, False, False, 5)
return _vbox
def _make_angular_opts(prefstate):
_vbox = gtk.VBox(False, 5)
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_IN)
_text = "%s" % _('Angular Dimension Options')
_label = gtk.Label(_text)
_label.set_use_markup(True)
_frame.add(_label)
_vbox.pack_start(_frame, False, False, 5)
_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Primary Dimension Text Options'))
_table = gtk.Table(2, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
_label = gtk.Label(_('Default prefix:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['ANGULAR_DIM_PRIMARY_PREFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('ANGULAR_DIM_PRIMARY_PREFIX'):
prefstate.setWidget('ANGULAR_DIM_PRIMARY_PREFIX', _entry)
_table.attach(_entry, 1, 2, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_label = gtk.Label(_('Default suffix:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['ANGULAR_DIM_PRIMARY_SUFFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('ANGULAR_DIM_PRIMARY_SUFFIX'):
prefstate.setWidget('ANGULAR_DIM_PRIMARY_SUFFIX', _entry)
_table.attach(_entry, 1, 2, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
_frame = gtk.Frame(_('Secondary Dimension Text Options'))
_table = gtk.Table(2, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
if not prefstate.hasWidgetKey('ANGULAR_SECONDARY_FRAME'):
prefstate.setWidget('ANGULAR_SECONDARY_FRAME', _frame)
_label = gtk.Label(_('Default prefix:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['ANGULAR_DIM_SECONDARY_PREFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('ANGULAR_DIM_SECONDARY_PREFIX'):
prefstate.setWidget('ANGULAR_DIM_SECONDARY_PREFIX', _entry)
_table.attach(_entry, 1, 2, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_label = gtk.Label(_('Default suffix:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_entry = gtk.Entry()
_entry.set_text(globals.prefs['ANGULAR_DIM_SECONDARY_SUFFIX'])
_size_group.add_widget(_entry)
if not prefstate.hasWidgetKey('ANGULAR_DIM_SECONDARY_SUFFIX'):
prefstate.setWidget('ANGULAR_DIM_SECONDARY_SUFFIX', _entry)
_table.attach(_entry, 1, 2, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
return _vbox
def _make_basic_opts(prefstate):
_vbox = gtk.VBox(False, 5)
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_IN)
_text = "%s" % _('Basic Options')
_label = gtk.Label(_text)
_label.set_use_markup(True)
_frame.add(_label)
_vbox.pack_start(_frame, False, False, 5)
_frame = gtk.Frame(_('Units'))
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_frame.add(_fhbox)
_label = gtk.Label(_('Drawing units:'))
_fhbox.pack_start(_label, False, False, 5)
_unit_list = units.get_all_units()
_cur_unit = globals.prefs['UNITS']
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_unit_list)):
if _i == _cur_unit:
_idx = _i
_widget.append_text(_unit_list[_i])
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_unit_list)):
if _i == _cur_unit:
_idx = _i
_item = gtk.MenuItem(_unit_list[_i])
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('DRAWING_UNITS'):
prefstate.setWidget('DRAWING_UNITS', _widget)
_fhbox.pack_start(_widget, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
_frame = gtk.Frame(_('Highlight Points'))
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_frame.add(_fhbox)
_cb = gtk.CheckButton(_('Boxes are drawn around Point objects'))
_state = globals.prefs['HIGHLIGHT_POINTS']
_cb.set_active(_state)
if not prefstate.hasWidgetKey('HIGHLIGHT_POINTS'):
prefstate.setWidget('HIGHLIGHT_POINTS', _cb)
_fhbox.pack_start(_cb, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
_frame = gtk.Frame(_('Autosplitting'))
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_frame.add(_fhbox)
_cb = gtk.CheckButton(_('New Points split existing entities'))
_state = globals.prefs['AUTOSPLIT']
_cb.set_active(_state)
if not prefstate.hasWidgetKey('AUTOSPLIT'):
prefstate.setWidget('AUTOSPLIT', _cb)
_fhbox.pack_start(_cb, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
_frame = gtk.Frame(_('Colors'))
_table = gtk.Table(4, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
_label = gtk.Label(_('Drawing area color:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.FILL,
gtk.FILL,
2, 2)
_color = globals.prefs['BACKGROUND_COLOR']
_gtkcolor = gtk.gdk.color_parse(str(_color))
if hasattr(gtk, 'ColorButton'):
_button = gtk.ColorButton(color=_gtkcolor)
_button.set_title(_('Select Background Color'))
if not prefstate.hasWidgetKey('BACKGROUND_COLOR'):
prefstate.setWidget('BACKGROUND_COLOR', _button)
else:
_button = gtk.Button()
_bframe = gtk.Frame()
_bframe.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_bframe.set_border_width(5)
_button.add(_bframe)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_da.modify_bg(gtk.STATE_NORMAL, _gtkcolor)
if not prefstate.hasWidgetKey('BACKGROUND_COLOR'):
prefstate.setWidget('BACKGROUND_COLOR', _da)
_bframe.add(_da)
_button.connect("clicked", _select_background_color)
_table.attach(_button, 1, 2, 0, 1,
gtk.FILL,
gtk.FILL,
2, 2)
#
_label = gtk.Label(_('Inactive layer color:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.FILL,
gtk.FILL,
2, 2)
_color = globals.prefs['INACTIVE_LAYER_COLOR']
_gtkcolor = gtk.gdk.color_parse(str(_color))
if hasattr(gtk, 'ColorButton'):
_button = gtk.ColorButton(color=_gtkcolor)
_button.set_title(_('Select Inactive Layer Color'))
if not prefstate.hasWidgetKey('INACTIVE_LAYER_COLOR'):
prefstate.setWidget('INACTIVE_LAYER_COLOR', _button)
else:
_button = gtk.Button()
_bframe = gtk.Frame()
_bframe.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_bframe.set_border_width(5)
_button.add(_bframe)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_da.modify_bg(gtk.STATE_NORMAL, _gtkcolor)
if not prefstate.hasWidgetKey('INACTIVE_LAYER_COLOR'):
prefstate.setWidget('INACTIVE_LAYER_COLOR', _da)
_bframe.add(_da)
_button.connect("clicked", _select_background_color)
_table.attach(_button, 1, 2, 1, 2,
gtk.FILL,
gtk.FILL,
2, 2)
#
_label = gtk.Label(_('Single point color:'))
_table.attach(_label, 0, 1, 2, 3,
gtk.FILL,
gtk.FILL,
2, 2)
_color = globals.prefs['SINGLE_POINT_COLOR']
_gtkcolor = gtk.gdk.color_parse(str(_color))
if hasattr(gtk, 'ColorButton'):
_button = gtk.ColorButton(color=_gtkcolor)
_button.set_title(_('Select Single Use Point Outline Color'))
if not prefstate.hasWidgetKey('SINGLE_POINT_COLOR'):
prefstate.setWidget('SINGLE_POINT_COLOR', _button)
else:
_button = gtk.Button()
_bframe = gtk.Frame()
_bframe.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_bframe.set_border_width(5)
_button.add(_bframe)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_da.modify_bg(gtk.STATE_NORMAL, _gtkcolor)
if not prefstate.hasWidgetKey('SINGLE_POINT_COLOR'):
prefstate.setWidget('SINGLE_POINT_COLOR', _da)
_bframe.add(_da)
_button.connect("clicked", _select_background_color)
_table.attach(_button, 1, 2, 2, 3,
gtk.FILL,
gtk.FILL,
2, 2)
#
_label = gtk.Label(_('Multi point color:'))
_table.attach(_label, 0, 1, 3, 4,
gtk.FILL,
gtk.FILL,
2, 2)
_color = globals.prefs['MULTI_POINT_COLOR']
_gtkcolor = gtk.gdk.color_parse(str(_color))
if hasattr(gtk, 'ColorButton'):
_button = gtk.ColorButton(color=_gtkcolor)
_button.set_title(_('Select Multi-Use Point Outline Color'))
if not prefstate.hasWidgetKey('MULTI_POINT_COLOR'):
prefstate.setWidget('MULTI_POINT_COLOR', _button)
else:
_button = gtk.Button()
_bframe = gtk.Frame()
_bframe.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_bframe.set_border_width(5)
_button.add(_bframe)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_da.modify_bg(gtk.STATE_NORMAL, _gtkcolor)
if not prefstate.hasWidgetKey('MULTI_POINT_COLOR'):
prefstate.setWidget('MULTI_POINT_COLOR', _da)
_bframe.add(_da)
_button.connect("clicked", _select_background_color)
_table.attach(_button, 1, 2, 3, 4,
gtk.FILL,
gtk.FILL,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Line Thickness'))
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_frame.add(_fhbox)
_label = gtk.Label(_('Thickness:'))
_fhbox.pack_start(_label, False, False, 5)
_entry = gtk.Entry()
_thickness = "%f" % globals.prefs['LINE_THICKNESS']
_entry.set_text(_thickness)
if not prefstate.hasWidgetKey('LINE_THICKNESS'):
prefstate.setWidget('LINE_THICKNESS', _entry)
_entry.connect("activate", entry_activate)
_entry.connect("focus-out-event", _thickness_entry_focus_out, prefstate)
_handlerid = _entry.connect("insert-text", entry_insert_text)
_entry.set_data('handlerid', _handlerid)
_size_group.add_widget(_entry)
_fhbox.pack_start(_entry, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
return _vbox
def _make_size_opts(prefstate):
_vbox = gtk.VBox(False, 5)
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_IN)
_label_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_entry_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_text = "%s" % _('Size Options')
_label = gtk.Label(_text)
_label.set_use_markup(True)
_frame.add(_label)
_vbox.pack_start(_frame, False, False, 5)
#
# leader line arrow size
#
_frame = gtk.Frame(_('Leader Arrow Size'))
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_frame.add(_fhbox)
_label = gtk.Label(_('Size:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_entry = gtk.Entry()
_arrowsize = "%f" % globals.prefs['LEADER_ARROW_SIZE']
_entry.set_text(_arrowsize)
if not prefstate.hasWidgetKey('LEADER_ARROW_SIZE'):
prefstate.setWidget('LEADER_ARROW_SIZE', _entry)
_entry.connect("activate", entry_activate)
_entry.connect("focus-out-event", _leader_entry_focus_out, prefstate)
_handlerid = _entry.connect("insert-text", entry_insert_text)
_entry.set_data('handlerid', _handlerid)
_entry_size_group.add_widget(_entry)
_fhbox.pack_start(_entry, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
#
# Chamfer length
#
_frame = gtk.Frame(_('Chamfer Length'))
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_frame.add(_fhbox)
_label = gtk.Label(_('Length:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_entry = gtk.Entry()
_length = "%f" % globals.prefs['CHAMFER_LENGTH']
_entry.set_text(_length)
if not prefstate.hasWidgetKey('CHAMFER_LENGTH'):
prefstate.setWidget('CHAMFER_LENGTH', _entry)
_entry.connect("activate", entry_activate)
_entry.connect("focus-out-event", _chamfer_entry_focus_out, prefstate)
_handlerid = _entry.connect("insert-text", entry_insert_text)
_entry.set_data('handlerid', _handlerid)
_entry_size_group.add_widget(_entry)
_fhbox.pack_start(_entry, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
#
# Fillet radius
#
_frame = gtk.Frame(_('Fillet Radius'))
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_frame.add(_fhbox)
_label = gtk.Label(_('Radius:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_entry = gtk.Entry()
_radius = "%f" % globals.prefs['FILLET_RADIUS']
_entry.set_text(_radius)
if not prefstate.hasWidgetKey('FILLET_RADIUS'):
prefstate.setWidget('FILLET_RADIUS', _entry)
_entry.connect("activate", entry_activate)
_entry.connect("focus-out-event", _fillet_entry_focus_out, prefstate)
_handlerid = _entry.connect("insert-text", entry_insert_text)
_entry.set_data('handlerid', _handlerid)
_entry_size_group.add_widget(_entry)
_fhbox.pack_start(_entry, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
return _vbox
def _make_text_opts(prefstate):
_vbox = gtk.VBox(False, 5)
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_IN)
_text = "%s" % _('Text Options')
_label = gtk.Label(_text)
_label.set_use_markup(True)
_frame.add(_label)
_vbox.pack_start(_frame, False, False, 5)
_label_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_menu_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Font Properties'))
_frame.set_border_width(5)
_fvbox = gtk.VBox(False, 5)
_frame.add(_fvbox)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Family:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_families = prefstate.getFamilies()
if _families is None:
_families = []
_window = prefstate.getWindow()
for _family in _window.get_pango_context().list_families():
_families.append(_family.get_name())
_families.sort()
prefstate.setFamilies(_families)
_idx = 0
_family = globals.prefs['FONT_FAMILY']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_families)):
_f = _families[_i]
if _family == _f:
_idx = _i
_widget.append_text(_f)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_families)):
_f = _families[_i]
if _family == _f:
_idx = _i
_item = gtk.MenuItem(_f)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('FONT_FAMILY'):
prefstate.setWidget('FONT_FAMILY', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Style:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_style = globals.prefs['FONT_STYLE']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_font_styles)):
_name = _font_styles[_i]
if _style == TextStyle.getStyleFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_font_styles)):
_name = _font_styles[_i]
if _style == TextStyle.getStyleFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('FONT_STYLE'):
prefstate.setWidget('FONT_STYLE', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Weight:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_weight = globals.prefs['FONT_WEIGHT']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_font_weights)):
_name = _font_weights[_i]
if _weight == TextStyle.getWeightFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_font_weights)):
_name = _font_weights[_i]
if _weight == TextStyle.getWeightFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('FONT_WEIGHT'):
prefstate.setWidget('FONT_WEIGHT', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Alignment:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_idx = 0
_align = globals.prefs['TEXT_ALIGNMENT']
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_text_align)):
_name = _text_align[_i]
if _align == TextStyle.getAlignmentFromString(_name):
_idx = _i
_widget.append_text(_name)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_text_align)):
_name = _text_align[_i]
if _align == TextStyle.getAlignmentFromString(_name):
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
if not prefstate.hasWidgetKey('TEXT_ALIGNMENT'):
prefstate.setWidget('TEXT_ALIGNMENT', _widget)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(2)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Color:'))
_fhbox.pack_start(_label, False, False, 5)
_color = globals.prefs['FONT_COLOR']
_gtkcolor = gtk.gdk.color_parse(str(_color))
if hasattr(gtk, 'ColorButton'):
_button = gtk.ColorButton(color=_gtkcolor)
_button.set_title(_('Select Font Color'))
if not prefstate.hasWidgetKey('FONT_COLOR'):
prefstate.setWidget('FONT_COLOR', _button)
else:
_button = gtk.Button()
_bframe = gtk.Frame()
_bframe.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_bframe.set_border_width(5)
_button.add(_bframe)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_da.modify_bg(gtk.STATE_NORMAL, _gtkcolor)
if not prefstate.hasWidgetKey('FONT_COLOR'):
prefstate.setWidget('FONT_COLOR', _da)
_button.connect("clicked", _select_font_color)
_bframe.add(_da)
_fhbox.pack_start(_button, False, False, 5)
#
_fhbox = gtk.HBox(False, 5)
_fhbox.set_border_width(5)
_fvbox.pack_start(_fhbox, False, False, 5)
_label = gtk.Label(_('Size:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 5)
_entry = gtk.Entry()
_size = "%f" % globals.prefs['TEXT_SIZE']
_entry.set_text(_size)
if not prefstate.hasWidgetKey('TEXT_SIZE'):
prefstate.setWidget('TEXT_SIZE', _entry)
_entry.connect("activate", entry_activate)
_entry.connect("focus-out-event", _textsize_entry_focus_out, prefstate)
_handlerid = _entry.connect("insert-text", entry_insert_text)
_entry.set_data('handlerid', _handlerid)
# _entry_size_group.add_widget(_entry)
_fhbox.pack_start(_entry, False, False, 5)
_vbox.pack_start(_frame, False, False, 5)
return _vbox
def _make_pref_tree(hbox, prefstate):
_sw = gtk.ScrolledWindow()
_sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
_sw.set_size_request(120, 300)
_tree_store = gtk.TreeStore(gobject.TYPE_STRING,
gobject.TYPE_STRING)
_iter1 = _tree_store.append(None)
_tree_store.set(_iter1, 0, _('Basic'))
_tree_store.set(_iter1, 1, 'basic')
_iter1 = _tree_store.append(None)
_tree_store.set(_iter1, 0, _('Sized Objects'))
_tree_store.set(_iter1, 1, 'sizes')
_iter1 = _tree_store.append(None)
_tree_store.set(_iter1, 0, _('Text'))
_tree_store.set(_iter1, 1, 'text')
#_tree_view = gtk.TreeView(_tree_store)
_iter1 = _tree_store.append(None)
# Snap
_tree_store.set(_iter1, 0, _('Snap'))
_tree_store.set(_iter1, 1, 'snap')
_tree_view = gtk.TreeView(_tree_store)
_iter1 = _tree_store.append(None)
# Dimension
_tree_store.set(_iter1, 0, _('Dimensions'))
_tree_store.set(_iter1, 1, 'dimensions')
_iter2 = _tree_store.append(_iter1)
_tree_store.set(_iter2, 0, _('Primary'))
_tree_store.set(_iter2, 1, 'primary')
_iter2 = _tree_store.append(_iter1)
_tree_store.set(_iter2, 0, _('Secondary'))
_tree_store.set(_iter2, 1, 'secondary')
_iter2 = _tree_store.append(_iter1)
_tree_store.set(_iter2, 0, _('Linear'))
_tree_store.set(_iter2, 1, 'linear')
_iter2 = _tree_store.append(_iter1)
_tree_store.set(_iter2, 0, _('Radial'))
_tree_store.set(_iter2, 1, 'radial')
_iter2 = _tree_store.append(_iter1)
_tree_store.set(_iter2, 0, _('Angular'))
_tree_store.set(_iter2, 1, 'angular')
_tree_view.set_reorderable(False) # no drag-and-drop
_select = _tree_view.get_selection()
_select.set_mode(gtk.SELECTION_SINGLE)
_select.connect("changed", tree_select_cb, prefstate)
_renderer = gtk.CellRendererText()
_column = gtk.TreeViewColumn(_("Options"), _renderer, text=0)
_tree_view.append_column(_column)
_sw.add(_tree_view)
hbox.pack_start(_sw, False, False, 5)
return _tree_view
def _set_dim_offset(prefstate):
_text = prefstate.getWidget('DIM_OFFSET').get_text()
if len(_text) and _text != '+':
globals.prefs['DIM_OFFSET'] = float(_text)
def _set_dim_extension(prefstate):
_text = prefstate.getWidget('DIM_EXTENSION').get_text()
if len(_text) and _text != '+':
globals.prefs['DIM_EXTENSION'] = float(_text)
def _set_dim_color(prefstate):
_widget = prefstate.getWidget('DIM_COLOR')
if hasattr(gtk, 'ColorButton') and isinstance(_widget, gtk.ColorButton):
_color = _widget.get_color()
elif isinstance(_widget, gtk.DrawingArea):
_color= _widget.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for DIM_COLOR: " + `type(_widget)`
_r, _g, _b = _get_rgb_values(_color)
_dimcolor = get_color(_r, _g, _b)
globals.prefs['DIM_EXTENSION'] = get_color(_r, _g, _b)
def _set_background_color(prefstate):
_widget = prefstate.getWidget('BACKGROUND_COLOR')
if hasattr(gtk, 'ColorButton') and isinstance(_widget, gtk.ColorButton):
_color = _widget.get_color()
elif isinstance(_widget, gtk.DrawingArea):
_color= _widget.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for BACKGROUND_COLOR: " + `type(_widget)`
_r, _g, _b = _get_rgb_values(_color)
globals.prefs['BACKGROUND_COLOR'] = get_color(_r, _g, _b)
def _set_inactive_layer_color(prefstate):
_widget = prefstate.getWidget('INACTIVE_LAYER_COLOR')
if hasattr(gtk, 'ColorButton') and isinstance(_widget, gtk.ColorButton):
_color = _widget.get_color()
elif isinstance(_widget, gtk.DrawingArea):
_color= _widget.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for INACTIVE_LAYER_COLOR: " + `type(_widget)`
_r, _g, _b = _get_rgb_values(_color)
globals.prefs['INACTIVE_LAYER_COLOR'] = get_color(_r, _g, _b)
def _set_single_point_color(prefstate):
_widget = prefstate.getWidget('SINGLE_POINT_COLOR')
if hasattr(gtk, 'ColorButton') and isinstance(_widget, gtk.ColorButton):
_color = _widget.get_color()
elif isinstance(_widget, gtk.DrawingArea):
_color= _widget.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for SINGLE_POINT_COLOR: " + `type(_widget)`
_r, _g, _b = _get_rgb_values(_color)
globals.prefs['SINGLE_POINT_COLOR'] = get_color(_r, _g, _b)
def _set_multi_point_color(prefstate):
_widget = prefstate.getWidget('MULTI_POINT_COLOR')
if hasattr(gtk, 'ColorButton') and isinstance(_widget, gtk.ColorButton):
_color = _widget.get_color()
elif isinstance(_widget, gtk.DrawingArea):
_color= _widget.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for MULTI_POINT_COLOR: " + `type(_widget)`
_r, _g, _b = _get_rgb_values(_color)
globals.prefs['MULTI_POINT_COLOR'] = get_color(_r, _g, _b)
def _set_font_color(prefstate):
_widget = prefstate.getWidget('FONT_COLOR')
if hasattr(gtk, 'ColorButton') and isinstance(_widget, gtk.ColorButton):
_color = _widget.get_color()
elif isinstance(_widget, gtk.DrawingArea):
_color= _widget.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for FONT_COLOR: " + `type(_widget)`
_r, _g, _b = _get_rgb_values(_color)
globals.prefs['FONT_COLOR'] = get_color(_r, _g, _b)
def _set_dim_primary_font_color(prefstate):
_widget = prefstate.getWidget('DIM_PRIMARY_FONT_COLOR')
if hasattr(gtk, 'ColorButton') and isinstance(_widget, gtk.ColorButton):
_color = _widget.get_color()
elif isinstance(_widget, gtk.DrawingArea):
_color= _widget.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for DIM_PRIMARY_FONT_COLOR: " + `type(_widget)`
_r, _g, _b = _get_rgb_values(_color)
globals.prefs['DIM_PRIMARY_FONT_COLOR'] = get_color(_r, _g, _b)
def _set_dim_secondary_font_color(prefstate):
_widget = prefstate.getWidget('DIM_SECONDARY_FONT_COLOR')
if hasattr(gtk, 'ColorButton') and isinstance(_widget, gtk.ColorButton):
_color = _widget.get_color()
elif isinstance(_widget, gtk.DrawingArea):
_color= _widget.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for DIM_SECONDARY_FONT_COLOR: " + `type(_widget)`
_r, _g, _b = _get_rgb_values(_color)
globals.prefs['DIM_SECONDARY_FONT_COLOR'] = get_color(_r, _g, _b)
def _set_line_thickness(prefstate):
_text = prefstate.getWidget('LINE_THICKNESS').get_text()
if len(_text) and _text != '+':
globals.prefs['LINE_THICKNESS'] = float(_text)
def _set_leader_arrow_size(prefstate):
_text = prefstate.getWidget('LEADER_ARROW_SIZE').get_text()
if len(_text) and _text != '+':
globals.prefs['LEADER_ARROW_SIZE'] = float(_text)
def _set_chamfer_length(prefstate):
_text = prefstate.getWidget('CHAMFER_LENGTH').get_text()
if len(_text) and _text != '+':
globals.prefs['CHAMFER_LENGTH'] = float(_text)
def _set_fillet_radius(prefstate):
_text = prefstate.getWidget('FILLET_RADIUS').get_text()
if len(_text) and _text != '+':
globals.prefs['FILLET_RADIUS'] = float(_text)
def _set_dim_endpoint_size(prefstate):
_text = prefstate.getWidget('DIM_ENDPOINT_SIZE').get_text()
if len(_text) and _text != '+':
globals.prefs['DIM_ENDPOINT_SIZE'] = float(_text)
def _set_text_size(prefstate):
_text = prefstate.getWidget('TEXT_SIZE').get_text()
if len(_text) and _text != '+':
globals.prefs['TEXT_SIZE'] = float(_text)
def _set_dim_primary_text_size(prefstate):
_text = prefstate.getWidget('DIM_PRIMARY_TEXT_SIZE').get_text()
if len(_text) and _text != '+':
globals.prefs['DIM_PRIMARY_TEXT_SIZE'] = float(_text)
def _set_dim_secondary_text_size(prefstate):
_text = prefstate.getWidget('DIM_SECONDARY_TEXT_SIZE').get_text()
if len(_text) and _text != '+':
globals.prefs['DIM_SECONDARY_TEXT_SIZE'] = float(_text)
def _set_dim_position_offset(prefstate):
_text = prefstate.getWidget('DIM_POSITION_OFFSET').get_text()
if len(_text) and _text != '+':
globals.prefs['DIM_POSITION_OFFSET'] = float(_text)
def _set_dim_dual_mode_offset(prefstate):
_text = prefstate.getWidget('DIM_DUAL_MODE_OFFSET').get_text()
if len(_text) and _text != '+':
globals.prefs['DIM_DUAL_MODE_OFFSET'] = float(_text)
def _set_dim_dual_mode(prefstate):
_cb = prefstate.getWidget('DIM_DUAL_MODE')
globals.prefs['DIM_DUAL_MODE'] = _cb.get_active()
def _set_highlight_points(prefstate):
_cb = prefstate.getWidget('HIGHLIGHT_POINTS')
globals.prefs['HIGHLIGHT_POINTS'] = _cb.get_active()
def _set_autosplit(prefstate):
_cb = prefstate.getWidget('AUTOSPLIT')
globals.prefs['AUTOSPLIT'] = _cb.get_active()
def _set_dim_primary_leading_zero(prefstate):
_cb = prefstate.getWidget('DIM_PRIMARY_LEADING_ZERO')
globals.prefs['DIM_PRIMARY_LEADING_ZERO'] = _cb.get_active()
def _set_dim_primary_trailing_decimal(prefstate):
_cb = prefstate.getWidget('DIM_PRIMARY_TRAILING_DECIMAL')
globals.prefs['DIM_PRIMARY_TRAILING_DECIMAL'] = _cb.get_active()
def _set_dim_primary_precision(prefstate):
_sb = prefstate.getWidget('DIM_PRIMARY_PRECISION')
globals.prefs['DIM_PRIMARY_PRECISION'] = _sb.get_value_as_int()
def _set_dim_secondary_leading_zero(prefstate):
_cb = prefstate.getWidget('DIM_SECONDARY_LEADING_ZERO')
globals.prefs['DIM_SECONDARY_LEADING_ZERO'] = _cb.get_active()
def _set_dim_secondary_trailing_decimal(prefstate):
_cb = prefstate.getWidget('DIM_SECONDARY_TRAILING_DECIMAL')
globals.prefs['DIM_SECONDARY_TRAILING_DECIMAL'] = _cb.get_active()
def _set_dim_secondary_precision(prefstate):
_sb = prefstate.getWidget('DIM_SECONDARY_PRECISION')
globals.prefs['DIM_SECONDARY_PRECISION'] = _sb.get_value_as_int()
def _set_dim_primary_prefix(prefstate):
_text = prefstate.getWidget('DIM_PRIMARY_PREFIX').get_text()
globals.prefs['DIM_PRIMARY_PREFIX'] = unicode(_text)
def _set_dim_primary_suffix(prefstate):
_text = prefstate.getWidget('DIM_PRIMARY_SUFFIX').get_text()
globals.prefs['DIM_PRIMARY_SUFFIX'] = unicode(_text)
def _set_dim_secondary_prefix(prefstate):
_text = prefstate.getWidget('DIM_SECONDARY_PREFIX').get_text()
globals.prefs['DIM_SECONDARY_PREFIX' ] = unicode(_text)
def _set_dim_secondary_suffix(prefstate):
_text = prefstate.getWidget('DIM_SECONDARY_SUFFIX').get_text()
globals.prefs['DIM_SECONDARY_SUFFIX'] = unicode(_text)
def _set_radial_dim_primary_prefix(prefstate):
_text = prefstate.getWidget('RADIAL_DIM_PRIMARY_PREFIX').get_text()
globals.prefs['RADIAL_DIM_PRIMARY_PREFIX'] = unicode(_text)
def _set_radial_dim_primary_suffix(prefstate):
_text = prefstate.getWidget('RADIAL_DIM_PRIMARY_SUFFIX').get_text()
globals.prefs['RADIAL_DIM_PRIMARY_SUFFIX'] = unicode(_text)
def _set_radial_dim_secondary_prefix(prefstate):
_text = prefstate.getWidget('RADIAL_DIM_SECONDARY_PREFIX').get_text()
globals.prefs['RADIAL_DIM_SECONDARY_PREFIX'] = unicode(_text)
def _set_radial_dim_secondary_suffix(prefstate):
_text = prefstate.getWidget('RADIAL_DIM_SECONDARY_SUFFIX').get_text()
globals.prefs['RADIAL_DIM_SECONDARY_SUFFIX'] = unicode(_text)
def _set_radial_dim_dia_mode(prefstate):
_cb = prefstate.getWidget('RADIAL_DIM_DIA_MODE')
globals.prefs['RADIAL_DIM_DIA_MODE'] = _cb.get_active()
def _set_angular_dim_primary_prefix(prefstate):
_text = prefstate.getWidget('ANGULAR_DIM_PRIMARY_PREFIX').get_text()
globals.prefs['ANGULAR_DIM_PRIMARY_PREFIX'] = unicode(_text)
def _set_angular_dim_primary_suffix(prefstate):
_text = prefstate.getWidget('ANGULAR_DIM_PRIMARY_SUFFIX').get_text()
globals.prefs['ANGULAR_DIM_PRIMARY_SUFFIX'] = unicode(_text)
def _set_angular_dim_secondary_prefix(prefstate):
_text = prefstate.getWidget('ANGULAR_DIM_SECONDARY_PREFIX').get_text()
globals.prefs['ANGULAR_DIM_SECONDARY_PREFIX'] = unicode(_text)
def _set_angular_dim_secondary_suffix(prefstate):
_text = prefstate.getWidget('ANGULAR_DIM_SECONDARY_SUFFIX').get_text()
globals.prefs['ANGULAR_DIM_SECONDARY_SUFFIX'] = unicode(_text)
def _set_drawing_units(prefstate):
_widget = prefstate.getWidget('DRAWING_UNITS')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_unit = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_unit = _widget.get_history()
else:
raise TypeError, "Unexpected DRAWING_UNITS widget: " + `type(_widget)`
globals.prefs['UNITS'] = _unit
def _set_dim_primary_units(prefstate):
_widget = prefstate.getWidget('DIM_PRIMARY_UNITS')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_unit = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_unit = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_PRIMARY_UNITS widget: " + `type(_widget)`
globals.prefs['DIM_PRIMARY_UNITS'] = _unit
def _set_dim_secondary_units(prefstate):
_widget = prefstate.getWidget('DIM_SECONDARY_UNITS')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_unit = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_unit = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_SECONDARY_UNITS widget: " + `type(_widget)`
globals.prefs['DIM_SECONDARY_UNITS'] = _unit
def _set_dim_endpoint(prefstate):
_widget = prefstate.getWidget('DIM_ENDPOINT')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_ENDPOINT widget: " + `type(_widget)`
_endpoint = Dimension.getEndpointTypeFromString(_dim_endpoints[_idx])
globals.prefs['DIM_ENDPOINT'] = _endpoint
def _set_dim_position(prefstate):
_widget = prefstate.getWidget('DIM_POSITION')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_POSITION widget: " + `type(_widget)`
_pos = Dimension.getPositionFromString(_dim_positions[_idx])
globals.prefs['DIM_POSITION'] = _pos
def _set_font_family(prefstate):
_widget = prefstate.getWidget('FONT_FAMILY')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected FONT_FAMILY widget: " + `type(_widget)`
_families = prefstate.getFamilies()
globals.prefs['FONT_FAMILY'] = _families[_idx]
def _set_font_style(prefstate):
_widget = prefstate.getWidget('FONT_STYLE')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected FONT_STYLE widget: " + `type(_widget)`
_style = TextStyle.getStyleFromString(_font_styles[_idx])
globals.prefs['FONT_STYLE']= _style
def _set_font_weight(prefstate):
_widget = prefstate.getWidget('FONT_WEIGHT')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected FONT_WEIGHT widget: " + `type(_widget)`
_weight = TextStyle.getWeightFromString(_font_weights[_idx])
globals.prefs['FONT_WEIGHT'] = _weight
def _set_text_alignment(prefstate):
_widget = prefstate.getWidget('TEXT_ALIGNMENT')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected TEXT_ALIGNMENT widget: " + `type(_widget)`
_align = TextStyle.getAlignmentFromString(_text_align[_idx])
globals.prefs['TEXT_ALIGNMENT'] = _align
def _set_dim_primary_font_family(prefstate):
_widget = prefstate.getWidget('DIM_PRIMARY_FONT_FAMILY')
_families = prefstate.getFamilies()
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_PRIMARY_FONT_FAMILY widget: " + `type(_widget)`
globals.prefs['DIM_PRIMARY_FONT_FAMILY'] = _families[_idx]
def _set_dim_primary_font_style(prefstate):
_widget = prefstate.getWidget('DIM_PRIMARY_FONT_STYLE')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_PRIMARY_FONT_STYLE widget: " + `type(_widget)`
_style = TextStyle.getStyleFromString(_font_styles[_idx])
globals.prefs['DIM_PRIMARY_FONT_STYLE'] = _style
def _set_dim_primary_font_weight(prefstate):
_widget = prefstate.getWidget('DIM_PRIMARY_FONT_WEIGHT')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_PRIMARY_FONT_WEIGHT widget: " + `type(_widget)`
_weight = TextStyle.getWeightFromString(_font_weights[_idx])
globals.prefs['DIM_PRIMARY_FONT_WEIGHT'] = _weight
def _set_dim_primary_text_alignment(prefstate):
_widget = prefstate.getWidget('DIM_PRIMARY_TEXT_ALIGNMENT')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_PRIMARY_TEXT_ALIGNMENT widget: " + `type(_widget)`
_align = TextStyle.getAlignmentFromString(_text_align[_idx])
globals.prefs['DIM_PRIMARY_TEXT_ALIGNMENT'] = _align
def _set_dim_primary_font(prefstate):
_fontsel = prefstate.getWidget('DIM_PRIMARY_FONT')
_font = _fontsel.get_font_name()
_family, _style, _weight, _stretch, _size = (None, None, None, None, None)
globals.prefs['DIM_PRIMARY_FONT_FAMILY'] = _family
globals.prefs['DIM_PRIMARY_TEXT_SIZE'] = float(_size) # fixme
globals.prefs['DIM_PRIMARY_FONT_STYLE'] = _style
globals.prefs['DIM_PRIMARY_FONT_WEIGHT'] = _weight
def _set_dim_secondary_font_family(prefstate):
_widget = prefstate.getWidget('DIM_SECONDARY_FONT_FAMILY')
_families = prefstate.getFamilies()
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_SECONDARY_FONT_FAMILY widget: " + `type(_widget)`
globals.prefs['DIM_SECONDARY_FONT_FAMILY'] = _families[_idx]
def _set_dim_secondary_font_style(prefstate):
_widget = prefstate.getWidget('DIM_SECONDARY_FONT_STYLE')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_SECONDARY_FONT_STYLE widget: " + `type(_widget)`
_style = TextStyle.getStyleFromString(_font_styles[_idx])
globals.prefs['DIM_SECONDARY_FONT_STYLE'] = _style
def _set_dim_secondary_font_weight(prefstate):
_widget = prefstate.getWidget('DIM_SECONDARY_FONT_WEIGHT')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_SECONDARY_FONT_WEIGHT widget: " + `type(_widget)`
_weight = TextStyle.getWeightFromString(_font_weights[_idx])
globals.prefs['DIM_SECONDARY_FONT_WEIGHT'] = _weight
def _set_dim_secondary_text_alignment(prefstate):
_widget = prefstate.getWidget('DIM_SECONDARY_TEXT_ALIGNMENT')
if hasattr(gtk, 'ComboBox') and isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected DIM_SECONDARY_TEXT_ALIGNMENT widget: " + `type(_widget)`
_align = TextStyle.getAlignmentFromString(_text_align[_idx])
globals.prefs['DIM_SECONDARY_TEXT_ALIGNMENT'] = _align
def _set_dim_secondary_font(prefstate):
_fontsel = prefstate.getWidget('DIM_SECONDARY_FONT')
_font = _fontsel.get_font_name()
_family, _style, _weight, _stretch, _size = (None, None, None, None, None)
globals.prefs['DIM_SECONDARY_FONT_FAMILY'] = _family
globals.prefs['DIM_SECONDARY_TEXT_SIZE'] = float(_size) # fixme
globals.prefs['DIM_SECONDARY_FONT_STYLE'] = _style
globals.prefs['DIM_SECONDARY_FONT_WEIGHT'] = _weight
def _set_snap_option(prefstate):
"""
set Snap Option
"""
_keymap = {
'DIM_OFFSET' : _set_dim_offset,
'DIM_EXTENSION' : _set_dim_extension,
'DIM_COLOR' : _set_dim_color,
'BACKGROUND_COLOR' : _set_background_color,
'INACTIVE_LAYER_COLOR' : _set_inactive_layer_color,
'SINGLE_POINT_COLOR' : _set_single_point_color,
'MULTI_POINT_COLOR' : _set_multi_point_color,
'FONT_COLOR' : _set_font_color,
'DIM_PRIMARY_FONT_COLOR' : _set_dim_primary_font_color,
'DIM_SECONDARY_FONT_COLOR' : _set_dim_secondary_font_color,
'LINE_THICKNESS' : _set_line_thickness,
'LEADER_ARROW_SIZE' : _set_leader_arrow_size,
'CHAMFER_LENGTH' : _set_chamfer_length,
'FILLET_RADIUS' : _set_fillet_radius,
'HIGHLIGHT_POINTS' : _set_highlight_points,
'AUTOSPLIT' : _set_autosplit,
'DIM_PRIMARY_FONT_FAMILY' : _set_dim_primary_font_family,
'DIM_PRIMARY_FONT_STYLE' : _set_dim_primary_font_style,
'DIM_PRIMARY_FONT_WEIGHT' : _set_dim_primary_font_weight,
'DIM_PRIMARY_TEXT_SIZE' : _set_dim_primary_text_size,
'DIM_PRIMARY_TEXT_ALIGNMENT' : _set_dim_primary_text_alignment,
'DIM_PRIMARY_PRECISION' : _set_dim_primary_precision,
'DIM_PRIMARY_LEADING_ZERO' : _set_dim_primary_leading_zero,
'DIM_PRIMARY_TRAILING_DECIMAL' : _set_dim_primary_trailing_decimal,
'DIM_SECONDARY_FONT_FAMILY' : _set_dim_secondary_font_family,
'DIM_SECONDARY_FONT_STYLE' : _set_dim_secondary_font_style,
'DIM_SECONDARY_FONT_WEIGHT' : _set_dim_secondary_font_weight,
'DIM_SECONDARY_TEXT_SIZE' : _set_dim_secondary_text_size,
'DIM_SECONDARY_TEXT_ALIGNMENT' : _set_dim_secondary_text_alignment,
'DIM_SECONDARY_PRECISION' : _set_dim_secondary_precision,
'DIM_SECONDARY_LEADING_ZERO' : _set_dim_secondary_leading_zero,
'DIM_SECONDARY_TRAILING_DECIMAL' : _set_dim_secondary_trailing_decimal,
'DIM_PRIMARY_PREFIX' : _set_dim_primary_prefix,
'DIM_PRIMARY_SUFFIX' : _set_dim_primary_suffix,
'DIM_SECONDARY_PREFIX' : _set_dim_secondary_prefix,
'DIM_SECONDARY_SUFFIX' : _set_dim_secondary_suffix,
'RADIAL_DIM_PRIMARY_PREFIX' : _set_radial_dim_primary_prefix,
'RADIAL_DIM_PRIMARY_SUFFIX' : _set_radial_dim_primary_suffix,
'RADIAL_DIM_SECONDARY_PREFIX' : _set_radial_dim_secondary_prefix,
'RADIAL_DIM_SECONDARY_SUFFIX' : _set_radial_dim_secondary_suffix,
'RADIAL_DIM_DIA_MODE' : _set_radial_dim_dia_mode,
'ANGULAR_DIM_PRIMARY_PREFIX' : _set_angular_dim_primary_prefix,
'ANGULAR_DIM_PRIMARY_SUFFIX' : _set_angular_dim_primary_suffix,
'ANGULAR_DIM_SECONDARY_PREFIX' : _set_angular_dim_secondary_prefix,
'ANGULAR_DIM_SECONDARY_SUFFIX' : _set_angular_dim_secondary_suffix,
'DRAWING_UNITS' : _set_drawing_units,
'DIM_PRIMARY_UNITS' : _set_dim_primary_units,
'DIM_SECONDARY_UNITS' : _set_dim_secondary_units,
'FONT_FAMILY' : _set_font_family,
'FONT_STYLE' : _set_font_style,
'FONT_WEIGHT' : _set_font_weight,
'TEXT_SIZE' : _set_text_size,
'TEXT_ALIGNMENT' : _set_text_alignment,
'DIM_PRIMARY_FONT' : _set_dim_primary_font,
'DIM_SECONDARY_FONT' : _set_dim_secondary_font,
'DIM_ENDPOINT' : _set_dim_endpoint,
'DIM_ENDPOINT_SIZE' : _set_dim_endpoint_size,
'DIM_DUAL_MODE' : _set_dim_dual_mode,
'DIM_POSITION' : _set_dim_position,
'DIM_DUAL_MODE_OFFSET' : _set_dim_dual_mode_offset,
'DIM_POSITION_OFFSET' : _set_dim_position_offset,
'SNAP_OPTION' : _set_snap_option,
}
def apply_prefs(prefstate):
"""
apply preferences to from the dialog
"""
for _key in prefstate.getWidgetKeys():
# print "widget key: " + _key
if _key in _keymap:
_optfunc = _keymap[_key]
_optfunc(prefstate)
# else:
# print "no function for " + _key
def prefs_dialog(gtkimage):
"""
Create Preferences dialog
"""
_window = gtkimage.getWindow()
_prefstate = Prefstate()
_prefstate.setImage(gtkimage.image)
_prefstate.setWindow(_window)
_dialog = gtk.Dialog(_('Set Preferences'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 5)
_prefstate.setHBox(_hbox)
_hbox.set_border_width(5)
_dialog.vbox.pack_start(_hbox, True, True)
_tree_view = _make_pref_tree(_hbox, _prefstate)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
apply_prefs(_prefstate)
preferences.save_user_prefs()
_prefstate.clear()
_dialog.destroy()
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkmirror.py 0000644 0001750 0001750 00000011533 11307666732 021777 0 ustar matteo matteo #
# Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 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
#
#
# functions for doing mirroring operations
#
import pygtk
pygtk.require('2.0')
import gtk
from PythonCAD.Generic.hcline import HCLine
from PythonCAD.Generic.acline import ACLine
from PythonCAD.Generic.vcline import VCLine
from PythonCAD.Generic.cline import CLine
from PythonCAD.Generic import mirror
def mirror_objects(gtkimage, tool, objs):
_mline = tool.getMirrorLine()
tool.reset()
_prompt = _('Click on the mirroring construction line.')
if len(objs):
_image = gtkimage.getImage()
_image.startAction()
try:
mirror.mirror_objects(_mline, objs)
finally:
_image.endAction()
mirror_mode_init(gtkimage)
else:
gtkimage.refresh()
_prompt = ('Click on an object to mirror')
tool.setMirrorLine(_mline)
tool.setHandler("button_press", first_button_press_cb)
gtkimage.setPrompt(_prompt)
def select_motion_notify(gtkimage, widget, event, tool):
_tx, _ty = tool.getLocation()
_px, _py = gtkimage.coordToPixTransform(_tx, _ty)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_xmin = min(_xc, _px)
_ymin = min(_yc, _py)
_rw = abs(_xc - _px)
_rh = abs(_yc - _py)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _rw, _rh)
tool.setCurrentPoint(_x, _y)
_xmin = min(_x, _px)
_ymin = min(_y, _py)
_rw = abs(_x - _px)
_rh = abs(_y - _py)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _rw, _rh)
return True
def second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_active_layer = _image.getActiveLayer()
_pts = _active_layer.find('point', _x, _y)
if len(_pts) > 0:
_x, _y = _pts[0].getCoords()
_x1, _y1 = tool.getLocation()
_xmin = min(_x1, _x)
_ymin = min(_y1, _y)
_xmax = max(_x1, _x)
_ymax = max(_y1, _y)
_objs = _active_layer.objsInRegion(_xmin, _ymin, _xmax, _ymax, True)
mirror_objects(gtkimage, tool, _objs)
return True
def first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
_objs = []
for _obj, _pt in _objdict[_active_layer]:
_objs.append(_obj)
mirror_objects(gtkimage, tool, _objs)
else:
_x, _y = _image.getClosestPoint(_x, _y, tolerance=_tol)
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", second_button_press_cb)
gtkimage.setPrompt(_('Enclose objects to mirror with the box'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def get_mirror_line_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
for _obj, _pt in _objdict[_active_layer]:
if isinstance(_obj, (HCLine, VCLine, ACLine, CLine)):
tool.setMirrorLine(_obj)
if _image.hasSelection():
mirror_objects(gtkimage, tool,
_image.getSelectedObjects())
else:
tool.setHandler("button_press", first_button_press_cb)
gtkimage.setPrompt(_('Click on an object to mirror'))
break
return True
def mirror_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the mirroring construction line'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", get_mirror_line_cb)
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkdimension.py 0000644 0001750 0001750 00000043134 11307666732 022454 0 ustar matteo matteo #
# Copyright (c) 2002, 2003, 2004, 2006, 2007 Art Haas
#
# 2009 Matteo Boscolo
#
# 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
#
#
# gtk dimension code
#
import pygtk
pygtk.require('2.0')
import gtk
import pango
from PythonCAD.Generic.dimension import Dimension
from PythonCAD.Interface.Gtk import gtktext
from PythonCAD.Generic import snap
#
# linear dimension motion-notify handler
#
def dim_pts_motion_notify_cb(gtkimage, widget, event, tool):
_tx, _ty = tool.getLocation()
_px, _py = gtkimage.coordToPixTransform(_tx, _ty)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
_segs = []
if _cp is not None:
_xc, _yc = _cp
_segs.append((_px, _py, _xc, _yc))
tool.setCurrentPoint(_x, _y)
_segs.append((_px, _py, _x, _y))
widget.window.draw_segments(_gc, _segs)
return True
def dim_txt_motion_notify_cb(gtkimage, widget, event, tool):
_ix, _iy = gtkimage.image.getCurrentPoint()
_gc = gtkimage.getGC()
_ex = int(event.x)
_ey = int(event.y)
_cp = tool.getCurrentPoint()
_dim = tool.getDimension()
_bar1, _bar2 = _dim.getDimBars()
_crossbar = _dim.getDimCrossbar()
_segs = []
if _cp is not None:
_ep1, _ep2 = _bar1.getEndpoints()
_px1, _py1 = gtkimage.coordToPixTransform(_ep1[0], _ep1[1])
_px2, _py2 = gtkimage.coordToPixTransform(_ep2[0], _ep2[1])
_segs.append((_px1, _py1, _px2, _py2))
_ep1, _ep2 = _bar2.getEndpoints()
_px1, _py1 = gtkimage.coordToPixTransform(_ep1[0], _ep1[1])
_px2, _py2 = gtkimage.coordToPixTransform(_ep2[0], _ep2[1])
_segs.append((_px1, _py1, _px2, _py2))
_ep1, _ep2 = _crossbar.getEndpoints()
_px1, _py1 = gtkimage.coordToPixTransform(_ep1[0], _ep1[1])
_px2, _py2 = gtkimage.coordToPixTransform(_ep2[0], _ep2[1])
_segs.append((_px1, _py1, _px2, _py2))
tool.setCurrentPoint(_ex, _ey)
_dim.setLocation(_ix, _iy)
_dim.calcDimValues(False)
_ep1, _ep2 = _bar1.getEndpoints()
_px1, _py1 = gtkimage.coordToPixTransform(_ep1[0], _ep1[1])
_px2, _py2 = gtkimage.coordToPixTransform(_ep2[0], _ep2[1])
_segs.append((_px1, _py1, _px2, _py2))
_ep1, _ep2 = _bar2.getEndpoints()
_px1, _py1 = gtkimage.coordToPixTransform(_ep1[0], _ep1[1])
_px2, _py2 = gtkimage.coordToPixTransform(_ep2[0], _ep2[1])
_segs.append((_px1, _py1, _px2, _py2))
_ep1, _ep2 = _crossbar.getEndpoints()
_px1, _py1 = gtkimage.coordToPixTransform(_ep1[0], _ep1[1])
_px2, _py2 = gtkimage.coordToPixTransform(_ep2[0], _ep2[1])
_segs.append((_px1, _py1, _px2, _py2))
widget.window.draw_segments(_gc, _segs)
return True
def add_dimension(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_init_func = _tool.getHandler("initialize")
_image = gtkimage.getImage()
_image.startAction()
try:
_tool.create(_image)
finally:
_image.endAction()
_init_func(gtkimage)
def linear_text_button_press_cb(gtkimage, widget, event, tool):
_x, _y = gtkimage.image.getCurrentPoint()
_ldim = tool.getDimension()
_ldim.setLocation(_x, _y)
_ldim.calcDimValues()
_ldim.reset()
add_dimension(gtkimage)
return True
def linear_second_button_press_cb(gtkimage, widget, event, tool):
_snapArray={'perpendicular':False,'tangent':False}
_strPnt=snap.getSnapOnTruePoint(gtkimage,_snapArray)
if _strPnt.point is not None:
_x, _y = _strPnt.point.getCoords()
tool.setSecondPoint(_strPnt.point)
tool.setDimPosition(_x, _y)
tool.clearCurrentPoint()
tool.makeDimension(gtkimage.getImage())
#
# set GraphicsContext to Dimension color
#
_gc = gtkimage.getGC()
_gc.set_function(gtk.gdk.INVERT)
_col = tool.getDimension().getColor()
_gc.set_foreground(gtkimage.getColor(_col))
tool.setHandler("button_press", linear_text_button_press_cb)
tool.setHandler("motion_notify", dim_txt_motion_notify_cb)
gtkimage.setPrompt(_('Click where the dimension text should go.'))
gtkimage.refresh()
return True
def linear_first_button_press_cb(gtkimage, widget, event, tool):
_snapArray={'perpendicular':False,'tangent':False}
_strPnt=snap.getSnapOnTruePoint(gtkimage,_snapArray)
if _strPnt is not None:
_x, _y =_strPnt.point.getCoords()
tool.setLocation(_x, _y)
tool.setFirstPoint(_strPnt.point)
tool.setHandler("button_press", linear_second_button_press_cb)
tool.setHandler("motion_notify", dim_pts_motion_notify_cb)
gtkimage.setPrompt(_('Click on the second point for the dimension.'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
else:
gtkimage.setPrompt(_('Click on the first point for the dimension.'))
tool.setHandler("button_press", linear_first_button_press_cb)
tool.setHandler("initialize", linear_mode_init)
return True
#
# linear dimensions
#
def linear_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the first point for the dimension.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", linear_first_button_press_cb)
_tool.setHandler("initialize", linear_mode_init)
#
# horizontal dimensions
#
def horizontal_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the first point for the dimension.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", linear_first_button_press_cb)
_tool.setHandler("initialize", horizontal_mode_init)
#
# vertical dimensions
#
def vertical_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the first point for the dimension.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", linear_first_button_press_cb)
_tool.setHandler("initialize", vertical_mode_init)
#
# radial dimensions
#
def radial_txt_motion_notify_cb(gtkimage, widget, event, tool):
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_rdim = tool.getDimension()
_crossbar = _rdim.getDimCrossbar()
_cp = tool.getCurrentPoint()
_segs = []
if _cp is not None:
_p1, _p2 = _crossbar.getEndpoints()
_p0x, _p0y = gtkimage.coordToPixTransform(_p1[0], _p1[1])
_p1x, _p1y = gtkimage.coordToPixTransform(_p2[0], _p2[1])
_segs.append((_p0x, _p0y, _p1x, _p1y))
tool.setCurrentPoint(_x, _y)
_ix, _iy = gtkimage.image.getCurrentPoint()
_rdim.setLocation(_ix, _iy)
_rdim.calcDimValues(False)
_p1, _p2 = _crossbar.getEndpoints()
_p0x, _p0y = gtkimage.coordToPixTransform(_p1[0], _p1[1])
_p1x, _p1y = gtkimage.coordToPixTransform(_p2[0], _p2[1])
_segs.append((_p0x, _p0y, _p1x, _p1y))
widget.window.draw_segments(_gc, _segs)
return True
def radial_text_button_press_cb(gtkimage, widget, event, tool):
_x, _y = gtkimage.image.getCurrentPoint()
_rdim = tool.getDimension()
_rdim.setLocation(_x, _y)
_rdim.calcDimValues()
_rdim.reset()
add_dimension(gtkimage)
return True
def radial_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_dc = None
_layers = [_image.getTopLayer()]
while(len(_layers)):
_layer = _layers.pop()
if _layer.isVisible():
_cobjs = (_layer.getLayerEntities("circle") +
_layer.getLayerEntities("arc"))
for _cobj in _cobjs:
_mp = _cobj.mapCoords(_x, _y, _tol)
if _mp is not None:
_dc = _cobj
break
_layers.extend(_layer.getSublayers())
if _dc is not None:
_x, _y = _mp
tool.setDimObject(_dc)
tool.setDimPosition(_x, _y)
tool.makeDimension(_image)
tool.setHandler("motion_notify", radial_txt_motion_notify_cb)
tool.setHandler("button_press", radial_text_button_press_cb)
gtkimage.setPrompt(_('Click where the dimension text should be placed.'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def radial_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on an arc or a circle to dimension.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", radial_mode_init)
_tool.setHandler("button_press", radial_button_press_cb)
#
# angular dimensions
#
def adim_txt_motion_notify_cb(gtkimage, widget, event, tool):
_ix, _iy = gtkimage.image.getCurrentPoint()
_gc = gtkimage.getGC()
_ex = int(event.x)
_ey = int(event.y)
_cp = tool.getCurrentPoint()
_adim = tool.getDimension()
_vx, _vy = _adim.getVertexPoint().getCoords()
_px, _py = gtkimage.coordToPixTransform(_vx, _vy)
_win = widget.window
_bar1, _bar2 = _adim.getDimBars()
_crossarc = _adim.getDimCrossarc()
_segs = []
if _cp is not None:
#
# draw bars
#
_ep1, _ep2 = _bar1.getEndpoints()
_p1x, _p1y = gtkimage.coordToPixTransform(_ep1[0], _ep1[1])
_p2x, _p2y = gtkimage.coordToPixTransform(_ep2[0], _ep2[1])
_segs.append((_p1x, _p1y, _p2x, _p2y))
_ep1, _ep2 = _bar2.getEndpoints()
_p1x, _p1y = gtkimage.coordToPixTransform(_ep1[0], _ep1[1])
_p2x, _p2y = gtkimage.coordToPixTransform(_ep2[0], _ep2[1])
_segs.append((_p1x, _p1y, _p2x, _p2y))
_win.draw_segments(_gc, _segs)
del _segs[:]
#
# draw arc
#
_sa = _crossarc.getStartAngle()
_ea = _crossarc.getEndAngle()
_rad = int(_crossarc.getRadius()/gtkimage.getUnitsPerPixel())
_pxmin = _px - _rad
_pymin = _py - _rad
_cw = _ch = _rad * 2
if _sa < _ea:
_sweep = _ea - _sa
else:
_sweep = 360.0 - (_sa - _ea)
_win.draw_arc(_gc, False, _pxmin, _pymin, _cw, _ch,
int(_sa * 64), int(_sweep * 64))
tool.setCurrentPoint(_ex, _ey)
_adim.setLocation(_ix, _iy)
_adim.calcDimValues(False)
#
# draw bars
#
_ep1, _ep2 = _bar1.getEndpoints()
_p1x, _p1y = gtkimage.coordToPixTransform(_ep1[0], _ep1[1])
_p2x, _p2y = gtkimage.coordToPixTransform(_ep2[0], _ep2[1])
_segs.append((_p1x, _p1y, _p2x, _p2y))
_ep1, _ep2 = _bar2.getEndpoints()
_p1x, _p1y = gtkimage.coordToPixTransform(_ep1[0], _ep1[1])
_p2x, _p2y = gtkimage.coordToPixTransform(_ep2[0], _ep2[1])
_segs.append((_p1x, _p1y, _p2x, _p2y))
_win.draw_segments(_gc, _segs)
#
# draw arc
#
_sa = _crossarc.getStartAngle()
_ea = _crossarc.getEndAngle()
_rad = int(_crossarc.getRadius()/gtkimage.getUnitsPerPixel())
_pxmin = _px - _rad
_pymin = _py - _rad
_cw = _ch = _rad * 2
if _sa < _ea:
_sweep = _ea - _sa
else:
_sweep = 360.0 - (_sa - _ea)
_win.draw_arc(_gc, False, _pxmin, _pymin, _cw, _ch,
int(_sa * 64), int(_sweep * 64))
return True
def angular_pts_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_active_layer = _image.getActiveLayer()
_pt = None
_pts = _active_layer.find('point',_x, _y, _tol)
if len(_pts) > 0:
_pt = _pts[0]
if _pt is None:
_layers = [_image.getTopLayer()]
while(len(_layers)):
_layer = _layers.pop()
if _layer is not _active_layer and _layer.isVisible():
_pts = _layer.find('point', _x, _y, _tol)
if len(_pts) > 0:
_pt = _pts[0]
break
_layers.extend(_layer.getSublayers())
if _pt is not None:
_x, _y = _pt.getCoords()
tool.storeCoords(_x, _y)
if len(tool) == 2:
tool.pushObject(_pt)
else:
from PythonCAD.Generic.dimension import AngularDimension
_p1 = tool.popObject()
_vp = tool.popObject()
_ds = _image.getOption("DIM_STYLE")
_adim = AngularDimension(_vp, _p1, _pt, _x, _y, _ds)
tool.pushObject(_adim)
return True
def angular_text_button_press_cb(gtkimage, widget, event, tool):
_x, _y = gtkimage.image.getCurrentPoint()
_adim = tool.getDimension()
_adim.setLocation(_x, _y)
_adim.calcDimValues()
_adim.reset()
add_dimension(gtkimage)
return True
def angular_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_layers = [_image.getTopLayer()]
while len(_layers):
_layer = _layers.pop()
if _layer.isVisible():
_pt = None
_pts = _layer.find('point', _x, _y, _tol)
if len(_pts) > 0:
_pt = _pts[0]
if _pt is not None:
_x, _y = _pt.getCoords()
tool.setLocation(_x, _y)
tool.setSecondPoint(_pt)
tool.setDimPosition(_x, _y)
tool.makeDimension(_image)
#
# set GraphicsContext to Dimension color
#
_gc = gtkimage.getGC()
_gc.set_function(gtk.gdk.INVERT)
_col = tool.getDimension().getColor()
_gc.set_foreground(gtkimage.getColor(_col))
tool.setHandler("button_press", angular_text_button_press_cb)
tool.setHandler("motion_notify", adim_txt_motion_notify_cb)
gtkimage.setPrompt(_('Click where the dimension text should be located.'))
gtkimage.refresh()
break
_layers.extend(_layer.getSublayers())
return True
def angular_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_layers = [_image.getTopLayer()]
while len(_layers):
_layer = _layers.pop()
if _layer.isVisible():
_pt = None
_pts = _layer.find('point', _x, _y, _tol)
if len(_pts) > 0:
_pt = _pts[0]
if _pt is not None:
_x, _y = _pt.getCoords()
tool.setLocation(_x, _y)
tool.setFirstPoint(_pt)
tool.setHandler("button_press", angular_second_button_press_cb)
gtkimage.setPrompt(_('Click on the second point for the dimension.'))
break
_layers.extend(_layer.getSublayers())
return True
def _test_layer(l, x, y, tol):
_pt = _arc = None
_pts = l.find('point', x, y)
if len(_pts) > 0:
_pt = _pts[0]
if _pt is None:
_pts = l.find('point', x, y, tol)
if len(_pts) > 0:
_pt = _pts[0]
if _pt is None:
_arc_pt = None
for _arc in l.getLayerEntities("arc"):
_arc_pt = _arc.mapCoords(x, y, tol)
if _arc_pt is not None:
break
if _arc_pt is None:
_arc = None # no hits on any arcs ...
return _pt, _arc
def angular_initial_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_active_layer = _image.getActiveLayer()
_pt, _arc = _test_layer(_active_layer, _x, _y, _tol)
if _pt is None and _arc is None:
_layers = [_image.getTopLayer()]
while len(_layers):
_layer = _layers.pop()
if _layer is not _active_layer and _layer.isVisible():
_pt, _arc = _test_layer(_layer, _x, _y, _tol)
if _pt is not None or _arc is not None:
break
_layers.extend(_layer.getSublayers())
if _pt is not None:
tool.setVertexPoint(_pt)
tool.setHandler("button_press", angular_first_button_press_cb)
gtkimage.setPrompt(_('Click on the first endpoint for the dimension.'))
elif _arc is not None:
_cp = _arc.getCenter()
tool.setVertexPoint(_cp)
_ep1, _ep2 = _arc.getEndpoints()
_ex, _ey = _ep1
_pts = _active_layer.find('point', _ex, _ey)
assert len(_pts) > 0, "Missing arc first endpoint"
tool.setFirstPoint(_pts[0])
_ex, _ey = _ep2
_pts = _active_layer.find('point', _ex, _ey)
assert len(_pts) > 0, "Missing arc second endpoint"
tool.setSecondPoint(_pts[0])
tool.setDimPosition(_x, _y)
tool.makeDimension(_image)
tool.setHandler("button_press", angular_text_button_press_cb)
tool.setHandler("motion_notify", adim_txt_motion_notify_cb)
gtkimage.getGC().set_function(gtk.gdk.INVERT)
gtkimage.setPrompt(_('Click where the dimension text should be located.'))
return True
def angular_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the angle vertex point or an arc.'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", angular_initial_button_press_cb)
_tool.setHandler("initialize", angular_mode_init)
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkDialog.py 0000644 0001750 0001750 00000010207 11307674214 021653 0 ustar matteo matteo #
# Copyright (c) 2009 Matteo Boscolo
#
# 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 for dialogs
#
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import sys
import os
ioDebug=True
def _error_dialog(gtkimage, errmsg):
"""
Show an error dialog
"""
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('PythonCad Error'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_label = gtk.Label(errmsg)
_dialog.vbox.pack_start(_label, True, True, 0)
_label.show()
_dialog.show_all()
_response = _dialog.run()
_dialog.destroy()
if ioDebug :
for s in sys.exc_info():
print "Exception Error: %s"%str(s)
def _message_dialog(gtkimage,label1,label2):
"""
Create a dialogo with two label to give more information at the user
"""
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('PythonCad Message'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_label1 = gtk.Label(label1)
_label2 = gtk.Label(label2)
_dialog.vbox.pack_start(_label1, True, True, 0)
_dialog.vbox.pack_start(_label2, True, True, 0)
_label1.show()
_label2.show()
_dialog.show_all()
_response = _dialog.run()
_dialog.destroy()
def _yesno_dialog(gtkimage,label):
"""
Create a dialogo with a label and a yes no button
"""
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('PythonCad Message'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
_label = gtk.Label(label)
_dialog.vbox.pack_start(_label, True, True, 0)
_label.show()
_dialog.show_all()
_response = _dialog.run()
_dialog.destroy()
return _response
def delete_event(widget, event, data=None):
gtk.main_quit()
return False
def _help_dialog(gtkimage,Command):
"""
Show the help dialog for the specifie comand
Need to be implemented
1) open a child windows that show html text
2) load the command file
"""
pass
def abautDialog():
"""
Show The application debug dialog
"""
_abautDialog=gtk.AboutDialog()
_abautDialog.set_name("PythonCad")
_abautDialog.set_program_name("PythonCad")
_abautDialog.set_version("DS1-R37")
_abautDialog.set_comments("CAD built from Python")
_iconPath=os.path.join(os.getcwd(),"gtkpycad.png")
_pixBuf=gtk.gdk.pixbuf_new_from_file(_iconPath)
_abautDialog.set_logo(_pixBuf)
_abautDialog.set_website("http://sourceforge.net/projects/pythoncad")
_licMsg='PythonCAD is distributed in the hope that it will be useful, \n \
but WITHOUT ANY WARRANTY; without even the implied warranty of \n \
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n \
GNU General Public License for more details. \n \
You should have received a copy of the GNU General Public License \n \
along with PythonCAD; if not, write to the Free Software \n \
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA'
_abautDialog.set_license(_licMsg)
response = _abautDialog.run()
_abautDialog.destroy()
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/__init__.py 0000644 0001750 0001750 00000002105 11307666657 021517 0 ustar matteo matteo #
# Copyright (c) 2002, 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
#
#
# define __all__ so that "from Interface/Gtk import *" works
#
__all__ = [
'gtkactions',
'gtkconobjs',
'gtkdimension',
'gtkedit',
'gtkentities',
'gtkimage',
'gtkinit',
'gtkmenus',
'gtkmirror',
'gtkmodify',
'gtkprefs',
'gtkprinting',
'gtkshell',
'gtktext'
]
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkinit.py 0000644 0001750 0001750 00000153557 11307666732 021445 0 ustar matteo matteo #
# Copyright (c) 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 for adding graphical methods to drawing entities
#
import types
from math import pi
_dtr = (pi/180.0)
import pygtk
pygtk.require('2.0')
import gtk
import pango
from PythonCAD.Generic import color
from PythonCAD.Generic import point
from PythonCAD.Generic import segment
from PythonCAD.Generic import circle
from PythonCAD.Generic import arc
from PythonCAD.Generic import leader
from PythonCAD.Generic import polyline
from PythonCAD.Generic import segjoint
from PythonCAD.Generic import conobject
from PythonCAD.Generic import hcline
from PythonCAD.Generic import vcline
from PythonCAD.Generic import acline
from PythonCAD.Generic import cline
from PythonCAD.Generic import ccircle
from PythonCAD.Generic import text
from PythonCAD.Generic import dimension
from PythonCAD.Generic import layer
from PythonCAD.Interface.Gtk import gtkimage
def _set_gc_values(gc, dl, c, t):
if dl is None:
_lt = gtk.gdk.LINE_SOLID
else:
_lt = gtk.gdk.LINE_DOUBLE_DASH
gc.set_dashes(0, dl)
gc.set_foreground(c)
_t = t
if not isinstance(_t, int):
_t = int(round(t))
if _t < 1: # no zero-pixel lines
_t = 1
gc.set_function(gtk.gdk.COPY)
gc.set_line_attributes(_t, _lt, gtk.gdk.CAP_ROUND, gtk.gdk.JOIN_MITER)
_point_color = color.Color(255, 255, 255) # white
def _draw_point(self, gimage, col=None):
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_x, _y = self.getCoords()
_px, _py = gimage.coordToPixTransform(_x, _y)
_w, _h = gimage.getSize()
if (((_px + 5) < 0) or
((_py + 5) < 0) or
((_px - 5) > _w) or
((_py - 5) > _h)):
return
if _col is None:
_col = _point_color
_pixmap = _gc = None
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
_ctx.move_to(_px, _py)
_ctx.line_to(_px, _py)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_gc.set_foreground(gimage.getColor(_col))
_pixmap = gimage.getPixmap()
_pixmap.draw_point(_gc, _px, _py)
_image = gimage.getImage()
if _image.getOption('HIGHLIGHT_POINTS'):
_count = 0
for _user in self.getUsers():
if not isinstance(_user, dimension.Dimension):
_count = _count + 1
if _count > 1:
break
if _count > 1:
_col = _image.getOption('MULTI_POINT_COLOR')
else:
_col = _image.getOption('SINGLE_POINT_COLOR')
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
_ctx.rectangle((_px - 5), (_py - 5), 10, 10)
_ctx.stroke()
_ctx.restore()
else:
_set_gc_values(_gc, None, gimage.getColor(_col), 1)
_pixmap.draw_rectangle(_gc, False, (_px - 5), (_py - 5), 10, 10)
def _erase_point(self, gimage):
_x, _y = self.getCoords()
_px, _py = gimage.coordToPixTransform(_x, _y)
_w, _h = gimage.getSize()
if (((_px + 5) < 0) or
((_py + 5) < 0) or
((_px - 5) > _w) or
((_py - 5) > _h)):
return
_image = gimage.getImage()
_col = _image.getOption('BACKGROUND_COLOR')
_pixmap = _gc = None
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
if(_col!=None):
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
_ctx.move_to(_px, _py)
_ctx.line_to(_px, _py)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_gc.set_foreground(gimage.getColor(_col))
_pixmap = gimage.getPixmap()
_pixmap.draw_point(_gc, _px, _py)
if _image.getOption('HIGHLIGHT_POINTS'):
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
_ctx.rectangle((_px - 5), (_py - 5), 10, 10)
_ctx.stroke()
_ctx.restore()
else:
_gc.set_function(gtk.gdk.COPY)
_gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_ROUND, gtk.gdk.JOIN_MITER)
_pixmap.draw_rectangle(_gc, False, (_px - 5), (_py - 5), 10, 10)
def _draw_segment(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_xmin, _ymin, _xmax, _ymax = gimage.getView()
_coords = self.clipToRegion(_xmin, _ymin, _xmax, _ymax)
if _coords is not None:
_p1, _p2 = self.getEndpoints()
_x1, _y1, _x2, _y2 = _coords
_p1x, _p1y = gimage.coordToPixTransform(_x1, _y1)
_p2x, _p2y = gimage.coordToPixTransform(_x2, _y2)
if _col is None:
_col = self.getColor()
_dlist = self.getLinetype().getList()
_lw = self.getThickness()/gimage.getUnitsPerPixel()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(_lw)
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), _lw)
gimage.getPixmap().draw_line(_gc, _p1x, _p1y, _p2x, _p2y)
def _erase_segment(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_circle(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_cp = self.getCenter()
_x, _y = _cp.getCoords()
_r = self.getRadius()
_px, _py = gimage.coordToPixTransform(_x, _y)
_rx, _ry = gimage.coordToPixTransform((_x + _r), _y)
_rad = _rx - _px
if _col is None:
_col = self.getColor()
_dlist = self.getLinetype().getList()
_lw = self.getThickness()/gimage.getUnitsPerPixel()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(_lw)
_ctx.arc(_px, _py, _rad, 0, (2.0 * pi))
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), _lw)
_pxmin = _px - _rad
_pymin = _py - _rad
_cw = _ch = _rad * 2
gimage.getPixmap().draw_arc(_gc, False,
_pxmin, _pymin,
_cw, _ch,
0, (360*64))
def _erase_circle(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_arc(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_layer = self.getParent()
if _layer is None:
raise RuntimeError, "No parent Layer for Arc"
_cp = self.getCenter()
_x, _y = _cp.getCoords()
_r = self.getRadius()
_sa = self.getStartAngle()
_ea = self.getEndAngle()
_px, _py = gimage.coordToPixTransform(_x, _y)
_rx, _ry = gimage.coordToPixTransform((_x + _r), _y)
_rad = _rx - _px
if _col is None:
_col = self.getColor()
_dlist = self.getLinetype().getList()
_lw = self.getThickness()/gimage.getUnitsPerPixel()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(_lw)
_rsa = _sa * _dtr
_rea = _ea * _dtr
#
# arc drawing relies on Cairo transformations
#
_ctx.scale(1.0, -1.0)
_ctx.translate(_px, -(_py))
if abs(_sa - _ea) < 1e-10:
_ctx.arc(0, 0, _rad, _rsa, (_rsa + (2.0 * pi)))
else:
_ctx.arc(0, 0, _rad, _rsa, _rea)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
for _ep in self.getEndpoints():
_ex, _ey = _ep
_pts = _layer.find('point', _ex, _ey)
if len(_pts) == 0:
raise RuntimeError, "No Arc endpoint at: " + str(_ep)
_ept = None
for _pt in _pts:
for _user in _pt.getUsers():
if _user is self:
_ept = _pt
break
if _ept is not None:
break
if abs(_sa - _ea) < 1e-10:
break
_pxmin = _px - _rad
_pymin = _py - _rad
_cw = _ch = _rad * 2
_set_gc_values(_gc, _dlist, gimage.getColor(_col), _lw)
if abs(_sa - _ea) < 1e-10:
_sweep = 360.0
elif _sa > _ea:
_sweep = 360.0 - (_sa - _ea)
else:
_sweep = _ea - _sa
gimage.getPixmap().draw_arc(_gc, False,
_pxmin, _pymin,
_cw, _ch,
int(round(_sa * 64)),
int(round(_sweep * 64)))
def _erase_arc(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_leader(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_p1, _p2, _p3 = self.getPoints()
_p1x, _p1y = gimage.coordToPixTransform(_p1.x, _p1.y)
_p2x, _p2y = gimage.coordToPixTransform(_p2.x, _p2.y)
_p3x, _p3y = gimage.coordToPixTransform(_p3.x, _p3.y)
_pts = self.getArrowPoints()
_a1x, _a1y = gimage.coordToPixTransform(_pts[0], _pts[1])
_a2x, _a2y = gimage.coordToPixTransform(_pts[2], _pts[3])
if _col is None:
_col = self.getColor()
_dlist = self.getLinetype().getList()
_lw = self.getThickness()/gimage.getUnitsPerPixel()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(_lw)
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_ctx.line_to(_p3x, _p3y)
_ctx.stroke()
_ctx.move_to(_p3x, _p3y)
_ctx.line_to(_a1x, _a1y)
_ctx.line_to(_a2x, _a2y)
_ctx.close_path()
_ctx.fill()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), _lw)
_pixmap = gimage.getPixmap()
_pts = [(_p1x, _p1y), (_p2x, _p2y), (_p3x, _p3y)]
_pixmap.draw_lines(_gc, _pts)
_apts = [(_p3x, _p3y), (_a1x, _a1y), (_a2x, _a2y)]
_pixmap.draw_polygon(_gc, True, _apts)
def _erase_leader(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_polyline(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_pts = []
for _pt in self.getPoints():
_x, _y = _pt.getCoords()
_px, _py = gimage.coordToPixTransform(_x, _y)
_pts.append((_px, _py))
if _col is None:
_col = self.getColor()
_dlist = self.getLinetype().getList()
_lw = self.getThickness()/gimage.getUnitsPerPixel()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(_lw)
_px, _py = _pts[0]
_ctx.move_to(_px, _py)
for _px, _py in _pts[1:]:
_ctx.line_to(_px, _py)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), _lw)
gimage.getPixmap().draw_lines(_gc, _pts)
def _erase_polyline(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_chamfer(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_p1, _p2 = self.getMovingPoints()
_p1x, _p1y = gimage.coordToPixTransform(_p1.x, _p1.y)
_p2x, _p2y = gimage.coordToPixTransform(_p2.x, _p2.y)
if _col is None:
_col = self.getColor()
_dlist = self.getLinetype().getList()
_lw = self.getThickness()/gimage.getUnitsPerPixel()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(_lw)
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), _lw)
gimage.getPixmap().draw_line(_gc, _p1x, _p1y, _p2x, _p2y)
def _erase_chamfer(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_fillet(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
if _col is None:
_col = self.getColor()
_cx, _cy = self.getCenter()
_pcx, _pcy = gimage.coordToPixTransform(_cx, _cy)
_p1, _p2 = self.getMovingPoints()
_p1x, _p1y = gimage.coordToPixTransform(_p1.x, _p1.y)
_p2x, _p2y = gimage.coordToPixTransform(_p2.x, _p2.y)
_r = self.getRadius()
_rx, _ry = gimage.coordToPixTransform((_cx + _r), _cy)
_pr = _rx - _pcx
_sa1, _sa2 = self.getAngles()
_amin = min(_sa1, _sa2)
_amax = max(_sa1, _sa2)
if _amax - _amin > 180.0:
_a1 = _amax
_a2 = _amin
else:
_a1 = _amin
_a2 = _amax
# print "a1: %g" % _a1
# print "a2: %g" % _a2
_dlist = self.getLinetype().getList()
_lw = self.getThickness()/gimage.getUnitsPerPixel()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(_lw)
_ra1 = _a1 * _dtr
_ra2 = _a2 * _dtr
#
# arc drawing relies on Cairo transformations
#
_ctx.scale(1.0, -1.0)
_ctx.translate(_pcx, -(_pcy))
_ctx.arc(0, 0, _pr, _ra1, _ra2)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), _lw)
_pxmin = _pcx - _pr
_pymin = _pcy - _pr
_cw = _ch = _pr * 2
if _a1 > _a2:
_sweep = 360.0 - (_a1 - _a2)
else:
_sweep = _a2 - _a1
gimage.getPixmap().draw_arc(_gc, False,
_pxmin, _pymin,
_cw, _ch,
int(round(_a1 * 64)),
int(round(_sweep * 64)))
def _erase_fillet(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_hcline(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_lp = self.getLocation()
_x, _y = _lp.getCoords()
_px, _py = gimage.coordToPixTransform(_x, _y)
if _col is None:
_col = self.getColor()
_dlist = self.getLinetype().getList()
_w, _h = gimage.getSize()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(1.0)
_ctx.move_to(0, _py)
_ctx.line_to(_w, _py)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), 1)
gimage.getPixmap().draw_line(_gc, 0, _py, _w, _py)
def _erase_hcline(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_vcline(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_lp = self.getLocation()
_x, _y = _lp.getCoords()
_px, _py = gimage.coordToPixTransform(_x, _y)
if _col is None:
_col = self.getColor()
_dlist = self.getLinetype().getList()
_w, _h = gimage.getSize()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(1.0)
_ctx.move_to(_px, 0)
_ctx.line_to(_px, _h)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), 1)
gimage.getPixmap().draw_line(_gc, _px, 0, _px, _h)
def _erase_vcline(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_acline(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_xmin, _ymin, _xmax, _ymax = gimage.getView()
_coords = self.clipToRegion(_xmin, _ymin, _xmax, _ymax)
if _coords is not None:
_lp = self.getLocation()
_x1, _y1, _x2, _y2 = _coords
_p1x, _p1y = gimage.coordToPixTransform(_x1, _y1)
_p2x, _p2y = gimage.coordToPixTransform(_x2, _y2)
_p1x, _p1y = gimage.coordToPixTransform(_x1, _y1)
_p2x, _p2y = gimage.coordToPixTransform(_x2, _y2)
if _col is None:
_col = self.getColor()
_dlist = self.getLinetype().getList()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(1.0)
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), 1)
gimage.getPixmap().draw_line(_gc, _p1x, _p1y, _p2x, _p2y)
def _erase_acline(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_cline(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_xmin, _ymin, _xmax, _ymax = gimage.getView()
_coords = self.clipToRegion(_xmin, _ymin, _xmax, _ymax)
if _coords is not None:
_p1, _p2 = self.getKeypoints()
_x1, _y1, _x2, _y2 = _coords
_p1x, _p1y = gimage.coordToPixTransform(_x1, _y1)
_p2x, _p2y = gimage.coordToPixTransform(_x2, _y2)
if _col is None:
_col = self.getColor()
_dlist = self.getLinetype().getList()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(1.0)
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), 1)
gimage.getPixmap().draw_line(_gc, _p1x, _p1y, _p2x, _p2y)
def _erase_cline(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_ccircle(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_cp = self.getCenter()
_x, _y = _cp.getCoords()
_r = self.getRadius()
_px, _py = gimage.coordToPixTransform(_x, _y)
_rx, _ry = gimage.coordToPixTransform((_x + _r), _y)
_rad = _rx - _px
_dlist = self.getLinetype().getList()
if _col is None:
_col = self.getColor()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _dlist is not None:
_ctx.set_dash(_dlist)
_ctx.set_line_width(1.0)
_ctx.arc(_px, _py, _rad, 0, (2.0 * pi))
_ctx.stroke()
_ctx.restore()
else:
_gc = gimage.getGC()
_set_gc_values(_gc, _dlist, gimage.getColor(_col), 1)
_cw = _ch = _rad * 2
_pxmin = _px - _rad
_pymin = _py - _rad
gimage.getPixmap().draw_arc(_gc, False,
_pxmin, _pymin,
_cw, _ch,
0, (360*64))
def _erase_ccircle(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _format_layout(self, gimage, layout):
_fd = pango.FontDescription()
_fd.set_family(self.getFamily())
_val = self.getStyle()
if _val == text.TextStyle.FONT_NORMAL:
_style = pango.STYLE_NORMAL
elif _val == text.TextStyle.FONT_OBLIQUE:
_style = pango.STYLE_OBLIQUE
elif _val == text.TextStyle.FONT_ITALIC:
_style = pango.STYLE_ITALIC
else:
raise ValueError, "Unexpected TextBlock font style: %d" % _val
_fd.set_style(_style)
_val = self.getWeight()
if _val == text.TextStyle.WEIGHT_NORMAL:
_weight = pango.WEIGHT_NORMAL
elif _val == text.TextStyle.WEIGHT_LIGHT:
_weight = pango.WEIGHT_LIGHT
elif _val == text.TextStyle.WEIGHT_BOLD:
_weight = pango.WEIGHT_BOLD
elif _val == text.TextStyle.WEIGHT_HEAVY:
_weight = pango.WEIGHT_HEAVY
else:
raise ValueError, "Unexpected TextBlock font weight: %d" % _val
_fd.set_weight(_weight)
_upp = gimage.getUnitsPerPixel()
_sz = int(pango.SCALE * (self.getSize()/_upp))
if _sz < pango.SCALE:
_sz = pango.SCALE
# print "pango units text size: %d" % _sz
_fd.set_size(_sz)
#
# todo: handle drawing rotated text
#
_align = self.getAlignment()
if _align == text.TextStyle.ALIGN_LEFT:
layout.set_alignment(pango.ALIGN_LEFT)
elif _align == text.TextStyle.ALIGN_CENTER:
layout.set_alignment(pango.ALIGN_CENTER)
elif _align == text.TextStyle.ALIGN_RIGHT:
layout.set_alignment(pango.ALIGN_RIGHT)
else:
raise ValueError, "Unexpected TextBlock alignment value: %d" % _align
layout.set_font_description(_fd)
if self.getLineCount() > 0:
_w, _h = layout.get_pixel_size()
self.setBounds((_w * _upp), (_h * _upp))
def _draw_textblock(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_text = self.getText()
_ctx = gimage.getCairoContext()
if _ctx is not None:
_layout = _ctx.create_layout()
_layout.set_text(_text)
else:
_layout = gimage.getDA().create_pango_layout(_text)
self._formatLayout(gimage, _layout)
_x, _y = self.getLocation()
_px, _py = gimage.coordToPixTransform(_x, _y)
if _col is None:
_col = self.getColor()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
_ctx.move_to(_px, _py)
_ctx.show_layout(_layout)
_ctx.restore()
else:
_gc = gimage.getGC()
_gc.set_foreground(gimage.getColor(_col))
_gc.set_function(gtk.gdk.COPY)
gimage.getPixmap().draw_layout(_gc, _px, _py, _layout)
_layout = None
def _erase_textblock(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_dimstrings(self, gimage, col=None):
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_da = gimage.getDA()
#
# fixme - calculating dimensions needs rework!
#
_image = gimage.getImage()
_slen = _image.scaleLength(self.calculate())
_dims = self.getDimensions(_slen)
_dx, _dy = self.getLocation()
_ds1 = _ds2 = _l1 = _l2 = _x1 = _y1 = _x2 = _y2 = None
if self.getDualDimMode():
_off = self.getDualModeOffset()
_ds1 = self.getPrimaryDimstring()
if _ctx is not None:
_l1 = _ctx.create_layout()
_l1.set_text(_ds1.getText())
else:
_l1 = _da.create_pango_layout(_ds1.getText())
_ds1._formatLayout(gimage, _l1)
_w1, _h1 = _ds1.getBounds()
_ds1.setLocation((_dx - (_w1/2.0)), (_dy + _h1 + _off))
_x1, _y1 = _ds1.getLocation()
_ds2 = self.getSecondaryDimstring()
if _ctx is not None:
_l2 = _ctx.create_layout()
_l2.set_text(_ds2.getText())
else:
_l2 = _da.create_pango_layout(_ds2.getText())
_ds2._formatLayout(gimage, _l2)
_w2, _h2 = _ds2.getBounds()
_ds2.setLocation((_dx - (_w2/2.0)), (_dy - _off))
_x2, _y2 = _ds2.getLocation()
_brect = (min(_x1, _x2), # xmin
_y1, # ymax
max((_x1 + _w1), (_x2 + _w2)), # xmax
(_y2 - _h2)) # ymin
else:
_ds1 = self.getPrimaryDimstring()
if _ctx is not None:
_l1 = _ctx.create_layout()
_l1.set_text(_ds1.getText())
else:
_l1 = _da.create_pango_layout(_ds1.getText())
_ds1._formatLayout(gimage, _l1)
_w, _h = _ds1.getBounds()
_ds1.setLocation((_dx - (_w/2.0)), (_dy + (_h/2.0)))
_x1, _y1 = _ds1.getLocation()
_brect = (_x1, _y1, (_x1 + _w), (_y1 - _h))
_bx1, _by1 = gimage.coordToPixTransform(_brect[0], _brect[1])
_bx2, _by2 = gimage.coordToPixTransform(_brect[2], _brect[3])
_pixmap = None
_bgcol = _image.getOption('BACKGROUND_COLOR') #this is a string not an object
print "Debug: _bhcol %s"%str(_bgcol)
if _ctx is not None :
_r, _g, _b = _bgcol.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
_ctx.rectangle((_bx1 - 2), (_by1 - 2),
((_bx2 - _bx1) + 4), ((_by2 - _by1) + 4))
_ctx.fill()
else:
_gc = gimage.getGC()
_gc.set_function(gtk.gdk.COPY)
_gc.set_foreground(gimage.getColor(_bgcol))
_pixmap = gimage.getPixmap()
_pixmap.draw_rectangle(_gc, True, (_bx1 - 2), (_by1 - 2),
((_bx2 - _bx1) + 4), ((_by2 - _by1) + 4))
_col = col
if _col is None:
_col = _ds1.getColor()
_px, _py = gimage.coordToPixTransform(_x1, _y1)
if _ctx is not None:
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
_ctx.move_to(_px, _py)
_ctx.show_layout(_l1)
else:
_gc.set_foreground(gimage.getColor(_col))
_px, _py = gimage.coordToPixTransform(_x1, _y1)
_pixmap.draw_layout(_gc, _px, _py, _l1)
if _ds2 is not None:
_col = col
if _col is None:
_col = _ds2.getColor()
if _ctx is not None:
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
_px, _py = gimage.coordToPixTransform(_x2, _y2)
_ctx.move_to(_px, _py)
_ctx.show_layout(_l2)
else:
_gc.set_foreground(gimage.getColor(_col))
_px, _py = gimage.coordToPixTransform(_x2, _y2)
_pixmap.draw_layout(_gc, _px, _py, _l2)
_col = col
if _col is None:
_col = self.getColor()
_px1, _py1 = gimage.coordToPixTransform(_brect[0], _dy)
_px2, _py2 = gimage.coordToPixTransform(_brect[2], _dy)
if _ctx is not None:
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
_ctx.move_to(_px1, _py1)
_ctx.line_to(_px2, _py2)
_ctx.stroke()
else:
_gc.set_foreground(gimage.getColor(_col))
_pixmap.draw_line(_gc, _px1, _py1, _px2, _py2)
_l2 = None
_l1 = None
if _ctx is not None:
_ctx.restore()
def _cairo_draw_arrow_endpt(ctx, gimage, cpts, mpts):
#
# crossbar/crossarc points
#
_cx, _cy = cpts[0]
_cp1x, _cp1y = gimage.coordToPixTransform(_cx, _cy)
_cx, _cy = cpts[1]
_cp2x, _cp2y = gimage.coordToPixTransform(_cx, _cy)
#
# marker points
#
_mp = mpts[0]
if _mp is not None:
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.move_to(_px, _py)
ctx.line_to(_cp1x, _cp1y)
_mp = mpts[1]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.move_to(_px, _py)
ctx.line_to(_cp1x, _cp1y)
_mp = mpts[2]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.move_to(_px, _py)
ctx.line_to(_cp2x, _cp2y)
_mp = mpts[3]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.move_to(_px, _py)
ctx.line_to(_cp2x, _cp2y)
ctx.stroke()
def _cairo_draw_filled_arrow_endpt(ctx, gimage, cpts, mpts):
#
# crossbar/crossarc points
#
_cx, _cy = cpts[0]
_cp1x, _cp1y = gimage.coordToPixTransform(_cx, _cy)
_cx, _cy = cpts[1]
_cp2x, _cp2y = gimage.coordToPixTransform(_cx, _cy)
#
# marker points
#
_mp = mpts[0]
if _mp is not None:
ctx.move_to(_cp1x, _cp1y)
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.line_to(_px, _py)
_mp = mpts[1]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.line_to(_px, _py)
ctx.close_path()
ctx.fill()
_mp = mpts[2]
ctx.move_to(_cp2x, _cp2y)
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.line_to(_px, _py)
_mp = mpts[3]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.line_to(_px, _py)
ctx.close_path()
ctx.fill()
def _cairo_draw_slash_endpt(ctx, gimage, mpts):
#
# marker points
#
_mp = mpts[0]
if _mp is not None:
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.move_to(_px, _py)
_mp = mpts[1]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.line_to(_px, _py)
_mp = mpts[2]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.move_to(_px, _py)
_mp = mpts[3]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
ctx.line_to(_px, _py)
ctx.stroke()
def _cairo_draw_circle_endpt(ctx, gimage, cpts, size):
#
# crossbar/crossarc points
#
_cp = cpts[0]
if _cp is not None:
_cp1x, _cp1y = gimage.coordToPixTransform(_cp[0], _cp[1])
_cx, _cy = cpts[1]
_cp2x, _cp2y = gimage.coordToPixTransform(_cx, _cy)
#
# circle
#
_r = size/2.0
_pw = int(round(_r/gimage.getUnitsPerPixel()))
if _cp is not None:
ctx.arc(_cp1x, _cp1y, _pw, 0, (2.0 * pi))
ctx.fill()
ctx.arc(_cp2x, _cp2y, _pw, 0, (2.0 * pi))
ctx.fill()
def _gdk_draw_arrow_endpt(gc, gimage, pixmap, cpts, mpts):
#
# crossbar/crossarc points
#
_cx, _cy = cpts[0]
_cp1x, _cp1y = gimage.coordToPixTransform(_cx, _cy)
_cx, _cy = cpts[1]
_cp2x, _cp2y = gimage.coordToPixTransform(_cx, _cy)
#
# marker points
#
_segs = []
_mp = mpts[0]
if _mp is not None:
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
_segs.append((_px, _py, _cp1x, _cp1y))
_mp = mpts[1]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
_segs.append((_px, _py, _cp1x, _cp1y))
_mp = mpts[2]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
_segs.append((_px, _py, _cp2x, _cp2y))
_mp = mpts[3]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
_segs.append((_px, _py, _cp2x, _cp2y))
pixmap.draw_segments(gc, _segs)
def _gdk_draw_filled_arrow_endpt(gc, gimage, pixmap, cpts, mpts):
#
# crossbar/crossarc points
#
_cx, _cy = cpts[0]
_cp1x, _cp1y = gimage.coordToPixTransform(_cx, _cy)
_cx, _cy = cpts[1]
_cp2x, _cp2y = gimage.coordToPixTransform(_cx, _cy)
#
# marker points
#
_mp = mpts[0]
if _mp is not None:
_p1 = []
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
_p1.append((_px, _py))
_mp = mpts[1]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
_p1.append((_px, _py))
_p1.append((_cp1x, _cp1y))
pixmap.draw_polygon(gc, True, _p1)
_p2 = []
_mp = mpts[2]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
_p2.append((_px, _py))
_mp = mpts[3]
_px, _py = gimage.coordToPixTransform(_mp[0], _mp[1])
_p2.append((_px, _py))
_p2.append((_cp2x, _cp2y))
pixmap.draw_polygon(gc, True, _p2)
def _gdk_draw_slash_endpt(gc, gimage, pixmap, mpts):
#
# marker points
#
_segs = []
_mp = mpts[0]
if _mp is not None:
_px1, _py1 = gimage.coordToPixTransform(_mp[0], _mp[1])
_mp = mpts[1]
_px2, _py2 = gimage.coordToPixTransform(_mp[0], _mp[1])
_segs.append((_px1, _py1, _px2, _py2))
_mp = mpts[2]
_px1, _py1 = gimage.coordToPixTransform(_mp[0], _mp[1])
_mp = mpts[3]
_px2, _py2 = gimage.coordToPixTransform(_mp[0], _mp[1])
_segs.append((_px1, _py1, _px2, _py2))
#
pixmap.draw_segments(gc, _segs)
def _gdk_draw_circle_endpt(gc, gimage, pixmap, cpts, size):
#
# crossbar/crossarc points
#
_cp = cpts[0]
if _cp is not None:
_cp1x, _cp1y = gimage.coordToPixTransform(_cp[0], _cp[1])
_cx, _cy = cpts[1]
_cp2x, _cp2y = gimage.coordToPixTransform(_cx, _cy)
#
_r = size/2.0
_pw = int(round(_r/gimage.getUnitsPerPixel()))
_cw = _ch = _pw * 2
if _cp is not None:
_xm = _cp1x - _pw
_ym = _cp1y - _pw
pixmap.draw_arc(gc, True, _xm, _ym, _cw, _ch, 0, (360 * 64))
_xm = _cp2x - _pw
_ym = _cp2y - _pw
pixmap.draw_arc(gc, True, _xm, _ym, _cw, _ch, 0, (360 * 64))
def _draw_ldim(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_bar1, _bar2 = self.getDimBars()
_cbar = self.getDimCrossbar()
if _col is None:
_col = self.getColor()
_lw = self.getThickness()/gimage.getUnitsPerPixel()
#
# bars and crossbar coordinates
#
_tlist = []
_ep1, _ep2 = _bar1.getEndpoints()
_px1, _py1 = gimage.coordToPixTransform(_ep1[0], _ep1[1])
_px2, _py2 = gimage.coordToPixTransform(_ep2[0], _ep2[1])
_tlist.append((_px1, _py1, _px2, _py2))
_ep1, _ep2 = _bar2.getEndpoints()
_px1, _py1 = gimage.coordToPixTransform(_ep1[0], _ep1[1])
_px2, _py2 = gimage.coordToPixTransform(_ep2[0], _ep2[1])
_tlist.append((_px1, _py1, _px2, _py2))
_ep1, _ep2 = _cbar.getEndpoints()
_px1, _py1 = gimage.coordToPixTransform(_ep1[0], _ep1[1])
_px2, _py2 = gimage.coordToPixTransform(_ep2[0], _ep2[1])
_tlist.append((_px1, _py1, _px2, _py2))
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _lw < 1.0:
_lw = 1.0
_ctx.set_line_width(_lw)
_p1x, _p1y, _p2x, _p2y = _tlist[0]
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_p1x, _p1y, _p2x, _p2y = _tlist[1]
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_p1x, _p1y, _p2x, _p2y = _tlist[2]
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_ctx.stroke()
else:
_gc = gimage.getGC()
_gc.set_function(gtk.gdk.COPY)
_gc.set_foreground(gimage.getColor(_col))
_t = int(round(_lw))
if _t < 1: # no zero-pixel lines
_t = 1
_gc.set_line_attributes(_t, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT,
gtk.gdk.JOIN_MITER)
_pixmap = gimage.getPixmap()
_pixmap.draw_segments(_gc, _tlist)
#
# draw endpoints
#
_etype = self.getEndpointType()
if _etype != dimension.Dimension.DIM_ENDPT_NONE:
_cpts = _cbar.getCrossbarPoints()
if (_etype == dimension.Dimension.DIM_ENDPT_ARROW or
_etype == dimension.Dimension.DIM_ENDPT_FILLED_ARROW or
_etype == dimension.Dimension.DIM_ENDPT_SLASH):
_mpts = _cbar.getMarkerPoints()
if _etype == dimension.Dimension.DIM_ENDPT_ARROW:
if _ctx is not None:
_cairo_draw_arrow_endpt(_ctx, gimage, _cpts, _mpts)
else:
_gdk_draw_arrow_endpt(_gc, gimage, _pixmap, _cpts, _mpts)
elif _etype == dimension.Dimension.DIM_ENDPT_FILLED_ARROW:
if _ctx is not None:
_cairo_draw_filled_arrow_endpt(_ctx, gimage, _cpts, _mpts)
else:
_gdk_draw_filled_arrow_endpt(_gc, gimage, _pixmap,
_cpts, _mpts)
elif _etype == dimension.Dimension.DIM_ENDPT_SLASH:
if _ctx is not None:
_cairo_draw_slash_endpt(_ctx, gimage, _mpts)
else:
_gdk_draw_slash_endpt(_gc, gimage, _pixmap, _mpts)
else:
raise ValueError, "Unexpected end point type: %d" % _etype
elif _etype == dimension.Dimension.DIM_ENDPT_CIRCLE:
_size = self.getEndpointSize()
if _ctx is not None:
_cairo_draw_circle_endpt(_ctx, gimage, _cpts, _size)
else:
_gdk_draw_circle_endpt(_gc, gimage, _pixmap, _cpts, _size)
else:
raise ValueError, "Unexpected endpoint value: %d" % _etype
self._drawDimStrings(gimage, col)
if _ctx is not None:
_ctx.restore()
def _draw_rdim(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
if _col is None:
_col = self.getColor()
_lw = self.getThickness()/gimage.getUnitsPerPixel()
#
# Dimension bar
#
_cbar = self.getDimCrossbar()
_ep1, _ep2 = _cbar.getEndpoints()
_p1x, _p1y = gimage.coordToPixTransform(_ep1[0], _ep1[1])
_p2x, _p2y = gimage.coordToPixTransform(_ep2[0], _ep2[1])
_tlist = []
_tlist.append((_p1x, _p1y, _p2x, _p2y))
_dx, _dy = self.getLocation()
_pdx, _pdy = gimage.coordToPixTransform(_dx, _dy)
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _lw < 1.0:
_lw = 1.0
_ctx.set_line_width(_lw)
_p1x, _p1y, _p2x, _p2y = _tlist[0]
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_ctx.stroke()
else:
_gc = gimage.getGC()
_gc.set_function(gtk.gdk.COPY)
_gc.set_foreground(gimage.getColor(_col))
_t = int(round(_lw))
if _t < 1: # no zero-pixel lines
_t = 1
_gc.set_line_attributes(_t, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT,
gtk.gdk.JOIN_MITER)
gimage.getPixmap().draw_segments(_gc, _tlist)
#
# draw marker points
#
_etype = self.getEndpointType()
if _etype != dimension.Dimension.DIM_ENDPT_NONE:
_cpts = _cbar.getCrossbarPoints()
_dia_mode = self.getDiaMode()
if (_etype == dimension.Dimension.DIM_ENDPT_ARROW or
_etype == dimension.Dimension.DIM_ENDPT_FILLED_ARROW or
_etype == dimension.Dimension.DIM_ENDPT_SLASH):
_mpts = _cbar.getMarkerPoints()
if _etype == dimension.Dimension.DIM_ENDPT_ARROW:
if _dia_mode:
_mpts[0] = None
if _ctx is not None:
_cairo_draw_arrow_endpt(_ctx, gimage, _cpts, _mpts)
else:
_gdk_draw_arrow_endpt(_gc, gimage, _pixmap, _cpts, _mpts)
elif _etype == dimension.Dimension.DIM_ENDPT_FILLED_ARROW:
if _dia_mode:
_mpts[0] = None
if _ctx is not None:
_cairo_draw_filled_arrow_endpt(_ctx, gimage, _cpts, _mpts)
else:
_gdk_draw_filled_arrow_endpt(_gc, gimage, _pixmap,
_cpts, _mpts)
elif _etype == dimension.Dimension.DIM_ENDPT_SLASH:
if _dia_mode:
_mpts[0] = None
if _ctx is not None:
_cairo_draw_slash_endpt(_ctx, gimage, _mpts)
else:
_gdk_draw_slash_endpt(_gc, gimage, _pixmap, _mpts)
else:
raise ValueError, "Unexpected end point type: %d" % _etype
elif _etype == dimension.Dimension.DIM_ENDPT_CIRCLE:
_size = self.getEndpointSize()
if _dia_mode:
_cpts[0] = None
if _ctx is not None:
_cairo_draw_circle_endpt(_ctx, gimage, _cpts, _size)
else:
_gdk_draw_circle_endpt(gc, gimage, _pixmap, _cpts, _size)
else:
raise ValueError, "Unexpected endpoint value: %d" % _etype
self._drawDimStrings(gimage, col)
if _ctx is not None:
_ctx.restore()
def _draw_adim(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_bar1, _bar2 = self.getDimBars()
_carc = self.getDimCrossarc()
if _col is None:
_col = self.getColor()
_lw = self.getThickness()/gimage.getUnitsPerPixel()
_sa = _carc.getStartAngle()
_ea = _carc.getEndAngle()
_vx, _vy = self.getVertexPoint().getCoords()
_pvx, _pvy = gimage.coordToPixTransform(_vx, _vy)
_dx, _dy = self.getLocation()
_pdx, _pdy = gimage.coordToPixTransform(_dx, _dy)
_pr = int(_carc.getRadius()/gimage.getUnitsPerPixel())
#
# bars and crossarc coords
#
_tlist = []
_ep1, _ep2 = _bar1.getEndpoints()
_p1x, _p1y = gimage.coordToPixTransform(_ep1[0], _ep1[1])
_p2x, _p2y = gimage.coordToPixTransform(_ep2[0], _ep2[1])
_tlist.append((_p1x, _p1y, _p2x, _p2y))
_ep1, _ep2 = _bar2.getEndpoints()
_p1x, _p1y = gimage.coordToPixTransform(_ep1[0], _ep1[1])
_p2x, _p2y = gimage.coordToPixTransform(_ep2[0], _ep2[1])
_tlist.append((_p1x, _p1y, _p2x, _p2y))
_ctx = gimage.getCairoContext()
if _ctx is not None:
_ctx.save()
_r, _g, _b = _col.getColors()
_ctx.set_source_rgb((_r/255.0), (_g/255.0), (_b/255.0))
if _lw < 1.0:
_lw = 1.0
_ctx.set_line_width(_lw)
#
# arc drawing relies on Cairo transformations
#
_ctx.scale(1.0, -1.0)
_ctx.translate(_pvx, -(_pvy))
_ctx.arc(0, 0, _pr, (_sa * _dtr), (_ea * _dtr))
_ctx.identity_matrix()
#
_p1x, _p1y, _p2x, _p2y = _tlist[0]
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_p1x, _p1y, _p2x, _p2y = _tlist[1]
_ctx.move_to(_p1x, _p1y)
_ctx.line_to(_p2x, _p2y)
_ctx.stroke()
else:
_gc = gimage.getGC()
_gc.set_function(gtk.gdk.COPY)
_gc.set_foreground(gimage.getColor(_col))
_t = int(round(_lw))
if _t < 1: # no zero-pixel lines
_t = 1
_gc.set_line_attributes(_t, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT,
gtk.gdk.JOIN_MITER)
_pixmap = gimage.getPixmap()
_pixmap.draw_segments(_gc, _tlist)
_pxmin = _pvx - _pr
_pymin = _pvy - _pr
_cw = _ch = _pr * 2
if _sa < _ea:
_sweep = _ea - _sa
else:
_sweep = 360.0 - (_sa - _ea)
_pixmap.draw_arc(_gc, False, _pxmin, _pymin, _cw, _ch,
int(_sa * 64), int(_sweep * 64))
#
# draw endpoints
#
_etype = self.getEndpointType()
if _etype != dimension.Dimension.DIM_ENDPT_NONE:
_cpts = _carc.getCrossbarPoints()
if (_etype == dimension.Dimension.DIM_ENDPT_ARROW or
_etype == dimension.Dimension.DIM_ENDPT_FILLED_ARROW or
_etype == dimension.Dimension.DIM_ENDPT_SLASH):
_mpts = _carc.getMarkerPoints()
if _etype == dimension.Dimension.DIM_ENDPT_ARROW:
if _ctx is not None:
_cairo_draw_arrow_endpt(_ctx, gimage, _cpts, _mpts)
else:
_gdk_draw_arrow_endpt(_gc, gimage, _pixmap, _cpts, _mpts)
elif _etype == dimension.Dimension.DIM_ENDPT_FILLED_ARROW:
if _ctx is not None:
_cairo_draw_filled_arrow_endpt(_ctx, gimage, _cpts, _mpts)
else:
_gdk_draw_filled_arrow_endpt(_gc, gimage, _pixmap,
_cpts, _mpts)
elif _etype == dimension.Dimension.DIM_ENDPT_SLASH:
if _ctx is not None:
_cairo_draw_slash_endpt(_ctx, gimage, _mpts)
else:
_gdk_draw_slash_endpt(_gc, gimage, _pixmap, _mpts)
else:
raise ValueError, "Unexpected end point type: %d" % _etype
elif _etype == dimension.Dimension.DIM_ENDPT_CIRCLE:
_size = self.getEndpointSize()
if _ctx is not None:
_cairo_draw_circle_endpt(_ctx, gimage, _cpts, _size)
else:
_gdk_draw_circle_endpt(gc, gimage, _pixmap, _cpts, _size)
else:
raise ValueError, "Unexpected endpoint value: %d" % _etype
self._drawDimStrings(gimage, col)
if _ctx is not None:
_ctx.restore()
def _erase_dim(self, gimage):
pass
# originally the erase_dim set the color of the dimansion equal to the background color
#for deleting the dimansion.
#but when we close the application we get an error
#Adding pass to the erese_dim functions we not have any problems
#self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
def _draw_layer(self, gimage, col=None):
if not isinstance(gimage, gtkimage.GTKImage):
raise TypeError, "Invalid GTKImage: " + `type(gimage)`
_col = col
if _col is not None and not isinstance(_col, color.Color):
raise TypeError, "Invalid Color: " + `type(_col)`
_image = gimage.getImage()
if _col is None:
if self.isVisible() and _image.getActiveLayer() is not self:
_col = _image.getOption('INACTIVE_LAYER_COLOR')
else:
_col = _image.getOption('BACKGROUND_COLOR')
for _obj in self.getLayerEntities('point'):
if _obj.isVisible():
_obj.draw(gimage, _col)
_ctypes = ['hcline', 'vcline', 'acline', 'cline', 'ccircle']
for _ctype in _ctypes:
for _obj in self.getLayerEntities(_ctype):
if _obj.isVisible():
_obj.draw(gimage, _col)
_gtypes = ['segment', 'circle', 'arc', 'leader', 'polyline',
'chamfer', 'fillet', 'textblock', 'linear_dimension',
'horizontal_dimension', 'vertical_dimension',
'radial_dimension', 'angular_dimension']
for _gtype in _gtypes:
for _obj in self.getLayerEntities(_gtype):
if _obj.isVisible():
_obj.draw(gimage, _col)
def _erase_layer(self, gimage):
self.draw(gimage, gimage.image.getOption('BACKGROUND_COLOR'))
for _pt in self.getLayerEntities('point'):
_pt.erase(gimage)
def add_graphic_methods():
_class = point.Point
_class.draw = types.MethodType(_draw_point, None, _class)
_class.erase = types.MethodType(_erase_point, None, _class)
_class = segment.Segment
_class.draw = types.MethodType(_draw_segment, None, _class)
_class.erase = types.MethodType(_erase_segment, None, _class)
_class = circle.Circle
_class.draw = types.MethodType(_draw_circle, None, _class)
_class.erase = types.MethodType(_erase_circle, None, _class)
_class = arc.Arc
_class.draw = types.MethodType(_draw_arc, None, _class)
_class.erase = types.MethodType(_erase_arc, None, _class)
_class = leader.Leader
_class.draw = types.MethodType(_draw_leader, None, _class)
_class.erase = types.MethodType(_erase_leader, None, _class)
_class = polyline.Polyline
_class.draw = types.MethodType(_draw_polyline, None, _class)
_class.erase = types.MethodType(_erase_polyline, None, _class)
_class = segjoint.Chamfer
_class.draw = types.MethodType(_draw_chamfer, None, _class)
_class.erase = types.MethodType(_erase_chamfer, None, _class)
_class = segjoint.Fillet
_class.draw = types.MethodType(_draw_fillet, None, _class)
_class.erase = types.MethodType(_erase_fillet, None, _class)
_class = hcline.HCLine
_class.draw = types.MethodType(_draw_hcline, None, _class)
_class.erase = types.MethodType(_erase_hcline, None, _class)
_class = vcline.VCLine
_class.draw = types.MethodType(_draw_vcline, None, _class)
_class.erase = types.MethodType(_erase_vcline, None, _class)
_class = acline.ACLine
_class.draw = types.MethodType(_draw_acline, None, _class)
_class.erase = types.MethodType(_erase_acline, None, _class)
_class = cline.CLine
_class.draw = types.MethodType(_draw_cline, None, _class)
_class.erase = types.MethodType(_erase_cline, None, _class)
_class = ccircle.CCircle
_class.draw = types.MethodType(_draw_ccircle, None, _class)
_class.erase = types.MethodType(_erase_ccircle, None, _class)
_class = text.TextBlock
_class._formatLayout = types.MethodType(_format_layout, None, _class)
_class.draw = types.MethodType(_draw_textblock, None, _class)
_class.erase = types.MethodType(_erase_textblock, None, _class)
_class = dimension.LinearDimension
_class.draw = types.MethodType(_draw_ldim, None, _class)
_class = dimension.RadialDimension
_class.draw = types.MethodType(_draw_rdim, None, _class)
_class = dimension.AngularDimension
_class.draw = types.MethodType(_draw_adim, None, _class)
_class = dimension.Dimension
_class.erase = types.MethodType(_erase_dim, None, _class)
_class._drawDimStrings = types.MethodType(_draw_dimstrings, None, _class)
_class = layer.Layer
_class.draw = types.MethodType(_draw_layer, None, _class)
_class.erase = types.MethodType(_erase_layer, None, _class)
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtktextprefs.py 0000644 0001750 0001750 00000061205 11307666657 022520 0 ustar matteo matteo #
# Copyright (c) 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., 51 Franklin Stree, Fifth Floor, Boston, MA 02110-1301,
# USA
#
#
# code for displaying TextStyle values
#
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import sys
from PythonCAD.Generic import color
from PythonCAD.Generic import units
from PythonCAD.Generic import text
from PythonCAD.Generic import image
class GtkTextStyle(object):
"""
"""
__font_styles = text.TextStyle.getStyleStrings()
__font_weights = text.TextStyle.getWeightStrings()
__text_align = text.TextStyle.getAlignmentStrings()
__families = None
def __init__(self, window, ts=None):
if not isinstance(window, gtk.Window):
raise TypeError, "Invalid window type: " + `type(window)`
self.__window = window
self.__widgets = {}
self.__textstyles = []
self.__ts = None
if ts is not None:
self.setTextStyle(ts)
def addTextStyle(self, ts):
"""Store a TextStyle in the GtkTextStyle
addTextStyle(ts)
Argument 'ts' must be a TextStyle instance.
"""
if not isinstance(ts, text.TextStyle):
raise TypeError, "Invalid TextStyle: " + `type(ts)`
self.__textstyles.append(ts)
def getTextStyles(self):
"""Return the list of stored TextStyles.
getTextStyles()
This method returns a list of TextStyle instances stored
with the addTextStyle() method.
"""
return self.__textstyles
def setTextStyle(self, ts):
"""Set the TextStyle defining the various widget values.
setTextStyle(ts)
Argument 'ts' must be a TextStyle instance.
"""
if not isinstance(ts, text.TextStyle):
raise TypeError, "Invalid TextStyle: " + `type(ts)`
self.__ts = ts
self.setValues()
def getTextStyle(self):
"""Get the TextStyle used to define the widget values.
getTextStyle()
This method returns a TextStyle instance or None if no TextStyle
has been stored in the GtkTextStyle instance.
"""
return self.__ts
def __selectColor(button, s=None):
_s = s
if _s is None:
_s = _('Select Color')
_da = button.get_child().get_child()
_color = _da.get_style().bg[gtk.STATE_NORMAL]
_dialog = gtk.ColorSelectionDialog(_s)
_colorsel = _dialog.colorsel
_colorsel.set_previous_color(_color)
_colorsel.set_current_color(_color)
_colorsel.set_has_palette(True)
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_r, _g, _b = _get_rgb_values(_colorsel.get_current_color())
_str = "#%02x%02x%02x" % (_r, _g, _b)
_color = gtk.gdk.color_parse(_str)
_da.modify_bg(gtk.STATE_NORMAL, _color)
_dialog.destroy()
__selectColor = staticmethod(__selectColor)
def __moveCursor(entry):
entry.set_position(-1)
return False
__moveCursor = staticmethod(__moveCursor)
def __entryActivate(entry):
_text = entry.get_text()
entry.delete_text(0, -1)
if len(_text):
if _text == '-' or _text == '+':
sys.stderr.write("Incomplete value: '%s'\n" % _text)
else:
try:
_value = float(_text)
except:
sys.stderr.write("Invalid float: '%s'\n" % _text)
else:
sys.stderr.write("Empty entry box.")
__entryActivate = staticmethod(__entryActivate)
def __entryFocusOut(entry, event, text=''):
_text = entry.get_text()
if _text == '' or _text == '+':
_size = entry.get_data('size')
_hid = entry.get_data('handlerid')
entry.delete_text(0, -1)
entry.handler_block(_hid)
try:
entry.set_text(_size)
finally:
entry.handler_unblock(_hid)
return False
__entryFocusOut = staticmethod(__entryFocusOut)
def __entryInsertText(entry, new_text, new_text_length, position):
if (new_text.isdigit() or
new_text == '.' or
new_text == '+'):
_string = entry.get_text() + new_text[:new_text_length]
_hid = entry.get_data('handlerid')
_move = True
entry.handler_block(_hid)
try:
_pos = entry.get_position()
if _string == '+':
_pos = entry.insert_text(new_text, _pos)
else:
try:
_val = float(_string)
except StandardError, e:
_move = False
else:
_pos = entry.insert_text(new_text, _pos)
finally:
entry.handler_unblock(_hid)
if _move:
if hasattr(gobject, 'idle_add'):
gobject.idle_add(GtkTextStyle.__moveCursor, entry)
else:
gtk.idle_add(GtkTextStyle.__moveCursor, entry)
entry.stop_emission('insert-text')
__entryInsertText = staticmethod(__entryInsertText)
def __getColorDA(widgets, key, val, s=None):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.Button()
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_frame.set_border_width(5)
_widget.add(_frame)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_widget.connect('clicked', GtkTextStyle.__selectColor, s)
_frame.add(_da)
else:
_da = _widget.get_child().get_child()
_da.modify_bg(gtk.STATE_NORMAL, val)
return _widget
__getColorDA = staticmethod(__getColorDA)
def __getColorButton(widgets, key, val, s):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.ColorButton()
_widget.set_title(s)
_widget.set_color(gtk.gdk.color_parse(str(val)))
return _widget
__getColorButton = staticmethod(__getColorButton)
def __getOptionMenu(widgets, key, val, entries):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.OptionMenu()
_menu = gtk.Menu()
else:
_menu = _widget.getMenu()
for _child in _menu.get_children():
_menu.remove(_child)
_idx = 0
for _i in range(len(entries)):
_val = entries[_i]
if _val == val:
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget.set_menu(_menu)
_widget.set_history(_idx)
return _widget
__getOptionMenu = staticmethod(__getOptionMenu)
def __getComboBox(widgets, key, val, entries):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.combo_box_new_text()
else:
_model = _widget.get_model()
if _model is not None:
while len(_model):
_widget.remove_text(0)
_idx = 0
for _i in range(len(entries)):
_val = entries[_i]
if _val == val:
_idx = _i
_widget.append_text(_val)
_widget.set_active(_idx)
return _widget
__getComboBox = staticmethod(__getComboBox)
def setValues(self):
"""Store the TextStyle values in the interface widgets.
setValues()
"""
_ts = self.__ts
if _ts is None:
raise RuntimeError, "No TextStyle defined for the GtkTextStyle instance."
_widgets = self.__widgets
#
if GtkTextStyle.__families is None:
_families = []
for _family in self.__window.get_pango_context().list_families():
_families.append(_family.get_name())
_families.sort()
GtkTextStyle.__families = _families
_val = _ts.getFamily()
if hasattr(gtk, 'ComboBox'):
_sm = GtkTextStyle.__getComboBox
else:
_sm = GtkTextStyle.__getOptionMenu
_key = 'FONT_FAMILY'
_widget = _sm(_widgets, _key, _val, GtkTextStyle.__families)
if _key not in _widgets:
_widgets[_key] = _widget
#
_val = _ts.getStyle()
if hasattr(gtk, 'ComboBox'):
_sm = GtkTextStyle.__getComboBox
else:
_sm = GtkTextStyle.__getOptionMenu
_key = 'FONT_STYLE'
_widget = _sm(_widgets, _key, _val, GtkTextStyle.__font_styles)
if _key not in _widgets:
_widgets[_key] = _widget
#
_val = _ts.getWeight()
if hasattr(gtk, 'ComboBox'):
_sm = GtkTextStyle.__getComboBox
else:
_sm = GtkTextStyle.__getOptionMenu
_key = 'FONT_WEIGHT'
_widget = _sm(_widgets, _key, _val, GtkTextStyle.__font_weights)
if _key not in _widgets:
_widgets[_key] = _widget
#
_val = _ts.getColor()
_s = _('Select Font Color')
if hasattr(gtk, 'ColorButton'):
_sm = GtkTextStyle.__getColorButton
else:
_sm = GtkTextStyle.__getColorDA
_key = 'FONT_COLOR'
_widget = _sm(_widgets, _key, _val, _s)
if _key not in _widgets:
_widgets[_key] = _widget
#
# fixme - TEXT_ANGLE
#
_val = _ts.getAlignment()
if hasattr(gtk, 'ComboBox'):
_sm = GtkTextStyle.__getComboBox
else:
_sm = GtkTextStyle.__getOptionMenu
_key = 'TEXT_ALIGNMENT'
_widget = _sm(_widgets, _key, _val, GtkTextStyle.__text_align)
if _key not in _widgets:
_widgets[_key] = _widget
#
_key = 'TEXT_SIZE'
_entry = _widgets.setdefault(_key, gtk.Entry())
_val = _ts.getSize()
_size = "%f" % _val
_entry.set_data('size', _size)
_hid = _entry.get_data('handlerid')
if _hid is not None:
_entry.handler_block(_hid)
try:
_entry.set_text(_size)
finally:
_entry.handler_unblock(_hid)
else:
_entry.set_text(_size)
_handlerid = _entry.connect('insert-text',
GtkTextStyle.__entryInsertText)
_entry.set_data('handlerid', _handlerid)
_entry.connect('activate', GtkTextStyle.__entryActivate)
_entry.connect('focus-out-event',
GtkTextStyle.__entryFocusOut)
if _key not in _widgets:
_widgets[_key] = _entry
def __getRGBValues(color):
if not isinstance(color, gtk.gdk.Color):
raise TypeError, "Unexpected color type: " + `type(color)`
_r = int(round((color.red/65535.0) * 255.0))
_g = int(round((color.green/65535.0) * 255.0))
_b = int(round((color.blue/65535.0) * 255.0))
return _r, _g, _b
__getRGBValues = staticmethod(__getRGBValues)
def getValues(self):
"""Return the values stored in the widgets
getValues()
This method returns a list of tuples in the form (key, value),
where 'key' is the TextStyle option and 'value' is the option value.
"""
_ts = self.__ts
if _ts is None:
raise RuntimeError, "No TextStyle defined for the GtkTextStyle instance."
_values = []
_widgets = self.__widgets
#
_key = 'FONT_FAMILY'
_widget = _widgets[_key]
if hasattr(gtk, 'ComboBox'):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
_values.append((_key, GtkTextStyle.__families[_idx]))
#
_key = 'FONT_WEIGHT'
_widget = _widgets[_key]
if hasattr(gtk, 'ComboBox'):
_value = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_value = _widget.get_history()
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
_values.append((_key, _value))
#
_key = 'FONT_STYLE'
_widget = _widgets[_key]
if hasattr(gtk, 'ComboBox'):
_value = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_value = _widget.get_history()
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
_values.append((_key, _value))
#
_key = 'FONT_COLOR'
_widget = _widgets[_key]
if hasattr(gtk, 'ColorButton'):
_color = _widget.get_color()
elif isinstance(_widget, gtk.Button):
_da = _widget.getChild().getChild()
_color= _da.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
_values.append((_key, GtkTextStyle.__getRGBValues(_color)))
#
_key = 'TEXT_ALIGNMENT'
_widget = _widgets[_key]
if hasattr(gtk, 'ComboBox'):
_value = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_value = _widget.get_history()
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
_values.append((_key, _value))
#
_key = 'TEXT_SIZE'
_widget = _widgets[_key]
_text = _widget.get_text()
if len(_text) and _text != '+':
_value = float(_text)
else:
_value = _ts.getSize()
_values.append((_key, _value))
#
# fixme - TEXT_ANGLE
#
return _values
def getWidget(self, key):
"""Return a widget associated with a TextStyle option.
getWidget(key)
Argument 'key' must be a valid TextStyle option key. This method
returns a widget or None.
"""
if (key != 'FONT_FAMILY' and
key != 'FONT_STYLE' and
key != 'FONT_WEIGHT' and
key != 'FONT_COLOR' and
key != 'TEXT_SIZE' and
key != 'TEXT_ALIGNMENT' and
key != 'TEXT_ANGLE'):
return ValueError, "Invalid TextStyle key: " + key
return self.__widgets.get(key)
def clear(self):
"""Clear out all values and widgets in the GtkTextStyle.
clear()
"""
self.__window = None
self.__widgets.clear()
del self.__textstyles[:]
self.__ts = None
def setImageSettings(self, im):
"""Adjust the widgets values based on current Image values
setImageSettings(im)
Argument 'im' must be an Image instance.
"""
if not isinstance(im, image.Image):
raise TypeError, "Invalid Image type: " + `type(im)`
_widgets = self.__widgets
_key = 'FONT_FAMILY'
_ival = im.getOption(_key)
if GtkTextStyle.__families is None:
_families = []
for _family in self.__window.get_pango_context().list_families():
_families.append(_family.get_name())
_families.sort()
GtkTextStyle.__families = _families
if hasattr(gtk, 'ComboBox'):
_sm = GtkTextStyle.__getComboBox
else:
_sm = GtkTextStyle.__getOptionMenu
_widget = _sm(_widgets, _key, _ival, GtkTextStyle.__families)
if _key not in _widgets:
_widgets[_key] = _widget
#
_key = 'FONT_STYLE'
_ival = im.getOption(_key)
if hasattr(gtk, 'ComboBox'):
_sm = GtkTextStyle.__getComboBox
else:
_sm = GtkTextStyle.__getOptionMenu
_optlist = GtkTextStyle.__font_styles
_widget = _sm(_widgets, _key, _ival, _optlist)
_idx = 0
for _i in range(len(_optlist)):
_val = text.TextStyle.getStyleFromString(_optlist[_i])
if _val == _ival:
_idx = _i
_widget.set_active(_idx)
if _key not in _widgets:
_widgets[_key] = _widget
#
_key = 'FONT_WEIGHT'
_ival = im.getOption(_key)
if hasattr(gtk, 'ComboBox'):
_sm = GtkTextStyle.__getComboBox
else:
_sm = GtkTextStyle.__getOptionMenu
_optlist = GtkTextStyle.__font_weights
_widget = _sm(_widgets, _key, _ival, _optlist)
_idx = 0
for _i in range(len(_optlist)):
_val = text.TextStyle.getWeightFromString(_optlist[_i])
if _val == _ival:
_idx = _i
_widget.set_active(_idx)
if _key not in _widgets:
_widgets[_key] = _widget
#
_key = 'FONT_COLOR'
_ival = im.getOption(_key)
_s = _('Select Font Color')
if hasattr(gtk, 'ColorButton'):
_sm = GtkTextStyle.__getColorButton
else:
_sm = GtkTextStyle.__getColorDA
_widget = _sm(_widgets, _key, _ival, _s)
if _key not in _widgets:
_widgets[_key] = _widget
#
# fixme - TEXT_ANGLE
#
_key = 'TEXT_ALIGNMENT'
_ival = im.getOption(_key)
if hasattr(gtk, 'ComboBox'):
_sm = GtkTextStyle.__getComboBox
else:
_sm = GtkTextStyle.__getOptionMenu
_optlist = GtkTextStyle.__text_align
_widget = _sm(_widgets, _key, _ival, _optlist)
_idx = 0
for _i in range(len(_optlist)):
_val = text.TextStyle.getAlignmentFromString(_optlist[_i])
if _val == _ival:
_idx = _i
_widget.set_active(_idx)
if _key not in _widgets:
_widgets[_key] = _widget
#
_key = 'TEXT_SIZE'
_entry = _widgets.setdefault(_key, gtk.Entry())
_ival = im.getOption(_key)
_size = "%f" % _ival
_entry.set_data('size', _size)
_hid = _entry.get_data('handlerid')
if _hid is not None:
_entry.handler_block(_hid)
try:
_entry.set_text(_size)
finally:
_entry.handler_unblock(_hid)
else:
_entry.set_text(_size)
_handlerid = _entry.connect('insert-text',
GtkTextStyle.__entryInsertText)
_entry.set_data('handlerid', _handlerid)
_entry.connect('activate', GtkTextStyle.__entryActivate)
_entry.connect('focus-out-event',
GtkTextStyle.__entryFocusOut)
if _key not in _widgets:
_widgets[_key] = _entry
def _widget_changed(widget, gts):
if hasattr(gtk, 'ComboBox'):
_idx = widget.get_active()
else:
_idx = widget.get_history()
_textstyles = gts.getTextStyles()
gts.setTextStyle(_textstyles[_idx])
def _fill_dialog(dvbox, gts):
_lsg = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_msg = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
#
_frame = gtk.Frame(_('Font Properties'))
_frame.set_border_width(2)
_vbox = gtk.VBox(False, 2)
_vbox.set_border_width(2)
_frame.add(_vbox)
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, False, False, 2)
_label = gtk.Label(_('Family:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = gts.getWidget('FONT_FAMILY')
_msg.add_widget(_widget)
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, False, False, 2)
_label = gtk.Label(_('Style:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = gts.getWidget('FONT_STYLE')
_msg.add_widget(_widget)
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, False, False, 2)
_label = gtk.Label(_('Weight:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = gts.getWidget('FONT_WEIGHT')
_msg.add_widget(_widget)
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, False, False, 2)
_label = gtk.Label(_('Alignment:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = gts.getWidget('TEXT_ALIGNMENT')
_msg.add_widget(_widget)
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, False, False, 2)
_label = gtk.Label(_('Size:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = gts.getWidget('TEXT_SIZE')
_hbox.pack_start(_widget, False, False, 2)
#
# fixme - TEXT_ANGLE
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, True, True, 2)
_label = gtk.Label(_('Color:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = gts.getWidget('FONT_COLOR')
_hbox.pack_start(_widget, False, False, 2)
#
dvbox.pack_start(_frame, False, False, 2)
def textstyle_dialog(gtkimage, textstyles):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('TextStyle Settings'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_image = gtkimage.getImage()
_ts = _image.getOption('TEXT_STYLE')
_hbox = gtk.HBox(False, 5)
_hbox.set_border_width(5)
_label = gtk.Label(_('Active TextStyle:'))
_hbox.pack_start(_label, False, False, 5)
_idx = 0
if hasattr(gtk, 'ComboBox'):
_widget = gtk.combo_box_new_text()
for _i in range(len(textstyles)):
_textstyle = textstyles[_i]
if (_ts is _textstyle or
_ts == _textstyle):
_idx = _i
_widget.append_text(_textstyle.getName())
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(textstyles)):
_textstyle = textstyles[_i]
if (_ts is _textstyle or
_ts == _textstyle):
_idx = _i
_item = gtk.MenuItem(_textstyle.getName())
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_widget, False, False, 0)
_dialog.vbox.pack_start(_hbox, True, True)
#
_gts = GtkTextStyle(_window)
for _textstyle in textstyles:
_gts.addTextStyle(_textstyle)
_gts.setTextStyle(_ts)
_gts.setImageSettings(_image)
_fill_dialog(_dialog.vbox, _gts)
_widget.connect('changed', _widget_changed, _gts)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_nts = _gts.getTextStyle()
if _nts != _ts:
_image.setOption('TEXT_STYLE', _nts)
for _opt, _val in _gts.getValues():
if _opt == 'FONT_FAMILY':
if _val != _image.getOption(_opt):
_image.setOption(_opt, _val)
elif _opt == 'FONT_STYLE':
if _val != _image.getOption(_opt):
_image.setOption(_opt, _val)
elif _opt == 'FONT_WEIGHT':
if _val != _image.getOption(_opt):
_image.setOption(_opt, _val)
elif _opt == 'FONT_COLOR':
if _val != _image.getOption(_opt).getColors():
_r, _g, _b = _val
_image.setOption(_opt, color.Color(_r, _g, _b))
elif _opt == 'TEXT_SIZE':
if abs(_val - _image.getOption(_opt)) > 1e-10:
_image.setOption(_opt, _val)
elif _opt == 'TEXT_ANGLE':
if abs(_val - _image.getOption(_opt)) > 1e-10:
_image.setOption(_opt, _val)
elif _opt == 'TEXT_ALIGNMENT':
if _val != _image.getOption(_opt):
_image.setOption(_opt, _val)
else:
raise RuntimeError, "Unexpected TextStyle option '%s'" % _opt
_gts.clear()
_dialog.destroy()
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtktext.py 0000644 0001750 0001750 00000023031 11307666732 021445 0 ustar matteo matteo #
# Copyright (c) 2003, 2004, 2006, 2007 Art Haas
#
# 2009 Matteo Boscolo
#
# 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
#
#
# GTK interface code for dealing with text entities
#
import pygtk
pygtk.require('2.0')
import gtk
import pango
import copy
from PythonCAD.Generic.text import TextStyle, TextBlock
from PythonCAD.Generic import snap
def set_textblock_bounds(gtkimage, tblock):
# print "set_textblock_bounds() ..."
_text = tblock.getText()
if len(_text) == 0:
tblock.setBounds(0, 0)
tblock.setFontScale(1/float(pango.SCALE))
return
_family = tblock.getFamily()
_style = tblock.getStyle()
_weight = tblock.getWeight()
_size = tblock.getSize()
_da = gtkimage.getDA()
_upp = gtkimage.getUnitsPerPixel()
#
# initial test layout ...
#
_layout = _da.create_pango_layout(_text)
_fd = pango.FontDescription()
_fd.set_family(_family)
_fd.set_style(_style)
_fd.set_weight(_weight)
#
# use an 18-point font as first size guess
#
_fs = 18
_fd.set_size(pango.SCALE * _fs)
_layout.set_font_description(_fd)
_nlines = _layout.get_line_count()
#
# the pixel height of the TextBlock
#
_th = _nlines * _size
# print "TextBlock height: %g" % _th
_ph = _th/_upp
_iph = int(_ph)
if _iph/_nlines < 3: # tiny text - use the 18-point values for boundary
_w, _h = _layout.get_size()
_tw = (_w * _th)/float(_h)
tblock.setBounds(_tw, _th)
tblock.setFontScale(1/float(pango.SCALE))
_layout = None
return
# print "TextBlock pixel height: %g [%d]" % (_ph, _iph)
_w, _h = _layout.get_pixel_size()
# print "first layout: w: %d; h: %d" % (_w, _h)
_i = 0
if _h != _iph:
#
# loop until the layout pixel height equals the "correct" pixel height
#
_diff = abs(_h - _iph)
_ofs = _fs
_fs = (_fs * _ph)/float(_h)
# print "adjusted font size: %g" % (_fs)
while True:
_layout = _da.create_pango_layout(_text)
_fd = pango.FontDescription()
_fd.set_family(_family)
_fd.set_style(_style)
_fd.set_weight(_weight)
_fd.set_size(int(pango.SCALE * _fs))
_layout.set_font_description(_fd)
_w, _h = _layout.get_pixel_size()
# print "adjusted layout: w: %d; h: %d" % (_w, _h)
#
# tests to bail out
#
# all the inexact comparisons and iteration max
# count text are arbitrary ...
#
if _h == _iph:
# print "exact match"
break
if ((_iph > 10) and (abs(_iph - _h) < 2)):
# print "within 2"
break
if ((_iph > 100) and (abs(_iph - _h) < 10)):
# print "within 10"
break
if ((_iph > 1000) and (abs(_iph - _h) < 40)):
# print "within 40"
break
if _i > 25:
# print "25 iterations"
break
#
# bah, another iteration
#
_d = abs(_h - _iph)
if _d < _diff:
_diff = _d
_ofs = _fs
_fs = (_fs * _ph)/float(_h)
else:
# split the difference in the changed font size
# and try again, but do not reset the old font
# size
_fs = _ofs + ((_fs - _ofs)/2.0)
# print "adjusted font size: %g" % (_fs)
_i = _i + 1
#
# with the layout sized "correctly", calculate the TextBlock width
#
_w, _h = _layout.get_size()
_tw = (_w * _th)/float(_h)
# print "TextBlock width: %g" % _tw
tblock.setBounds(_tw, _th)
tblock.setFontScale(_fs)
_layout = None
def _make_pango_layout(gtkimage, text, family, style, weight, size):
_layout = gtkimage.getDA().create_pango_layout(text)
_fd = pango.FontDescription()
_fd.set_family(family)
if style == TextStyle.FONT_NORMAL:
_style = pango.STYLE_NORMAL
elif style == TextStyle.FONT_OBLIQUE:
_style = pango.STYLE_OBLIQUE
elif style == TextStyle.FONT_ITALIC:
_style = pango.STYLE_ITALIC
else:
raise ValueError, "Unexpected font style: %d" % style
_fd.set_style(_style)
if weight == TextStyle.WEIGHT_NORMAL:
_weight = pango.WEIGHT_NORMAL
elif weight == TextStyle.WEIGHT_LIGHT:
_weight = pango.WEIGHT_LIGHT
elif weight == TextStyle.WEIGHT_BOLD:
_weight = pango.WEIGHT_BOLD
elif weight == TextStyle.WEIGHT_HEAVY:
_weight = pango.WEIGHT_HEAVY
else:
raise ValueError, "Unexpected font weight: %d" % weight
_fd.set_weight(_weight)
_sz = int(pango.SCALE * (size/gtkimage.getUnitsPerPixel()))
if _sz < pango.SCALE:
_sz = pango.SCALE
_fd.set_size(_sz)
_layout.set_font_description(_fd)
return _layout
def text_button_press(gtkimage, widget, event, tool):
_image=gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_sn=snap.getSnapPoint(_image,gtkimage.getTolerance(),_snapArray)
_x,_y=_sn.point.getCoords()
tool.getTextBlock().setLocation(_x,_y)
_tool=copy.copy(tool)
_image.startAction()
try:
tool.create(_image)
finally:
_image.endAction()
text_add_init(gtkimage,_tool)
return True
def text_motion_notify(gtkimage, widget, event, tool):
_tblock = tool.getTextBlock()
_tw, _th = tool.getPixelSize()
_gc = gtkimage.getGC()
_align = _tblock.getAlignment()
if _align == TextStyle.ALIGN_LEFT:
_xoff = 0
elif _align == TextStyle.ALIGN_CENTER:
_xoff = _tw//2
elif _align == TextStyle.ALIGN_RIGHT:
_xoff = _tw
else:
raise ValueError, "Unexpected alignment value: %d" % _align
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_xc = _xc - _xoff
widget.window.draw_rectangle(_gc, False, _xc, _yc, _tw, _th)
_snapArray={'perpendicular':False,'tangent':False}
_sn=snap.getSnapPoint(gtkimage.getImage(),gtkimage.getTolerance(),_snapArray)
_x, _y=_sn.point.getCoords()
_x = _x - _xoff
_x,_y = gtkimage.coordToPixTransform(_x,_y)
tool.setCurrentPoint(_x,_y)
widget.window.draw_rectangle(_gc, False, _x, _y, _tw, _th)
return True
def text_add_init(gtkimage, tool=None):
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
if tool is not None:
_image.setTool(tool)
_tool = _image.getTool()
_text = _tool.getText()
_ts = _image.getOption('TEXT_STYLE')
_tb = TextBlock(_x, _y, _text, _ts)
_f = _image.getOption('FONT_FAMILY')
if _f != _ts.getFamily():
_tb.setFamily(_f)
_s = _image.getOption('FONT_STYLE')
if _s != _ts.getStyle():
_tb.setStyle(_s)
_w = _image.getOption('FONT_WEIGHT')
if _w != _ts.getWeight():
_tb.setWeight(_w)
_c = _image.getOption('FONT_COLOR')
if _c != _ts.getColor():
_tb.setColor(_c)
_sz = _image.getOption('TEXT_SIZE')
if abs(_sz - _ts.getSize()) > 1e-10:
_tb.setSize(_sz)
_a = _image.getOption('TEXT_ANGLE')
if abs(_a - _ts.getAngle()) > 1e-10:
_tb.setAngle(_a)
_al = _image.getOption('TEXT_ALIGNMENT')
if _al != _ts.getAlignment():
_tb.setAlignment(_al)
_tool.setTextBlock(_tb)
_layout = _make_pango_layout(gtkimage, _text, _f, _s, _w, _sz)
_tool.setLayout(_layout)
_lw, _lh = _layout.get_pixel_size()
_tool.setPixelSize(_lw, _lh)
_upp = gtkimage.getUnitsPerPixel()
#
# the width and height calculations can be somewhat inaccurate
# as the unitsPerPixel value gets large
#
_w = _lw * _upp
_h = _lh * _upp
_tool.setBounds(_w, _h)
_tool.setHandler("motion_notify", text_motion_notify)
_tool.setHandler("button_press", text_button_press)
gtkimage.setPrompt(_('Click where to place the text'))
_gc = gtkimage.getGC()
_gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
_gc.set_function(gtk.gdk.INVERT)
def text_add_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Enter text'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_tb = gtk.TextBuffer()
_tv = gtk.TextView(_tb)
_sw = gtk.ScrolledWindow()
_sw.set_size_request(400, 300)
_sw.add_with_viewport(_tv)
_dialog.vbox.pack_start(_sw, False, False, 0)
_dialog.show_all()
_text = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_start_iter, _end_iter = _tb.get_bounds()
_text = _tb.get_text(_start_iter, _end_iter)
_dialog.destroy()
return _text
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkmodify.py 0000644 0001750 0001750 00000271430 11307666732 021760 0 ustar matteo matteo #
# Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 Art Haas
#
# 2009 Matteo Bosocolo
#
# 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
#
#
# functions for doing modifications on drawing
# entities
#
import pygtk
pygtk.require('2.0')
import gtk
from math import atan2, pi
from PythonCAD.Generic.dimension import Dimension
from PythonCAD.Generic.dimension import LinearDimension
from PythonCAD.Generic.dimension import HorizontalDimension
from PythonCAD.Generic.dimension import VerticalDimension
from PythonCAD.Generic.dimension import RadialDimension
from PythonCAD.Generic.dimension import AngularDimension
from PythonCAD.Generic import color
from PythonCAD.Generic.graphicobject import GraphicObject
from PythonCAD.Generic.segment import Segment
from PythonCAD.Generic.circle import Circle
from PythonCAD.Generic.arc import Arc
from PythonCAD.Generic.polyline import Polyline
from PythonCAD.Generic.text import TextStyle, TextBlock
from PythonCAD.Generic.hcline import HCLine
from PythonCAD.Generic.acline import ACLine
from PythonCAD.Generic.vcline import VCLine
from PythonCAD.Generic.cline import CLine
from PythonCAD.Generic import util
from PythonCAD.Generic import split
from PythonCAD.Generic import snap
import PythonCAD.Generic.units
import PythonCAD.Generic.move
import PythonCAD.Generic.transfer
import PythonCAD.Generic.delete
import PythonCAD.Generic.rotate
#
# common code
#
def select_motion_notify(gtkimage, widget, event, tool):
"""
Draw the rectangle selections
"""
_tx, _ty = tool.getLocation()
_px, _py = gtkimage.coordToPixTransform(_tx, _ty)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_xmin = min(_xc, _px)
_ymin = min(_yc, _py)
_rw = abs(_xc - _px)
_rh = abs(_yc - _py)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _rw, _rh)
tool.setCurrentPoint(_x, _y)
_xmin = min(_x, _px)
_ymin = min(_y, _py)
_rw = abs(_x - _px)
_rh = abs(_y - _py)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _rw, _rh)
return True
#
# move objects
#
def move_objects(gtkimage, objlist, tool):
_init_func = tool.getHandler("initialize")
_dx, _dy = tool.getDistance()
_image = gtkimage.getImage()
_image.startAction()
try:
PythonCAD.Generic.move.move_objects(objlist, _dx, _dy)
finally:
_image.endAction()
gtkimage.setPrompt(_('Click in the drawing area or enter a distance.'))
tool.reset()
gtkimage.redraw()
_init_func(gtkimage, tool)
def move_button_press(gtkimage, tool):
_image = gtkimage.getImage()
_tol = gtkimage.getTolerance()
_onlySnap={"Freepoint":True}
_sp=snap.getOnlySnap(_image,_tol,_onlySnap)
_x, _y = _sp.point.getCoords()
#
# need to find if the point is an intersection of drawing objects ...
#
tool.pushObject(_x)
tool.pushObject(_y)
return True
def move_end_button_press_cb(gtkimage, widget, event, tool):
_image = gtkimage.getImage()
_tol = gtkimage.getTolerance()
_onlySnap={"Freepoint":True}
_sp=snap.getOnlySnap(_image,_tol,_onlySnap)
_x2, _y2 = _sp.point.getCoords()
_x1, _y1 = tool.getLocation()
_xmin = min(_x1, _x2)
_xmax = max(_x1, _x2)
_ymin = min(_y1, _y2)
_ymax = max(_y1, _y2)
_active_layer = _image.getActiveLayer()
_objlist = _active_layer.objsInRegion(_xmin, _ymin, _xmax, _ymax)
move_objects(gtkimage, _objlist, tool)
return True
def move_elem_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_onlySnap={"Freepoint":True}
_sp=snap.getOnlySnap(_image,_tol,_onlySnap)
_x,_y=_sp.point.getCoords()
#_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol, None)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
_objs = []
for _obj, _pt in _objdict[_active_layer]:
_objs.append(_obj)
_dx, _dy = tool.getDistance()
move_objects(gtkimage, _objs, tool)
else:
_onlySnap={"Freepoint":True}
_sp=snap.getOnlySnap(_image,_tol,_onlySnap)
_x,_y=_sp.point.getCoords()
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", move_end_button_press_cb)
gtkimage.setPrompt(_('Click the second point for defining the region'))
_gc = gtkimage.getGC()
_gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
_gc.set_function(gtk.gdk.INVERT)
return True
#
# move horizontal
#
def move_horizontal_entry_event(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_image = gtkimage.getImage()
_dist = util.get_float(eval(_text, _image.getImageVariables()))
tool.setDistance(_dist, 0.0)
if _image.hasSelection():
move_objects(gtkimage, _image.getSelectedObjects(), tool)
else:
gtkimage.setPrompt(_('Click on the objects to move.'))
tool.setHandler("button_press", move_elem_button_press_cb)
tool.delHandler("entry_event")
def move_horizontal_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
_x1, _y1 = tool.getLocation()
tool.setDistance((_x - _x1), 0.0)
if _image.hasSelection():
move_objects(gtkimage, _image.getSelectedObjects(), tool)
else:
tool.clearLocation()
gtkimage.setPrompt(_('Select the objects to move.'))
tool.setHandler("button_press", move_elem_button_press_cb)
tool.delHandler("entry_event")
return True
def move_horizontal_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
tool.setLocation(_x, _y)
gtkimage.setPrompt(_('Click another point to define the distance'))
tool.setHandler("button_press", move_horizontal_second_button_press_cb)
return True
def move_horizontal_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter the distance.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", move_horizontal_first_button_press_cb)
_tool.setHandler("entry_event", move_horizontal_entry_event)
_tool.setHandler("initialize", move_horizontal_init)
#
# move vertical
#
def move_vertical_entry_event(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_image = gtkimage.getImage()
_dist = util.get_float(eval(_text, _image.getImageVariables()))
tool.setDistance(0.0, _dist)
if _image.hasSelection():
move_objects(gtkimage, _image.getSelectedObjects(), tool)
else:
gtkimage.setPrompt(_('Click on the objects to move.'))
tool.setHandler("button_press", move_elem_button_press_cb)
tool.delHandler("entry_event")
def move_vertical_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
_x1, _y1 = tool.getLocation()
tool.setDistance(0.0, (_y - _y1))
if _image.hasSelection():
move_objects(gtkimage, _image.getSelectedObjects(), tool)
else:
tool.clearLocation()
gtkimage.setPrompt(_('Select the objects to move.'))
tool.setHandler("button_press", move_elem_button_press_cb)
tool.delHandler("entry_event")
return True
def move_vertical_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
tool.setLocation(_x, _y)
gtkimage.setPrompt(_('Click another point to define the distance'))
tool.setHandler("button_press", move_vertical_second_button_press_cb)
return True
def move_vertical_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter the distance.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", move_vertical_first_button_press_cb)
_tool.setHandler("entry_event", move_vertical_entry_event)
_tool.setHandler("initialize", move_vertical_init)
#
# move based on two mouse clicks
#
def move_xy_entry_event(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_image = gtkimage.getImage()
_x, _y = eval(_text, _image.getImageVariables())
tool.setDistance(util.get_float(_x), util.get_float(_y))
if _image.hasSelection():
move_objects(gtkimage, _image.getSelectedObjects(), tool)
else:
gtkimage.setPrompt(_('Click on the objects to move.'))
tool.setHandler("button_press", move_elem_button_press_cb)
tool.delHandler("entry_event")
def move_xy_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
_x1, _y1 = tool.getLocation()
tool.setDistance((_x - _x1), (_y - _y1))
if _image.hasSelection():
move_objects(gtkimage, _image.getSelectedObjects(), tool)
else:
tool.clearLocation()
gtkimage.setPrompt(_('Select the objects to move.'))
tool.setHandler("button_press", move_elem_button_press_cb)
tool.delHandler("entry_event")
return True
def move_xy_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
tool.setLocation(_x, _y)
gtkimage.setPrompt(_('Click another point to define the distance'))
tool.setHandler("button_press", move_xy_second_button_press_cb)
return True
def move_twopoint_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter the x and y distances.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", move_xy_first_button_press_cb)
_tool.setHandler("entry_event", move_xy_entry_event)
_tool.setHandler("initialize", move_twopoint_init)
#
# delete objects
#
def delete_region_end_cb(gtkimage, widget, event, tool):
_image = gtkimage.getImage()
_x2, _y2 = _image.getCurrentPoint()
_x1, _y1 = tool.getLocation()
_xmin = min(_x1, _x2)
_xmax = max(_x1, _x2)
_ymin = min(_y1, _y2)
_ymax = max(_y1, _y2)
tool.delHandler("motion_notify")
tool.setHandler("button_press", delete_button_press_cb)
_active_layer = _image.getActiveLayer()
_objs = _active_layer.objsInRegion(_xmin, _ymin, _xmax, _ymax)
if len(_objs):
_image.startAction()
try:
PythonCAD.Generic.delete.delete_objects(_objs)
finally:
_image.endAction()
tool.reset()
delete_mode_init(gtkimage)
gtkimage.redraw()
def delete_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_active_layer = _image.getActiveLayer()
_objs = _active_layer.mapPoint((_x, _y), _tol)
if len(_objs):
_dims = []
_image.startAction()
try:
for _obj in _objs:
if isinstance(_obj, Dimension):
_dims.append(_obj)
elif isinstance(_obj, tuple):
_entity, _pt = _obj
_active_layer.delObject(_entity)
else:
raise TypeError, "Unhandled object: " + `_obj`
for _dim in _dims:
if _dim in _active_layer: # it may have been removed ...
_active_layer.delObject(_dim)
finally:
_image.endAction()
gtkimage.redraw()
else:
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", delete_region_end_cb)
gtkimage.setPrompt(_('Click the second point for defining the region'))
_gc = gtkimage.getGC()
_gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
_gc.set_function(gtk.gdk.INVERT)
return True
def delete_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the items you want to delete.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", delete_button_press_cb)
_tool.setHandler("initialize", delete_mode_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = _image.getSelectedObjects()
_image.startAction()
try:
PythonCAD.Generic.delete.delete_objects(_objs)
finally:
_image.endAction()
#
# stretch operations
#
def stretch_end_button_press_cb(gtkimage, widget, event, tool):
_image = gtkimage.getImage()
_x2, _y2 = _image.getCurrentPoint()
_y1 = tool.popObject()
_x1 = tool.popObject()
_xmin = min(_x1, _x2)
_xmax = max(_x1, _x2)
_ymin = min(_y1, _y2)
_ymax = max(_y1, _y2)
tool.delHandler("motion_notify")
_active_layer = _image.getActiveLayer()
_dx, _dy = tool.getDistance()
_image.startAction()
try:
for _pt in _active_layer.getLayerEntities("point"):
if _pt.inRegion(_xmin, _ymin, _xmax, _ymax):
_pt.move(_dx, _dy)
finally:
_image.endAction()
gtkimage.redraw()
tool.clearLocation()
tool.clearCurrentPoint()
tool.setHandler("button_press", stretch_elem_button_press_cb)
return True
def stretch_elem_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
_active_layer = _image.getActiveLayer()
_pt = None
_pts = _active_layer.find('point', _x, _y, _tol)
if len(_pts):
_dx, _dy = tool.getDistance()
_image.startAction()
try:
for _pt in _pts:
_pt.move(_dx, _dy)
finally:
_image.endAction()
gtkimage.redraw()
else:
tool.pushObject(_x)
tool.pushObject(_y)
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", stretch_end_button_press_cb)
gtkimage.setPrompt(_('Click the second point for defining the region'))
_gc = gtkimage.getGC()
_gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
_gc.set_function(gtk.gdk.INVERT)
return True
#
# stretch horizontal
#
def stretch_horiz_button_press_cb(gtkimage, widget, event, tool):
if not len(tool):
move_button_press(gtkimage, tool)
gtkimage.setPrompt(_('Click a second point to indicate the horizontal distance'))
else:
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(gtkimage.getImage(),gtkimage.getTolerance(),_snapArray).point.getCoords()
#
# see if the point is at an intersection of drawing objects ...
#
_y1 = tool.popObject()
_x1 = tool.popObject()
tool.setDistance((_x - _x1), 0.0)
gtkimage.setPrompt(_('Select the points to move.'))
tool.delHandler("entry_event")
tool.setHandler("button_press", stretch_elem_button_press_cb)
return True
def stretch_horiz_entry_event(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_dist = util.get_float(eval(_text, gtkimage.image.getImageVariables()))
tool.setDistance(_dist, 0.0)
gtkimage.setPrompt(_('Select the points to move.'))
tool.setHandler("button_press", stretch_elem_button_press_cb)
tool.delHandler("entry_event")
def stretch_horizontal_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on a point or enter the horizontal distance.'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", stretch_horiz_button_press_cb)
_tool.setHandler("entry_event", stretch_horiz_entry_event)
_tool.setHandler("initialize", stretch_horizontal_init)
#
# stretch vertical
#
def stretch_vert_button_press_cb(gtkimage, widget, event, tool):
if not len(tool):
move_button_press(gtkimage, tool)
gtkimage.setPrompt(_('Click a second point to indicate the vertical distance'))
else:
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(gtkimage.getImage(),gtkimage.getTolerance(),_snapArray).point.getCoords()
#
# see if the point is at an intersection of drawing objects ...
#
_y1 = tool.popObject()
_x1 = tool.popObject()
tool.setDistance(0.0, (_y - _y1))
gtkimage.setPrompt(_('Select the points to move.'))
tool.delHandler("entry_event")
tool.setHandler("button_press", stretch_elem_button_press_cb)
return True
def stretch_vert_entry_event(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_dist = util.get_float(eval(_text, gtkimage.image.getImageVariables()))
tool.setDistance(0.0, _dist)
gtkimage.setPrompt(_('Select the points to move.'))
tool.setHandler("button_press", stretch_elem_button_press_cb)
tool.delHandler("entry_event")
def stretch_vertical_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter the distance.'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", stretch_vert_button_press_cb)
_tool.setHandler("entry_event", stretch_vert_entry_event)
_tool.setHandler("initialize", stretch_vertical_init)
#
# stretch x/y
#
def stretch_xy_entry_event(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = eval(_text, gtkimage.image.getImageVariables())
tool.setDistance(util.get_float(_x), util.get_float(_y))
gtkimage.setPrompt(_('Select the points to move.'))
tool.setHandler("button_press", stretch_elem_button_press_cb)
tool.delHandler("entry_event")
def stretch_xy_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
_x1, _y1 = tool.getLocation()
tool.setDistance((_x - _x1), (_y - _y1))
tool.clearLocation()
gtkimage.setPrompt(_('Select the points to move.'))
tool.setHandler("button_press", stretch_elem_button_press_cb)
tool.delHandler("entry_event")
return True
def stretch_xy_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
tool.setLocation(_x, _y)
gtkimage.setPrompt(_('Click another point to define the distance'))
tool.setHandler("button_press", stretch_xy_second_button_press_cb)
return True
def stretch_xy_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter the x and y distances.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", stretch_xy_first_button_press_cb)
_tool.setHandler("entry_event", stretch_xy_entry_event)
_tool.setHandler("initialize", stretch_xy_init)
#
# rotate objects
#
def rotate_objects(gtkimage, objlist, tool):
_init_func = tool.getHandler("initialize")
_cx, _cy = tool.getRotationPoint()
_angle = tool.getAngle()
_image = gtkimage.getImage()
_image.startAction()
try:
PythonCAD.Generic.rotate.rotate_objects(objlist, _cx, _cy, _angle)
finally:
_image.endAction()
tool.reset()
_init_func(gtkimage, tool)
def rotate_end_button_press_cb(gtkimage, widget, event, tool):
_image = gtkimage.getImage()
_x2, _y2 = _image.getCurrentPoint()
_x1, _y1 = tool.getLocation()
_xmin = min(_x1, _x2)
_xmax = max(_x1, _x2)
_ymin = min(_y1, _y2)
_ymax = max(_y1, _y2)
_active_layer = _image.getActiveLayer()
_objlist = _active_layer.objsInRegion(_xmin, _ymin, _xmax, _ymax)
rotate_objects(gtkimage, _objlist, tool)
return True
def rotate_elem_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol, None)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
_objs = []
for _obj, _pt in _objdict[_active_layer]:
_objs.append(_obj)
rotate_objects(gtkimage, _objs, tool)
else:
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", rotate_end_button_press_cb)
gtkimage.setPrompt(_('Click the second point for defining the region'))
_gc = gtkimage.getGC()
_gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
_gc.set_function(gtk.gdk.INVERT)
return True
def rotate_angle_entry_event(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_angle = eval(_text, gtkimage.image.getImageVariables())
tool.setAngle(util.get_float(_angle))
gtkimage.setPrompt(_('Select the objects to rotate'))
tool.delHandler("entry_event")
tool.setHandler("button_press", rotate_elem_button_press_cb)
def rotate_angle_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
_objdict = _image.mapPoint(_x, _y, _tol)
_a2 = None
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
for _obj, _pt in _objdict[_active_layer]:
if isinstance(_obj, HCLine):
_a2 = 0.0
elif isinstance(_obj, VCLine):
_a2 = 90.0
elif isinstance(_obj, ACLine):
_a2 = _obj.getAngle()
elif isinstance(_obj, CLine):
_p1, _p2 = _obj.getKeypoints()
_a2 = atan2((_p2.y - _p1.y), (_p2.x - _p1.x)) * (180.0/pi)
else:
pass
if _a2 is not None:
break
if _a2 is not None:
_cl = tool.getObject(0)
if isinstance(_cl, HCLine):
_a1 = 0.0
elif isinstance(_cl, VCLine):
_a1 = 90.0
elif isinstance(_cl, ACLine):
_a1 = _cl.getAngle()
elif isinstance(_cl, CLine):
_p1, _p2 = _cl.getKeypoints()
_a1 = atan2((_p2.y - _p1.y), (_p2.x - _p1.x)) * (180.0/pi)
else:
raise RuntimeError, "Unexpected conline type: " + `type(_cl)`
_angle = _a2 - _a1
if abs(_angle) > 1e-10:
tool.setAngle(_angle)
gtkimage.setPrompt(_('Select the objects to rotate'))
tool.delHandler("entry_event")
tool.setHandler("button_press", rotate_elem_button_press_cb)
return True
def rotate_angle_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
_objdict = _image.mapPoint(_x, _y, _tol)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
for _obj, _pt in _objdict[_active_layer]:
if isinstance(_obj, (HCLine, VCLine, ACLine, CLine)):
tool.pushObject(_obj)
tool.setHandler("button_press",
rotate_angle_second_button_press_cb)
gtkimage.setPrompt(_('Click on another construction line to define the angle of rotation or enter the rotation angle.'))
break
return True
def rotate_point_entry_event(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = eval(_text, gtkimage.image.getImageVariables())
tool.setRotationPoint(util.get_float(_x), util.get_float(_y))
gtkimage.setPrompt(_('Click on a construction line or enter the rotation angle.'))
tool.setHandler("entry_event", rotate_angle_entry_event)
tool.setHandler("button_press", rotate_angle_first_button_press_cb)
def rotate_point_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_x,_y=snap.getSnapPoint(_image,_tol,_snapArray).point.getCoords()
tool.setRotationPoint(_x, _y)
gtkimage.setPrompt(_('Click on a construction line or enter the rotation angle'))
tool.setHandler("button_press", rotate_angle_first_button_press_cb)
tool.setHandler("entry_event", rotate_angle_entry_event)
return True
def rotate_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter the rotation center coordinates.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", rotate_point_button_press_cb)
_tool.setHandler("entry_event", rotate_point_entry_event)
_tool.setHandler("initialize", rotate_init)
#
# split objects into two pieces or at intersection points
#
def split_end_button_press_cb(gtkimage, widget, event, tool):
_image = gtkimage.getImage()
_x2, _y2 = getSnapPoint(_image,_image.get.getTolerance()).point.getCoords()
_y1 = tool.popObject()
_x1 = tool.popObject()
_xmin = min(_x1, _x2)
_xmax = max(_x1, _x2)
_ymin = min(_y1, _y2)
_ymax = max(_y1, _y2)
tool.delHandler("motion_notify")
_active_layer = _image.getActiveLayer()
_objs = _active_layer.objsInRegion(_xmin, _ymin, _xmax, _ymax, True)
if len(_objs):
_splitable = []
for _obj in _objs:
if isinstance(_obj, (Segment, Circle, Arc, Polyline)):
_splitable.append(_obj)
if len(_splitable):
_image.startAction()
try:
split.split_objects(_splitable)
finally:
_image.endAction()
gtkimage.setPrompt(_('Click on the objects you want to split.'))
tool.clearLocation()
tool.clearCurrentPoint()
tool.setHandler("button_press", split_object_button_press_cb)
return True
def split_object_button_press_cb(gtkimage, widget, event, tool):
"""
First callbeck for the split comand
"""
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = snap.getSnapPoint(_image,_tol).point.getCoords()
_active_layer = _image.getActiveLayer()
_objlist = _active_layer.mapPoint((_x, _y), _tol, None)
if len(_objlist):
for _obj, _pt in _objlist:
_px, _py = _pt.getCoords()
if isinstance(_obj, Segment):
_image.startAction()
try:
_segs = split.split_segment_at(_obj, _px, _py)
if _segs is not None:
_active_layer.delObject(_obj)
_s1, _s2 = _segs
_active_layer.addObject(_s1)
_active_layer.addObject(_s2)
finally:
_image.endAction()
elif isinstance(_obj, Arc):
_image.startAction()
try:
_arcs = split.split_arc_at(_obj, _px, _py)
if _arcs is not None:
_active_layer.delObject(_obj)
_a1, _a2 = _arcs
_active_layer.addObject(_a1)
_active_layer.addObject(_a2)
finally:
_image.endAction()
elif isinstance(_obj, Circle):
_image.startAction()
try:
_arc = split.split_circle_at(_obj, _px, _py)
if _arc is not None:
_active_layer.delObject(_obj)
_active_layer.addObject(_arc)
finally:
_image.endAction()
elif isinstance(_obj, Polyline):
_image.startAction()
try:
if split.split_polyline_at(_obj, _px, _py):
_obj.erase(gtkimage)
_obj.draw(gtkimage)
finally:
_image.endAction()
else:
pass
else:
tool.pushObject(_x)
tool.pushObject(_y)
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", split_end_button_press_cb)
gtkimage.setPrompt(_('Click the second point for defining the region'))
_gc = gtkimage.getGC()
_gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
_gc.set_function(gtk.gdk.INVERT)
return True
def split_object_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the objects you want to split'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("initialize", split_object_init)
_tool.setHandler("button_press", split_object_button_press_cb)
_image = gtkimage.getImage()
if _image.hasSelection():
_splitable = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, (Segment, Circle, Arc, Polyline)):
_splitable.append(_obj)
if len(_splitable):
_image.startAction()
try:
split.split_objects(_splitable)
finally:
_image.endAction()
#
# transfer objects from one layer to another
#
def transfer_end_button_press_cb(gtkimage, widget, event, tool):
_image = gtkimage.getImage()
_x2, _y2 = _image.getCurrentPoint()
_y1 = tool.popObject()
_x1 = tool.popObject()
_xmin = min(_x1, _x2)
_xmax = max(_x1, _x2)
_ymin = min(_y1, _y2)
_ymax = max(_y1, _y2)
tool.delHandler("motion_notify")
_active_layer = _image.getActiveLayer()
_layers = [_image.getTopLayer()]
_objdict = {}
while len(_layers):
_layer = _layers.pop()
if _layer is not _active_layer:
if _layer.isVisible():
_objs = _layer.objsInRegion(_xmin, _ymin, _xmax, _ymax)
if len(_objs):
_objdict[_layer] = _objs
_layers.extend(_layer.getSublayers())
if len(_objdict):
_image.startAction()
try:
for _layer in _objdict:
if _layer is not _active_layer:
_objs = _objdict[_layer]
PythonCAD.Generic.transfer.transfer_objects(_objs, _active_layer)
finally:
_image.endAction()
tool.clearLocation()
tool.clearCurrentPoint()
tool.setHandler("button_press", transfer_object_button_press_cb)
return True
def transfer_object_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_active_layer = _image.getActiveLayer()
_objdict = _image.mapPoint(_x, _y, _tol, None)
if len(_objdict):
_image.startAction()
try:
for _layer in _objdict:
if _layer is not _active_layer:
_objs = []
for _obj, _pt in _objdict[_layer]:
_objs.append(_obj)
PythonCAD.Generic.transfer.transfer_objects(_objs, _active_layer)
finally:
_image.endAction()
else:
tool.pushObject(_x)
tool.pushObject(_y)
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", transfer_end_button_press_cb)
gtkimage.setPrompt(_('Click the second point for defining the region'))
gc = gtkimage.getGC()
gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
gc.set_function(gtk.gdk.INVERT)
return True
def transfer_object_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the objects you want to transfer to the active layer'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", transfer_object_button_press_cb)
#
# common attribute changing code
#
def _change_attribute(gtkimage, objlist, tool=None):
_tool = gtkimage.getImage().getTool()
_init = _tool.getHandler('initialize')
_attr = _tool.getAttribute()
_value = _tool.getValue()
if len(objlist):
_image = gtkimage.getImage()
_image.startAction()
try:
for _obj in objlist:
getattr(_obj, _attr)(_value)
finally:
_image.endAction()
_tool.reset()
_init(gtkimage, _tool)
def change_attr_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_active_layer = _image.getActiveLayer()
_pts = _active_layer.find('point', _x, _y)
if len(_pts) > 0:
_x, _y = _pts[0].getCoords()
_x1, _y1 = tool.getLocation()
_xmin = min(_x1, _x)
_ymin = min(_y1, _y)
_xmax = max(_x1, _x)
_ymax = max(_y1, _y)
_objs = []
_filter = tool.getFilter()
_objtype = tool.getObjtype()
for _obj in _active_layer.objsInRegion(_xmin, _ymin, _xmax, _ymax):
if _filter is not None:
_fobj = _filter(tool, _obj)
if _fobj is not None:
_objs.append(_fobj)
elif _objtype is not None:
if isinstance(_obj, _objtype):
_objs.append(_obj)
else:
_objs.append(_obj)
_change_attribute(gtkimage, _objs, tool)
return True
def change_attr_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol, None)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
_objs = []
_objtype = tool.getObjtype()
for _obj, _pt in _objdict[_active_layer]:
if _objtype is None:
_objs.append(_obj)
else:
if isinstance(_obj, _objtype):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, tool)
else:
_x, _y = _image.getClosestPoint(_x, _y, tolerance=_tol)
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", change_attr_second_button_press_cb)
gtkimage.setPrompt(_('Click the second point for defining the region'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
#
# change color
#
def change_color_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_color_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, GraphicObject):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the items you want the color to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_color_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.ColorSelectionDialog(_('Set Active Color'))
_dialog.set_transient_for(_window)
_colorsel = _dialog.colorsel
_image = gtkimage.getImage()
_prev_color = _image.getOption('LINE_COLOR')
_gtk_color = gtkimage.getColor(_prev_color)
_colorsel.set_previous_color(_gtk_color)
_colorsel.set_current_color(_gtk_color)
_colorsel.set_has_palette(True)
_color = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_gtk_color = _colorsel.get_current_color()
_r = int(round((_gtk_color.red/65535.0) * 255.0))
_g = int(round((_gtk_color.green/65535.0) * 255.0))
_b = int(round((_gtk_color.blue/65535.0) * 255.0))
for _c in _image.getImageEntities('color'):
if _c.r == _r and _c.g == _g and _c.b == _b:
_color = _c
break
if _color is None:
_color = color.Color(_r, _g, _b)
_dialog.destroy()
return _color
#
# change linetypes
#
def change_linetype_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_linetype_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, GraphicObject):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the items you want the linetype to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_linetype_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Linetype'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Linetype:'))
_hbox.pack_start(_label, False, False, 0)
_image = gtkimage.getImage()
_clt = _image.getOption('LINE_TYPE')
_linetypes = _image.getImageEntities('linetype')
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_linetypes)):
_lt = _linetypes[_i]
if _lt is _clt:
_idx = _i
_widget.append_text(_lt.getName())
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_linetypes)):
_lt = _linetypes[_i]
if _lt is _clt:
_idx = _i
_item = gtk.MenuItem(_lt.getName())
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_widget, True, True, 0)
_dialog.show_all()
_lt = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected widget: " + `type(_widget)`
_lt = _linetypes[_idx]
_dialog.destroy()
return _lt
#
# change thickness
#
def change_thickness_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_thickness_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, GraphicObject):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the items you want the thickness to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_thickness_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Thickness'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Thickness:'))
_hbox.pack_start(_label, False, False, 0)
_thickness = gtkimage.image.getOption('LINE_THICKNESS')
_adj = gtk.Adjustment(_thickness, 0.0001, 20.0, 0.1, 1.0, 1.0)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(1)
_sb.set_numeric(False)
_hbox.pack_start(_sb, True, True, 0)
_dialog.show_all()
_t = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_t = float(_sb.get_value())
_dialog.destroy()
return _t
#
# change the style
#
def change_style_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_style_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, GraphicObject):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the items you want the style to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_style_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Style'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Style:'))
_image = gtkimage.getImage()
_cst = _image.getOption('LINE_STYLE')
_styles = _image.getImageEntities('style')
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_styles)):
_s = _styles[_i]
if _s is _cst:
_idx = _i
_widget.append_text(_s.getName())
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_styles)):
_s = _styles[_i]
if _s is _cst:
_idx = _i
_item = gtk.MenuItem(_s.getName())
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_label, False, False, 0)
_hbox.pack_start(_widget, True, True, 0)
_dialog.show_all()
_s = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected widget: " + `type(_widget)`
_s = _styles[_idx]
_dialog.destroy()
return _s
#
# Change TextBlock properties
#
def change_textblock_size_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_textblock_size_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, TextBlock):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the items you want the size to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_textblock_size_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Text Size'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Text Size:'))
_hbox.pack_start(_label, False, False, 0)
_size = gtkimage.image.getOption(key)
_adj = gtk.Adjustment(_size, 0.0001, 400.0, 0.1, 1.0, 1.0)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(1)
_sb.set_numeric(False)
_hbox.pack_start(_sb, True, True, 0)
_dialog.show_all()
_size = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_size = float(_sb.get_value())
_dialog.destroy()
return _size
def change_textblock_family_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_textblock_family_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, TextBlock):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the objects you want the family to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_textblock_family_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Font Family'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_families = []
for _family in _window.get_pango_context().list_families():
_families.append(_family.get_name())
_families.sort()
_label = gtk.Label(_('Family:'))
_family = gtkimage.image.getOption(key)
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_families)):
_f = _families[_i]
if _f == _family:
_idx = _i
_widget.append_text(_f)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_families)):
_f = _families[_i]
if _f == _family:
_idx = _i
_item = gtk.MenuItem(_f)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_label, False, False, 0)
_hbox.pack_start(_widget, True, True, 0)
_dialog.show_all()
_family = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected widget: " + `type(_widget)`
_family = _families[_idx]
_dialog.destroy()
return _family
def change_textblock_weight_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_textblock_weight_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, TextBlock):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the objects you want the weight to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_textblock_weight_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Text Weight'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Text Weight:'))
_weight = gtkimage.image.getOption(key)
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
_widget.append_text(_('NORMAL'))
if _weight == TextStyle.WEIGHT_NORMAL:
_idx = 0
_widget.append_text(_('LIGHT'))
if _weight == TextStyle.WEIGHT_LIGHT:
_idx = 1
_widget.append_text(_('BOLD'))
if _weight == TextStyle.WEIGHT_BOLD:
_idx = 2
_widget.append_text(_('HEAVY'))
if _weight == TextStyle.WEIGHT_HEAVY:
_idx = 3
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
_item = gtk.MenuItem(_('NORMAL'))
_menu.append(_item)
if _weight == TextStyle.WEIGHT_NORMAL:
_idx = 0
_item = gtk.MenuItem(_('LIGHT'))
_menu.append(_item)
if _weight == TextStyle.WEIGHT_LIGHT:
_idx = 1
_item = gtk.MenuItem(_('BOLD'))
_menu.append(_item)
if _weight == TextStyle.WEIGHT_BOLD:
_idx = 2
_item = gtk.MenuItem(_('HEAVY'))
_menu.append(_item)
if _weight == TextStyle.WEIGHT_HEAVY:
_idx = 3
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_label, False, False, 0)
_hbox.pack_start(_widget, True, True, 0)
_dialog.show_all()
_weight = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if isinstance(_widget, gtk.ComboBox):
_weight = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_weight = _widget.get_history()
else:
raise TypeError, "Unexpected widget: " + `type(_widget)`
_dialog.destroy()
return _weight
def change_textblock_style_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_textblock_style_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, TextBlock):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the objects you want the style to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_textblock_style_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Text Style'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Text Style:'))
_style = gtkimage.image.getOption(key)
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
_widget.append_text(_('NORMAL'))
if _style == TextStyle.FONT_NORMAL:
_idx = 0
_widget.append_text(_('OBLIQUE'))
if _style == TextStyle.FONT_OBLIQUE:
_idx = 1
_widget.append_text(_('ITALIC'))
if _style == TextStyle.FONT_ITALIC:
_idx = 2
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
_item = gtk.MenuItem(_('NORMAL'))
_menu.append(_item)
if _style == TextStyle.FONT_NORMAL:
_idx = 0
_item = gtk.MenuItem(_('OBLIQUE'))
_menu.append(_item)
if _style == TextStyle.FONT_OBLIQUE:
_idx = 1
_item = gtk.MenuItem(_('ITALIC'))
_menu.append(_item)
if _style == TextStyle.FONT_ITALIC:
_idx = 2
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_label, False, False, 0)
_hbox.pack_start(_widget, True, True, 0)
_dialog.show_all()
_style = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if isinstance(_widget, gtk.ComboBox):
_style = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_style = _widget.get_history()
else:
raise TypeError, "Unexpected widget: " + `type(_widget)`
_dialog.destroy()
return _style
def change_textblock_alignment_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_textblock_alignment_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, TextBlock):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the objects you want the alignment to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_textblock_alignment_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Text Alignment'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Text Alignment:'))
_align = gtkimage.image.getOption(key)
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
_widget.append_text(_('LEFT'))
if _align == TextStyle.ALIGN_LEFT:
_idx = 0
_widget.append_text(_('CENTER'))
if _align == TextStyle.ALIGN_CENTER:
_idx = 1
_widget.append_text(_('RIGHT'))
if _align == TextStyle.ALIGN_RIGHT:
_idx = 2
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
_item = gtk.MenuItem(_('LEFT'))
_menu.append(_item)
if _align == TextStyle.ALIGN_LEFT:
_idx = 0
_item = gtk.MenuItem(_('CENTER'))
_menu.append(_item)
if _align == TextStyle.ALIGN_CENTER:
_idx = 1
_item = gtk.MenuItem(_('RIGHT'))
_menu.append(_item)
if _align == TextStyle.ALIGN_RIGHT:
_idx = 2
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_label, False, False, 0)
_hbox.pack_start(_widget, True, True, 0)
_dialog.show_all()
_align = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if isinstance(_widget, gtk.ComboBox):
_align = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_align = _widget.get_history()
else:
raise TypeError, "Unexpected widget: " + `type(_widget)`
_dialog.destroy()
return _align
def change_textblock_color_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_textblock_color_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, TextBlock):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the objects you want the color to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_textblock_color_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.ColorSelectionDialog(_('Change Font Color'))
_dialog.set_transient_for(_window)
_colorsel = _dialog.colorsel
_image = gtkimage.getImage()
_color = _image.getOption(key)
_gtk_color = gtkimage.getColor(_color)
_colorsel.set_previous_color(_gtk_color)
_colorsel.set_current_color(_gtk_color)
_colorsel.set_has_palette(True)
_color = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_gtk_color = _colorsel.get_current_color()
_r = int(round((_gtk_color.red/65535.0) * 255.0))
_g = int(round((_gtk_color.green/65535.0) * 255.0))
_b = int(round((_gtk_color.blue/65535.0) * 255.0))
for _c in _image.getImageEntities('color'):
if _c.r == _r and _c.g == _g and _c.b == _b:
_color = _c
break
if _color is None:
_color = color.Color(_r, _g, _b)
_dialog.destroy()
return _color
#
# Change Dimension Properties
#
def change_dim_offset_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dim_offset_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, Dimension):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the dimension you want the offset to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_dim_offset_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Offset Length'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Length:'))
_hbox.pack_start(_label, False, False, 0)
_offset = gtkimage.image.getOption('DIM_OFFSET')
_adj = gtk.Adjustment(_offset, 0.01, 200.0, 0.1, 1.0, 1.0)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(2)
_sb.set_numeric(False)
_hbox.pack_start(_sb, True, True, 0)
_dialog.show_all()
_offset = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_offset = float(_sb.get_value())
_dialog.destroy()
return _offset
def change_dim_extension_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dim_extension_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, Dimension):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the dimension you want the extension to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_dim_extension_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Extension Length'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Length:'))
_hbox.pack_start(_label, False, False, 0)
_extlen = gtkimage.image.getOption('DIM_EXTENSION')
_adj = gtk.Adjustment(_extlen, 0.01, 200.0, 0.1, 1.0, 1.0)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(2)
_sb.set_numeric(False)
_hbox.pack_start(_sb, True, True, 0)
_dialog.show_all()
_extlen = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_extlen = float(_sb.get_value())
_dialog.destroy()
return _extlen
def change_dim_endpoint_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dim_endpoint_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, Dimension):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the dimension you want the endpoint type to change.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_dim_endpoint_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Endpoint Markers'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Endpoints:'))
_endpt = gtkimage.image.getOption('DIM_ENDPOINT')
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
_widget.append_text(_('None'))
if _endpt == Dimension.DIM_ENDPT_NONE:
_idx = 0
_widget.append_text(_('Arrow'))
if _endpt == Dimension.DIM_ENDPT_ARROW:
_idx = 1
_widget.append_text(_('Filled Arrow'))
if _endpt == Dimension.DIM_ENDPT_FILLED_ARROW:
_idx = 2
_widget.append_text(_('Slash'))
if _endpt == Dimension.DIM_ENDPT_SLASH:
_idx = 3
_widget.append_text(_('Circle'))
if _endpt == Dimension.DIM_ENDPT_CIRCLE:
_idx = 4
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
_item = gtk.MenuItem(_('None'))
_menu.append(_item)
if _endpt == Dimension.DIM_ENDPT_NONE:
_idx = 0
_item = gtk.MenuItem(_('Arrow'))
_menu.append(_item)
if _endpt == Dimension.DIM_ENDPT_ARROW:
_idx = 1
_item = gtk.MenuItem(_('Filled Arrow'))
_menu.append(_item)
if _endpt == Dimension.DIM_ENDPT_FILLED_ARROW:
_idx = 2
_item = gtk.MenuItem(_('Slash'))
_menu.append(_item)
if _endpt == Dimension.DIM_ENDPT_SLASH:
_idx = 3
_item = gtk.MenuItem(_('Circle'))
_menu.append(_item)
if _endpt == Dimension.DIM_ENDPT_CIRCLE:
_idx = 4
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_label, False, False, 0)
_hbox.pack_start(_widget, True, True, 0)
_dialog.show_all()
_endpt = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if isinstance(_widget, gtk.ComboBox):
_endpt = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_endpt = _widget.get_history()
else:
raise TypeError, "Unexpected widget: " + `type(_widget)`
_dialog.destroy()
return _endpt
def change_dim_endpoint_size_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dim_endpoint_size_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, Dimension):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the dimension you want the endpoint size to change.'))
tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_dim_endpoint_size_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Endpoint Size'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Length:'))
_hbox.pack_start(_label, False, False, 0)
_size = gtkimage.image.getOption('DIM_ENDPOINT_SIZE')
_adj = gtk.Adjustment(_size, 0.01, 200.0, 0.1, 1.0, 1.0)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(2)
_sb.set_numeric(False)
_hbox.pack_start(_sb, True, True, 0)
_dialog.show_all()
_size = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_size = float(_sb.get_value())
_dialog.destroy()
return _size
def change_dim_dual_mode_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dim_dual_mode_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, Dimension):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the dimension you want to change the dual dimension display.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_dim_dual_mode_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Dual Mode'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_cb = gtk.CheckButton(_('Display Two Dimension Values'))
_mode = gtkimage.image.getOption('DIM_DUAL_MODE')
_cb.set_active(_mode)
_hbox.pack_start(_cb, True, True, 0)
_dialog.show_all()
_mode = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_mode = _cb.get_active()
_dialog.destroy()
return _mode
def change_dim_dual_mode_offset_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dim_dual_mode_offset_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, Dimension):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the dimension you want to change the dual dimension offset value.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_dim_dual_mode_offset_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Dual Mode Offset'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Length:'))
_hbox.pack_start(_label, False, False, 0)
_offset = gtkimage.image.getOption('DIM_DUAL_MODE_OFFSET')
_adj = gtk.Adjustment(_offset, 0.01, 200.0, 0.1, 1.0, 1.0)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(2)
_sb.set_numeric(False)
_hbox.pack_start(_sb, True, True, 0)
_dialog.show_all()
_offset = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_offset = float(_sb.get_value())
_dialog.destroy()
return _offset
def change_dim_thickness_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dim_thickness_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, Dimension):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the dimension you want to change the thickess.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_dim_thickness_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Dim Thickness'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Thickness:'))
_hbox.pack_start(_label, False, False, 0)
_t = gtkimage.image.getOption('DIM_THICKNESS')
_adj = gtk.Adjustment(_t, 0.01, 200.0, 0.1, 1.0, 1.0)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(2)
_sb.set_numeric(False)
_hbox.pack_start(_sb, True, True, 0)
_dialog.show_all()
_t = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_t = float(_sb.get_value())
_dialog.destroy()
return _t
def change_dim_color_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dim_color_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, Dimension):
_objs.append(_obj)
_change_attribute(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the dimension you want to change the color.'))
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_dim_color_dialog(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.ColorSelectionDialog(_('Change Dimension Color'))
_dialog.set_transient_for(_window)
_colorsel = _dialog.colorsel
_image = gtkimage.getImage()
_color = _image.getOption('DIM_COLOR')
_gtk_color = gtkimage.getColor(_color)
_colorsel.set_previous_color(_gtk_color)
_colorsel.set_current_color(_gtk_color)
_colorsel.set_has_palette(True)
_color = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_gtk_color = _colorsel.get_current_color()
_r = int(round((_gtk_color.red/65535.0) * 255.0))
_g = int(round((_gtk_color.green/65535.0) * 255.0))
_b = int(round((_gtk_color.blue/65535.0) * 255.0))
for _c in _image.getImageEntities('color'):
if _c.r == _r and _c.g == _g and _c.b == _b:
_color = _c
break
if _color is None:
_color = color.Color(_r, _g, _b)
_dialog.destroy()
return _color
#
# Change DimString properties
#
def _dimstring_filter_proc(tool, obj):
_ds = None
if isinstance(obj, Dimension):
if tool.getPrimary():
_ds = obj.getPrimaryDimstring()
else:
_ds = obj.getSecondaryDimstring()
return _ds
def _ldimstring_filter_proc(tool, obj):
_ds = None
if isinstance(obj, (LinearDimension,
HorizontalDimension,
VerticalDimension)):
if tool.getPrimary():
_ds = obj.getPrimaryDimstring()
else:
_ds = obj.getSecondaryDimstring()
return _ds
def _rdimstring_filter_proc(tool, obj):
_ds = None
if isinstance(obj, RadialDimension):
if tool.getPrimary():
_ds = obj.getPrimaryDimstring()
else:
_ds = obj.getSecondaryDimstring()
return _ds
def _adimstring_filter_proc(tool, obj):
_ds = None
if isinstance(obj, AngularDimension):
if tool.getPrimary():
_ds = obj.getPrimaryDimstring()
else:
_ds = obj.getSecondaryDimstring()
return _ds
def change_dimstr_prefix_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Prefix'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Prefix:'))
_hbox.pack_start(_label, True, True, 0)
_prefix = gtkimage.image.getOption(key)
_entry = gtk.Entry()
_entry.set_text(_prefix)
_hbox.pack_start(_entry, True, True, 0)
_dialog.show_all()
_prefix = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_prefix = _entry.get_text()
_dialog.destroy()
return _prefix
def change_dimstr_suffix_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Suffix'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Suffix:'))
_hbox.pack_start(_label, True, True, 0)
_suffix = gtkimage.image.getOption(key)
_entry = gtk.Entry()
_entry.set_text(_suffix)
_hbox.pack_start(_entry, True, True, 0)
_dialog.show_all()
_suffix = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_suffix = _entry.get_text()
_dialog.destroy()
return _suffix
def change_dimstr_precision_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Precision'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Precision:'))
_hbox.pack_start(_label, False, False, 0)
_prec = gtkimage.image.getOption(key)
_adj = gtk.Adjustment(_prec, 0, 15, 1, 1, 1)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(0)
_sb.set_numeric(True)
_hbox.pack_start(_sb, True, True, 0)
_dialog.show_all()
_prec = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_prec = int(_sb.get_value())
_dialog.destroy()
return _prec
def change_dimstr_units_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Units'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Units'))
_hbox.pack_start(_label, False, False, 0)
_units = [(_('Millimeters'), PythonCAD.Generic.units.MILLIMETERS),
(_('Micrometers'), PythonCAD.Generic.units.MICROMETERS),
(_('Meters'), PythonCAD.Generic.units.METERS),
(_('Kilometers'), PythonCAD.Generic.units.KILOMETERS),
(_('Inches'), PythonCAD.Generic.units.INCHES),
(_('Feet'), PythonCAD.Generic.units.FEET),
(_('Yards'), PythonCAD.Generic.units.YARDS),
(_('Miles'), PythonCAD.Generic.units.MILES),
]
_unit = gtkimage.image.getOption(key)
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_unit_widget = gtk.combo_box_new_text()
for _i in range(len(_units)):
_str, _val = _units[_i]
if _unit == _val:
_idx = _i
_unit_widget.append_text(_str)
_unit_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_units)):
_str, _val = _units[_i]
if _unit == _val:
_idx = _i
_item = gtk.MenuItem(_str)
_menu.append(_item)
_unit_widget = gtk.OptionMenu()
_unit_widget.set_menu(_menu)
_unit_widget.set_history(_idx)
_hbox.pack_start(_unit_widget, True, True, 0);
_dialog.show_all()
_unit = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_idx = _unit_widget.get_active()
else:
_idx = _unit_widget.get_history()
_unit = _units[_idx][1]
_dialog.destroy()
return _unit
def change_dimstr_print_decimal_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Print Decimal'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_cb = gtk.CheckButton(_('Print Trailing Decimal'))
_mode = gtkimage.image.getOption(key)
_cb.set_active(_mode)
_hbox.pack_start(_cb, True, True, 0)
_dialog.show_all()
_mode = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_mode = _cb.get_active()
_dialog.destroy()
return _mode
def change_dimstr_print_zero_dialog(gtkimage, key):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Change Print Zero'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_cb = gtk.CheckButton(_('Print Leading Zero'))
_mode = gtkimage.image.getOption(key)
_cb.set_active(_mode)
_hbox.pack_start(_cb, True, True, 0)
_dialog.show_all()
_mode = None
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_mode = _cb.get_active()
_dialog.destroy()
return _mode
def _change_dimstring_init(gtkimage, tool=None):
_image = gtkimage.getImage()
_tool = _image.getTool()
if _image.hasSelection():
_primary = tool.getPrimary()
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, Dimension):
if _primary:
_objs.append(_obj.getPrimaryDimstring())
else:
_objs.append(_obj.getSecondaryDimstring())
_change_attribute(gtkimage, _objs, _tool)
else:
_tool.setHandler("button_press", change_attr_first_button_press_cb)
def change_dimstr_family_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString family.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dimstr_family_init)
_tool.setFilter(_dimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_dimstr_style_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString style.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dimstr_style_init)
_tool.setFilter(_dimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_dimstr_weight_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString weight.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dimstr_weight_init)
_tool.setFilter(_dimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_dimstr_alignment_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString alignment.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dimstr_alignment_init)
_tool.setFilter(_dimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_dimstr_size_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString size.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dimstr_size_init)
_tool.setFilter(_dimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_dimstr_color_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString color.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dimstr_color_init)
_tool.setFilter(_dimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_ldimstr_prefix_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString prefix.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_ldimstr_prefix_init)
_tool.setFilter(_ldimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_ldimstr_suffix_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString suffix.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_ldimstr_suffix_init)
_tool.setFilter(_ldimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_rdimstr_prefix_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the RadialDimension you want to change the DimString prefix.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_rdimstr_prefix_init)
_tool.setFilter(_rdimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_rdimstr_suffix_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the RadialDimension you want to change the DimString suffix.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_rdimstr_suffix_init)
_tool.setFilter(_rdimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_adimstr_prefix_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the AngularDimension you want to change the DimString prefix.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_adimstr_prefix_init)
_tool.setFilter(_adimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_adimstr_suffix_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the AngularDimension you want to change the DimString suffix.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_adimstr_suffix_init)
_tool.setFilter(_adimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_dimstr_precision_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString precision.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dimstr_precision_init)
_tool.setFilter(_dimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_dimstr_units_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString units.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dimstr_units_init)
_tool.setFilter(_dimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_dimstr_print_zero_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString print leading zero flag.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dimstr_print_zero_init)
_tool.setFilter(_dimstring_filter_proc)
_change_dimstring_init(gtkimage)
def change_dimstr_print_decimal_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click the dimension you want to change the DimString print trailing decimal flag.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_dimstr_print_decimal_init)
_tool.setFilter(_dimstring_filter_proc)
_change_dimstring_init(gtkimage)
def _change_rdim_dia_mode(gtkimage, objlist, tool):
_init = tool.getHandler('initialize')
if len(objlist):
_image = gtkimage.getImage()
_image.startAction()
try:
for _obj in objlist:
_mode = not _obj.getDiaMode()
_obj.setDiaMode(_mode)
finally:
_image.endAction()
tool.reset()
_init(gtkimage)
def _rdim_dia_mode_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_active_layer = _image.getActiveLayer()
_pts = _active_layer.find('point', _x, _y)
if len(_pts) > 0:
_x, _y = _pts[0].getCoords()
_x1, _y1 = tool.getLocation()
_xmin = min(_x1, _x)
_ymin = min(_y1, _y)
_xmax = max(_x1, _x)
_ymax = max(_y1, _y)
_objs = []
for _obj in _active_layer.objsInRegion(_xmin, _ymin, _xmax, _ymax):
if isinstance(_obj, RadialDimension):
_objs.append(_obj)
_change_rdim_dia_mode(gtkimage, _objs, tool)
return True
def _rdim_dia_mode_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol, None)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
_objs = []
for _obj, _pt in _objdict[_active_layer]:
if isinstance(_obj, RadialDimension):
_objs.append(_obj)
_change_rdim_dia_mode(gtkimage, _objs, tool)
else:
_x, _y = _image.getClosestPoint(_x, _y, tolerance=_tol)
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", _rdim_dia_mode_second_button_press_cb)
gtkimage.setPrompt(_('Click the second point for defining the region'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def change_rdim_dia_mode_init(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", change_rdim_dia_mode_init)
_image = gtkimage.getImage()
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, RadialDimension):
_objs.append(_obj)
_change_rdim_dia_mode(gtkimage, _objs, tool)
else:
gtkimage.setPrompt(_('Click the RadialDimensions to toggle diameter dimension display'))
_tool.setHandler("button_press", _rdim_dia_mode_first_button_press_cb)
def _invert_adim(gtkimage, objlist, tool):
_init = tool.getHandler('initialize')
if len(objlist):
_image = gtkimage.getImage()
_image.startAction()
try:
for _obj in objlist:
_obj.invert()
finally:
_image.endAction()
tool.reset()
_init(gtkimage)
def _invert_adim_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_active_layer = _image.getActiveLayer()
_pts = _active_layer.find('point', _x, _y)
if len(_pts) > 0:
_x, _y = _pts[0].getCoords()
_x1, _y1 = tool.getLocation()
_xmin = min(_x1, _x)
_ymin = min(_y1, _y)
_xmax = max(_x1, _x)
_ymax = max(_y1, _y)
_objs = []
for _obj in _active_layer.objsInRegion(_xmin, _ymin, _xmax, _ymax):
if isinstance(_obj, AngularDimension):
_objs.append(_obj)
_invert_adim(gtkimage, _objs, tool)
return True
def _invert_adim_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_objdict = _image.mapPoint(_x, _y, _tol, None)
if len(_objdict):
_active_layer = _image.getActiveLayer()
if _active_layer in _objdict:
_objs = []
for _obj, _pt in _objdict[_active_layer]:
if isinstance(_obj, AngularDimension):
_objs.append(_obj)
_invert_adim(gtkimage, _objs, tool)
else:
_x, _y = _image.getClosestPoint(_x, _y, tolerance=_tol)
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", select_motion_notify)
tool.setHandler("button_press", _invert_adim_second_button_press_cb)
gtkimage.setPrompt(_('Click the second point for defining the region'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def invert_adim_init(gtkimage, tool=None):
_image = gtkimage.getImage()
_tool = _image.getTool()
_tool.setHandler("initialize", invert_adim_init)
if _image.hasSelection():
_objs = []
for _obj in _image.getSelectedObjects():
if isinstance(_obj, AngularDimension):
_objs.append()
_invert_adim(gtkimage, _objs, _tool)
else:
gtkimage.setPrompt(_('Click the AngularDimensions to be inverted'))
_tool.setHandler("button_press", _invert_adim_first_button_press_cb)
#
# arbitrary zoom
#
def zoom_end_button_press_cb(gtkimage, widget, event, tool):
_xp, _yp = gtkimage.image.getCurrentPoint()
_x1, _y1 = tool.getLocation()
_xmin = min(_xp, _x1)
_ymin = min(_yp, _y1)
_width, _height = gtkimage.getSize()
_fw = float(_width)
_fh = float(_height)
_wpp = abs(_x1 - _xp)/_fw
_hpp = abs(_y1 - _yp)/_fh
if _wpp > _hpp:
_scale = _wpp
else:
_scale = _hpp
gtkimage.setView(_xmin, _ymin, _scale)
zoom_init(gtkimage)
return True
def zoom_motion_notify(gtkimage, widget, event, tool):
_tx, _ty = tool.getLocation()
_px, _py = gtkimage.coordToPixTransform(_tx, _ty)
# width, height = gtkimage.getSize()
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
#
# it would be nice to draw the rectangle in the current
# shape of the window ...
#
if _cp is not None:
_xc, _yc = _cp
_xmin = min(_px, _xc)
_ymin = min(_py, _yc)
_rw = abs(_xc - _px)
_rh = abs(_yc - _py)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _rw, _rh)
_xmin = min(_x, _px)
_ymin = min(_y, _py)
tool.setCurrentPoint(_x, _y)
_rw = abs(_x - _px)
_rh = abs(_y - _py)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _rw, _rh)
return True
def zoom_button_press_cb(gtkimage, widget, event, tool):
_x, _y = gtkimage.image.getCurrentPoint()
tool.setLocation(_x, _y)
tool.setHandler("motion_notify", zoom_motion_notify)
tool.setHandler("button_press", zoom_end_button_press_cb)
gtkimage.setPrompt(_('Click a second point to define the zoom window'))
_gc = gtkimage.getGC()
_gc.set_line_attributes(1, gtk.gdk.LINE_SOLID,
gtk.gdk.CAP_BUTT, gtk.gdk.JOIN_MITER)
_gc.set_function(gtk.gdk.INVERT)
return True
def zoom_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the window.'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", zoom_button_press_cb)
#
# Pan Zoom
#
def zoomPan_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Press Left Mause Button To Make Pan'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", zoomPan_button_press_cb)
def zoomPan_button_press_cb(gtkimage, widget, event, tool):
gtkimage.setPrompt(_('Press Right Mause Button To Stop Pan'))
if(gtkimage.isPan()):
gtkimage.StopPanImage()
else:
gtkimage.StartPanImage()
return True
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkshell.py 0000644 0001750 0001750 00000074407 11307666657 021613 0 ustar matteo matteo #
# 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
#
#
# the GTK code for displaying a drawing
#
import types
import pygtk
pygtk.require('2.0')
import gtk
import gobject
from PythonCAD.Generic import image
from PythonCAD.Generic import layer
from PythonCAD.Generic import util
_debug = False
class LayerDisplay(object):
def __init__(self, im, win):
"""
This class defines the layer display graphic on the left side of
the window. The calling arg should be a member of the image class.
"""
if _debug is True:
print "SDB debug: instantiated another LayerDisplay class instance"
if not isinstance(im, image.Image):
raise TypeError, "Invalid Image type: " + `type(im)`
if not isinstance(win, gtk.Window):
raise TypeError, "Invalid Window type: " + `type(win)`
_sw = gtk.ScrolledWindow()
_sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
_model = gtk.TreeStore(gobject.TYPE_STRING, gobject.TYPE_PYOBJECT)
# _model.connect("rows-reordered", self.__reordered)
_iter = _model.append(None)
_layer = im.getTopLayer()
_layer.connect('visibility_changed', self.__layerVisibilityChanged)
_layer.connect('name_changed', self.__layerNameChanged)
_model.set(_iter, 0, _layer.getName())
_model.set(_iter, 1, _layer)
_tv = gtk.TreeView(_model)
_tv.set_reorderable(True) # drag-and-drop
_tv.set_search_column(0)
_tv.connect("button_press_event", self.__treeViewButtonPress)
_select = _tv.get_selection()
_select.set_mode(gtk.SELECTION_SINGLE)
_select.connect("changed", self.__selectionChanged)
_renderer = gtk.CellRendererText()
# _renderer.set_property("editable", True)
_renderer.connect("edited", self.__cellEdited)
_column = gtk.TreeViewColumn(_('Layers'), _renderer, text=0)
_tv.append_column(_column)
_sw.add(_tv)
self.__image = im
self.__window = win
self.__sw = _sw
self.__model = _model
self.__treeview = _tv
self.__layer = None
#
# establish messages connections
#
im.connect('active_layer_changed', self.__activeLayerChanged)
im.connect('added_child', self.__imageAddedChild)
im.connect('removed_child', self.__imageRemovedChild)
_layers = [im.getTopLayer()]
while len(_layers):
_layer = _layers.pop()
self.__layer = _layer
self.__model.foreach(self.__modelAddLayer)
_layer.connect('visibility_changed', self.__layerVisibilityChanged)
_layer.connect('name_changed', self.__layerNameChanged)
_layers.extend(_layer.getSublayers())
def __treeViewButtonPress(self, widget, event, data=None):
_button = event.button
_x = int(event.x)
_y = int(event.y)
_rv = event.window is widget.get_bin_window() and _button == 3
if _rv:
_menu = self.__makePopupMenu(widget, _x, _y)
if _menu is not None:
_menu.popup(None, None, None, _button, event.time)
return _rv
def __makePopupMenu(self, widget, x, y):
# print "Entered LayerDisplay._makePopupMenu"
_data = widget.get_path_at_pos(x, y)
if _data is None:
return None
_path, _col, _cx, _cy = _data
_model = widget.get_model()
_iter = _model.get_iter(_path)
_layer = _model.get_value(_iter, 1)
#
_menu = gtk.Menu()
_item = gtk.MenuItem(_('Rename'))
_item.connect("activate", self.__renameLayer)
_menu.append(_item)
if _layer.isVisible():
_item = gtk.MenuItem(_('Hide'))
_flag = False
else:
_item = gtk.MenuItem(_('Show'))
_flag = True
_item.connect("activate", self.__setLayerVisibility, _flag)
_menu.append(_item)
_item = gtk.MenuItem(_('Add Child Layer'))
_item.connect("activate", self.__addChildLayer)
_menu.append(_item)
if _layer.hasSublayers():
_item = gtk.MenuItem(_('Hide Children'))
_item.connect("activate", self.__setChildrenVisibility, False)
_menu.append(_item)
_item = gtk.MenuItem(_('Show Children'))
_item.connect("activate", self.__setChildrenVisibility, True)
_menu.append(_item)
else:
if _layer.getParentLayer() is not None:
if not _layer.hasSublayers():
_item = gtk.MenuItem(_('Delete'))
_item.connect("activate", self.__deleteLayer)
_menu.append(_item)
_item = gtk.MenuItem(_('Clear Layer'))
_item.connect("activate", self.__clearLayer)
_menu.append(_item)
_menu.show_all()
self.__layer = _layer
return _menu
def __selectionChanged(self, selection, data=None):
if selection is not None:
_model, _iter = selection.get_selected()
if _iter is not None:
_layer = _model.get_value(_iter, 1)
self.__image.setActiveLayer(_layer)
def __cellEdited(self, cell_renderer, path, text):
_model = self.__model
_iter = _model.get_iter_from_string(path)
_layer = _model.get_value(_iter, 1)
_layer.setName(text)
_model.set(_iter, 0, text)
def __reordered(self, model, path, iter, new_order):
print "in reordered()"
print "model: " + `model`
print "path: " + `path`
print "iter: " + `iter`
print "new_order: " + `new_order`
def __modelFindLayer(self, iter=None):
# print "_modelFindLayer() ..."
_model = self.__model
_iter = iter
if _iter is None:
_iter = _model.get_iter_first()
_layer = self.__layer
_path = None
_mlayer = _model.get_value(_iter, 1)
if _mlayer is _layer:
_path = _model.get_path(_iter)
else:
if _model.iter_has_child(_iter):
_child = _model.iter_children(_iter)
while _child is not None:
_path = self.__modelFindLayer(_child)
if _path is not None:
break
_child = _model.iter_next(_child)
return _path
def __modelAddLayer(self, model, path, iter):
# print "_modelAddLayer() ..."
_layer = self.__layer
_mlayer = model.get_value(iter, 1)
_val = _mlayer is _layer.getParentLayer()
if _val:
_iter = model.append(iter)
model.set(_iter, 0, _layer.getName())
model.set(_iter, 1, _layer)
return _val
def __imageAddedChild(self, obj, *args):
# print "__imageAddedChild()"
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_newlayer = args[0]
self.__layer = _newlayer
self.__model.foreach(self.__modelAddLayer)
_path = self.__modelFindLayer()
if _path is None:
raise ValueError, "Layer not found in model!"
_ppath = _path[:-1]
_tv = self.__treeview
while len(_ppath):
if not _tv.row_expanded(_ppath):
_tv.expand_row(_ppath, False)
_ppath = _ppath[:-1]
_tv.get_selection().select_path(_path)
_newlayer.connect('visibility_changed', self.__layerVisibilityChanged)
_newlayer.connect('name_changed', self.__layerNameChanged)
def __modelDeleteLayer(self, model, path, iter):
# print "_modelDeleteLayer() ..."
_mlayer = model.get_value(iter, 1)
_val = _mlayer is self.__layer
if _val:
model.remove(iter)
return _val
def __imageRemovedChild(self, obj, *args):
# print "__imageRemovedChild()"
_path = self.__modelFindLayer()
if _path is None:
raise ValueError, "Layer not found in model!"
_ppath = _path[:-1]
_tv = self.__treeview
while len(_ppath):
if not _tv.row_expanded(_ppath):
_tv.expand_row(_ppath, False)
_ppath = _ppath[:-1]
self.__model.foreach(self.__modelDeleteLayer)
self.__layer.disconnect(self)
_tv.get_selection().select_path(_path[:-1])
def __modelDisconnectLayer(self, model, path, iter):
# print "__modelDisconnnectLayer() ..."
_layer = model.get_value(iter, 1)
_layer.disconnect(self)
return False
def __activeLayerChanged(self, obj, *args):
# print "_activeLayerChanged()"
self.__layer = obj.getActiveLayer()
_path = self.__modelFindLayer()
if _path is None:
raise ValueError, "Layer not found in model!"
_ppath = _path[:-1]
_tv = self.__treeview
while len(_ppath):
if not _tv.row_expanded(_ppath):
_tv.expand_row(_ppath, False)
_ppath = _ppath[:-1]
_tv.get_selection().select_path(_path)
def __layerVisibilityChanged(self, obj, *args):
# print "_layerVisibilityChanged()"
for _obj in obj.getLayerEntities('point'):
if _obj.isVisible():
_obj.sendMessage('refresh')
_ctypes = ['hcline', 'vcline', 'acline', 'cline', 'ccircle']
for _ctype in _ctypes:
for _obj in obj.getLayerEntities(_ctype):
if _obj.isVisible():
_obj.sendMessage('refresh')
_gtypes = ['segment', 'circle', 'arc', 'leader', 'polyline',
'chamfer', 'fillet', 'textblock', 'linear_dimension',
'horizontal_dimension', 'vertical_dimension',
'radial_dimension', 'angular_dimension']
for _gtype in _gtypes:
for _obj in obj.getLayerEntities(_gtype):
if _obj.isVisible():
_obj.sendMessage('refresh')
def __modelRenameLayer(self, model, path, iter):
_layer = self.__layer
_mlayer = model.get_value(iter, 1)
_val = _mlayer is _layer
if _val:
model.set(iter, 0, _layer.getName())
return _val
def __layerNameChanged(self, obj, *args):
self.__layer = obj
self.__model.foreach(self.__modelRenameLayer)
def __setLayerVisibility(self, menuitem, data=None):
_image = self.__image
_image.startAction()
try:
self.__layer.setVisibility(data)
finally:
_image.endAction()
return False
def __setChildrenVisibility(self, menuitem, data=None):
_image = self.__image
_image.startAction()
try:
_layers = self.__layer.getSublayers()
while len(_layers):
_layer = _layers.pop()
_layer.setVisibility(data)
_layers.extend(_layer.getSublayers())
finally:
_image.endAction()
return False
def __deleteLayer(self, menuitem, data=None):
_image = self.__image
_layer = self.__layer
_image.startAction()
try:
if _layer.hasChildren():
_layer.clear()
_image.delLayer(_layer)
_layer.finish()
finally:
_image.endAction()
self.__layer = None
return False
def __clearLayer(self, menuitem, data=None):
_image = self.__image
_image.startAction()
try:
self.__layer.clear()
finally:
_image.endAction()
return False
def __addChildLayer(self, menuitem, data=None):
if _debug is True:
print "SDB Debug: entered LayerDisplay.addChildLayer()..."
_window = self.__window
_dialog = gtk.Dialog(_('Add New Child Layer'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Name:'))
_hbox.pack_start(_label, False, False, 0)
_entry = gtk.Entry()
_entry.set_text(_('NewChildLayer'))
_hbox.pack_start(_entry, True, True, 0)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_name = _entry.get_text()
if len(_name):
_new_layer = layer.Layer(_name)
_image = self.__image
_image.startAction()
try:
_image.addChildLayer(_new_layer, self.__layer)
finally:
_image.endAction()
_dialog.destroy()
return False
def __renameLayer(self, menuitem, data=None):
if _debug is True:
print "SDB debug: entered _renameLayer()"
_layer = self.__layer
_name = _layer.getName()
_window = self.__window
_dialog = gtk.Dialog(_('Rename Layer'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Name:'))
_hbox.pack_start(_label, False, False, 0)
_entry = gtk.Entry()
_entry.set_text(_name)
_hbox.pack_start(_entry, True, True, 0)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_new_name = _entry.get_text()
if len(_new_name):
_image = self.__image
_image.startAction()
try:
_layer.setName(_new_name)
finally:
_image.endAction()
_dialog.destroy()
return False
def close(self):
self.__model.foreach(self.__modelDisconnectLayer)
self.__image.disconnect(self)
self.__image = None
self.__window = None
self.__sw = None
self.__model = None
self.__treeview = None
self.__layer = None
def getWindow(self):
return self.__sw
class ImageView(object):
def __init__(self, im, xmin=0.0, ymax=0.0, upp=1.0):
if _debug is True:
print "SDB debug: Created new ImageView class instance"
if not isinstance(im, image.Image):
raise TypeError, "Invalid Image type: " + `type(im)`
_xmin = util.get_float(xmin)
_ymax = util.get_float(ymax)
_upp = util.get_float(upp)
if not _upp > 0.0:
raise ValueError, "Invalid units-per-pixel value: %g" % _upp
self.__image = im
self.__pixmap = None
self.__gc = None
self.__width = None
self.__height = None
_da = gtk.DrawingArea()
_da.set_size_request(100, 100)
_black = gtk.gdk.color_parse('black')
_da.modify_fg(gtk.STATE_NORMAL, _black)
_da.modify_bg(gtk.STATE_NORMAL, _black)
_da.set_flags(gtk.CAN_FOCUS)
_da.connect("expose_event", self.__exposeEvent)
_da.connect("realize", self.__realizeEvent)
_da.connect("configure_event", self.__configureEvent)
_da.connect("key_press_event", self.__keyPressEvent)
_da.connect("key_release_event", self.__keyPressEvent)
_da.connect("enter_notify_event", self.__elNotifyEvent)
_da.connect("leave_notify_event", self.__elNotifyEvent)
_da.connect("focus_in_event", self.__focusChangedEvent)
_da.connect("focus_out_event", self.__focusChangedEvent)
_da.set_events(gtk.gdk.EXPOSURE_MASK |
gtk.gdk.LEAVE_NOTIFY_MASK |
gtk.gdk.BUTTON_PRESS_MASK |
gtk.gdk.BUTTON_RELEASE_MASK |
gtk.gdk.ENTER_NOTIFY_MASK|
gtk.gdk.LEAVE_NOTIFY_MASK|
gtk.gdk.KEY_PRESS_MASK |
gtk.gdk.KEY_RELEASE_MASK |
gtk.gdk.FOCUS_CHANGE_MASK |
gtk.gdk.POINTER_MOTION_MASK)
self.__da = _da
self.__xmin = _xmin
self.__ymax = _ymax
self.__upp = _upp
self.__view = None
im.connect('added_child', self.__imageAddedChild)
im.connect('removed_child', self.__imageRemovedChild)
im.connect('modified', self.__objModified)
def __realizeEvent(self, widget, data=None):
_win = widget.window
_w, _h = _win.get_size()
self.__width = _w
self.__height = _h
_gc = _win.new_gc()
_gc.set_exposures(True)
self.__gc = _gc
def __exposeEvent(self, widget, event, data=None):
_pixmap = self.__pixmap
_x, _y, _w, _h = event.area
_gc = widget.get_style().fg_gc[gtk.STATE_NORMAL]
widget.window.draw_drawable(_gc, _pixmap, _x, _y, _x, _y, _w, _h)
return True
def __configureEvent(self, widget, event, data=None):
_win = widget.window
_w, _h = _win.get_size()
if self.__width != _w or self.__height != _h:
self.__view = None
self.__width = _w
self.__height = _h
_pixmap = gtk.gdk.Pixmap(_win, _w, _h)
_gc = widget.get_style().fg_gc[gtk.STATE_NORMAL]
_pixmap.draw_rectangle(_gc, True, 0, 0, _w, _h)
self.__pixmap = _pixmap
return True
def __focusChangedEvent(self, widget, event, data=None):
return False
def __buttonPressEvent(self, widget, event, data=None):
_rv = False
_tool = gtkimage.getTool()
gtkimage.setToolpoint(event)
if (event.button == 1 and
_tool is not None and
_tool.hasHandler('button_press')):
_rv = _tool.getHandler('button_press')(gtkimage, widget,
event, _tool)
return _rv
def __buttonReleaseEvent(self, widget, event, data=None):
_rv = False
_tool = gtkimage.getTool()
gtkimage.setToolpoint(event)
if (event.button == 1 and
_tool is not None and
_tool.hasHandler('button_release')):
_rv = _tool.getHandler('button_release')(gtkimage, widget,
event, _tool)
return _rv
def __keyPressEvent(self, widget, event, data=None):
_key = event.keyval
_rv = (_key == gtk.keysyms.Left or
_key == gtk.keysyms.Right or
_key == gtk.keysyms.Up or
_key == gtk.keysyms.Down)
if _rv:
_mods = event.state & gtk.accelerator_get_default_mod_mask()
_dx = _dy = None
if (_key == gtk.keysyms.Left):
_dx = -1.0
elif (_key == gtk.keysyms.Right):
_dx = 1.0
elif (_key == gtk.keysyms.Up):
_dy = 1.0
elif (_key == gtk.keysyms.Down):
_dy = -1.0
else:
raise ValueError, "Unexpected keyval: %d" % _key
if (_mods == gtk.gdk.CONTROL_MASK):
_scale = 0.25
elif (_mods == gtk.gdk.SHIFT_MASK):
_scale = 0.5
elif (_mods == gtk.gdk.CONTROL_MASK | gtk.gdk.SHIFT_MASK):
_scale = 1.0
else:
_scale = 0.05
if not _rv:
_tool = gtkimage.getTool()
if _tool is not None and _tool.hasHandler('key_press'):
_rv = _tool.getHandler('key_press')(gtkimage, widget,
event, _tool)
return _rv
def __keyReleaseEvent(self, widget, event, data=None):
_rv = False
_tool = gtkimage.getTool()
if _tool is not None and _tool.hasHandler('key_release'):
_rv = _tool.getHandler('key_release')(gtkimage, widget,
event, _tool)
return _rv
def __motionNotifyEvent(self, widget, event, data=None):
_rv = False
_tool = gtkimage.getTool()
gtkimage.setToolpoint(event)
if _tool is not None and _tool.hasHandler('motion_notify'):
_rv = _tool.getHandler('motion_notify')(gtkimage, widget,
event, _tool)
return _rv
def __elNotifyEvent(self, widget, event, data=None):
gtkimage.setToolpoint(event)
return True
def __drawObject(self, obj, col=None):
_col = col
_xmin, _ymin, _xmax, _ymax = self.getView()
if obj.inRegion(_xmin, _ymin, _xmax, _ymax):
_image = self.__image
if _col is None:
if obj.getParent() is not _image.getActiveLayer():
_col = _image.getOption('INACTIVE_LAYER_COLOR')
obj.draw(self, _col)
def __imageAddedChild(self, obj, *args):
# print "_imageAddedChild()"
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_layer = args[0]
if not isinstance(_layer, layer.Layer):
raise TypeError, "Unexpected child type: " + `type(_layer)`
_layer.connect('added_child', self.__layerAddedChild)
_layer.connect('removed_child', self.__layerRemovedChild)
def __layerAddedChild(self, obj, *args):
# print "__layerAddedChild()"
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_child = args[0] # need some verification test here ...
_child.connect('modified', self.__objModified)
_child.connect('visibility_changed', self.__objVisibilityChanged)
_child.connect('refresh', self.__refreshObject)
_child.connect('change_pending', self.__objChanging)
if _child.isVisible() and obj.isVisible():
self.__drawObject(_child)
def __imageRemovedChild(self, obj, *args):
# print "__imageRemovedChild()"
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_layer = args[0]
if not isinstance(_layer, layer.Layer):
raise TypeError, "Unexpected child type: " + `type(_layer)`
_layer.disconnect(self)
def __layerRemovedChild(self, obj, *args):
# print "__layerDeletedChild()"
_alen = len(args)
if _alen < 1:
raise ValueError, "Invalid argument count: %d" % _alen
_child = args[0] # need some verification test here ...
if _child.isVisible() and obj.isVisible():
_color = self.__image.getOption('BACKGROUND_COLOR')
self.__drawObject(_child, _color)
_child.disconnect(self)
def __objModified(self, obj, *args):
# print "__objModified()"
if obj.isVisible() and obj.getParent().isVisible():
self.__drawObject(obj)
def __objChanging(self, obj, *args):
# print "__objChanging()"
if obj.isVisible() and obj.getParent().isVisible():
self.__drawObject(obj, self.__image.getOption('BACKGROUND_COLOR'))
def __objVisibilityChanged(self, obj, *args):
# print "__objVisibilityChanged()"
if obj.getParent().isVisible():
_col = None
if not obj.isVisible():
_col = self.__image.getOption('BACKGROUND_COLOR')
self.__drawObject(obj, _col)
def __refreshObject(self, obj, *args):
# print "__refreshObject()"
_col = None
if not obj.isVisible() or not obj.getParent().isVisible():
_col = self.__image.getOption('BACKGROUND_COLOR')
self.__drawObject(obj, _col)
def getView(self):
"""Get the region of space the ImageView draws
getRegion()
This method returns a tuple of four values: xmin, ymin, xmax, ymax
"""
if self.__view is None:
_xmin = self.__xmin
_ymax = self.__ymax
_upp = self.__upp
_w = self.__width
_h = self.__height
_xmax = _xmin + (_upp * _w)
_ymin = _ymax - (_upp * _h)
self.__view = (_xmin, _ymin, _xmax, _ymax)
return self.__view
def getPixmap(self):
"""Return the gtk.gdk.Pixmap for this ImageView.
getPixmap()
"""
return self.__pixmap
def getUnitsPerPixel(self):
"""Return the units-per-pixel scaling factor for the ImageView.
getUnitsPerPixel()
"""
return self.__upp
def setUnitsPerPixel(self, upp):
"""Set the units-per-pixel scaling factor for the ImageView.
setUnitsPerPixel(upp)
Argument 'upp' should be a float value greater
"""
_upp = util.get_float(upp)
if not _upp > 0.0:
raise ValueError, "Invalid units-per-pixel value: %g" % _upp
self.__upp = _upp
self.__view = None
def pixelsToCoords(self, x, y):
"""Convert from pixel coordinates to x-y coordinates.
pixelsToCoords(x, y)
Arguments 'x' and 'y' should be positive integers. This method
returns a tuple of two float values
"""
if not isinstance(x, int):
raise TypeError, "Invalid 'x' type: " + `type(x)`
if x < 0:
raise ValueError, "Invalid 'x' value: %d" % x
if not isinstance(y, int):
raise TypeError, "Invalid 'y' type: " + `type(y)`
if y < 0:
raise ValueError, "Invalid 'y' value: %d" % y
_upp = self.__upp
_xc = self.__xmin + (x * _upp)
_yc = self.__ymax - (y * _upp)
return _xc, _yc
def coordsToPixels(self, x, y):
"""Convert from x-y coordinates to pixel coordinates
coordsToPixels(x, y)
Arguments 'x' and 'y' should be float values. This method
returns a tuple holding two integer values
"""
_x = util.get_float(x)
_y = util.get_float(y)
_upp = self.__upp
_xp = int((x - self.__xmin)/_upp)
_yp = int((self.__ymax - y)/_upp)
return _xp, _yp
def close(self):
self.__image.disconnect(self)
def redraw(self):
"""This method draws all the objects visible in the ImageView.
redraw()
"""
_da = self.__da
if (_da.flags() & gtk.MAPPED):
_image = self.__image
_w = self.__width
_h = self.__height
_gc = _da.get_style().fg_gc[gtk.STATE_NORMAL]
self.__pixmap.draw_rectangle(_gc, True, 0, 0, _w, _h)
_active = _image.getActiveLayer()
_layers = [_image.getTopLayer()]
while (len(_layers)):
_layer = _layers.pop()
if _layer is not _active:
self.drawLayer(_layer)
_layers.extend(_layer.getSublayers())
self.drawLayer(_active)
_da.queue_draw() # generate an expose event
def drawLayer(self, l):
if not isinstance(l, layer.Layer):
raise TypeError, "Invalid layer type: " + `type(l)`
if l.getParent() is not self.__image:
raise ValueError, "Layer not found in Image"
if l.isVisible():
_xmin = self.__xmin
_ymax = self.__ymax
_upp = self.__upp
_xmax = _xmin + (_upp * _w)
_ymin = _ymax - (_upp * _h)
_col = self.getOption('INACTIVE_LAYER_COLOR')
if l is self.getActiveLayer():
_col = None
_cobjs = []
_objs = []
_pts = []
for _obj in l.objsInRegion(_xmin, _ymin, _xmax, _ymax):
if _obj.isVisible():
if isinstance(_obj, Point):
_pts.append(_obj)
elif isinstance(_obj, ConstructionObject):
_cobjs.append(_obj)
else:
_objs.append(_obj)
for _obj in _cobjs:
_obj.draw(self, _col)
for _obj in _pts:
_obj.draw(self, _col)
for _obj in _objs:
_obj.draw(self, _col)
class ImageWindow(object):
def __init__(self, im):
if _debug is True:
print "SDB debug: instantiated another ImageWindow class instance"
if not isinstance(im, image.Image):
raise TypeError, "Invalid Image type: " + `type(im)`
self.__image = im
#
# Display window
#
_window = gtk.Window()
_window.set_title("Untitled")
_window.connect("destroy", self._closeImage)
_width = min(1024, int(0.8 * float(gtk.gdk.screen_width())))
_height = min(768, int(0.8 * float(gtk.gdk.screen_height())))
_window.set_default_size(_width, _height)
#
_vbox = gtk.VBox(False, 2)
_vbox.set_border_width(2)
_window.add(_vbox)
self.__ldisp = LayerDisplay(im)
def getImage(self):
"""Return the Image stored in the ImageDisplay.
getImage()
"""
return self.__image
image = property(getImage, None, None, "The Image used for visualizing.")
def closeImage(self, widget):
"""Close a window containing a Image.
closeImage()
"""
_image = self.__image
_image.close()
_image.disconnect(self)
self.__ldisp(close)
for _i in xrange(len(globals.imagelist)):
_gimage = globals.imagelist[_i]
if _image is _gimage:
del globals.imagelist[_i]
_gimage.window.destroy()
if not len(globals.imagelist):
gtk.main_quit()
break
return False
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkstyleprefs.py 0000644 0001750 0001750 00000050670 11307666657 022700 0 ustar matteo matteo #
# Copyright (c) 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., 51 Franklin Stree, Fifth Floor, Boston, MA 02110-1301,
# USA
#
#
# code for displaying Style values
#
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import sys
from PythonCAD.Generic import style
from PythonCAD.Generic import linetype
from PythonCAD.Generic import color
from PythonCAD.Generic import image
class GtkStyle(object):
"""
"""
def __init__(self, window, gs=None):
if not isinstance(window, gtk.Window):
raise TypeError, "Invalid window type: " + `type(window)`
self.__window = window
self.__widgets = {}
self.__styles = []
self.__linetypes = []
self.__style = None
if gs is not None:
self.setStyle(gs)
def addStyle(self, s):
"""Store a Style in the GtkStyle
addStyle(s)
Argument 's' must be a Style instance.
"""
if not isinstance(s, style.Style):
raise TypeError, "Invalid Style: " + `type(s)`
self.__styles.append(s)
def addLinetype(self, l):
"""
"""
if not isinstance(l, linetype.Linetype):
raise TypeError, "Invalid Linetype: " + `type(l)`
self.__linetypes.append(l)
def getStyles(self):
"""Return the list of stored Styles.
getStyles()
This method returns a list of Style instances stored
with the addStyle() method.
"""
return self.__styles
def getLinetypes(self):
"""Return the list of stored Linetypes
getLinetypes()
This method returns a list of Linetype instances stored
with the addLinetype() method.
"""
return self.__linetypes
def setStyle(self, s):
"""Set the Style defining the various widget values.
setTextStyle(ts)
Argument 's' must be a Style instance.
"""
if not isinstance(s, style.Style):
raise TypeError, "Invalid Style: " + `type(s)`
self.__style = s
self.setValues()
def getStyle(self):
"""Get the Style used to define the widget values.
getStyle()
This method returns a Style instance or None if no Style
has been stored in the GtkStyle instance.
"""
return self.__style
def __selectColor(button, s=None):
_s = s
if _s is None:
_s = _('Select Color')
_da = button.get_child().get_child()
_color = _da.get_style().bg[gtk.STATE_NORMAL]
_dialog = gtk.ColorSelectionDialog(_s)
_colorsel = _dialog.colorsel
_colorsel.set_previous_color(_color)
_colorsel.set_current_color(_color)
_colorsel.set_has_palette(True)
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_r, _g, _b = _get_rgb_values(_colorsel.get_current_color())
_str = "#%02x%02x%02x" % (_r, _g, _b)
_da.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(_str))
_dialog.destroy()
__selectColor = staticmethod(__selectColor)
def __moveCursor(entry):
entry.set_position(-1)
return False
__moveCursor = staticmethod(__moveCursor)
def __entryActivate(entry):
_text = entry.get_text()
entry.delete_text(0, -1)
if len(_text):
if _text == '-' or _text == '+':
sys.stderr.write("Incomplete value: '%s'\n" % _text)
else:
try:
_value = float(_text)
except:
sys.stderr.write("Invalid float: '%s'\n" % _text)
else:
sys.stderr.write("Empty entry box.")
__entryActivate = staticmethod(__entryActivate)
def __entryFocusOut(entry, event, text=''):
_text = entry.get_text()
if _text == '' or _text == '+':
_thickness = entry.get_data('thickness')
_hid = entry.get_data('handlerid')
entry.delete_text(0, -1)
entry.handler_block(_hid)
try:
entry.set_text(_thickness)
finally:
entry.handler_unblock(_hid)
return False
__entryFocusOut = staticmethod(__entryFocusOut)
def __entryInsertText(entry, new_text, new_text_length, position):
if (new_text.isdigit() or
new_text == '.' or
new_text == '+'):
_string = entry.get_text() + new_text[:new_text_length]
_hid = entry.get_data('handlerid')
_move = True
entry.handler_block(_hid)
try:
_pos = entry.get_position()
if _string == '+':
_pos = entry.insert_text(new_text, _pos)
else:
try:
_val = float(_string)
except StandardError, e:
_move = False
else:
_pos = entry.insert_text(new_text, _pos)
finally:
entry.handler_unblock(_hid)
if _move:
if hasattr(gobject, 'idle_add'):
gobject.idle_add(GtkStyle.__moveCursor, entry)
else:
gtk.idle_add(GtkStyle.__moveCursor, entry)
entry.stop_emission("insert-text")
__entryInsertText = staticmethod(__entryInsertText)
def __getColorDA(widgets, key, val, s=None):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.Button()
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_frame.set_border_width(5)
_widget.add(_frame)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_widget.connect('clicked', GtkStyle.__selectColor, s)
_frame.add(_da)
else:
_da = _widget.get_child().get_child()
_da.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(str(val)))
return _widget
__getColorDA = staticmethod(__getColorDA)
def __getColorButton(widgets, key, val, s):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.ColorButton()
_widget.set_title(s)
_widget.set_color(gtk.gdk.color_parse(str(val)))
return _widget
__getColorButton = staticmethod(__getColorButton)
def __getOptionMenu(widgets, key, val, entries):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.OptionMenu()
_menu = gtk.Menu()
else:
_menu = _widget.getMenu()
for _child in _menu.get_children():
_menu.remove(_child)
_idx = 0
for _i in range(len(entries)):
_name, _val = entries[_i]
if _val == val:
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget.set_menu(_menu)
_widget.set_history(_idx)
return _widget
__getOptionMenu = staticmethod(__getOptionMenu)
def __getComboBox(widgets, key, val, entries):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.combo_box_new_text()
else:
_model = _widget.get_model()
if _model is not None:
while len(_model):
_widget.remove_text(0)
_idx = 0
for _i in range(len(entries)):
_val = entries[_i]
if _val == val:
_idx = _i
_widget.append_text(_val)
_widget.set_active(_idx)
return _widget
__getComboBox = staticmethod(__getComboBox)
def setValues(self):
"""Store the TextStyle values in the interface widgets.
setValues()
"""
_s = self.__style
if _s is None:
raise RuntimeError, "No Style defined for the GtkStyle instance."
_widgets = self.__widgets
#
_key = 'LINE_TYPE'
_widget = _widgets.get(_key)
_lt = _s.getLinetype()
_ltname = _lt.getName()
_lts = self.__linetypes
if hasattr(gtk, 'ComboBox'):
if _widget is None:
_widget = gtk.combo_box_new_text()
else:
_model = _widget.get_model()
if _model is not None:
while len(_model):
_widget.remove_text(0)
_idx = 0
for _i in range(len(_lts)):
_val = _lts[_i]
_vname = _val.getName()
if _vname == _ltname:
_idx = _i
_widget.append_text(_vname)
_widget.set_active(_idx)
else:
if _widget is None:
_widget = gtk.OptionMenu()
_menu = gtk.Menu()
else:
_menu = _widget.getMenu()
for _child in _menu.get_children():
_menu.remove(_child)
_idx = 0
for _i in range(len(_lts)):
_val = _lts[_i]
_vname = _val.getName()
if _vname == _ltname:
_idx = _i
_item = gtk.MenuItem(_vname)
_menu.append(_item)
_widget.set_menu(_menu)
_widget.set_history(_idx)
if _key not in _widgets:
_widgets[_key] = _widget
#
_val = _s.getColor()
_str = _('Select Color')
if hasattr(gtk, 'ColorButton'):
_sm = GtkStyle.__getColorButton
else:
_sm = GtkStyle.__getColorDA
_key = 'LINE_COLOR'
_widget = _sm(_widgets, _key, _val, _str)
if _key not in _widgets:
_widgets[_key] = _widget
#
_key = 'LINE_THICKNESS'
_entry = _widgets.setdefault(_key, gtk.Entry())
_val = _s.getThickness()
_size = "%f" % _val
_entry.set_data('thickness', _val)
_hid = _entry.get_data('handlerid')
if _hid is not None:
_entry.handler_block(_hid)
try:
_entry.set_text(_size)
finally:
_entry.handler_unblock(_hid)
else:
_entry.set_text(_size)
_handlerid = _entry.connect('insert-text',
GtkStyle.__entryInsertText)
_entry.set_data('handlerid', _handlerid)
_entry.connect('activate', GtkStyle.__entryActivate)
_entry.connect('focus-out-event',
GtkStyle.__entryFocusOut)
if _key not in _widgets:
_widgets[_key] = _entry
def __getRGBValues(color):
if not isinstance(color, gtk.gdk.Color):
raise TypeError, "Unexpected color type: " + `type(color)`
_r = int(round((color.red/65535.0) * 255.0))
_g = int(round((color.green/65535.0) * 255.0))
_b = int(round((color.blue/65535.0) * 255.0))
return _r, _g, _b
__getRGBValues = staticmethod(__getRGBValues)
def setImageSettings(self, im):
"""Store the Image settings of various Style values.
setImageSettings(im)
Argument 'im' must be and Image instance.
"""
if not isinstance(im, image.Image):
raise TypeError, "Invalid Image type: " + `type(im)`
_widgets = self.__widgets
#
_key = 'LINE_TYPE'
_widget = _widgets.get(_key)
_lt = im.getOption(_key)
_ltname = _lt.getName()
_lts = self.__linetypes
if hasattr(gtk, 'ComboBox'):
if _widget is None:
_widget = gtk.combo_box_new_text()
else:
_model = _widget.get_model()
if _model is not None:
while len(_model):
_widget.remove_text(0)
_idx = 0
for _i in range(len(_lts)):
_val = _lts[_i]
_vname = _val.getName()
if _vname == _ltname:
_idx = _i
_widget.append_text(_vname)
_widget.set_active(_idx)
else:
if _widget is None:
_widget = gtk.OptionMenu()
_menu = gtk.Menu()
else:
_menu = _widget.getMenu()
for _child in _menu.get_children():
_menu.remove(_child)
_idx = 0
for _i in range(len(_lts)):
_val = _lts[_i]
_vname = _val.getName()
if _vname == _ltname:
_idx = _i
_item = gtk.MenuItem(_vname)
_menu.append(_item)
_widget.set_menu(_menu)
_widget.set_history(_idx)
if _key not in _widgets:
_widgets[_key] = _widget
#
_key = 'LINE_COLOR'
_val = im.getOption(_key)
_str = _('Select Color')
if hasattr(gtk, 'ColorButton'):
_sm = GtkStyle.__getColorButton
else:
_sm = GtkStyle.__getColorDA
_widget = _sm(_widgets, _key, _val, _str)
if _key not in _widgets:
_widgets[_key] = _widget
#
_key = 'LINE_THICKNESS'
_entry = _widgets.setdefault(_key, gtk.Entry())
_val = im.getOption(_key)
_size = "%f" % _val
_entry.set_data('thickness', _val)
_hid = _entry.get_data('handlerid')
if _hid is not None:
_entry.handler_block(_hid)
try:
_entry.set_text(_size)
finally:
_entry.handler_unblock(_hid)
else:
_entry.set_text(_size)
_handlerid = _entry.connect('insert-text',
GtkStyle.__entryInsertText)
_entry.set_data('handlerid', _handlerid)
_entry.connect('activate', GtkStyle.__entryActivate)
_entry.connect('focus-out-event',
GtkStyle.__entryFocusOut)
if _key not in _widgets:
_widgets[_key] = _entry
def getValues(self):
"""Return the values stored in the widgets
getValues()
This method returns a list of tuples in the form (key, value),
where 'key' is the Style option and 'value' is the option value.
"""
_s = self.__style
if _s is None:
raise RuntimeError, "No Style defined for the GtkStyle instance."
_values = []
_widgets = self.__widgets
#
_key = 'LINE_TYPE'
_widget = _widgets[_key]
if hasattr(gtk, 'ComboBox'):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
_values.append((_key, self.__linetypes[_idx]))
#
_key = 'LINE_COLOR'
_widget = _widgets[_key]
if hasattr(gtk, 'ColorButton'):
_color = _widget.get_color()
elif isinstance(_widget, gtk.Button):
_da = _widget.getChild().getChild()
_color= _da.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
_values.append((_key, GtkStyle.__getRGBValues(_color)))
_key = 'LINE_THICKNESS'
_widget = _widgets[_key]
_text = _widget.get_text()
if len(_text) and _text != '+':
_value = float(_text)
else:
_value = _s.getThickness()
_values.append((_key, _value))
return _values
def getWidget(self, key):
"""Return a widget associated with a Style option.
getWidget(key)
Argument 'key' must be a valid Style option key. This method
returns a widget or None.
"""
if (key != 'LINE_TYPE' and
key != 'LINE_COLOR' and
key != 'LINE_THICKNESS'):
return ValueError, "Invalid Style key: " + key
return self.__widgets.get(key)
def clear(self):
"""Clear out all values and widgets in the GtkStyle.
clear()
"""
self.__window = None
self.__widgets.clear()
del self.__styles[:]
del self.__linetypes[:]
self.__style = None
def _widget_changed(widget, gs):
if hasattr(gtk, 'ComboBox'):
_idx = widget.get_active()
else:
_idx = widget.get_history()
_styles = gs.getStyles()
gs.setStyle(_styles[_idx])
def _fill_dialog(dvbox, gs):
_lsg = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Graphic Properties'))
_frame.set_border_width(2)
_vbox = gtk.VBox(False, 2)
_vbox.set_border_width(2)
_frame.add(_vbox)
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, False, False, 2)
_label = gtk.Label(_('Linetype:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = gs.getWidget('LINE_TYPE')
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, True, True, 2)
_label = gtk.Label(_('Color:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = gs.getWidget('LINE_COLOR')
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, False, False, 2)
_label = gtk.Label(_('Thickness:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = gs.getWidget('LINE_THICKNESS')
_hbox.pack_start(_widget, False, False, 2)
#
dvbox.pack_start(_frame, False, False, 2)
def style_dialog(gtkimage, styles, linetypes):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Style Settings'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_image = gtkimage.getImage()
_st = _image.getOption('LINE_STYLE')
_hbox = gtk.HBox(False, 5)
_hbox.set_border_width(5)
_label = gtk.Label(_('Active Style:'))
_hbox.pack_start(_label, False, False, 5)
_idx = 0
if hasattr(gtk, 'ComboBox'):
_widget = gtk.combo_box_new_text()
for _i in range(len(styles)):
_style = styles[_i]
if (_st is _style or
_st == _style):
_idx = _i
_widget.append_text(_style.getName())
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(styles)):
_style = styles[_i]
if (_st is _style or
_st == _style):
_idx = _i
_item = gtk.MenuItem(_style.getName())
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_widget, False, False, 0)
_dialog.vbox.pack_start(_hbox, True, True)
#
_gs = GtkStyle(_window)
for _style in styles:
_gs.addStyle(_style)
for _lt in linetypes:
_gs.addLinetype(_lt)
_gs.setStyle(_st)
_gs.setImageSettings(_image)
_fill_dialog(_dialog.vbox, _gs)
_widget.connect('changed', _widget_changed, _gs)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_nst = _gs.getStyle()
if _nst != _st:
_image.setOption('LINE_STYLE', _nst)
for _opt, _val in _gs.getValues():
if _opt == 'LINE_TYPE':
if _val != _image.getOption(_opt):
_image.setOption(_opt, _val)
elif _opt == 'LINE_COLOR':
if _val != _image.getOption(_opt).getColors():
_r, _g, _b = _val
_image.setOption(_opt, color.Color(_r, _g, _b))
elif _opt == 'LINE_THICKNESS':
if abs(_val - _image.getOption(_opt)) > 1e-10:
_image.setOption(_opt, _val)
else:
raise RuntimeError, "Unexpected TextStyle option '%s'" % _opt
_gs.clear()
_dialog.destroy()
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkactions.py 0000644 0001750 0001750 00000045164 11307666657 022142 0 ustar matteo matteo #
# Copyright (c) 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
#
#
# GTK Menu building code
#
# In GTK 2.4 the Action and ActionGroup classes were added to simplify,
# and enhance the UI code of GTK. Earlier releases had the ItemFactory
# or just raw MenuBar, MenuItem, and Menu widgets. The code in
# this file is meant to provide some functionality found in the gtk.Action
# and gtk.ActionGroup classes so that PythonCAD can still run on PyGTK
# releases prior to the support of the GTK Action and ActionGroup classes
#
#
import pygtk
pygtk.require('2.0')
import gtk
import gobject
class stdActionGroup(gobject.GObject):
__gproperties__ = {
'name' : (gobject.TYPE_STRING, 'Name', 'Name',
'', gobject.PARAM_READWRITE),
'sensitive' : (gobject.TYPE_BOOLEAN, 'Sensitive',
'Sensitivity', True, gobject.PARAM_READWRITE),
'visible' : (gobject.TYPE_BOOLEAN, 'Visible',
'Visibility', True, gobject.PARAM_READWRITE),
}
__gsignals__ = {
'connect-proxy' : (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
(gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
'disconnect-proxy' : (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
(gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT)),
'post-activate' : (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
(gobject.TYPE_PYOBJECT,)),
'pre-activate' : (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
(gobject.TYPE_PYOBJECT,))
}
def __init__(self, name):
gobject.GObject.__init__(self)
self.name = name
self.__actions = {}
self.sensitive = True
self.visible = True
def get_name(self):
return self.name
def get_sensitive(self):
return self.sensitive
def set_sensitive(self, sensitive):
_s = self.sensitive
if _s is not sensitive:
self.sensitive = sensitive
def get_visible(self):
return self.visible
def set_visible(self, visible):
_v = self.visible
if _v is not visible:
self.visible = visible
def get_action(self, action):
return self.__actions.get(action)
def list_actions(self):
return self.__actions.values()
def add_action(self, action):
_name = action.get_name()
action.set_property('action-group', self)
self.__actions[_name] = action
def add_action_with_accel(self, action, accel):
# print "add_action_with_accel"
_keyval = None
_mods = None
_name = action.get_name()
_path = "/".join(['', self.name, _name])
if accel is None:
# print "accel is None"
_sid = action.get_property('stock-id')
if _sid != '':
# print "sid = '%s'" % _sid
_data = gtk.stock_lookup(_sid)
if _data is not None and _data[3] != 0:
# print "data: " + str(_data)
_mods = _data[2]
_keyval = _data[3]
else:
_k, _m = gtk.accelerator_parse(accel)
if gtk.accelerator_valid(_k, _m):
_keyval = _k
_mods = _m
if _keyval is not None:
# print "calling gtk.accel_map_change_entry()"
# print "Path: " + _path
# print "Key: " + str(_keyval)
# print "Mods: " + str(_mods)
if not gtk.accel_map_change_entry(_path, _keyval, _mods, True):
print "Failed to change accel_map for '%s'" % _path
action.set_accel_path(_path)
self.add_action(action)
def remove_action(self, action):
_name = action.get_name()
del self.__actions[_name]
action.set_property('action-group', None)
def do_get_property(self, property):
if property.name == 'name':
_val = self.name
elif property.name == 'sensitive':
_val = self.sensitive
elif property.name == 'visible':
_val = self.visible
else:
raise AttributeError, "Unknown property '%s'" % property
return _val
def do_set_property(self, property, value):
if property.name == 'name':
raise AttributeError, "Property 'name' cannot be changed."
elif property.name == 'sensitive':
self.set_sensitive(value)
elif property.name == 'visible':
self.set_visible(value)
else:
raise AttributeError, "Unknown property '%s'" % property
if not hasattr(gtk, 'ActionGroup'):
gobject.type_register(stdActionGroup)
class stdAction(gobject.GObject):
__gproperties__ = {
'action_group' : (gobject.TYPE_PYOBJECT, 'Action Group',
'Action Group', gobject.PARAM_READWRITE),
'hide_if_empty' : (gobject.TYPE_BOOLEAN, 'Hide', 'Hide',
True, gobject.PARAM_READWRITE),
'is_important' : (gobject.TYPE_BOOLEAN, 'Importance', 'Importance',
False, gobject.PARAM_READWRITE),
'label' : (gobject.TYPE_STRING, 'Label', 'Label',
'', gobject.PARAM_READWRITE),
'name' : (gobject.TYPE_STRING, 'Name', 'Name',
'', gobject.PARAM_READWRITE),
'sensitive' : (gobject.TYPE_BOOLEAN, 'Sensitive',
'Sensitivity', True, gobject.PARAM_READWRITE),
'short_label' : (gobject.TYPE_STRING, 'Short Label', 'Short Label',
'', gobject.PARAM_READWRITE),
'stock_id' : (gobject.TYPE_STRING, 'Stock ID', 'Stock ID',
'', gobject.PARAM_READWRITE),
'tooltip' : (gobject.TYPE_STRING, 'Tooltip', 'Tooltip',
'', gobject.PARAM_READWRITE),
'visible' : (gobject.TYPE_BOOLEAN, 'Visible',
'Visibility', True, gobject.PARAM_READWRITE),
'visible_horizontal' : (gobject.TYPE_BOOLEAN,
'Visible Horizontal', 'Visible Horizontal',
True, gobject.PARAM_READWRITE),
'visible_overflown' : (gobject.TYPE_BOOLEAN,
'Visible Overflown', 'Visible Overflown',
True, gobject.PARAM_READWRITE),
'visible_vertical' : (gobject.TYPE_BOOLEAN,
'Visible Vertical', 'Visible Vertical',
True, gobject.PARAM_READWRITE)
}
__gsignals__ = {
'activate' : (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE,
())
}
def __init__(self, name, label, tooltip, stock_id):
gobject.GObject.__init__(self)
self.name = name
self.label = label
self.tooltip = ''
if tooltip is not None:
self.tooltip = tooltip
self.stock_id = ''
if stock_id is not None:
self.stock_id = stock_id
self.action_group = None
self.hide_if_empty = False
self.is_important = True
self.sensitive = True
self.short_label = None
self.visible = True
self.visible_horizontal = True
self.visible_overflown = True
self.visible_vertical = True
self.__lset = False # lab
self.__slset = False
self.__accelpath = None
self.__accelgroup = None
self.__accelcount = 0
self.__proxies = []
self.__hids = {}
def get_name(self):
return self.name
def is_sensitive(self):
return self.sensitive and (self.action_group is None or
self.action_group.get_sensitive())
def get_sensitive(self):
return self.sensitive
def set_sensitive(self, sensitive):
_s = self.sensitive
if _s is not sensitive:
self.sensitive = sensitive
self.notify('sensitive')
def is_visible(self):
return self.visible and (self.action_group is None or
self.action_group.get_visible())
def get_visible(self):
return self.visible
def set_visible(self, visible):
_v = self.visible
if _v is not visible:
self.visible = visible
self.notify('visible')
def activate(self):
# print "stdAction::activate()"
if self.is_sensitive():
_group = self.action_group
if _group is not None:
_group.emit('pre-activate', self)
self.emit('activate')
if _group is not None:
_group.emit('post-activate', self)
def create_icon(self, size):
_icon = None
if self.stock_id != '':
_icon = gtk.image_new_from_stock(self.stock_id, size)
return _icon
def create_menu_item(self):
_item = gtk.ImageMenuItem()
self.connect_proxy(_item)
return _item
def create_tool_item(self):
return None
def connect_proxy(self, widget):
_pact = widget.get_data('gtk-action')
if _pact is not None:
_pact.disconnect_proxy(widget)
_hids = self.__hids.setdefault(id(widget),[])
widget.set_data('gtk-action', self)
self.__proxies.insert(0, widget)
_hid = widget.connect('destroy', self._remove_proxy)
_hids.append(_hid)
_hid = self.connect_object('notify::sensitive',
self._sync_sensitivity,
widget)
_hids.append(_hid)
widget.set_sensitive(self.is_sensitive())
_hid = self.connect_object('notify::visible',
self._sync_visibility,
widget)
_hids.append(_hid)
if self.is_visible():
widget.show()
else:
widget.hide()
if hasattr(widget, 'set_no_show_all'):
widget.set_no_show_all(True)
if isinstance(widget, gtk.MenuItem):
if self.__accelpath is not None:
self.connect_accelerator()
widget.set_accel_path(self.__accelpath)
_label = widget.child
if _label is None:
_label = gtk.AccelLabel('')
_label.set_property('use_underline', True)
_label.set_property('xalign', 0.0)
_label.set_property('visible', True)
_label.set_property('parent', widget)
_label.set_accel_widget(widget)
_label.set_label(self.label)
_hid = self.connect_object('notify::label',
self._sync_label,
widget)
_hids.append(_hid)
if isinstance(widget, gtk.ImageMenuItem):
_image = widget.get_image()
if _image is not None and not isinstance(_image, gtk.Image):
widget.set_image(None)
_image = None
if _image is None:
_image = gtk.image_new_from_stock(self.stock_id,
gtk.ICON_SIZE_MENU)
widget.set_image(_image)
_image.show()
_image.set_from_stock(self.stock_id, gtk.ICON_SIZE_MENU)
_hid = self.connect_object('notify::stock-id',
self._sync_stock_id,
widget)
_hids.append(_hid)
if widget.get_submenu() is None:
_hid = widget.connect_object('activate',
stdAction.activate,
self)
_hids.append(_hid)
else:
raise TypeError, "Unexpected proxy widget type: " + `type(widget)`
if self.action_group is not None:
self.action_group.emit('connect-proxy', self, widget)
def disconnect_proxy(self, widget):
if widget.get_data('gtk-action') is not self:
raise ValueError, "Action not being proxied by widget: " + `widget`
widget.set_data('gtk-action', None)
_hids = self.__hids.get(id(widget))
if _hids is not None:
for _hid in _hids:
if self.handler_is_connected(_hid):
self.disconnect(_hid)
continue
if widget.handler_is_connected(_hid):
widget.disconnect(_hid)
if self.action_group is not None:
self.action_group.emit('disconnect-proxy', self, widget)
def get_proxies(self):
return self.__proxies[:]
def _accel_cb(self, accelgroup, acceleratable, keyval, mod):
# print "_accel_cb()"
pass
def connect_accelerator(self):
# print "connect_accelerator()"
if self.__accelgroup is not None and self.__accelpath is not None:
_count = self.__accelcount
if _count == 0:
# print "calling accelgroup.connect_by_path()"
# print "accelpath: " + self.__accelpath
if hasattr(self.__accelgroup, 'connect_by_path'):
self.__accelgroup.connect_by_path(self.__accelpath,
self._accel_cb)
_count = _count + 1
def disconnect_accelerator(self):
# print "disconnect_accelerator()"
if self.__accelgroup is not None and self.__accelpath is not None:
_count = self.__accelcount
_count = _count - 1
if _count > 0:
self.__accelgroup.disconnect(self._accel_cb)
def block_activate_from(self, widget):
pass
def unblock_activate_from(self, widget):
pass
def get_accel_path(self):
return self.__accelpath
def set_accel_path(self, path):
self.__accelpath = path
def set_accel_group(self, group):
self.__accelgroup = group
def do_get_property(self, property):
if property.name == 'name':
_val = self.name
elif property.name == 'label':
_val = self.label
elif property.name == 'tooltip':
_val = self.tooltip
elif property.name == 'stock-id':
_val = self.stock_id
elif property.name == 'action-group':
_val = self.action_group
elif property.name == 'hide-if-empty':
_val = self.hide_if_empty
elif property.name == 'is-important':
_val = self.is_important
elif property.name == 'sensitive':
_val = self.sensitive
elif property.name == 'short-label':
_val = self.short_label
elif property.name == 'visible':
_val = self.visible
elif property.name == 'visible-horizontal':
_val = self.visible_horizontal
elif property.name == 'visible-overflown':
_val = self.visible_overflown
elif property.name == 'visible-vertical':
_val = self.visible_vertical
else:
raise AttributeError, "Unknown property '%s'" % property
return _val
def do_set_property(self, property, value):
if property.name == 'name':
raise AttributeError, "Property 'name' cannot be changed."
elif property.name == 'label':
self.label = value
self.__lset = self.label != ''
if not self.__lset and self.stock_id != '':
_item = gtk.stock_lookup(self.stock_id)
if _item is not None:
self.label = _item[2]
if not self.__slset:
self.short_label = self.label
self.notify('short-label')
elif property.name == 'tooltip':
self.tooltip = value
elif property.name == 'stock-id':
self.stock_id = value
if not self.__lset:
_item = gtk.stock_lookup(self.stock_id)
if _item is not None:
self.label = _item[2]
else:
self.label = ''
self.notify('label')
if not self.__slset:
self.short_label = self.label
self.notify('short-label')
elif property.name == 'action-group':
self.action_group = value
elif property.name == 'hide-if-empty':
self.hide_if_empty = value
elif property.name == 'is-important':
self.is_important = value
elif property.name == 'sensitive':
self.set_sensitive(value)
elif property.name == 'short-label':
self.short_label = value
self.__slset = self.short_label != ''
if not self.__slset:
self.__slset = self.label
elif property.name == 'visible':
self.set_visible(value)
elif property.name == 'visible-horizontal':
self.visible_horizontal = value
elif property.name == 'visible-overflow':
self.visible_overflown = value
elif property.name == 'visible-vertical':
self.visible_vertical = value
else:
raise AttributeError, "Unknown property '%s'" % property
def do_activate(self):
#print "do_activate()"
pass
def _remove_proxy(self, widget):
for _p in self.__proxies[:]:
if _p is widget:
self.__proxies.remove(_p)
break
def _sync_sensitivity(self, widget, data=None):
widget.set_sensitive(self.is_sensitive())
def _sync_visibility(self, widget, data=None):
widget.set_visible(self.is_visible())
def _sync_label(self, widget, data=None):
_label = widget.child
if _label is not None and isinstance(_label, gtk.Label):
_label.set_label(self.label)
def _sync_stock_id(self, widget, data=None):
_image = widget.get_image()
if isinstance(_image, gtk.Image):
_image.set_from_stock(self.stock_id, gtk.ICON_SIZE_MENU)
if not hasattr(gtk, 'Action'):
gobject.type_register(stdAction)
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkdimprefs.py 0000644 0001750 0001750 00000152337 11307666657 022314 0 ustar matteo matteo #
# Copyright (c) 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., 51 Franklin Stree, Fifth Floor, Boston, MA 02110-1301,
# USA
#
#
# code for displaying DimStyle values
#
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import sys
from PythonCAD.Generic import color
from PythonCAD.Generic import units
from PythonCAD.Generic import text
from PythonCAD.Generic import dimension
from PythonCAD.Generic import image
class GtkDimStyle(object):
"""
"""
__keys = dimension.DimStyle.getDimStyleOptions()
__font_styles = text.TextStyle.getStyleStrings()
__font_weights = text.TextStyle.getWeightStrings()
__text_align = text.TextStyle.getAlignmentStrings()
__dim_positions = dimension.Dimension.getPositionStrings()
__dim_endpoints = dimension.Dimension.getEndpointTypeStrings()
__units = units.Unit.getUnitStrings()
__families = None
def __init__(self, window, ds=None):
if not isinstance(window, gtk.Window):
raise TypeError, "Invalid window type: " + `type(window)`
self.__window = window
self.__widgets = {}
self.__notebook = gtk.Notebook()
self.__dimstyles = []
self.__ds = None
if ds is not None:
self.setimStyle(ds)
def getNotebook(self):
"""Get the gtk.Notebook widget in the GtkDimStyle.
getNotebook()
"""
return self.__notebook
notebook = property(getNotebook, None, None, "gtk.Notebook widget")
def addDimStyle(self, ds):
"""Store a DimStyle in the GtkDimStyle
addDimStyle(ds)
Argument 'ds' must be a DimStyle instance.
"""
if not isinstance(ds, dimension.DimStyle):
raise TypeError, "Invalid DimStyle: " + `type(ds)`
self.__dimstyles.append(ds)
def getDimStyles(self):
"""Return the list of stored DimStyles
getDimStyles()
This method returns a list of DimStyle instances stored
with the addDimStyle() method.
"""
return self.__dimstyles
def setDimStyle(self, ds):
"""Set the DimStyle defining the various widget values.
setDimStyle(ds)
Argument 'ds' must be a DimStyle instance.
"""
if not isinstance(ds, dimension.DimStyle):
raise TypeError, "Invalid DimStyle: " + `type(ds)`
self.__ds = ds
for _key in GtkDimStyle.__keys:
self.setValues(_key)
if self.__notebook.get_current_page() == -1:
self.__initNotebook()
def getDimStyle(self):
"""Get the DimStyle used to define the widget values.
getDimStyle()
This method returns a DimStyle instance or None if no DimStyle
has been stored in the GtkDimStyle instance.
"""
return self.__ds
def __getCheckButton(widgets, key, s):
return widgets.setdefault(key, gtk.CheckButton(s))
__getCheckButton = staticmethod(__getCheckButton)
def __selectColor(button, s=None):
_s = s
if _s is None:
_s = _('Select Color')
_da = button.get_child().get_child()
_color = _da.get_style().bg[gtk.STATE_NORMAL]
_dialog = gtk.ColorSelectionDialog(_s)
_colorsel = _dialog.colorsel
_colorsel.set_previous_color(_color)
_colorsel.set_current_color(_color)
_colorsel.set_has_palette(True)
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_r, _g, _b = _get_rgb_values(_colorsel.get_current_color())
_str = "#%02x%02x%02x" % (_r, _g, _b)
_color = gtk.gdk.color_parse(_str)
_da.modify_bg(gtk.STATE_NORMAL, _color)
_dialog.destroy()
__selectColor = staticmethod(__selectColor)
def __moveCursor(entry):
entry.set_position(-1)
return False
__moveCursor = staticmethod(__moveCursor)
def __entryActivate(entry):
_text = entry.get_text()
entry.delete_text(0, -1)
if len(_text):
if _text == '-' or _text == '+':
sys.stderr.write("Incomplete value: '%s'\n" % _text)
else:
try:
_value = float(_text)
except:
sys.stderr.write("Invalid float: '%s'\n" % _text)
else:
sys.stderr.write("Empty entry box.")
__entryActivate = staticmethod(__entryActivate)
def __entryFocusOut(entry, event, text=''):
_text = entry.get_text()
if _text == '' or _text == '+':
_length = entry.get_data('length')
_hid = entry.get_data('handlerid')
entry.delete_text(0, -1)
entry.handler_block(_hid)
try:
entry.set_text(_length)
finally:
entry.handler_unblock(_hid)
return False
__entryFocusOut = staticmethod(__entryFocusOut)
def __entryInsertText(entry, new_text, new_text_length, position):
if (new_text.isdigit() or
new_text == '.' or
new_text == '+'):
_string = entry.get_text() + new_text[:new_text_length]
_hid = entry.get_data('handlerid')
_move = True
entry.handler_block(_hid)
try:
_pos = entry.get_position()
if _string == '+':
_pos = entry.insert_text(new_text, _pos)
else:
try:
_val = float(_string)
except StandardError, e:
_move = False
else:
_pos = entry.insert_text(new_text, _pos)
finally:
entry.handler_unblock(_hid)
if _move:
if hasattr(gobject, 'idle_add'):
gobject.idle_add(GtkDimStyle.__moveCursor, entry)
else:
gtk.idle_add(GtkDimStyle.__moveCursor, entry)
entry.stop_emission("insert-text")
__entryInsertText = staticmethod(__entryInsertText)
def __getColorDA(widgets, key, val, s=None):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.Button()
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_frame.set_border_width(5)
_widget.add(_frame)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_widget.connect('clicked', GtkDimStyle.__selectColor, s)
_frame.add(_da)
else:
_da = _widget.get_child().get_child()
_da.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(str(val)))
return _widget
__getColorDA = staticmethod(__getColorDA)
def __getColorButton(widgets, key, val, s):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.ColorButton()
_widget.set_title(s)
_widget.set_color(gtk.gdk.color_parse(str(val)))
return _widget
__getColorButton = staticmethod(__getColorButton)
def __getOptionMenu(widgets, key, val, entries):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.OptionMenu()
_menu = gtk.Menu()
else:
_menu = _widget.getMenu()
for _child in _menu.get_children():
_menu.remove(_child)
_idx = 0
for _i in range(len(entries)):
_val = entries[_i]
if _val == val:
_idx = _i
_item = gtk.MenuItem(_name)
_menu.append(_item)
_widget.set_menu(_menu)
_widget.set_history(_idx)
return _widget
__getOptionMenu = staticmethod(__getOptionMenu)
def __getComboBox(widgets, key, val, entries):
_widget = widgets.get(key)
if _widget is None:
_widget = gtk.combo_box_new_text()
else:
_model = _widget.get_model()
if _model is not None:
while len(_model):
_widget.remove_text(0)
_idx = 0
for _i in range(len(entries)):
_val = entries[_i]
if _val == val:
_idx = _i
_widget.append_text(_val)
_widget.set_active(_idx)
return _widget
__getComboBox = staticmethod(__getComboBox)
def __toggleSecondaryOpts(checkbox, widgets):
_state = checkbox.get_active()
for _key in GtkDimStyle.__keys:
if (_key.startswith('DIM_SECONDARY') or
_key.startswith('RADIAL_DIM_SECONDARY') or
_key.startswith('ANGULAR_DIM_SECONDARY')):
_widget = widgets.get(_key)
if _widget is not None:
_widget.set_sensitive(_state)
__toggleSecondaryOpts = staticmethod(__toggleSecondaryOpts)
def setValues(self, key):
"""Store the DimStyle values in the interface widgets.
setValues(key)
"""
_ds = self.__ds
if _ds is None:
raise RuntimeError, "No DimStyle defined for the GtkDimStyle instance."
_widgets = self.__widgets
if (key == 'DIM_PRIMARY_FONT_FAMILY' or
key == 'DIM_SECONDARY_FONT_FAMILY'):
if GtkDimStyle.__families is None:
_families = []
_window = self.__window
for _family in _window.get_pango_context().list_families():
_families.append(_family.get_name())
_families.sort()
GtkDimStyle.__families = _families
_val = _ds.getValue(key)
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_widget = _sm(_widgets, key, _val, GtkDimStyle.__families)
if key not in _widgets:
_widgets[key] = _widget
elif (key == 'DIM_PRIMARY_FONT_STYLE' or
key == 'DIM_SECONDARY_FONT_STYLE'):
_val = _ds.getValue(key)
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_widget = _sm(_widgets, key, _val, GtkDimStyle.__font_styles)
if key not in _widgets:
_widgets[key] = _widget
elif (key == 'DIM_PRIMARY_FONT_WEIGHT' or
key == 'DIM_SECONDARY_FONT_WEIGHT'):
_val = _ds.getValue(key)
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_widget = _sm(_widgets, key, _val, GtkDimStyle.__font_weights)
if key not in _widgets:
_widgets[key] = _widget
elif key == 'DIM_PRIMARY_FONT_COLOR':
_color = _ds.getValue(key)
_s = _('Select Primary Dimension Font Color')
if hasattr(gtk, 'ColorButton'):
_sm = GtkDimStyle.__getColorButton
else:
_sm = GtkDimStyle.__getColorDA
_widget = _sm(_widgets, key, _color, _s)
if key not in _widgets:
_widgets[key] = _widget
elif key == 'DIM_SECONDARY_FONT_COLOR':
_color = _ds.getValue(key)
_s = _('Select Secondary Dimension Font Color')
if hasattr(gtk, 'ColorButton'):
_sm = GtkDimStyle.__getColorButton
else:
_sm = GtkDimStyle.__getColorDA
_widget = _sm(_widgets, key, _color, _s)
if key not in _widgets:
_widgets[key] = _widget
elif (key == 'DIM_PRIMARY_TEXT_ANGLE' or
key == 'DIM_SECONDARY_TEXT_ANGLE'):
pass
elif (key == 'DIM_PRIMARY_TEXT_ALIGNMENT' or
key == 'DIM_SECONDARY_TEXT_ALIGNMENT'):
_val = _ds.getValue(key)
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_widget = _sm(_widgets, key, _val, GtkDimStyle.__text_align)
if key not in _widgets:
_widgets[key] = _widget
elif (key == 'DIM_PRIMARY_PREFIX' or
key == 'DIM_SECONDARY_PREFIX' or
key == 'DIM_PRIMARY_SUFFIX' or
key == 'DIM_SECONDARY_SUFFIX' or
key == 'RADIAL_DIM_PRIMARY_PREFIX' or
key == 'RADIAL_DIM_SECONDARY_PREFIX' or
key == 'RADIAL_DIM_PRIMARY_SUFFIX' or
key == 'RADIAL_DIM_SECONDARY_SUFFIX' or
key == 'ANGULAR_DIM_PRIMARY_PREFIX' or
key == 'ANGULAR_DIM_SECONDARY_PREFIX' or
key == 'ANGULAR_DIM_PRIMARY_SUFFIX' or
key == 'ANGULAR_DIM_SECONDARY_SUFFIX'):
_entry = _widgets.setdefault(key, gtk.Entry())
_entry.set_text(_ds.getValue(key))
if key not in _widgets:
_widgets[key] = _entry
elif (key == 'DIM_PRIMARY_PRECISION' or
key == 'DIM_SECONDARY_PRECISION'):
_widget = _widgets.get(key)
_val = _ds.getValue(key)
if _widget is None:
_adj = gtk.Adjustment(_val, 0, 15, 1, 1, 1)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(0)
_sb.set_numeric(True)
_widgets[key] = _sb
else:
_widget.set_value(_val)
elif (key == 'DIM_PRIMARY_UNITS' or
key == 'DIM_SECONDARY_UNITS'):
_val = _ds.getValue(key)
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_widget = _sm(_widgets, key, _val, GtkDimStyle.__units)
if key not in _widgets:
_widgets[key] = _widget
elif (key == 'DIM_PRIMARY_LEADING_ZERO' or
key == 'DIM_SECONDARY_LEADING_ZERO'):
_str = _('Print leading 0')
_cb = GtkDimStyle.__getCheckButton(_widgets, key, _str)
_cb.set_active(_ds.getValue(key))
if key not in _widgets:
_widgets[key] = _cb
elif (key == 'DIM_PRIMARY_TRAILING_DECIMAL' or
key == 'DIM_SECONDARY_TRAILING_DECIMAL'):
_str = _('Print trailing decimal point')
_cb = GtkDimStyle.__getCheckButton(_widgets, key, _str)
_cb.set_active(_ds.getValue(key))
if key not in _widgets:
_widgets[key] = _cb
elif (key == 'DIM_OFFSET' or
key == 'DIM_EXTENSION' or
key == 'DIM_ENDPOINT_SIZE' or
key == 'DIM_THICKNESS' or
key == 'DIM_PRIMARY_TEXT_SIZE' or
key == 'DIM_SECONDARY_TEXT_SIZE'):
_entry = _widgets.setdefault(key, gtk.Entry())
_length = "%f" % _ds.getValue(key)
_entry.set_data('length', _length)
_hid = _entry.get_data('handlerid')
if _hid is not None:
_entry.handler_block(_hid)
try:
_entry.set_text(_length)
finally:
_entry.handler_unblock(_hid)
else:
_entry.set_text(_length)
_handlerid = _entry.connect("insert-text",
GtkDimStyle.__entryInsertText)
_entry.set_data('handlerid', _handlerid)
_entry.connect("activate", GtkDimStyle.__entryActivate)
_entry.connect("focus-out-event",
GtkDimStyle.__entryFocusOut)
if key not in _widgets:
_widgets[key] = _entry
elif (key == 'DIM_COLOR'):
_color = _ds.getValue(key)
_s = _('Select Dimension Color')
if hasattr(gtk, 'ColorButton'):
_sm = GtkDimStyle.__getColorButton
else:
_sm = GtkDimStyle.__getColorDA
_widget = _sm(_widgets, key, _color, _s)
if key not in _widgets:
_widgets[key] = _widget
elif (key == 'DIM_POSITION'):
_val = _ds.getValue(key)
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_widget = _sm(_widgets, key, _val, GtkDimStyle.__dim_positions)
if key not in _widgets:
_widgets[key] = _widget
elif (key == 'DIM_ENDPOINT'):
_val = _ds.getValue(key)
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_widget = _sm(_widgets, key, _val, GtkDimStyle.__dim_endpoints)
if key not in _widgets:
_widgets[key] = _widget
elif (key == 'DIM_DUAL_MODE'):
_str = _('Display secondary dimension text')
_cb = GtkDimStyle.__getCheckButton(_widgets, key, _str)
_cb.set_active(_ds.getValue(key))
# _cb.connect('toggled', GtkDimStyle.__toggleSecondaryOpts, _widgets)
if key not in _widgets:
_widgets[key] = _cb
elif (key == 'DIM_POSITION_OFFSET'):
pass
elif (key == 'DIM_DUAL_MODE_OFFSET'):
pass
elif (key == 'RADIAL_DIM_DIA_MODE'):
_str = _('Show diameterical dimension value')
_cb = GtkDimStyle.__getCheckButton(_widgets, key, _str)
_cb.set_active(_ds.getValue(key))
if key not in _widgets:
_widgets[key] = _cb
else:
raise ValueError, "Unexpected key: " + key
def __getRGBValues(color):
if not isinstance(color, gtk.gdk.Color):
raise TypeError, "Unexpected color type: " + `type(color)`
_r = int(round((color.red/65535.0) * 255.0))
_g = int(round((color.green/65535.0) * 255.0))
_b = int(round((color.blue/65535.0) * 255.0))
return _r, _g, _b
__getRGBValues = staticmethod(__getRGBValues)
def getValues(self):
"""Return the values stored in the widgets
getValues()
This method returns a list of tuples in the form (key, value),
where 'key' is the DimStyle option and 'value' is the option value.
"""
_ds = self.__ds
if _ds is None:
raise RuntimeError, "No DimStyle defined for the GtkDimStyle instance."
_values = []
_widgets = self.__widgets
for _key in GtkDimStyle.__keys:
_widget = _widgets.get(_key)
if _widget is None:
continue
if (_key == 'DIM_PRIMARY_FONT_FAMILY' or
_key == 'DIM_SECONDARY_FONT_FAMILY'):
if hasattr(gtk, 'ComboBox'):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
_value = GtkDimStyle.__families[_idx]
elif (_key == 'DIM_PRIMARY_FONT_STYLE' or
_key == 'DIM_SECONDARY_FONT_STYLE' or
_key == 'DIM_PRIMARY_FONT_WEIGHT' or
_key == 'DIM_SECONDARY_FONT_WEIGHT' or
_key == 'DIM_PRIMARY_TEXT_ALIGNMENT' or
_key == 'DIM_SECONDARY_TEXT_ALIGNMENT' or
_key == 'DIM_PRIMARY_UNITS' or
_key == 'DIM_SECONDARY_UNITS' or
_key == 'DIM_POSITION' or
_key == 'DIM_ENDPOINT'):
if hasattr(gtk, 'ComboBox'):
_value = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_value = _widget.get_history()
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
elif (_key == 'DIM_PRIMARY_FONT_COLOR' or
_key == 'DIM_SECONDARY_FONT_COLOR' or
_key == 'DIM_COLOR'):
if hasattr(gtk, 'ColorButton'):
_color = _widget.get_color()
elif isinstance(_widget, gtk.Button):
_da = _widget.getChild().getChild()
_color= _da.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
_value = GtkDimStyle.__getRGBValues(_color)
elif (_key == 'DIM_PRIMARY_TEXT_ANGLE' or
_key == 'DIM_SECONDARY_TEXT_ANGLE'):
pass
elif (_key == 'DIM_PRIMARY_PREFIX' or
_key == 'DIM_SECONDARY_PREFIX' or
_key == 'DIM_PRIMARY_SUFFIX' or
_key == 'DIM_SECONDARY_SUFFIX' or
_key == 'RADIAL_DIM_PRIMARY_PREFIX' or
_key == 'RADIAL_DIM_SECONDARY_PREFIX' or
_key == 'RADIAL_DIM_PRIMARY_SUFFIX' or
_key == 'RADIAL_DIM_SECONDARY_SUFFIX' or
_key == 'ANGULAR_DIM_PRIMARY_PREFIX' or
_key == 'ANGULAR_DIM_SECONDARY_PREFIX' or
_key == 'ANGULAR_DIM_PRIMARY_SUFFIX' or
_key == 'ANGULAR_DIM_SECONDARY_SUFFIX'):
_value = _widget.get_text()
elif (_key == 'DIM_PRIMARY_PRECISION' or
_key == 'DIM_SECONDARY_PRECISION'):
_value = _widget.get_value_as_int()
elif (_key == 'DIM_PRIMARY_LEADING_ZERO' or
_key == 'DIM_SECONDARY_LEADING_ZERO' or
_key == 'DIM_PRIMARY_TRAILING_DECIMAL' or
_key == 'DIM_SECONDARY_TRAILING_DECIMAL' or
_key == 'DIM_DUAL_MODE' or
_key == 'RADIAL_DIM_DIA_MODE'):
_value = _widget.get_active()
elif (_key == 'DIM_OFFSET' or
_key == 'DIM_EXTENSION' or
_key == 'DIM_ENDPOINT_SIZE' or
_key == 'DIM_THICKNESS' or
_key == 'DIM_PRIMARY_TEXT_SIZE' or
_key == 'DIM_SECONDARY_TEXT_SIZE'):
_text = _widget.get_text()
if len(_text) and _text != '+':
_value = float(_text)
else:
_value = self.__ds.getOption(_key)
elif (key == 'DIM_POSITION_OFFSET'):
pass
elif (key == 'DIM_DUAL_MODE_OFFSET'):
pass
else:
raise ValueError, "Unexpected key: " + key
_values.append((_key, _value))
return _values
def getWidget(self, key):
"""Return a widget associated with a DimStyle option.
getWidget(key)
Argument 'key' must be a valid DimStyle option key. This method
returns a widget or None.
"""
if key not in GtkDimStyle.__keys:
return ValueError, "Invalid DimStyle key: " + key
return self.__widgets.get(key)
def __generalPage(self):
"""Populate the 'General' Notebook page
__generalPage()
This method is private to the GtkDimStyle class.
"""
_widgets = self.__widgets
_vbox = gtk.VBox(False, 2)
_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Dimension Bar Options'))
_table = gtk.Table(4, 2, False)
_table.set_border_width(2)
_table.set_row_spacings(2)
_table.set_col_spacings(2)
_frame.add(_table)
_label = gtk.Label(_('Offset length:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_widget = _widgets.get('DIM_OFFSET')
_size_group.add_widget(_widget)
_table.attach(_widget, 1, 2, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_label = gtk.Label(_('Extension length:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
_widget = _widgets.get('DIM_EXTENSION')
_size_group.add_widget(_widget)
_table.attach(_widget, 1, 2, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_hbox = gtk.HBox(False, 2)
_label = gtk.Label(_('Dimension bar color:'))
_hbox.pack_start(_label, False, False, 2)
_widget = _widgets.get('DIM_COLOR')
_hbox.pack_start(_widget, False, False, 2)
_table.attach(_hbox, 0, 2, 2, 3,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_hbox = gtk.HBox(False, 2)
_label = gtk.Label(_('Dimension bar thickness:'))
_hbox.pack_start(_label, False, False, 2)
_widget = _widgets.get('DIM_THICKNESS')
_hbox.pack_start(_widget, False, False, 2)
_table.attach(_hbox, 0, 2, 3, 4,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 2)
#
# options for dimension text position
#
_frame = gtk.Frame(_('Dimension Text Position'))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_frame.add(_hbox)
_label = gtk.Label(_('Text Location at crossbar:'))
_hbox.pack_start(_label, False, False, 2)
_widget = _widgets.get('DIM_POSITION')
_hbox.pack_start(_widget, False, False, 0)
_vbox.pack_start(_frame, False, False, 2)
#
# options for dimension crossbar/crossarc markers
#
_frame = gtk.Frame(_('Dimension Crossbar Markers'))
_table = gtk.Table(2, 2, False)
_table.set_border_width(2)
_table.set_row_spacings(2)
_table.set_col_spacings(2)
_frame.add(_table)
_label = gtk.Label(_('Dimension marker:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.FILL,
gtk.FILL,
2, 2)
_widget = _widgets.get('DIM_ENDPOINT')
_table.attach(_widget, 1, 2, 0, 1,
gtk.FILL,
gtk.FILL,
2, 2)
_label = gtk.Label(_('Marker size:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.FILL,
gtk.FILL,
2, 2)
_widget = _widgets.get('DIM_ENDPOINT_SIZE')
_size_group.add_widget(_widget)
_table.attach(_widget, 1, 2, 1, 2,
gtk.FILL,
gtk.FILL,
2, 2)
_vbox.pack_start(_frame, False, False, 2)
#
_widget = _widgets.get('DIM_DUAL_MODE')
_vbox.pack_start(_widget, False, False, 2)
self.__notebook.append_page(_vbox, gtk.Label(_('General')))
def __psPage(self, pds=True):
"""Populate the Primary/Secondary DimString pages
psPage([pds])
This method is private to the GtkDimString class.
"""
_widgets = self.__widgets
_vbox = gtk.VBox(False, 2)
_frame = gtk.Frame(_('Units'))
_frame.set_border_width(2)
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_frame.add(_hbox)
_label = gtk.Label(_('Dimension units:'))
_hbox.pack_start(_label, False, False, 2)
if pds:
_key = 'DIM_PRIMARY_UNITS'
else:
_key = 'DIM_SECONDARY_UNITS'
_widget = _widgets.get(_key)
_hbox.pack_start(_widget, False, False, 2)
_vbox.pack_start(_frame, False, False, 2)
#
_label_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_menu_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
#
_frame = gtk.Frame(_('Font Properties'))
_frame.set_border_width(2)
_fvbox = gtk.VBox(False, 2)
_fvbox.set_border_width(2)
_frame.add(_fvbox)
_fhbox = gtk.HBox(False, 2)
_fhbox.set_border_width(2)
_fvbox.pack_start(_fhbox, False, False, 2)
_label = gtk.Label(_('Family:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 2)
if pds:
_key = 'DIM_PRIMARY_FONT_FAMILY'
else:
_key = 'DIM_SECONDARY_FONT_FAMILY'
_widget = _widgets.get(_key)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 2)
#
_fhbox = gtk.HBox(False, 2)
_fhbox.set_border_width(2)
_fvbox.pack_start(_fhbox, False, False, 2)
_label = gtk.Label(_('Style:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 2)
if pds:
_key = 'DIM_PRIMARY_FONT_STYLE'
else:
_key = 'DIM_SECONDARY_FONT_STYLE'
_widget = _widgets.get(_key)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 2)
#
_fhbox = gtk.HBox(False, 2)
_fhbox.set_border_width(2)
_fvbox.pack_start(_fhbox, False, False, 2)
_label = gtk.Label(_('Weight:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 2)
if pds:
_key = 'DIM_PRIMARY_FONT_WEIGHT'
else:
_key = 'DIM_SECONDARY_FONT_WEIGHT'
_widget = _widgets.get(_key)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 2)
#
_fhbox = gtk.HBox(False, 2)
_fhbox.set_border_width(2)
_fvbox.pack_start(_fhbox, False, False, 2)
_label = gtk.Label(_('Alignment:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 2)
if pds:
_key = 'DIM_PRIMARY_TEXT_ALIGNMENT'
else:
_key = 'DIM_SECONDARY_TEXT_ALIGNMENT'
_widget = _widgets.get(_key)
_menu_size_group.add_widget(_widget)
_fhbox.pack_start(_widget, False, False, 2)
#
_fhbox = gtk.HBox(False, 2)
_fhbox.set_border_width(2)
_fvbox.pack_start(_fhbox, False, False, 2)
_label = gtk.Label(_('Size:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 2)
if pds:
_key = 'DIM_PRIMARY_TEXT_SIZE'
else:
_key = 'DIM_SECONDARY_TEXT_SIZE'
_widget = _widgets.get(_key)
_fhbox.pack_start(_widget, False, False, 2)
#
_fhbox = gtk.HBox(False, 2)
_fhbox.set_border_width(2)
_fvbox.pack_start(_fhbox, True, True, 2)
_label = gtk.Label(_('Color:'))
_label_size_group.add_widget(_label)
_fhbox.pack_start(_label, False, False, 2)
if pds:
_key = 'DIM_PRIMARY_FONT_COLOR'
else:
_key = 'DIM_SECONDARY_FONT_COLOR'
_widget = _widgets.get(_key)
_fhbox.pack_start(_widget, False, False, 2)
_vbox.pack_start(_frame, False, False, 2)
#
_frame = gtk.Frame(_('Format Options'))
_frame.set_border_width(2)
_table = gtk.Table(3, 1, False)
_table.set_border_width(2)
_table.set_row_spacings(2)
_table.set_col_spacings(2)
_frame.add(_table)
if pds:
_key = 'DIM_PRIMARY_LEADING_ZERO'
else:
_key = 'DIM_SECONDARY_LEADING_ZERO'
_widget = _widgets.get(_key)
_table.attach(_widget, 0, 1, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
if pds:
_key = 'DIM_PRIMARY_TRAILING_DECIMAL'
else:
_key = 'DIM_SECONDARY_TRAILING_DECIMAL'
_widget = _widgets.get(_key)
_table.attach(_widget, 0, 1, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
#
_thbox = gtk.HBox(False, 2)
_label = gtk.Label(_('Display precision:'))
_thbox.pack_start(_label, False, False, 2)
if pds:
_key = 'DIM_PRIMARY_PRECISION'
else:
_key = 'DIM_SECONDARY_PRECISION'
_widget = _widgets.get(_key)
_thbox.pack_start(_widget, False, False, 2)
_table.attach(_thbox, 0, 1, 2, 3,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 2)
if pds:
_label = gtk.Label(_('Primary'))
else:
_label = gtk.Label(_('Secondary'))
self.__notebook.append_page(_vbox, _label)
def __dimPage(self, dstr):
"""Populate the Linear/Radial/Angular dimension pages
__dimPage(dstr)
This method is private to the GtkDimStyle class
"""
if (dstr != 'linear' and
dstr != 'radial' and
dstr != 'angular'):
raise ValueError, "Unexpected argument: " + dstr
_widgets = self.__widgets
_vbox = gtk.VBox(False, 5)
_size_group = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Primary Dimension Text Options'))
_table = gtk.Table(2, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
_label = gtk.Label(_('Default prefix:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
if dstr == 'linear':
_key = 'DIM_PRIMARY_PREFIX'
elif dstr == 'radial':
_key = 'RADIAL_DIM_PRIMARY_PREFIX'
else:
_key = 'ANGULAR_DIM_PRIMARY_PREFIX'
_widget = _widgets.get(_key)
_size_group.add_widget(_widget)
_table.attach(_widget, 1, 2, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_label = gtk.Label(_('Default suffix:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
if dstr == 'linear':
_key = 'DIM_PRIMARY_SUFFIX'
elif dstr == 'radial':
_key = 'RADIAL_DIM_PRIMARY_SUFFIX'
else:
_key = 'ANGULAR_DIM_PRIMARY_SUFFIX'
_widget = _widgets.get(_key)
_size_group.add_widget(_widget)
_table.attach(_widget, 1, 2, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
#
_frame = gtk.Frame(_('Secondary Dimension Text Options'))
_table = gtk.Table(2, 2, False)
_table.set_border_width(5)
_table.set_row_spacings(5)
_table.set_col_spacings(5)
_frame.add(_table)
_label = gtk.Label(_('Default prefix:'))
_table.attach(_label, 0, 1, 0, 1,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
if dstr == 'linear':
_key = 'DIM_SECONDARY_PREFIX'
elif dstr == 'radial':
_key = 'RADIAL_DIM_SECONDARY_PREFIX'
else:
_key = 'ANGULAR_DIM_SECONDARY_PREFIX'
_widget = _widgets.get(_key)
_size_group.add_widget(_widget)
_table.attach(_widget, 1, 2, 0, 1,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_label = gtk.Label(_('Default suffix:'))
_table.attach(_label, 0, 1, 1, 2,
gtk.EXPAND,
gtk.EXPAND,
2, 2)
if dstr == 'linear':
_key = 'DIM_SECONDARY_SUFFIX'
elif dstr == 'radial':
_key = 'RADIAL_DIM_SECONDARY_SUFFIX'
else:
_key = 'ANGULAR_DIM_SECONDARY_SUFFIX'
_widget = _widgets.get(_key)
_size_group.add_widget(_widget)
_table.attach(_widget, 1, 2, 1, 2,
gtk.FILL | gtk.EXPAND,
gtk.FILL | gtk.EXPAND,
2, 2)
_vbox.pack_start(_frame, False, False, 5)
if dstr == 'radial':
_widget = _widgets.get('RADIAL_DIM_DIA_MODE')
_vbox.pack_start(_widget, False, False, 5)
if dstr == 'linear':
_label = gtk.Label(_('Linear'))
elif dstr == 'radial':
_label = gtk.Label(_('Radial'))
else:
_label = gtk.Label(_('Angular'))
self.__notebook.append_page(_vbox, _label)
def __initNotebook(self):
"""Populate the gtk.Notebook with widgets.
__initNotebook()
This method is private to the GtkDimStyle class.
"""
self.__generalPage()
self.__psPage() # Primary
self.__psPage(False) # Secondary
self.__dimPage('linear')
self.__dimPage('radial')
self.__dimPage('angular')
def clear(self):
"""Clear out all values and widgets in the GtkDimStyle.
clear()
"""
self.__window = None
_nb = self.__notebook
_nb.set_current_page(0)
while _nb.get_current_page() != -1:
_nb.remove_page(-1)
self.__widgets.clear()
del self.__dimstyles[:]
self.__ds = None
def setImageSettings(self, im):
"""Adjust the widgets values based on current Image values
setImageSettings(im)
Argument 'im' must be an Image instance.
"""
if not isinstance(im, image.Image):
raise TypeError, "Invalid Image type: " + `type(im)`
_widgets = self.__widgets
for _key in GtkDimStyle.__keys:
_ival = im.getOption(_key)
if (_key == 'DIM_PRIMARY_FONT_FAMILY' or
_key == 'DIM_SECONDARY_FONT_FAMILY'):
if GtkDimStyle.__families is None:
_families = []
_window = self.__window
for _family in _window.get_pango_context().list_families():
_families.append(_family.get_name())
_families.sort()
GtkDimStyle.__families = _families
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_widget = _sm(_widgets, _key, _ival,
GtkDimStyle.__families)
if _key not in _widgets:
_widgets[_key] = _widget
elif (_key == 'DIM_PRIMARY_FONT_STYLE' or
_key == 'DIM_SECONDARY_FONT_STYLE'):
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_optlist = GtkDimStyle.__font_styles
_widget = _sm(_widgets, _key, _ival, _optlist)
_idx = 0
for _i in range(len(_optlist)):
_val = text.TextStyle.getStyleFromString(_optlist[_i])
if _val == _ival:
_idx = _i
_widget.set_active(_idx)
if _key not in _widgets:
_widgets[_key] = _widget
elif (_key == 'DIM_PRIMARY_FONT_WEIGHT' or
_key == 'DIM_SECONDARY_FONT_WEIGHT'):
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_optlist = GtkDimStyle.__font_weights
_widget = _sm(_widgets, _key, _ival, _optlist)
_idx = 0
for _i in range(len(_optlist)):
_val = text.TextStyle.getWeightFromString(_optlist[_i])
if _val == _ival:
_idx = _i
_widget.set_active(_idx)
if _key not in _widgets:
_widgets[_key] = _widget
elif _key == 'DIM_PRIMARY_FONT_COLOR':
_s = _('Select Primary Dimension Font Color')
if hasattr(gtk, 'ColorButton'):
_sm = GtkDimStyle.__getColorButton
else:
_sm = GtkDimStyle.__getColorDA
_widget = _sm(_widgets, _key, _ival, _s)
if _key not in _widgets:
_widgets[_key] = _widget
elif _key == 'DIM_SECONDARY_FONT_COLOR':
_s = _('Select Secondary Dimension Font Color')
if hasattr(gtk, 'ColorButton'):
_sm = GtkDimStyle.__getColorButton
else:
_sm = GtkDimStyle.__getColorDA
_widget = _sm(_widgets, _key, _ival, _s)
if _key not in _widgets:
_widgets[_key] = _widget
elif (_key == 'DIM_PRIMARY_TEXT_ANGLE' or
_key == 'DIM_SECONDARY_TEXT_ANGLE'):
pass
elif (_key == 'DIM_PRIMARY_TEXT_ALIGNMENT' or
_key == 'DIM_SECONDARY_TEXT_ALIGNMENT'):
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_optlist = GtkDimStyle.__text_align
_widget = _sm(_widgets, _key, _ival, _optlist)
_idx = 0
for _i in range(len(_optlist)):
_val = text.TextStyle.getAlignmentFromString(_optlist[_i])
if _val == _ival:
_idx = _i
_widget.set_active(_idx)
if _key not in _widgets:
_widgets[_key] = _widget
elif (_key == 'DIM_PRIMARY_PREFIX' or
_key == 'DIM_SECONDARY_PREFIX' or
_key == 'DIM_PRIMARY_SUFFIX' or
_key == 'DIM_SECONDARY_SUFFIX' or
_key == 'RADIAL_DIM_PRIMARY_PREFIX' or
_key == 'RADIAL_DIM_SECONDARY_PREFIX' or
_key == 'RADIAL_DIM_PRIMARY_SUFFIX' or
_key == 'RADIAL_DIM_SECONDARY_SUFFIX' or
_key == 'ANGULAR_DIM_PRIMARY_PREFIX' or
_key == 'ANGULAR_DIM_SECONDARY_PREFIX' or
_key == 'ANGULAR_DIM_PRIMARY_SUFFIX' or
_key == 'ANGULAR_DIM_SECONDARY_SUFFIX'):
_entry = _widgets.setdefault(_key, gtk.Entry())
_entry.set_text(_ival)
if _key not in _widgets:
_widgets[_key] = _entry
elif (_key == 'DIM_PRIMARY_PRECISION' or
_key == 'DIM_SECONDARY_PRECISION'):
_widget = _widgets.get(_key)
if _widget is None:
_adj = gtk.Adjustment(_ival, 0, 15, 1, 1, 1)
_sb = gtk.SpinButton(_adj)
_sb.set_digits(0)
_sb.set_numeric(True)
_widgets[_key] = _sb
else:
_widget.set_value(_ival)
elif (_key == 'DIM_PRIMARY_UNITS' or
_key == 'DIM_SECONDARY_UNITS'):
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_widget = _sm(_widgets, _key, _ival, GtkDimStyle.__units)
if _key not in _widgets:
_widgets[_key] = _widget
elif (_key == 'DIM_PRIMARY_LEADING_ZERO' or
_key == 'DIM_SECONDARY_LEADING_ZERO'):
_str = _('Print leading 0')
_cb = GtkDimStyle.__getCheckButton(_widgets, _key, _str)
_cb.set_active(_ival)
if _key not in _widgets:
_widgets[_key] = _cb
elif (_key == 'DIM_PRIMARY_TRAILING_DECIMAL' or
_key == 'DIM_SECONDARY_TRAILING_DECIMAL'):
_str = _('Print trailing decimal point')
_cb = GtkDimStyle.__getCheckButton(_widgets, _key, _str)
_cb.set_active(_ival)
if _key not in _widgets:
_widgets[_key] = _cb
elif (_key == 'DIM_OFFSET' or
_key == 'DIM_EXTENSION' or
_key == 'DIM_ENDPOINT_SIZE' or
_key == 'DIM_THICKNESS' or
_key == 'DIM_PRIMARY_TEXT_SIZE' or
_key == 'DIM_SECONDARY_TEXT_SIZE'):
_entry = _widgets.setdefault(_key, gtk.Entry())
_length = "%f" % _ival
_entry.set_data('length', _length)
_hid = _entry.get_data('handlerid')
if _hid is not None:
_entry.handler_block(_hid)
try:
_entry.set_text(_length)
finally:
_entry.handler_unblock(_hid)
else:
_entry.set_text(_length)
_handlerid = _entry.connect("insert-text",
GtkDimStyle.__entryInsertText)
_entry.set_data('handlerid', _handlerid)
_entry.connect("activate", GtkDimStyle.__entryActivate)
_entry.connect("focus-out-event",
GtkDimStyle.__entryFocusOut)
if _key not in _widgets:
_widgets[_key] = _entry
elif (_key == 'DIM_COLOR'):
_color = _ival
_s = _('Select Dimension Color')
if hasattr(gtk, 'ColorButton'):
_sm = GtkDimStyle.__getColorButton
else:
_sm = GtkDimStyle.__getColorDA
_widget = _sm(_widgets, _key, _ival, _s)
if _key not in _widgets:
_widgets[_key] = _widget
elif (_key == 'DIM_POSITION'):
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_optlist = GtkDimStyle.__dim_positions
_widget = _sm(_widgets, _key, _ival, _optlist)
_idx = 0
for _i in range(len(_optlist)):
_val = dimension.Dimension.getPositionFromString(_optlist[_i])
if _val == _ival:
_idx = _i
_widget.set_active(_idx)
if _key not in _widgets:
_widgets[_key] = _widget
elif (_key == 'DIM_ENDPOINT'):
if hasattr(gtk, 'ComboBox'):
_sm = GtkDimStyle.__getComboBox
else:
_sm = GtkDimStyle.__getOptionMenu
_optlist = GtkDimStyle.__dim_endpoints
_widget = _sm(_widgets, _key, _ival, _optlist)
_idx = 0
for _i in range(len(_optlist)):
_val = dimension.Dimension.getEndpointTypeFromString(_optlist[_i])
if _val == _ival:
_idx = _i
_widget.set_active(_idx)
if _key not in _widgets:
_widgets[_key] = _widget
elif (_key == 'DIM_DUAL_MODE'):
_str = _('Display secondary dimension text')
_cb = GtkDimStyle.__getCheckButton(_widgets, _key, _str)
_cb.set_active(_ival)
if _key not in _widgets:
_widgets[_key] = _cb
elif (_key == 'DIM_POSITION_OFFSET'):
pass
elif (_key == 'DIM_DUAL_MODE_OFFSET'):
pass
elif (_key == 'RADIAL_DIM_DIA_MODE'):
_str = _('Show diameterical dimension value')
_cb = GtkDimStyle.__getCheckButton(_widgets, _key, _str)
_cb.set_active(_ival)
if _key not in _widgets:
_widgets[_key] = _cb
else:
raise ValueError, "Unexpected key: " + _key
def _widget_changed(widget, gds):
if hasattr(gtk, 'ComboBox'):
_idx = widget.get_active()
else:
_idx = widget.get_history()
_dimstyles = gds.getDimStyles()
gds.setDimStyle(_dimstyles[_idx])
def dimstyle_dialog(gtkimage, dimstyles):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('DimStyle Settings'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_image = gtkimage.getImage()
_ds = _image.getOption('DIM_STYLE')
_hbox = gtk.HBox(False, 5)
_hbox.set_border_width(5)
_label = gtk.Label(_('Active DimStyle:'))
_hbox.pack_start(_label, False, False, 5)
_idx = 0
if hasattr(gtk, 'ComboBox'):
_widget = gtk.combo_box_new_text()
for _i in range(len(dimstyles)):
_dimstyle = dimstyles[_i]
if (_ds is _dimstyle or
_ds == _dimstyle):
_idx = _i
_widget.append_text(_dimstyle.getName())
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(dimstyles)):
_dimstyle = dimstyles[_i]
if (_ds is _dimstyle or
_ds == _dimstyle):
_idx = _i
_item = gtk.MenuItem(_dimstyle.getName())
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_widget, False, False, 0)
_dialog.vbox.pack_start(_hbox, True, True)
#
_gds = GtkDimStyle(_window)
for _dimstyle in dimstyles:
_gds.addDimStyle(_dimstyle)
_gds.setDimStyle(_ds)
_gds.setImageSettings(_image)
_dialog.vbox.pack_start(_gds.notebook, True, True)
_widget.connect('changed', _widget_changed, _gds)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_nds = _gds.getDimStyle()
if _nds != _ds:
_image.setOption('DIM_STYLE', _nds)
for _opt, _val in _gds.getValues():
_set = False
_cv = _image.getOption(_opt)
if (_opt == 'DIM_PRIMARY_FONT_FAMILY' or
_opt == 'DIM_SECONDARY_FONT_FAMILY' or
_opt == 'DIM_PRIMARY_FONT_WEIGHT' or
_opt == 'DIM_SECONDARY_FONT_WEIGHT' or
_opt == 'DIM_PRIMARY_FONT_STYLE' or
_opt == 'DIM_SECONDARY_FONT_STYLE' or
_opt == 'DIM_PRIMARY_TEXT_ALIGNMENT' or
_opt == 'DIM_SECONDARY_TEXT_ALIGNMENT' or
_opt == 'DIM_PRIMARY_PREFIX' or
_opt == 'DIM_SECONDARY_PREFIX' or
_opt == 'DIM_PRIMARY_SUFFIX' or
_opt == 'DIM_SECONDARY_SUFFIX' or
_opt == 'DIM_PRIMARY_PRECISION' or
_opt == 'DIM_SECONDARY_PRECISION' or
_opt == 'DIM_PRIMARY_UNITS' or
_opt == 'DIM_SECONDARY_UNITS' or
_opt == 'DIM_POSITION' or
_opt == 'DIM_ENDPOINT' or
_opt == 'RADIAL_DIM_PRIMARY_PREFIX' or
_opt == 'RADIAL_DIM_PRIMARY_SUFFIX' or
_opt == 'RADIAL_DIM_SECONDARY_PREFIX' or
_opt == 'RADIAL_DIM_SECONDARY_SUFFIX' or
_opt == 'ANGULAR_DIM_PRIMARY_PREFIX' or
_opt == 'ANGULAR_DIM_PRIMARY_SUFFIX' or
_opt == 'ANGULAR_DIM_SECONDARY_PREFIX' or
_opt == 'ANGULAR_DIM_SECONDARY_SUFFIX'):
if _val != _cv:
_set = True
elif (_opt == 'DIM_PRIMARY_TEXT_SIZE' or
_opt == 'DIM_SECONDARY_TEXT_SIZE' or
_opt == 'DIM_OFFSET' or
_opt == 'DIM_EXTENSION' or
_opt == 'DIM_THICKNESS' or
_opt == 'DIM_ENDPOINT_SIZE'):
if abs(_val - _cv) > 1e-10:
_set = True
elif (_opt == 'DIM_PRIMARY_LEADING_ZERO' or
_opt == 'DIM_SECONDARY_LEADING_ZERO' or
_opt == 'DIM_PRIMARY_TRAILING_DECIMAL' or
_opt == 'DIM_SECONDARY_TRAILING_DECIMAL' or
_opt == 'DIM_DUAL_MODE' or
_opt == 'RADIAL_DIM_DIA_MODE'):
if ((_val is False and _cv is True) or
(_val is True and _cv is False)):
_set = True
elif (_opt == 'DIM_COLOR' or
_opt == 'DIM_PRIMARY_FONT_COLOR' or
_opt == 'DIM_SECONDARY_FONT_COLOR'):
if _val != _cv.getColors():
_r, _g, _b = _val
_val = color.Color(_r, _g, _b)
elif (_opt == 'DIM_PRIMARY_TEXT_ANGLE' or
_opt == 'DIM_SECONDARY_TEXT_ANGLE' or
_opt == 'DIM_POSITION_OFFSET' or
_opt == 'DIM_DUAL_MODE_OFFSET'):
pass
else:
raise RuntimeError, "Unexpected DimStyle option: '%s'" % _opt
if _set:
_image.setOption(_opt, _val)
_dialog.destroy()
_gds.clear()
PythonCAD-DS1-R37/PythonCAD/Interface/Gtk/gtkentities.py 0000644 0001750 0001750 00000174252 11307666732 022321 0 ustar matteo matteo #
# Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007 Art Haas
#
# 2009 Matteo Boscolo
#
# 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
#
#
# menu functions for creating entities in drawing
# like segments, circles, etc ...
#
from math import hypot, pi, atan2
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import math
import sys
from PythonCAD.Generic import globals
from PythonCAD.Generic.point import Point
from PythonCAD.Generic.segment import Segment
from PythonCAD.Generic.segjoint import Chamfer, Fillet
from PythonCAD.Generic import color
from PythonCAD.Generic import util
from PythonCAD.Generic import units
from PythonCAD.Interface.Gtk import gtkDialog
from PythonCAD.Generic import tools
from PythonCAD.Generic import snap
def make_tuple(text, gdict):
_tpl = eval(text, gdict)
if not isinstance(_tpl, tuple):
raise TypeError, "Invalid tuple: " + `type(_tpl)`
if len(_tpl) != 2:
raise ValueError, "Invalid tuple: " + str(_tpl)
return _tpl
def create_entity(gtkimage, tool=None):
_tool = gtkimage.getImage().getTool()
_init_func = _tool.getHandler("initialize")
_image = gtkimage.getImage()
_image.startAction()
try:
_tool.create(_image)
finally:
_image.endAction()
_init_func(gtkimage)
#
# points
#
def point_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
snap.setSnap(_image,tool.setPoint,_tol)
create_entity(gtkimage)
return True
def point_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setPoint(_x, _y)
create_entity(gtkimage)
def point_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter the point.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", point_mode_init)
_tool.setHandler("button_press", point_button_press_cb)
_tool.setHandler("entry_event", point_entry_event_cb)
#
# segments
#
def segment_motion_notify_cb(gtkimage, widget, event, tool):
"""
Segment notify motion event
"""
_segs = []
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_x1, _y1 = tool.getFirstPoint().point.getCoords()
_px1, _py1 = gtkimage.coordToPixTransform(_x1, _y1)
#
# manage horizontal vertical angle forced
#
_x,_y = gtkimage.pixToCoordTransform(_x,_y)
_x,_y = trasformCoords(_x1, _y1,_x,_y,tool.direction)
_x,_y = gtkimage.coordToPixTransform(_x, _y)
_cp = tool.getCurrentPoint()
if _cp is not None: # draw the old line
_xc, _yc = _cp
_segs.append((_px1, _py1, _xc, _yc))
tool.setCurrentPoint(_x, _y)
_segs.append((_px1, _py1, _x, _y))
widget.window.draw_segments(_gc, _segs)
return True
def trasformCoords(x,y,x1,y1,angle):
"""
trasform the given cordinate with en angle
useful in case you whont to force a segment to be in a partuicular
direction
"""
_x=x1
_y=y1
if angle is not None:
if angle == 90.0 or angle == 270.0:
_x=x
elif angle == 0.0 or angle == 180.0:
_y=y
else:
_radDir=(math.pi*angle)/180
_tan=math.tan(_radDir)*abs(x-x1)
if x>x1:
_y=y-_tan
_x=x-abs(x-x1)
else:
_y=y+_tan
_x=x+abs(x-x1)
return _x,_y
def segment_set_direction(text,tool):
"""
parse the text and set the direction into the tool
"""
if isinstance(text,str) :
if text.find(':') >0 :
cmdArgs=text.split(':')
if len(cmdArgs)==2:
_firstArgs=cmdArgs[0].strip().lower()
if _firstArgs == 'd' :
_r = setSegmentDirection(tool,cmdArgs[1])
return _r
return False
def setSegmentDirection(tool,angle):
"""
set the segment direction
"""
if str(angle).strip().lower() == "n" :
tool.direction=None
return False
else:
tool.direction=angle
return True
def segment_second_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
if segment_set_direction(_text,tool):
tool.setHandler("button_press", segment_second_button_press_cb)
tool.setHandler("motion_notify", segment_motion_notify_cb)
tool.setHandler("entry_event", segment_second_entry_event_cb)
_dir=str(tool.direction)
gtkimage.setPrompt(_('Segmend d ' + _dir + 'Enter the second Point or click in the drawing area'))
_entry.delete_text(0, -1)
gtkimage.redraw()
return
_entry.delete_text(0, -1)
if len(_text):
try:
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
except:
if _text.strip()!="d:n" :
gtkDialog._message_dialog(gtkimage,"Wrong comand","inser a touple of values x,y")
return
_str=snap.SnapPointStr("Freepoint",Point(_x, _y),None)
tool.setSecondPoint(_str)
create_entity(gtkimage)
def segment_first_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
_str=snap.SnapPointStr("Freepoint",Point(_x, _y),None)
tool.setFirstPoint(_str)
tool.setHandler("button_press", segment_second_button_press_cb)
tool.setHandler("motion_notify", segment_motion_notify_cb)
tool.setHandler("entry_event", segment_second_entry_event_cb)
gtkimage.setPrompt(_('Enter the second Point or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
def segment_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
snap.setSnap(_image,tool.setSecondPoint,_tol)
if tool.direction is not None:
_x,_y=tool.getFirstPoint().point.getCoords()
_x1,_y1=tool.getSecondPoint().point.getCoords()
_x1,_y1=trasformCoords(_x,_y,_x1,_y1,tool.direction)
_strP=snap.SnapPointStr("Freepoint",Point(_x1,_y1),"None")
tool.setSecondPoint(_strP)
try:
create_entity(gtkimage)
tool.direction=None
except:
tool.setHandler("button_press", segment_second_button_press_cb)
tool.setHandler("entry_event", segment_second_entry_event_cb)
tool.setHandler("motion_notify", segment_motion_notify_cb)
gtkimage.setPrompt(_('Enter the second point or click in the drawing area'))
return True
def segment_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
snap.setSnap(_image,tool.setFirstPoint,_tol)
tool.setHandler("button_press", segment_second_button_press_cb)
tool.setHandler("entry_event", segment_second_entry_event_cb)
tool.setHandler("motion_notify", segment_motion_notify_cb)
gtkimage.setPrompt(_('Enter the second point or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def segment_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter a point.'))
_tool = gtkimage.getImage().getTool()
_tool.direction=None
_tool.setHandler("initialize", segment_mode_init)
_tool.setHandler("button_press", segment_first_button_press_cb)
_tool.setHandler("entry_event", segment_first_entry_event_cb)
#
# rectangles
#
def rectangle_motion_notify_cb(gtkimage, widget, event, tool):
_x1, _y1 = tool.getFirstPoint().point.getCoords()
_px, _py = gtkimage.coordToPixTransform(_x1, _y1)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_xmin = min(_px, _xc)
_ymin = min(_py, _yc)
_width = abs(_px - _xc)
_height = abs(_py - _yc)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _width, _height)
tool.setCurrentPoint(_x, _y)
_xmin = min(_px, _x)
_ymin = min(_py, _y)
_width = abs(_px - _x)
_height = abs(_py - _y)
widget.window.draw_rectangle(_gc, False, _xmin, _ymin, _width, _height)
return True
def rectangle_second_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setSecondPoint(_x, _y)
create_entity(gtkimage)
def rectangle_first_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setFirstPoint(_x, _y)
tool.setHandler("button_press", rectangle_second_button_press_cb)
tool.setHandler("entry_event", rectangle_second_entry_event_cb)
tool.setHandler("motion_notify", rectangle_motion_notify_cb)
gtkimage.setPrompt(_('Enter the second Point or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
def rectangle_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
snap.setSnap(_image,tool.setSecondPoint,_tol)
create_entity(gtkimage)
return True
def rectangle_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
snap.setSnap(_image,tool.setFirstPoint,_tol)
tool.setHandler("button_press", rectangle_second_button_press_cb)
tool.setHandler("motion_notify", rectangle_motion_notify_cb)
tool.setHandler("entry_event", rectangle_second_entry_event_cb)
gtkimage.setPrompt(_('Enter the second point or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def rectangle_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter a point.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", rectangle_mode_init)
_tool.setHandler("button_press", rectangle_first_button_press_cb)
_tool.setHandler("entry_event", rectangle_first_entry_event_cb)
#
# circles
#
def circle_center_motion_notify_cb(gtkimage, widget, event, tool):
_cx, _cy = tool.center.point.getCoords()
_pcx, _pcy = gtkimage.coordToPixTransform(_cx, _cy)
_upp = gtkimage.getUnitsPerPixel()
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_radius = tool.getRadius()
if _radius is not None:
_pr = int(_radius/_upp)
_xmin = _pcx - _pr
_ymin = _pcy - _pr
_cw = _ch = _pr * 2
widget.window.draw_arc(_gc, False, _xmin, _ymin, _cw, _ch,
0, 360*64)
_ix, _iy = gtkimage.image.getCurrentPoint()
_radius = hypot((_cx - _ix),(_cy - _iy))
if _radius<0.0:
print "Debug: R: "+ str(_radius)
_radius=0.1 # Convention if radius is less the 0 i assume 0.1
tool.setRadius(_radius)
_pr = int(_radius/_upp)
_xmin = _pcx - _pr
_ymin = _pcy - _pr
_cw = _ch = _pr * 2
widget.window.draw_arc(_gc, False, _xmin, _ymin, _cw, _ch,
0, 360*64)
return True
def circle_radius_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_r = util.get_float(eval(_text, gtkimage.image.getImageVariables()))
if not _r > 0.0:
raise ValueError, "Invalid radius: %g" % _r
tool.setRadius(_r)
create_entity(gtkimage)
def circle_point_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setCenter(_x, _y)
tool.setHandler("button_press", circle_radius_button_press_cb)
tool.setHandler("motion_notify", circle_center_motion_notify_cb)
tool.setHandler("entry_event", circle_radius_entry_event_cb)
gtkimage.setPrompt(_('Enter the radius or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
#stop snap object
stopOneShutSnap(gtkimage)
def circle_radius_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
snap.setSnap(_image,tool.setRadiusPoint,_tol)
_x,_y=tool.radiusPoint.point.getCoords()
_cx,_cy=tool.getCenter().point.getCoords()
_radius = hypot((_cx - _x), (_cy - _y))
tool.setRadius(_radius)
create_entity(gtkimage)
return True
def circle_center_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setCenter,_tol,_snapArray)
tool.setHandler("button_press", circle_radius_button_press_cb)
tool.setHandler("motion_notify", circle_center_motion_notify_cb)
tool.setHandler("entry_event", circle_radius_entry_event_cb)
gtkimage.setPrompt(_('Enter the radius or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def circle_center_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter a point.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", circle_center_button_press_cb)
_tool.setHandler("entry_event", circle_point_entry_event_cb)
_tool.setHandler("initialize", circle_center_mode_init)
#
# circle from two points
#
def circle_tp_motion_notify_cb(gtkimage, widget, event, tool):
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_radius = tool.getRadius()
_upp = gtkimage.getUnitsPerPixel()
if _radius is not None:
_cx, _cy = tool.getCenter().point.getCoords()
_pcx, _pcy = gtkimage.coordToPixTransform(_cx, _cy)
_pr = int(_radius/_upp)
_xmin = _pcx - _pr
_ymin = _pcy - _pr
_cw = _ch = _pr * 2
widget.window.draw_arc(_gc, False, _xmin, _ymin, _cw, _ch,0, 360*64)
snap.setDinamicSnap(gtkimage,tool.setSecondPoint,None)
_cx, _cy = tool.getCenter().point.getCoords()
_pcx, _pcy = gtkimage.coordToPixTransform(_cx, _cy)
_radius = tool.getRadius()
_pr = int(_radius/_upp)
_xmin = _pcx - _pr
_ymin = _pcy - _pr
_cw = _ch = _pr * 2
widget.window.draw_arc(_gc, False, _xmin, _ymin, _cw, _ch,0, 360*64)
return True
def circle_tp_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
#todo imlement the tangent snap for the two point circle
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setSecondPoint,_tol,_snapArray)
create_entity(gtkimage)
return True
def circle_tp_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
#todo imlement the tangent snap for the two point circle
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setFirstPoint,_tol,_snapArray)
tool.setHandler("button_press", circle_tp_second_button_press_cb)
tool.setHandler("motion_notify", circle_tp_motion_notify_cb)
tool.setHandler("entry_event", circle_tp_second_entry_event_cb)
gtkimage.setPrompt(_('Enter the second point or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
return True
def circle_tp_second_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setSecondPoint(_x, _y)
create_entity(gtkimage)
def circle_tp_first_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setFirstPoint(_x, _y)
tool.setHandler("motion_notify", circle_tp_motion_notify_cb)
tool.setHandler("entry_event", circle_tp_second_entry_event_cb)
gtkimage.setPrompt(_('Enter another point or click in the drawing area'))
gtkimage.getGC().set_function(gtk.gdk.INVERT)
def circle_tp_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter a point.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", circle_tp_first_button_press_cb)
_tool.setHandler("entry_event", circle_tp_first_entry_event_cb)
_tool.setHandler("initialize", circle_tp_mode_init)
#
# arcs
#
def arc_center_end_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_snp=snap.getSnapPoint(_image,_tol,_snapArray)
_x,_y=_snp.point.getCoords()
_cx, _cy = tool.getCenter().point.getCoords()
_angle = (180.0/pi) * atan2((_y - _cy),(_x - _cx))
if _angle < 0.0:
_angle = _angle + 360.0
tool.setEndAngle(_angle)
create_entity(gtkimage)
return True
def arc_angle_motion_notify_cb(gtkimage, widget, event, tool):
_ix, _iy = gtkimage.image.getCurrentPoint()
_cx, _cy = tool.getCenter().point.getCoords() # arc center
_radius = tool.getRadius()
_sa = tool.getStartAngle()
_pcx, _pcy = gtkimage.coordToPixTransform(_cx, _cy)
_upp = gtkimage.getUnitsPerPixel()
_pr = int(_radius/_upp)
_xmin = _pcx - _pr
_ymin = _pcy - _pr
_cw = _ch = _pr * 2
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_ea = tool.getEndAngle()
_win = widget.window
if _ea is not None:
if _sa < _ea:
_sweep = _ea - _sa
else:
_sweep = 360.0 - (_sa - _ea)
_win.draw_arc(_gc, False, _xmin, _ymin, _cw, _ch,
int(_sa * 64), int(_sweep * 64))
_ea = (180.0/pi) * atan2((_iy - _cy), (_ix - _cx))
if _ea < 0.0:
_ea = _ea + 360.0
tool.setEndAngle(_ea)
if _sa < _ea:
_sweep = _ea - _sa
else:
_sweep = 360.0 - (_sa - _ea)
_win.draw_arc(_gc, False, _xmin, _ymin, _cw, _ch,
int(_sa * 64), int(_sweep * 64))
return True
def arc_start_angle_button_press_cb(gtkimage, widget, event, tool):
_cx, _cy = tool.getCenter()
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_snp=snap.getSnapPoint(_image,_tol,_snapArray)
_x,_y=_snp.point.getCoords()
_angle = (180.0/pi) * atan2((_y - _cy), (_x - _cx))
if _angle < 0.0:
_angle = _angle + 360.0
tool.setStartAngle(_angle)
tool.setHandler("motion_notify", arc_angle_motion_notify_cb)
tool.setHandler("entry_event", arc_center_ea_entry_event_cb)
gtkimage.setPrompt(_('Enter the end angle of the arc.'))
return True
def arc_center_ea_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_angle = util.make_c_angle(eval(_text, gtkimage.image.getImageVariables()))
tool.setEndAngle(_angle)
create_entity(gtkimage)
def arc_center_sa_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_angle = util.make_c_angle(eval(_text, gtkimage.image.getImageVariables()))
tool.setStartAngle(_angle)
tool.setHandler("motion_notify", arc_angle_motion_notify_cb)
tool.setHandler("entry_event", arc_center_ea_entry_event_cb)
gtkimage.setPrompt(_('Enter the end angle of the arc.'))
def arc_center_radius_button_press_cb(gtkimage, widget, event, tool):
_cx, _cy = tool.getCenter().point.getCoords()
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
_snp=snap.getSnapPoint(_image,_tol,_snapArray)
_x,_y=_snp.point.getCoords()
_radius = hypot((_x - _cx), (_y - _cy))
tool.setRadius(_radius)
_angle = (180.0/pi) * atan2((_y - _cy), (_x - _cx))
if _angle < 0.0:
_angle = _angle + 360.0
tool.setStartAngle(_angle)
tool.delHandler("entry_event")
tool.setHandler("motion_notify", arc_angle_motion_notify_cb)
gtkimage.refresh()
gtkimage.getGC().set_function(gtk.gdk.INVERT)
tool.setHandler("button_press", arc_center_end_button_press_cb)
gtkimage.setPrompt(_('Click in the drawing area to finish the arc'))
return True
def arc_center_radius_entry_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_r = util.get_float(eval(_text, gtkimage.image.getImageVariables()))
if not _r > 0.0:
raise ValueError, "Invalid radius: %g" % _r
tool.setRadius(_r)
tool.setHandler("entry_event", arc_center_sa_entry_event_cb)
tool.setHandler("button_press", arc_start_angle_button_press_cb)
gtkimage.setPrompt(_('Enter the start angle of the arc.'))
def arc_radius_motion_notify_cb(gtkimage, widget, event, tool):
_cx, _cy = tool.getCenter().point.getCoords()
_pcx, _pcy = gtkimage.coordToPixTransform(_cx, _cy)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_radius = tool.getRadius()
_upp = gtkimage.getUnitsPerPixel()
if _radius is not None:
_pr = int(_radius/_upp)
_xmin = _pcx - _pr
_ymin = _pcy - _pr
_cw = _ch = _pr * 2
widget.window.draw_arc(_gc, False, _xmin, _ymin, _cw, _ch,
0, 360*64)
_ix, _iy = gtkimage.image.getCurrentPoint()
_radius = hypot((_cx - _ix), (_cy - _iy))
tool.setRadius(_radius)
_pr = int(_radius/_upp)
_xmin = _pcx - _pr
_ymin = _pcy - _pr
_cw = _ch = _pr * 2
widget.window.draw_arc(_gc, False, _xmin, _ymin, _cw, _ch,
0, 360*64)
return True
def arc_center_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setCenter,_tol,_snapArray)
gtkimage.getGC().set_function(gtk.gdk.INVERT)
tool.setHandler("motion_notify", arc_radius_motion_notify_cb)
tool.setHandler("entry_event", arc_center_radius_entry_cb)
tool.setHandler("button_press", arc_center_radius_button_press_cb)
gtkimage.setPrompt(_('Enter the radius or click in the drawing area'))
return True
def arc_center_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setCenter(_x, _y)
gtkimage.getGC().set_function(gtk.gdk.INVERT)
tool.setHandler("motion_notify", arc_radius_motion_notify_cb)
tool.setHandler("button_press", arc_center_radius_button_press_cb)
tool.setHandler("entry_event", arc_center_radius_entry_cb)
gtkimage.setPrompt(_('Enter the arc radius or click in the drawing area'))
def arc_center_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area or enter a point.'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("button_press", arc_center_button_press_cb)
_tool.setHandler("entry_event", arc_center_entry_event_cb)
_tool.setHandler("initialize", arc_center_mode_init)
#
# chamfers
#
def chamfer_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_pt, _new_pt = _image.findPoint(_x, _y, _tol)
if _pt is not None and not _new_pt:
_active_layer = _image.getActiveLayer()
_users = _pt.getUsers()
if len(_users) != 2:
return
_s1 = _s2 = None
for _user in _users:
if not isinstance(_user, Segment):
return
if _s1 is None:
_s1 = _user
else:
_s2 = _user
_len = _image.getOption('CHAMFER_LENGTH')
_s = _image.getOption('LINE_STYLE')
_l = _image.getOption('LINE_TYPE')
_c = _image.getOption('LINE_COLOR')
_t = _image.getOption('LINE_THICKNESS')
#
# the following is a work-around that needs to
# eventually be replaced ...
#
_p1, _p2 = _s1.getEndpoints()
_x1, _y1 = _p1.getCoords()
_x2, _y2 = _p2.getCoords()
_slen = _s1.length()
_factor = 2.0
_r = (_slen - (_len/_factor))/_slen
_xn = _x1 + _r * (_x2 - _x1)
_yn = _y1 + _r * (_y2 - _y1)
_pts = _active_layer.find('point', _xn, _yn)
while len(_pts) > 0:
_factor = _factor + 1.0
if _factor > 1000:
break
_r = (_slen - (_len/_factor))/_slen
_xn = _x1 + _r * (_x2 - _x1)
_yn = _y1 + _r * (_y2 - _y1)
_pts = _active_layer.find('point', _xn, _yn)
if len(_pts) == 0:
_image.startAction()
try:
_pc = Point(_xn, _yn)
_active_layer.addObject(_pc)
if _pt is _p1:
_s1.setP1(_pc)
elif _pt is _p2:
_s1.setP2(_pc)
else:
raise ValueError, "Unexpected endpoint: " + str(_pc)
_ptx, _pty = _pt.getCoords()
_pc.setCoords(_ptx, _pty)
_chamfer = Chamfer(_s1, _s2, _len, _s)
if _l != _s.getLinetype():
_chamfer.setLinetype(_l)
if _c != _s.getColor():
_chamfer.setColor(_c)
if abs(_t - _s.getThickness()) > 1e-10:
_chamfer.setThickness(_t)
_active_layer.addObject(_chamfer)
finally:
_image.endAction()
return True
def chamfer_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click on the points where you want a chamfer.'))
_tool = gtkimage.getImage().getTool()
_tool.initialize()
_tool.setHandler("button_press", chamfer_button_press_cb)
#
# fillet
#
def fillet_entry_event_cb(gtkimage, widget, tool):
"""
Manage the radius entered from the entry
"""
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text)>3:
if _text.find(':') >0 :
cmdArgs=_text.split(':')
if len(cmdArgs)==2:
_firstArgs=cmdArgs[0].strip().lower()
if _firstArgs == 'r' :
setFilletRadius(gtkimage,tool,cmdArgs[1])
return
elif _firstArgs == 'tm':
setTrimMode(gtkimage,tool,cmdArgs[1])
return
if _text.find('?') >= 0:
gtkDialog._help_dialog(gtkimage,"FilletTwoPoint")
return
gtkDialog._error_dialog(gtkimage,"Wrong command")
def setTrimMode(gtkimage,tool,mode):
"""
set the trim fillet mode
"""
_mode=mode.strip().lower()
if _mode=='f' :
tool.TrimMode="f"
elif _mode=='s' :
tool.TrimMode="s"
elif _mode=='b' :
tool.TrimMode="b"
elif _mode=='n' :
tool.TrimMode="n"
else:
gtkDialog._error_dialog(gtkimage,"Wrong command")
return
fillet_prompt_message(gtkimage,tool)
def setFilletRadius(gtkimage,tool,radius):
"""
set the fillet radius in to the tool
"""
_r=radius.strip()
rad=float(_r)
tool.rad=rad
fillet_prompt_message(gtkimage,tool)
def fillet_prompt_message(gtkimage,tool,startMessage=None):
"""
set the fillet message
"""
if startMessage == None:
_oldMsg=gtkimage.getPrompt()
else:
_oldMsg=startMessage
if isinstance(tool,tools.FilletTool):
_msg =_oldMsg.split('(')[0] + '( r: ' + str(tool.rad) + ' )' + _oldMsg.split(')')[1]
if isinstance(tool,tools.FilletTwoLineTool):
_msg=_oldMsg.split('(')[0] + '( r: ' + str(tool.rad) + ' tm: ' + str(tool.TrimMode) + ' )' + _oldMsg.split(')')[1]
gtkimage.setPrompt(_msg)
def fillet_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_x, _y = _image.getCurrentPoint()
_pt, _new_pt = _image.findPoint(_x, _y, _tol)
if _pt is not None and not _new_pt:
_active_layer = _image.getActiveLayer()
_users = _pt.getUsers()
if len(_users) != 2:
return
_s1 = _s2 = None
for _user in _users:
if not isinstance(_user, Segment):
return
if _s1 is None:
_s1 = _user
else:
_s2 = _user
if(tool.rad!=None):
_rad = tool.rad
else:
_rad = _image.getOption('FILLET_RADIUS')
_s = _image.getOption('LINE_STYLE')
_l = _image.getOption('LINE_TYPE')
_c = _image.getOption('LINE_COLOR')
_t = _image.getOption('LINE_THICKNESS')
#
# the following is a work-around that needs to
# eventually be replaced ...
#
_p1, _p2 = _s1.getEndpoints()
_x1, _y1 = _p1.getCoords()
_x2, _y2 = _p2.getCoords()
_slen = _s1.length()
_factor = 2.0
_r = 1.0 - (_slen/_factor)
_xn = _x1 + _r * (_x2 - _x1)
_yn = _y1 + _r * (_y2 - _y1)
_pts = _active_layer.find('point', _xn, _yn)
while len(_pts) > 0:
_factor = _factor + 1.0
if _factor > 1000:
break
_r = 1.0 - (_slen/_factor)
_xn = _x1 + _r * (_x2 - _x1)
_yn = _y1 + _r * (_y2 - _y1)
_pts = _active_layer.find('point', _xn, _yn)
if len(_pts) == 0:
_image.startAction()
try:
_pc = Point(_xn, _yn)
_active_layer.addObject(_pc)
if _pt is _p1:
_s1.setP1(_pc)
elif _pt is _p2:
_s1.setP2(_pc)
else:
raise ValueError, "Unexpected endpoint: " + str(_pc)
_ptx, _pty = _pt.getCoords()
_pc.setCoords(_ptx, _pty)
_fillet = Fillet(_s1, _s2, _rad, _s)
if _l != _s.getLinetype():
_fillet.setLinetype(_l)
if _c != _s.getColor():
_fillet.setColor(_c)
if abs(_t - _s.getThickness()) > 1e-10:
_fillet.setThickness(_t)
_active_layer.addObject(_fillet)
finally:
_image.endAction()
gtkimage.redraw()
return True
def fillet_mode_init(gtkimage, tool=None):
"""
Init function for the fillet comand
"""
_image = gtkimage.getImage()
if tool!= None and tool.rad!=None:
_rad = tool.rad
else:
_rad = _image.getOption('FILLET_RADIUS')
_tool = gtkimage.getImage().getTool()
_msg = 'Click on the points where you want a fillet( ) or enter the Radius.'
_tool.initialize()
_tool.rad=_rad
fillet_prompt_message(gtkimage,_tool,_msg)
_tool.setHandler("initialize", fillet_mode_init)
_tool.setHandler("button_press", fillet_button_press_cb)
_tool.setHandler("entry_event", fillet_entry_event_cb)
#
# Fillet two line
#
def fillet_two_button_second_press_cb(gtkimage, widget, event, tool):
"""
Second selection commad
"""
_image = gtkimage.getImage()
_objs,pnt=snap.getSelections(gtkimage,Segment)
if _objs!=None and pnt!=None:
_image.startAction()
try:
tool.SecondLine=_objs
tool.SecondPoint=pnt
tool.Create(_image)
except ValueError,err:
_errmsg = "Fillet ValueError error: %s" % str(err)
gtkDialog._error_dialog(gtkimage,_errmsg )
except:
_errmsg = "Fillet error: %s" % str( sys.exc_info()[0])
gtkDialog._error_dialog(gtkimage,_errmsg )
for s in sys.exc_info():
print "Exception Error: %s"%str(s)
finally:
_image.endAction()
gtkimage.redraw()
fillet_two_line_mode_init(gtkimage,tool)
def fillet_two_button_press_cb(gtkimage, widget, event, tool):
"""
First Entity selected
"""
_image = gtkimage.getImage()
_objs,pnt=snap.getSelections(gtkimage,Segment)
if _objs!=None and pnt!=None:
_image.startAction()
try:
tool.FirstLine=_objs
tool.FirstPoint=pnt
if(tool.rad!=None):
_rad = tool.rad
_mod=tool.TrimMode
else:
_rad = _image.getOption('FILLET_RADIUS')
_mod = _image.getOption('FILLET_TWO_TRIM_MODE')
_msg = 'Click on the Second Entity ( ) or enter command options.'
fillet_prompt_message(gtkimage,tool,_msg)
tool.setHandler("button_press", fillet_two_button_second_press_cb)
#
finally:
_image.endAction()
def fillet_two_line_mode_init(gtkimage, tool=None):
"""
init function for the fillet two line comand
"""
_image = gtkimage.getImage()
if tool !=None and tool.rad!=None:
_rad = tool.rad
_tool=tool
else:
_rad = _image.getOption('FILLET_RADIUS')
_tool = gtkimage.getImage().getTool()
_msg = 'Click on the first Entity ( ) or enter command options.'
_tool.initialize()
_tool.rad=_rad
fillet_prompt_message(gtkimage,_tool,_msg)
_tool.setHandler("initialize", fillet_two_line_mode_init)
_tool.setHandler("button_press", fillet_two_button_press_cb)
_tool.setHandler("entry_event", fillet_entry_event_cb)
gtkimage._activateSnap=False
#
# leader lines
#
def leader_second_motion_notify_cb(gtkimage, widget, event, tool):
_segs = []
_x2, _y2 = tool.getMidPoint().point.getCoords()
_px2, _py2 = gtkimage.coordToPixTransform(_x2, _y2)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_segs.append((_px2, _py2, _xc, _yc))
tool.setCurrentPoint(_x, _y)
_segs.append((_px2, _py2, _x, _y))
widget.window.draw_segments(_gc, _segs)
return True
def leader_first_motion_notify_cb(gtkimage, widget, event, tool):
_segs = []
_x1, _y1 = tool.getFirstPoint().point.getCoords()
_px1, _py1 = gtkimage.coordToPixTransform(_x1, _y1)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_segs.append((_px1, _py1, _xc, _yc))
tool.setCurrentPoint(_x, _y)
_segs.append((_px1, _py1, _x, _y))
widget.window.draw_segments(_gc, _segs)
def leader_final_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setFinalPoint,_tol,_snapArray)
create_entity(gtkimage)
gtkimage.setPrompt(_('Click in the drawing area to place the initial point'))
return True
def leader_second_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setMidPoint,_tol,_snapArray)
tool.clearCurrentPoint()
tool.setHandler("motion_notify", leader_second_motion_notify_cb)
tool.setHandler("button_press", leader_final_button_press_cb)
gtkimage.setPrompt(_('Click in the drawing area to place the final point'))
return True
def leader_first_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setFirstPoint,_tol,_snapArray)
tool.setHandler("motion_notify", leader_first_motion_notify_cb)
tool.setHandler("button_press", leader_second_button_press_cb)
gtkimage.getGC().set_function(gtk.gdk.INVERT)
gtkimage.setPrompt(_('Click in the drawing area to place the second point'))
return True
def leader_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area to enter the first point'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", leader_mode_init)
_tool.setHandler("button_press", leader_first_button_press_cb)
#
# polylines
#
def polyline_motion_notify_cb(gtkimage, widget, event, tool):
_segs = []
_x1, _y1 = tool.getPoint(-1).point.getCoords()
_px1, _py1 = gtkimage.coordToPixTransform(_x1, _y1)
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
if _cp is not None:
_xc, _yc = _cp
_segs.append((_px1, _py1, _xc, _yc))
tool.setCurrentPoint(_x, _y)
_segs.append((_px1, _py1, _x, _y))
widget.window.draw_segments(_gc, _segs)
return True
def polyline_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
tool.clearCurrentPoint()
snap.setSnap(_image,tool.storePoint,_tol,None)
_state = event.state
if ((_state & gtk.gdk.SHIFT_MASK) == gtk.gdk.SHIFT_MASK):
create_entity(gtkimage)
else:
tool.setHandler("motion_notify", polyline_motion_notify_cb)
gtkimage.getGC().set_function(gtk.gdk.INVERT)
gtkimage.setPrompt(_('Click to place the next point. Shift-click to finish polyline'))
return True
def polyline_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
if _text == 'end':
create_entity(gtkimage)
else:
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setPoint(_x, _y)
tool.setHandler("motion_notify", polyline_motion_notify_cb)
gtkimage.getGC().set_function(gtk.gdk.INVERT)
gtkimage.setPrompt(_('Click to place the next point. Shift-click to finish polyline.'))
def polyline_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area to enter the first point'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", polyline_mode_init)
_tool.setHandler("entry_event", polyline_entry_event_cb)
_tool.setHandler("button_press", polyline_button_press_cb)
#
# polygons
#
def polygon_radius_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setLocation,_tol,_snapArray)
create_entity(gtkimage)
return True
def polygon_radius_motion_notify_cb(gtkimage, widget, event, tool):
_segs = []
_gc = gtkimage.getGC()
_x = int(event.x)
_y = int(event.y)
_cp = tool.getCurrentPoint()
_count = tool.getSideCount()
if _cp is not None:
_tx0, _ty0 = tool.getCoord(0)
_px0, _py0 = gtkimage.coordToPixTransform(_tx0, _ty0)
_px1 = _px0
_py1 = _py0
for _i in range(1, _count):
_txi, _tyi = tool.getCoord(_i)
_pxi, _pyi = gtkimage.coordToPixTransform(_txi, _tyi)
_segs.append((_px1, _py1, _pxi, _pyi))
_px1 = _pxi
_py1 = _pyi
_segs.append((_px1, _py1, _px0, _py0))
tool.setCurrentPoint(_x, _y)
_snapArray={'perpendicular':False,'tangent':False}
snap.setDinamicSnap(gtkimage,tool.setLocation,_snapArray)
_tx0, _ty0 = tool.getCoord(0)
_px0, _py0 = gtkimage.coordToPixTransform(_tx0, _ty0)
_px1 = _px0
_py1 = _py0
for _i in range(1, _count):
_txi, _tyi = tool.getCoord(_i)
_pxi, _pyi = gtkimage.coordToPixTransform(_txi, _tyi)
_segs.append((_px1, _py1, _pxi, _pyi))
_px1 = _pxi
_py1 = _pyi
_segs.append((_px1, _py1, _px0, _py0))
widget.window.draw_segments(_gc, _segs)
return True
def polygon_center_button_press_cb(gtkimage, widget, event, tool):
_tol = gtkimage.getTolerance()
_image = gtkimage.getImage()
_snapArray={'perpendicular':False,'tangent':False}
snap.setSnap(_image,tool.setCenter,_tol,_snapArray)
tool.setHandler("motion_notify", polygon_radius_motion_notify_cb)
tool.setHandler("button_press", polygon_radius_button_press_cb)
gtkimage.getGC().set_function(gtk.gdk.INVERT)
gtkimage.setPrompt(_('Click in the drawing area to place the second point'))
return True
def polygon_center_entry_event_cb(gtkimage, widget, tool):
_entry = gtkimage.getEntry()
_text = _entry.get_text()
_entry.delete_text(0,-1)
if len(_text):
_x, _y = make_tuple(_text, gtkimage.image.getImageVariables())
tool.setCenter(_x, _y)
tool.setHandler("motion_notify", polygon_radius_motion_notify_cb)
gtkimage.getGC().set_function(gtk.gdk.INVERT)
tool.setHandler("button_press", polygon_radius_button_press_cb)
tool.delHandler("entry_event") # ???
gtkimage.setPrompt(_('Click in the drawing area to draw the polygon'))
def polygon_mode_init(gtkimage, tool=None):
gtkimage.setPrompt(_('Click in the drawing area to define the center'))
_tool = gtkimage.getImage().getTool()
_tool.setHandler("initialize", polygon_mode_init)
_tool.setHandler("entry_event", polygon_center_entry_event_cb)
_tool.setHandler("button_press", polygon_center_button_press_cb)
#
# set the active style
#
def set_active_style(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Set Active Style'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Style:'))
_image = gtkimage.getImage()
_cur_style = _image.getOption('LINE_STYLE')
_styles = _image.getImageEntities("style")
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_styles)):
_s = _styles[_i]
if _s is _cur_style:
_idx = _i
_widget.append_text(_s.getName())
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_styles)):
_s = _styles[_i]
if _s is _cur_style:
_idx = _i
_item = gtk.MenuItem(_s.getName())
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_label, False, False, 0)
_hbox.pack_start(_widget, True, True, 0)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected widget: " + `type(_widget)`
_image.setOption('LINE_STYLE', _styles[_idx])
_dialog.destroy()
#
# set the current color
#
def set_active_color(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.ColorSelectionDialog(_('Set Active Color'))
_dialog.set_transient_for(_window)
_colorsel = _dialog.colorsel
_image = gtkimage.getImage()
_prev_color = _image.getOption('LINE_COLOR')
_gtk_color = gtkimage.getColor(_prev_color)
_colorsel.set_previous_color(_gtk_color)
_colorsel.set_current_color(_gtk_color)
_colorsel.set_has_palette(True)
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_gtk_color = _colorsel.get_current_color()
_r = int(round((_gtk_color.red/65535.0) * 255.0))
_g = int(round((_gtk_color.green/65535.0) * 255.0))
_b = int(round((_gtk_color.blue/65535.0) * 255.0))
_color = None
for _c in _image.getImageEntities('color'):
if _c.r == _r and _c.g == _g and _c.b == _b:
_color = _c
break
if _color is None:
_color = color.Color(_r, _g, _b)
_image.setOption('LINE_COLOR', _color)
_dialog.destroy()
#
# set the current linetype
#
def set_active_linetype(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Set Active Linetype'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Linetype:'))
_hbox.pack_start(_label, False, False, 0)
_image = gtkimage.getImage()
_cur_linetype = _image.getOption('LINE_TYPE')
_linetypes = _image.getImageEntities("linetype")
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_linetypes)):
_lt = _linetypes[_i]
if _lt is _cur_linetype:
_idx = _i
_widget.append_text(_lt.getName())
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_linetypes)):
_lt = _linetypes[_i]
if _lt is _cur_linetype:
_idx = _i
_item = gtk.MenuItem(_lt.getName())
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_hbox.pack_start(_widget, True, True, 0)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if isinstance(_widget, gtk.ComboBox):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected widget: " + `type(_widget)`
_image.setOption('LINE_TYPE', _linetypes[_idx])
_dialog.destroy()
#
# set the current line thickness
#
def move_cursor(entry):
entry.set_position(-1)
return False
def thickness_activate(entry): # this probably isn't a good choice ...
entry.stop_emission("activate")
def thickness_focus_out(entry, event):
_text = entry.get_text()
if _text == '-' or _text == '+':
entry.delete_text(0, -1)
return False
def thickness_insert_text(entry, new_text, new_text_length, position):
if (new_text.isdigit() or
new_text == '.' or
new_text == '+'):
_string = entry.get_text() + new_text[:new_text_length]
_hid = entry.get_data('handlerid')
entry.handler_block(_hid)
try:
_pos = entry.get_position()
if _string == '+':
_pos = entry.insert_text(new_text, _pos)
else:
try:
_val = float(_string)
_pos = entry.insert_text(new_text, _pos)
except StandardError, e:
pass
finally:
entry.handler_unblock(_hid)
if hasattr(gobject, 'idle_add'):
gobject.idle_add(move_cursor, entry)
else:
gtk.idle_add(move_cursor, entry)
entry.stop_emission("insert-text")
def set_line_thickness(gtkimage):
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Set Line Thickness'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK,
gtk.RESPONSE_OK,
gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL))
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_dialog.vbox.pack_start(_hbox, False, False, 0)
_label = gtk.Label(_('Thickness:'))
_hbox.pack_start(_label, False, False, 0)
_image = gtkimage.getImage()
_thickness = "%g" % _image.getOption('LINE_THICKNESS')
_entry = gtk.Entry()
_entry.set_text(_thickness)
_entry.connect("focus_out_event", thickness_focus_out)
_entry.connect("activate", thickness_activate)
_handlerid = _entry.connect("insert-text", thickness_insert_text)
_entry.set_data('handlerid', _handlerid)
_hbox.pack_start(_entry, True, True, 0)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_text = _entry.get_text()
_thickness = float(_text)
_image.setOption('LINE_THICKNESS', _thickness)
_dialog.destroy()
#
def _selectColor(button):
_s = _('Select Color')
_da = button.get_child().get_child()
_color = _da.get_style().bg[gtk.STATE_NORMAL]
_dialog = gtk.ColorSelectionDialog(_s)
_colorsel = _dialog.colorsel
_colorsel.set_previous_color(_color)
_colorsel.set_current_color(_color)
_colorsel.set_has_palette(True)
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_r, _g, _b = _get_rgb_values(_colorsel.get_current_color())
_str = "#%02x%02x%02x" % (_r, _g, _b)
_color = gtk.gdk.color_parse(_str)
_da.modify_bg(gtk.STATE_NORMAL, _color)
_dialog.destroy()
def _fill_color_dialog(dvbox, widgets):
_lsg = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Color Settings'))
_frame.set_border_width(2)
_vbox = gtk.VBox(False, 2)
_vbox.set_border_width(2)
_frame.add(_vbox)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, True, True, 2)
_label = gtk.Label(_('Inactive Layer Color:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = widgets['INACTIVE_LAYER_COLOR']
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, True, True, 2)
_label = gtk.Label(_('Background Color:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = widgets['BACKGROUND_COLOR']
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, True, True, 2)
_label = gtk.Label(_('Single Point Color:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = widgets['SINGLE_POINT_COLOR']
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, True, True, 2)
_label = gtk.Label(_('Multi-Point Color:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = widgets['MULTI_POINT_COLOR']
_hbox.pack_start(_widget, False, False, 2)
#
dvbox.pack_start(_frame, False, False, 2)
def _selectColor(button):
_s = _('Select Color')
_da = button.get_child().get_child()
_color = _da.get_style().bg[gtk.STATE_NORMAL]
_dialog = gtk.ColorSelectionDialog(_s)
_colorsel = _dialog.colorsel
_colorsel.set_previous_color(_color)
_colorsel.set_current_color(_color)
_colorsel.set_has_palette(True)
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
_r, _g, _b = _get_rgb_values(_colorsel.get_current_color())
_str = "#%02x%02x%02x" % (_r, _g, _b)
_color = gtk.gdk.color_parse(_str)
_da.modify_bg(gtk.STATE_NORMAL, _color)
_dialog.destroy()
def _get_color_da():
_widget = gtk.Button()
_frame = gtk.Frame()
_frame.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
_frame.set_border_width(5)
_widget.add(_frame)
_da = gtk.DrawingArea()
_da.set_size_request(20, 10)
_widget.connect('clicked', _select_color)
_frame.add(_da)
return _widget
def _get_widget(col):
if hasattr(gtk, 'ColorButton'):
_widget = gtk.ColorButton()
_widget.set_color(col)
else:
_widget = _get_color_da()
_widget.modify_bg(gtk.STATE_NORMAL, col)
return _widget
def _get_color_widgets(opts, im):
_widgets = {}
for _opt in opts:
_color = gtk.gdk.color_parse(str(im.getOption(_opt)))
_widgets[_opt] = _get_widget(_color)
return _widgets
def _get_color(widgets, key):
_widget = widgets[key]
if hasattr(gtk, 'ColorButton'):
_color = _widget.get_color()
elif isinstance(_widget, gtk.Button):
_da = _widget.getChild().getChild()
_color= _da.get_style().bg[gtk.STATE_NORMAL]
else:
raise TypeError, "Unexpected widget for '%s': " + (_key, `type(_widget)`)
return _color
def set_colors_dialog(gtkimage):
_opts = ['INACTIVE_LAYER_COLOR',
'BACKGROUND_COLOR',
'SINGLE_POINT_COLOR',
'MULTI_POINT_COLOR']
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Color Settings'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_image = gtkimage.getImage()
_widgets = _get_color_widgets(_opts, _image)
_fill_color_dialog(_dialog.vbox, _widgets)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
for _opt in _opts:
_color = _get_color(_widgets, _opt)
_r = int(round((_color.red/65535.0) * 255.0))
_g = int(round((_color.green/65535.0) * 255.0))
_b = int(round((_color.blue/65535.0) * 255.0))
if (_r, _g, _b) != _image.getOption(_opt).getColors():
_image.setOption(_opt, color.Color(_r, _g, _b))
_widgets.clear()
_dialog.destroy()
#
def _size_move_cursor(entry):
entry.set_position(-1)
return False
def _size_entry_activate(entry):
_text = entry.get_text()
entry.delete_text(0, -1)
if len(_text):
if _text == '-' or _text == '+':
sys.stderr.write("Incomplete value: '%s'\n" % _text)
else:
try:
_value = float(_text)
except:
sys.stderr.write("Invalid float: '%s'\n" % _text)
else:
sys.stderr.write("Empty entry box.")
def _size_entry_focus_out(entry, event, text=''):
_text = entry.get_text()
if _text == '' or _text == '+':
_size = entry.get_data('size')
_hid = entry.get_data('handlerid')
entry.delete_text(0, -1)
entry.handler_block(_hid)
try:
entry.set_text(_size)
finally:
entry.handler_unblock(_hid)
return False
def _size_entry_insert_text(entry, new_text, new_text_length, position):
if (new_text.isdigit() or
new_text == '.' or
new_text == '+'):
_string = entry.get_text() + new_text[:new_text_length]
_hid = entry.get_data('handlerid')
_move = True
entry.handler_block(_hid)
try:
_pos = entry.get_position()
if _string == '+':
_pos = entry.insert_text(new_text, _pos)
else:
try:
_val = float(_string)
except StandardError, e:
_move = False
else:
_pos = entry.insert_text(new_text, _pos)
finally:
entry.handler_unblock(_hid)
if _move:
if hasattr(gobject, 'idle_add'):
gobject.idle_add(_size_move_cursor, entry)
else:
gtk.idle_add(_size_move_cursor, entry)
entry.stop_emission('insert-text')
def _fill_size_dialog(dvbox, widgets):
_lsg = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL)
_frame = gtk.Frame(_('Size Settings'))
_frame.set_border_width(2)
_vbox = gtk.VBox(False, 2)
_vbox.set_border_width(2)
_frame.add(_vbox)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, True, True, 2)
_label = gtk.Label(_('Chamfer length:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = widgets['CHAMFER_LENGTH']
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, True, True, 2)
_label = gtk.Label(_('Fillet Radius:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = widgets['FILLET_RADIUS']
_hbox.pack_start(_widget, False, False, 2)
#
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, True, True, 2)
_label = gtk.Label(_('Leader Arrow Size:'))
_lsg.add_widget(_label)
_hbox.pack_start(_label, False, False, 2)
_widget = widgets['LEADER_ARROW_SIZE']
_hbox.pack_start(_widget, False, False, 2)
#
dvbox.pack_start(_frame, False, False, 2)
def set_sizes_dialog(gtkimage):
_opts = ['CHAMFER_LENGTH',
'FILLET_RADIUS',
'LEADER_ARROW_SIZE']
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Size Settings'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_image = gtkimage.getImage()
_widgets = {}
for _opt in _opts:
_val = _image.getOption(_opt)
_entry = gtk.Entry()
_sval = "%f" % _val
_entry.set_data('size', _sval)
_entry.set_text(_sval)
_handlerid = _entry.connect('insert-text', _size_entry_insert_text)
_entry.set_data('handlerid', _handlerid)
_entry.connect('activate', _size_entry_activate)
_entry.connect('focus-out-event', _size_entry_focus_out)
_widgets[_opt] = _entry
_fill_size_dialog(_dialog.vbox, _widgets)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
for _opt in _opts:
_text = _widgets[_opt].get_text()
_ival = _image.getOption(_opt)
if len(_text) and _text != '+':
_value = float(_text)
else:
_value = _ival
if abs(_value - _ival) > 1e-10:
_image.setOption(_opt, _value)
_widgets.clear()
_dialog.destroy()
#
def set_toggle_dialog(gtkimage):
_opts = ['AUTOSPLIT', 'HIGHLIGHT_POINTS']
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Operation Settings'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_image = gtkimage.getImage()
_widgets = {}
for _opt in _opts:
_val = _image.getOption(_opt)
if _opt == 'AUTOSPLIT':
_str = _('New Points split existing entities')
else:
_str = _('Boxes are drawn around Point objects')
_cb = gtk.CheckButton(_str)
_cb.set_active(_val)
_widgets[_opt] = _cb
_frame = gtk.Frame(_('Operation Settings'))
_frame.set_border_width(2)
_vbox = gtk.VBox(False, 2)
_vbox.set_border_width(2)
_frame.add(_vbox)
_vbox.pack_start(_widgets['AUTOSPLIT'], True, True, 2)
_vbox.pack_start(_widgets['HIGHLIGHT_POINTS'], True, True, 2)
_dialog.vbox.pack_start(_frame, False, False, 2)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
for _opt in _opts:
_val = _widgets[_opt].get_active()
_image.setOption(_opt, _val)
_widgets.clear()
_dialog.destroy()
def set_units_dialog(gtkimage):
_units = units.Unit.getUnitStrings()
_window = gtkimage.getWindow()
_dialog = gtk.Dialog(_('Image Units'), _window,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_OK,
gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
_image = gtkimage.getImage()
_unit = _image.getUnits()
_idx = 0
if hasattr(gtk, 'ComboBox'): # PyGTK 2.4
_widget = gtk.combo_box_new_text()
for _i in range(len(_units)):
_ui = _units[_i]
if _unit == units.Unit.getUnitFromString(_ui):
_idx = _i
_widget.append_text(_ui)
_widget.set_active(_idx)
else:
_menu = gtk.Menu()
for _i in range(len(_units)):
_ui = _units[_i]
if _unit is _units.Unit.getUnitFromString(_ui):
_idx = _i
_item = gtk.MenuItem(_ui)
_menu.append(_item)
_widget = gtk.OptionMenu()
_widget.set_menu(_menu)
_widget.set_history(_idx)
_vbox = _dialog.vbox
_vbox.set_border_width(5)
_hbox = gtk.HBox(False, 2)
_hbox.set_border_width(2)
_vbox.pack_start(_hbox, True, True, 2)
_label = gtk.Label(_('Units:'))
_hbox.pack_start(_label, False, False, 2)
_hbox.pack_start(_widget, False, False, 2)
_dialog.show_all()
_response = _dialog.run()
if _response == gtk.RESPONSE_OK:
if hasattr(gtk, 'ComboBox'):
_idx = _widget.get_active()
elif isinstance(_widget, gtk.OptionMenu):
_idx = _widget.get_history()
else:
raise TypeError, "Unexpected widget " + `type(_widget)`
_val = units.Unit.getUnitFromString(_units[_idx])
if _val != _unit:
_image.setUnits(_val)
_dialog.destroy()
PythonCAD-DS1-R37/PythonCAD/Interface/__init__.py 0000644 0001750 0001750 00000000263 11307666657 020775 0 ustar matteo matteo #
# Copyright (c) 2002, Art Haas
#
#
# don't define an __all__ variable - the value of importing
# different front-end interfaces into a module seems very
# low right now ...
#
PythonCAD-DS1-R37/PythonCAD/Interface/Cocoa/ 0000755 0001750 0001750 00000000000 11307677001 017670 5 ustar matteo matteo PythonCAD-DS1-R37/PythonCAD/Interface/Cocoa/LayerView.py 0000644 0001750 0001750 00000006556 11307666657 022204 0 ustar matteo matteo #
# Copyright (c) 2002-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
#
# Subclass of NSOutlineView, used to diplay layers in image
#
from PythonCAD.Interface.Cocoa import Globals
import PythonCAD.Generic.layer
from AppKit import NSOutlineView, NSMenu, NSMenuItem
class LayerOutlineView(NSOutlineView):
""" Subclass of NSOutlineView, used to display layers
The purpose of the subclass is primarily to allow custom
context menus for the layer items.
"""
def menuForEvent_(self, event):
_point = self.convertPoint_fromView_(event.locationInWindow(), None)
_index = self.rowAtPoint_(_point)
if -1 == _index:
return None
if not self.isRowSelected_(_index):
self.selectRow_byExtendingSelection_(_index, False)
_item = self.itemAtRow_(_index)
_layer = Globals.unwrap(_item)
if not isinstance(_layer, PythonCAD.Generic.layer.Layer):
raise TypeError, "Invalid Layer: " + `_layer`
_menu = NSMenu.alloc().initWithTitle_("Context")
_menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Rename", "EditLayerName:", "")
_menu.addItem_(_menuItem)
if _layer.isVisible():
_menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Hide", "HideLayer:", "")
else:
_menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Show", "ShowLayer:", "")
_menuItem.setRepresentedObject_(_item)
_menu.addItem_(_menuItem)
_menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Add Child Layer", "AddChildLayer:", "")
_menuItem.setRepresentedObject_(_item)
_menu.addItem_(_menuItem)
_menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Clear", "ClearLayer:", "")
_menuItem.setRepresentedObject_(_item)
_menu.addItem_(_menuItem)
if _layer.hasChildren():
_menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Hide Children", "HideChildLayers:", "")
_menuItem.setRepresentedObject_(_item)
_menu.insertItem_atIndex_(_menuItem, 3)
_menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Show Children", "ShowChildLayers:", "")
_menuItem.setRepresentedObject_(_item)
_menu.insertItem_atIndex_(_menuItem, 4)
elif _layer.getParentLayer() is not None:
_menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Delete", "DeleteLayer:", "")
_menuItem.setRepresentedObject_(_item)
_menu.addItem_(_menuItem)
return _menu
PythonCAD-DS1-R37/PythonCAD/Interface/Cocoa/CocoaPrompt.py 0000644 0001750 0001750 00000013323 11307666657 022511 0 ustar matteo matteo #
# Copyright (c) 2003 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
#
#
# This code handles interpreting entries in the gtkimage.entry box
# and calling the apprpriate internal command
#
# Author: David Broadwell ( dbroadwell@mindspring.com, 05/26/2003 )
#
''' 05/29/03 R2c Complete redesign, no longer does the internal name
need to be a function, dropped prompt.py filesize from 9.8 to
5.3Kb! cleaned up the feywords file, no appreciable difference
Used a dictionary instead of discreet functions for every entry
and for R3, menus. '''
def lookup(text):
"""Interface to promptdef dictionary, returns code by keyword definition
lookup(text)
"""
assert text in promptdefs, "No command for %s" % str(text)
return promptdefs[text]
promptdefs = {
'acline' : "NSApp.sendAction_to_from_(\"drawACLine:\", None, self)",
'arcc' : "NSApp.sendAction_to_from_(\"drawArc:\", None, self)",
'ccircen' : "NSApp.sendAction_to_from_(\"drawCCircleCenter:\", None, self)",
'ccir2p' : "NSApp.sendAction_to_from_(\"drawCCircle2Point:\", None, self)",
'chamfer' : "NSApp.sendAction_to_from_(\"drawChamfer:\", None, self)",
'close' : "NSApp.sendAction_to_from_(\"performClose:\", None, self)",
'circen' : "NSApp.sendAction_to_from_(\"drawCircleCentered:\", None, self)",
'cir2p' : "NSApp.sendAction_to_from_(\"drawCircle2Point:\", None, self)",
'cl' : "NSApp.sendAction_to_from_(\"draw2PointCLine:\", None, self)",
'cut' : "NSApp.sendAction_to_from_(\"cut:\", None, self)",
'copy' : "NSApp.sendAction_to_from_(\"copy:\", None, self)",
'delete' : "NSApp.sendAction_to_from_(\"delete:\", None, self)",
'dimpref' : "NSApp.sendAction_to_from_(\"dimension_prefs_cb(None)",
'fillet' : "NSApp.sendAction_to_from_(\"drawFillet:\", None, self)",
'hcline' : "NSApp.sendAction_to_from_(\"drawHCLine:\", None, self)",
'leader' : "NSApp.sendAction_to_from_(\"drawLeader:\", None, self)",
'mirror' : "NSApp.sendAction_to_from_(\"modifyMirror:\", None, self)",
'moveh' : "NSApp.sendAction_to_from_(\"modifyMoveHorizontal:\", None, self)",
'movev' : "NSApp.sendAction_to_from_(\"modifyMoveVertical:\", None, self)",
'move' : "NSApp.sendAction_to_from_(\"modifyMoveFree:\", None, self)",
'new' : "NSApp.sendAction_to_from_(\"newDocument:\", None, self)",
'opend' : "NSApp.sendAction_to_from_(\"openDocument:\", None, self)",
'paste' : "NSApp.sendAction_to_from_(\"paste:\", None, self)",
'pcline' : "NSApp.sendAction_to_from_(\"drawPerpendicularCLine:\", None, self)",
'point' : "NSApp.sendAction_to_from_(\"drawPoint:\", None, self)",
'polyline' : "NSApp.sendAction_to_from_(\"drawPolyline:\", None, self)",
'polygon' : "NSApp.sendAction_to_from_(\"drawPolygon:\", None, self)",
'polygonext' : "NSApp.sendAction_to_from_(\"drawPolygonExternal:\", None, self)",
'pref' : "NSApp.sendAction_to_from_(\"prefs_cb(None)",
'rect' : "NSApp.sendAction_to_from_(\"drawRect:\", None, self)",
'redraw' : "self.document().getDA().setNeedsDisplay_(True)",
'redo ' : "NSApp.delegate().redo_(None)",
'refresh' : "self.document().getDA().setNeedsDisplay_(True)",
'saa' : "NSApp.sendAction_to_from_(\"select_all_arcs_cb(None)",
'saacl' : "NSApp.sendAction_to_from_(\"select_all_aclines_cb(None)",
'sac' : "NSApp.sendAction_to_from_(\"select_all_circles_cb(None)",
'sacc' : "NSApp.sendAction_to_from_(\"select_all_ccircles_cb(None)",
'sacl' : "NSApp.sendAction_to_from_(\"select_all_clines_cb(None)",
'sahcl' : "NSApp.sendAction_to_from_(\"select_all_hclines_cb(None)",
'sap' : "NSApp.sendAction_to_from_(\"select_all_points_cb(None)",
'sas' : "NSApp.sendAction_to_from_(\"select_all_segments_cb(None)",
'savcl' : "NSApp.sendAction_to_from_(\"select_all_vclines_cb(None)",
'saveas' : "NSApp.sendAction_to_from_(\"saveDocumentAs:\", None, self)",
'saves' : "NSApp.sendAction_to_from_(\"saveDocument:\", None, self)",
'savel' : "NSApp.sendAction_to_from_(\"saveLayerAs:\", None, self)",
'segment' : "NSApp.sendAction_to_from_(\"drawSegment:\", None, self)",
'split' : "NSApp.sendAction_to_from_(\"modifySplit:\", None, self)",
'strh' : "NSApp.sendAction_to_from_(\"modifyStretchHorizontal:\", None, self)",
'strv' : "NSApp.sendAction_to_from_(\"modifyStretchVertical:\", None, self)",
'str' : "NSApp.sendAction_to_from_(\"modifyStretchFree:\", None, self)",
'tcline' : "NSApp.sendAction_to_from_(\"drawTanCLine:\", None, self)",
'text' : "NSApp.sendAction_to_from_(\"drawText:\", None, self)",
'transfer' : "NSApp.sendAction_to_from_(\"modifyTransfer:\", None, self)",
'undo' : "NSApp.delegate().undo_(None)",
'vcline' : "NSApp.sendAction_to_from_(\"drawVCLine:\", None, self)",
'quit' : "NSApp.sendAction_to_from_(\"terminate:\", None, self)",
'zoomd' : "NSApp.sendAction_to_from_(\"windowZoom:\", None, self)",
'zoomi' : "NSApp.sendAction_to_from_(\"windowZoomIn:\", None, self)",
'zoomo' : "NSApp.sendAction_to_from_(\"windowZoomOut:\", None, self)",
'zoomf' : "NSApp.sendAction_to_from_(\"windowZoomFit:\", None, self)"
}
PythonCAD-DS1-R37/PythonCAD/Interface/Cocoa/MainMenu.nib/ 0000755 0001750 0001750 00000000000 11307677001 022150 5 ustar matteo matteo PythonCAD-DS1-R37/PythonCAD/Interface/Cocoa/MainMenu.nib/classes.nib 0000644 0001750 0001750 00000004177 11307666657 024327 0 ustar matteo matteo {
IBClasses = (
{
ACTIONS = {
dimensionAngular = id;
dimensionHorizontal = id;
dimensionLinear = id;
dimensionRadial = id;
dimensionVertical = id;
draw2PointCLine = id;
drawACLine = id;
drawArc = id;
drawCCircle1Tan = id;
drawCCircle2Point = id;
drawCCircle2Tan = id;
drawCCircleCenter = id;
drawChamfer = id;
drawCircle2Point = id;
drawCircleCentered = id;
drawFillet = id;
drawHCLine = id;
drawLeader = id;
drawParallelCLine = id;
drawPerpendicularCLine = id;
drawPoint = id;
drawPolygon = id;
drawPolygonExternal = id;
drawPolyline = id;
drawRect = id;
drawSegment = id;
drawTan2CircleCLine = id;
drawTanCLine = id;
drawText = id;
drawTextSheetCancel = id;
drawTextSheetOK = id;
drawVCLine = id;
modifyMirror = id;
modifyMoveFree = id;
modifyMoveHorizontal = id;
modifyMoveVertical = id;
modifySplit = id;
modifyStretchFree = id;
modifyStretchHorizontal = id;
modifyStretchVertical = id;
modifyTransfer = id;
redo = id;
saveLayerAs = id;
undo = id;
windowZoom = id;
windowZoomFit = id;
windowZoomIn = id;
windowZoomOut = id;
};
CLASS = AppController;
LANGUAGE = ObjC;
OUTLETS = {polygonPanel = NSPanel; textSheet = NSWindow; };
SUPERCLASS = NSObject;
},
{CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }
);
IBVersion = 1;
} PythonCAD-DS1-R37/PythonCAD/Interface/Cocoa/MainMenu.nib/keyedobjects.nib 0000644 0001750 0001750 00000073306 11307666657 025345 0 ustar matteo matteo bplist00
Y$archiverX$versionT$topX$objects_NSKeyedArchiver ]IB.objectdataR + / 3 : = ? C G !"$(,012479:<?CDEFILDMNQSTUX[\]^adefgjmnopsvwxy| "%'(*-012479;>@ACFHJMPQRTXZ[]^_behijmopqtvwx{}~
#$%(+,-023479:;?VWXY[chpq
'*-124567:;>@ACDFGJTUVWX[aefuvw{~z "#$'456()+,./121416F8;>ABCFHILNORTUVY[\]C_behijmopqtvwx{~3Q<>@BFGHIKNO=GRUGVWY\G]^`abcfGfgilGmqrstwGxy{|~vGGGGoGGGGGUGG GG!G!"$%')+JL]NPQSUWX}Y[\]^_`bdefghijl[pqrtK
! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? @ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ U$null
! " # $ % &