File: drSourceBrowser.py

package info (click to toggle)
drpython 1%3A3.11.4-1.1
  • links: PTS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, stretch
  • size: 3,868 kB
  • ctags: 2,871
  • sloc: python: 16,653; makefile: 141; sh: 1
file content (433 lines) | stat: -rw-r--r-- 16,691 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
#   Programmer: Daniel Pozmanter
#   E-mail:     drpython@bluebottle.com
#   Note:       You must reply to the verification e-mail to get through.
#
#   Copyright 2003-2010 Daniel Pozmanter
#
#   Distributed under the terms of the GPL (GNU Public License)
#
#    DrPython 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

#Source Browser

#   Icons taken from "Noia Kde 100" by Carles Carbonell Bernado from the KDE-LOOK site (some edited a bit).
#   An excellent artist.

import wx
import drScrolledMessageDialog
from drProperty import *
import wx.stc
import os
import re

recolour = re.compile('#\w+')

def GetCount(line, compchar):
    l = len(line)
    x = 0
    y = 0
    while x < l:
        if line[x] == compchar:
            y = y + 1
        elif not line[x].isspace():
            x = l
        x = x + 1
    return y

class drTree(wx.TreeCtrl):
    def __init__(self, parent, id, point, size, style, ancestor):
        wx.TreeCtrl.__init__(self, parent, id, point, size, style)

        self.grandparent = ancestor
        self.parent = parent

        style = self.grandparent.prefs.sourcebrowserstyle
        yarrr = convertStyleStringToWXFontArray(style)

        if self.grandparent.prefs.sourcebrowseruseimages==1:
            imagesize = (16,16)

            self.imagelist = wx.ImageList(imagesize[0], imagesize[1])
            self.images = [wx.BitmapFromImage(wx.Image(os.path.join(self.grandparent.bitmapdirectory, "16/class.png"), wx.BITMAP_TYPE_PNG)),
            wx.BitmapFromImage(wx.Image(os.path.join(self.grandparent.bitmapdirectory, "16/def.png"), wx.BITMAP_TYPE_PNG)),
            wx.BitmapFromImage(wx.Image(os.path.join(self.grandparent.bitmapdirectory, "16/import.png"), wx.BITMAP_TYPE_PNG)),
            wx.BitmapFromImage(wx.Image(os.path.join(self.grandparent.bitmapdirectory, "16/transparent.png"), wx.BITMAP_TYPE_PNG))]

            map(self.imagelist.Add, self.images)

            self.AssignImageList(self.imagelist)

        w = wx.Font(yarrr[1], wx.NORMAL, wx.NORMAL, wx.NORMAL, yarrr[2])

        w.SetFaceName(yarrr[0])

        if yarrr[3]:
            w.SetWeight(wx.BOLD)
        else:
            w.SetWeight(wx.NORMAL)
        if yarrr[4]:
            w.SetStyle(wx.ITALIC)
        else:
            w.SetStyle(wx.NORMAL)

        self.SetFont(w)

        f = convertColorPropertyToColorArray(getStyleProperty("fore", style))
        b = convertColorPropertyToColorArray(getStyleProperty("back", style))

        self.TextColor = wx.Colour(f[0], f[1], f[2])

        self.SetForegroundColour(self.TextColor)

        self.SetBackgroundColour(wx.Colour(b[0], b[1], b[2]))

        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED,  self.OnItemActivated, id=id)
        self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK,  self.OnItemActivated, id=id)

        self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnExpandedCollapse, id=id)
        self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnExpandedCollapse, id=id)

    def OnExpandedCollapse(self, event):
        event.Skip()
        #AB: it is necesserary to do something to refresh scroll bars

    def OnCompareItems(self, item1, item2):
        #Overriding Base, Return -1 for <, 0 for ==, +1 for >
        t1 = self.GetItemText(item1).lower()
        t2 = self.GetItemText(item2).lower()

        x = 0
        l = len(t1)
        if l > len(t2):
            l = len(t2)
        while x < l:
            if t1[x] < t2[x]:
                return -1
            elif t1[x] > t2[x]:
                return 1
            x = x + 1

        if l == len(t2):
            return -1

        return 0

    def OnItemActivated(self, event):
        sel = self.GetSelection()
        if not sel.IsOk():
            return
        t = self.GetItemText(sel)
        try:
            i = self.parent.ItemsIndex.index(sel)
            pos = self.parent.ItemsPos[i]
            line = self.grandparent.txtDocument.LineFromPosition(pos)
            if self.grandparent.prefs.docfolding:
                #Make sure the line is visible.
                self.grandparent.txtDocument.EnsureVisible(line)
            self.grandparent.txtDocument.ScrollToLine(line)
            self.grandparent.txtDocument.GotoLine(line)
            self.grandparent.txtDocument.GotoPos(pos)
            self.grandparent.Raise()
            self.grandparent.SetFocus()
            if self.grandparent.prefs.sourcebrowsercloseonactivate:
                self.parent.OnbtnClose(event)
            else:
                self.grandparent.txtDocument.SetFocus()
        except:
            drScrolledMessageDialog.ShowMessage(self.parent, "Error Activating Item", "Source Browser Error")

class drSourceBrowserPanel(wx.Panel):
    def __init__(self, parent, id, Position, Index):
        wx.Panel.__init__(self, parent, id)

        self.theSizer = wx.BoxSizer(wx.VERTICAL)

        self.mixed = 0

        self.renext = re.compile(r"^[ \t]*[^#^\s]", re.M)

        self.reinspect = re.compile(r'(^[ \t]*?class\s.*[(:])|(^[ \t]*?def\s.*[(:])|(^[ \t]*?import\s.*$)|(^[ \t]*?from\s.*$)|(^\s*#---.+)', re.MULTILINE)

        self.panelparent = parent.GetGrandParent().GetParent()

        self.parent = parent.GetGrandParent().GetGrandParent()

        self.classtree = drTree(self, -1, wx.Point(0, 0), (400, 200), wx.TR_DEFAULT_STYLE|wx.TR_HIDE_ROOT, self.parent)

        self.btnClose = wx.Button(self, 101, "&Close")
        self.btnRefresh = wx.Button(self, 102, "&Refresh")

        self.theSizer.Add(self.classtree, 9, wx.EXPAND)
        self.bSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.bSizer.Add(self.btnRefresh, 0,  wx.SHAPED | wx.ALIGN_LEFT)
        self.bSizer.Add(self.btnClose, 0,  wx.SHAPED | wx.ALIGN_LEFT)
        self.edSearch = wx.TextCtrl(self, -1, "", size=(-1,-1)) #edit for search in tree
        self.bSizer.Add(self.edSearch, 1,   wx.ALIGN_RIGHT)

        self.theSizer.Add(self.bSizer, 0, wx.EXPAND)

        self.position = Position
        self.Index = Index

        self.Bind(wx.EVT_BUTTON, self.OnbtnClose, id=101)
        self.Bind(wx.EVT_BUTTON, self.OnbtnRefresh, id=102)
        self.parent.PBind(self.parent.EVT_DRPY_DOCUMENT_CHANGED, self.OnbtnRefresh, None)
        self.edSearch.Bind(wx.EVT_KEY_UP, self.OnedSearch)
        self.edSearch.SetToolTipString("Search in the class-tree")
        self.eol = self.parent.txtDocument.GetEndOfLineCharacter()

        if not self.Browse():
            self.mixed = 1
            msg = "This document is mixed.  It uses tabs and spaces for indentation.\nDrPython may not be able to correctly display the class browser.  Please use 'Edit:Whitespace:Clean Up Indentation' to fix this."
            drScrolledMessageDialog.ShowMessage(self, msg, "Check Indentation Results")

        self.SetAutoLayout(True)
        self.SetSizer(self.theSizer)

        #AB:
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnClose)

    def OnClose(self, event):
        """Cleaning old references.
        It is necessary when the notebook panel is closed on his tab menu. Otherwise we get:
        wx._core.PyDeadObjectError: The C++ part of the drSourceBrowserPanel object has
        been deleted, attribute access no longer allowed."""
        self.parent.SourceBrowser = None
        self.parent.PUnbind(self.parent.EVT_DRPY_DOCUMENT_CHANGED, self.OnbtnRefresh)
        #AB end

    def Browse(self):

        #Submitted Patch:  Christian Daven
        self.classtree.Freeze()
        #/Submitted Patch:  Christian Daven

        self.classtree.DeleteAllItems()

        if self.parent.txtDocument.filetype != 0: # no python file
            self.classtree.Thaw()
            return 1 #without sense; destroys class tree font format?

        self.root = self.classtree.AddRoot("")

        self.ItemsIndex = []

        self.ItemsPos = []


        self.targetText = self.parent.txtDocument.GetText()

        if self.mixed:
            return 1
        RootArray = [self.root]
        Roots = [self.root]
        currentRoot = 0
        Indents = [0]
        currentIndent = 0

        #What is this document using?
        result = self.parent.txtDocument.CheckIndentation()
        wasnotmixed = 1
        if result == 0:
            wasnotmixed = 0
            if self.parent.prefs.docusetabs[self.parent.txtDocument.filetype]:
                result = 1
            else:
                result = -1
        if result == 1:
            compchar = '\t'
            dec = 1
        else:
            compchar = " "
            dec = self.parent.prefs.doctabwidth[0]

        #Handle Triple Quoted Strings:
        self.targetText = self.RemoveTripleQuotedString(self.targetText)

        matcher = self.reinspect.finditer(self.targetText)

        #Get On With It!
        try:
            match = matcher.next()
        except:
            match = None
        while match is not None:
            matchedtext = match.group().strip()
            if matchedtext[0] == '#':
                nextmatch = self.renext.search(self.targetText[match.end():])

                indent = 0

                if nextmatch is not None:
                    indent = GetCount(nextmatch.group(), compchar)

                cR = currentRoot
                cI = currentIndent

                while indent < Indents[cI]:
                        cR = cR - 1
                        cI = cI - 1

                i = matchedtext[4:].find("---")
                if i > -1:
                    a = matchedtext[4:i+4]
                else:
                    a = matchedtext[4:]

                m = match.group().find('#')

                currentitem = self.classtree.AppendItem(Roots[cI], a)
                #applied patch from bug report [ 1215144 ], 11.04.2007:
                Roots.append(currentitem)
                self.classtree.SetPyData(Roots[-1], None)
                currentRoot += 1
                RootArray.append(Roots[currentRoot])
                self.ItemsIndex.append(currentitem)
                self.ItemsPos.append(match.start() + m)

                colours = recolour.findall(matchedtext)

                if len(colours) > 1:
                    try:
                        self.classtree.SetItemTextColour(currentitem, convertColorPropertyToColorArray(colours[0]))
                        self.classtree.SetItemBackgroundColour(currentitem, convertColorPropertyToColorArray(colours[1]))
                    except Exception, e:
                        print "Error Setting Label Colour:", e
                self.classtree.SetItemImage(currentitem, 3, wx.TreeItemIcon_Normal)
                self.classtree.SetItemImage(currentitem, 3, wx.TreeItemIcon_Expanded)
            else:
                indent = GetCount(match.group(), compchar)

                while indent < Indents[currentIndent]:
                        Roots.pop()
                        currentRoot = currentRoot - 1
                        Indents.pop()
                        currentIndent = currentIndent - 1

                Indents.append(indent + dec)
                currentIndent = currentIndent + 1
                currentitem = self.classtree.AppendItem(Roots[currentRoot], matchedtext)
                Roots.append(currentitem)
                #Submitted bugfix, Franz Steinhausler
                self.classtree.SetPyData(Roots[-1], None)
                currentRoot += 1
                RootArray.append(Roots[currentRoot])
                self.ItemsIndex.append(Roots[currentRoot])
                self.ItemsPos.append(match.start())
                if matchedtext[0] == 'c':
                    try:
                        fg, bg = convertStyleToColorArray(self.parent.prefs.PythonStyleDictionary[5])
                        self.classtree.SetItemTextColour(Roots[currentRoot], fg)
                        self.classtree.SetItemBackgroundColour(Roots[currentRoot], bg)
                    except Exception, e:
                        print "Error Setting Class Colour:", e
                    self.classtree.SetItemImage(Roots[currentRoot], 0, wx.TreeItemIcon_Normal)
                    self.classtree.SetItemImage(Roots[currentRoot], 0, wx.TreeItemIcon_Expanded)
                elif matchedtext[0] == 'd':
                    try:
                        fg, bg = convertStyleToColorArray(self.parent.prefs.PythonStyleDictionary[8])
                        self.classtree.SetItemTextColour(Roots[currentRoot], fg)
                        self.classtree.SetItemBackgroundColour(Roots[currentRoot], bg)
                    except Exception, e:
                        print "Error Setting Def Colour:", e
                    self.classtree.SetItemImage(Roots[currentRoot], 1, wx.TreeItemIcon_Normal)
                    self.classtree.SetItemImage(Roots[currentRoot], 1, wx.TreeItemIcon_Expanded)
                else:
                    self.classtree.SetItemImage(Roots[currentRoot], 2, wx.TreeItemIcon_Normal)
                    self.classtree.SetItemImage(Roots[currentRoot], 2, wx.TreeItemIcon_Expanded)
            try:
                match = matcher.next()
            except:
                match = None

        if self.parent.prefs.sourcebrowserissorted:
            self.classtree.SortChildren(self.root)
            x = 0
            l = len(RootArray)
            while x < l:
                self.classtree.SortChildren(RootArray[x])
                x = x + 1

        #Submitted Patch:  Christian Daven
        self.classtree.Thaw()
        #/Submitted Patch:  Christian Daven

        return wasnotmixed

    def OnedSearch(self, event): #search on tree
        o = event.GetEventObject()
        s = o.GetValue().lower()
        if len(s) < 2:
            return
        #s=self.classtree.GetItemText(self.classtree.GetSelection())
        sel = self.classtree.GetSelection()
        found = False
        start = False
        #First try after selected item:
        for item in self.ItemsIndex:
            if start:
                z = self.classtree.GetItemText(item).lower()
                if z.find(s) > 0:
                    self.classtree.SelectItem(item, True)
                    self.classtree.OnItemActivated(None)
                    o.SetFocus()
                    o.SetInsertionPointEnd()
                    found = True
                    break
            if item == sel:
                start = True
        #Second try from start
        if not found:
            for item in self.ItemsIndex:
                z = self.classtree.GetItemText(item).lower()
                if z.find(s) > 0:
                    self.classtree.SelectItem(item, True)
                    self.classtree.OnItemActivated(None)
                    o.SetFocus()
                    o.SetInsertionPointEnd()
                    break
        event.Skip()

    def OnbtnClose(self, event):
        self.parent.PUnbind(self.parent.EVT_DRPY_DOCUMENT_CHANGED, self.OnbtnRefresh)
        self.parent.SourceBrowser = None
        self.parent.txtDocument.SetFocus()
        self.panelparent.ClosePanel(self.position, self.Index)

    def OnbtnRefresh(self, event):
        self.mixed = 0
        if not self.Browse():
            self.mixed = 1
            msg = "This document is mixed.  It uses tabs and spaces for indentation.\nDrPython may not be able to correctly display the class browser.  Please use 'Edit:Whitespace:Clean Up Indentation' to fix this."
            drScrolledMessageDialog.ShowMessage(self, msg, "Check Indentation Results")
        if event is not None:
            event.Skip()

    def RemoveTripleQuotedString(self, text):
        text = self.removeStringTripleQuotedWith(text, "'''")
        text = self.removeStringTripleQuotedWith(text, '"""')
        return text

    def removeStringTripleQuotedWith(self, text, target):
        start = text.find(target)
        while start > -1:
            end = text[start+3:].find(target)
            if end == -1:
                text = text[:start]
            else:
                end = start + 3 + end
                text = text[:start] + "".zfill((end - start) + 3) + text[end+3:]
            start = text.find(target)
        return text