File: OGLViews.py

package info (click to toggle)
boa-constructor 0.3.0-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 8,188 kB
  • ctags: 8,857
  • sloc: python: 54,163; sh: 66; makefile: 36
file content (922 lines) | stat: -rw-r--r-- 33,528 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
#----------------------------------------------------------------------
# Name:        OGLViews.py
# Purpose:     Diagrammatic views on the source using the OGL lib.
#
# Author:      Riaan Booysen
#
# Created:     1999
# RCS-ID:      $Id: OGLViews.py,v 1.21 2004/08/16 13:07:41 riaan Exp $
# Copyright:   (c) 1999 - 2004 Riaan Booysen
# Licence:     GPL
#----------------------------------------------------------------------
print 'importing Views.OGLViews'

import pickle, os

from wxPython.wx import *
from wxPython.ogl import *

import Preferences, Utils

from Preferences import IS

import EditorViews

# XXX It would be better to not apply persistent positions after creating shapes,
# XXX but to use positions when shape is created

# XXX Bug on right click in background

# Wishlist
# * Is the topological layout applicable to import diagrams? (They can be cyclic)
# * Optional hiding of classes in UMLView

wxOGLInitialize()

class RoundedRectangleShape(wxRectangleShape):
    def __init__(self, w=0.0, h=0.0):
        wxRectangleShape.__init__(self, w, h)
        self.SetCornerRadius(-0.3)

class MyEvtHandler(wxShapeEvtHandler):
    def OnLeftClick(self, x, y, keys = 0, attachment = 0):
        shape = self.GetShape()
        canvas = shape.GetCanvas()
        dc = wxClientDC(canvas)
        canvas.PrepareDC(dc)

        if shape.Selected():
            shape.Select(false, dc)
            canvas.Redraw(dc)
        else:
            redraw = false
            shapeList = canvas.GetDiagram().GetShapeList()
            toUnselect = []
            for s in shapeList:
                try:
                    if s and s.Selected():
                        # If we unselect it now then some of the objects in
                        # shapeList will become invalid (the control points are
                        # shapes too!) and bad things will happen...
                        toUnselect.append(s)
                except Exception, message: pass#print Exception, message

            shape.Select(true, dc)

            if toUnselect:
                for s in toUnselect:
                    s.Select(false, dc)
                canvas.Redraw(dc)

    def OnEndDragLeft(self, x, y, keys = 0, attachment = 0):
        shape = self.GetShape()
        self.base_OnEndDragLeft(x, y, keys, attachment)
        if not shape.Selected():
            self.OnLeftClick(x, y, keys, attachment)

    def OnSize(self, x, y):
        self.base_OnSize(x, y)

    def OnRightClick(self, x, y, keys, attachment):
        shape = self.GetShape()
        if not shape.Selected():
            self.OnLeftClick(x, y, keys, attachment)

        if hasattr(self, 'menu') and self.menu:
            shape.GetCanvas().PopupMenu(self.menu, wxPoint(x, y))

    def OnRightDown(self, event):
        print "OnRightDown", event

#----------------------------------------------------------------------

incy = 45

class PersistentShapeCanvas(wxShapeCanvas):
    ext = '.lay'
    def __init__(self, parent, shapes):
        wxShapeCanvas.__init__(self, parent, style = 0)
        self.SetBackgroundColour(Preferences.vpOGLCanvasBackgroundColour)
        self.shapes = shapes

    def saveSizes(self, filename):
        """ Build a picklable dictionary of sizes/positions and save. """
        persProps = {}

        for shape in self.shapes:
            try:
                if hasattr(shape, 'unqPclName'):
                    persProps[shape.unqPclName] = shape.getPos()
            except:
                print 'error:', shape
                raise

        from Explorers.Explorer import openEx
        t = openEx(filename)
        t.save(t.currentFilename(), pickle.dumps(persProps))

    def printSizes(self, filename):
        """ Export the Canvas to Postscript """
        prdata=wxPrintData()
        from Explorers.Explorer import openEx
        t=openEx(filename)
        prdata.SetFilename(t.currentFilename())
        dc=wxPostScriptDC(prdata)
        if dc.Ok():
            dc.StartDoc('Export')
            self.Redraw(dc)
            dc.EndDoc()
            
            wxLogMessage('Exported %s'%filename)

    def loadSizes(self, filename):
        from Explorers.Explorer import openEx, TransportError
        t = openEx(filename)
        try:
            persProps = pickle.loads(t.load())
        except SyntaxError:
            if wxMessageBox('%s is possibly corrupt (cannot be unpickled), delete it?'\
                            'Default layout will be used.'%filename,
                  'Corrupt file', style = wxYES_NO | wxICON_EXCLAMATION) == wxYES:
                # XXX Just lazy, must fix to use transport !!
                if filename[:7] != 'file://':
                    wxLogMessage('Sorry, only supported on the filesystem')
                else:
                    os.remove(filename[7:])

            raise TransportError('Corrupt layout file')

        unmatchedPcls = persProps.keys()
        matchedShapes = []

        for shape in self.shapes:
            if persProps.has_key(shape.unqPclName):
                unmatchedPcls.remove(shape.unqPclName)
            else:
                unmatchedPcls.append(shape.unqPclName)

        for shape in self.shapes:
            if persProps.has_key(shape.unqPclName):
                pos = persProps[shape.unqPclName]
                shape.setPos(pos)

        self.redraw()

    def redraw(self):
        diagram = self.GetDiagram()
        canvas = diagram.GetCanvas()
        dc = wxClientDC(canvas)
        canvas.PrepareDC(dc)
        for shape in self.shapes:
            shape.Move(dc, shape.GetX(), shape.GetY())
#            shape.SetRegionSizes()
        diagram.Clear(dc)
        diagram.Redraw(dc)

class PerstShape:
    def __init__(self, unqPclName):
        self.unqPclName = unqPclName

    def setPos(self, pos):
        """Must be implemented for any class deriving from it, called
         after reading positions from pickle."""

    def getPos(self, pos):
        """Must be implemented for any class deriving from it, called
         before reading sizes into pickle."""


class PerstDividedShape(wxDividedShape, PerstShape):
    def __init__(self, unqPclName, width, height):
        wxDividedShape.__init__(self, width, height)
        PerstShape.__init__(self, unqPclName)

    def setPos(self, pos):
        '''Pos for divide shape, format:
         (width, height)'''

        self.SetX(pos[0])
        self.SetY(pos[1])


    def getPos(self):
        """Pos for divide shape, format:
         (width, height)"""

        return (self.GetX(), self.GetY())

    def FlushText(self):
        """This method retrieves the text from the shape
        regions and draws it. There seems to be a problem that
        the text is not normally drawn. """
        canvas = self.GetCanvas()
        dc = wxClientDC(canvas)
        canvas.PrepareDC(dc)
        count = 0
        for region in self.GetRegions():
            region.SetFormatMode(4)
            self.FormatText(dc, region.GetText(), count)
            count = count + 1

class ScrollingContainer(wxScrolledWindow):
    scrollStepX = 10
    scrollStepY = 10
    def __init__(self, parent, size):
        wxScrolledWindow.__init__(self, parent, -1, style = wxSUNKEN_BORDER)
        self.SetScrollbars(self.scrollStepX, self.scrollStepY,
                           size.x / self.scrollStepX, size.y / self.scrollStepY)

class PersistentOGLView(ScrollingContainer, EditorViews.EditorView):
    viewName = 'OGL'
    loadBmp = 'Images/Editor/Open.png'
    saveBmp = 'Images/Editor/Save.png'
    defSize = 2000

    def __init__(self, parent, model, actions = ()):
        ScrollingContainer.__init__(self, parent, wxSize(self.defSize, self.defSize))
        EditorViews.EditorView.__init__(self, model,
          (('(Re)load diagram', self.OnLoad, self.loadBmp, ''),
           ('Save diagram', self.OnSave, self.saveBmp, ''),
           ('Print diagram to PostScript', self.OnPrintToPS, '-', ''), 
           ('-', None, '-', ''),
           ('Change size', self.OnSetSize, '-', ''),
           )+actions)

        self.shapes = []
        self.canvas = PersistentShapeCanvas(self, self.shapes)
        self.canvas.SetSize(self.GetVirtualSize())

        EVT_RIGHT_UP(self.canvas, self.OnRightClick)

        self.diagram = wxDiagram()
        self.canvas.SetDiagram(self.diagram)
        self.diagram.SetCanvas(self.canvas)

        self.shapeMenu = None

        self.size = self.defSize

        self._loaded = false

        self.active = true

    def destroy(self):
        self.destroyShapes()
        self.diagram.Destroy()
        EditorViews.EditorView.destroy(self)

    def destroyShapes(self):
        self.shapes[:] = []
        self.diagram.DeleteAllShapes()

    def refreshCtrl(self):
        layoutFile = os.path.splitext(self.model.filename)[0]+self.ext
        from Explorers.Explorer import TransportError
        try:
            self.canvas.loadSizes(layoutFile)
            self._loaded = true
        except TransportError:
            self._loaded = false

    def newLine(self, dc, fromShape, toShape):
        line = wxLineShape()
        line.SetCanvas(self.canvas)
        line.SetPen(Preferences.vpOGLLinePen)
        line.SetBrush(Preferences.vpOGLLineBrush)

        line.AddArrow(ARROW_ARROW)
        #pmf = wxPseudoMetaFile()
        #pmf.LoadFromMetaFile('Images/Views/UML/inherit.wmf', 10.0, 10.0)
        #line.AddArrow(ARROW_METAFILE, mf=pmf)
        line.MakeLineControlPoints(2)
        fromShape.AddLine(line, toShape)
        self.diagram.AddShape(line)
        line.Show(true)

        # for some reason, the shapes have to be moved for the line to show up...
        fromShape.Move(dc, fromShape.GetX(), fromShape.GetY())

    def newRegion(self, font, name, textLst, maxWidth, totHeight = 10):
        region = wxShapeRegion()
        dc = wxClientDC(self.canvas)
        dc.SetFont(font)

        for text in textLst:
            w, h = dc.GetTextExtent(text)
            if w > maxWidth: maxWidth = w
            totHeight = totHeight + h + 0 # interline padding

        region.SetFont(font)
        region.SetText('\n'.join(textLst))
        #region._text = string.join(textLst, '\n')
        region.SetName(name)

        return region, maxWidth, totHeight

    def addShape(self, shape, x, y, pen, brush, text):
#        shape.SetDraggable(false)
        shape.SetCanvas(self.canvas)
        shape.SetX(x)
        shape.SetY(y)
        shape.SetPen(pen)
        shape.SetBrush(brush)
#        shape.SetFont(wxFont(6, wxMODERN, wxNORMAL, wxNORMAL, false))
        shape.AddText(text)
        shape.SetShadowMode(SHADOW_RIGHT)
        self.diagram.AddShape(shape)
        shape.Show(true)

        evthandler = MyEvtHandler()
        evthandler.menu = self.shapeMenu
        evthandler.view = self
        evthandler.SetShape(shape)
        evthandler.SetPreviousHandler(shape.GetEventHandler())
        shape.SetEventHandler(evthandler)

        self.shapes.append(shape)

        return len(self.shapes) -1

    def setSize(self, size):
        nvsx, nvsy = size.x / self.scrollStepX, size.y / self.scrollStepY
        self.Scroll(0, 0)
        self.SetScrollbars(self.scrollStepX, self.scrollStepY, nvsx, nvsy)
        self.canvas.SetSize(self.GetVirtualSize())


    def OnLoad(self, event):
        self.canvas.loadSizes(os.path.splitext(self.model.filename)[0]+self.ext)

    def OnSave(self, event):
        self.canvas.saveSizes(os.path.splitext(self.model.filename)[0]+self.ext)

    def OnPrintToPS(self, event):
        self.canvas.printSizes(os.path.splitext(self.model.filename)[0]+'.ps')

    def OnSetSize(self, event):
        dlg = wxTextEntryDialog(self, 'Enter new canvas size (width==height)',
            'Size', `self.size`)
        try:
            if dlg.ShowModal() == wxID_OK:
                self.size = int(dlg.GetValue())
                self.setSize(wxSize(self.size, self.size))
        finally:
            dlg.Destroy()

    def OnRightClick1(self, event):
        print self.canvas.HitTest(event.GetX(), event.GetX())
        event.Skip()


class SortedUMLViewMix:
    """ Currently uses topological sort to make the UML diagram
    more readily readable on load.  Also resizes the diagram
    to the space taken by the actual diagram elements so that
    very large diagrams can be accommodated.

    The resulting diagrams are far more white-space-intensive
    than the original jumbles.  A more appropriate algorithm
    may be found by someone else.
    """
    def getShapeSize( self, shape ):
        """Return the size of a shape's representation, an abstraction point"""
        return shape.GetBoundingBoxMax()
    def getCurrentShape( self, className ):
        """Attempt to retrieve an already-existing class model object, another abstraction point"""
        return self.AllClasses.get( className )

    def buildShapes( self, dc ):
        """Retrieve the current module and build the graph elements

        Where possible, re-use the already-built class shapes.
        Uses toposort to attempt to arrange the shapes after
        they have been built.
        """
        module = self.model.getModule()
        routes = []
        nodes = []
        todo = [ module.createHierarchy() ]
        while todo:
            hierarchy = todo[0]
            for className in hierarchy.keys():
                if self.getCurrentShape( className ):
                    if className not in nodes:
                        nodes.append( className )
                else:
                    # build a new node...
                    if module.classes.has_key(className):
                        # this is a local class (defined in this module)
                        classModel = module.classes[className]
                        classShape = self.newClass(
                            (20, 30), (0, 0),
                            className,
                            classModel.methods.keys(),
                            classModel.attributes.keys()
                        )
                    else:
                        # external class
                        classShape = self.newExternalClass(
                            (20, 30), (0,0),
                            className,
                        )
                    self.AllClasses[className] = classShape
                    nodes.append( className )
                    classShape.SetId(1000 + len(self.AllClasses))
                # hierarchy maps the children of the classes by name
                if hierarchy.get( className ):
                    todo.append( hierarchy.get(className) )
                    children = hierarchy.get(className).keys()
                    for child in children:
                        if (className, child) not in routes:
                            routes.append( (className, child) )
            del todo[0]
        for parent, child in routes:
            self.newLine(dc, self.getCurrentShape(child), self.getCurrentShape(parent), )
        # now make it look nice...
        self.arrangeShapes( dc, nodes, routes)

    def arrangeShapes( self, dc, nodes, routes, whiteSpaceFactor = 1.1 ):
        """Given the nodes and routes (values are names only), arrange the shapes

        This could be called as an action after the initial display if prefered.
        """
        # okay, we've now built all of the nodes and collected all routes...
        generations = sort( nodes, routes )
        # now display the generations...
        # calculate width + height of all elements
        sizes = []
        for generation in generations:
            sizes.append([])
            for child in generation:
                sizes[-1].append( self.getShapeSize(self.getCurrentShape(child)))
        # calculate total width and total height
        width = 0
        height = 0
        widths = []
        heights = []
        for generation in sizes:
            currentWidth = 0
            currentHeight = 0
            for x,y in generation:
                if y > currentHeight:
                    currentHeight = y
                currentWidth = currentWidth + x
            # update totals
            if currentWidth > width:
                width = currentWidth
            height = height + currentHeight
            # store generation info
            widths.append( currentWidth )
            heights.append( currentHeight )
        # add in some whitespace so we can see lines...
        width = width * whiteSpaceFactor
        rawHeight = height
        height = height * whiteSpaceFactor
        verticalWhiteSpace = (height-rawHeight)/(len(generations)-1.0 or 2.0)
        self.setSize(wxSize(int(width+50), int(height+50))) # fudge factors to keep some extra space
        # distribute each generation across the width
        # and the generations across height
        y = 0
        for currentWidth, currentHeight, generation in map( None, widths, heights, generations ):
            x = 0
            # whiteSpace is the space between any two elements...
            whiteSpace = (width - currentWidth)/(len(generation)-1.0 or 2.0)
            for className in generation:
                classShape = self.getCurrentShape(className)
                shapeX, shapeY = self.getShapeSize(classShape)
                # snap to diagram grid coords
                csX, csY = self.diagram.Snap((shapeX/2.0)+x, (shapeY/2.0)+y)
                # don't display until finished
                classShape.Move(dc, csX, csY, false)
                x = x + shapeX + whiteSpace
            y = y + currentHeight + verticalWhiteSpace


class RecursionError( OverflowError, ValueError ):
    """ Unable to calculate result because of recursive structure """

def sort(nodes, routes, noRecursion=0):
    """ Passed a list of node IDs and a list of source,dest ID routes
    attempt to create a list of stages where each sub list
    is one stage in a process.
    """
    children, parents = _buildChildrenLists(routes)
    # first stage is those nodes
    # having no incoming routes...
    stage = []
    stages = [stage]
    taken = []
    for node in nodes:
        if (not parents.get(node)):
            stage.append (node)
    if nodes and not stage:
        # there is no element which does not depend on
        # some other element!!!
        stage.append( nodes[0])
    taken.extend( stage )
    nodes = filter ( lambda x, l=stage: x not in l, nodes )
    while nodes:
        previousStageChildren = []
        nodelen = len(nodes)
        # second stage are those nodes
        # which are direct children of the first stage
        for node in stage:
            for child in children.get (node, []):
                if child not in previousStageChildren and child not in taken:
                    previousStageChildren.append(child)
                elif child in taken and noRecursion:
                    raise RecursionError( (child, node) )
        # unless they are children of other direct children...
        # TODO, actually do that...
        stage = previousStageChildren
        removes = []
        for current in stage:
            currentParents = parents.get( current, [] )
            for parent in currentParents:
                if parent in stage and parent != current:
                    # might wind up removing current...
                    if not current in parents.get(parent, []):
                        # is not mutually dependent...
                        removes.append( current )
        for remove in removes:
            while remove in stage:
                stage.remove( remove )
        stages.append( stage)
        taken.extend( stage )
        nodes = filter ( lambda x, l=stage: x not in l, nodes )
        if nodelen == len(nodes):
            if noRecursion:
                raise RecursionError( nodes )
            else:
                stages.append( nodes[:] )
                nodes = []
    return stages

def _buildChildrenLists (routes):
    childrenTable = {}
    parentTable = {}
    for sourceID,destinationID in routes:
        currentChildren = childrenTable.get( sourceID, [])
        currentParents = parentTable.get( destinationID, [])
        if not destinationID in currentChildren:
            currentChildren.append ( destinationID)
        if not sourceID in currentParents:
            currentParents.append ( sourceID)
        childrenTable[sourceID] = currentChildren
        parentTable[destinationID] = currentParents
    return childrenTable, parentTable

class UMLView(PersistentOGLView, SortedUMLViewMix):
    ext = '.umllay'
    viewName = 'UML'
    showAttributes = 1
    showMethods = 1
    AllClasses = {}
    toggleAttrBmp = 'Images/Views/UML/attribute.png'
    toggleMethBmp = 'Images/Views/UML/method.png'

    def __init__(self, parent, model):
        PersistentOGLView.__init__(self, parent, model, (
            ('-', None, '-', ''),
            ('Toggle Attributes', self.OnToggleAttributes, self.toggleAttrBmp, ''),
            ('Toggle Methods', self.OnToggleMethods, self.toggleMethBmp, ''),
            ('-', None, '-', ''),
            ('Force layout', self.OnForceLayout, '-', ''),
        ))
        self.menuStdClass = wxMenu()
        id = wxNewId()
        self.menuStdClass.Append(id, "Goto Source")
        EVT_MENU(self, id, self.OnGotoSource)
        id = wxNewId()
        self.menuStdClass.Append(id, "Goto Documentation",)
        EVT_MENU(self, id, self.OnGotoDoc)

        self.shapeMenu = self.menuStdClass

    def destroy(self):
        PersistentOGLView.destroy(self)
        self.menuStdClass.Destroy()

    def newClass(self, size, pos, className, classMeths, classAttrs):
        shape = PerstDividedShape(className, size[0], size[1])

        maxWidth = 10 #padding
        if not self.showAttributes: classAttrs = [' ']
        if not self.showMethods: classMeths = [' ']

        regionName, maxWidth, nameHeight = self.newRegion(
              Preferences.oglBoldFont, 'class_name', [className], maxWidth)
        regionAttribs, maxWidth, attribsHeight = self.newRegion(
              Preferences.oglStdFont, 'attributes', classAttrs, maxWidth)
        regionMeths, maxWidth, methsHeight = self.newRegion(
              Preferences.oglStdFont, 'methods', classMeths, maxWidth)

        totHeight = nameHeight + attribsHeight + methsHeight

        regionName.SetProportions(0.0, 1.0*(nameHeight/float(totHeight)))
        regionAttribs.SetProportions(0.0, 1.0*(attribsHeight/float(totHeight)))
        regionMeths.SetProportions(0.0, 1.0*(methsHeight/float(totHeight)))

        shape.AddRegion(regionName)
        shape.AddRegion(regionAttribs)
        shape.AddRegion(regionMeths)

        shape.SetSize(maxWidth + 10, totHeight + 10)

        shape.SetRegionSizes()

        idx = self.addShape(shape, pos[0], pos[1], Preferences.vpOGLClassShapePen,
          Preferences.vpOGLClassShapeBrush, '')

        shape.FlushText()

        return self.shapes[idx]

    def newExternalClass(self, size, pos, className):
        shape = PerstDividedShape(className, size[0], size[1])

        maxWidth = 10 #padding
        regionName, maxWidth, nameHeight = self.newRegion(
              Preferences.oglBoldFont, 'class_name', [className], maxWidth)
        totHeight = nameHeight
        regionName.SetProportions(0.0, 1.0*(nameHeight/float(totHeight)))
        shape.AddRegion(regionName)
        shape.SetSize(maxWidth + 10, totHeight + 10)
        shape.SetRegionSizes()

        idx = self.addShape(shape, pos[0], pos[1],
            Preferences.vpOGLExternalClassShapePen,
            Preferences.vpOGLExternalClassShapeBrush, '')

        shape.FlushText()

        return self.shapes[idx]

    def refreshCtrl(self):
        dc = wxClientDC(self.canvas)
        self.canvas.PrepareDC(dc)

        self.destroyShapes()
        self.AllClasses = {}

        # Do initial layout
        self.buildShapes(dc)
        # Try to load layout from a pickle
        PersistentOGLView.refreshCtrl(self)

    def OnToggleMethods(self, event):
        if self.showMethods == 1: self.showMethods = 0
        else: self.showMethods = 1
        return self.refreshCtrl()

    def OnToggleAttributes(self, event):
        if self.showAttributes == 1: self.showAttributes = 0
        else: self.showAttributes = 1
        return self.refreshCtrl()

    def OnGotoDoc(self, event):
        if self.menuClass:
            name = self.menuClass
            if self.model.views.has_key('Documentation') and \
              self.model.getModule().classes.has_key(name):
                srcView = self.model.views['Documentation']
                srcView.focus()
                module = self.model.getModule()
                #srcView.gotoLine(int(module.classes[name].block.start) -1)
            else:
                print "Documentation View is not open"
        else:
            print "No shape selected"

    def OnGotoSource(self, event):
        if self.menuClass:
            name = self.menuClass
            if self.model.views.has_key('Source') and \
              self.model.getModule().classes.has_key(name):
                srcView = self.model.views['Source']
                srcView.focus()
                module = self.model.getModule()
                srcView.gotoLine(int(module.classes[name].block.start) -1)
            else:
                print "No source for selection"
        else:
            print "No shape selected"

    ## This allows me to pop-up a menu for the shape. However it loses the
    ## main menu position (x, y) go to 0,0 after the skip
    def OnRightClick(self, event):
        """If the event occurs on one of our shapes, I want to pop-up a shape"""
        x, y = (event.m_x, event.m_y)
        hit = 0
        for (name, shape) in self.AllClasses.items():
            (hit, attach_point, distance) = shape.HitTest(x, y)
            if hit: break
        x, y = self.CalcScrolledPosition(x, y)
        if not hit:
            menu = self.generateMenu()
            self.PopupMenuXY(menu, x, y)
            menu.Destroy()
            return
        # If we reach this point, then we have a selected shape.
        # However, it may be a class or external
        if self.model.getModule().classes.has_key(name):
            (self.menuShape, self.menuClass) = (shape, name)
            self.PopupMenu(self.menuStdClass, wxPoint(x, y))
            (self.menuShape, self.menuClass) = (None, None)

    def OnForceLayout(self, event):
        dc = wxClientDC(self.canvas)
        self.canvas.PrepareDC(dc)

        self.destroyShapes()
        self.AllClasses = {}

        self.buildShapes(dc)

        self.canvas.redraw()

#-------------------------------------------------------------------------------

class ImportsView(PersistentOGLView):
    ext = '.implay'
    refreshBmp = 'Images/Editor/Refresh.png'
    viewName = 'Imports'

    def __init__(self, parent, model):
        PersistentOGLView.__init__(self, parent, model,
          (('-', None, '', ''),
           ('Refresh', self.OnRefresh, self.refreshBmp, ''))
        )
        self.relationships = None
        self.showImports = 1

    def newModule(self, size, pos, moduleName, importList):
        idx = self.addShape(PerstDividedShape(moduleName, size[0], size[1]),
          pos[0], pos[1],
          Preferences.vpOGLModuleShapePen,
          Preferences.vpOGLModuleShapeBrush, '')

        if not self.showImports: importList = [' ']

        maxWidth = 10 #padding

        regionName, maxWidth, nameHeight = self.newRegion(
              Preferences.oglBoldFont, 'module_name', [moduleName], maxWidth)
        regionClss, maxWidth, clssHeight = self.newRegion(
              Preferences.oglStdFont, 'methods', importList, maxWidth)

        totHeight = nameHeight + clssHeight

        regionName.SetProportions(0.0, 1.0*(nameHeight/float(totHeight)))
        regionClss.SetProportions(0.0, 1.0*(clssHeight/float(totHeight)))

        shape = self.shapes[idx]
        shape.AddRegion(regionName)
        shape.AddRegion(regionClss)

        shape.SetSize(maxWidth + 10, totHeight + 10)

        shape.SetRegionSizes()
        shape.FlushText()

        return shape, maxWidth + 10

    def refreshCtrl(self):
        dc = wxClientDC(self)
        self.PrepareDC(dc)

        # Because of slow building process, cache after first time
        if not self.relationships:
            relations = self.model.buildImportRelationshipDict()
            self.relationships = relations
            self.destroyShapes()
        else:
            return
            #relations = self.relationships

        shapes = {}
        p = 10
        y = 20
        if hasattr(self.model, 'packageName'):
            packageName = self.model.packageName
        else:
            packageName = ''
        # Add shapes
        for rel in relations.keys():
            impLst = []
            for i in relations[rel].imports.keys():
                if i.startswith(packageName+'.'):
                    i = i[len(packageName)+1:]
                if relations.has_key(i):
                    impLst.append(i)
            for i in relations[rel].from_imports.keys():
                if i.startswith(packageName+'.'):
                    i = i[len(packageName)+1:]
                if relations.has_key(i):
                    impLst.append(i)

            shape, width = self.newModule((20, 30), (p, y), rel, relations[rel].classes.keys())
            shapes[rel] = (shape, impLst)
            p = p + width + 10
            if p > self.GetSize().x:
                p = 10
                y = y + 120

        # Add lines
        for module in shapes.keys():
            for line in shapes[module][1]:
                self.newLine(dc, shapes[module][0], shapes[line][0])

        PersistentOGLView.refreshCtrl(self)

    def OnRefresh(self, event):
        self.relationships = None
        self.refreshCtrl()


class AppPackageView(PersistentOGLView):
    ext = '.apklay'
    refreshBmp = 'Images/Editor/Refresh.png'
    viewName = 'Application packages'

    def __init__(self, parent, model):
        PersistentOGLView.__init__(self, parent, model,
          (('-', None, '', ''),
           ('Refresh', self.OnRefresh, self.refreshBmp, ''))
        )
        self.relationships = None

    def newModule(self, size, pos, moduleName, importList):
        idx = self.addShape(PerstDividedShape(moduleName, size[0], size[1]),
          pos[0], pos[1], wxBLACK_PEN, wxLIGHT_GREY_BRUSH, '')

        maxWidth = 10 #padding

        regionName, maxWidth, nameHeight = self.newRegion(
              Preferences.oglBoldFont, 'module_name', [moduleName], maxWidth)
        regionClss, maxWidth, clssHeight = self.newRegion(
              Preferences.oglStdFont, 'methods', importList, maxWidth)

        totHeight = nameHeight + clssHeight

        regionName.SetProportions(0.0, 1.0*(nameHeight/float(totHeight)))
        regionClss.SetProportions(0.0, 1.0*(clssHeight/float(totHeight)))

        shape = self.shapes[idx]
        shape.AddRegion(regionName)
        shape.AddRegion(regionClss)

        shape.SetSize(maxWidth + 10, totHeight + 10)

        shape.SetRegionSizes()
        shape.FlushText()

        return shape, maxWidth + 10

    def refreshCtrl(self):
        dc = wxClientDC(self)
        self.PrepareDC(dc)

        # Because of slow building process, cache after first time
        if not self.relationships:
            relations = self.model.buildImportRelationshipDict()
            self.relationships = relations
            self.destroyShapes()
        else:
            return
            #relations = self.relationships

        shapes = {}
        p = 10
        y = 20
        # Add shapes
        for rel in relations.keys():
            impLst = []
            for i in relations[rel].imports.keys():
                if relations.has_key(i): impLst.append(i)

            shape, width = self.newModule((20, 30), (p, y), rel, relations[rel].classes.keys())
            shapes[rel] = (shape, impLst)
            p = p + width + 10
            if p > self.GetSize().x:
                p = 10
                y = y + 120

        # Add lines
        for module in shapes.keys():
            for line in shapes[module][1]:
                self.newLine(dc, shapes[module][0], shapes[line][0])

        PersistentOGLView.refreshCtrl(self)

    def OnRefresh(self, event):
        self.relationships = None
        self.refreshCtrl()

class __Cleanup:
    cleanup = wxOGLCleanUp
    def __del__(self):
        self.cleanup()

# when this module gets cleaned up then wxOGLCleanUp() will get called
__cu = __Cleanup()