File: gtkimage.py

package info (click to toggle)
pythoncad 0.1.35-4
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 3,536 kB
  • ctags: 4,286
  • sloc: python: 62,752; sh: 743; makefile: 39
file content (1184 lines) | stat: -rw-r--r-- 41,795 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
#
# 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
#

from __future__ import division

import math
import types

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.tools import Tool
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.
    """
    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("Untitled")
        self.__window.connect("destroy", self.__destroyEvent)
        self.__window.connect("event", self.__windowEvent)
        self.__window.connect("key_press_event", self.__keyPressEvent)
        _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

        #
        # our tool used to draw stuff
        #

        self.__tool = None

        #
        # 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)

        _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):
        self.close()
        for _i in xrange(len(globals.imagelist)):
            _gimage = globals.imagelist[_i]
            if self 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.__tool
        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()
                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.__tool
                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
                        _cmd = prompt.lookup(_opt)
                        # print "cmd: '%s'" % _cmd
                        eval(_cmd) # this will go away ...
                    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.__tool
        if _type == 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)
        elif _type == 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)
        elif _type == 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)
        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")
                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"):
                _rv = _tool.getHandler("key_press")(self, widget,
                                                    event, _tool)
            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:
            self.setToolpoint(event)
            _rv = True
        elif _type == gtk.gdk.LEAVE_NOTIFY:
            self.setToolpoint(event)
            _rv = True
        else:
            debug_print("Got type %d" % _type)
            pass
        return _rv

    #------------------------------------------------------------------
    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.
        """
        if not isinstance(tool, Tool):
            raise TypeError, "Invalid tool: " + str(tool)
        self.__tool = tool

    #------------------------------------------------------------------
    def getTool(self):
        """Return the current Tool used in the drawing.

getTool()
        """
        return self.__tool

    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.

redraw()
        """
        _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 reset(self):
        """Set the image to an initial drawing state.

reset()
        """
        if self.__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 self.__tool is None:
                debug_print(".....This is second time to be in reset")
                self.__image.clearSelectedObjects()
        self.__tool = None
        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 __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)

#------------------------------------------------------------------
def debug_print(string):
    if _debug is True:
        print "SDB Debug: " + string