From 1f780e48af479e7bf9a07eaaa1ab6b41f1ffb17b Mon Sep 17 00:00:00 2001 From: Robin Dunn Date: Fri, 8 Apr 2005 22:54:02 +0000 Subject: [PATCH] Added the ActiveGrid IDE as a sample application git-svn-id: https://svn.wxwidgets.org/svn/wx/wxWidgets/trunk@33440 c3d73ce0-8a6f-49c7-b76d-6d57e0e08775 --- wxPython/distrib/DIRLIST | 10 +- wxPython/distrib/make_installer.py | 15 +- wxPython/docs/CHANGES.txt | 1 + wxPython/samples/ide/ActiveGridIDE.py | 33 + wxPython/samples/ide/activegrid/__init__.py | 0 .../ide/activegrid/tool/AboutDialog.py | 119 + .../ide/activegrid/tool/AbstractEditor.py | 641 +++++ .../samples/ide/activegrid/tool/CodeEditor.py | 1014 +++++++ .../ide/activegrid/tool/DebuggerHarness.py | 690 +++++ .../ide/activegrid/tool/DebuggerService.py | 2275 ++++++++++++++++ .../ide/activegrid/tool/FindInDirService.py | 446 ++++ .../ide/activegrid/tool/FindService.py | 521 ++++ .../samples/ide/activegrid/tool/HtmlEditor.py | 222 ++ wxPython/samples/ide/activegrid/tool/IDE.py | 2056 ++++++++++++++ .../ide/activegrid/tool/IDEFindService.py | 445 ++++ .../ide/activegrid/tool/ImageEditor.py | 93 + .../ide/activegrid/tool/MarkerService.py | 91 + .../ide/activegrid/tool/MessageService.py | 143 + .../ide/activegrid/tool/OutlineService.py | 520 ++++ .../samples/ide/activegrid/tool/PHPEditor.py | 297 +++ .../samples/ide/activegrid/tool/PerlEditor.py | 425 +++ .../ide/activegrid/tool/ProjectEditor.py | 1847 +++++++++++++ .../ide/activegrid/tool/PythonEditor.py | 614 +++++ .../ide/activegrid/tool/STCTextEditor.py | 1293 +++++++++ .../samples/ide/activegrid/tool/Service.py | 327 +++ .../samples/ide/activegrid/tool/TabbedView.py | 48 + .../samples/ide/activegrid/tool/UICommon.py | 115 + .../samples/ide/activegrid/tool/Wizard.py | 967 +++++++ .../samples/ide/activegrid/tool/XmlEditor.py | 165 ++ .../samples/ide/activegrid/tool/__init__.py | 0 .../samples/ide/activegrid/tool/checker.py | 896 +++++++ .../samples/ide/activegrid/tool/data/tips.txt | 7 + .../samples/ide/activegrid/tool/process.py | 2364 +++++++++++++++++ .../samples/ide/activegrid/util/__init__.py | 72 + .../samples/ide/activegrid/util/aglogging.py | 84 + .../ide/activegrid/util/cachedloader.py | 87 + .../ide/activegrid/util/dependencymgr.py | 145 + .../samples/ide/activegrid/util/fileutils.py | 39 + .../ide/activegrid/util/gettersetter.py | 36 + .../ide/activegrid/util/xmlmarshaller.py | 649 +++++ .../ide/activegrid/util/xmlmarshallertests.py | 183 ++ .../ide/activegrid/util/xmlprettyprinter.py | 63 + 42 files changed, 20049 insertions(+), 9 deletions(-) create mode 100644 wxPython/samples/ide/ActiveGridIDE.py create mode 100644 wxPython/samples/ide/activegrid/__init__.py create mode 100644 wxPython/samples/ide/activegrid/tool/AboutDialog.py create mode 100644 wxPython/samples/ide/activegrid/tool/AbstractEditor.py create mode 100644 wxPython/samples/ide/activegrid/tool/CodeEditor.py create mode 100644 wxPython/samples/ide/activegrid/tool/DebuggerHarness.py create mode 100644 wxPython/samples/ide/activegrid/tool/DebuggerService.py create mode 100644 wxPython/samples/ide/activegrid/tool/FindInDirService.py create mode 100644 wxPython/samples/ide/activegrid/tool/FindService.py create mode 100644 wxPython/samples/ide/activegrid/tool/HtmlEditor.py create mode 100644 wxPython/samples/ide/activegrid/tool/IDE.py create mode 100644 wxPython/samples/ide/activegrid/tool/IDEFindService.py create mode 100644 wxPython/samples/ide/activegrid/tool/ImageEditor.py create mode 100644 wxPython/samples/ide/activegrid/tool/MarkerService.py create mode 100644 wxPython/samples/ide/activegrid/tool/MessageService.py create mode 100644 wxPython/samples/ide/activegrid/tool/OutlineService.py create mode 100644 wxPython/samples/ide/activegrid/tool/PHPEditor.py create mode 100644 wxPython/samples/ide/activegrid/tool/PerlEditor.py create mode 100644 wxPython/samples/ide/activegrid/tool/ProjectEditor.py create mode 100644 wxPython/samples/ide/activegrid/tool/PythonEditor.py create mode 100644 wxPython/samples/ide/activegrid/tool/STCTextEditor.py create mode 100644 wxPython/samples/ide/activegrid/tool/Service.py create mode 100644 wxPython/samples/ide/activegrid/tool/TabbedView.py create mode 100644 wxPython/samples/ide/activegrid/tool/UICommon.py create mode 100644 wxPython/samples/ide/activegrid/tool/Wizard.py create mode 100644 wxPython/samples/ide/activegrid/tool/XmlEditor.py create mode 100644 wxPython/samples/ide/activegrid/tool/__init__.py create mode 100644 wxPython/samples/ide/activegrid/tool/checker.py create mode 100644 wxPython/samples/ide/activegrid/tool/data/tips.txt create mode 100644 wxPython/samples/ide/activegrid/tool/process.py create mode 100644 wxPython/samples/ide/activegrid/util/__init__.py create mode 100644 wxPython/samples/ide/activegrid/util/aglogging.py create mode 100644 wxPython/samples/ide/activegrid/util/cachedloader.py create mode 100644 wxPython/samples/ide/activegrid/util/dependencymgr.py create mode 100644 wxPython/samples/ide/activegrid/util/fileutils.py create mode 100644 wxPython/samples/ide/activegrid/util/gettersetter.py create mode 100644 wxPython/samples/ide/activegrid/util/xmlmarshaller.py create mode 100644 wxPython/samples/ide/activegrid/util/xmlmarshallertests.py create mode 100644 wxPython/samples/ide/activegrid/util/xmlprettyprinter.py diff --git a/wxPython/distrib/DIRLIST b/wxPython/distrib/DIRLIST index a4a065fc38..8a749638f0 100644 --- a/wxPython/distrib/DIRLIST +++ b/wxPython/distrib/DIRLIST @@ -61,10 +61,12 @@ wxPython/licence wxPython/samples wxPython/samples/StyleEditor wxPython/samples/docview -wxPython/samples/docview/activegrid -wxPython/samples/docview/activegrid/tool -wxPython/samples/docview/activegrid/tool/data -wxPython/samples/docview/activegrid/tool/images +wxPython/samples/pydocview +wxPython/samples/ide +wxPython/samples/ide/activegrid +wxPython/samples/ide/activegrid/tool +wxPython/samples/ide/activegrid/tool/data +wxPython/samples/ide/activegrid/util wxPython/samples/doodle wxPython/samples/embedded wxPython/samples/frogedit diff --git a/wxPython/distrib/make_installer.py b/wxPython/distrib/make_installer.py index ed0e57dfd4..96672b8ddf 100644 --- a/wxPython/distrib/make_installer.py +++ b/wxPython/distrib/make_installer.py @@ -409,11 +409,16 @@ Source: "samples\doodle\*.bat"; DestDir: "{app}\samples\doodle"; Source: "samples\doodle\sample.ddl"; DestDir: "{app}\samples\doodle"; Source: "samples\doodle\superdoodle.iss"; DestDir: "{app}\samples\doodle"; -Source: "samples\docview\*.py"; DestDir: "{app}\samples\docview"; -Source: "samples\docview\activegrid\*.py"; DestDir: "{app}\samples\docview\activegrid"; -Source: "samples\docview\activegrid\tool\*.py"; DestDir: "{app}\samples\docview\activegrid\tool"; -Source: "samples\docview\activegrid\tool\data\*.txt"; DestDir: "{app}\samples\docview\activegrid\tool\data"; -Source: "samples\docview\activegrid\tool\images\*.jpg"; DestDir: "{app}\samples\docview\activegrid\tool\images"; +Source: "samples\docview\*.py"; DestDir: "{app}\samples\docview"; +Source: "samples\pydocview\*.py"; DestDir: "{app}\samples\pydocview"; +Source: "samples\pydocview\*.jpg"; DestDir: "{app}\samples\pydocview"; +Source: "samples\pydocview\*.txt"; DestDir: "{app}\samples\pydocview"; + +Source: "samples\ide\*.py"; DestDir: "{app}\samples\ide"; +Source: "samples\ide\activegrid\*.py"; DestDir: "{app}\samples\ide\activegrid"; +Source: "samples\ide\activegrid\tool\*.py"; DestDir: "{app}\samples\ide\activegrid\tool"; +Source: "samples\ide\activegrid\tool\data\*.txt"; DestDir: "{app}\samples\ide\activegrid\tool\data"; +Source: "samples\ide\activegrid\util\*.py"; DestDir: "{app}\samples\ide\activegrid\util"; Source: "samples\embedded\*.py"; DestDir: "{app}\samples\embedded"; Source: "samples\embedded\*.cpp"; DestDir: "{app}\samples\embedded"; diff --git a/wxPython/docs/CHANGES.txt b/wxPython/docs/CHANGES.txt index 454eb6dbd2..426c834fc6 100644 --- a/wxPython/docs/CHANGES.txt +++ b/wxPython/docs/CHANGES.txt @@ -85,6 +85,7 @@ list of top-level windows that currently exist in the application. Updated docview library modules and sample apps from the ActiveGrid folks. +Added the ActiveGrid IDE as a sample application. diff --git a/wxPython/samples/ide/ActiveGridIDE.py b/wxPython/samples/ide/ActiveGridIDE.py new file mode 100644 index 0000000000..868acca0e7 --- /dev/null +++ b/wxPython/samples/ide/ActiveGridIDE.py @@ -0,0 +1,33 @@ +#---------------------------------------------------------------------------- +# Name: ActiveGridIDE.py +# Purpose: +# +# Author: Lawrence Bruhmuller +# +# Created: 3/30/05 +# CVS-ID: $Id$ +# Copyright: (c) 2004-2005 ActiveGrid, Inc. +# License: wxWindows License +#---------------------------------------------------------------------------- +import wx.lib.pydocview +import activegrid.tool.IDE + +import os +import sys +sys.stdout = sys.stderr + +# This is here as the base IDE entry point. Only difference is that -baseide is passed. + +sys.argv.append('-baseide'); + +# Put activegrid dir in path so python files can be found from py2exe +# This code should never do anything when run from the python interpreter +execDir = os.path.dirname(sys.executable) +try: + sys.path.index(execDir) +except ValueError: + sys.path.append(execDir) +app = activegrid.tool.IDE.IDEApplication(redirect = False) +app.GetTopWindow().Raise() # sometimes it shows up beneath other windows. e.g. running self in debugger +app.MainLoop() + diff --git a/wxPython/samples/ide/activegrid/__init__.py b/wxPython/samples/ide/activegrid/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/wxPython/samples/ide/activegrid/tool/AboutDialog.py b/wxPython/samples/ide/activegrid/tool/AboutDialog.py new file mode 100644 index 0000000000..ce1e0cdfa5 --- /dev/null +++ b/wxPython/samples/ide/activegrid/tool/AboutDialog.py @@ -0,0 +1,119 @@ +#---------------------------------------------------------------------------- +# Name: AboutDialog.py +# Purpose: AboutBox which has copyright notice, license information, and credits +# +# Author: Morgan Hua +# +# Created: 3/22/05 +# Copyright: (c) 2005 ActiveGrid, Inc. +# CVS-ID: $Id$ +# License: wxWindows License +#---------------------------------------------------------------------------- + +import wx +from IDE import ACTIVEGRID_BASE_IDE, getSplashBitmap +_ = wx.GetTranslation + +#---------------------------------------------------------------------------- +# Package License Data for AboutDialog +# Package, License, URL +# If no information is available, put a None as a place holder. +#---------------------------------------------------------------------------- + + +licenseData = [ + ("ActiveGrid", "ASL 2.0", "http://apache.org/licenses/LICENSE-2.0"), + ("Python 2.3", "Python Software Foundation License", "http://www.python.org/2.3/license.html"), + ("wxPython 2.5", "wxWidgets 2 - LGPL", "http://wxwidgets.org/newlicen.htm"), + ("wxWidgets", "wxWindows Library License 3", "http://www.wxwidgets.org/manuals/2.5.4/wx_wxlicense.html"), + ("pychecker", "MetaSlash - BSD", "http://pychecker.sourceforge.net/COPYRIGHT"), + ("process.py", "See file", "http://starship.python.net/~tmick/"), +] + +if not ACTIVEGRID_BASE_IDE: # add licenses for database connections only if not the base IDE + licenseData += [ + ("pydb2", "LGPL", "http://sourceforge.net/projects/pydb2"), + ("pysqlite", "Python License (CNRI)", "http://sourceforge.net/projects/pysqlite"), + ("mysql-python", "GPL, Python License (CNRI), Zope Public License", "http://sourceforge.net/projects/mysql-python"), + ("cx_Oracle", "Computronix", "http://http://www.computronix.com/download/License(cxOracle).txt"), + ("SQLite", "Public Domain", "http://www.sqlite.org/copyright.html"), + ("PyGreSQL", "BSD", "http://www.pygresql.org"), + ] + +if wx.Platform == '__WXMSW__': + licenseData += [("pywin32", "Python Software Foundation License", "http://sourceforge.net/projects/pywin32/")] + +class AboutDialog(wx.Dialog): + + def __init__(self, parent): + """ + Initializes the about dialog. + """ + wx.Dialog.__init__(self, parent, -1, _("About ") + wx.GetApp().GetAppName(), style = wx.DEFAULT_DIALOG_STYLE) + + nb = wx.Notebook(self, -1) + + aboutPage = wx.Panel(nb, -1) + sizer = wx.BoxSizer(wx.VERTICAL) + splash_bmp = getSplashBitmap() + image = wx.StaticBitmap(aboutPage, -1, splash_bmp, (0,0), (splash_bmp.GetWidth(), splash_bmp.GetHeight())) + sizer.Add(image, 0, wx.ALIGN_CENTER|wx.ALL, 0) + sizer.Add(wx.StaticText(aboutPage, -1, wx.GetApp().GetAppName() + _("\nVersion 0.6 Early Access\n\nCopyright (c) 2003-2005 ActiveGrid Incorporated and Contributors. All rights reserved.")), 0, wx.ALIGN_LEFT|wx.ALL, 10) + sizer.Add(wx.StaticText(aboutPage, -1, _("http://www.activegrid.com")), 0, wx.ALIGN_LEFT|wx.LEFT|wx.BOTTOM, 10) + aboutPage.SetSizer(sizer) + nb.AddPage(aboutPage, _("Copyright")) + + licensePage = wx.Panel(nb, -1) + grid = wx.grid.Grid(licensePage, -1) + grid.CreateGrid(len(licenseData), 2) + + dc = wx.ClientDC(grid) + dc.SetFont(grid.GetLabelFont()) + grid.SetColLabelValue(0, _("License")) + grid.SetColLabelValue(1, _("URL")) + w, maxHeight = dc.GetTextExtent(_("License")) + w, h = dc.GetTextExtent(_("URL")) + if h > maxHeight: + maxHeight = h + grid.SetColLabelSize(maxHeight + 6) # add a 6 pixel margin + + for row, data in enumerate(licenseData): + package = data[0] + license = data[1] + url = data[2] + if package: + grid.SetRowLabelValue(row, package) + if license: + grid.SetCellValue(row, 0, license) + if url: + grid.SetCellValue(row, 1, url) + + grid.EnableEditing(False) + grid.EnableDragGridSize(False) + grid.EnableDragColSize(False) + grid.EnableDragRowSize(False) + grid.SetRowLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE) + grid.SetLabelBackgroundColour(wx.WHITE) + grid.AutoSizeColumn(0, 100) + grid.AutoSizeColumn(1, 100) + sizer = wx.BoxSizer(wx.VERTICAL) + sizer.Add(grid, 1, wx.EXPAND|wx.ALL, 10) + licensePage.SetSizer(sizer) + nb.AddPage(licensePage, _("Licenses")) + + creditsPage = wx.Panel(nb, -1) + sizer = wx.BoxSizer(wx.VERTICAL) + sizer.Add(wx.StaticText(creditsPage, -1, _("ActiveGrid Development Team:\n\nLawrence Bruhmuller\nEric Chu\nMatt Fryer\nJoel Hare\nMorgan Hua\nAlan Mullendore\nJeff Norton\nKevin Wang\nPeter Yared")), 0, wx.ALIGN_LEFT|wx.ALL, 10) + creditsPage.SetSizer(sizer) + nb.AddPage(creditsPage, _("Credits")) + + sizer = wx.BoxSizer(wx.VERTICAL) + sizer.Add(nb, 0, wx.ALIGN_CENTRE|wx.ALL, 5) + btn = wx.Button(self, wx.ID_OK) + sizer.Add(btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5) + + self.SetSizer(sizer) + self.SetAutoLayout(True) + sizer.Fit(self) + + diff --git a/wxPython/samples/ide/activegrid/tool/AbstractEditor.py b/wxPython/samples/ide/activegrid/tool/AbstractEditor.py new file mode 100644 index 0000000000..8bda44696d --- /dev/null +++ b/wxPython/samples/ide/activegrid/tool/AbstractEditor.py @@ -0,0 +1,641 @@ +#---------------------------------------------------------------------------- +# Name: AbstractEditor.py +# Purpose: Non-text editor for DataModel and Process +# +# Author: Peter Yared, Morgan Hua +# +# Created: 7/28/04 +# CVS-ID: $Id$ +# Copyright: (c) 2004-2005 ActiveGrid, Inc. +# License: wxWindows License +#---------------------------------------------------------------------------- + + +import wx +import wx.lib.docview +import wx.lib.ogl as ogl +import PropertyService +_ = wx.GetTranslation + + +SELECT_BRUSH = wx.Brush("BLUE", wx.SOLID) +SHAPE_BRUSH = wx.Brush("WHEAT", wx.SOLID) +LINE_BRUSH = wx.BLACK_BRUSH + + +def GetRawModel(model): + if hasattr(model, "GetRawModel"): + rawModel = model.GetRawModel() + else: + rawModel = model + return rawModel + + +class CanvasView(wx.lib.docview.View): + + + #---------------------------------------------------------------------------- + # Overridden methods + #---------------------------------------------------------------------------- + + + def __init__(self, brush = SHAPE_BRUSH): + wx.lib.docview.View.__init__(self) + self._brush = brush + self._canvas = None + self._pt1 = None + self._pt2 = None + self._needEraseLasso = False + self._propShape = None + + + def OnCreate(self, doc, flags): + frame = wx.GetApp().CreateDocumentFrame(self, doc, flags) + frame.Show() + sizer = wx.BoxSizer() + self._CreateCanvas(frame) + sizer.Add(self._canvas, 1, wx.EXPAND, 0) + frame.SetSizer(sizer) + frame.Layout() + self.Activate() + return True + + + def OnActivateView(self, activate, activeView, deactiveView): + if activate and self._canvas: + # In MDI mode just calling set focus doesn't work and in SDI mode using CallAfter causes an endless loop + if self.GetDocumentManager().GetFlags() & wx.lib.docview.DOC_SDI: + self._canvas.SetFocus() + else: + wx.CallAfter(self._canvas.SetFocus) + + + def OnClose(self, deleteWindow = True): + statusC = wx.GetApp().CloseChildDocuments(self.GetDocument()) + statusP = wx.lib.docview.View.OnClose(self, deleteWindow = deleteWindow) + if hasattr(self, "ClearOutline"): + wx.CallAfter(self.ClearOutline) # need CallAfter because when closing the document, it is Activated and then Close, so need to match OnActivateView's CallAfter + if not (statusC and statusP): + return False + self.Activate(False) + if deleteWindow and self.GetFrame(): + self.GetFrame().Destroy() + return True + + + def _CreateCanvas(self, parent): + self._canvas = ogl.ShapeCanvas(parent) + wx.EVT_LEFT_DOWN(self._canvas, self.OnLeftClick) + wx.EVT_LEFT_UP(self._canvas, self.OnLeftUp) + wx.EVT_MOTION(self._canvas, self.OnLeftDrag) + wx.EVT_LEFT_DCLICK(self._canvas, self.OnLeftDoubleClick) + wx.EVT_KEY_DOWN(self._canvas, self.OnKeyPressed) + + maxWidth = 2000 + maxHeight = 16000 + self._canvas.SetScrollbars(20, 20, maxWidth / 20, maxHeight / 20) + + self._canvas.SetBackgroundColour(wx.WHITE) + self._diagram = ogl.Diagram() + self._canvas.SetDiagram(self._diagram) + self._diagram.SetCanvas(self._canvas) + + + def OnKeyPressed(self, event): + key = event.KeyCode() + if key == wx.WXK_DELETE: + self.OnClear(event) + else: + event.Skip() + + + def OnLeftClick(self, event): + self.EraseRubberBand() + + dc = wx.ClientDC(self._canvas) + self._canvas.PrepareDC(dc) + + # keep track of mouse down for group select + self._pt1 = event.GetLogicalPosition(dc) # this takes into account scrollbar offset + self._pt2 = None + + shape = self._canvas.FindShape(self._pt1[0], self._pt1[1])[0] + if shape: + self.BringToFront(shape) + + self._pt1 = None + event.Skip() # pass on event to shape handler to take care of selection + + return + elif event.ControlDown() or event.ShiftDown(): # extend select, don't deselect + pass + else: + # click on empty part of canvas, deselect everything + needRefresh = False + for shape in self._diagram.GetShapeList(): + if hasattr(shape, "GetModel"): + if shape.Selected(): + needRefresh = True + shape.Select(False, dc) + if needRefresh: + self._canvas.Redraw(dc) + + self.SetPropertyModel(None) + + if len(self.GetSelection()) == 0: + self.SetPropertyShape(None) + + + + def OnLeftDoubleClick(self, event): + propertyService = wx.GetApp().GetService(PropertyService.PropertyService) + if propertyService: + propertyService.ShowWindow() + + + def OnLeftDrag(self, event): + # draw lasso for group select + if self._pt1 and event.LeftIsDown(): # we are in middle of lasso selection + self.EraseRubberBand() + + dc = wx.ClientDC(self._canvas) + self._canvas.PrepareDC(dc) + self._pt2 = event.GetLogicalPosition(dc) # this takes into account scrollbar offset + self.DrawRubberBand() + else: + event.Skip() + + + def OnLeftUp(self, event): + # do group select + if self._needEraseLasso: + self.EraseRubberBand() + + dc = wx.ClientDC(self._canvas) + self._canvas.PrepareDC(dc) + x1, y1 = self._pt1 + x2, y2 = event.GetLogicalPosition(dc) # this takes into account scrollbar offset + + tol = self._diagram.GetMouseTolerance() + if abs(x1 - x2) > tol or abs(y1 - y2) > tol: + # make sure x1 < x2 and y1 < y2 to make comparison test easier + if x1 > x2: + temp = x1 + x1 = x2 + x2 = temp + if y1 > y2: + temp = y1 + y1 = y2 + y2 = temp + + for shape in self._diagram.GetShapeList(): + if not shape.GetParent() and hasattr(shape, "GetModel"): # if part of a composite, don't select it + x, y = shape.GetX(), shape.GetY() + width, height = shape.GetBoundingBoxMax() + selected = x1 < x - width/2 and x2 > x + width/2 and y1 < y - height/2 and y2 > y + height/2 + if event.ControlDown() or event.ShiftDown(): # extend select, don't deselect + if selected: + shape.Select(selected, dc) + else: # select items in lasso and deselect items out of lasso + shape.Select(selected, dc) + self._canvas.Redraw(dc) + else: + event.Skip() + else: + event.Skip() + + + def EraseRubberBand(self): + if self._needEraseLasso: + self._needEraseLasso = False + + dc = wx.ClientDC(self._canvas) + self._canvas.PrepareDC(dc) + dc.SetLogicalFunction(wx.XOR) + pen = wx.Pen(wx.Colour(200, 200, 200), 1, wx.SHORT_DASH) + dc.SetPen(pen) + brush = wx.Brush(wx.Colour(255, 255, 255), wx.TRANSPARENT) + dc.SetBrush(brush) + dc.ResetBoundingBox() + dc.BeginDrawing() + + x1, y1 = self._pt1 + x2, y2 = self._pt2 + + # make sure x1 < x2 and y1 < y2 + # this will make (x1, y1) = upper left corner + if x1 > x2: + temp = x1 + x1 = x2 + x2 = temp + if y1 > y2: + temp = y1 + y1 = y2 + y2 = temp + + # erase previous outline + dc.SetClippingRegion(x1, y1, x2 - x1, y2 - y1) + dc.DrawRectangle(x1, y1, x2 - x1, y2 - y1) + dc.EndDrawing() + + + def DrawRubberBand(self): + self._needEraseLasso = True + + dc = wx.ClientDC(self._canvas) + self._canvas.PrepareDC(dc) + dc.SetLogicalFunction(wx.XOR) + pen = wx.Pen(wx.Colour(200, 200, 200), 1, wx.SHORT_DASH) + dc.SetPen(pen) + brush = wx.Brush(wx.Colour(255, 255, 255), wx.TRANSPARENT) + dc.SetBrush(brush) + dc.ResetBoundingBox() + dc.BeginDrawing() + + x1, y1 = self._pt1 + x2, y2 = self._pt2 + + # make sure x1 < x2 and y1 < y2 + # this will make (x1, y1) = upper left corner + if x1 > x2: + temp = x1 + x1 = x2 + x2 = temp + if y1 > y2: + temp = y1 + y1 = y2 + y2 = temp + + # draw outline + dc.SetClippingRegion(x1, y1, x2 - x1, y2 - y1) + dc.DrawRectangle(x1, y1, x2 - x1, y2 - y1) + dc.EndDrawing() + + + def FindParkingSpot(self, width, height): + """ given a width and height, find a upper left corner where shape can be parked without overlapping other shape """ + offset = 30 # space between shapes + x = offset + y = offset + maxX = 700 # max distance to the right where we'll place tables + noParkingSpot = True + + while noParkingSpot: + point = self.isSpotOccupied(x, y, width, height) + if point: + x = point[0] + offset + if x > maxX: + x = offset + y = point[1] + offset + else: + noParkingSpot = False + + return x, y + + + def isSpotOccupied(self, x, y, width, height): + """ returns None if at x,y,width,height no object occupies that rectangle, + otherwise returns lower right corner of object that occupies given x,y position + """ + x2 = x + width + y2 = y + height + + for shape in self._diagram.GetShapeList(): + if isinstance(shape, ogl.RectangleShape) or isinstance(shape, ogl.EllipseShape): + if shape.GetParent() and isinstance(shape.GetParent(), ogl.CompositeShape): + # skip, part of a composite shape + continue + + if hasattr(shape, "GetModel"): + other_x, other_y, other_width, other_height = shape.GetModel().getEditorBounds() + other_x2 = other_x + other_width + other_y2 = other_y + other_height + else: + # shapes x,y are at the center of the shape, need to transform to upper left coordinate + other_width, other_height = shape.GetBoundingBoxMax() + other_x = shape.GetX() - other_width/2 + other_y = shape.GetY() - other_height/2 + + other_x2 = other_x + other_width + other_y2 = other_y + other_height + # intersection check + if ((other_x2 < other_x or other_x2 > x) and + (other_y2 < other_y or other_y2 > y) and + (x2 < x or x2 > other_x) and + (y2 < y or y2 > other_y)): + return (other_x2, other_y2) + return None + + + #---------------------------------------------------------------------------- + # Canvas methods + #---------------------------------------------------------------------------- + + def AddShape(self, shape, x = None, y = None, pen = None, brush = None, text = None, eventHandler = None): + if isinstance(shape, ogl.CompositeShape): + dc = wx.ClientDC(self._canvas) + self._canvas.PrepareDC(dc) + shape.Move(dc, x, y) + else: + shape.SetDraggable(True, True) + shape.SetCanvas(self._canvas) + + if x: + shape.SetX(x) + if y: + shape.SetY(y) + shape.SetCentreResize(False) + if pen: + shape.SetPen(pen) + if brush: + shape.SetBrush(brush) + if text: + shape.AddText(text) + shape.SetShadowMode(ogl.SHADOW_RIGHT) + self._diagram.AddShape(shape) + shape.Show(True) + if not eventHandler: + eventHandler = EditorCanvasShapeEvtHandler(self) + eventHandler.SetShape(shape) + eventHandler.SetPreviousHandler(shape.GetEventHandler()) + shape.SetEventHandler(eventHandler) + return shape + + + def RemoveShape(self, model = None, shape = None): + if not model and not shape: + return + + if not shape: + shape = self.GetShape(model) + + if shape: + shape.Select(False) + self._diagram.RemoveShape(shape) + if isinstance(shape, ogl.CompositeShape): + shape.RemoveFromCanvas(self._canvas) + + + def UpdateShape(self, model): + for shape in self._diagram.GetShapeList(): + if hasattr(shape, "GetModel") and shape.GetModel() == model: + x, y, w, h = model.getEditorBounds() + newX = x + w / 2 + newY = y + h / 2 + changed = False + if isinstance(shape, ogl.CompositeShape): + if shape.GetX() != newX or shape.GetY() != newY: + dc = wx.ClientDC(self._canvas) + self._canvas.PrepareDC(dc) + shape.SetSize(w, h, True) # wxBug: SetSize must be before Move because links won't go to the right place + shape.Move(dc, newX, newY) # wxBug: Move must be before SetSize because links won't go to the right place + changed = True + else: + oldw, oldh = shape.GetBoundingBoxMax() + oldx = shape.GetX() + oldy = shape.GetY() + if oldw != w or oldh != h or oldx != newX or oldy != newY: + shape.SetSize(w, h) + shape.SetX(newX) + shape.SetY(newY) + changed = True + if changed: + shape.ResetControlPoints() + self._canvas.Refresh() + break + + + def GetShape(self, model): + for shape in self._diagram.GetShapeList(): + if hasattr(shape, "GetModel") and shape.GetModel() == model: + return shape + return None + + + def GetSelection(self): + return filter(lambda shape: shape.Selected(), self._diagram.GetShapeList()) + + + def SetSelection(self, models, extendSelect = False): + dc = wx.ClientDC(self._canvas) + self._canvas.PrepareDC(dc) + update = False + if not isinstance(models, type([])) and not isinstance(models, type(())): + models = [models] + for shape in self._diagram.GetShapeList(): + if hasattr(shape, "GetModel"): + if shape.Selected() and not shape.GetModel() in models: # was selected, but not in new list, so deselect, unless extend select + if not extendSelect: + shape.Select(False, dc) + update = True + elif not shape.Selected() and shape.GetModel() in models: # was not selected and in new list, so select + shape.Select(True, dc) + update = True + elif extendSelect and shape.Selected() and shape.GetModel() in models: # was selected, but extend select means to deselect + shape.Select(False, dc) + update = True + if update: + self._canvas.Redraw(dc) + + + def BringToFront(self, shape): + if shape.GetParent() and isinstance(shape.GetParent(), ogl.CompositeShape): + self._diagram.RemoveShape(shape.GetParent()) + self._diagram.AddShape(shape.GetParent()) + else: + self._diagram.RemoveShape(shape) + self._diagram.AddShape(shape) + + + def SendToBack(self, shape): + if shape.GetParent() and isinstance(shape.GetParent(), ogl.CompositeShape): + self._diagram.RemoveShape(shape.GetParent()) + self._diagram.InsertShape(shape.GetParent()) + else: + self._diagram.RemoveShape(shape) + self._diagram.InsertShape(shape) + + + def ScrollVisible(self, shape): + xUnit, yUnit = shape._canvas.GetScrollPixelsPerUnit() + scrollX, scrollY = self._canvas.GetViewStart() # in scroll units + scrollW, scrollH = self._canvas.GetSize() # in pixels + w, h = shape.GetBoundingBoxMax() # in pixels + x = shape.GetX() - w/2 # convert to upper left coordinate from center + y = shape.GetY() - h/2 # convert to upper left coordinate from center + + if x >= scrollX*xUnit and x <= scrollX*xUnit + scrollW: # don't scroll if already visible + x = -1 + else: + x = x/xUnit + + if y >= scrollY*yUnit and y <= scrollY*yUnit + scrollH: # don't scroll if already visible + y = -1 + else: + y = y/yUnit + + self._canvas.Scroll(x, y) # in scroll units + + + def SetPropertyShape(self, shape): + # no need to highlight if no PropertyService is running + propertyService = wx.GetApp().GetService(PropertyService.PropertyService) + if not propertyService: + return + + if shape == self._propShape: + return + + if hasattr(shape, "GetPropertyShape"): + shape = shape.GetPropertyShape() + + dc = wx.ClientDC(self._canvas) + self._canvas.PrepareDC(dc) + dc.BeginDrawing() + + # erase old selection if it still exists + if self._propShape and self._propShape in self._diagram.GetShapeList(): + self._propShape.SetBrush(self._brush) + if (self._propShape._textColourName in ["BLACK", "WHITE"]): # Would use GetTextColour() but it is broken + self._propShape.SetTextColour("BLACK", 0) + self._propShape.Draw(dc) + + # set new selection + self._propShape = shape + + # draw new selection + if self._propShape and self._propShape in self._diagram.GetShapeList(): + self._propShape.SetBrush(SELECT_BRUSH) + if (self._propShape._textColourName in ["BLACK", "WHITE"]): # Would use GetTextColour() but it is broken + self._propShape.SetTextColour("WHITE", 0) + self._propShape.Draw(dc) + + dc.EndDrawing() + + + #---------------------------------------------------------------------------- + # Property Service methods + #---------------------------------------------------------------------------- + + def GetPropertyModel(self): + if hasattr(self, "_propModel"): + return self._propModel + return None + + + def SetPropertyModel(self, model): + # no need to set the model if no PropertyService is running + propertyService = wx.GetApp().GetService(PropertyService.PropertyService) + if not propertyService: + return + + if hasattr(self, "_propModel") and model == self._propModel: + return + + self._propModel = model + propertyService.LoadProperties(self._propModel, self.GetDocument()) + + +class EditorCanvasShapeMixin: + + def GetModel(self): + return self._model + + + def SetModel(self, model): + self._model = model + + +class EditorCanvasShapeEvtHandler(ogl.ShapeEvtHandler): + + """ wxBug: Bug in OLG package. With wxShape.SetShadowMode() turned on, when we set the size, + the width/height is larger by 6 pixels. Need to subtract this value from width and height when we + resize the object. + """ + SHIFT_KEY = 1 + CONTROL_KEY = 2 + + def __init__(self, view): + ogl.ShapeEvtHandler.__init__(self) + self._view = view + + + def OnLeftClick(self, x, y, keys = 0, attachment = 0): + shape = self.GetShape() + if hasattr(shape, "GetModel"): # Workaround, on drag, we should deselect all other objects and select the clicked on object + model = shape.GetModel() + else: + shape = shape.GetParent() + if shape: + model = shape.GetModel() + + self._view.SetSelection(model, keys == self.SHIFT_KEY or keys == self.CONTROL_KEY) + self._view.SetPropertyShape(shape) + self._view.SetPropertyModel(model) + + + def OnEndDragLeft(self, x, y, keys = 0, attachment = 0): + ogl.ShapeEvtHandler.OnEndDragLeft(self, x, y, keys, attachment) + shape = self.GetShape() + if hasattr(shape, "GetModel"): # Workaround, on drag, we should deselect all other objects and select the clicked on object + model = shape.GetModel() + else: + parentShape = shape.GetParent() + if parentShape: + model = parentShape.GetModel() + self._view.SetSelection(model, keys == self.SHIFT_KEY or keys == self.CONTROL_KEY) + + + def OnMovePost(self, dc, x, y, oldX, oldY, display): + if x == oldX and y == oldY: + return + if not self._view.GetDocument(): + return + shape = self.GetShape() + if isinstance(shape, EditorCanvasShapeMixin) and shape.Draggable(): + model = shape.GetModel() + if hasattr(model, "getEditorBounds") and model.getEditorBounds(): + x, y, w, h = model.getEditorBounds() + newX = shape.GetX() - shape.GetBoundingBoxMax()[0] / 2 + newY = shape.GetY() - shape.GetBoundingBoxMax()[1] / 2 + newWidth = shape.GetBoundingBoxMax()[0] + newHeight = shape.GetBoundingBoxMax()[1] + if shape._shadowMode != ogl.SHADOW_NONE: + newWidth -= shape._shadowOffsetX + newHeight -= shape._shadowOffsetY + newbounds = (newX, newY, newWidth, newHeight) + + if x != newX or y != newY or w != newWidth or h != newHeight: + self._view.GetDocument().GetCommandProcessor().Submit(EditorCanvasUpdateShapeBoundariesCommand(self._view.GetDocument(), model, newbounds)) + + + def Draw(self, dc): + pass + + +class EditorCanvasUpdateShapeBoundariesCommand(wx.lib.docview.Command): + + + def __init__(self, canvasDocument, model, newbounds): + wx.lib.docview.Command.__init__(self, canUndo = True) + self._canvasDocument = canvasDocument + self._model = model + self._oldbounds = model.getEditorBounds() + self._newbounds = newbounds + + + def GetName(self): + name = self._canvasDocument.GetNameForObject(self._model) + if not name: + name = "" + print "ERROR: AbstractEditor.EditorCanvasUpdateShapeBoundariesCommand.GetName: unable to get name for ", self._model + return _("Move/Resize %s") % name + + + def Do(self): + return self._canvasDocument.UpdateEditorBoundaries(self._model, self._newbounds) + + + def Undo(self): + return self._canvasDocument.UpdateEditorBoundaries(self._model, self._oldbounds) + diff --git a/wxPython/samples/ide/activegrid/tool/CodeEditor.py b/wxPython/samples/ide/activegrid/tool/CodeEditor.py new file mode 100644 index 0000000000..09a96abf53 --- /dev/null +++ b/wxPython/samples/ide/activegrid/tool/CodeEditor.py @@ -0,0 +1,1014 @@ +#---------------------------------------------------------------------------- +# Name: CodeEditor.py +# Purpose: Abstract Code Editor for pydocview tbat uses the Styled Text Control +# +# Author: Peter Yared +# +# Created: 8/10/03 +# CVS-ID: $Id$ +# Copyright: (c) 2004-2005 ActiveGrid, Inc. +# License: wxWindows License +#---------------------------------------------------------------------------- + + +import STCTextEditor +import wx +import wx.lib.docview +import OutlineService +import os +import re +import string +import sys +import DebuggerService +import MarkerService +_ = wx.GetTranslation +if wx.Platform == '__WXMSW__': + _WINDOWS = True +else: + _WINDOWS = False + + +EXPAND_TEXT_ID = wx.NewId() +COLLAPSE_TEXT_ID = wx.NewId() +EXPAND_TOP_ID = wx.NewId() +COLLAPSE_TOP_ID = wx.NewId() +EXPAND_ALL_ID = wx.NewId() +COLLAPSE_ALL_ID = wx.NewId() +CHECK_CODE_ID = wx.NewId() +AUTO_COMPLETE_ID = wx.NewId() +CLEAN_WHITESPACE = wx.NewId() +COMMENT_LINES_ID = wx.NewId() +UNCOMMENT_LINES_ID = wx.NewId() +INDENT_LINES_ID = wx.NewId() +DEDENT_LINES_ID = wx.NewId() +USE_TABS_ID = wx.NewId() +SET_INDENT_WIDTH_ID = wx.NewId() +FOLDING_ID = wx.NewId() + + +class CodeDocument(STCTextEditor.TextDocument): + pass + + +class CodeView(STCTextEditor.TextView): + + + #---------------------------------------------------------------------------- + # Overridden methods + #---------------------------------------------------------------------------- + + + def GetCtrlClass(self): + """ Used in split window to instantiate new instances """ + return CodeCtrl + + + def ProcessEvent(self, event): + id = event.GetId() + if id == EXPAND_TEXT_ID: + self.GetCtrl().ToggleFold(self.GetCtrl().GetCurrentLine()) + return True + elif id == COLLAPSE_TEXT_ID: + self.GetCtrl().ToggleFold(self.GetCtrl().GetCurrentLine()) + return True + elif id == EXPAND_TOP_ID: + self.GetCtrl().ToggleFoldAll(expand = True, topLevelOnly = True) + return True + elif id == COLLAPSE_TOP_ID: + self.GetCtrl().ToggleFoldAll(expand = False, topLevelOnly = True) + return True + elif id == EXPAND_ALL_ID: + self.GetCtrl().ToggleFoldAll(expand = True) + return True + elif id == COLLAPSE_ALL_ID: + self.GetCtrl().ToggleFoldAll(expand = False) + return True + elif id == CHECK_CODE_ID: + self.OnCheckCode() + return True + elif id == AUTO_COMPLETE_ID: + self.OnAutoComplete() + return True + elif id == CLEAN_WHITESPACE: + self.OnCleanWhiteSpace() + return True + elif id == SET_INDENT_WIDTH_ID: + self.OnSetIndentWidth() + return True + elif id == USE_TABS_ID: + self.GetCtrl().SetUseTabs(not self.GetCtrl().GetUseTabs()) + return True + elif id == INDENT_LINES_ID: + self.GetCtrl().CmdKeyExecute(wx.stc.STC_CMD_TAB) + return True + elif id == DEDENT_LINES_ID: + self.GetCtrl().CmdKeyExecute(wx.stc.STC_CMD_BACKTAB) + return True + elif id == COMMENT_LINES_ID: + self.OnCommentLines() + return True + elif id == UNCOMMENT_LINES_ID: + self.OnUncommentLines() + return True + else: + return STCTextEditor.TextView.ProcessEvent(self, event) + + + def ProcessUpdateUIEvent(self, event): + if not self.GetCtrl(): + return False + hasText = self.GetCtrl().GetTextLength() > 0 + id = event.GetId() + if id == EXPAND_TEXT_ID: + event.Enable(self.GetCtrl().CanLineExpand(self.GetCtrl().GetCurrentLine())) + return True + elif id == COLLAPSE_TEXT_ID: + event.Enable(self.GetCtrl().CanLineCollapse(self.GetCtrl().GetCurrentLine())) + return True + elif id == EXPAND_TOP_ID: + event.Enable(hasText) + return True + elif id == COLLAPSE_TOP_ID: + event.Enable(hasText) + return True + elif id == EXPAND_ALL_ID: + event.Enable(hasText) + return True + elif id == COLLAPSE_ALL_ID: + event.Enable(hasText) + return True + elif id == CHECK_CODE_ID: + event.Enable(False) + return True + elif id == AUTO_COMPLETE_ID: + event.Enable(hasText) + return True + elif id == CLEAN_WHITESPACE: + event.Enable(hasText) + return True + elif id == SET_INDENT_WIDTH_ID: + event.Enable(True) + return True + elif id == USE_TABS_ID: + event.Enable(True) + event.Check(self.GetCtrl().GetUseTabs()) + return True + elif id == INDENT_LINES_ID: + event.Enable(hasText) + return True + elif id == DEDENT_LINES_ID: + event.Enable(hasText) + return True + elif id == COMMENT_LINES_ID: + event.Enable(hasText) + return True + elif id == UNCOMMENT_LINES_ID: + event.Enable(hasText) + return True + elif id == FOLDING_ID: + event.Enable(True) + return True + else: + return STCTextEditor.TextView.ProcessUpdateUIEvent(self, event) + + + #---------------------------------------------------------------------------- + # Methods for OutlineService + #---------------------------------------------------------------------------- + + def OnChangeFilename(self): + wx.lib.docview.View.OnChangeFilename(self) + self.LoadOutline(force=True) + + + def ClearOutline(self): + outlineService = wx.GetApp().GetService(OutlineService.OutlineService) + if not outlineService: + return + + outlineView = outlineService.GetView() + if not outlineView: + return + + outlineView.ClearTreeCtrl() + + + def LoadOutline(self, force=False): + outlineService = wx.GetApp().GetService(OutlineService.OutlineService) + if not outlineService: + return + outlineService.LoadOutline(self, force=force) + + + def DoLoadOutlineCallback(self, force=False): + outlineService = wx.GetApp().GetService(OutlineService.OutlineService) + if not outlineService: + return False + + outlineView = outlineService.GetView() + if not outlineView: + return False + + treeCtrl = outlineView.GetTreeCtrl() + if not treeCtrl: + return False + + view = treeCtrl.GetCallbackView() + newCheckSum = self.GenCheckSum() + if not force: + if view and view is self: + if self._checkSum == newCheckSum: + return False + self._checkSum = newCheckSum + + treeCtrl.DeleteAllItems() + + document = self.GetDocument() + if not document: + return True + + filename = document.GetFilename() + if filename: + rootItem = treeCtrl.AddRoot(os.path.basename(filename)) + treeCtrl.SetDoSelectCallback(rootItem, self, None) + else: + return True + + text = self.GetValue() + if not text: + return True + + CLASS_PATTERN = 'class[ \t]+\w+.*?:' + DEF_PATTERN = 'def[ \t]+\w+\(.*?\)' + classPat = re.compile(CLASS_PATTERN, re.M|re.S) + defPat= re.compile(DEF_PATTERN, re.M|re.S) + pattern = re.compile('^[ \t]*((' + CLASS_PATTERN + ')|('+ DEF_PATTERN +'.*?:)).*?$', re.M|re.S) + + iter = pattern.finditer(text) + indentStack = [(0, rootItem)] + for pattern in iter: + line = pattern.string[pattern.start(0):pattern.end(0)] + classLine = classPat.search(line) + if classLine: + indent = classLine.start(0) + itemStr = classLine.string[classLine.start(0):classLine.end(0)-1] # don't take the closing ':' + else: + defLine = defPat.search(line) + if defLine: + indent = defLine.start(0) + itemStr = defLine.string[defLine.start(0):defLine.end(0)] + + if indent == 0: + parentItem = rootItem + else: + lastItem = indentStack.pop() + while lastItem[0] >= indent: + lastItem = indentStack.pop() + indentStack.append(lastItem) + parentItem = lastItem[1] + + item = treeCtrl.AppendItem(parentItem, itemStr) + treeCtrl.SetDoSelectCallback(item, self, (pattern.end(0), pattern.start(0) + indent)) # select in reverse order because we want the cursor to be at the start of the line so it wouldn't scroll to the right + indentStack.append((indent, item)) + + treeCtrl.Expand(rootItem) + + return True + + + def DoSelectCallback(self, data): + if data: + self.EnsureVisibleEnforcePolicy(self.LineFromPosition(data[0])) + # wxBug: need to select in reverse order (end, start) to place cursor at begining of line, + # otherwise, display is scrolled over to the right hard and is hard to view + self.SetSelection(data[1], data[0]) + + +## def checksum(self, bytes): +## def rotate_right(c): +## if c&1: +## return (c>>1)|0x8000 +## else: +## return c>>1 +## +## result = 0 +## for ch in bytes: +## ch = ord(ch) & 0xFF +## result = (rotate_right(result)+ch) & 0xFFFF +## return result +## + + def GenCheckSum(self): + """ Poor man's checksum. We'll assume most changes will change the length of the file. + """ + text = self.GetValue() + if text: + return len(text) + else: + return 0 + + + #---------------------------------------------------------------------------- + # Format methods + #---------------------------------------------------------------------------- + + def OnCheckCode(self): + """ Need to overshadow this for each specific subclass """ + if 0: + try: + code = self.GetCtrl().GetText() + codeObj = compile(code, self.GetDocument().GetFilename(), 'exec') + self._GetParentFrame().SetStatusText(_("The file successfully compiled")) + except SyntaxError, (message, (fileName, line, col, text)): + pos = self.GetCtrl().PositionFromLine(line - 1) + col - 1 + self.GetCtrl().SetSelection(pos, pos) + self._GetParentFrame().SetStatusText(_("Syntax Error: %s") % message) + except: + self._GetParentFrame().SetStatusText(sys.exc_info()[0]) + + + def OnAutoComplete(self): + self.GetCtrl().AutoCompCancel() + self.GetCtrl().AutoCompSetAutoHide(0) + self.GetCtrl().AutoCompSetChooseSingle(True) + self.GetCtrl().AutoCompSetIgnoreCase(True) + context, hint = self.GetAutoCompleteHint() + replaceList, replaceLen = self.GetAutoCompleteKeywordList(context, hint) + if replaceList and len(replaceList) != 0: + self.GetCtrl().AutoCompShow(replaceLen, replaceList) + + + def GetAutoCompleteHint(self): + """ Replace this method with Editor specific method """ + pos = self.GetCtrl().GetCurrentPos() + if pos == 0: + return None, None + if chr(self.GetCtrl().GetCharAt(pos - 1)) == '.': + pos = pos - 1 + hint = None + else: + hint = '' + + validLetters = string.letters + string.digits + '_.' + word = '' + while (True): + pos = pos - 1 + if pos < 0: + break + char = chr(self.GetCtrl().GetCharAt(pos)) + if char not in validLetters: + break + word = char + word + + context = word + if hint is not None: + lastDot = word.rfind('.') + if lastDot != -1: + context = word[0:lastDot] + hint = word[lastDot+1:] + + return context, hint + + + def GetAutoCompleteDefaultKeywords(self): + """ Replace this method with Editor specific keywords """ + return ['Put', 'Editor Specific', 'Keywords', 'Here'] + + + def CaseInsensitiveCompare(self, s1, s2): + """ GetAutoCompleteKeywordList() method used to show keywords in case insensitive order """ + s1L = s1.lower() + s2L = s2.lower() + if s1L == s2L: + return 0 + elif s1L < s2L: + return -1 + else: + return 1 + + + def GetAutoCompleteKeywordList(self, context, hint): + """ Replace this method with Editor specific keywords """ + kw = self.GetAutoCompleteDefaultKeywords() + + if hint and len(hint): + lowerHint = hint.lower() + filterkw = filter(lambda item: item.lower().startswith(lowerHint), kw) # remove variables and methods that don't match hint + kw = filterkw + + if hint: + replaceLen = len(hint) + else: + replaceLen = 0 + + kw.sort(self.CaseInsensitiveCompare) + return " ".join(kw), replaceLen + + + def OnCleanWhiteSpace(self): + newText = "" + for lineNo in self._GetSelectedLineNumbers(): + lineText = string.rstrip(self.GetCtrl().GetLine(lineNo)) + indent = 0 + lstrip = 0 + for char in lineText: + if char == '\t': + indent = indent + self.GetCtrl().GetIndent() + lstrip = lstrip + 1 + elif char in string.whitespace: + indent = indent + 1 + lstrip = lstrip + 1 + else: + break + if self.GetCtrl().GetUseTabs(): + indentText = (indent / self.GetCtrl().GetIndent()) * '\t' + (indent % self.GetCtrl().GetIndent()) * ' ' + else: + indentText = indent * ' ' + lineText = indentText + lineText[lstrip:] + '\n' + newText = newText + lineText + self._ReplaceSelectedLines(newText) + + + def OnSetIndentWidth(self): + dialog = wx.TextEntryDialog(self._GetParentFrame(), _("Enter new indent width (2-10):"), _("Set Indent Width"), "%i" % self.GetCtrl().GetIndent()) + if dialog.ShowModal() == wx.ID_OK: + try: + indent = int(dialog.GetValue()) + if indent >= 2 and indent <= 10: + self.GetCtrl().SetIndent(indent) + self.GetCtrl().SetTabWidth(indent) + except: + pass + dialog.Destroy() + + + def GetIndentWidth(self): + return self.GetCtrl().GetIndent() + + + def OnCommentLines(self): + newText = "" + for lineNo in self._GetSelectedLineNumbers(): + lineText = self.GetCtrl().GetLine(lineNo) + if (len(lineText) > 1 and lineText[0] == '#') or (len(lineText) > 2 and lineText[:2] == '##'): + newText = newText + lineText + else: + newText = newText + "##" + lineText + self._ReplaceSelectedLines(newText) + + + def OnUncommentLines(self): + newText = "" + for lineNo in self._GetSelectedLineNumbers(): + lineText = self.GetCtrl().GetLine(lineNo) + if len(lineText) >= 2 and lineText[:2] == "##": + lineText = lineText[2:] + elif len(lineText) >= 1 and lineText[:1] == "#": + lineText = lineText[1:] + newText = newText + lineText + self._ReplaceSelectedLines(newText) + + + def _GetSelectedLineNumbers(self): + selStart, selEnd = self._GetPositionsBoundingSelectedLines() + return range(self.GetCtrl().LineFromPosition(selStart), self.GetCtrl().LineFromPosition(selEnd)) + + + def _GetPositionsBoundingSelectedLines(self): + startPos = self.GetCtrl().GetCurrentPos() + endPos = self.GetCtrl().GetAnchor() + if startPos > endPos: + temp = endPos + endPos = startPos + startPos = temp + if endPos == self.GetCtrl().PositionFromLine(self.GetCtrl().LineFromPosition(endPos)): + endPos = endPos - 1 # If it's at the very beginning of a line, use the line above it as the ending line + selStart = self.GetCtrl().PositionFromLine(self.GetCtrl().LineFromPosition(startPos)) + selEnd = self.GetCtrl().PositionFromLine(self.GetCtrl().LineFromPosition(endPos) + 1) + return selStart, selEnd + + + def _ReplaceSelectedLines(self, text): + if len(text) == 0: + return + selStart, selEnd = self._GetPositionsBoundingSelectedLines() + self.GetCtrl().SetSelection(selStart, selEnd) + self.GetCtrl().ReplaceSelection(text) + self.GetCtrl().SetSelection(selStart + len(text), selStart) + + + def OnUpdate(self, sender = None, hint = None): + if hint == "ViewStuff": + self.GetCtrl().SetViewDefaults() + elif hint == "Font": + font, color = self.GetFontAndColorFromConfig() + self.GetCtrl().SetFont(font) + self.GetCtrl().SetFontColor(color) + else: + dbg_service = wx.GetApp().GetService(DebuggerService.DebuggerService) + if dbg_service: + dbg_service.SetCurrentBreakpointMarkers(self) + + +class CodeService(STCTextEditor.TextService): + + + def __init__(self): + STCTextEditor.TextService.__init__(self) + + + def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None): + # TODO NEED TO DO INSTANCEOF CHECK HERE FOR SDI + #if document and document.GetDocumentTemplate().GetDocumentType() != TextDocument: + # return + if not document and wx.GetApp().GetDocumentManager().GetFlags() & wx.lib.docview.DOC_SDI: + return + + viewMenu = menuBar.GetMenu(menuBar.FindMenu(_("&View"))) + isWindows = (wx.Platform == '__WXMSW__') + + if not menuBar.FindItemById(EXPAND_TEXT_ID): # check if below menu items have been already been installed + foldingMenu = wx.Menu() + if isWindows: + foldingMenu.Append(EXPAND_TEXT_ID, _("&Expand\tNumpad-Plus"), _("Expands a collapsed block of text")) + else: + foldingMenu.Append(EXPAND_TEXT_ID, _("&Expand"), _("Expands a collapsed block of text")) + + wx.EVT_MENU(frame, EXPAND_TEXT_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, EXPAND_TEXT_ID, frame.ProcessUpdateUIEvent) + + if isWindows: + foldingMenu.Append(COLLAPSE_TEXT_ID, _("&Collapse\tNumpad+Minus"), _("Collapse a block of text")) + else: + foldingMenu.Append(COLLAPSE_TEXT_ID, _("&Collapse"), _("Collapse a block of text")) + wx.EVT_MENU(frame, COLLAPSE_TEXT_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, COLLAPSE_TEXT_ID, frame.ProcessUpdateUIEvent) + + if isWindows: + foldingMenu.Append(EXPAND_TOP_ID, _("Expand &Top Level\tCtrl+Numpad+Plus"), _("Expands the top fold levels in the document")) + else: + foldingMenu.Append(EXPAND_TOP_ID, _("Expand &Top Level"), _("Expands the top fold levels in the document")) + wx.EVT_MENU(frame, EXPAND_TOP_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, EXPAND_TOP_ID, frame.ProcessUpdateUIEvent) + + if isWindows: + foldingMenu.Append(COLLAPSE_TOP_ID, _("Collapse Top &Level\tCtrl+Numpad+Minus"), _("Collapses the top fold levels in the document")) + else: + foldingMenu.Append(COLLAPSE_TOP_ID, _("Collapse Top &Level"), _("Collapses the top fold levels in the document")) + wx.EVT_MENU(frame, COLLAPSE_TOP_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, COLLAPSE_TOP_ID, frame.ProcessUpdateUIEvent) + + if isWindows: + foldingMenu.Append(EXPAND_ALL_ID, _("Expand &All\tShift+Numpad+Plus"), _("Expands all of the fold levels in the document")) + else: + foldingMenu.Append(EXPAND_ALL_ID, _("Expand &All"), _("Expands all of the fold levels in the document")) + wx.EVT_MENU(frame, EXPAND_ALL_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, EXPAND_ALL_ID, frame.ProcessUpdateUIEvent) + + if isWindows: + foldingMenu.Append(COLLAPSE_ALL_ID, _("Colla&pse All\tShift+Numpad+Minus"), _("Collapses all of the fold levels in the document")) + else: + foldingMenu.Append(COLLAPSE_ALL_ID, _("Colla&pse All"), _("Collapses all of the fold levels in the document")) + wx.EVT_MENU(frame, COLLAPSE_ALL_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, COLLAPSE_ALL_ID, frame.ProcessUpdateUIEvent) + + viewMenu.AppendMenu(FOLDING_ID, _("&Folding"), foldingMenu) + wx.EVT_UPDATE_UI(frame, FOLDING_ID, frame.ProcessUpdateUIEvent) + + formatMenuIndex = menuBar.FindMenu(_("&Format")) + if formatMenuIndex > -1: + formatMenu = menuBar.GetMenu(formatMenuIndex) + else: + formatMenu = wx.Menu() + if not menuBar.FindItemById(CHECK_CODE_ID): # check if below menu items have been already been installed + formatMenu.AppendSeparator() + formatMenu.Append(CHECK_CODE_ID, _("&Check Code"), _("Checks the document for syntax and indentation errors")) + wx.EVT_MENU(frame, CHECK_CODE_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, CHECK_CODE_ID, frame.ProcessUpdateUIEvent) + formatMenu.Append(AUTO_COMPLETE_ID, _("&Auto Complete\tCtrl+Space"), _("Provides suggestions on how to complete the current statement")) + wx.EVT_MENU(frame, AUTO_COMPLETE_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, AUTO_COMPLETE_ID, frame.ProcessUpdateUIEvent) + formatMenu.Append(CLEAN_WHITESPACE, _("Clean &Whitespace"), _("Converts leading spaces to tabs or vice versa per 'use tabs' and clears trailing spaces")) + wx.EVT_MENU(frame, CLEAN_WHITESPACE, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, CLEAN_WHITESPACE, frame.ProcessUpdateUIEvent) + formatMenu.AppendSeparator() + formatMenu.Append(INDENT_LINES_ID, _("&Indent Lines\tTab"), _("Indents the selected lines one indent width")) + wx.EVT_MENU(frame, INDENT_LINES_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, INDENT_LINES_ID, frame.ProcessUpdateUIEvent) + formatMenu.Append(DEDENT_LINES_ID, _("&Dedent Lines\tShift+Tab"), _("Dedents the selected lines one indent width")) + wx.EVT_MENU(frame, DEDENT_LINES_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, DEDENT_LINES_ID, frame.ProcessUpdateUIEvent) + formatMenu.Append(COMMENT_LINES_ID, _("Comment &Lines\tCtrl+Q"), _("Comments out the selected lines be prefixing each one with a comment indicator")) + wx.EVT_MENU(frame, COMMENT_LINES_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, COMMENT_LINES_ID, frame.ProcessUpdateUIEvent) + formatMenu.Append(UNCOMMENT_LINES_ID, _("&Uncomment Lines\tCtrl+Shift+Q"), _("Removes comment prefixes from each of the selected lines")) + wx.EVT_MENU(frame, UNCOMMENT_LINES_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, UNCOMMENT_LINES_ID, frame.ProcessUpdateUIEvent) + formatMenu.AppendSeparator() + formatMenu.AppendCheckItem(USE_TABS_ID, _("Use &Tabs"), _("Toggles use of tabs or whitespaces for indents")) + wx.EVT_MENU(frame, USE_TABS_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, USE_TABS_ID, frame.ProcessUpdateUIEvent) + formatMenu.Append(SET_INDENT_WIDTH_ID, _("&Set Indent Width..."), _("Sets the indent width")) + wx.EVT_MENU(frame, SET_INDENT_WIDTH_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, SET_INDENT_WIDTH_ID, frame.ProcessUpdateUIEvent) + if formatMenuIndex == -1: + viewMenuIndex = menuBar.FindMenu(_("&View")) + menuBar.Insert(viewMenuIndex + 1, formatMenu, _("&Format")) + +## accelTable = wx.AcceleratorTable([ +## (wx.ACCEL_NORMAL, wx.WXK_TAB, INDENT_LINES_ID), +## (wx.ACCEL_SHIFT, wx.WXK_TAB, DEDENT_LINES_ID), +## eval(_("wx.ACCEL_CTRL, ord('Q'), COMMENT_LINES_ID")), +## eval(_("wx.ACCEL_CTRL | wx.ACCEL_SHIFT, ord('Q'), UNCOMMENT_LINES_ID")) +## ]) +## frame.SetAcceleratorTable(accelTable) + + def ProcessUpdateUIEvent(self, event): + id = event.GetId() + if id == EXPAND_TEXT_ID: + event.Enable(False) + return True + elif id == COLLAPSE_TEXT_ID: + event.Enable(False) + return True + elif id == EXPAND_TOP_ID: + event.Enable(False) + return True + elif id == COLLAPSE_TOP_ID: + event.Enable(False) + return True + elif id == EXPAND_ALL_ID: + event.Enable(False) + return True + elif id == COLLAPSE_ALL_ID: + event.Enable(False) + return True + elif id == CHECK_CODE_ID: + event.Enable(False) + return True + elif id == AUTO_COMPLETE_ID: + event.Enable(False) + return True + elif id == CLEAN_WHITESPACE: + event.Enable(False) + return True + elif id == SET_INDENT_WIDTH_ID: + event.Enable(False) + return True + elif id == USE_TABS_ID: + event.Enable(False) + return True + elif id == INDENT_LINES_ID: + event.Enable(False) + return True + elif id == DEDENT_LINES_ID: + event.Enable(False) + return True + elif id == COMMENT_LINES_ID: + event.Enable(False) + return True + elif id == UNCOMMENT_LINES_ID: + event.Enable(False) + return True + elif id == FOLDING_ID: + event.Enable(False) + return True + else: + return STCTextEditor.TextService.ProcessUpdateUIEvent(self, event) + + +class CodeCtrl(STCTextEditor.TextCtrl): + CURRENT_LINE_MARKER_NUM = 2 + BREAKPOINT_MARKER_NUM = 1 + CURRENT_LINE_MARKER_MASK = 0x4 + BREAKPOINT_MARKER_MASK = 0x2 + + + def __init__(self, parent, ID = -1, style = wx.NO_FULL_REPAINT_ON_RESIZE): + if ID == -1: + ID = wx.NewId() + STCTextEditor.TextCtrl.__init__(self, parent, ID, style) + + self.UsePopUp(False) + self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp) + self.SetProperty("fold", "1") + + # Setup a margin to hold fold markers + #self.SetFoldFlags(16) ### WHAT IS THIS VALUE? WHAT ARE THE OTHER FLAGS? DOES IT MATTER? + self.SetMarginType(2, wx.stc.STC_MARGIN_SYMBOL) + self.SetMarginMask(2, wx.stc.STC_MASK_FOLDERS) + self.SetMarginSensitive(2, True) + self.SetMarginWidth(2, 12) + + self.SetMarginSensitive(1, False) + self.SetMarginMask(1, 0x4) + + self.SetMarginSensitive(0, True) + self.SetMarginType(0, wx.stc.STC_MARGIN_SYMBOL) + self.SetMarginMask(0, 0x3) + self.SetMarginWidth(0, 12) + + self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDEREND, wx.stc.STC_MARK_BOXPLUSCONNECTED, "white", "black") + self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDEROPENMID, wx.stc.STC_MARK_BOXMINUSCONNECTED, "white", "black") + self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERMIDTAIL, wx.stc.STC_MARK_TCORNER, "white", "black") + self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERTAIL, wx.stc.STC_MARK_LCORNER, "white", "black") + self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERSUB, wx.stc.STC_MARK_VLINE, "white", "black") + self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDER, wx.stc.STC_MARK_BOXPLUS, "white", "black") + self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDEROPEN, wx.stc.STC_MARK_BOXMINUS, "white", "black") + # Define the current line marker + self.MarkerDefine(CodeCtrl.CURRENT_LINE_MARKER_NUM, wx.stc.STC_MARK_SHORTARROW, wx.BLACK, (255,255,128)) + # Define the breakpoint marker + self.MarkerDefine(CodeCtrl.BREAKPOINT_MARKER_NUM, wx.stc.STC_MARK_CIRCLE, wx.BLACK, (255,0,0)) + + if _WINDOWS: # should test to see if menu item exists, if it does, add this workaround + self.CmdKeyClear(wx.stc.STC_KEY_TAB, 0) # menu item "Indent Lines" from CodeService.InstallControls() generates another INDENT_LINES_ID event, so we'll explicitly disable the tab processing in the editor + + wx.stc.EVT_STC_MARGINCLICK(self, ID, self.OnMarginClick) + wx.EVT_KEY_DOWN(self, self.OnKeyPressed) + if self.GetMatchingBraces(): + wx.stc.EVT_STC_UPDATEUI(self, ID, self.OnUpdateUI) + + self.StyleClearAll() + self.UpdateStyles() + + + def OnRightUp(self, event): + #Hold onto the current line number, no way to get it later. + self._rightClickPosition = self.PositionFromPoint(event.GetPosition()) + self._rightClickLine = self.LineFromPosition(self._rightClickPosition) + self.PopupMenu(self.CreatePopupMenu(), event.GetPosition()) + self._rightClickLine = -1 + self._rightClickPosition = -1 + + + def CreatePopupMenu(self): + TOGGLEBREAKPOINT_ID = wx.NewId() + TOGGLEMARKER_ID = wx.NewId() + SYNCTREE_ID = wx.NewId() + + menu = wx.Menu() + + self.Bind(wx.EVT_MENU, self.OnPopSyncOutline, id=SYNCTREE_ID) + item = wx.MenuItem(menu, SYNCTREE_ID, _("Find in Outline View")) + menu.AppendItem(item) + menu.AppendSeparator() + self.Bind(wx.EVT_MENU, self.OnPopToggleBP, id=TOGGLEBREAKPOINT_ID) + item = wx.MenuItem(menu, TOGGLEBREAKPOINT_ID, _("Toggle Breakpoint")) + menu.AppendItem(item) + self.Bind(wx.EVT_MENU, self.OnPopToggleMarker, id=TOGGLEMARKER_ID) + item = wx.MenuItem(menu, TOGGLEMARKER_ID, _("Toggle Marker")) + menu.AppendItem(item) + menu.AppendSeparator() + + itemIDs = [wx.ID_UNDO, wx.ID_REDO, None, + wx.ID_CUT, wx.ID_COPY, wx.ID_PASTE, wx.ID_CLEAR, None, wx.ID_SELECTALL] + + menuBar = wx.GetApp().GetTopWindow().GetMenuBar() + for itemID in itemIDs: + if not itemID: + menu.AppendSeparator() + else: + item = menuBar.FindItemById(itemID) + if item: + menu.Append(itemID, item.GetLabel()) + + return menu + + + def OnPopToggleBP(self, event): + """ Toggle break point on right click line, not current line """ + wx.GetApp().GetService(DebuggerService.DebuggerService).OnToggleBreakpoint(event, line=self._rightClickLine) + + + def OnPopToggleMarker(self, event): + """ Toggle marker on right click line, not current line """ + wx.GetApp().GetDocumentManager().GetCurrentView().MarkerToggle(lineNum = self._rightClickLine) + + + def OnPopSyncOutline(self, event): + wx.GetApp().GetService(OutlineService.OutlineService).LoadOutline(wx.GetApp().GetDocumentManager().GetCurrentView(), position=self._rightClickPosition) + + + def HasSelection(self): + return self.GetSelectionStart() - self.GetSelectionEnd() != 0 + + + def ClearCurrentLineMarkers(self): + self.MarkerDeleteAll(CodeCtrl.CURRENT_LINE_MARKER_NUM) + + + def ClearCurrentBreakpoinMarkers(self): + self.MarkerDeleteAll(CodeCtrl.BREAKPOINT_MARKER_NUM) + + + def GetDefaultFont(self): + if wx.Platform == '__WXMSW__': + font = "Courier New" + else: + font = "Courier" + return wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, faceName = font) + + + def GetMatchingBraces(self): + """ Overwrite this method for language specific braces """ + return "[]{}()" + + + def CanWordWrap(self): + return False + + + def SetFont(self, font): + self._font = font + + + def SetFontColor(self, fontColor): + self._fontColor = fontColor + + + def UpdateStyles(self): + + if not self.GetFont(): + return + + faces = { 'font' : self.GetFont().GetFaceName(), + 'size' : self.GetFont().GetPointSize(), + 'size2': self.GetFont().GetPointSize() - 2, + 'color' : "%02x%02x%02x" % (self.GetFontColor().Red(), self.GetFontColor().Green(), self.GetFontColor().Blue()) + } + + # Global default styles for all languages + self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, "face:%(font)s,fore:#FFFFFF,size:%(size)d" % faces) + self.StyleSetSpec(wx.stc.STC_STYLE_LINENUMBER, "face:%(font)s,back:#C0C0C0,face:%(font)s,size:%(size2)d" % faces) + self.StyleSetSpec(wx.stc.STC_STYLE_CONTROLCHAR, "face:%(font)s" % faces) + self.StyleSetSpec(wx.stc.STC_STYLE_BRACELIGHT, "face:%(font)s,fore:#000000,back:#70FFFF,size:%(size)d" % faces) + self.StyleSetSpec(wx.stc.STC_STYLE_BRACEBAD, "face:%(font)s,fore:#000000,back:#FF0000,size:%(size)d" % faces) + + + def OnKeyPressed(self, event): + if self.CallTipActive(): + self.CallTipCancel() + key = event.KeyCode() + if False: # key == wx.WXK_SPACE and event.ControlDown(): + pos = self.GetCurrentPos() + # Tips + if event.ShiftDown(): + self.CallTipSetBackground("yellow") + self.CallTipShow(pos, 'param1, param2') + # Code completion + else: + #lst = [] + #for x in range(50000): + # lst.append('%05d' % x) + #st = string.join(lst) + #print len(st) + #self.AutoCompShow(0, st) + + kw = keyword.kwlist[:] + kw.append("zzzzzz") + kw.append("aaaaa") + kw.append("__init__") + kw.append("zzaaaaa") + kw.append("zzbaaaa") + kw.append("this_is_a_longer_value") + kw.append("this_is_a_much_much_much_much_much_much_much_longer_value") + + kw.sort() # Python sorts are case sensitive + self.AutoCompSetIgnoreCase(False) # so this needs to match + + self.AutoCompShow(0, string.join(kw)) + elif key == wx.WXK_RETURN: + self.DoIndent() + else: + STCTextEditor.TextCtrl.OnKeyPressed(self, event) + + + def DoIndent(self): + self.AddText('\n') + # Need to do a default one for all languges + + + def OnMarginClick(self, evt): + # fold and unfold as needed + if evt.GetMargin() == 2: + if evt.GetShift() and evt.GetControl(): + lineCount = self.GetLineCount() + expanding = True + + # find out if we are folding or unfolding + for lineNum in range(lineCount): + if self.GetFoldLevel(lineNum) & wx.stc.STC_FOLDLEVELHEADERFLAG: + expanding = not self.GetFoldExpanded(lineNum) + break; + + self.ToggleFoldAll(expanding) + else: + lineClicked = self.LineFromPosition(evt.GetPosition()) + if self.GetFoldLevel(lineClicked) & wx.stc.STC_FOLDLEVELHEADERFLAG: + if evt.GetShift(): + self.SetFoldExpanded(lineClicked, True) + self.Expand(lineClicked, True, True, 1) + elif evt.GetControl(): + if self.GetFoldExpanded(lineClicked): + self.SetFoldExpanded(lineClicked, False) + self.Expand(lineClicked, False, True, 0) + else: + self.SetFoldExpanded(lineClicked, True) + self.Expand(lineClicked, True, True, 100) + else: + self.ToggleFold(lineClicked) + + elif evt.GetMargin() == 0: + #This is used to toggle breakpoints via the debugger service. + db_service = wx.GetApp().GetService(DebuggerService.DebuggerService) + if db_service: + db_service.OnToggleBreakpoint(evt, line=self.LineFromPosition(evt.GetPosition())) + + + def OnUpdateUI(self, evt): + braces = self.GetMatchingBraces() + + # check for matching braces + braceAtCaret = -1 + braceOpposite = -1 + charBefore = None + caretPos = self.GetCurrentPos() + if caretPos > 0: + charBefore = self.GetCharAt(caretPos - 1) + styleBefore = self.GetStyleAt(caretPos - 1) + + # check before + if charBefore and chr(charBefore) in braces: + braceAtCaret = caretPos - 1 + + # check after + if braceAtCaret < 0: + charAfter = self.GetCharAt(caretPos) + styleAfter = self.GetStyleAt(caretPos) + if charAfter and chr(charAfter) in braces: + braceAtCaret = caretPos + + if braceAtCaret >= 0: + braceOpposite = self.BraceMatch(braceAtCaret) + + if braceAtCaret != -1 and braceOpposite == -1: + self.BraceBadLight(braceAtCaret) + else: + self.BraceHighlight(braceAtCaret, braceOpposite) + + evt.Skip() + + + def ToggleFoldAll(self, expand = True, topLevelOnly = False): + i = 0 + lineCount = self.GetLineCount() + while i < lineCount: + if not topLevelOnly or (topLevelOnly and self.GetFoldLevel(i) & wx.stc.STC_FOLDLEVELNUMBERMASK == wx.stc.STC_FOLDLEVELBASE): + if (expand and self.CanLineExpand(i)) or (not expand and self.CanLineCollapse(i)): + self.ToggleFold(i) + i = i + 1 + + + def CanLineExpand(self, line): + return not self.GetFoldExpanded(line) + + + def CanLineCollapse(self, line): + return self.GetFoldExpanded(line) and self.GetFoldLevel(line) & wx.stc.STC_FOLDLEVELHEADERFLAG + + + def Expand(self, line, doExpand, force=False, visLevels=0, level=-1): + lastChild = self.GetLastChild(line, level) + line = line + 1 + while line <= lastChild: + if force: + if visLevels > 0: + self.ShowLines(line, line) + else: + self.HideLines(line, line) + else: + if doExpand: + self.ShowLines(line, line) + + if level == -1: + level = self.GetFoldLevel(line) + + if level & wx.stc.STC_FOLDLEVELHEADERFLAG: + if force: + if visLevels > 1: + self.SetFoldExpanded(line, True) + else: + self.SetFoldExpanded(line, False) + line = self.Expand(line, doExpand, force, visLevels-1) + + else: + if doExpand and self.GetFoldExpanded(line): + line = self.Expand(line, True, force, visLevels-1) + else: + line = self.Expand(line, False, force, visLevels-1) + else: + line = line + 1; + + return line + + diff --git a/wxPython/samples/ide/activegrid/tool/DebuggerHarness.py b/wxPython/samples/ide/activegrid/tool/DebuggerHarness.py new file mode 100644 index 0000000000..a12b8e579b --- /dev/null +++ b/wxPython/samples/ide/activegrid/tool/DebuggerHarness.py @@ -0,0 +1,690 @@ +#---------------------------------------------------------------------------- +# Name: DebuggerHarness.py +# Purpose: +# +# Author: Matt Fryer +# +# Created: 7/28/04 +# CVS-ID: $Id$ +# Copyright: (c) 2005 ActiveGrid, Inc. +# License: wxWindows License +#---------------------------------------------------------------------------- +import bdb +import sys +import SimpleXMLRPCServer +import threading +import xmlrpclib +import os +import types +import Queue +import traceback +import inspect +from xml.dom.minidom import getDOMImplementation +import atexit +import pickle + +if sys.platform.startswith("win"): + import win32api + _WINDOWS = True +else: + _WINDOWS = False + +_VERBOSE = False +_DEBUG_DEBUGGER = False + +class Adb(bdb.Bdb): + + def __init__(self, harness, queue): + bdb.Bdb.__init__(self) + self._harness = harness + self._userBreak = False + self._queue = queue + self._knownCantExpandFiles = {} + self._knownExpandedFiles = {} + + def getLongName(self, filename): + if not _WINDOWS: + return filename + if self._knownCantExpandFiles.get(filename): + return filename + if self._knownExpandedFiles.get(filename): + return self._knownExpandedFiles.get(filename) + try: + newname = win32api.GetLongPathName(filename) + self._knownExpandedFiles[filename] = newname + return newname + except: + self._knownCantExpandFiles[filename] = filename + return filename + + def canonic(self, orig_filename): + if orig_filename == "<" + orig_filename[1:-1] + ">": + return orig_filename + filename = self.getLongName(orig_filename) + + canonic = self.fncache.get(filename) + if not canonic: + canonic = os.path.abspath(filename) + canonic = os.path.normcase(canonic) + self.fncache[filename] = canonic + return canonic + + + # Overriding this so that we continue to trace even if no breakpoints are set. + def set_continue(self): + self.stopframe = self.botframe + self.returnframe = None + self.quitting = 0 + + def do_clear(self, arg): + bdb.Breakpoint.bpbynumber[int(arg)].deleteMe() + + def user_line(self, frame): + if self.in_debugger_code(frame): + self.set_step() + return + message = self.__frame2message(frame) + self._harness.interaction(message, frame, "") + + def user_call(self, frame, argument_list): + if self.in_debugger_code(frame): + self.set_step() + return + if self.stop_here(frame): + message = self.__frame2message(frame) + self._harness.interaction(message, frame, "") + + def user_return(self, frame, return_value): + if self.in_debugger_code(frame): + self.set_step() + return + message = self.__frame2message(frame) + self._harness.interaction(message, frame, "") + + def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): + frame.f_locals['__exception__'] = exc_type, exc_value + if type(exc_type) == type(''): + exc_type_name = exc_type + else: + exc_type_name = exc_type.__name__ + message = "Exception occured: " + repr(exc_type_name) + " See locals.__exception__ for details." + traceback.print_exception(exc_type, exc_value, exc_traceback) + self._harness.interaction(message, frame, message) + + def in_debugger_code(self, frame): + if _DEBUG_DEBUGGER: return False + message = self.__frame2message(frame) + return message.count('DebuggerHarness') > 0 + + def frame2message(self, frame): + return self.__frame2message(frame) + + def __frame2message(self, frame): + code = frame.f_code + filename = code.co_filename + lineno = frame.f_lineno + basename = os.path.basename(filename) + message = "%s:%s" % (basename, lineno) + if code.co_name != "?": + message = "%s: %s()" % (message, code.co_name) + return message + + def runFile(self, fileName): + self.reset() + #global_dict = {} + #global_dict['__name__'] = '__main__' + try: + fileToRun = open(fileName, mode='r') + if _VERBOSE: print "Running file ", fileName + sys.settrace(self.trace_dispatch) + import __main__ + exec fileToRun in __main__.__dict__,__main__.__dict__ + except SystemExit: + pass + except: + tp, val, tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + + sys.settrace(None) + self.quitting = 1 + #global_dict.clear() + + def trace_dispatch(self, frame, event, arg): + if self.quitting: + return # None + # Check for ui events + self.readQueue() + if event == 'line': + return self.dispatch_line(frame) + if event == 'call': + return self.dispatch_call(frame, arg) + if event == 'return': + return self.dispatch_return(frame, arg) + if event == 'exception': + return self.dispatch_exception(frame, arg) + print 'Adb.dispatch: unknown debugging event:', `event` + return self.trace_dispatch + + def readQueue(self): + while self._queue.qsize(): + try: + item = self._queue.get_nowait() + if item.kill(): + self._harness.do_exit(kill=True) + elif item.breakHere(): + self._userBreak = True + elif item.hasBreakpoints(): + self.set_all_breakpoints(item.getBreakpoints()) + except Queue.Empty: + pass + + def set_all_breakpoints(self, dict): + self.clear_all_breaks() + for fileName in dict.keys(): + lineList = dict[fileName] + for lineNumber in lineList: + + if _VERBOSE: print "Setting break at line ", str(lineNumber), " in file ", self.canonic(fileName) + self.set_break(fileName, int(lineNumber)) + return "" + + def stop_here(self, frame): + if( self._userBreak ): + return True + + + # (CT) stopframe may now also be None, see dispatch_call. + # (CT) the former test for None is therefore removed from here. + if frame is self.stopframe: + return True + while frame is not None and frame is not self.stopframe: + if frame is self.botframe: + return True + frame = frame.f_back + return False + +class BreakNotify(object): + def __init__(self, bps=None, break_here=False, kill=False): + self._bps = bps + self._break_here = break_here + self._kill = kill + + def breakHere(self): + return self._break_here + + def kill(self): + return self._kill + + def getBreakpoints(self): + return self._bps + + def hasBreakpoints(self): + return (self._bps != None) + +class AGXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): + def __init__(self, address, logRequests=0): + SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, address, logRequests=logRequests) + +class BreakListenerThread(threading.Thread): + def __init__(self, host, port, queue): + threading.Thread.__init__(self) + self._host = host + self._port = int(port) + self._keepGoing = True + self._queue = queue + self._server = AGXMLRPCServer((self._host, self._port), logRequests=0) + self._server.register_function(self.update_breakpoints) + self._server.register_function(self.break_requested) + self._server.register_function(self.die) + + def break_requested(self): + bn = BreakNotify(break_here=True) + self._queue.put(bn) + return "" + + def update_breakpoints(self, pickled_Binary_bpts): + dict = pickle.loads(pickled_Binary_bpts.data) + bn = BreakNotify(bps=dict) + self._queue.put(bn) + return "" + + def die(self): + bn = BreakNotify(kill=True) + self._queue.put(bn) + return "" + + def run(self): + while self._keepGoing: + try: + self._server.handle_request() + except: + if _VERBOSE: + tp, val, tb = sys.exc_info() + print "Exception in BreakListenerThread.run():", str(tp), str(val) + self._keepGoing = False + + def AskToStop(self): + self._keepGoing = False + if type(self._server) is not types.NoneType: + if _VERBOSE: print "Before calling server close on breakpoint server" + self._server.server_close() + if _VERBOSE: print "Calling server close on breakpoint server" + + +class DebuggerHarness(object): + + def __init__(self): + # Host and port for debugger-side RPC server + self._hostname = sys.argv[1] + self._portNumber = int(sys.argv[2]) + # Name the gui proxy object is registered under + self._breakPortNumber = int(sys.argv[3]) + # Host and port where the gui proxy can be found. + self._guiHost = sys.argv[4] + self._guiPort = int(sys.argv[5]) + # Command to debug. + self._command = sys.argv[6] + # Strip out the harness' arguments so that the process we run will see argv as if + # it was called directly. + sys.argv = sys.argv[6:] + self._currentFrame = None + self._wait = False + # Connect to the gui-side RPC server. + self._guiServerUrl = 'http://' + self._guiHost + ':' + str(self._guiPort) + '/' + if _VERBOSE: print "Connecting to gui server at ", self._guiServerUrl + self._guiServer = xmlrpclib.ServerProxy(self._guiServerUrl,allow_none=1) + + # Start the break listener + self._breakQueue = Queue.Queue(50) + self._breakListener = BreakListenerThread(self._hostname, self._breakPortNumber, self._breakQueue) + self._breakListener.start() + # Create the debugger. + self._adb = Adb(self, self._breakQueue) + + # Create the debugger-side RPC Server and register functions for remote calls. + self._server = AGXMLRPCServer((self._hostname, self._portNumber), logRequests=0) + self._server.register_function(self.set_step) + self._server.register_function(self.set_continue) + self._server.register_function(self.set_next) + self._server.register_function(self.set_return) + self._server.register_function(self.set_breakpoint) + self._server.register_function(self.clear_breakpoint) + self._server.register_function(self.set_all_breakpoints) + self._server.register_function(self.attempt_introspection) + self._server.register_function(self.add_watch) + + self.message_frame_dict = {} + self.introspection_list = [] + atexit.register(self.do_exit) + + def run(self): + self._adb.runFile(self._command) + self.do_exit(kill=True) + + + def do_exit(self, kill=False): + self._adb.set_quit() + self._breakListener.AskToStop() + self._server.server_close() + try: + self._guiServer.quit() + except: + pass + if kill: + try: + sys.exit() + except: + pass + + def set_breakpoint(self, fileName, lineNo): + self._adb.set_break(fileName, lineNo) + return "" + + def set_all_breakpoints(self, dict): + self._adb.clear_all_breaks() + for fileName in dict.keys(): + lineList = dict[fileName] + for lineNumber in lineList: + self._adb.set_break(fileName, int(lineNumber)) + if _VERBOSE: print "Setting break at ", str(lineNumber), " in file ", fileName + return "" + + def clear_breakpoint(self, fileName, lineNo): + self._adb.clear_break(fileName, lineNo) + return "" + + def add_watch(self, name, text, frame_message, run_once): + if len(frame_message) > 0: + frame = self.message_frame_dict[frame_message] + try: + item = eval(text, frame.f_globals, frame.f_locals) + return self.get_watch_document(item, name) + except: + tp, val, tb = sys.exc_info() + return self.get_exception_document(tp, val, tb) + return "" + + def attempt_introspection(self, frame_message, chain): + try: + frame = self.message_frame_dict[frame_message] + if frame: + name = chain.pop(0) + if name == 'globals': + item = frame.f_globals + elif name == 'locals': + item = frame.f_locals + + for name in chain: + item = self.getNextItem(item, name) + return self.get_introspection_document(item, name) + except: + tp, val, tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + return self.get_empty_introspection_document() + + def getNextItem(self, link, identifier): + tp = type(link) + if self.isTupleized(identifier): + return self.deTupleize(link, identifier) + else: + if tp == types.DictType or tp == types.DictProxyType: + return link[identifier] + else: + if hasattr(link, identifier): + return getattr(link, identifier) + if _VERBOSE or True: print "Failed to find link ", identifier, " on thing: ", self.saferepr(link), " of type ", repr(type(link)) + return None + + def isPrimitive(self, item): + tp = type(item) + return tp is types.IntType or tp is types.LongType or tp is types.FloatType \ + or tp is types.BooleanType or tp is types.ComplexType \ + or tp is types.StringType + + def isTupleized(self, value): + return value.count('[') + + def deTupleize(self, link, string1): + try: + start = string1.find('[') + end = string1.find(']') + num = int(string1[start+1:end]) + return link[num] + except: + tp,val,tb = sys.exc_info() + if _VERBOSE: print "Got exception in deTupleize: ", val + return None + + def wrapAndCompress(self, stringDoc): + import bz2 + return xmlrpclib.Binary(bz2.compress(stringDoc)) + + def get_empty_introspection_document(self): + doc = getDOMImplementation().createDocument(None, "replacement", None) + return self.wrapAndCompress(doc.toxml()) + + def get_watch_document(self, item, identifier): + doc = getDOMImplementation().createDocument(None, "watch", None) + top_element = doc.documentElement + self.addAny(top_element, identifier, item, doc, 2) + return self.wrapAndCompress(doc.toxml()) + + def get_introspection_document(self, item, identifier): + doc = getDOMImplementation().createDocument(None, "replacement", None) + top_element = doc.documentElement + self.addAny(top_element, identifier, item, doc, 2) + return self.wrapAndCompress(doc.toxml()) + + def get_exception_document(self, name, tp, val, tb): + stack = traceback.format_exception(tp, val, tb) + wholeStack = "" + for line in stack: + wholeStack += line + doc = getDOMImplementation().createDocument(None, "watch", None) + top_element = doc.documentElement + item_node = doc.createElement("dict_nv_element") + item_node.setAttribute('value', wholeStack) + item_node.setAttribute('name', str(name)) + top_element.appendChild(item_node) + + def addAny(self, top_element, name, item, doc, ply): + tp = type(item) + if ply < 1: + self.addNode(top_element,name, self.saferepr(item), doc) + elif tp is types.TupleType or tp is types.ListType: + self.addTupleOrList(top_element, name, item, doc, ply - 1) + elif tp is types.DictType or tp is types.DictProxyType: + self.addDict(top_element, name, item, doc, ply -1) + elif inspect.ismodule(item): + self.addModule(top_element, name, item, doc, ply -1) + elif inspect.isclass(item) or tp is types.InstanceType: + self.addClass(top_element, name, item, doc, ply -1) + #elif hasattr(item, '__dict__'): + # self.addDictAttr(top_element, name, item, doc, ply -1) + elif hasattr(item, '__dict__'): + self.addDict(top_element, name, item.__dict__, doc, ply -1) + else: + self.addNode(top_element,name, self.saferepr(item), doc) + + def addTupleOrList(self, top_node, name, tupple, doc, ply): + tupleNode = doc.createElement('tuple') + tupleNode.setAttribute('name', str(name)) + tupleNode.setAttribute('value', str(type(tupple))) + top_node.appendChild(tupleNode) + count = 0 + for item in tupple: + self.addAny(tupleNode, name +'[' + str(count) + ']',item, doc, ply -1) + count += 1 + + + def getFrameXML(self, base_frame): + doc = getDOMImplementation().createDocument(None, "stack", None) + top_element = doc.documentElement + + stack = [] + frame = base_frame + while frame is not None: + if((frame.f_code.co_filename.count('DebuggerHarness.py') == 0) or _DEBUG_DEBUGGER): + stack.append(frame) + frame = frame.f_back + stack.reverse() + self.message_frame_dict = {} + for f in stack: + self.addFrame(f,top_element, doc) + return doc.toxml() + + def addFrame(self, frame, root_element, document): + frameNode = document.createElement('frame') + root_element.appendChild(frameNode) + + code = frame.f_code + filename = code.co_filename + frameNode.setAttribute('file', str(filename)) + frameNode.setAttribute('line', str(frame.f_lineno)) + message = self._adb.frame2message(frame) + frameNode.setAttribute('message', message) + #print "Frame: %s %s %s" %(message, frame.f_lineno, filename) + self.message_frame_dict[message] = frame + self.addDict(frameNode, "locals", frame.f_locals, document, 2) + self.addNode(frameNode, "globals", "", document) + + def getRepr(self, varName, globals, locals): + try: + return repr(eval(varName, globals, locals)) + except: + return 'Error: Could not recover value.' + + def addNode(self, parent_node, name, value, document): + item_node = document.createElement("dict_nv_element") + item_node.setAttribute('value', self.saferepr(value)) + item_node.setAttribute('name', str(name)) + parent_node.appendChild(item_node) + + def addDictAttr(self, root_node, name, thing, document, ply): + dict_node = document.createElement('thing') + root_node.setAttribute('name', name) + root_node.setAttribute('value', str(type(dict)) + " add attr") + self.addDict(root_node, name, thing.__dict__, document, ply) # Not decreminting ply + + def saferepr(self, thing): + try: + return repr(thing) + except: + tp, val, tb = sys.exc_info() + return repr(val) + + def addDict(self, root_node, name, dict, document, ply): + dict_node = document.createElement('dict') + dict_node.setAttribute('name', name) + dict_node.setAttribute('value', str(type(dict)) + " add dict") + root_node.appendChild(dict_node) + for key in dict.keys(): + strkey = str(key) + try: + self.addAny(dict_node, strkey, dict[key], document, ply-1) + except: + tp,val,tb=sys.exc_info() + if _VERBOSE: + print "Error recovering key: ", str(key), " from node ", str(name), " Val = ", str(val) + traceback.print_exception(tp, val, tb) + self.addAny(dict_node, strkey, "Exception getting " + str(name) + "[" + strkey + "]: " + str(val), document, ply -1) + + def addClass(self, root_node, name, class_item, document, ply): + item_node = document.createElement('class') + item_node.setAttribute('name', str(name)) + root_node.appendChild(item_node) + try: + if hasattr(class_item, '__dict__'): + self.addAny(item_node, '__dict__', class_item.__dict__, document, ply -1) + except: + tp,val,tb=sys.exc_info() + if _VERBOSE: + traceback.print_exception(tp, val, tb) + self.addAny(item_node, '__dict__', "Exception getting __dict__: " + str(val), document, ply -1) + try: + if hasattr(class_item, '__name__'): + self.addAny(item_node,'__name__',class_item.__name__, document, ply -1) + except: + tp,val,tb=sys.exc_info() + if _VERBOSE: + traceback.print_exception(tp, val, tb) + self.addAny(item_node,'__name__',"Exception getting class.__name__: " + val, document, ply -1) + try: + if hasattr(class_item, '__module__'): + self.addAny(item_node, '__module__', class_item.__module__, document, ply -1) + except: + tp,val,tb=sys.exc_info() + if _VERBOSE: + traceback.print_exception(tp, val, tb) + self.addAny(item_node, '__module__', "Exception getting class.__module__: " + val, document, ply -1) + try: + if hasattr(class_item, '__doc__'): + self.addAny(item_node, '__doc__', class_item.__doc__, document, ply -1) + except: + tp,val,tb=sys.exc_info() + if _VERBOSE: + traceback.print_exception(tp, val, tb) + self.addAny(item_node, '__doc__', "Exception getting class.__doc__: " + val, document, ply -1) + try: + if hasattr(class_item, '__bases__'): + self.addAny(item_node, '__bases__', class_item.__bases__, document, ply -1) + except: + tp,val,tb=sys.exc_info() + if _VERBOSE: + traceback.print_exception(tp, val, tb) + self.addAny(item_node, '__bases__', "Exception getting class.__bases__: " + val, document, ply -1) + + def addModule(self, root_node, name, module_item, document, ply): + item_node = document.createElement('module') + item_node.setAttribute('name', str(name)) + root_node.appendChild(item_node) + try: + if hasattr(module_item, '__file__'): + self.addAny(item_node, '__file__', module_item.__file__, document, ply -1) + except: + pass + try: + if hasattr(module_item, '__doc__'): + self.addAny(item_node,'__doc__', module_item.__doc__, document, ply -1) + except: + pass + + # The debugger calls this method when it reaches a breakpoint. + def interaction(self, message, frame, info): + if _VERBOSE: + print 'hit debug side interaction' + self._userBreak = False + + self._currentFrame = frame + done = False + while not done: + try: + import bz2 + xml = self.getFrameXML(frame) + arg = xmlrpclib.Binary(bz2.compress(xml)) + if _VERBOSE: + print '============== calling gui side interaction============' + self._guiServer.interaction(xmlrpclib.Binary(message), arg, info) + if _VERBOSE: + print 'after interaction' + done = True + except: + tp, val, tb = sys.exc_info() + if True or _VERBOSE: + print 'Error contacting GUI server!: ' + try: + traceback.print_exception(tp, val, tb) + except: + print "Exception printing traceback", + tp, val, tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + done = False + # Block while waiting to be called back from the GUI. Eventually, self._wait will + # be set false by a function on this side. Seems pretty lame--I'm surprised it works. + self.waitForRPC() + + + def waitForRPC(self): + self._wait = True + while self._wait : + try: + if _VERBOSE: + print "+++ in harness wait for rpc, before handle_request" + self._server.handle_request() + if _VERBOSE: + print "+++ in harness wait for rpc, after handle_request" + except: + if _VERBOSE: + tp, val, tb = sys.exc_info() + print "Got waitForRpc exception : ", repr(tp), ": ", val + #time.sleep(0.1) + + def set_step(self): + self._adb.set_step() + self._wait = False + return "" + + def set_continue(self): + self._adb.set_continue() + self._wait = False + return "" + + def set_next(self): + self._adb.set_next(self._currentFrame) + self._wait = False + return "" + + def set_return(self): + self._adb.set_return(self._currentFrame) + self._wait = False + return "" + +if __name__ == '__main__': + try: + harness = DebuggerHarness() + harness.run() + except SystemExit: + print "Exiting..." + except: + tp, val, tb = sys.exc_info() + traceback.print_exception(tp, val, tb) diff --git a/wxPython/samples/ide/activegrid/tool/DebuggerService.py b/wxPython/samples/ide/activegrid/tool/DebuggerService.py new file mode 100644 index 0000000000..ef4a37a879 --- /dev/null +++ b/wxPython/samples/ide/activegrid/tool/DebuggerService.py @@ -0,0 +1,2275 @@ +#---------------------------------------------------------------------------- +# Name: DebuggerService.py +# Purpose: Debugger Service for Python. +# +# Author: Matt Fryer +# +# Created: 12/9/04 +# CVS-ID: $Id$ +# Copyright: (c) 2004-2005 ActiveGrid, Inc. +# License: wxWindows License +#---------------------------------------------------------------------------- + +import wx +import wx.lib.intctrl +import wx.lib.docview +import wx.lib.dialogs +import wx.gizmos +import wx._core +import wx.lib.pydocview +import Service +import STCTextEditor +import CodeEditor +import PythonEditor +from IDE import ACTIVEGRID_BASE_IDE +if not ACTIVEGRID_BASE_IDE: + import ProcessModelEditor +import wx.lib.scrolledpanel as scrolled +import sys +import time +import SimpleXMLRPCServer +import xmlrpclib +import os +import threading +import process +import Queue +import SocketServer +import ProjectEditor +import types +from xml.dom.minidom import parse, parseString +import bz2 +import pickle +import DebuggerHarness +import traceback +import StringIO +if wx.Platform == '__WXMSW__': + import win32api + _WINDOWS = True +else: + _WINDOWS = False +_ = wx.GetTranslation + +_VERBOSE = False +_WATCHES_ON = False + +# Class to read from stdout or stderr and write the result to a text control. +# Args: file=file-like object +# callback_function= function that takes a single argument, the line of text +# read. +class OutputReaderThread(threading.Thread): + def __init__(self, file, callback_function, callbackOnExit=None, accumulate=True): + threading.Thread.__init__(self) + self._file = file + self._callback_function = callback_function + self._keepGoing = True + self._lineCount = 0 + self._accumulate = accumulate + self._callbackOnExit = callbackOnExit + + def run(self): + file = self._file + start = time.time() + output = "" + while self._keepGoing: + try: + # This could block--how to handle that? + text = file.readline() + if text == '' or text == None: + self._keepGoing = False + elif not self._accumulate: + self._callback_function(text) + else: + # Should use a buffer? StringIO? + output += text + # Seems as though the read blocks if we got an error, so, to be + # sure that at least some of the exception gets printed, always + # send the first hundred lines back as they come in. + if self._lineCount < 100: + self._callback_function(output) + self._lineCount += 1 + output = "" + elif time.time() - start > 0.25: + try: + self._callback_function(output) + except wx._core.PyDeadObjectError: + # GUI was killed while we were blocked. + self._keepGoing = False + start = time.time() + output = "" + except: + tp, val, tb = sys.exc_info() + print "Exception in OutputReaderThread.run():", tp, val + self._keepGoing = False + if self._callbackOnExit: + try: + self._callbackOnExit() + except wx._core.PyDeadObjectError: + pass + if _VERBOSE: print "Exiting OutputReaderThread" + + def AskToStop(self): + self._keepGoing = False + +import wx.lib.newevent +(UpdateTextEvent, EVT_UPDATE_STDTEXT) = wx.lib.newevent.NewEvent() +(UpdateErrorEvent, EVT_UPDATE_ERRTEXT) = wx.lib.newevent.NewEvent() + +class Executor: + + def GetPythonExecutablePath(): + config = wx.ConfigBase_Get() + path = config.Read("ActiveGridPythonLocation") + if path: + return path + wx.MessageBox(_("To proceed I need to know the location of the python.exe you would like to use.\nTo set this, go to Tools-->Options and use the 'Python' tab to enter a value.\n"), _("Python Executable Location Unknown")) + return None + GetPythonExecutablePath = staticmethod(GetPythonExecutablePath) + + def __init__(self, fileName, wxComponent, arg1=None, arg2=None, arg3=None, arg4=None, arg5=None, arg6=None, arg7=None, arg8=None, arg9=None, callbackOnExit=None): + self._fileName = fileName + self._stdOutCallback = self.OutCall + self._stdErrCallback = self.ErrCall + self._callbackOnExit = callbackOnExit + self._wxComponent = wxComponent + path = Executor.GetPythonExecutablePath() + self._cmd = '"' + path + '" -u \"' + fileName + '\"' + #Better way to do this? Quotes needed for windows file paths. + if(arg1 != None): + self._cmd += ' \"' + arg1 + '\"' + if(arg2 != None): + self._cmd += ' \"' + arg2 + '\"' + if(arg3 != None): + self._cmd += ' \"' + arg3 + '\"' + if(arg4 != None): + self._cmd += ' \"' + arg4 + '\"' + if(arg5 != None): + self._cmd += ' \"' + arg5 + '\"' + if(arg6 != None): + self._cmd += ' \"' + arg6 + '\"' + if(arg7 != None): + self._cmd += ' \"' + arg7 + '\"' + if(arg8 != None): + self._cmd += ' \"' + arg8 + '\"' + if(arg9 != None): + self._cmd += ' \"' + arg9 + '\"' + + self._stdOutReader = None + self._stdErrReader = None + self._process = None + + def OutCall(self, text): + evt = UpdateTextEvent(value = text) + wx.PostEvent(self._wxComponent, evt) + + def ErrCall(self, text): + evt = UpdateErrorEvent(value = text) + wx.PostEvent(self._wxComponent, evt) + + def Execute(self, arguments, startIn=None, environment=None): + if not startIn: + startIn = str(os.getcwd()) + startIn = os.path.abspath(startIn) + command = self._cmd + ' ' + arguments + #stdinput = process.IOBuffer() + #self._process = process.ProcessProxy(command, mode='b', cwd=startIn, stdin=stdinput) + self._process = process.ProcessOpen(command, mode='b', cwd=startIn, env=environment) + # Kick off threads to read stdout and stderr and write them + # to our text control. + self._stdOutReader = OutputReaderThread(self._process.stdout, self._stdOutCallback, callbackOnExit=self._callbackOnExit) + self._stdOutReader.start() + self._stdErrReader = OutputReaderThread(self._process.stderr, self._stdErrCallback, accumulate=False) + self._stdErrReader.start() + + + def DoStopExecution(self): + if(self._process != None): + self._process.kill() + self._process.close() + self._process = None + if(self._stdOutReader != None): + self._stdOutReader.AskToStop() + if(self._stdErrReader != None): + self._stdErrReader.AskToStop() + +class RunCommandUI(wx.Panel): + + def __init__(self, parent, id, fileName): + wx.Panel.__init__(self, parent, id) + self._noteBook = parent + + self.KILL_PROCESS_ID = wx.NewId() + self.CLOSE_TAB_ID = wx.NewId() + + self.Bind(wx.EVT_END_PROCESS, self.OnProcessEnded) + + # GUI Initialization follows + sizer = wx.BoxSizer(wx.HORIZONTAL) + self._tb = tb = wx.ToolBar(self, -1, wx.DefaultPosition, (30,1000), wx.TB_VERTICAL| wx.TB_FLAT, "Runner" ) + tb.SetToolBitmapSize((16,16)) + sizer.Add(tb, 0, wx.EXPAND |wx.ALIGN_LEFT|wx.ALL, 1) + + close_bmp = getCloseBitmap() + tb.AddSimpleTool( self.CLOSE_TAB_ID, close_bmp, _('Close Window')) + wx.EVT_TOOL(self, self.CLOSE_TAB_ID, self.OnToolClicked) + + stop_bmp = getStopBitmap() + tb.AddSimpleTool(self.KILL_PROCESS_ID, stop_bmp, _("Stop the Run.")) + wx.EVT_TOOL(self, self.KILL_PROCESS_ID, self.OnToolClicked) + + tb.Realize() + self._textCtrl = STCTextEditor.TextCtrl(self, wx.NewId()) #id) + sizer.Add(self._textCtrl, 1, wx.ALIGN_LEFT|wx.ALL|wx.EXPAND, 1) + self._textCtrl.SetViewLineNumbers(False) + self._textCtrl.SetReadOnly(True) + if wx.Platform == '__WXMSW__': + font = "Courier New" + else: + font = "Courier" + self._textCtrl.SetFont(wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.NORMAL, faceName = font)) + self._textCtrl.SetFontColor(wx.BLACK) + self._textCtrl.StyleClearAll() + + #Disabling for now...may interfere with file open. wx.stc.EVT_STC_DOUBLECLICK(self._textCtrl, self._textCtrl.GetId(), self.OnDoubleClick) + + self.SetSizer(sizer) + sizer.Fit(self) + + # Executor initialization + self._executor = Executor(fileName, self, callbackOnExit=self.ExecutorFinished) + self.Bind(EVT_UPDATE_STDTEXT, self.AppendText) + self.Bind(EVT_UPDATE_ERRTEXT, self.AppendErrorText) + + def __del__(self): + self._executor.DoStopExecution() + + def Execute(self, initialArgs, startIn, environment): + self._executor.Execute(initialArgs, startIn, environment) + + def ExecutorFinished(self): + self._tb.EnableTool(self.KILL_PROCESS_ID, False) + nb = self.GetParent() + for i in range(0,nb.GetPageCount()): + if self == nb.GetPage(i): + text = nb.GetPageText(i) + newText = text.replace("Running", "Finished") + nb.SetPageText(i, newText) + break + + def StopExecution(self): + self.Unbind(EVT_UPDATE_STDTEXT) + self.Unbind(EVT_UPDATE_ERRTEXT) + self._executor.DoStopExecution() + + def AppendText(self, event): + self._textCtrl.SetReadOnly(False) + self._textCtrl.AddText(event.value) + self._textCtrl.ScrollToLine(self._textCtrl.GetLineCount()) + self._textCtrl.SetReadOnly(True) + + def AppendErrorText(self, event): + self._textCtrl.SetReadOnly(False) + self._textCtrl.SetFontColor(wx.RED) + self._textCtrl.StyleClearAll() + self._textCtrl.AddText(event.value) + self._textCtrl.ScrollToLine(self._textCtrl.GetLineCount()) + self._textCtrl.SetFontColor(wx.BLACK) + self._textCtrl.StyleClearAll() + self._textCtrl.SetReadOnly(True) + + #------------------------------------------------------------------------------ + # Event handling + #----------------------------------------------------------------------------- + + def OnToolClicked(self, event): + id = event.GetId() + + if id == self.KILL_PROCESS_ID: + self._executor.DoStopExecution() + + elif id == self.CLOSE_TAB_ID: + self._executor.DoStopExecution() + index = self._noteBook.GetSelection() + self._noteBook.GetPage(index).Show(False) + self._noteBook.RemovePage(index) + + def OnDoubleClick(self, event): + # Looking for a stack trace line. + lineText, pos = self._textCtrl.GetCurLine() + fileBegin = lineText.find("File \"") + fileEnd = lineText.find("\", line ") + lineEnd = lineText.find(", in ") + if lineText == "\n" or fileBegin == -1 or fileEnd == -1 or lineEnd == -1: + # Check the line before the one that was clicked on + lineNumber = self._textCtrl.GetCurrentLine() + if(lineNumber == 0): + return + lineText = self._textCtrl.GetLine(lineNumber - 1) + fileBegin = lineText.find("File \"") + fileEnd = lineText.find("\", line ") + lineEnd = lineText.find(", in ") + if lineText == "\n" or fileBegin == -1 or fileEnd == -1 or lineEnd == -1: + return + + filename = lineText[fileBegin + 6:fileEnd] + lineNum = int(lineText[fileEnd + 8:lineEnd]) + + foundView = None + openDocs = wx.GetApp().GetDocumentManager().GetDocuments() + for openDoc in openDocs: + if openDoc.GetFilename() == filename: + foundView = openDoc.GetFirstView() + break + + if not foundView: + doc = wx.GetApp().GetDocumentManager().CreateDocument(filename, wx.lib.docview.DOC_SILENT) + foundView = doc.GetFirstView() + + if foundView: + foundView.GetFrame().SetFocus() + foundView.Activate() + foundView.GotoLine(lineNum) + startPos = foundView.PositionFromLine(lineNum) + + # FACTOR THIS INTO DocManager + openDocs = wx.GetApp().GetDocumentManager().GetDocuments() + for openDoc in openDocs: + if(isinstance(openDoc.GetFirstView(), CodeEditor.CodeView)): + openDoc.GetFirstView().GetCtrl().ClearCurrentLineMarkers() + + foundView.GetCtrl().MarkerAdd(lineNum -1, CodeEditor.CodeCtrl.CURRENT_LINE_MARKER_NUM) + + def OnProcessEnded(self, evt): + self._executor.DoStopExecution() + +DEFAULT_PORT = 32032 +DEFAULT_HOST = 'localhost' +PORT_COUNT = 21 + +class DebugCommandUI(wx.Panel): + debuggerPortList = None + debuggers = [] + + def NotifyDebuggersOfBreakpointChange(): + for debugger in DebugCommandUI.debuggers: + debugger.BreakPointChange() + + NotifyDebuggersOfBreakpointChange = staticmethod(NotifyDebuggersOfBreakpointChange) + + def DebuggerRunning(): + for debugger in DebugCommandUI.debuggers: + if debugger._executor: + return True + return False + DebuggerRunning = staticmethod(DebuggerRunning) + + def ShutdownAllDebuggers(): + for debugger in DebugCommandUI.debuggers: + debugger.StopExecution() + + ShutdownAllDebuggers = staticmethod(ShutdownAllDebuggers) + + def GetAvailablePort(): + for index in range( 0, len(DebugCommandUI.debuggerPortList)): + port = DebugCommandUI.debuggerPortList[index] + if DebugCommandUI.PortAvailable(port): + DebugCommandUI.debuggerPortList.pop(index) + return port + wx.MessageBox(_("Out of ports for debugging! Please restart the application builder.\nIf that does not work, check for and remove running instances of python."), _("Out of Ports")) + assert False, "Out of ports for debugger." + + GetAvailablePort = staticmethod(GetAvailablePort) + + def ReturnPortToPool(port): + config = wx.ConfigBase_Get() + startingPort = config.ReadInt("DebuggerStartingPort", DEFAULT_PORT) + if port in range(startingPort, startingPort + PORT_COUNT): + DebugCommandUI.debuggerPortList.append(port) + + ReturnPortToPool = staticmethod(ReturnPortToPool) + + def PortAvailable(port): + config = wx.ConfigBase_Get() + hostname = config.Read("DebuggerHostName", DEFAULT_HOST) + try: + server = AGXMLRPCServer((hostname, port)) + server.server_close() + if _VERBOSE: print "Port ", str(port), " available." + return True + except: + tp,val,tb = sys.exc_info() + if _VERBOSE: traceback.print_exception(tp, val, tb) + if _VERBOSE: print "Port ", str(port), " unavailable." + return False + + PortAvailable = staticmethod(PortAvailable) + + def NewPortRange(): + config = wx.ConfigBase_Get() + startingPort = config.ReadInt("DebuggerStartingPort", DEFAULT_PORT) + DebugCommandUI.debuggerPortList = range(startingPort, startingPort + PORT_COUNT) + NewPortRange = staticmethod(NewPortRange) + + def __init__(self, parent, id, command, service): + # Check for ports before creating the panel. + if not DebugCommandUI.debuggerPortList: + DebugCommandUI.NewPortRange() + self._debuggerPort = str(DebugCommandUI.GetAvailablePort()) + self._guiPort = str(DebugCommandUI.GetAvailablePort()) + self._debuggerBreakPort = str(DebugCommandUI.GetAvailablePort()) + + wx.Panel.__init__(self, parent, id) + + self._parentNoteBook = parent + self._command = command + self._textCtrl = None + self._service = service + self._executor = None + self.STEP_ID = wx.NewId() + self.CONTINUE_ID = wx.NewId() + self.STEP_OUT_ID = wx.NewId() + self.NEXT_ID = wx.NewId() + self.KILL_PROCESS_ID = wx.NewId() + self.CLOSE_WINDOW_ID = wx.NewId() + self.BREAK_INTO_DEBUGGER_ID = wx.NewId() + self.CLEAR_ID = wx.NewId() + self.ADD_WATCH_ID = wx.NewId() + sizer = wx.BoxSizer(wx.VERTICAL) + self._tb = tb = wx.ToolBar(self, -1, wx.DefaultPosition, (1000,30), wx.TB_HORIZONTAL| wx.NO_BORDER| wx.TB_FLAT| wx.TB_TEXT, "Debugger" ) + sizer.Add(tb, 0, wx.EXPAND |wx.ALIGN_LEFT|wx.ALL, 1) + tb.SetToolBitmapSize((16,16)) + + close_bmp = getCloseBitmap() + tb.AddSimpleTool( self.CLOSE_WINDOW_ID, close_bmp, _('Close Window')) + wx.EVT_TOOL(self, self.CLOSE_WINDOW_ID, self.StopAndRemoveUI) + + stop_bmp = getStopBitmap() + tb.AddSimpleTool( self.KILL_PROCESS_ID, stop_bmp, _("Stop Debugging")) + wx.EVT_TOOL(self, self.KILL_PROCESS_ID, self.StopExecution) + + tb.AddSeparator() + + break_bmp = getBreakBitmap() + tb.AddSimpleTool( self.BREAK_INTO_DEBUGGER_ID, break_bmp, _("Break into Debugger")) + wx.EVT_TOOL(self, self.BREAK_INTO_DEBUGGER_ID, self.BreakExecution) + + tb.AddSeparator() + + continue_bmp = getContinueBitmap() + tb.AddSimpleTool( self.CONTINUE_ID, continue_bmp, _("Continue Execution")) + wx.EVT_TOOL(self, self.CONTINUE_ID, self.OnContinue) + + tb.AddSeparator() + + next_bmp = getNextBitmap() + tb.AddSimpleTool( self.NEXT_ID, next_bmp, _("Step to next line")) + wx.EVT_TOOL(self, self.NEXT_ID, self.OnNext) + + step_bmp = getStepInBitmap() + tb.AddSimpleTool( self.STEP_ID, step_bmp, _("Step in")) + wx.EVT_TOOL(self, self.STEP_ID, self.OnSingleStep) + + stepOut_bmp = getStepReturnBitmap() + tb.AddSimpleTool(self.STEP_OUT_ID, stepOut_bmp, _("Stop at function return")) + wx.EVT_TOOL(self, self.STEP_OUT_ID, self.OnStepOut) + + tb.AddSeparator() + if _WATCHES_ON: + watch_bmp = getAddWatchBitmap() + tb.AddSimpleTool(self.ADD_WATCH_ID, watch_bmp, _("Add a watch")) + wx.EVT_TOOL(self, self.ADD_WATCH_ID, self.OnAddWatch) + tb.AddSeparator() + + clear_bmp = getClearOutputBitmap() + tb.AddSimpleTool(self.CLEAR_ID, clear_bmp, _("Clear output pane")) + wx.EVT_TOOL(self, self.CLEAR_ID, self.OnClearOutput) + + tb.Realize() + self.framesTab = None + self.DisableWhileDebuggerRunning() + self._notebook = wx.Notebook(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.LB_DEFAULT, "Debugger") + sizer.Add(self._notebook, 1, wx.ALIGN_LEFT|wx.ALL|wx.EXPAND, 1) + self.consoleTab = self.MakeConsoleTab(self._notebook, wx.NewId(), None) + self.framesTab = self.MakeFramesTab(self._notebook, wx.NewId(), None) + self.breakPointsTab = self.MakeBreakPointsTab(self._notebook, wx.NewId(), None) + self._notebook.AddPage(self.consoleTab, "Output") + self._notebook.AddPage(self.framesTab, "Frames") + self._notebook.AddPage(self.breakPointsTab, "Break Points") + + self._statusBar = wx.StatusBar( self, -1) + self._statusBar.SetFieldsCount(1) + sizer.Add(self._statusBar, 0, wx.EXPAND |wx.ALIGN_LEFT|wx.ALL, 1) + + self.SetStatusText("Starting debug...") + + self.SetSizer(sizer) + sizer.Fit(self) + config = wx.ConfigBase_Get() + self._debuggerHost = self._guiHost = config.Read("DebuggerHostName", DEFAULT_HOST) + url = 'http://' + self._debuggerHost + ':' + self._debuggerPort + '/' + self._breakURL = 'http://' + self._debuggerHost + ':' + self._debuggerBreakPort + '/' + self._callback = DebuggerCallback(self._guiHost, self._guiPort, url, self._breakURL, self) + if DebuggerHarness.__file__.find('library.zip') > 0: + try: + fname = DebuggerHarness.__file__ + parts = fname.split('library.zip') + path = os.path.join(parts[0],'activegrid', 'tool', 'DebuggerHarness.py') + except: + tp, val, tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + + else: + print "Starting debugger on these ports: %s, %s, %s" % (str(self._debuggerPort) , str(self._guiPort) , str(self._debuggerBreakPort)) + path = DebuggerService.ExpandPath(DebuggerHarness.__file__) + self._executor = Executor(path, self, self._debuggerHost, \ + self._debuggerPort, self._debuggerBreakPort, self._guiHost, self._guiPort, self._command, callbackOnExit=self.ExecutorFinished) + + self.Bind(EVT_UPDATE_STDTEXT, self.AppendText) + self.Bind(EVT_UPDATE_ERRTEXT, self.AppendErrorText) + DebugCommandUI.debuggers.append(self) + self._stopped = False + + def OnSingleStep(self, event): + self._callback.SingleStep() + + def OnContinue(self, event): + self._callback.Continue() + + def OnStepOut(self, event): + self._callback.Return() + + def OnNext(self, event): + self._callback.Next() + + def BreakPointChange(self): + if not self._stopped: + self._callback.pushBreakpoints() + self.breakPointsTab.PopulateBPList() + + def __del__(self): + if self in DebugCommandUI.debuggers: + DebugCommandUI.debuggers.remove(self) + + def SwitchToOutputTab(self): + self._notebook.SetSelection(0) + + def DisableWhileDebuggerRunning(self): + self._tb.EnableTool(self.STEP_ID, False) + self._tb.EnableTool(self.CONTINUE_ID, False) + self._tb.EnableTool(self.STEP_OUT_ID, False) + self._tb.EnableTool(self.NEXT_ID, False) + self._tb.EnableTool(self.BREAK_INTO_DEBUGGER_ID, True) + if _WATCHES_ON: + self._tb.EnableTool(self.ADD_WATCH_ID, False) + openDocs = wx.GetApp().GetDocumentManager().GetDocuments() + for openDoc in openDocs: + if(isinstance(openDoc.GetFirstView(), CodeEditor.CodeView)): + openDoc.GetFirstView().GetCtrl().ClearCurrentLineMarkers() + if self.framesTab: + self.framesTab.ClearWhileRunning() + #wx.GetApp().ProcessPendingEvents() #Yield(True) + + def EnableWhileDebuggerStopped(self): + self._tb.EnableTool(self.STEP_ID, True) + self._tb.EnableTool(self.CONTINUE_ID, True) + self._tb.EnableTool(self.STEP_OUT_ID, True) + self._tb.EnableTool(self.NEXT_ID, True) + if _WATCHES_ON: + self._tb.EnableTool(self.ADD_WATCH_ID, True) + self._tb.EnableTool(self.BREAK_INTO_DEBUGGER_ID, False) + #if _WINDOWS: + # wx.GetApp().GetTopWindow().RequestUserAttention() + + def ExecutorFinished(self): + if _VERBOSE: print "In ExectorFinished" + try: + self.DisableAfterStop() + except wx._core.PyDeadObjectError: + pass + try: + nb = self.GetParent() + for i in range(0, nb.GetPageCount()): + if self == nb.GetPage(i): + text = nb.GetPageText(i) + newText = text.replace("Debugging", "Finished") + nb.SetPageText(i, newText) + if _VERBOSE: print "In ExectorFinished, changed tab title." + break + except: + if _VERBOSE: print "In ExectorFinished, got exception" + + def DisableAfterStop(self): + self.DisableWhileDebuggerRunning() + self._tb.EnableTool(self.BREAK_INTO_DEBUGGER_ID, False) + self._tb.EnableTool(self.KILL_PROCESS_ID, False) + + def SynchCurrentLine(self, filename, lineNum): + # FACTOR THIS INTO DocManager + self.DeleteCurrentLineMarkers() + + # Filename will be if we're in a bit of code that was executed from + # a string (rather than a file). I haven't been able to get the original string + # for display. + if filename == '': + return + foundView = None + openDocs = wx.GetApp().GetDocumentManager().GetDocuments() + for openDoc in openDocs: + # This ugliness to prevent comparison failing because the drive letter + # gets lowercased occasionally. Don't know why that happens or why it + # only happens occasionally. + if DebuggerService.ComparePaths(openDoc.GetFilename(),filename): + foundView = openDoc.GetFirstView() + break + + if not foundView: + if _VERBOSE: + print "filename=", filename + doc = wx.GetApp().GetDocumentManager().CreateDocument(DebuggerService.ExpandPath(filename), wx.lib.docview.DOC_SILENT) + foundView = doc.GetFirstView() + + if foundView: + foundView.GetFrame().SetFocus() + foundView.Activate() + foundView.GotoLine(lineNum) + startPos = foundView.PositionFromLine(lineNum) + + foundView.GetCtrl().MarkerAdd(lineNum -1, CodeEditor.CodeCtrl.CURRENT_LINE_MARKER_NUM) + + def DeleteCurrentLineMarkers(self): + openDocs = wx.GetApp().GetDocumentManager().GetDocuments() + for openDoc in openDocs: + if(isinstance(openDoc.GetFirstView(), CodeEditor.CodeView)): + openDoc.GetFirstView().GetCtrl().ClearCurrentLineMarkers() + + def LoadFramesListXML(self, framesXML): + self.framesTab.LoadFramesListXML(framesXML) + + def SetStatusText(self, text): + self._statusBar.SetStatusText(text,0) + + def Execute(self, initialArgs, startIn, environment): + self._callback.start() + self._executor.Execute(initialArgs, startIn, environment) + self._callback.waitForRPC() + + def BreakExecution(self, event): + self._callback.BreakExecution() + + + def StopExecution(self, event): + self._stopped = True + self.DisableAfterStop() + try: + self._callback.ServerClose() + except: + pass + try: + if self._executor: + self._executor.DoStopExecution() + self._executor = None + except: + pass + self.DeleteCurrentLineMarkers() + DebugCommandUI.ReturnPortToPool(self._debuggerPort) + DebugCommandUI.ReturnPortToPool(self._guiPort) + DebugCommandUI.ReturnPortToPool(self._debuggerBreakPort) + + def StopAndRemoveUI(self, event): + self.StopExecution(None) + if self in DebugCommandUI.debuggers: + DebugCommandUI.debuggers.remove(self) + index = self._parentNoteBook.GetSelection() + self._parentNoteBook.GetPage(index).Show(False) + self._parentNoteBook.RemovePage(index) + + def GetConsoleTextControl(self): + return self._textCtrl + + def OnClearOutput(self, event): + self._textCtrl.SetReadOnly(False) + self._textCtrl.ClearAll() + self._textCtrl.SetReadOnly(True) + + def OnAddWatch(self, event): + if self.framesTab: + self.framesTab.OnWatch(event) + + def MakeConsoleTab(self, parent, id, debugger): + panel = wx.Panel(parent, id) + sizer = wx.BoxSizer(wx.HORIZONTAL) + self._textCtrl = STCTextEditor.TextCtrl(panel, wx.NewId()) + sizer.Add(self._textCtrl, 1, wx.ALIGN_LEFT|wx.ALL|wx.EXPAND, 1) + self._textCtrl.SetViewLineNumbers(False) + self._textCtrl.SetReadOnly(True) + if wx.Platform == '__WXMSW__': + font = "Courier New" + else: + font = "Courier" + self._textCtrl.SetFont(wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.NORMAL, faceName = font)) + self._textCtrl.SetFontColor(wx.BLACK) + self._textCtrl.StyleClearAll() + panel.SetSizer(sizer) + sizer.Fit(panel) + + return panel + + def MakeFramesTab(self, parent, id, debugger): + panel = FramesUI(parent, id, self) + return panel + + def MakeBreakPointsTab(self, parent, id, debugger): + panel = BreakpointsUI(parent, id, self) + return panel + + def AppendText(self, event): + self._textCtrl.SetReadOnly(False) + self._textCtrl.AddText(event.value) + self._textCtrl.ScrollToLine(self._textCtrl.GetLineCount()) + self._textCtrl.SetReadOnly(True) + + def AppendErrorText(self, event): + self._textCtrl.SetReadOnly(False) + self._textCtrl.SetFontColor(wx.RED) + self._textCtrl.StyleClearAll() + self._textCtrl.AddText(event.value) + self._textCtrl.ScrollToLine(self._textCtrl.GetLineCount()) + self._textCtrl.SetFontColor(wx.BLACK) + self._textCtrl.StyleClearAll() + self._textCtrl.SetReadOnly(True) + +class BreakpointsUI(wx.Panel): + def __init__(self, parent, id, ui): + wx.Panel.__init__(self, parent, id) + self._ui = ui + self.currentItem = None + self.clearBPID = wx.NewId() + self.Bind(wx.EVT_MENU, self.ClearBreakPoint, id=self.clearBPID) + self.syncLineID = wx.NewId() + self.Bind(wx.EVT_MENU, self.SyncBPLine, id=self.syncLineID) + + sizer = wx.BoxSizer(wx.VERTICAL) + p1 = self + self._bpListCtrl = wx.ListCtrl(p1, -1, pos=wx.DefaultPosition, size=(1000,1000), style=wx.LC_REPORT) + sizer.Add(self._bpListCtrl, 1, wx.ALIGN_LEFT|wx.ALL|wx.EXPAND, 1) + self._bpListCtrl.InsertColumn(0, "File") + self._bpListCtrl.InsertColumn(1, "Line") + self._bpListCtrl.InsertColumn(2, "Path") + self._bpListCtrl.SetColumnWidth(0, 150) + self._bpListCtrl.SetColumnWidth(1, 50) + self._bpListCtrl.SetColumnWidth(2, 450) + self._bpListCtrl.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnListRightClick) + self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.ListItemSelected, self._bpListCtrl) + self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.ListItemDeselected, self._bpListCtrl) + + self.PopulateBPList() + + p1.SetSizer(sizer) + sizer.Fit(p1) + p1.Layout() + + def PopulateBPList(self): + list = self._bpListCtrl + list.DeleteAllItems() + + bps = wx.GetApp().GetService(DebuggerService).GetMasterBreakpointDict() + index = 0 + for fileName in bps.keys(): + shortFile = os.path.basename(fileName) + lines = bps[fileName] + if lines: + for line in lines: + list.InsertStringItem(index, shortFile) + list.SetStringItem(index, 1, str(line)) + list.SetStringItem(index, 2, fileName) + + def OnListRightClick(self, event): + menu = wx.Menu() + item = wx.MenuItem(menu, self.clearBPID, "Clear Breakpoint") + menu.AppendItem(item) + item = wx.MenuItem(menu, self.syncLineID, "Goto Source Line") + menu.AppendItem(item) + self.PopupMenu(menu, event.GetPosition()) + menu.Destroy() + + def SyncBPLine(self, event): + if self.currentItem != -1: + list = self._bpListCtrl + fileName = list.GetItem(self.currentItem, 2).GetText() + lineNumber = list.GetItem(self.currentItem, 1).GetText() + self._ui.SynchCurrentLine( fileName, int(lineNumber) ) + + def ClearBreakPoint(self, event): + if self.currentItem >= 0: + list = self._bpListCtrl + fileName = list.GetItem(self.currentItem, 2).GetText() + lineNumber = list.GetItem(self.currentItem, 1).GetText() + wx.GetApp().GetService(DebuggerService).OnToggleBreakpoint(None, line=int(lineNumber) -1, fileName=fileName ) + + def ListItemSelected(self, event): + self.currentItem = event.m_itemIndex + + def ListItemDeselected(self, event): + self.currentItem = -1 + +class Watch: + CODE_ALL_FRAMES = 1 + CODE_THIS_BLOCK = 2 + CODE_THIS_LINE = 4 + CODE_RUN_ONCE = 8 + + def __init__(self, name, command, show_code=CODE_ALL_FRAMES): + self._name = name + self._command = command + self._show_code = show_code + +class WatchDialog(wx.Dialog): + WATCH_ALL_FRAMES = "Watch in all frames" + WATCH_THIS_FRAME = "Watch in this frame only" + WATCH_ONCE = "Watch once and delete" + def __init__(self, parent, title, chain): + wx.Dialog.__init__(self, parent, -1, title, style=wx.DEFAULT_DIALOG_STYLE) + self._chain = chain + self.label_2 = wx.StaticText(self, -1, "Watch Name:") + self._watchNameTextCtrl = wx.TextCtrl(self, -1, "") + self.label_3 = wx.StaticText(self, -1, "eval(", style=wx.ALIGN_RIGHT) + self._watchValueTextCtrl = wx.TextCtrl(self, -1, "") + self.label_4 = wx.StaticText(self, -1, ",frame.f_globals, frame.f_locals)") + self.radio_box_1 = wx.RadioBox(self, -1, "Watch Information", choices=[WatchDialog.WATCH_ALL_FRAMES, WatchDialog.WATCH_THIS_FRAME, WatchDialog.WATCH_ONCE], majorDimension=0, style=wx.RA_SPECIFY_ROWS) + + self._okButton = wx.Button(self, wx.ID_OK, "OK", size=(75,-1)) + self._okButton.SetDefault() + self._okButton.SetHelpText(_("The OK button completes the dialog")) + def OnOkClick(event): + if self._watchNameTextCtrl.GetValue() == "": + wx.MessageBox(_("You must enter a name for the watch."), _("Add Watch")) + return + if self._watchValueTextCtrl.GetValue() == "": + wx.MessageBox(_("You must enter some code to run for the watch."), _("Add Watch")) + return + self.EndModal(wx.ID_OK) + self.Bind(wx.EVT_BUTTON, OnOkClick, self._okButton) + + self._cancelButton = wx.Button(self, wx.ID_CANCEL, _("Cancel"), size=(75,-1)) + self._cancelButton.SetHelpText(_("The Cancel button cancels the dialog.")) + + self.__set_properties() + self.__do_layout() + + def GetSettings(self): + return self._watchNameTextCtrl.GetValue(), self._watchValueTextCtrl.GetValue(), self.GetSendFrame(), self.GetRunOnce() + + def GetSendFrame(self): + return (WatchDialog.WATCH_ALL_FRAMES != self.radio_box_1.GetStringSelection()) + + def GetRunOnce(self): + return (WatchDialog.WATCH_ONCE == self.radio_box_1.GetStringSelection()) + + def __set_properties(self): + self.SetTitle("Add a Watch") + #self.SetSize((400, 250)) + self.radio_box_1.SetSelection(0) + + def __do_layout(self): + sizer_1 = wx.BoxSizer(wx.VERTICAL) + grid_sizer_4 = wx.FlexGridSizer(1, 3, 5, 5) + grid_sizer_2 = wx.FlexGridSizer(1, 2, 5, 5) + grid_sizer_2.Add(self.label_2, 0, wx.ALIGN_CENTER_VERTICAL|wx.FIXED_MINSIZE, 0) + grid_sizer_2.Add(self._watchNameTextCtrl, 0, wx.EXPAND, 0) + grid_sizer_2.AddGrowableCol(1) + sizer_1.Add(grid_sizer_2, 1, wx.EXPAND, 0) + grid_sizer_4.Add(self.label_3, 0, wx.ALIGN_CENTER_VERTICAL|wx.FIXED_MINSIZE, 0) + grid_sizer_4.Add(self._watchValueTextCtrl, 0, wx.EXPAND, 0) + grid_sizer_4.AddGrowableCol(1) + grid_sizer_4.Add(self.label_4, 0, wx.ALIGN_CENTER_VERTICAL|wx.FIXED_MINSIZE, 0) + sizer_1.Add(grid_sizer_4, 0, wx.EXPAND, 0) + sizer_1.Add(self.radio_box_1, 0, wx.EXPAND, 0) + + box = wx.BoxSizer(wx.HORIZONTAL) + box.Add(self._okButton, 0, wx.ALIGN_RIGHT|wx.ALL, 5) + box.Add(self._cancelButton, 0, wx.ALIGN_RIGHT|wx.ALL, 5) + sizer_1.Add(box, 1, wx.EXPAND, 0) + self.SetAutoLayout(True) + self.SetSizer(sizer_1) + self.Layout() + +class FramesUI(wx.SplitterWindow): + def __init__(self, parent, id, ui): + wx.SplitterWindow.__init__(self, parent, id, style = wx.SP_3D) + self._ui = ui + sizer = wx.BoxSizer(wx.VERTICAL) + self._p1 = p1 = wx.ScrolledWindow(self, -1) + p1.Bind(wx.EVT_SIZE, self.OnSize) + + self._framesListCtrl = wx.ListCtrl(p1, -1, pos=wx.DefaultPosition, size=(250,150), style=wx.LC_REPORT) + sizer.Add(self._framesListCtrl, 1, wx.ALIGN_LEFT|wx.ALL|wx.EXPAND, 1) + self._framesListCtrl.InsertColumn(0, "Frame") + self._framesListCtrl.SetColumnWidth(0, 250) + self._framesListCtrl.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnListRightClick) + self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.ListItemSelected, self._framesListCtrl) + self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.ListItemDeselected, self._framesListCtrl) + + sizer2 = wx.BoxSizer(wx.VERTICAL) + self._p2 = p2 = wx.ScrolledWindow(self, -1) + p2.Bind(wx.EVT_SIZE, self.OnSize) + + self._treeCtrl = wx.gizmos.TreeListCtrl(p2, -1, size=(530,250), style=wx.TR_DEFAULT_STYLE| wx.TR_FULL_ROW_HIGHLIGHT) + self._treeCtrl.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnRightClick) + sizer2.Add(self._framesListCtrl, 1, wx.ALIGN_LEFT|wx.ALL|wx.EXPAND, 1) + tree = self._treeCtrl + tree.AddColumn("Thing") + tree.AddColumn("Value") + tree.SetMainColumn(0) # the one with the tree in it... + tree.SetColumnWidth(0, 175) + tree.SetColumnWidth(1, 355) + self._root = tree.AddRoot("Frame") + tree.SetItemText(self._root, "", 1) + + self.SetMinimumPaneSize(20) + self.SplitVertically(p1, p2, 250) + self.currentItem = None + self.Layout() + + def OnRightClick(self, event): + #Refactor this... + self._introspectItem = event.GetItem() + self._parentChain = self.GetItemChain(event.GetItem()) + watchOnly = len(self._parentChain) < 1 + if not _WATCHES_ON and watchOnly: + return + menu = wx.Menu() + if not watchOnly: + if not hasattr(self, "introspectID"): + self.introspectID = wx.NewId() + self.Bind(wx.EVT_MENU, self.OnIntrospect, id=self.introspectID) + item = wx.MenuItem(menu, self.introspectID, "Attempt Introspection") + menu.AppendItem(item) + menu.AppendSeparator() + if _WATCHES_ON: + if not hasattr(self, "watchID"): + self.watchID = wx.NewId() + self.Bind(wx.EVT_MENU, self.OnWatch, id=self.watchID) + item = wx.MenuItem(menu, self.watchID, "Create a Watch") + menu.AppendItem(item) + menu.AppendSeparator() + if not watchOnly: + if not hasattr(self, "viewID"): + self.viewID = wx.NewId() + self.Bind(wx.EVT_MENU, self.OnView, id=self.viewID) + item = wx.MenuItem(menu, self.viewID, "View in Dialog") + menu.AppendItem(item) + offset = wx.Point(x=0, y=20) + menuSpot = event.GetPoint() + offset + self._treeCtrl.PopupMenu(menu, menuSpot) + menu.Destroy() + self._parentChain = None + self._introspectItem = None + + def GetItemChain(self, item): + parentChain = [] + if item: + if _VERBOSE: print 'Exploding: %s' % self._treeCtrl.GetItemText(item, 0) + while item != self._root: + text = self._treeCtrl.GetItemText(item, 0) + if _VERBOSE: print "Appending ", text + parentChain.append(text) + item = self._treeCtrl.GetItemParent(item) + parentChain.reverse() + return parentChain + + def OnView(self, event): + title = self._treeCtrl.GetItemText(self._introspectItem,0) + value = self._treeCtrl.GetItemText(self._introspectItem,1) + dlg = wx.lib.dialogs.ScrolledMessageDialog(self, value, title, style=wx.DD_DEFAULT_STYLE | wx.RESIZE_BORDER) + dlg.Show() + + def OnWatch(self, event): + try: + if hasattr(self, '_parentChain'): + wd = WatchDialog(wx.GetApp().GetTopWindow(), "Add a Watch", self._parentChain) + else: + wd = WatchDialog(wx.GetApp().GetTopWindow(), "Add a Watch", None) + if wd.ShowModal() == wx.ID_OK: + name, text, send_frame, run_once = wd.GetSettings() + if send_frame: + frameNode = self._stack[int(self.currentItem)] + message = frameNode.getAttribute("message") + else: + message = "" + binType = self._ui._callback._debuggerServer.add_watch(name, text, message, run_once) + xmldoc = bz2.decompress(binType.data) + domDoc = parseString(xmldoc) + nodeList = domDoc.getElementsByTagName('watch') + if len(nodeList) == 1: + watchValue = nodeList.item(0).getAttribute("message") + except: + tp, val, tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + + def OnIntrospect(self, event): + wx.GetApp().GetTopWindow().SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) + + try: + list = self._framesListCtrl + frameNode = self._stack[int(self.currentItem)] + message = frameNode.getAttribute("message") + binType = self._ui._callback._debuggerServer.attempt_introspection(message, self._parentChain) + xmldoc = bz2.decompress(binType.data) + + domDoc = parseString(xmldoc) + nodeList = domDoc.getElementsByTagName('replacement') + replacementNode = nodeList.item(0) + if len(replacementNode.childNodes): + thingToWalk = replacementNode.childNodes.item(0) + tree = self._treeCtrl + parent = tree.GetItemParent(self._introspectItem) + treeNode = self.AppendSubTreeFromNode(thingToWalk, thingToWalk.getAttribute('name'), parent, insertBefore=self._introspectItem) + tree.Delete(self._introspectItem) + except: + tp,val,tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + + wx.GetApp().GetTopWindow().SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT)) + + def OnSize(self, event): + self._treeCtrl.SetSize(self._p2.GetSize()) + w,h = self._p1.GetClientSizeTuple() + self._framesListCtrl.SetDimensions(0, 0, w, h) + + def ClearWhileRunning(self): + list = self._framesListCtrl + list.DeleteAllItems() + tree = self._treeCtrl + tree.Hide() + + def OnListRightClick(self, event): + if not hasattr(self, "syncFrameID"): + self.syncFrameID = wx.NewId() + self.Bind(wx.EVT_MENU, self.OnSyncFrame, id=self.syncFrameID) + menu = wx.Menu() + item = wx.MenuItem(menu, self.syncFrameID, "Goto Source Line") + menu.AppendItem(item) + self.PopupMenu(menu, event.GetPosition()) + menu.Destroy() + + def OnSyncFrame(self, event): + list = self._framesListCtrl + frameNode = self._stack[int(self.currentItem)] + file = frameNode.getAttribute("file") + line = frameNode.getAttribute("line") + self._ui.SynchCurrentLine( file, int(line) ) + + def LoadFramesListXML(self, framesXML): + wx.GetApp().GetTopWindow().SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) + try: + domDoc = parseString(framesXML) + list = self._framesListCtrl + list.DeleteAllItems() + self._stack = [] + nodeList = domDoc.getElementsByTagName('frame') + frame_count = -1 + for index in range(0, nodeList.length): + frameNode = nodeList.item(index) + message = frameNode.getAttribute("message") + list.InsertStringItem(index, message) + self._stack.append(frameNode) + frame_count += 1 + list.Select(frame_count) + self._p1.FitInside() + frameNode = nodeList.item(index) + file = frameNode.getAttribute("file") + line = frameNode.getAttribute("line") + self._ui.SynchCurrentLine( file, int(line) ) + except: + tp,val,tb=sys.exc_info() + traceback.print_exception(tp, val, tb) + + wx.GetApp().GetTopWindow().SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT)) + + def ListItemDeselected(self, event): + pass + + def ListItemSelected(self, event): + self.currentItem = event.m_itemIndex + frameNode = self._stack[int(self.currentItem)] + self.PopulateTreeFromFrameNode(frameNode) + # Temporarily doing this to test out automatically swicting to source line. + self.OnSyncFrame(None) + + def PopulateTreeFromFrameNode(self, frameNode): + tree = self._treeCtrl + tree.Show(True) + root = self._root + tree.DeleteChildren(root) + children = frameNode.childNodes + firstChild = None + for index in range(0, children.length): + subNode = children.item(index) + treeNode = self.AppendSubTreeFromNode(subNode, subNode.getAttribute('name'), root) + if not firstChild: + firstChild = treeNode + tree.Expand(root) + tree.Expand(firstChild) + self._p2.FitInside() + + def AppendSubTreeFromNode(self, node, name, parent, insertBefore=None): + tree = self._treeCtrl + if insertBefore != None: + treeNode = tree.InsertItem(parent, insertBefore, name) + else: + treeNode = tree.AppendItem(parent, name) + children = node.childNodes + if children.length == 0: + tree.SetItemText(treeNode, self.StripOuterSingleQuotes(node.getAttribute("value")), 1) + for index in range(0, children.length): + subNode = children.item(index) + if self.HasChildren(subNode): + self.AppendSubTreeFromNode(subNode, subNode.getAttribute("name"), treeNode) + else: + name = subNode.getAttribute("name") + value = self.StripOuterSingleQuotes(subNode.getAttribute("value")) + n = tree.AppendItem(treeNode, name) + tree.SetItemText(n, value, 1) + return treeNode + + def StripOuterSingleQuotes(self, string): + if string.startswith("'") and string.endswith("'"): + return string[1:-1] + elif type(string) == types.UnicodeType: + return string[1:-1] + else: + return string + + def HasChildren(self, node): + try: + return node.childNodes.length > 0 + except: + tp,val,tb=sys.exc_info() + return False + +class DebuggerView(Service.ServiceView): + + #---------------------------------------------------------------------------- + # Overridden methods + #---------------------------------------------------------------------------- + + def __init__(self, service): + Service.ServiceView.__init__(self, service) + + def _CreateControl(self, parent, id): + return None + + #------------------------------------------------------------------------------ + # Event handling + #----------------------------------------------------------------------------- + + def OnToolClicked(self, event): + self.GetFrame().ProcessEvent(event) + + #------------------------------------------------------------------------------ + # Class methods + #----------------------------------------------------------------------------- + +class Interaction: + def __init__(self, message, framesXML, info=None, quit=False): + self._framesXML = framesXML + self._message = message + self._info = info + self._quit = quit + + def getFramesXML(self): + return self._framesXML + + def getMessage(self): + return self._message + + def getInfo(self): + return self._info + + def getQuit(self): + return self._quit + +class AGXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): + def __init__(self, address, logRequests=0): + SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, address, logRequests=logRequests) + +class RequestHandlerThread(threading.Thread): + def __init__(self, queue, address): + threading.Thread.__init__(self) + self._keepGoing = True + self._queue = queue + self._address = address + self._server = AGXMLRPCServer(self._address,logRequests=0) + self._server.register_function(self.interaction) + self._server.register_function(self.quit) + self._server.register_function(self.dummyOperation) + if _VERBOSE: print "RequestHandlerThread on fileno %s" % str(self._server.fileno()) + + def run(self): + while self._keepGoing: + try: + self._server.handle_request() + except: + tp, val, tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + self._keepGoing = False + if _VERBOSE: print "Exiting Request Handler Thread." + + def interaction(self, message, frameXML, info): + if _VERBOSE: print "In RequestHandlerThread.interaction -- adding to queue" + interaction = Interaction(message, frameXML, info) + self._queue.put(interaction) + return "" + + def quit(self): + interaction = Interaction(None, None, info=None, quit=True) + self._queue.put(interaction) + return "" + + def dummyOperation(self): + return "" + + def AskToStop(self): + self._keepGoing = False + if type(self._server) is not types.NoneType: + try: + # This is a really ugly way to make sure this thread isn't blocked in + # handle_request. + url = 'http://' + self._address[0] + ':' + str(self._address[1]) + '/' + tempServer = xmlrpclib.ServerProxy(url, allow_none=1) + tempServer.dummyOperation() + except: + tp, val, tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + self._server.server_close() + + +class RequestBreakThread(threading.Thread): + def __init__(self, server, interrupt=False, pushBreakpoints=False, breakDict=None, kill=False): + threading.Thread.__init__(self) + self._server = server + + self._interrupt = interrupt + self._pushBreakpoints = pushBreakpoints + self._breakDict = breakDict + self._kill = kill + + def run(self): + try: + if _VERBOSE: print "RequestBreakThread, before call" + if self._interrupt: + self._server.break_requested() + if self._pushBreakpoints: + self._server.update_breakpoints(xmlrpclib.Binary(pickle.dumps(self._breakDict))) + if self._kill: + try: + self._server.die() + except: + pass + if _VERBOSE: print "RequestBreakThread, after call" + except: + tp,val,tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + +class DebuggerOperationThread(threading.Thread): + def __init__(self, function): + threading.Thread.__init__(self) + self._function = function + + def run(self): + if _VERBOSE: print "In DOT, before call" + try: + self._function() + except: + tp,val,tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + if _VERBOSE: print "In DOT, after call" + +class DebuggerCallback: + + def __init__(self, host, port, debugger_url, break_url, debuggerUI): + if _VERBOSE: print "+++++++ Creating server on port, ", str(port) + + self._queue = Queue.Queue(50) + self._host = host + self._port = int(port) + threading._VERBOSE = _VERBOSE + self._serverHandlerThread = RequestHandlerThread(self._queue, (self._host, self._port)) + + self._debugger_url = debugger_url + self._debuggerServer = None + self._waiting = False + self._service = wx.GetApp().GetService(DebuggerService) + self._debuggerUI = debuggerUI + self._break_url = break_url + self._breakServer = None + self._firstInteraction = True + self._pendingBreak = False + + def start(self): + self._serverHandlerThread.start() + + def ServerClose(self): + rbt = RequestBreakThread(self._breakServer, kill=True) + rbt.start() + self.setWaiting(False) + if self._serverHandlerThread: + self._serverHandlerThread.AskToStop() + self._serverHandlerThread = None + + def BreakExecution(self): + rbt = RequestBreakThread(self._breakServer, interrupt=True) + rbt.start() + + def SingleStep(self): + self._debuggerUI.DisableWhileDebuggerRunning() + #dot = DebuggerOperationThread(self._debuggerServer.set_step) + #dot.start() + self._debuggerServer.set_step() # Figure out where to set allowNone + self.waitForRPC() + + def Next(self): + self._debuggerUI.DisableWhileDebuggerRunning() + #dot = DebuggerOperationThread(self._debuggerServer.set_next) + #dot.start() + self._debuggerServer.set_next() + self.waitForRPC() + + def Continue(self): + self._debuggerUI.DisableWhileDebuggerRunning() + #dot = DebuggerOperationThread(self._debuggerServer.set_continue) + #dot.start() + self._debuggerServer.set_continue() + self.waitForRPC() + + def Return(self): + self._debuggerUI.DisableWhileDebuggerRunning() + #dot = DebuggerOperationThread(self._debuggerServer.set_return) + #dot.start() + self._debuggerServer.set_return() + self.waitForRPC() + + def setWaiting(self, value): + self._waiting = value + + def getWaiting(self): + return self._waiting + + def readQueue(self): + if self._queue.qsize(): + try: + item = self._queue.get_nowait() + if item.getQuit(): + self.interaction(None, None, None, True) + else: + data = bz2.decompress(item.getFramesXML().data) + self.interaction(item.getMessage().data, data, item.getInfo(), False) + except Queue.Empty: + pass + + def pushBreakpoints(self): + rbt = RequestBreakThread(self._breakServer, pushBreakpoints=True, breakDict=self._service.GetMasterBreakpointDict()) + rbt.start() + + + def waitForRPC(self): + self.setWaiting(True) + while self.getWaiting(): + try: + self.readQueue() + import time + time.sleep(0.02) + except: + tp, val, tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + wx.GetApp().Yield(True) + if _VERBOSE: print "Exiting waitForRPC." + + def interaction(self, message, frameXML, info, quit): + + #This method should be hit as the debugger starts. + if self._firstInteraction: + self._firstInteraction = False + self._debuggerServer = xmlrpclib.ServerProxy(self._debugger_url, allow_none=1) + self._breakServer = xmlrpclib.ServerProxy(self._break_url, allow_none=1) + self.pushBreakpoints() + self.setWaiting(False) + if _VERBOSE: print "+"*40 + if(quit): + self._debuggerUI.StopExecution(None) + return "" + if(info != ""): + if _VERBOSE: print "Hit interaction with exception" + #self._debuggerUI.StopExecution(None) + #self._debuggerUI.SetStatusText("Got exception: " + str(info)) + self._debuggerUI.SwitchToOutputTab() + else: + if _VERBOSE: print "Hit interaction no exception" + self._debuggerUI.SetStatusText(message) + self._debuggerUI.LoadFramesListXML(frameXML) + self._debuggerUI.EnableWhileDebuggerStopped() + if _VERBOSE: print "+"*40 + +class DebuggerService(Service.Service): + + #---------------------------------------------------------------------------- + # Constants + #---------------------------------------------------------------------------- + TOGGLE_BREAKPOINT_ID = wx.NewId() + CLEAR_ALL_BREAKPOINTS = wx.NewId() + RUN_ID = wx.NewId() + DEBUG_ID = wx.NewId() + + def ComparePaths(first, second): + one = DebuggerService.ExpandPath(first) + two = DebuggerService.ExpandPath(second) + if _WINDOWS: + return one.lower() == two.lower() + else: + return one == two + ComparePaths = staticmethod(ComparePaths) + + # Make sure we're using an expanded path on windows. + def ExpandPath(path): + if _WINDOWS: + try: + return win32api.GetLongPathName(path) + except: + print "Cannot get long path for %s" % path + + return path + + ExpandPath = staticmethod(ExpandPath) + + #---------------------------------------------------------------------------- + # Overridden methods + #---------------------------------------------------------------------------- + + def __init__(self, serviceName, embeddedWindowLocation = wx.lib.pydocview.EMBEDDED_WINDOW_LEFT): + Service.Service.__init__(self, serviceName, embeddedWindowLocation) + self.BREAKPOINT_DICT_STRING = "MasterBreakpointDict" + config = wx.ConfigBase_Get() + pickledbps = config.Read(self.BREAKPOINT_DICT_STRING) + if pickledbps: + try: + self._masterBPDict = pickle.loads(pickledbps.encode('ascii')) + except: + tp, val, tb = sys.exc_info() + traceback.print_exception(tp,val,tb) + self._masterBPDict = {} + else: + self._masterBPDict = {} + + def OnCloseFrame(self, event): + # IS THIS THE RIGHT PLACE? + try: + config = wx.ConfigBase_Get() + config.Write(self.BREAKPOINT_DICT_STRING, pickle.dumps(self._masterBPDict)) + except: + tp,val,tb = sys.exc_info() + traceback.print_exception(tp, val, tb) + return True + + def _CreateView(self): + return DebuggerView(self) + + + #---------------------------------------------------------------------------- + # Service specific methods + #---------------------------------------------------------------------------- + + def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None): + #Service.Service.InstallControls(self, frame, menuBar, toolBar, statusBar, document) + + config = wx.ConfigBase_Get() + + debuggerMenu = wx.Menu() + if not menuBar.FindItemById(DebuggerService.CLEAR_ALL_BREAKPOINTS): + + debuggerMenu.Append(DebuggerService.RUN_ID, _("&Run...\tCtrl+R"), _("Runs a file")) + wx.EVT_MENU(frame, DebuggerService.RUN_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, DebuggerService.RUN_ID, frame.ProcessUpdateUIEvent) + + debuggerMenu.Append(DebuggerService.DEBUG_ID, _("&Debug...\tCtrl+D"), _("Debugs a file")) + wx.EVT_MENU(frame, DebuggerService.DEBUG_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, DebuggerService.DEBUG_ID, frame.ProcessUpdateUIEvent) + + debuggerMenu.AppendSeparator() + + debuggerMenu.Append(DebuggerService.TOGGLE_BREAKPOINT_ID, _("&Toggle Breakpoint...\tCtrl+B"), _("Toggle a breakpoint")) + wx.EVT_MENU(frame, DebuggerService.TOGGLE_BREAKPOINT_ID, self.ProcessEvent) + wx.EVT_UPDATE_UI(frame, DebuggerService.TOGGLE_BREAKPOINT_ID, self.ProcessUpdateUIEvent) + + debuggerMenu.Append(DebuggerService.CLEAR_ALL_BREAKPOINTS, _("&Clear All Breakpoints"), _("Clear All Breakpoints")) + wx.EVT_MENU(frame, DebuggerService.CLEAR_ALL_BREAKPOINTS, self.ProcessEvent) + wx.EVT_UPDATE_UI(frame, DebuggerService.CLEAR_ALL_BREAKPOINTS, self.ProcessUpdateUIEvent) + + + viewMenuIndex = menuBar.FindMenu(_("&Project")) + menuBar.Insert(viewMenuIndex + 1, debuggerMenu, _("&Run")) + + return True + + + + #---------------------------------------------------------------------------- + # Event Processing Methods + #---------------------------------------------------------------------------- + + def ProcessEventBeforeWindows(self, event): + return False + + + def ProcessEvent(self, event): + if Service.Service.ProcessEvent(self, event): + return True + + an_id = event.GetId() + if an_id == DebuggerService.TOGGLE_BREAKPOINT_ID: + self.OnToggleBreakpoint(event) + return True + elif an_id == DebuggerService.CLEAR_ALL_BREAKPOINTS: + self.ClearAllBreakpoints() + return True + elif an_id == DebuggerService.RUN_ID: + self.OnRunProject(event) + return True + elif an_id == DebuggerService.DEBUG_ID: + self.OnDebugProject(event) + return True + return False + + def ProcessUpdateUIEvent(self, event): + if Service.Service.ProcessUpdateUIEvent(self, event): + return True + + an_id = event.GetId() + if an_id == DebuggerService.TOGGLE_BREAKPOINT_ID: + currentView = self.GetDocumentManager().GetCurrentView() + event.Enable(isinstance(currentView, PythonEditor.PythonView)) + return True + elif an_id == DebuggerService.CLEAR_ALL_BREAKPOINTS: + event.Enable(self.HasBreakpointsSet()) + return True + elif an_id == DebuggerService.RUN_ID: + event.Enable(self.HasAnyFiles()) + return True + elif an_id == DebuggerService.DEBUG_ID: + event.Enable(self.HasAnyFiles()) + return True + else: + return False + + #---------------------------------------------------------------------------- + # Class Methods + #---------------------------------------------------------------------------- + + def OnDebugProject(self, event): + if not Executor.GetPythonExecutablePath(): + return + if DebugCommandUI.DebuggerRunning(): + wx.MessageBox(_("A debugger is already running. Please shut down the other debugger first."), _("Debugger Running")) + return + self.ShowWindow(True) + projectService = wx.GetApp().GetService(ProjectEditor.ProjectService) + project = projectService.GetView().GetDocument() + dlg = CommandPropertiesDialog(self.GetView().GetFrame(), 'Debug Python File', projectService, None, pythonOnly=True, okButtonName="Debug", debugging=True) + if dlg.ShowModal() == wx.ID_OK: + fileToDebug, initialArgs, startIn, isPython, environment = dlg.GetSettings() + dlg.Destroy() + else: + dlg.Destroy() + return + self.PromptToSaveFiles() + + shortFile = os.path.basename(fileToDebug) + fileToDebug = DebuggerService.ExpandPath(fileToDebug) + try: + page = DebugCommandUI(Service.ServiceView.bottomTab, -1, str(fileToDebug), self) + count = Service.ServiceView.bottomTab.GetPageCount() + Service.ServiceView.bottomTab.AddPage(page, "Debugging: " + shortFile) + Service.ServiceView.bottomTab.SetSelection(count) + page.Execute(initialArgs, startIn, environment) + except: + pass + + def HasAnyFiles(self): + docs = wx.GetApp().GetDocumentManager().GetDocuments() + return len(docs) > 0 + + def PromptToSaveFiles(self, running=True): + filesModified = False + docs = wx.GetApp().GetDocumentManager().GetDocuments() + for doc in docs: + if doc.IsModified(): + filesModified = True + break + if filesModified: + frame = self.GetView().GetFrame() + if running: + yesNoMsg = wx.MessageDialog(frame, + _("Files have been modified.\nWould you like to save all files before running?"), + _("Run"), + wx.YES_NO + ) + else: + yesNoMsg = wx.MessageDialog(frame, + _("Files have been modified.\nWould you like to save all files before debugging?"), + _("Debug"), + wx.YES_NO + ) + if yesNoMsg.ShowModal() == wx.ID_YES: + docs = wx.GetApp().GetDocumentManager().GetDocuments() + for doc in docs: + doc.Save() + + def OnExit(self): + DebugCommandUI.ShutdownAllDebuggers() + + def OnRunProject(self, event): + if not Executor.GetPythonExecutablePath(): + return + projectService = wx.GetApp().GetService(ProjectEditor.ProjectService) + project = projectService.GetView().GetDocument() + dlg = CommandPropertiesDialog(self.GetView().GetFrame(), 'Run', projectService, None) + if dlg.ShowModal() == wx.ID_OK: + fileToRun, initialArgs, startIn, isPython, environment = dlg.GetSettings() + + + dlg.Destroy() + else: + dlg.Destroy() + return + self.PromptToSaveFiles() + # This will need to change when we can run more than .py and .bpel files. + if not isPython: + projectService.RunProcessModel(fileToRun) + return + + self.ShowWindow(True) + shortFile = os.path.basename(fileToRun) + page = RunCommandUI(Service.ServiceView.bottomTab, -1, str(fileToRun)) + count = Service.ServiceView.bottomTab.GetPageCount() + Service.ServiceView.bottomTab.AddPage(page, "Running: " + shortFile) + Service.ServiceView.bottomTab.SetSelection(count) + page.Execute(initialArgs, startIn, environment) + + def OnToggleBreakpoint(self, event, line=-1, fileName=None): + if not fileName: + view = wx.GetApp().GetDocumentManager().GetCurrentView() + # Test to make sure we aren't the project view. + if not hasattr(view, 'MarkerExists'): + return + fileName = wx.GetApp().GetDocumentManager().GetCurrentDocument().GetFilename() + if line < 0: + line = view.GetCtrl().GetCurrentLine() + if self.BreakpointSet(fileName, line + 1): + self.ClearBreak(fileName, line + 1) + else: + self.SetBreak(fileName, line + 1) + # Now refresh all the markers icons in all the open views. + self.ClearAllBreakpointMarkers() + self.SetAllBreakpointMarkers() + + def SilentToggleBreakpoint(self, fileName, line): + found = False + for lineNumber in self.GetBreakpointList(fileName): + if int(lineNumber) == int(line): + found = True + break + if found: + self.SetBreak(fileName, line) + else: + self.ClearBreak(fileName, line) + + def SetBreak(self, fileName, line): + expandedName = DebuggerService.ExpandPath(fileName) + if not self._masterBPDict.has_key(expandedName): + self._masterBPDict[expandedName] = [line] + else: + self._masterBPDict[expandedName] += [line] + # If we're already debugging, pass this bp off to the DebuggerCallback + self.NotifyDebuggersOfBreakpointChange() + + def NotifyDebuggersOfBreakpointChange(self): + DebugCommandUI.NotifyDebuggersOfBreakpointChange() + + def GetBreakpointList(self, fileName): + expandedName = DebuggerService.ExpandPath(fileName) + if not self._masterBPDict.has_key(expandedName): + return [] + else: + return self._masterBPDict[expandedName] + + def BreakpointSet(self, fileName, line): + expandedName = DebuggerService.ExpandPath(fileName) + if not self._masterBPDict.has_key(expandedName): + return False + else: + newList = [] + for number in self._masterBPDict[expandedName]: + if(int(number) == int(line)): + return True + return False + + def ClearBreak(self, fileName, line): + expandedName = DebuggerService.ExpandPath(fileName) + if not self._masterBPDict.has_key(expandedName): + print "In ClearBreak: no key" + return + else: + newList = [] + for number in self._masterBPDict[expandedName]: + if(int(number) != int(line)): + newList.append(number) + self._masterBPDict[expandedName] = newList + self.NotifyDebuggersOfBreakpointChange() + + def HasBreakpointsSet(self): + for key, value in self._masterBPDict.items(): + if len(value) > 0: + return True + return False + + def ClearAllBreakpoints(self): + self._masterBPDict = {} + self.NotifyDebuggersOfBreakpointChange() + self.ClearAllBreakpointMarkers() + + def ClearAllBreakpointMarkers(self): + openDocs = wx.GetApp().GetDocumentManager().GetDocuments() + for openDoc in openDocs: + if(isinstance(openDoc.GetFirstView(), CodeEditor.CodeView)): + openDoc.GetFirstView().MarkerDeleteAll(CodeEditor.CodeCtrl.BREAKPOINT_MARKER_NUM) + + def GetMasterBreakpointDict(self): + return self._masterBPDict + + def SetAllBreakpointMarkers(self): + openDocs = wx.GetApp().GetDocumentManager().GetDocuments() + for openDoc in openDocs: + if(isinstance(openDoc.GetFirstView(), CodeEditor.CodeView)): + self.SetCurrentBreakpointMarkers(openDoc.GetFirstView()) + + def SetCurrentBreakpointMarkers(self, view): + if isinstance(view, CodeEditor.CodeView) and hasattr(view, 'GetDocument'): + view.MarkerDeleteAll(CodeEditor.CodeCtrl.BREAKPOINT_MARKER_NUM) + for linenum in self.GetBreakpointList(view.GetDocument().GetFilename()): + view.MarkerAdd(lineNum=int(linenum) - 1, marker_index=CodeEditor.CodeCtrl.BREAKPOINT_MARKER_NUM) + +class DebuggerOptionsPanel(wx.Panel): + + + def __init__(self, parent, id): + wx.Panel.__init__(self, parent, id) + SPACE = 10 + config = wx.ConfigBase_Get() + localHostStaticText = wx.StaticText(self, -1, _("Local Host Name:")) + self._LocalHostTextCtrl = wx.TextCtrl(self, -1, config.Read("DebuggerHostName", DEFAULT_HOST), size = (150, -1)) + portNumberStaticText = wx.StaticText(self, -1, _("Port Range:")) + dashStaticText = wx.StaticText(self, -1, _("through to")) + startingPort=config.ReadInt("DebuggerStartingPort", DEFAULT_PORT) + self._PortNumberTextCtrl = wx.lib.intctrl.IntCtrl(self, -1, startingPort, size = (50, -1)) + self._PortNumberTextCtrl.SetMin(1)#What are real values? + self._PortNumberTextCtrl.SetMax(65514) #What are real values? + self.Bind(wx.lib.intctrl.EVT_INT, self.MinPortChange, self._PortNumberTextCtrl) + + self._EndPortNumberTextCtrl = wx.lib.intctrl.IntCtrl(self, -1, startingPort + PORT_COUNT, size = (50, -1)) + self._EndPortNumberTextCtrl.SetMin(22)#What are real values? + self._EndPortNumberTextCtrl.SetMax(65535)#What are real values? + self._EndPortNumberTextCtrl.Enable( False ) + debuggerPanelBorderSizer = wx.BoxSizer(wx.VERTICAL) + debuggerPanelSizer = wx.GridBagSizer(hgap = 5, vgap = 5) + debuggerPanelSizer.Add( localHostStaticText, (0,0), flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT) + debuggerPanelSizer.Add( self._LocalHostTextCtrl, (0,1), (1,3), flag=wx.EXPAND|wx.ALIGN_CENTER) + debuggerPanelSizer.Add( portNumberStaticText, (1,0), flag=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL) + debuggerPanelSizer.Add( self._PortNumberTextCtrl, (1,1), flag=wx.ALIGN_CENTER) + debuggerPanelSizer.Add( dashStaticText, (1,2), flag=wx.ALIGN_CENTER) + debuggerPanelSizer.Add( self._EndPortNumberTextCtrl, (1,3), flag=wx.ALIGN_CENTER) + FLUSH_PORTS_ID = wx.NewId() + self._flushPortsButton = wx.Button(self, FLUSH_PORTS_ID, "Reset Port List") + wx.EVT_BUTTON(parent, FLUSH_PORTS_ID, self.FlushPorts) + debuggerPanelSizer.Add(self._flushPortsButton, (2,2), (1,2), flag=wx.ALIGN_RIGHT) + + debuggerPanelBorderSizer.Add(debuggerPanelSizer, 0, wx.ALL, SPACE) + self.SetSizer(debuggerPanelBorderSizer) + self.Layout() + parent.AddPage(self, _("Debugger")) + + def FlushPorts(self, event): + if self._PortNumberTextCtrl.IsInBounds(): + config = wx.ConfigBase_Get() + config.WriteInt("DebuggerStartingPort", self._PortNumberTextCtrl.GetValue()) + DebugCommandUI.NewPortRange() + else: + wx.MessageBox(_("The starting port is not valid. Please change the value and try again.", "Invalid Starting Port Number")) + + def MinPortChange(self, event): + self._EndPortNumberTextCtrl.Enable( True ) + self._EndPortNumberTextCtrl.SetValue( self._PortNumberTextCtrl.GetValue() + PORT_COUNT) + self._EndPortNumberTextCtrl.Enable( False ) + + def OnOK(self, optionsDialog): + config = wx.ConfigBase_Get() + config.Write("DebuggerHostName", self._LocalHostTextCtrl.GetValue()) + if self._PortNumberTextCtrl.IsInBounds(): + config.WriteInt("DebuggerStartingPort", self._PortNumberTextCtrl.GetValue()) + +class CommandPropertiesDialog(wx.Dialog): + + def __init__(self, parent, title, projectService, currentProjectDocument, pythonOnly=False, okButtonName="Run", debugging=False): + if _WINDOWS: + wx.Dialog.__init__(self, parent, -1, title) + else: + wx.Dialog.__init__(self, parent, -1, title, size=(390,270)) + self._projService = projectService + self._pmext = None + self._pyext = None + for template in self._projService.GetDocumentManager().GetTemplates(): + if not ACTIVEGRID_BASE_IDE and template.GetDocumentType() == ProcessModelEditor.ProcessModelDocument: + self._pmext = template.GetDefaultExtension() + if template.GetDocumentType() == PythonEditor.PythonDocument: + self._pyext = template.GetDefaultExtension() + self._pythonOnly = pythonOnly + + self._currentProj = currentProjectDocument + projStaticText = wx.StaticText(self, -1, _("Project:")) + fileStaticText = wx.StaticText(self, -1, _("File:")) + argsStaticText = wx.StaticText(self, -1, _("Arguments:")) + startInStaticText = wx.StaticText(self, -1, _("Start in:")) + pythonPathStaticText = wx.StaticText(self, -1, _("PYTHONPATH:")) + postpendStaticText = _("Postpend win32api path") + cpPanelBorderSizer = wx.BoxSizer(wx.VERTICAL) + self._projectNameList, self._projectDocumentList, selectedIndex = self.GetProjectList() + self._projList = wx.Choice(self, -1, (200,-1), choices=self._projectNameList) + self.Bind(wx.EVT_CHOICE, self.EvtListBox, self._projList) + HALF_SPACE = 5 + flexGridSizer = wx.FlexGridSizer(cols = 3, vgap = 10, hgap = 10) + + flexGridSizer.Add(projStaticText, 0, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT) + flexGridSizer.Add(self._projList, 1, flag=wx.EXPAND) + flexGridSizer.Add(wx.StaticText(parent, -1, ""), 0) + + flexGridSizer.Add(fileStaticText, 0, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT) + self._fileList = wx.Choice(self, -1, (200,-1)) + self.Bind(wx.EVT_CHOICE, self.OnFileSelected, self._fileList) + flexGridSizer.Add(self._fileList, 1, flag=wx.EXPAND) + flexGridSizer.Add(wx.StaticText(parent, -1, ""), 0) + + config = wx.ConfigBase_Get() + self._lastArguments = config.Read("LastRunArguments") + self._argsEntry = wx.TextCtrl(self, -1, str(self._lastArguments)) + self._argsEntry.SetToolTipString(str(self._lastArguments)) + def TextChanged(event): + self._argsEntry.SetToolTipString(event.GetString()) + self.Bind(wx.EVT_TEXT, TextChanged, self._argsEntry) + + flexGridSizer.Add(argsStaticText, 0, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT) + flexGridSizer.Add(self._argsEntry, 1, flag=wx.EXPAND) + flexGridSizer.Add(wx.StaticText(parent, -1, ""), 0) + + flexGridSizer.Add(startInStaticText, 0, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT) + self._lastStartIn = config.Read("LastRunStartIn") + if not self._lastStartIn: + self._lastStartIn = str(os.getcwd()) + self._startEntry = wx.TextCtrl(self, -1, self._lastStartIn) + self._startEntry.SetToolTipString(self._lastStartIn) + def TextChanged2(event): + self._startEntry.SetToolTipString(event.GetString()) + self.Bind(wx.EVT_TEXT, TextChanged2, self._startEntry) + + flexGridSizer.Add(self._startEntry, 1, wx.EXPAND) + self._findDir = wx.Button(self, -1, _("Browse..."), size=(60,-1)) + self.Bind(wx.EVT_BUTTON, self.OnFindDirClick, self._findDir) + flexGridSizer.Add(self._findDir, 0, wx.RIGHT, 10) + + flexGridSizer.Add(pythonPathStaticText, 0, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT) + if os.environ.has_key('PYTHONPATH'): + startval = os.environ['PYTHONPATH'] + else: + startval = "" + self._lastPythonPath = config.Read("LastPythonPath", startval) + self._pythonPathEntry = wx.TextCtrl(self, -1, self._lastPythonPath) + self._pythonPathEntry.SetToolTipString(self._lastPythonPath) + flexGridSizer.Add(self._pythonPathEntry, 1, wx.EXPAND) + flexGridSizer.Add(wx.StaticText(parent, -1, ""), 0) + flexGridSizer.Add(wx.StaticText(parent, -1, ""), 0) + if debugging: + self._postpendCheckBox = wx.CheckBox(self, -1, postpendStaticText) + checked = bool(config.ReadInt("PythonPathPostpend", 1)) + self._postpendCheckBox.SetValue(checked) + flexGridSizer.Add(self._postpendCheckBox, 1, wx.EXPAND) + flexGridSizer.Add(wx.StaticText(parent, -1, ""), 0) + cpPanelBorderSizer.Add(flexGridSizer, 0, wx.ALL, 10) + + box = wx.BoxSizer(wx.HORIZONTAL) + self._okButton = wx.Button(self, wx.ID_OK, okButtonName, size=(75,-1)) + self._okButton.SetDefault() + self._okButton.SetHelpText(_("The ") + okButtonName + _(" button completes the dialog")) + box.Add(self._okButton, 0, wx.ALIGN_RIGHT|wx.ALL, 5) + self.Bind(wx.EVT_BUTTON, self.OnOKClick, self._okButton) + btn = wx.Button(self, wx.ID_CANCEL, _("Cancel"), size=(75,-1)) + btn.SetHelpText(_("The Cancel button cancels the dialog.")) + box.Add(btn, 0, wx.ALIGN_RIGHT|wx.ALL, 5) + cpPanelBorderSizer.Add(box, 0, wx.ALIGN_RIGHT|wx.BOTTOM, 5) + + self.SetSizer(cpPanelBorderSizer) + if _WINDOWS: + self.GetSizer().Fit(self) + + self.Layout() + + # Set up selections based on last values used. + self._fileNameList = None + self._selectedFileIndex = 0 + lastProject = config.Read("LastRunProject") + lastFile = config.Read("LastRunFile") + + if lastProject in self._projectNameList: + selectedIndex = self._projectNameList.index(lastProject) + elif selectedIndex < 0: + selectedIndex = 0 + self._projList.Select(selectedIndex) + self._selectedProjectIndex = selectedIndex + self._selectedProjectDocument = self._projectDocumentList[selectedIndex] + self.PopulateFileList(self._selectedProjectDocument, lastFile) + + def OnOKClick(self, event): + startIn = self._startEntry.GetValue() + fileToRun = self._fileList.GetStringSelection() + if not fileToRun: + wx.MessageBox(_("You must select a file to proceed. Note that not all projects have files that can be run or debugged.")) + return + isPython = fileToRun.endswith(self._pyext) + if isPython and not os.path.exists(startIn): + wx.MessageBox(_("Starting directory does not exist. Please change this value.")) + return + config = wx.ConfigBase_Get() + config.Write("LastRunProject", self._projectNameList[self._selectedProjectIndex]) + config.Write("LastRunFile", fileToRun) + # Don't update the arguments or starting directory unless we're runing python. + if isPython: + config.Write("LastRunArguments", self._argsEntry.GetValue()) + config.Write("LastRunStartIn", self._startEntry.GetValue()) + config.Write("LastPythonPath",self._pythonPathEntry.GetValue()) + if hasattr(self, "_postpendCheckBox"): + config.WriteInt("PythonPathPostpend", int(self._postpendCheckBox.GetValue())) + + self.EndModal(wx.ID_OK) + + def GetSettings(self): + filename = self._fileNameList[self._selectedFileIndex] + args = self._argsEntry.GetValue() + startIn = self._startEntry.GetValue() + isPython = filename.endswith(self._pyext) + env = os.environ + if hasattr(self, "_postpendCheckBox"): + postpend = self._postpendCheckBox.GetValue() + else: + postpend = False + if postpend: + env['PYTHONPATH'] = self._pythonPathEntry.GetValue() + os.pathsep + os.path.join(os.getcwd(), "3rdparty", "pywin32") + else: + env['PYTHONPATH'] = self._pythonPathEntry.GetValue() + + return filename, args, startIn, isPython, env + + def OnFileSelected(self, event): + self._selectedFileIndex = self._fileList.GetSelection() + self.EnableForFileType(event.GetString()) + + def EnableForFileType(self, fileName): + show = fileName.endswith(self._pyext) + self._startEntry.Enable(show) + self._findDir.Enable(show) + self._argsEntry.Enable(show) + + if not show: + self._lastStartIn = self._startEntry.GetValue() + self._startEntry.SetValue("") + self._lastArguments = self._argsEntry.GetValue() + self._argsEntry.SetValue("") + else: + self._startEntry.SetValue(self._lastStartIn) + self._argsEntry.SetValue(self._lastArguments) + + + + def OnFindDirClick(self, event): + dlg = wx.DirDialog(self, "Choose a starting directory:", self._startEntry.GetValue(), + style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON) + + if dlg.ShowModal() == wx.ID_OK: + self._startEntry.SetValue(dlg.GetPath()) + + dlg.Destroy() + + def EvtListBox(self, event): + if event.GetString(): + index = self._projectNameList.index(event.GetString()) + self._selectedProjectDocument = self._projectDocumentList[index] + self._selectedProjectIndex = index + self.PopulateFileList(self._selectedProjectDocument) + + def FilterFileList(self, list): + if self._pythonOnly: + files = filter(lambda f: f.endswith(self._pyext), list) + else: + files = filter(lambda f: (self._pmext and f.endswith(self._pmext)) or f.endswith(self._pyext), list) + return files + + def PopulateFileList(self, project, shortNameToSelect=None): + self._fileNameList = self.FilterFileList(project.GetFiles()[:]) + self._fileList.Clear() + if not self._fileNameList: + return + self._fileNameList.sort(lambda a, b: cmp(os.path.basename(a).lower(), os.path.basename(b).lower())) + strings = map(lambda file: os.path.basename(file), self._fileNameList) + for index in range(0, len(strings)): + if shortNameToSelect == strings[index]: + self._selectedFileIndex = index + break + self._fileList.Hide() + self._fileList.AppendItems(strings) + self._fileList.Show() + if self._selectedFileIndex not in range(0, len(strings)) : self._selectedFileIndex = 0 + self._fileList.SetSelection(self._selectedFileIndex) + self.EnableForFileType(strings[self._selectedFileIndex]) + + def GetProjectList(self): + docList = [] + nameList = [] + found = False + index = -1 + count = 0 + for document in self._projService.GetDocumentManager().GetDocuments(): + if document.GetDocumentTemplate().GetDocumentType() == ProjectEditor.ProjectDocument and len(document.GetFiles()): + docList.append(document) + nameList.append(os.path.basename(document.GetFilename())) + if document == self._currentProj: + found = True + index = count + count += 1 + return nameList, docList, index +#---------------------------------------------------------------------- +from wx import ImageFromStream, BitmapFromImage +from wx import EmptyIcon +import cStringIO +#---------------------------------------------------------------------- +def getBreakData(): + return \ +'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x11\x08\x06\ +\x00\x00\x00\xd4\xaf,\xc4\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\ +\x00\x00\x97IDAT8\x8d\xbdSA\x0e\xc3 \x0c\x8b\x13\xfe=\x1e^\xe2\x1dF\xbb\x8c\ +\xd2\x0c\xa9\xda,q\x88\x05\x8e\x1d\x00P\x93;\xd0[\xa7W\x04\xe8\x8d\x0f\xdfxU\ +c%\x02\xbd\xbd\x05HQ+Xv\xb0\xa3VN\xf9\xd4\x01\xbd\x11j\x18\x1d\x00\x10\xa8AD\ +\xa4\xa4\xd6_\x9b\x19\xbb\x03\xd8c|\x8f\x00\xe0\x93\xa8g>\x15 C\xee:\xe7\x8f\ +\x08\xdesj\xcf\xe6\xde(\xddn\xec\x18f0w\xe0m;\x8d\x9b\xe4\xb1\xd4\n\xa6\x0e2\ +\xc4{\x1f\xeb\xdf?\xe5\xff\t\xa8\x1a$\x0cg\xac\xaf\xb0\xf4\x992<\x01\xec\xa0\ +U9V\xf9\x18\xc8\x00\x00\x00\x00IEND\xaeB`\x82' + +def getBreakBitmap(): + return BitmapFromImage(getBreakImage()) + +def getBreakImage(): + stream = cStringIO.StringIO(getBreakData()) + return ImageFromStream(stream) + +def getBreakIcon(): + icon = EmptyIcon() + icon.CopyFromBitmap(getBreakBitmap()) + return icon + +#---------------------------------------------------------------------- +def getClearOutputData(): + return \ +'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\ +\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\ +\x00\x00\xb4IDAT8\x8d\xa5\x92\xdd\r\x03!\x0c\x83\xbf\xa0n\xd4\x9d\xda5\xb81\ +\xbaS\xbb\x12\xee\x03?\xe5\x08\xe5N\xba\xbc Db\xec\xd8p\xb1l\xb8\xa7\x83\xfe\ +\xb0\x02H\x92F\xc0_\xa3\x99$\x99\x99\xedznc\xe36\x81\x88\x98"\xb2\x02\xa2\ +\x1e\xc4Q\x9aUD\x161\xcd\xde\x1c\x83\x15\x084)\x8d\xc5)\x06\xab\xaaZ\x92\xee\ +\xce\x11W\xdbGD\x0cIT\x06\xe7\x00\xdeY\xfe\xcc\x89\x06\xf0\xf2\x99\x00\xe0\ +\x91\x7f\xab\x83\xed\xa4\xc8\xafK\x0c\xcf\x92\x83\x99\x8d\xe3p\xef\xe4\xa1\ +\x0b\xe57j\xc8:\x06\t\x08\x87.H\xb2n\xa8\xc9\xa9\x12vQ\xfeG"\xe3\xacw\x00\ +\x10$M\xd3\x86_\xf0\xe5\xfc\xb4\xfa\x02\xcb\x13j\x10\xc5\xd7\x92D\x00\x00\ +\x00\x00IEND\xaeB`\x82' + +def getClearOutputBitmap(): + return BitmapFromImage(getClearOutputImage()) + +def getClearOutputImage(): + stream = cStringIO.StringIO(getClearOutputData()) + return ImageFromStream(stream) + +def getClearOutputIcon(): + icon = EmptyIcon() + icon.CopyFromBitmap(getClearOutputBitmap()) + return icon + +#---------------------------------------------------------------------- +def getCloseData(): + return \ +'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x12\x00\x00\x00\x12\x08\x06\ +\x00\x00\x00V\xce\x8eW\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\x00\ +\x00\x86IDAT8\x8d\xed\x90\xb1\r\x80 \x10E_"c\xd80\x02-\x138\x87;8\x8f\x8d\ +\x8b\xb0\x02\xa5\xad\rS\x88\xcd\x11) \x82\xb6\xbe\xea\xf2\xc9\xbd\xfc\x03~\ +\xdeb\x81\xb9\x90\xabJ^%\x00N\x849\x0e\xf0\x85\xbc\x8a\x12YZR2\xc7\x1eIB\xcb\ +\xb2\xcb\x9at\x9d\x95c\xa5Y|\x92\x0c\x0f\xa2\r8e\x1e\x81\x1d8z\xdb8\xee?Ig\ +\xfa\xb7\x92)\xcb\xacd\x01XZ$QD\xba\xf0\xa6\x80\xd5\x18cZ\x1b\x95$?\x1f\xb9\ +\x00\x1d\x94\x1e*e_\x8a~\x00\x00\x00\x00IEND\xaeB`\x82' + +def getCloseBitmap(): + return BitmapFromImage(getCloseImage()) + +def getCloseImage(): + stream = cStringIO.StringIO(getCloseData()) + return ImageFromStream(stream) + +def getCloseIcon(): + icon = EmptyIcon() + icon.CopyFromBitmap(getCloseBitmap()) + return icon + +#---------------------------------------------------------------------- +def getContinueData(): + return \ +'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\ +\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\ +\x00\x00\x9eIDAT8\x8d\xbd\x92\xd1\r\x83@\x0cC\xed\x8a\x11X\xac\x1b\xddF,\xd6\ +\x11\x90\xdc\x0f\x9a\x93s)\x14Z\xa9\x91\x10\n\x97\xbc\xd89\x80?\x84\x1a\xa4\ +\x83\xfc\x1c$\x1e)7\xdf\x8a \xec5\x94\tc\xc4\x12\xab\x94\xeb\x7fkWr\xc9B%\ +\xfc\xd2\xfcM<\x01\xf6tn\x12O3c\xe6\x00\x00\x00\x00IEND\xaeB`\x82' + +def getContinueBitmap(): + return BitmapFromImage(getContinueImage()) + +def getContinueImage(): + stream = cStringIO.StringIO(getContinueData()) + return ImageFromStream(stream) + +def getContinueIcon(): + icon = EmptyIcon() + icon.CopyFromBitmap(getContinueBitmap()) + return icon + +#---------------------------------------------------------------------- +def getNextData(): + return \ +'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\ +\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\ +\x00\x00\x8eIDAT8\x8d\xa5SA\x12\xc4 \x08K\xb0\xff\xde\xe9\xbf\xb7\xa6\x87\ +\x1d:\xba\xa2tZn(\x84`"i\x05obk\x13\xd5CmN+\xcc\x00l\xd6\x0c\x00\xf5\xf8\x0e\ +gK\x06\x00 \xa5=k\x00\x00\xb0\xb2]\xd4?5f\xb1\xdb\xaf\xc6\xa2\xcb\xa8\xf0?\ +\x1c\x98\xae\x82\xbf\x81\xa4\x8eA\x16\xe1\n\xd1\xa4\x19\xb3\xe9\n\xce\xe8\ +\xf1\n\x9eg^\x18\x18\x90\xec<\x11\xf9#\x04XMZ\x19\xaac@+\x94\xd4\x99)SeP\xa1\ +)\xd6\x1dI\xe7*\xdc\xf4\x03\xdf~\xe7\x13T^Q?:X\x19d\x00\x00\x00\x00IEND\xaeB\ +`\x82' + +def getNextBitmap(): + return BitmapFromImage(getNextImage()) + +def getNextImage(): + stream = cStringIO.StringIO(getNextData()) + return ImageFromStream(stream) + +def getNextIcon(): + icon = EmptyIcon() + icon.CopyFromBitmap(getNextBitmap()) + return icon + +#---------------------------------------------------------------------- +def getStepInData(): + return \ +'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\ +\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\ +\x00\x00\x87IDAT8\x8d\xadSA\x12\x84 \x0ck\x8a\xffv\xfc\xb74{X\xeb0P@\x07s\ +\x84\xa4$\x01\x00M\xb2\x02]R\x8b\xc86\xda\xdc\xedd\xb4~\xe8\x86\xc6\x01-\x93\ +\x96\xd9#\xf6\x06\xc3;p1I\xd1\x14\x0b#|\x17aF\xec\r\xeeF\xa0eB\xd34\xca\xd0A\ +]j\x84\xa6\x03\x00""\xb7\xb0tRZ\xf7x\xb7\x83\x91]\xcb\x7fa\xd9\x89\x0fC\xfd\ +\x94\x9d|9\x99^k\x13\xa1 \xb3\x16\x0f#\xd4\x88N~\x14\xe1-\x96\x7f\xe3\x0f\ +\x11\x91UC\x0cX\'\x1e\x00\x00\x00\x00IEND\xaeB`\x82' + +def getStepInBitmap(): + return BitmapFromImage(getStepInImage()) + +def getStepInImage(): + stream = cStringIO.StringIO(getStepInData()) + return ImageFromStream(stream) + +def getStepInIcon(): + icon = EmptyIcon() + icon.CopyFromBitmap(getStepInBitmap()) + return icon + +#---------------------------------------------------------------------- +def getStopData(): + return \ +"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\ +\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\ +\x00\x00FIDAT8\x8d\xed\x91\xc1\t\xc00\x0c\x03O!\x0b\xa9\xfb\xef\xa6\xfcB\xa1\ +N\t\xf4Wr\xa0\x8f\xb1\x0f\x81\xe1\x97\xe4-\xb6}_V%\xc8\xc2, \t\x92\xe6]\xfbZ\ +\xf7\x08\xa0W\xc3\xea5\xdb\rl_IX\xe5\xf0d\x00\xfa\x8d#\x7f\xc4\xf7'\xab\x00\ +\x00\x00\x00IEND\xaeB`\x82" + +def getStopBitmap(): + return BitmapFromImage(getStopImage()) + +def getStopImage(): + stream = cStringIO.StringIO(getStopData()) + return ImageFromStream(stream) + +def getStopIcon(): + icon = EmptyIcon() + icon.CopyFromBitmap(getStopBitmap()) + return icon + +#---------------------------------------------------------------------- +def getStepReturnData(): + return \ +"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\ +\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\ +\x00\x00\x8dIDAT8\x8d\xa5S\xd1\x0e\xc4 \x08\xa3\xb0\xff\xbe\xdc\x7fO\xba'6\ +\xf1\xf44\xb3O$Phk\x04\xd4d\x07\xba\xc5\x16\x91#\nza\xdb\x84\x1a\xa2\xfe\xf8\ +\x99\xfa_=p+\xe8\x91ED\xbc<\xa4 \xb4\x0b\x01\xb5{\x01\xf9\xbbG-\x13\x87\x16f\ +\x84\xbf\x16V\xb0l\x01@\no\x86\xae\x82Q\xa8=\xa4\x0c\x80\xe70\xbd\x10jh\xbd\ +\x07R\x06#\xc9^N\xb6\xde\x03)\x83\x18\xaeU\x90\x9c>a\xb2P\r\xb3&/Y\xa8\xd1^^\ +\xb6\xf0\x16\xdb\xbf\xf1\x02\x81\xa5TK\x1d\x07\xde\x92\x00\x00\x00\x00IEND\ +\xaeB`\x82" + +def getStepReturnBitmap(): + return BitmapFromImage(getStepReturnImage()) + +def getStepReturnImage(): + stream = cStringIO.StringIO(getStepReturnData()) + return ImageFromStream(stream) + +def getStepReturnIcon(): + icon = EmptyIcon() + icon.CopyFromBitmap(getStepReturnBitmap()) + return icon + +def getAddWatchData(): + return \ +'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\ +\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\ +\x00\x00\x85IDAT8\x8dc`\x18h\xc0\x88.\xd0\xc0\xf0\xff?*\x9f\x11C\rN\x80\xae\ +\x19\x97\x18\xd1\x9a\x896\x84\x18[p\xa9aA\xe6\xfc7f\xc0P\xc4x\x163\x9cp\x1a0\ +\xeb,!w\x100 \x1dK\xac\x10\r\x08\x05".yFL\x85\x8c\x18b\xa8|Ty\xa2\x13\x92\'\ +\xc3\xe4\xff\x9f\x18\x1e3\xb82t\xa2\x88\x13\xedg.\x06aa&\x06VV\x7f\x86\xb9\ +\xcfU\x19\xbc\xb0\xba\x86h\xe0\xc8\xd0\xfc\xbf\x80\xe1>q)\x94\xe6\x00\x00\ +\x85\x923_\xd22\xa4\xcd\x00\x00\x00\x00IEND\xaeB`\x82' + +def getAddWatchBitmap(): + return BitmapFromImage(getAddWatchImage()) + +def getAddWatchImage(): + stream = cStringIO.StringIO(getAddWatchData()) + return ImageFromStream(stream) + +def getAddWatchIcon(): + icon = EmptyIcon() + icon.CopyFromBitmap(getAddWatchBitmap()) + return icon diff --git a/wxPython/samples/ide/activegrid/tool/FindInDirService.py b/wxPython/samples/ide/activegrid/tool/FindInDirService.py new file mode 100644 index 0000000000..f3e9da16c2 --- /dev/null +++ b/wxPython/samples/ide/activegrid/tool/FindInDirService.py @@ -0,0 +1,446 @@ +#---------------------------------------------------------------------------- +# Name: IDEFindService.py +# Purpose: Find Service for pydocview +# +# Author: Morgan Hua +# +# Created: 8/15/03 +# CVS-ID: $Id$ +# Copyright: (c) 2004-2005 ActiveGrid, Inc. +# License: wxWindows License +#---------------------------------------------------------------------------- + +import wx +import wx.lib.docview +import os +from os.path import join +import re +import ProjectEditor +import MessageService +import FindService +import OutlineService +_ = wx.GetTranslation + + +#---------------------------------------------------------------------------- +# Constants +#---------------------------------------------------------------------------- +FILENAME_MARKER = _("Found in file: ") +PROJECT_MARKER = _("Searching project: ") +FIND_MATCHDIR = "FindMatchDir" +FIND_MATCHDIRSUBFOLDERS = "FindMatchDirSubfolders" + +SPACE = 10 +HALF_SPACE = 5 + + +class FindInDirService(FindService.FindService): + + #---------------------------------------------------------------------------- + # Constants + #---------------------------------------------------------------------------- + FINDALL_ID = wx.NewId() # for bringing up Find All dialog box + FINDDIR_ID = wx.NewId() # for bringing up Find Dir dialog box + + + def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None): + FindService.FindService.InstallControls(self, frame, menuBar, toolBar, statusBar, document) + + editMenu = menuBar.GetMenu(menuBar.FindMenu(_("&Edit"))) + wx.EVT_MENU(frame, FindInDirService.FINDALL_ID, self.ProcessEvent) + wx.EVT_UPDATE_UI(frame, FindInDirService.FINDALL_ID, self.ProcessUpdateUIEvent) + editMenu.Append(FindInDirService.FINDALL_ID, _("Find in Project...\tCtrl+Shift+F"), _("Searches for the specified text in all the files in the project")) + wx.EVT_MENU(frame, FindInDirService.FINDDIR_ID, self.ProcessEvent) + wx.EVT_UPDATE_UI(frame, FindInDirService.FINDDIR_ID, self.ProcessUpdateUIEvent) + editMenu.Append(FindInDirService.FINDDIR_ID, _("Find in Directory..."), _("Searches for the specified text in all the files in the directory")) + + + def ProcessEvent(self, event): + id = event.GetId() + if id == FindInDirService.FINDALL_ID: + self.ShowFindAllDialog() + return True + elif id == FindInDirService.FINDDIR_ID: + self.ShowFindDirDialog() + return True + else: + return FindService.FindService.ProcessEvent(self, event) + + + def ProcessUpdateUIEvent(self, event): + id = event.GetId() + if id == FindInDirService.FINDALL_ID: + projectService = wx.GetApp().GetService(ProjectEditor.ProjectService) + view = projectService.GetView() + if view and view.GetDocument() and view.GetDocument().GetFiles(): + event.Enable(True) + else: + event.Enable(False) + return True + elif id == FindInDirService.FINDDIR_ID: + event.Enable(True) + else: + return FindService.FindService.ProcessUpdateUIEvent(self, event) + + + def ShowFindDirDialog(self): + config = wx.ConfigBase_Get() + + frame = wx.Dialog(None, -1, _("Find in Directory"), size= (320,200)) + borderSizer = wx.BoxSizer(wx.HORIZONTAL) + + contentSizer = wx.BoxSizer(wx.VERTICAL) + lineSizer = wx.BoxSizer(wx.HORIZONTAL) + lineSizer.Add(wx.StaticText(frame, -1, _("Directory:")), 0, wx.ALIGN_CENTER | wx.RIGHT, HALF_SPACE) + dirCtrl = wx.TextCtrl(frame, -1, config.Read(FIND_MATCHDIR, ""), size=(200,-1)) + dirCtrl.SetToolTipString(dirCtrl.GetValue()) + lineSizer.Add(dirCtrl, 0, wx.LEFT, HALF_SPACE) + findDirButton = wx.Button(frame, -1, "Browse...") + lineSizer.Add(findDirButton, 0, wx.LEFT, HALF_SPACE) + contentSizer.Add(lineSizer, 0, wx.BOTTOM, SPACE) + + def OnBrowseButton(event): + dlg = wx.DirDialog(frame, _("Choose a directory:"), style=wx.DD_DEFAULT_STYLE) + dir = dirCtrl.GetValue() + if len(dir): + dlg.SetPath(dir) + if dlg.ShowModal() == wx.ID_OK: + dirCtrl.SetValue(dlg.GetPath()) + dirCtrl.SetToolTipString(dirCtrl.GetValue()) + dirCtrl.SetInsertionPointEnd() + + dlg.Destroy() + wx.EVT_BUTTON(findDirButton, -1, OnBrowseButton) + + subfolderCtrl = wx.CheckBox(frame, -1, _("Search in subfolders")) + subfolderCtrl.SetValue(config.ReadInt(FIND_MATCHDIRSUBFOLDERS, True)) + contentSizer.Add(subfolderCtrl, 0, wx.BOTTOM, SPACE) + + lineSizer = wx.BoxSizer(wx.VERTICAL) # let the line expand horizontally without vertical expansion + lineSizer.Add(wx.StaticLine(frame, -1, size = (10,-1)), 0, flag=wx.EXPAND) + contentSizer.Add(lineSizer, flag=wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.BOTTOM, border=HALF_SPACE) + + lineSizer = wx.BoxSizer(wx.HORIZONTAL) + lineSizer.Add(wx.StaticText(frame, -1, _("Find what:")), 0, wx.ALIGN_CENTER | wx.RIGHT, HALF_SPACE) + findCtrl = wx.TextCtrl(frame, -1, config.Read(FindService.FIND_MATCHPATTERN, ""), size=(200,-1)) + lineSizer.Add(findCtrl, 0, wx.LEFT, HALF_SPACE) + contentSizer.Add(lineSizer, 0, wx.BOTTOM, SPACE) + wholeWordCtrl = wx.CheckBox(frame, -1, _("Match whole word only")) + wholeWordCtrl.SetValue(config.ReadInt(FindService.FIND_MATCHWHOLEWORD, False)) + matchCaseCtrl = wx.CheckBox(frame, -1, _("Match case")) + matchCaseCtrl.SetValue(config.ReadInt(FindService.FIND_MATCHCASE, False)) + regExprCtrl = wx.CheckBox(frame, -1, _("Regular expression")) + regExprCtrl.SetValue(config.ReadInt(FindService.FIND_MATCHREGEXPR, False)) + contentSizer.Add(wholeWordCtrl, 0, wx.BOTTOM, SPACE) + contentSizer.Add(matchCaseCtrl, 0, wx.BOTTOM, SPACE) + contentSizer.Add(regExprCtrl, 0, wx.BOTTOM, SPACE) + borderSizer.Add(contentSizer, 0, wx.TOP | wx.BOTTOM | wx.LEFT, SPACE) + + buttonSizer = wx.BoxSizer(wx.VERTICAL) + findBtn = wx.Button(frame, wx.ID_OK, _("Find")) + findBtn.SetDefault() + buttonSizer.Add(findBtn, 0, wx.BOTTOM, HALF_SPACE) + buttonSizer.Add(wx.Button(frame, wx.ID_CANCEL, _("Cancel")), 0) + borderSizer.Add(buttonSizer, 0, wx.ALL, SPACE) + + frame.SetSizer(borderSizer) + frame.Fit() + + status = frame.ShowModal() + + passedCheck = False + while status == wx.ID_OK and not passedCheck: + if not os.path.exists(dirCtrl.GetValue()): + dlg = wx.MessageDialog(frame, + _("'%s' does not exist.") % dirCtrl.GetValue(), + _("Find in Directory"), + wx.OK | wx.ICON_EXCLAMATION + ) + dlg.ShowModal() + dlg.Destroy() + + status = frame.ShowModal() + elif len(findCtrl.GetValue()) == 0: + dlg = wx.MessageDialog(frame, + _("'Find what:' cannot be empty."), + _("Find in Directory"), + wx.OK | wx.ICON_EXCLAMATION + ) + dlg.ShowModal() + dlg.Destroy() + + status = frame.ShowModal() + else: + passedCheck = True + + + # save user choice state for this and other Find Dialog Boxes + dirString = dirCtrl.GetValue() + searchSubfolders = subfolderCtrl.IsChecked() + self.SaveFindDirConfig(dirString, searchSubfolders) + + findString = findCtrl.GetValue() + matchCase = matchCaseCtrl.IsChecked() + wholeWord = wholeWordCtrl.IsChecked() + regExpr = regExprCtrl.IsChecked() + self.SaveFindConfig(findString, wholeWord, matchCase, regExpr) + + + if status == wx.ID_OK: + frame.Destroy() + + messageService = wx.GetApp().GetService(MessageService.MessageService) + messageService.ShowWindow() + + view = messageService.GetView() + if view: + wx.GetApp().GetTopWindow().SetCursor(wx.StockCursor(wx.CURSOR_WAIT)) + view.ClearLines() + view.SetCallback(self.OnJumpToFoundLine) + + view.AddLines(_("Searching for '%s' in '%s'\n\n") % (findString, dirString)) + + if os.path.isfile(dirString): + try: + docFile = file(dirString, 'r') + lineNum = 1 + needToDisplayFilename = True + line = docFile.readline() + while line: + count, foundStart, foundEnd, newText = self.DoFind(findString, None, line, 0, 0, True, matchCase, wholeWord, regExpr) + if count != -1: + if needToDisplayFilename: + view.AddLines(FILENAME_MARKER + dirString + "\n") + needToDisplayFilename = False + line = repr(lineNum).zfill(4) + ":" + line + view.AddLines(line) + line = docFile.readline() + lineNum += 1 + if not needToDisplayFilename: + view.AddLines("\n") + except IOError, (code, message): + print _("Warning, unable to read file: '%s'. %s") % (dirString, message) + else: + # do search in files on disk + for root, dirs, files in os.walk(dirString): + if not searchSubfolders and root != dirString: + break + + for name in files: + filename = os.path.join(root, name) + try: + docFile = file(filename, 'r') + except IOError, (code, message): + print _("Warning, unable to read file: '%s'. %s") % (filename, message) + continue + + lineNum = 1 + needToDisplayFilename = True + line = docFile.readline() + while line: + count, foundStart, foundEnd, newText = self.DoFind(findString, None, line, 0, 0, True, matchCase, wholeWord, regExpr) + if count != -1: + if needToDisplayFilename: + view.AddLines(FILENAME_MARKER + filename + "\n") + needToDisplayFilename = False + line = repr(lineNum).zfill(4) + ":" + line + view.AddLines(line) + line = docFile.readline() + lineNum += 1 + if not needToDisplayFilename: + view.AddLines("\n") + + view.AddLines(_("Search completed.")) + wx.GetApp().GetTopWindow().SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT)) + + return True + else: + frame.Destroy() + return False + + + def SaveFindDirConfig(self, dirString, searchSubfolders): + """ Save search dir patterns and flags to registry. + + dirString = search directory + searchSubfolders = Search subfolders + """ + config = wx.ConfigBase_Get() + config.Write(FIND_MATCHDIR, dirString) + config.WriteInt(FIND_MATCHDIRSUBFOLDERS, searchSubfolders) + + + def ShowFindAllDialog(self): + config = wx.ConfigBase_Get() + + frame = wx.Dialog(None, -1, _("Find in Project"), size= (320,200)) + borderSizer = wx.BoxSizer(wx.HORIZONTAL) + + contentSizer = wx.BoxSizer(wx.VERTICAL) + lineSizer = wx.BoxSizer(wx.HORIZONTAL) + lineSizer.Add(wx.StaticText(frame, -1, _("Find what:")), 0, wx.ALIGN_CENTER | wx.RIGHT, HALF_SPACE) + findCtrl = wx.TextCtrl(frame, -1, config.Read(FindService.FIND_MATCHPATTERN, ""), size=(200,-1)) + lineSizer.Add(findCtrl, 0, wx.LEFT, HALF_SPACE) + contentSizer.Add(lineSizer, 0, wx.BOTTOM, SPACE) + wholeWordCtrl = wx.CheckBox(frame, -1, _("Match whole word only")) + wholeWordCtrl.SetValue(config.ReadInt(FindService.FIND_MATCHWHOLEWORD, False)) + matchCaseCtrl = wx.CheckBox(frame, -1, _("Match case")) + matchCaseCtrl.SetValue(config.ReadInt(FindService.FIND_MATCHCASE, False)) + regExprCtrl = wx.CheckBox(frame, -1, _("Regular expression")) + regExprCtrl.SetValue(config.ReadInt(FindService.FIND_MATCHREGEXPR, False)) + contentSizer.Add(wholeWordCtrl, 0, wx.BOTTOM, SPACE) + contentSizer.Add(matchCaseCtrl, 0, wx.BOTTOM, SPACE) + contentSizer.Add(regExprCtrl, 0, wx.BOTTOM, SPACE) + borderSizer.Add(contentSizer, 0, wx.TOP | wx.BOTTOM | wx.LEFT, SPACE) + + buttonSizer = wx.BoxSizer(wx.VERTICAL) + findBtn = wx.Button(frame, wx.ID_OK, _("Find")) + findBtn.SetDefault() + buttonSizer.Add(findBtn, 0, wx.BOTTOM, HALF_SPACE) + buttonSizer.Add(wx.Button(frame, wx.ID_CANCEL, _("Cancel")), 0) + borderSizer.Add(buttonSizer, 0, wx.ALL, SPACE) + + frame.SetSizer(borderSizer) + frame.Fit() + + status = frame.ShowModal() + + # save user choice state for this and other Find Dialog Boxes + findString = findCtrl.GetValue() + matchCase = matchCaseCtrl.IsChecked() + wholeWord = wholeWordCtrl.IsChecked() + regExpr = regExprCtrl.IsChecked() + self.SaveFindConfig(findString, wholeWord, matchCase, regExpr) + + if status == wx.ID_OK: + frame.Destroy() + + messageService = wx.GetApp().GetService(MessageService.MessageService) + messageService.ShowWindow() + + view = messageService.GetView() + if view: + view.ClearLines() + view.SetCallback(self.OnJumpToFoundLine) + + projectService = wx.GetApp().GetService(ProjectEditor.ProjectService) + projectFilenames = projectService.GetFilesFromCurrentProject() + + projView = projectService.GetView() + if projView: + projName = wx.lib.docview.FileNameFromPath(projView.GetDocument().GetFilename()) + view.AddLines(PROJECT_MARKER + projName + "\n\n") + + # do search in open files first, open files may have been modified and different from disk because it hasn't been saved + openDocs = wx.GetApp().GetDocumentManager().GetDocuments() + openDocsInProject = filter(lambda openDoc: openDoc.GetFilename() in projectFilenames, openDocs) + for openDoc in openDocsInProject: + if isinstance(openDoc, ProjectEditor.ProjectDocument): # don't search project model + continue + + openDocView = openDoc.GetFirstView() + # some views don't have a in memory text object to search through such as the PM and the DM + # even if they do have a non-text searchable object, how do we display it in the message window? + if not hasattr(openDocView, "GetValue"): + continue + text = openDocView.GetValue() + + lineNum = 1 + needToDisplayFilename = True + start = 0 + end = 0 + count = 0 + while count != -1: + count, foundStart, foundEnd, newText = self.DoFind(findString, None, text, start, end, True, matchCase, wholeWord, regExpr) + if count != -1: + if needToDisplayFilename: + view.AddLines(FILENAME_MARKER + openDoc.GetFilename() + "\n") + needToDisplayFilename = False + + lineNum = openDocView.LineFromPosition(foundStart) + line = repr(lineNum).zfill(4) + ":" + openDocView.GetLine(lineNum) + view.AddLines(line) + + start = text.find("\n", foundStart) + if start == -1: + break + end = start + if not needToDisplayFilename: + view.AddLines("\n") + openDocNames = map(lambda openDoc: openDoc.GetFilename(), openDocs) + + # do search in closed files, skipping the open ones we already searched + filenames = filter(lambda filename: filename not in openDocNames, projectFilenames) + for filename in filenames: + try: + docFile = file(filename, 'r') + except IOError, (code, message): + print _("Warning, unable to read file: '%s'. %s") % (filename, message) + continue + + lineNum = 1 + needToDisplayFilename = True + line = docFile.readline() + while line: + count, foundStart, foundEnd, newText = self.DoFind(findString, None, line, 0, 0, True, matchCase, wholeWord, regExpr) + if count != -1: + if needToDisplayFilename: + view.AddLines(FILENAME_MARKER + filename + "\n") + needToDisplayFilename = False + line = repr(lineNum).zfill(4) + ":" + line + view.AddLines(line) + line = docFile.readline() + lineNum += 1 + if not needToDisplayFilename: + view.AddLines("\n") + + view.AddLines(_("Search for '%s' completed.") % findString) + + return True + else: + frame.Destroy() + return False + + + def OnJumpToFoundLine(self, event): + messageService = wx.GetApp().GetService(MessageService.MessageService) + lineText, pos = messageService.GetView().GetCurrLine() + if lineText == "\n" or lineText.find(FILENAME_MARKER) != -1 or lineText.find(PROJECT_MARKER) != -1: + return + lineEnd = lineText.find(":") + if lineEnd == -1: + return + else: + lineNum = int(lineText[0:lineEnd]) + + text = messageService.GetView().GetText() + curPos = messageService.GetView().GetCurrentPos() + + startPos = text.rfind(FILENAME_MARKER, 0, curPos) + endPos = text.find("\n", startPos) + filename = text[startPos + len(FILENAME_MARKER):endPos] + + foundView = None + openDocs = wx.GetApp().GetDocumentManager().GetDocuments() + for openDoc in openDocs: + if openDoc.GetFilename() == filename: + foundView = openDoc.GetFirstView() + break + + if not foundView: + doc = wx.GetApp().GetDocumentManager().CreateDocument(filename, wx.lib.docview.DOC_SILENT) + foundView = doc.GetFirstView() + + if foundView: + foundView.GetFrame().SetFocus() + foundView.Activate() + if hasattr(foundView, "GotoLine"): + foundView.GotoLine(lineNum) + startPos = foundView.PositionFromLine(lineNum) + # wxBug: Need to select in reverse order, (end, start) to put cursor at head of line so positioning is correct + # Also, if we use the correct positioning order (start, end), somehow, when we open a edit window for the first + # time, we don't see the selection, it is scrolled off screen + foundView.SetSelection(startPos - 1 + len(lineText[lineEnd:].rstrip("\n")), startPos) + wx.GetApp().GetService(OutlineService.OutlineService).LoadOutline(foundView, position=startPos) + + diff --git a/wxPython/samples/ide/activegrid/tool/FindService.py b/wxPython/samples/ide/activegrid/tool/FindService.py new file mode 100644 index 0000000000..da5235b5d9 --- /dev/null +++ b/wxPython/samples/ide/activegrid/tool/FindService.py @@ -0,0 +1,521 @@ +#---------------------------------------------------------------------------- +# Name: FindService.py +# Purpose: Find Service for pydocview +# +# Author: Peter Yared, Morgan Hua +# +# Created: 8/15/03 +# CVS-ID: $Id$ +# Copyright: (c) 2003-2005 ActiveGrid, Inc. +# License: wxWindows License +#---------------------------------------------------------------------------- + +import wx +import wx.lib.docview +import wx.lib.pydocview +import re +_ = wx.GetTranslation + + +#---------------------------------------------------------------------------- +# Constants +#---------------------------------------------------------------------------- +FIND_MATCHPATTERN = "FindMatchPattern" +FIND_MATCHREPLACE = "FindMatchReplace" +FIND_MATCHCASE = "FindMatchCase" +FIND_MATCHWHOLEWORD = "FindMatchWholeWordOnly" +FIND_MATCHREGEXPR = "FindMatchRegularExpr" +FIND_MATCHWRAP = "FindMatchWrap" +FIND_MATCHUPDOWN = "FindMatchUpDown" + +FIND_SYNTAXERROR = -2 + +SPACE = 10 +HALF_SPACE = 5 + + +#---------------------------------------------------------------------------- +# Classes +#---------------------------------------------------------------------------- + +class FindService(wx.lib.pydocview.DocService): + + #---------------------------------------------------------------------------- + # Constants + #---------------------------------------------------------------------------- + FIND_ID = wx.NewId() # for bringing up Find dialog box + FINDONE_ID = wx.NewId() # for doing Find + FIND_PREVIOUS_ID = wx.NewId() # for doing Find Next + FIND_NEXT_ID = wx.NewId() # for doing Find Prev + REPLACE_ID = wx.NewId() # for bringing up Replace dialog box + REPLACEONE_ID = wx.NewId() # for doing a Replace + REPLACEALL_ID = wx.NewId() # for doing Replace All + GOTO_LINE_ID = wx.NewId() # for bringing up Goto dialog box + + # Extending bitmasks: wx.FR_WHOLEWORD, wx.FR_MATCHCASE, and wx.FR_DOWN + FR_REGEXP = max([wx.FR_WHOLEWORD, wx.FR_MATCHCASE, wx.FR_DOWN]) << 1 + FR_WRAP = FR_REGEXP << 1 + + + def __init__(self): + self._replaceDialog = None + self._findDialog = None + self._findReplaceData = wx.FindReplaceData() + self._findReplaceData.SetFlags(wx.FR_DOWN) + + + def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None): + """ Install Find Service Menu Items """ + editMenu = menuBar.GetMenu(menuBar.FindMenu(_("&Edit"))) + editMenu.AppendSeparator() + editMenu.Append(FindService.FIND_ID, _("&Find...\tCtrl+F"), _("Finds the specified text")) + wx.EVT_MENU(frame, FindService.FIND_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, FindService.FIND_ID, frame.ProcessUpdateUIEvent) + editMenu.Append(FindService.FIND_PREVIOUS_ID, _("Find &Previous\tShift+F3"), _("Finds the specified text")) + wx.EVT_MENU(frame, FindService.FIND_PREVIOUS_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, FindService.FIND_PREVIOUS_ID, frame.ProcessUpdateUIEvent) + editMenu.Append(FindService.FIND_NEXT_ID, _("Find &Next\tF3"), _("Finds the specified text")) + wx.EVT_MENU(frame, FindService.FIND_NEXT_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, FindService.FIND_NEXT_ID, frame.ProcessUpdateUIEvent) + editMenu.Append(FindService.REPLACE_ID, _("R&eplace...\tCtrl+H"), _("Replaces specific text with different text")) + wx.EVT_MENU(frame, FindService.REPLACE_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, FindService.REPLACE_ID, frame.ProcessUpdateUIEvent) + editMenu.Append(FindService.GOTO_LINE_ID, _("&Go to Line...\tCtrl+G"), _("Goes to a certain line in the file")) + wx.EVT_MENU(frame, FindService.GOTO_LINE_ID, frame.ProcessEvent) + wx.EVT_UPDATE_UI(frame, FindService.GOTO_LINE_ID, frame.ProcessUpdateUIEvent) + + # wxBug: wxToolBar::GetToolPos doesn't exist, need it to find cut tool and then insert find in front of it. + toolBar.InsertTool(6, FindService.FIND_ID, getFindBitmap(), shortHelpString = _("Find"), longHelpString = _("Finds the specified text")) + toolBar.InsertSeparator(6) + toolBar.Realize() + + frame.Bind(wx.EVT_FIND, frame.ProcessEvent) + frame.Bind(wx.EVT_FIND_NEXT, frame.ProcessEvent) + frame.Bind(wx.EVT_FIND_REPLACE, frame.ProcessEvent) + frame.Bind(wx.EVT_FIND_REPLACE_ALL, frame.ProcessEvent) + + + def ProcessUpdateUIEvent(self, event): + id = event.GetId() + if id == FindService.FIND_ID: + event.Enable(False) + return True + elif id == FindService.FIND_PREVIOUS_ID: + event.Enable(False) + return True + elif id == FindService.FIND_NEXT_ID: + event.Enable(False) + return True + elif id == FindService.REPLACE_ID: + event.Enable(False) + return True + elif id == FindService.GOTO_LINE_ID: + event.Enable(False) + return True + else: + return False + + + def ShowFindReplaceDialog(self, findString="", replace = False): + """ Display find/replace dialog box. + + Parameters: findString is the default value shown in the find/replace dialog input field. + If replace is True, the replace dialog box is shown, otherwise only the find dialog box is shown. + """ + if replace: + if self._findDialog != None: + # No reason to have both find and replace dialogs up at the same time + self._findDialog.DoClose() + self._findDialog = None + + self._replaceDialog = FindReplaceDialog(self.GetDocumentManager().FindSuitableParent(), -1, _("Replace"), size=(320,200), findString=findString) + self._replaceDialog.Show(True) + else: + if self._replaceDialog != None: + # No reason to have both find and replace dialogs up at the same time + self._replaceDialog.DoClose() + self._replaceDialog = None + + self._findDialog = FindDialog(self.GetDocumentManager().FindSuitableParent(), -1, _("Find"), size=(320,200), findString=findString) + self._findDialog.Show(True) + + + + def OnFindClose(self, event): + """ Cleanup handles when find/replace dialog is closed """ + if self._findDialog != None: + self._findDialog = None + elif self._replaceDialog != None: + self._replaceDialog = None + + + def GetCurrentDialog(self): + """ return handle to either the find or replace dialog """ + if self._findDialog != None: + return self._findDialog + return self._replaceDialog + + + def GetLineNumber(self, parent): + """ Display Goto Line Number dialog box """ + line = -1 + dialog = wx.TextEntryDialog(parent, _("Enter line number to go to:"), _("Go to Line")) + if dialog.ShowModal() == wx.ID_OK: + try: + line = int(dialog.GetValue()) + if line > 65535: + line = 65535 + except: + pass + dialog.Destroy() + # This one is ugly: wx.GetNumberFromUser("", _("Enter line number to go to:"), _("Go to Line"), 1, min = 1, max = 65535, parent = parent) + return line + + + def DoFind(self, findString, replaceString, text, startLoc, endLoc, down, matchCase, wholeWord, regExpr = False, replace = False, replaceAll = False, wrap = False): + """ Do the actual work of the find/replace. + + Returns the tuple (count, start, end, newText). + count = number of string replacements + start = start position of found string + end = end position of found string + newText = new replaced text + """ + flags = 0 + if regExpr: + pattern = findString + else: + pattern = re.escape(findString) # Treat the strings as a literal string + if not matchCase: + flags = re.IGNORECASE + if wholeWord: + pattern = r"\b%s\b" % pattern + + try: + reg = re.compile(pattern, flags) + except: + # syntax error of some sort + import sys + msgTitle = wx.GetApp().GetAppName() + if not msgTitle: + msgTitle = _("Regular Expression Search") + wx.MessageBox(_("Invalid regular expression \"%s\". %s") % (pattern, sys.exc_value), + msgTitle, + wx.OK | wx.ICON_EXCLAMATION, + self.GetView()) + return FIND_SYNTAXERROR, None, None, None + + if replaceAll: + newText, count = reg.subn(replaceString, text) + if count == 0: + return -1, None, None, None + else: + return count, None, None, newText + + start = -1 + if down: + match = reg.search(text, endLoc) + if match == None: + if wrap: # try again, but this time from top of file + match = reg.search(text, 0) + if match == None: + return -1, None, None, None + else: + return -1, None, None, None + start = match.start() + end = match.end() + else: + match = reg.search(text) + if match == None: + return -1, None, None, None + found = None + i, j = match.span() + while i < startLoc and j <= startLoc: + found = match + if i == j: + j = j + 1 + match = reg.search(text, j) + if match == None: + break + i, j = match.span() + if found == None: + if wrap: # try again, but this time from bottom of file + match = reg.search(text, startLoc) + if match == None: + return -1, None, None, None + found = None + i, j = match.span() + end = len(text) + while i < end and j <= end: + found = match + if i == j: + j = j + 1 + match = reg.search(text, j) + if match == None: + break + i, j = match.span() + if found == None: + return -1, None, None, None + else: + return -1, None, None, None + start = found.start() + end = found.end() + + if replace and start != -1: + newText, count = reg.subn(replaceString, text, 1) + return count, start, end, newText + + return 0, start, end, None + + + def SaveFindConfig(self, findString, wholeWord, matchCase, regExpr = None, wrap = None, upDown = None, replaceString = None): + """ Save find/replace patterns and search flags to registry. + + findString = search pattern + wholeWord = match whole word only + matchCase = match case + regExpr = use regular expressions in search pattern + wrap = return to top/bottom of file on search + upDown = search up or down from current cursor position + replaceString = replace string + """ + config = wx.ConfigBase_Get() + + config.Write(FIND_MATCHPATTERN, findString) + config.WriteInt(FIND_MATCHCASE, matchCase) + config.WriteInt(FIND_MATCHWHOLEWORD, wholeWord) + if replaceString != None: + config.Write(FIND_MATCHREPLACE, replaceString) + if regExpr != None: + config.WriteInt(FIND_MATCHREGEXPR, regExpr) + if wrap != None: + config.WriteInt(FIND_MATCHWRAP, wrap) + if upDown != None: + config.WriteInt(FIND_MATCHUPDOWN, upDown) + + + def GetFindString(self): + """ Load the search pattern from registry """ + return wx.ConfigBase_Get().Read(FIND_MATCHPATTERN, "") + + + def GetReplaceString(self): + """ Load the replace pattern from registry """ + return wx.ConfigBase_Get().Read(FIND_MATCHREPLACE, "") + + + def GetFlags(self): + """ Load search parameters from registry """ + config = wx.ConfigBase_Get() + + flags = 0 + if config.ReadInt(FIND_MATCHWHOLEWORD, False): + flags = flags | wx.FR_WHOLEWORD + if config.ReadInt(FIND_MATCHCASE, False): + flags = flags | wx.FR_MATCHCASE + if config.ReadInt(FIND_MATCHUPDOWN, False): + flags = flags | wx.FR_DOWN + if config.ReadInt(FIND_MATCHREGEXPR, False): + flags = flags | FindService.FR_REGEXP + if config.ReadInt(FIND_MATCHWRAP, False): + flags = flags | FindService.FR_WRAP + return flags + + +class FindDialog(wx.Dialog): + """ Find Dialog with regular expression matching and wrap to top/bottom of file. """ + + def __init__(self, parent, id, title, size, findString=None): + wx.Dialog.__init__(self, parent, id, title, size=size) + + config = wx.ConfigBase_Get() + borderSizer = wx.BoxSizer(wx.VERTICAL) + gridSizer = wx.GridBagSizer(SPACE, SPACE) + + lineSizer = wx.BoxSizer(wx.HORIZONTAL) + lineSizer.Add(wx.StaticText(self, -1, _("Find what:")), 0, wx.ALIGN_CENTER_VERTICAL|wx.RIGHT, SPACE) + if not findString: + findString = config.Read(FIND_MATCHPATTERN, "") + self._findCtrl = wx.TextCtrl(self, -1, findString, size=(200,-1)) + lineSizer.Add(self._findCtrl, 0) + gridSizer.Add(lineSizer, pos=(0,0), span=(1,2)) + choiceSizer = wx.BoxSizer(wx.VERTICAL) + self._wholeWordCtrl = wx.CheckBox(self, -1, _("Match whole word only")) + self._wholeWordCtrl.SetValue(config.ReadInt(FIND_MATCHWHOLEWORD, False)) + self._matchCaseCtrl = wx.CheckBox(self, -1, _("Match case")) + self._matchCaseCtrl.SetValue(config.ReadInt(FIND_MATCHCASE, False)) + self._regExprCtrl = wx.CheckBox(self, -1, _("Regular expression")) + self._regExprCtrl.SetValue(config.ReadInt(FIND_MATCHREGEXPR, False)) + self._wrapCtrl = wx.CheckBox(self, -1, _("Wrap")) + self._wrapCtrl.SetValue(config.ReadInt(FIND_MATCHWRAP, False)) + choiceSizer.Add(self._wholeWordCtrl, 0, wx.BOTTOM, SPACE) + choiceSizer.Add(self._matchCaseCtrl, 0, wx.BOTTOM, SPACE) + choiceSizer.Add(self._regExprCtrl, 0, wx.BOTTOM, SPACE) + choiceSizer.Add(self._wrapCtrl, 0) + gridSizer.Add(choiceSizer, pos=(1,0), span=(2,1)) + + self._radioBox = wx.RadioBox(self, -1, _("Direction"), choices = ["Up", "Down"]) + self._radioBox.SetSelection(config.ReadInt(FIND_MATCHUPDOWN, 1)) + gridSizer.Add(self._radioBox, pos=(1,1), span=(2,1)) + + buttonSizer = wx.BoxSizer(wx.VERTICAL) + findBtn = wx.Button(self, FindService.FINDONE_ID, _("Find Next")) + findBtn.SetDefault() + wx.EVT_BUTTON(self, FindService.FINDONE_ID, self.OnActionEvent) + cancelBtn = wx.Button(self, wx.ID_CANCEL, _("Cancel")) + wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnClose) + buttonSizer.Add(findBtn, 0, wx.BOTTOM, HALF_SPACE) + buttonSizer.Add(cancelBtn, 0) + gridSizer.Add(buttonSizer, pos=(0,2), span=(3,1)) + + borderSizer.Add(gridSizer, 0, wx.ALL, SPACE) + + self.Bind(wx.EVT_CLOSE, self.OnClose) + + self.SetSizer(borderSizer) + self.Fit() + self._findCtrl.SetFocus() + + def SaveConfig(self): + """ Save find patterns and search flags to registry. """ + findService = wx.GetApp().GetService(FindService) + if findService: + findService.SaveFindConfig(self._findCtrl.GetValue(), + self._wholeWordCtrl.IsChecked(), + self._matchCaseCtrl.IsChecked(), + self._regExprCtrl.IsChecked(), + self._wrapCtrl.IsChecked(), + self._radioBox.GetSelection(), + ) + + + def DoClose(self): + self.SaveConfig() + self.Destroy() + + + def OnClose(self, event): + findService = wx.GetApp().GetService(FindService) + if findService: + findService.OnFindClose(event) + self.DoClose() + + + def OnActionEvent(self, event): + self.SaveConfig() + + if wx.GetApp().GetDocumentManager().GetFlags() & wx.lib.docview.DOC_MDI: + if wx.GetApp().GetTopWindow().ProcessEvent(event): + return True + else: + view = wx.GetApp().GetDocumentManager().GetLastActiveView() + if view and view.ProcessEvent(event): + return True + return False + + +class FindReplaceDialog(FindDialog): + """ Find/Replace Dialog with regular expression matching and wrap to top/bottom of file. """ + + def __init__(self, parent, id, title, size, findString=None): + wx.Dialog.__init__(self, parent, id, title, size=size) + + config = wx.ConfigBase_Get() + borderSizer = wx.BoxSizer(wx.VERTICAL) + gridSizer = wx.GridBagSizer(SPACE, SPACE) + + gridSizer2 = wx.GridBagSizer(SPACE, SPACE) + gridSizer2.Add(wx.StaticText(self, -1, _("Find what:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(0,0)) + if not findString: + findString = config.Read(FIND_MATCHPATTERN, "") + self._findCtrl = wx.TextCtrl(self, -1, findString, size=(200,-1)) + gridSizer2.Add(self._findCtrl, pos=(0,1)) + gridSizer2.Add(wx.StaticText(self, -1, _("Replace with:")), flag=wx.ALIGN_CENTER_VERTICAL, pos=(1,0)) + self._replaceCtrl = wx.TextCtrl(self, -1, config.Read(FIND_MATCHREPLACE, ""), size=(200,-1)) + gridSizer2.Add(self._replaceCtrl, pos=(1,1)) + gridSizer.Add(gridSizer2, pos=(0,0), span=(1,2)) + choiceSizer = wx.BoxSizer(wx.VERTICAL) + self._wholeWordCtrl = wx.CheckBox(self, -1, _("Match whole word only")) + self._wholeWordCtrl.SetValue(config.ReadInt(FIND_MATCHWHOLEWORD, False)) + self._matchCaseCtrl = wx.CheckBox(self, -1, _("Match case")) + self._matchCaseCtrl.SetValue(config.ReadInt(FIND_MATCHCASE, False)) + self._regExprCtrl = wx.CheckBox(self, -1, _("Regular expression")) + self._regExprCtrl.SetValue(config.ReadInt(FIND_MATCHREGEXPR, False)) + self._wrapCtrl = wx.CheckBox(self, -1, _("Wrap")) + self._wrapCtrl.SetValue(config.ReadInt(FIND_MATCHWRAP, False)) + choiceSizer.Add(self._wholeWordCtrl, 0, wx.BOTTOM, SPACE) + choiceSizer.Add(self._matchCaseCtrl, 0, wx.BOTTOM, SPACE) + choiceSizer.Add(self._regExprCtrl, 0, wx.BOTTOM, SPACE) + choiceSizer.Add(self._wrapCtrl, 0) + gridSizer.Add(choiceSizer, pos=(1,0), span=(2,1)) + + self._radioBox = wx.RadioBox(self, -1, _("Direction"), choices = ["Up", "Down"]) + self._radioBox.SetSelection(config.ReadInt(FIND_MATCHUPDOWN, 1)) + gridSizer.Add(self._radioBox, pos=(1,1), span=(2,1)) + + buttonSizer = wx.BoxSizer(wx.VERTICAL) + findBtn = wx.Button(self, FindService.FINDONE_ID, _("Find Next")) + findBtn.SetDefault() + wx.EVT_BUTTON(self, FindService.FINDONE_ID, self.OnActionEvent) + cancelBtn = wx.Button(self, wx.ID_CANCEL, _("Cancel")) + wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnClose) + replaceBtn = wx.Button(self, FindService.REPLACEONE_ID, _("Replace")) + wx.EVT_BUTTON(self, FindService.REPLACEONE_ID, self.OnActionEvent) + replaceAllBtn = wx.Button(self, FindService.REPLACEALL_ID, _("Replace All")) + wx.EVT_BUTTON(self, FindService.REPLACEALL_ID, self.OnActionEvent) + buttonSizer.Add(findBtn, 0, wx.BOTTOM, HALF_SPACE) + buttonSizer.Add(replaceBtn, 0, wx.BOTTOM, HALF_SPACE) + buttonSizer.Add(replaceAllBtn, 0, wx.BOTTOM, HALF_SPACE) + buttonSizer.Add(cancelBtn, 0) + gridSizer.Add(buttonSizer, pos=(0,2), span=(3,1)) + + borderSizer.Add(gridSizer, 0, wx.ALL, SPACE) + + self.Bind(wx.EVT_CLOSE, self.OnClose) + + self.SetSizer(borderSizer) + self.Fit() + self._findCtrl.SetFocus() + + + def SaveConfig(self): + """ Save find/replace patterns and search flags to registry. """ + findService = wx.GetApp().GetService(FindService) + if findService: + findService.SaveFindConfig(self._findCtrl.GetValue(), + self._wholeWordCtrl.IsChecked(), + self._matchCaseCtrl.IsChecked(), + self._regExprCtrl.IsChecked(), + self._wrapCtrl.IsChecked(), + self._radioBox.GetSelection(), + self._replaceCtrl.GetValue() + ) + + +#---------------------------------------------------------------------------- +# Menu Bitmaps - generated by encode_bitmaps.py +#---------------------------------------------------------------------------- +from wx import ImageFromStream, BitmapFromImage +import cStringIO + + +def getFindData(): + return \ +'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\ +\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\ +\x00\x00\x81IDAT8\x8d\xa5S\xc1\x16\xc0\x10\x0ckk\xff\xff\xc7d\x87\xad^U\r\ +\x93S\xe5U$\n\xb3$:\xc1e\x17(\x19Z\xb3$\x9e\xf1DD\xe2\x15\x01x\xea\x93\xef\ +\x04\x989\xea\x1b\xf2U\xc0\xda\xb4\xeb\x11\x1f:\xd8\xb5\xff8\x93\xd4\xa9\xae\ +@/S\xaaUwJ3\x85\xc0\x81\xee\xeb.q\x17C\x81\xd5XU \x1a\x93\xc6\x18\x8d\x90\ +\xe8}\x89\x00\x9a&\x9b_k\x94\x0c\xdf\xd78\xf8\x0b\x99Y\xb4\x08c\x9e\xfe\xc6\ +\xe3\x087\xf9\xd0D\x180\xf1#\x8e\x00\x00\x00\x00IEND\xaeB`\x82' + + +def getFindBitmap(): + return BitmapFromImage(getFindImage()) + + +def getFindImage(): + stream = cStringIO.StringIO(getFindData()) + return ImageFromStream(stream) + diff --git a/wxPython/samples/ide/activegrid/tool/HtmlEditor.py b/wxPython/samples/ide/activegrid/tool/HtmlEditor.py new file mode 100644 index 0000000000..e026fb978b --- /dev/null +++ b/wxPython/samples/ide/activegrid/tool/HtmlEditor.py @@ -0,0 +1,222 @@ +#---------------------------------------------------------------------------- +# Name: HtmlEditor.py +# Purpose: Abstract Code Editor for pydocview tbat uses the Styled Text Control +# +# Author: Peter Yared +# +# Created: 8/15/04 +# CVS-ID: $Id$ +# Copyright: (c) 2004-2005 ActiveGrid, Inc. +# License: wxWindows License +#---------------------------------------------------------------------------- + + +import wx +import os.path +import string +import STCTextEditor +import CodeEditor +_ = wx.GetTranslation + + +class HtmlDocument(CodeEditor.CodeDocument): + + pass + + +class HtmlView(CodeEditor.CodeView): + + + def GetCtrlClass(self): + """ Used in split window to instantiate new instances """ + return HtmlCtrl + + + def GetAutoCompleteHint(self): + pos = self.GetCtrl().GetCurrentPos() + if pos == 0: + return None, None + + validLetters = string.letters + string.digits + '_!-' + word = '' + while (True): + pos = pos - 1 + if pos < 0: + break + char = chr(self.GetCtrl().GetCharAt(pos)) + if char not in validLetters: + break + word = char + word + + return None, word + + + def GetAutoCompleteDefaultKeywords(self): + return HTMLKEYWORDS + + +## def _CreateControl(self, parent, id): +## import wx # wxBug: When inlining the import of the appropriate html control below, have to specifically import wx for some reason +## self._notebook = wx.Notebook(parent, wx.NewId(), style = wx.NB_BOTTOM) +## self._textEditor = HtmlCtrl(self._notebook, id) +## if wx.Platform =='__WXMSW__': +## import wxPython.iewin +## self._browserCtrl = wxPython.iewin.wxIEHtmlWin(self._notebook, -1, style = wx.NO_FULL_REPAINT_ON_RESIZE) +## else: +## import wx.html +## self._browserCtrl = wx.html.HtmlWindow(self._notebook, -1, style = wx.NO_FULL_REPAINT_ON_RESIZE) +## self._notebook.AddPage(self._textEditor, _("Edit")) +## self._notebook.AddPage(self._browserCtrl, _("View")) +## self._insertMode = True +## wx.EVT_NOTEBOOK_PAGE_CHANGED(self._notebook, self._notebook.GetId(), self.OnNotebookChanging) +## return self._textEditor +## +## +## def _CreateSizer(self, frame): +## sizer = wx.BoxSizer(wx.HORIZONTAL) +## sizer.Add(self._notebook, 1, wx.EXPAND) +## frame.SetSizer(sizer) +## frame.SetAutoLayout(True) +## +## +## def OnNotebookChanging(self, event): +## if event.GetSelection() == 0: # Going to the edit page +## pass # self._textEditor.Refresh() +## elif event.GetSelection() == 1: # Going to the browser page +## text = self._textEditor.GetText() +## if wx.Platform == '__WXMSW__': +## path = os.path.join(tempfile.gettempdir(), "temp.html") +## file = open(path, 'w') +## file.write(text) +## file.close() +## self._browserCtrl.Navigate("file://" + path) +## else: +## self._browserCtrl.SetPage(text) +## event.Skip() + + +class HtmlService(CodeEditor.CodeService): + + + def __init__(self): + CodeEditor.CodeService.__init__(self) + + +class HtmlCtrl(CodeEditor.CodeCtrl): + + + def __init__(self, parent, ID = -1, style = wx.NO_FULL_REPAINT_ON_RESIZE): + CodeEditor.CodeCtrl.__init__(self, parent, ID, style) + self.SetLexer(wx.stc.STC_LEX_HTML) + self.SetProperty("fold.html", "1") + + def GetMatchingBraces(self): + return "<>[]{}()" + + def CanWordWrap(self): + return True + + + def SetViewDefaults(self): + CodeEditor.CodeCtrl.SetViewDefaults(self, configPrefix = "Html", hasWordWrap = False, hasTabs = True) + + + def GetFontAndColorFromConfig(self): + return CodeEditor.CodeCtrl.GetFontAndColorFromConfig(self, configPrefix = "Html") + + + def UpdateStyles(self): + CodeEditor.CodeCtrl.UpdateStyles(self) + + if not self.GetFont(): + return + + faces = { 'font' : self.GetFont().GetFaceName(), + 'size' : self.GetFont().GetPointSize(), + 'size2': self.GetFont().GetPointSize() - 2, + 'color' : "%02x%02x%02x" % (self.GetFontColor().Red(), self.GetFontColor().Green(), self.GetFontColor().Blue()) + } + + # White space + self.StyleSetSpec(wx.stc.STC_H_DEFAULT, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces) + # Comment + self.StyleSetSpec(wx.stc.STC_H_COMMENT, "face:%(font)s,fore:#007F00,italic,face:%(font)s,size:%(size)d" % faces) + # Number + self.StyleSetSpec(wx.stc.STC_H_NUMBER, "face:%(font)s,fore:#007F7F,size:%(size)d" % faces) + # String + self.StyleSetSpec(wx.stc.STC_H_SINGLESTRING, "face:%(font)s,fore:#7F007F,face:%(font)s,size:%(size)d" % faces) + self.StyleSetSpec(wx.stc.STC_H_DOUBLESTRING, "face:%(font)s,fore:#7F007F,face:%(font)s,size:%(size)d" % faces) + # Tag + self.StyleSetSpec(wx.stc.STC_H_TAG, "face:%(font)s,fore:#00007F,bold,size:%(size)d" % faces) + # Attributes + self.StyleSetSpec(wx.stc.STC_H_ATTRIBUTE, "face:%(font)s,fore:#00007F,bold,size:%(size)d" % faces) + + +class HtmlOptionsPanel(STCTextEditor.TextOptionsPanel): + + def __init__(self, parent, id): + STCTextEditor.TextOptionsPanel.__init__(self, parent, id, configPrefix = "Html", label = "HTML", hasWordWrap = True, hasTabs = True) + + +HTMLKEYWORDS = [ + "A", "ABBR", "ACRONYM", "ADDRESS", "APPLET", "AREA", "B", "BASE", "BASEFONT", "BDO", "BIG", "BLOCKQUOTE", + "BODY", "BR", "BUTTON", "CAPTION", "CENTER", "CITE", "CODE", "COL", "COLGROUP", "DD", "DEL", "DFN", "DIR", + "DIV", "DL", "DT", "EM", "FIELDSET", "FONT", "FORM", "FRAME", "FRAMESET", "H1", "H2", "H3", "H4", "H5", "H6", + "HEAD", "HR", "HTML", "I", "IFRAME", "IMG", "INPUT", "INS", "ISINDEX", "KBD", "LABEL", "LEGEND", "LI", "LINK", + "MAP", "MENU", "META", "NOFRAMES", "NOSCRIPT", "OBJECT", "OL", "OPTGROUP", "OPTION", "P", "PARAM", + "PRE", "Q", "S", "SAMP", "SCRIPT", "SELECT", "SMALL", "SPAN", "STRIKE", "STRONG", "STYLE", "SUB", "SUP", + "TABLE", "TBODY", "TD", "TEXTAREA", "TFOOT", "TH", "THEAD", "TITLE", "TR", "TT", "U", "UL", "VAR", "XML", + "XMLNS", "ACCEPT-CHARSET", "ACCEPT", "ACCESSKEY", "ACTION", "ALIGN", "ALINK", "ALT", + "ARCHIVE", "AXIS", "BACKGROUND", "BGCOLOR", "BORDER", "CELLPADDING", "CELLSPACING", "CHAR", + "CHAROFF", "CHARSET", "CHECKED", "CLASS", "CLASSID", "CLEAR", "CODEBASE", "CODETYPE", + "COLOR", "COLS", "COLSPAN", "COMPACT", "CONTENT", "COORDS", "DATA", "DATAFLD", "DATAFORMATAS", + "DATAPAGESIZE", "DATASRC", "DATETIME", "DECLARE", "DEFER", "DISABLED", "ENCTYPE", + "EVENT", "FACE", "FOR", "FRAMEBORDER", "HEADERS", "HEIGHT", "HREF", "HREFLANG", "HSPACE", + "HTTP-EQUIV", "ID", "ISMAP", "LANG", "LANGUAGE", "LEFTMARGIN", "LONGDESC", + "MARGINWIDTH", "MARGINHEIGHT", "MAXLENGTH", "MEDIA", "METHOD", "MULTIPLE", "NAME", "NOHREF", + "NORESIZE", "NOSHADE", "NOWRAP", "ONBLUR", "ONCHANGE", "ONCLICK", "ONDBLCLICK", + "ONFOCUS", "ONKEYDOWN", "ONKEYPRESS", "ONKEYUP", "ONLOAD", "ONMOUSEDOWN", "ONMOUSEMOVE", + "ONMOUSEOVER", "ONMOUSEOUT", "ONMOUSEUP", "ONRESET", "ONSELECT", "ONSUBMIT", "ONUNLOAD", + "PROFILE", "PROMPT", "READONLY", "REL", "REV", "ROWS", "ROWSPAN", "RULES", "SCHEME", "SCOPE", + "SELECTED", "SHAPE", "SIZE", "SRC", "STANDBY", "START", "SUMMARY", "TABINDEX", + "TARGET", "TOPMARGIN", "TYPE", "USEMAP", "VALIGN", "VALUE", "VALUETYPE", + "VERSION", "VLINK", "VSPACE", "WIDTH", "TEXT", "PASSWORD", "CHECKBOX", "RADIO", "SUBMIT", "RESET", + "FILE", "HIDDEN", "IMAGE", "PUBLIC", "!DOCTYPE", + "ADD_DATE", "LAST_MODIFIED", "LAST_VISIT" + ] + + +#---------------------------------------------------------------------------- +# Icon Bitmaps - generated by encode_bitmaps.py +#---------------------------------------------------------------------------- +from wx import ImageFromStream, BitmapFromImage +from wx import EmptyIcon +import cStringIO + + +def getHTMLData(): + return \ +'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\ +\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\ +\x00\x00\xcdIDAT8\x8dcd`f\xf8\xcf@\x01`\xfc\x7f\xa3\x87"\x03X\xfe}\xbeI\x89~\ +\x06&\x8at\x0f\n\x03\x18\xe4\x954\xff\xc3\x00\x8c-\xaf\xa4\xf9_\xc7\xc0\xfc\ +\xbf\x93\xab\xf7\xff\xff\xff\xff\xff70\xb6\xfe\x7f\xed\xce\x93\xff\xd7\xee<\ +\xf9\xafc`\x0eW\xf3\xf5\xd7\xff\xff,\x0f\x1f^gPP\xd6B1\xf4\xc1\xddk\x0c\xf6\ +\xb6\x16\x0c{wma````x\xf7\xfc\x06\xc3\xea\xa5\xb3\x198\xd8X\x18\xbe~|\x06W\ +\xc7\xc5\xca\xc0\xc0\xc2\xc0\xc0\xc0P\\\x9c\xcf\xf0\xf4\xc5\x1b\x86\x15K\x97\ +\xc2%Y\xd9y\xe0lF\x0e1\x86C\x87\x8e0\x88\x88\x8a3\xfccD\x88\xe3\xf4\x026\xf6\ +\xa9c{\xfe_