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
This commit is contained in:
Robin Dunn
2005-04-08 22:54:02 +00:00
parent 510bb7480c
commit 1f780e48af
42 changed files with 20049 additions and 9 deletions
+6 -4
View File
@@ -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
+10 -5
View File
@@ -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";
+1
View File
@@ -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.
+33
View File
@@ -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()
@@ -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)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -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)
File diff suppressed because it is too large Load Diff
@@ -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_<s\x18\xc5\x9b\xf2J\x9a\xff\x19\xff\x9eN\xa5(!\r|4\x0e\x03\x03\
\x00R\xe4{\xe74\x9e\xbb\xd1\x00\x00\x00\x00IEND\xaeB`\x82'
def getHTMLBitmap():
return BitmapFromImage(getHTMLImage())
def getHTMLImage():
stream = cStringIO.StringIO(getHTMLData())
return ImageFromStream(stream)
def getHTMLIcon():
icon = EmptyIcon()
icon.CopyFromBitmap(getHTMLBitmap())
return icon
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,445 @@
#----------------------------------------------------------------------------
# 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 IDEFindService(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, IDEFindService.FINDALL_ID, self.ProcessEvent)
wx.EVT_UPDATE_UI(frame, IDEFindService.FINDALL_ID, self.ProcessUpdateUIEvent)
editMenu.Append(IDEFindService.FINDALL_ID, _("Find in Project...\tCtrl+Shift+F"), _("Searches for the specified text in all the files in the project"))
wx.EVT_MENU(frame, IDEFindService.FINDDIR_ID, self.ProcessEvent)
wx.EVT_UPDATE_UI(frame, IDEFindService.FINDDIR_ID, self.ProcessUpdateUIEvent)
editMenu.Append(IDEFindService.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 == IDEFindService.FINDALL_ID:
self.ShowFindAllDialog()
return True
elif id == IDEFindService.FINDDIR_ID:
self.ShowFindDirDialog()
return True
else:
return FindService.FindService.ProcessEvent(self, event)
def ProcessUpdateUIEvent(self, event):
id = event.GetId()
if id == IDEFindService.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 == IDEFindService.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()
# 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)
while not os.path.exists(dirString):
dlg = wx.MessageDialog(frame,
_("'%s' does not exist.") % dirString,
_("Find in Directory"),
wx.OK | wx.ICON_EXCLAMATION
)
dlg.ShowModal()
dlg.Destroy()
status = frame.ShowModal()
# 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_CANCEL:
break
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)
@@ -0,0 +1,93 @@
#----------------------------------------------------------------------------
# Name: ImageEditor.py
# Purpose: Image Editor for pydocview
#
# Author: Morgan Hua
#
# Created: 12/24/04
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# CVS-ID: $Id$
# License: wxWindows License
#----------------------------------------------------------------------------
import wx
import wx.lib.docview
_ = wx.GetTranslation
class ImageDocument(wx.lib.docview.Document):
pass
class ImageView(wx.lib.docview.View):
#----------------------------------------------------------------------------
# Overridden methods
#----------------------------------------------------------------------------
def __init__(self):
wx.lib.docview.View.__init__(self)
self._ctrl = None
def OnCreate(self, doc, flags):
if len(doc.GetFilename()) == 0:
wx.MessageBox(_("Cannot create a new image file.\n%s has no paint capability.") % wx.GetApp().GetAppName(),
_("New Image File"),
wx.OK | wx.ICON_EXCLAMATION)
return False
frame = wx.GetApp().CreateDocumentFrame(self, doc, flags)
panel = wx.Panel(frame, -1)
bitmap = wx.Image(doc.GetFilename()).ConvertToBitmap()
self._ctrl = wx.StaticBitmap(panel, -1, bitmap, (0,0), (bitmap.GetWidth(), bitmap.GetHeight()))
panel.SetClientSize(bitmap.GetSize())
frame.SetClientSize(panel.GetSize())
self.Activate()
return True
def OnClose(self, deleteWindow = True):
statusC = wx.GetApp().CloseChildDocuments(self.GetDocument())
statusP = wx.lib.docview.View.OnClose(self, deleteWindow = deleteWindow)
if not (statusC and statusP):
return False
self.Activate(False)
if deleteWindow:
self.GetFrame().Destroy()
return True
#----------------------------------------------------------------------------
# Icon Bitmaps - generated by encode_bitmaps.py
#----------------------------------------------------------------------------
from wx import ImageFromStream, BitmapFromImage
from wx import EmptyIcon
import cStringIO
def getImageData():
return \
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x0f\x00\x00\x00\x0e\x08\x06\
\x00\x00\x00\xf0\x8aF\xef\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
\x00\x00\x97IDAT(\x91\x9d\x93Q\n\xc4 \x0cD\'\xda\xd3\xa9\xe9ac\xdb\x8bx\xa0\
\xf4C"\xd6mAw@\x0c1/\t\x03\x123+\x16\x95s\x06\x00l\x00p\x9c\x17\xad\xc0\xe4<\
R\x0c\xeaf\x81\x14\x83\xa6\x18\x1e[N\xc1)\x06\x15\x01Dj\xbc\x04\x7fi\x9b):\
\xce\x8b\xf6\xbdN\xec\xfd\x99\x82G\xc8\xf4\xba\xf6\x9b9o\xfa\x81\xab9\x02\
\x11i\xe6|6cf%\xe7A\xce\x83\x99\xd5\xc4\xccZJ\xd11\xd7\xd76\xd8\x8aJ)\xed\
\xb6c\x8d,~\xc0\xe3\xe3L\xdc\xe0~\xcaJ\x03\xfa\xe7c\x98n\x01\x88\xc6k\xb1\
\x83\x04\x87\x00\x00\x00\x00IEND\xaeB`\x82'
def getImageBitmap():
return BitmapFromImage(getImageImage())
def getImageImage():
stream = cStringIO.StringIO(getImageData())
return ImageFromStream(stream)
def getImageIcon():
icon = EmptyIcon()
icon.CopyFromBitmap(getImageBitmap())
return icon
@@ -0,0 +1,91 @@
#----------------------------------------------------------------------------
# Name: MarkerService.py
# Purpose: Adding and removing line markers in text for easy searching
#
# Author: Morgan Hua
#
# Created: 10/6/03
# CVS-ID: $Id$
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import wx
import wx.stc
import wx.lib.docview
import wx.lib.pydocview
import STCTextEditor
_ = wx.GetTranslation
class MarkerService(wx.lib.pydocview.DocService):
MARKERTOGGLE_ID = wx.NewId()
MARKERDELALL_ID = wx.NewId()
MARKERNEXT_ID = wx.NewId()
MARKERPREV_ID = wx.NewId()
def __init__(self):
pass
def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None):
if document and document.GetDocumentTemplate().GetDocumentType() != STCTextEditor.TextDocument:
return
if not document and wx.GetApp().GetDocumentManager().GetFlags() & wx.lib.docview.DOC_SDI:
return
editMenu = menuBar.GetMenu(menuBar.FindMenu(_("&Edit")))
editMenu.AppendSeparator()
editMenu.Append(MarkerService.MARKERTOGGLE_ID, _("Toggle &Marker\tCtrl+M"), _("Toggles a jump marker to text line"))
wx.EVT_MENU(frame, MarkerService.MARKERTOGGLE_ID, frame.ProcessEvent)
wx.EVT_UPDATE_UI(frame, MarkerService.MARKERTOGGLE_ID, frame.ProcessUpdateUIEvent)
editMenu.Append(MarkerService.MARKERDELALL_ID, _("Clear Markers"), _("Removes all jump markers from selected file"))
wx.EVT_MENU(frame, MarkerService.MARKERDELALL_ID, frame.ProcessEvent)
wx.EVT_UPDATE_UI(frame, MarkerService.MARKERDELALL_ID, frame.ProcessUpdateUIEvent)
editMenu.Append(MarkerService.MARKERNEXT_ID, _("Marker Next\tF4"), _("Moves to next marker in selected file"))
wx.EVT_MENU(frame, MarkerService.MARKERNEXT_ID, frame.ProcessEvent)
wx.EVT_UPDATE_UI(frame, MarkerService.MARKERNEXT_ID, frame.ProcessUpdateUIEvent)
editMenu.Append(MarkerService.MARKERPREV_ID, _("Marker Previous\tShift+F4"), _("Moves to previous marker in selected file"))
wx.EVT_MENU(frame, MarkerService.MARKERPREV_ID, frame.ProcessEvent)
wx.EVT_UPDATE_UI(frame, MarkerService.MARKERPREV_ID, frame.ProcessUpdateUIEvent)
def ProcessEvent(self, event):
id = event.GetId()
if id == MarkerService.MARKERTOGGLE_ID:
wx.GetApp().GetDocumentManager().GetCurrentView().MarkerToggle()
return True
elif id == MarkerService.MARKERDELALL_ID:
wx.GetApp().GetDocumentManager().GetCurrentView().MarkerDeleteAll()
return True
elif id == MarkerService.MARKERNEXT_ID:
wx.GetApp().GetDocumentManager().GetCurrentView().MarkerNext()
return True
elif id == MarkerService.MARKERPREV_ID:
wx.GetApp().GetDocumentManager().GetCurrentView().MarkerPrevious()
return True
else:
return False
def ProcessUpdateUIEvent(self, event):
id = event.GetId()
if id == MarkerService.MARKERTOGGLE_ID:
view = wx.GetApp().GetDocumentManager().GetCurrentView()
event.Enable(hasattr(view, "MarkerToggle"))
return True
elif id == MarkerService.MARKERDELALL_ID:
view = wx.GetApp().GetDocumentManager().GetCurrentView()
event.Enable(hasattr(view, "MarkerDeleteAll") and view.GetMarkerCount())
return True
elif id == MarkerService.MARKERNEXT_ID:
view = wx.GetApp().GetDocumentManager().GetCurrentView()
event.Enable(hasattr(view, "MarkerNext") and view.GetMarkerCount())
return True
elif id == MarkerService.MARKERPREV_ID:
view = wx.GetApp().GetDocumentManager().GetCurrentView()
event.Enable(hasattr(view, "MarkerPrevious") and view.GetMarkerCount())
return True
else:
return False
@@ -0,0 +1,143 @@
#----------------------------------------------------------------------------
# Name: MessageService.py
# Purpose: Message View Service for pydocview
#
# Author: Morgan Hua
#
# Created: 9/2/04
# CVS-ID: $Id$
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import wx
import Service
import STCTextEditor
class MessageView(Service.ServiceView):
""" Reusable Message View for any document.
When an item is selected, the document view is called back (with DoSelectCallback) to highlight and display the corresponding item in the document view.
"""
#----------------------------------------------------------------------------
# Overridden methods
#----------------------------------------------------------------------------
def _CreateControl(self, parent, id):
txtCtrl = STCTextEditor.TextCtrl(parent, id)
txtCtrl.SetMarginWidth(1, 0) # hide line numbers
txtCtrl.SetReadOnly(True)
if wx.Platform == '__WXMSW__':
font = "Courier New"
else:
font = "Courier"
txtCtrl.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, faceName = font))
txtCtrl.SetFontColor(wx.BLACK)
txtCtrl.StyleClearAll()
txtCtrl.UpdateStyles()
return txtCtrl
## def ProcessEvent(self, event):
## stcControl = self.GetControl()
## if not isinstance(stcControl, wx.stc.StyledTextCtrl):
## return wx.lib.docview.View.ProcessUpdateUIEvent(self, event)
## id = event.GetId()
## if id == wx.ID_CUT:
## stcControl.Cut()
## return True
## elif id == wx.ID_COPY:
## stcControl.Copy()
## return True
## elif id == wx.ID_PASTE:
## stcControl.Paste()
## return True
## elif id == wx.ID_CLEAR:
## stcControl.Clear()
## return True
## elif id == wx.ID_SELECTALL:
## stcControl.SetSelection(0, -1)
## return True
##
##
## def ProcessUpdateUIEvent(self, event):
## stcControl = self.GetControl()
## if not isinstance(stcControl, wx.stc.StyledTextCtrl):
## return wx.lib.docview.View.ProcessUpdateUIEvent(self, event)
## id = event.GetId()
## if id == wx.ID_CUT:
## event.Enable(stcControl.CanCut())
## return True
## elif id == wx.ID_COPY:
## event.Enable(stcControl.CanCopy())
## return True
## elif id == wx.ID_PASTE:
## event.Enable(stcControl.CanPaste())
## return True
## elif id == wx.ID_CLEAR:
## event.Enable(True) # wxBug: should be stcControl.CanCut()) but disabling clear item means del key doesn't work in control as expected
## return True
## elif id == wx.ID_SELECTALL:
## event.Enable(stcControl.GetTextLength() > 0)
## return True
#----------------------------------------------------------------------------
# Service specific methods
#----------------------------------------------------------------------------
def ClearLines(self):
self.GetControl().SetReadOnly(False)
self.GetControl().ClearAll()
self.GetControl().SetReadOnly(True)
def AddLines(self, text):
self.GetControl().SetReadOnly(False)
self.GetControl().AddText(text)
self.GetControl().SetReadOnly(True)
def GetText(self):
return self.GetControl().GetText()
def GetCurrentPos(self):
return self.GetControl().GetCurrentPos()
def GetCurrLine(self):
return self.GetControl().GetCurLine()
#----------------------------------------------------------------------------
# Callback Methods
#----------------------------------------------------------------------------
def SetCallback(self, callback):
""" Sets in the event table for a doubleclick to invoke the given callback.
Additional calls to this method overwrites the previous entry and only the last set callback will be invoked.
"""
wx.stc.EVT_STC_DOUBLECLICK(self.GetControl(), self.GetControl().GetId(), callback)
class MessageService(Service.Service):
#----------------------------------------------------------------------------
# Constants
#----------------------------------------------------------------------------
SHOW_WINDOW = wx.NewId() # keep this line for each subclass, need unique ID for each Service
#----------------------------------------------------------------------------
# Overridden methods
#----------------------------------------------------------------------------
def _CreateView(self):
return MessageView(self)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,297 @@
#----------------------------------------------------------------------------
# Name: PHPEditor.py
# Purpose: PHP Script Editor for pydocview tbat uses the Styled Text Control
#
# Author: Morgan Hua
#
# Created: 1/4/04
# CVS-ID: $Id$
# Copyright: (c) 2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import wx
import string
import STCTextEditor
import CodeEditor
import OutlineService
import os
import re
class PHPDocument(CodeEditor.CodeDocument):
pass
class PHPView(CodeEditor.CodeView):
def GetCtrlClass(self):
""" Used in split window to instantiate new instances """
return PHPCtrl
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 PHPKEYWORDS
#----------------------------------------------------------------------------
# Methods for OutlineService
#----------------------------------------------------------------------------
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
INTERFACE_PATTERN = 'interface[ \t]+\w+'
CLASS_PATTERN = '((final|abstract)[ \t]+)?((public|private|protected)[ \t]+)?(static[ \t]+)?class[ \t]+\w+((implements|extends)\w+)?'
FUNCTION_PATTERN = '(abstract[ \t]+)?((public|private|protected)[ \t]+)?(static[ \t]+)?function[ \t]+?\w+\(.*?\)'
interfacePat = re.compile(INTERFACE_PATTERN, re.M|re.S)
classPat = re.compile(CLASS_PATTERN, re.M|re.S)
funcPat= re.compile(FUNCTION_PATTERN, re.M|re.S)
pattern = re.compile('^[ \t]*('+ CLASS_PATTERN + '.*?{|' + FUNCTION_PATTERN + '|' + INTERFACE_PATTERN +'\s*?{).*?$', re.M|re.S)
iter = pattern.finditer(text)
indentStack = [(0, rootItem)]
for pattern in iter:
line = pattern.string[pattern.start(0):pattern.end(0)]
foundLine = classPat.search(line)
if foundLine:
indent = foundLine.start(0)
itemStr = foundLine.string[foundLine.start(0):foundLine.end(0)]
else:
foundLine = funcPat.search(line)
if foundLine:
indent = foundLine.start(0)
itemStr = foundLine.string[foundLine.start(0):foundLine.end(0)]
else:
foundLine = interfacePat.search(line)
if foundLine:
indent = foundLine.start(0)
itemStr = foundLine.string[foundLine.start(0):foundLine.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
class PHPService(CodeEditor.CodeService):
def __init__(self):
CodeEditor.CodeService.__init__(self)
class PHPCtrl(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.SetStyleBits(7)
self.SetKeyWords(4, string.join(PHPKEYWORDS))
self.SetProperty("fold.html", "1")
def CanWordWrap(self):
return True
def SetViewDefaults(self):
CodeEditor.CodeCtrl.SetViewDefaults(self, configPrefix = "PHP", hasWordWrap = True, hasTabs = True)
def GetFontAndColorFromConfig(self):
return CodeEditor.CodeCtrl.GetFontAndColorFromConfig(self, configPrefix = "PHP")
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())
}
# HTML Styles
# 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)
# PHP Styles
self.StyleSetSpec(wx.stc.STC_HPHP_DEFAULT, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_HPHP_COMMENT, "face:%(font)s,fore:#007F00,italic,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_HPHP_COMMENTLINE, "face:%(font)s,fore:#007F00,italic,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_HPHP_NUMBER, "face:%(font)s,fore:#007F7F,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_HPHP_SIMPLESTRING, "face:%(font)s,fore:#7F007F,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_HPHP_HSTRING, "face:%(font)s,fore7F007F,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_HPHP_HSTRING_VARIABLE, "face:%(font)s,fore:#007F7F,italic,bold,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_HPHP_VARIABLE, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_HPHP_OPERATOR, "face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_HPHP_WORD, "face:%(font)s,fore:#00007F,bold,size:%(size)d" % faces) # keyword
class PHPOptionsPanel(STCTextEditor.TextOptionsPanel):
def __init__(self, parent, id):
STCTextEditor.TextOptionsPanel.__init__(self, parent, id, configPrefix = "PHP", label = "PHP", hasWordWrap = True, hasTabs = True)
PHPKEYWORDS = [
"and", "or", "xor", "__FILE__", "exception", "__LINE__", "array", "as", "break", "case",
"class", "const", "continue", "declare", "default", "die", "do", "echo", "else", "elseif",
"empty", "enddeclare", "endfor", "endforeach", "endif", "endswith", "endwhile", "eval",
"exit", "extends", "for", "foreach", "function", "global", "if", "include", "include_once",
"isset", "list", "new", "print", "require", "require_once", "return", "static", "switch",
"unset", "use", "var", "while", "__FUNCTION__", "__CLASS__", "__METHOD__", "final", "php_user_filter",
"interface", "implements", "extends", "public", "private", "protected", "abstract", "clone", "try", "catch",
"throw", "cfunction", "old_function",
"$_SERVER", "$_ENV", "$_COOKIE", "$_GET", "$_POST", "$_FILES", "$_REQUEST", "$_SESSION", "$GLOBALS", "$php_errormsg",
"PHP_VERSION", "PHP_OS", "PHP_EOL", "DEFAULT_INCLUDE_PATH", "PEAR_INSTALL_DIR", "PEAR_EXTENSION_DIR",
"PHP_EXTENSION_DIR", "PHP_BINDIR", "PHP_LIBDIR", "PHP_DATADIR", "PHP_SYSCONFDIR", "PHP_LOCALSTATEDIR",
"PHP_CONFIG_FILE_PATH", "PHP_OUTPUT_HANDLER_START", "PHP_OUTPUT_HANDLER_CONT", "PHP_OUTPUT_HANDLER_END",
"E_ERROR", "E_WARNING", "E_PARSE", "E_NOTICE", "E_CORE_ERROR", "E_CORE_WARNING", "E_COMPILE_ERROR",
"E_COMPILE_WARNING", "E_USER_ERROR", "E_USER_WARNING", "E_USER_NOTICE", "E_ALL", "E_STRICT",
"TRUE", "FALSE", "NULL", "ZEND_THREAD_SAFE",
"EXTR_OVERWRITE", "EXTR_SKIP", "EXTR_PREFIX_SAME", "EXTR_PREFIX_ALL", "EXTR_PREFIX_INVALID",
"EXTR_PREFIX_IF_EXISTS", "EXTR_IF_EXISTS", "SORT_ASC", "SORT_DESC", "SORT_REGULAR", "SORT_NUMERIC",
"SORT_STRING", "CASE_LOWER", "CASE_UPPER", "COUNT_NORMAL", "COUNT_RECURSIVE", "ASSERT_ACTIVE",
"ASSERT_CALLBACK", "ASSERT_BAIL", "ASSERT_WARNING", "ASSERT_QUIET_EVAL", "CONNECTION_ABORTED",
"CONNECTION_NORMAL", "CONNECTION_TIMEOUT", "INI_USER", "INI_PERDIR", "INI_SYSTEM", "INI_ALL",
"M_E", "M_LOG2E", "M_LOG10E", "M_LN2", "M_LN10", "M_PI", "M_PI_2", "M_PI_4", "M_1_PI", "M_2_PI",
"M_2_SQRTPI", "M_SQRT2", "M_SQRT1_2", "CRYPT_SALT_LENGTH", "CRYPT_STD_DES", "CRYPT_EXT_DES", "CRYPT_MD5",
"CRYPT_BLOWFISH", "DIRECTORY_SEPARATOR", "SEEK_SET", "SEEK_CUR", "SEEK_END", "LOCK_SH", "LOCK_EX", "LOCK_UN",
"LOCK_NB", "HTML_SPECIALCHARS", "HTML_ENTITIES", "ENT_COMPAT", "ENT_QUOTES", "ENT_NOQUOTES", "INFO_GENERAL",
"INFO_CREDITS", "INFO_CONFIGURATION", "INFO_MODULES", "INFO_ENVIRONMENT", "INFO_VARIABLES", "INFO_LICENSE",
"INFO_ALL", "CREDITS_GROUP", "CREDITS_GENERAL", "CREDITS_SAPI", "CREDITS_MODULES", "CREDITS_DOCS",
"CREDITS_FULLPAGE", "CREDITS_QA", "CREDITS_ALL", "STR_PAD_LEFT", "STR_PAD_RIGHT", "STR_PAD_BOTH",
"PATHINFO_DIRNAME", "PATHINFO_BASENAME", "PATHINFO_EXTENSION", "PATH_SEPARATOR", "CHAR_MAX", "LC_CTYPE",
"LC_NUMERIC", "LC_TIME", "LC_COLLATE", "LC_MONETARY", "LC_ALL", "LC_MESSAGES", "ABDAY_1", "ABDAY_2",
"ABDAY_3", "ABDAY_4", "ABDAY_5", "ABDAY_6", "ABDAY_7", "DAY_1", "DAY_2", "DAY_3", "DAY_4", "DAY_5",
"DAY_6", "DAY_7", "ABMON_1", "ABMON_2", "ABMON_3", "ABMON_4", "ABMON_5", "ABMON_6", "ABMON_7", "ABMON_8",
"ABMON_9", "ABMON_10", "ABMON_11", "ABMON_12", "MON_1", "MON_2", "MON_3", "MON_4", "MON_5", "MON_6", "MON_7",
"MON_8", "MON_9", "MON_10", "MON_11", "MON_12", "AM_STR", "PM_STR", "D_T_FMT", "D_FMT", "T_FMT", "T_FMT_AMPM",
"ERA", "ERA_YEAR", "ERA_D_T_FMT", "ERA_D_FMT", "ERA_T_FMT", "ALT_DIGITS", "INT_CURR_SYMBOL", "CURRENCY_SYMBOL",
"CRNCYSTR", "MON_DECIMAL_POINT", "MON_THOUSANDS_SEP", "MON_GROUPING", "POSITIVE_SIGN", "NEGATIVE_SIGN",
"INT_FRAC_DIGITS", "FRAC_DIGITS", "P_CS_PRECEDES", "P_SEP_BY_SPACE", "N_CS_PRECEDES", "N_SEP_BY_SPACE",
"P_SIGN_POSN", "N_SIGN_POSN", "DECIMAL_POINT", "RADIXCHAR", "THOUSANDS_SEP", "THOUSEP", "GROUPING",
"YESEXPR", "NOEXPR", "YESSTR", "NOSTR", "CODESET", "LOG_EMERG", "LOG_ALERT", "LOG_CRIT", "LOG_ERR",
"LOG_WARNING", "LOG_NOTICE", "LOG_INFO", "LOG_DEBUG", "LOG_KERN", "LOG_USER", "LOG_MAIL", "LOG_DAEMON",
"LOG_AUTH", "LOG_SYSLOG", "LOG_LPR", "LOG_NEWS", "LOG_UUCP", "LOG_CRON", "LOG_AUTHPRIV", "LOG_LOCAL0",
"LOG_LOCAL1", "LOG_LOCAL2", "LOG_LOCAL3", "LOG_LOCAL4", "LOG_LOCAL5", "LOG_LOCAL6", "LOG_LOCAL7",
"LOG_PID", "LOG_CONS", "LOG_ODELAY", "LOG_NDELAY", "LOG_NOWAIT", "LOG_PERROR"
]
#----------------------------------------------------------------------------
# Icon Bitmaps - generated by encode_bitmaps.py
#----------------------------------------------------------------------------
from wx import ImageFromStream, BitmapFromImage
from wx import EmptyIcon
import cStringIO
def getPHPData():
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{IDAT8\x8dclh8\xf0\x9f\x81\x02\xc0D\x89f\xaa\x18\xc0\x82M0<\\\x1c\
\xce^\xb9\xf2%y.\xd0\xd4\xd4$\xde\x05\xf8l\x0c\x0f\x17\x87\x8baS\xc7x\xfd\
\xfa\xf5\xff\xc8\xb6]\xbf~\x1d\xc3\x05\xf8\xc4\x98\x90\x05\xae_\xbf\x8e\xa1\
\x88\x90\xd8 \x8aF\x98\x93`~\xc3\x05\xd0\xd5\xc1\r\x80\t\xc0B\xf7\xfa\xf5\
\xeb(l\\\xeaP\xbc\x80\x1c\x85\xb8\xd8\xe8|&b\x9c\x8dn;2`\x1c\xf0\xdc\x08\x00\
\x8e\xf2S\xed\xb0\xbe\xaa\xbc\x00\x00\x00\x00IEND\xaeB`\x82'
def getPHPBitmap():
return BitmapFromImage(getPHPImage())
def getPHPImage():
stream = cStringIO.StringIO(getPHPData())
return ImageFromStream(stream)
def getPHPIcon():
icon = EmptyIcon()
icon.CopyFromBitmap(getPHPBitmap())
return icon
@@ -0,0 +1,425 @@
#----------------------------------------------------------------------------
# Name: PerlEditor.py
# Purpose: Perl Script Editor for pydocview tbat uses the Styled Text Control
#
# Author: Morgan Hua
#
# Created: 1/5/04
# CVS-ID: $Id$
# Copyright: (c) 2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import wx
import string
import STCTextEditor
import CodeEditor
class PerlDocument(CodeEditor.CodeDocument):
pass
class PerlView(CodeEditor.CodeView):
def GetCtrlClass(self):
""" Used in split window to instantiate new instances """
return PerlCtrl
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 PERLKEYWORDS
class PerlService(CodeEditor.CodeService):
def __init__(self):
CodeEditor.CodeService.__init__(self)
class PerlCtrl(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_PERL)
self.SetKeyWords(0, string.join(PERLKEYWORDS))
def CanWordWrap(self):
return True
def SetViewDefaults(self):
CodeEditor.CodeCtrl.SetViewDefaults(self, configPrefix = "Perl", hasWordWrap = True, hasTabs = True)
def GetFontAndColorFromConfig(self):
return CodeEditor.CodeCtrl.GetFontAndColorFromConfig(self, configPrefix = "Perl")
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())
}
# Perl Styles
self.StyleSetSpec(wx.stc.STC_PL_DEFAULT, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_COMMENTLINE, "face:%(font)s,fore:#007F00,italic,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_NUMBER, "face:%(font)s,fore:#007F7F,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_CHARACTER, "face:%(font)s,fore:#7F007F,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_STRING, "face:%(font)s,fore:#7F007F,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_STRING_Q, "face:%(font)s,fore:#7F007F,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_STRING_QQ, "face:%(font)s,fore:#7F007F,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_STRING_QX, "face:%(font)s,fore:#7F007F,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_STRING_QR, "face:%(font)s,fore:#7F007F,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_STRING_QW, "face:%(font)s,fore:#7F007F,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_BACKTICKS, "face:%(font)s,fore:#7F007F,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_WORD, "face:%(font)s,fore:#00007F,bold,size:%(size)d" % faces) # keyword
self.StyleSetSpec(wx.stc.STC_PL_IDENTIFIER, "face:%(font)s,fore:#%(color)s,face:%(font)s,size:%(size)d" % faces)
# Default
self.StyleSetSpec(wx.stc.STC_PL_ARRAY, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_DATASECTION, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_ERROR, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_HASH, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_HERE_DELIM, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_HERE_Q, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_HERE_QQ, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_HERE_QX, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_LONGQUOTE, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_OPERATOR, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_POD, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_PREPROCESSOR, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_PUNCTUATION, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_REGEX, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_REGSUBST, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_SCALAR, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
self.StyleSetSpec(wx.stc.STC_PL_SYMBOLTABLE, "face:%(font)s,fore:#000000,face:%(font)s,size:%(size)d" % faces)
class PerlOptionsPanel(STCTextEditor.TextOptionsPanel):
def __init__(self, parent, id):
STCTextEditor.TextOptionsPanel.__init__(self, parent, id, configPrefix = "Perl", label = "Perl", hasWordWrap = True, hasTabs = True)
PERLKEYWORDS = [
"abs",
"accept",
"alarm",
"atan2",
"bind",
"binmode",
"bless",
"caller",
"chdir",
"chmod",
"chomp",
"chop",
"chown",
"chr",
"chroot",
"close",
"closedir",
"connect",
"continue",
"cos",
"crypt",
"dbmclose",
"dbmopen",
"defined",
"delete",
"die",
"do",
"dump",
"each",
"endgrent",
"endhostent",
"endnetent",
"endprotoent",
"endpwent",
"endservent",
"eof",
"eval",
"exec",
"exists",
"exit",
"exp",
"fcntl",
"fileno",
"flock",
"fork",
"format",
"formline",
"getc",
"getgrent",
"getgrgid",
"getgrnam",
"gethostbyaddr",
"gethostbyname",
"gethostent",
"getlogin",
"getnetbyaddr",
"getnetbyname",
"getnetent",
"getpeername",
"getpgrp",
"getppid",
"getpriority",
"getprotobyname",
"getprotobynumber",
"getprotoent",
"getpwent",
"getpwnam",
"getpwuid",
"getservbyname",
"getservbyport",
"getservent",
"getsockname",
"getsockopt",
"glob",
"gmtime",
"goto",
"grep",
"hex",
"import",
"index",
"int",
"ioctl",
"join",
"keys",
"kill",
"last",
"lc",
"lcfirst",
"length",
"link",
"listen",
"local",
"localtime",
"log",
"lstat",
"m//",
"map",
"mkdir",
"msgctl",
"msgget",
"msgrcv",
"msgsnd",
"my",
"next",
"no",
"oct",
"open",
"opendir",
"ord",
"pack",
"package",
"pipe",
"pop",
"pos",
"print",
"printf",
"prototype",
"push",
"q/STRING/",
"qq/STRING/",
"quotemeta",
"qw",
"qw/STRING/",
"qx",
"qx/STRING/",
"rand",
"read",
"readdir",
"readline",
"readlink",
"readpipe",
"recv",
"redo",
"ref",
"rename",
"require",
"reset",
"return",
"reverse",
"rewinddir",
"rindex",
"rmdir",
"s///",
"scalar",
"seek",
"seekdir",
"select",
"semctl",
"semget",
"semop",
"send",
"setgrent",
"sethostent",
"setnetent",
"setpgrp",
"setpriority",
"setprotoent",
"setpwent",
"setservent",
"setsockopt",
"shift",
"shmctl",
"shmget",
"shmread",
"shmwrite",
"shutdown",
"sin",
"sleep",
"socket",
"socketpair",
"sort",
"splice",
"split",
"sprintf",
"sqrt",
"srand",
"stat",
"study",
"sub",
"substr",
"symlink",
"syscall",
"sysopen",
"sysread",
"sysseek",
"system",
"syswrite",
"tell",
"telldir",
"tie",
"tied",
"times",
"tr///",
"truncate",
"uc",
"ucfirst",
"umask",
"undef",
"unlink",
"unpack",
"unshift",
"untie",
"use",
"utime",
"values",
"vec",
"wait",
"waitpid",
"wantarray",
"warn",
"write",
"y///",
"eq",
"ne",
"lt",
"le",
"gt",
"ge",
"cmp",
"if",
"else"
"not",
"and",
"xor",
"or",
"if",
"while",
"until",
"for",
"foreach",
"last",
"next",
"redo",
"goto",
"STDIN",
"STDOUT",
"STDERR",
"WHEncE",
"BEGIN",
"END",
"require",
"integer",
"less",
"sigtrap",
"strict",
"subs"
]
#----------------------------------------------------------------------------
# Icon Bitmaps - generated by encode_bitmaps.py
#----------------------------------------------------------------------------
from wx import ImageFromStream, BitmapFromImage
from wx import EmptyIcon
import cStringIO
def getPerlData():
return \
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x0e\x00\x00\x00\x10\x08\x06\
\x00\x00\x00&\x94N:\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\x00\
\x01mIDAT(\x91\x9d\x93/\x8e\xf30\x10\xc5\x7f[\xed\x05\xca\x82,Ef\xc6e\x01Vx{\
\x89\x04\x16\x94\x97\x045\xa8\xa0\xa44G\x08\xc9\x01\xa2\x80\x1e $ld\xc9\xa8w\
\x08\xf0\xa2x\x93~\x1f\xda\x91F\xb2\xfd\xe6=\xcd?\x7f\xcd\xf3\x1c\xf8\x83}/\
\x87i\x9a\x000\xc6D\xb0\xeb:\x86a MS\xce\xe7\xf3\x968M\x13}\xdf\xe3\x9cCD\
\xb8\xddn\x18c\xe8\xba\x8e\xb2,\xc9\xb2\x0c\x11\x01\xd8\x90w\xc6\x18\x94R\
\xf1\xa1\xef{\xba\xae\xa3i\x1a\xb4\xd6h\xad)\x8a\x02\xe7\\\xccj\x93\xea\xa2\
\nP\xd75\xd7\xeb\x15\x00\xef\xfdFt)e\xb7\x80\x8b\xbas\x8e$I\xe2}\xc1\x8b\xa2\
\xd8\xf4b\x07\xa0\x94\xe2\xf5za\xad\xc5Z\xcb\xfb\xfdFD\xe8\xfb\x9e\x05\x17\
\x11\x9cs4M\xf3K<\x9dNdY\xc60\x0cx\xef\x11\x11\xea\xbaF)\x85s\x8e\xba\xae)\
\xcb\x12\x11!M\xd3_"\xc0\xfd~\xc7Z\x8bs\x0e\x80$I\xa2:@UU1u\x00\xe6y\x0ek\
\x1f\xc71\x1c\x0e\x87\xd0\xb6m\xd8\xef\xf7\xe1\xf1x\x84\xcb\xe5\x12\xe6y\x0e\
\xc7\xe31\xc6\xed\xf80\x11!\xcb2\xbc\xf7TUE\x9e\xe71=\xadul\xce\xf7\'Qk\x8d\
\xf7\x9e<\xcf\x81\xed&Yk\xb7\xe3\xf84\xa5\x14\xc6\x18D\x84\xe7\xf3\x19\x83\
\xd75\xfe\x97\xb8\x0eXo\xcc2\x9e\x7f\x9a3\x8ech\xdb6|6l\xf15\xf6\xf5\xd7o\
\xf5\x03\xaf\x9f\xfa@\x02\xe4\xdc\xf9\x00\x00\x00\x00IEND\xaeB`\x82'
def getPerlBitmap():
return BitmapFromImage(getPerlImage())
def getPerlImage():
stream = cStringIO.StringIO(getPerlData())
return ImageFromStream(stream)
def getPerlIcon():
icon = EmptyIcon()
icon.CopyFromBitmap(getPerlBitmap())
return icon
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,327 @@
#----------------------------------------------------------------------------
# Name: Service.py
# Purpose: Basic Reusable Service View for wx.lib.pydocview
#
# Author: Morgan Hua
#
# Created: 11/4/04
# CVS-ID: $Id$
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import wx
import wx.lib.docview
import wx.lib.pydocview
_ = wx.GetTranslation
FLOATING_MINIFRAME = -1
class ServiceView(wx.EvtHandler):
""" Basic Service View.
"""
bottomTab = None
#----------------------------------------------------------------------------
# Overridden methods
#----------------------------------------------------------------------------
def __init__(self, service):
wx.EvtHandler.__init__(self)
self._viewFrame = None
self._service = service
self._control = None
self._embeddedWindow = None
def Destroy(self):
wx.EvtHandler.Destroy(self)
def GetFrame(self):
return self._viewFrame
def SetFrame(self, frame):
self._viewFrame = frame
def _CreateControl(self, parent, id):
return None
def GetControl(self):
return self._control
def SetControl(self, control):
self._control = control
def OnCreate(self, doc, flags):
config = wx.ConfigBase_Get()
windowLoc = self._service.GetEmbeddedWindowLocation()
if windowLoc == FLOATING_MINIFRAME:
pos = config.ReadInt(self._service.GetServiceName() + "FrameXLoc", -1), config.ReadInt(self._service.GetServiceName() + "FrameYLoc", -1)
# make sure frame is visible
screenWidth = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)
screenHeight = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)
if pos[0] < 0 or pos[0] >= screenWidth or pos[1] < 0 or pos[1] >= screenHeight:
pos = wx.DefaultPosition
size = wx.Size(config.ReadInt(self._service.GetServiceName() + "FrameXSize", -1), config.ReadInt(self._service.GetServiceName() + "FrameYSize", -1))
title = _(self._service.GetServiceName())
if wx.GetApp().GetDocumentManager().GetFlags() & wx.lib.docview.DOC_SDI and wx.GetApp().GetAppName():
title = title + " - " + wx.GetApp().GetAppName()
frame = wx.MiniFrame(wx.GetApp().GetTopWindow(), -1, title, pos = pos, size = size, style = wx.CLOSE_BOX|wx.CAPTION|wx.SYSTEM_MENU)
wx.EVT_CLOSE(frame, self.OnCloseWindow)
elif wx.GetApp().IsMDI():
self._embeddedWindow = wx.GetApp().GetTopWindow().GetEmbeddedWindow(windowLoc)
frame = self._embeddedWindow
else:
pos = config.ReadInt(self._service.GetServiceName() + "FrameXLoc", -1), config.ReadInt(self._service.GetServiceName() + "FrameYLoc", -1)
# make sure frame is visible
screenWidth = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X)
screenHeight = wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y)
if pos[0] < 0 or pos[0] >= screenWidth or pos[1] < 0 or pos[1] >= screenHeight:
pos = wx.DefaultPosition
size = wx.Size(config.ReadInt(self._service.GetServiceName() + "FrameXSize", -1), config.ReadInt(self._service.GetServiceName() + "FrameYSize", -1))
title = _(self._service.GetServiceName())
if wx.GetApp().GetDocumentManager().GetFlags() & wx.lib.docview.DOC_SDI and wx.GetApp().GetAppName():
title = title + " - " + wx.GetApp().GetAppName()
frame = wx.GetApp().CreateDocumentFrame(self, doc, flags, pos = pos, size = size)
frame.SetTitle(title)
if config.ReadInt(self._service.GetServiceName() + "FrameMaximized", False):
frame.Maximize(True)
wx.EVT_CLOSE(frame, self.OnCloseWindow)
self.SetFrame(frame)
sizer = wx.BoxSizer(wx.VERTICAL)
windowLoc = self._service.GetEmbeddedWindowLocation()
if self._embeddedWindow or windowLoc == FLOATING_MINIFRAME:
if (self._service.GetEmbeddedWindowLocation() == wx.lib.pydocview.EMBEDDED_WINDOW_BOTTOM):
if ServiceView.bottomTab == None:
ServiceView.bottomTab = wx.Notebook(frame, wx.NewId(), (0,0), (100,100), wx.LB_DEFAULT, "Bottom Tab")
sizer.Add(ServiceView.bottomTab, 1, wx.TOP|wx.EXPAND, 4)
def OnFrameResize(event):
ServiceView.bottomTab.SetSize(ServiceView.bottomTab.GetParent().GetSize())
frame.Bind(wx.EVT_SIZE, OnFrameResize)
# Factor this out.
self._control = self._CreateControl(ServiceView.bottomTab, wx.NewId())
if self._control != None:
ServiceView.bottomTab.AddPage(self._control, self._service.GetServiceName())
ServiceView.bottomTab.Layout()
else:
# Factor this out.
self._control = self._CreateControl(frame, wx.NewId())
sizer.Add(self._control)
else:
# Factor this out.
self._control = self._CreateControl(frame, wx.NewId())
sizer.Add(self._control, 1, wx.EXPAND, 0)
frame.SetSizer(sizer)
frame.Layout()
return True
def OnCloseWindow(self, event):
frame = self.GetFrame()
config = wx.ConfigBase_Get()
if frame and not self._embeddedWindow:
if not frame.IsMaximized():
config.WriteInt(self._service.GetServiceName() + "FrameXLoc", frame.GetPositionTuple()[0])
config.WriteInt(self._service.GetServiceName() + "FrameYLoc", frame.GetPositionTuple()[1])
config.WriteInt(self._service.GetServiceName() + "FrameXSize", frame.GetSizeTuple()[0])
config.WriteInt(self._service.GetServiceName() + "FrameYSize", frame.GetSizeTuple()[1])
config.WriteInt(self._service.GetServiceName() + "FrameMaximized", frame.IsMaximized())
if not self._embeddedWindow:
windowLoc = self._service.GetEmbeddedWindowLocation()
if windowLoc == FLOATING_MINIFRAME:
# don't destroy it, just hide it
frame.Hide()
else:
# Call the original OnCloseWindow, could have subclassed SDIDocFrame and MDIDocFrame but this is easier since it will work for both SDI and MDI frames without subclassing both
frame.OnCloseWindow(event)
def Activate(self, activate = True):
""" Dummy function for SDI mode """
pass
def Close(self, deleteWindow = True):
"""
Closes the view by calling OnClose. If deleteWindow is true, this
function should delete the window associated with the view.
"""
if deleteWindow:
self.Destroy()
return True
#----------------------------------------------------------------------------
# Callback Methods
#----------------------------------------------------------------------------
def SetCallback(self, callback):
""" Sets in the event table for a doubleclick to invoke the given callback.
Additional calls to this method overwrites the previous entry and only the last set callback will be invoked.
"""
wx.stc.EVT_STC_DOUBLECLICK(self.GetControl(), self.GetControl().GetId(), callback)
#----------------------------------------------------------------------------
# Display Methods
#----------------------------------------------------------------------------
def IsShown(self):
if not self.GetFrame():
return False
return self.GetFrame().IsShown()
def Hide(self):
self.Show(False)
def Show(self, show = True):
self.GetFrame().Show(show)
if self._embeddedWindow:
mdiParentFrame = wx.GetApp().GetTopWindow()
mdiParentFrame.ShowEmbeddedWindow(self.GetFrame(), show)
class Service(wx.lib.pydocview.DocService):
#----------------------------------------------------------------------------
# Constants
#----------------------------------------------------------------------------
SHOW_WINDOW = wx.NewId() # keep this line for each subclass, need unique ID for each Service
def __init__(self, serviceName, embeddedWindowLocation = wx.lib.pydocview.EMBEDDED_WINDOW_LEFT):
self._serviceName = serviceName
self._embeddedWindowLocation = embeddedWindowLocation
self._view = None
def GetEmbeddedWindowLocation(self):
return self._embeddedWindowLocation
def SetEmbeddedWindowLocation(self, embeddedWindowLocation):
self._embeddedWindowLocation = embeddedWindowLocation
def InstallControls(self, frame, menuBar = None, toolBar = None, statusBar = None, document = None):
viewMenu = menuBar.GetMenu(menuBar.FindMenu(_("&View")))
menuItemPos = self.GetMenuItemPos(viewMenu, viewMenu.FindItem(_("&Status Bar"))) + 1
viewMenu.InsertCheckItem(menuItemPos, self.SHOW_WINDOW, self.GetMenuString(), self.GetMenuDescr())
wx.EVT_MENU(frame, self.SHOW_WINDOW, frame.ProcessEvent)
wx.EVT_UPDATE_UI(frame, self.SHOW_WINDOW, frame.ProcessUpdateUIEvent)
return True
def GetServiceName(self):
""" String used to save out Service View configuration information """
return self._serviceName
def GetMenuString(self):
""" Need to override this method to provide menu item for showing Service View """
return _(self.GetServiceName())
def GetMenuDescr(self):
""" Need to override this method to provide menu item for showing Service View """
return _("Show or hides the %s window") % self.GetMenuString()
#----------------------------------------------------------------------------
# Event Processing Methods
#----------------------------------------------------------------------------
def ProcessEvent(self, event):
id = event.GetId()
if id == self.SHOW_WINDOW:
self.ToggleWindow(event)
return True
else:
return False
def ProcessUpdateUIEvent(self, event):
id = event.GetId()
if id == self.SHOW_WINDOW:
event.Check(self._view != None and self._view.IsShown())
event.Enable(True)
return True
else:
return False
#----------------------------------------------------------------------------
# View Methods
#----------------------------------------------------------------------------
def _CreateView(self):
""" This method needs to be overridden with corresponding ServiceView """
return ServiceView(self)
def GetView(self):
# Window Menu Service Method
return self._view
def SetView(self, view):
self._view = view
def ShowWindow(self, show = True):
if show:
if self._view:
if not self._view.IsShown():
self._view.Show()
else:
view = self._CreateView()
view.OnCreate(None, flags = 0)
self.SetView(view)
else:
if self._view:
if self._view.IsShown():
self._view.Hide()
def HideWindow(self):
self.ShowWindow(False)
def ToggleWindow(self, event):
show = event.IsChecked()
wx.ConfigBase_Get().WriteInt(self.GetServiceName()+"Shown", show)
self.ShowWindow(show)
def OnCloseFrame(self, event):
if not self._view:
return True
if wx.GetApp().IsMDI():
self._view.OnCloseWindow(event)
# This is called when any SDI frame is closed, so need to check if message window is closing or some other window
elif self._view == event.GetEventObject().GetView():
self.SetView(None)
return True
@@ -0,0 +1,48 @@
#----------------------------------------------------------------------------
# Name: TabbedView.py
# Purpose:
#
# Author: Peter Yared
#
# Created: 8/17/04
# CVS-ID: $Id$
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import wx
import wx.lib.docview
class TabbedView(dict, wx.lib.docview.View):
#----------------------------------------------------------------------------
# Overridden methods
#----------------------------------------------------------------------------
def __init__(self):
wx.lib.docview.View.__init__(self)
self._views = {}
self._currentView = None
def OnCreate(self, doc, flags):
frame = wx.GetApp().CreateDocumentFrame(self, doc, flags)
sizer = wx.BoxSizer()
self._notebook = wx.Notebook(frame, -1, style = wx.NB_BOTTOM)
self.Activate()
return True
def AddView(self, viewName, view):
self._notebook.AddPage(wx.Panel(self._notebook, -1), viewName)
self._currentView = view
self._views[viewName] = view
def __getattr__(self, attrname):
return getattr(self._currentView, attrname)
def SetView(self, viewName):
self._currentview = self._views[viewName]
@@ -0,0 +1,115 @@
#----------------------------------------------------------------------------
# Name: UICommon.py
# Purpose: Shared UI stuff
#
# Author: Matt Fryer
#
# Created: 3/10/05
# CVS-ID: $Id$
# Copyright: (c) 2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import os
import os.path
import wx
import ProjectEditor
_ = wx.GetTranslation
def CreateDirectoryControl( parent, fileLabel, dirLabel, fileExtension, startingName="", startingDirectory=""):
nameControl = wx.TextCtrl(parent, -1, startingName, size=(-1,-1))
nameLabelText = wx.StaticText(parent, -1, fileLabel)
dirLabelText = wx.StaticText(parent, -1, dirLabel)
dirControl = wx.TextCtrl(parent, -1, startingDirectory, size=(-1,-1))
dirControl.SetToolTipString(startingDirectory)
button = wx.Button(parent, -1, _("Browse..."), size=(60,-1))
def OnFindDirClick(event):
name = ""
nameCtrlValue = nameControl.GetValue()
if nameCtrlValue:
root, ext = os.path.splitext( nameCtrlValue )
if ext == '.' + fileExtension:
name = nameCtrlValue
else:
name = _("%s.%s") % (nameCtrlValue, fileExtension)
path = wx.FileSelector(_("Choose a filename and directory"),
"",
"%s" % name,
wildcard=_("*.%s") % fileExtension ,
flags=wx.SAVE,
parent=parent)
if path:
dir, filename = os.path.split(path)
dirControl.SetValue(dir)
dirControl.SetToolTipString(dir)
nameControl.SetValue(filename)
parent.Bind(wx.EVT_BUTTON, OnFindDirClick, button)
def Validate(allowOverwriteOnPrompt=False):
if nameControl.GetValue() == "":
wx.MessageBox(_("Please provide a filename."), _("Provide a Filename"))
return False
if nameControl.GetValue().find(' ') != -1:
wx.MessageBox(_("Please provide a filename that does not contains spaces."), _("Spaces in Filename"))
return False
filePath = os.path.join(dirControl.GetValue(), MakeNameEndInExtension(nameControl.GetValue(), "." + fileExtension))
if os.path.exists(filePath):
if allowOverwriteOnPrompt:
res = wx.MessageBox(_("That file already exists. Would you like to overwrite it."), "File Exists", style=wx.YES_NO|wx.NO_DEFAULT)
return (res == wx.YES)
else:
wx.MessageBox(_("That file already exists. Please choose a different name."), "File Exists")
return False
return True
HALF_SPACE = 5
flexGridSizer = wx.FlexGridSizer(cols = 3, vgap = HALF_SPACE, hgap = HALF_SPACE)
flexGridSizer.AddGrowableCol(1,1)
flexGridSizer.Add(nameLabelText, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.TOP|wx.RIGHT, HALF_SPACE)
flexGridSizer.Add(nameControl, 2, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
flexGridSizer.Add(button, flag=wx.ALIGN_RIGHT|wx.LEFT, border=HALF_SPACE)
flexGridSizer.Add(dirLabelText, flag=wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT|wx.TOP|wx.RIGHT, border=HALF_SPACE)
flexGridSizer.Add(dirControl, 2, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND, border=HALF_SPACE)
flexGridSizer.Add(wx.StaticText(parent, -1, ""), 0)
return nameControl, dirControl, flexGridSizer, Validate
def AddFilesToCurrentProject(paths, save=False):
projectService = wx.GetApp().GetService(ProjectEditor.ProjectService)
if projectService:
projectDocument = projectService.GetCurrentProject()
if projectDocument:
files = projectDocument.GetFiles()
for path in paths:
if path in files:
paths.remove(path)
if paths:
projectDocument.GetCommandProcessor().Submit(ProjectEditor.ProjectAddFilesCommand(projectDocument, paths))
if save:
projectDocument.OnSaveDocument(projectDocument.GetFilename())
def MakeNameEndInExtension(name, extension):
if not name:
return name
root, ext = os.path.splitext(name)
if ext == extension:
return name
else:
return name + extension
# Lame
def PluralName(name):
if not name:
return name
if name.endswith('us'):
return name[0:-2] + 'ii'
elif name.endswith('s'):
return name
elif name.endswith('y'):
return name[0:-1] + 'ies'
else:
return name + 's'
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,165 @@
#----------------------------------------------------------------------------
# Name: XmlEditor.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 string
import STCTextEditor
import CodeEditor
class XmlDocument(CodeEditor.CodeDocument):
pass
class XmlView(CodeEditor.CodeView):
def GetCtrlClass(self):
""" Used in split window to instantiate new instances """
return XmlCtrl
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 XMLKEYWORDS
class XmlService(CodeEditor.CodeService):
def __init__(self):
CodeEditor.CodeService.__init__(self)
class XmlCtrl(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_XML)
self.SetProperty("fold.html", "1")
def GetMatchingBraces(self):
return "<>[]{}()"
def CanWordWrap(self):
return True
def SetViewDefaults(self):
CodeEditor.CodeCtrl.SetViewDefaults(self, configPrefix = "Xml", hasWordWrap = True, hasTabs = True)
def GetFontAndColorFromConfig(self):
return CodeEditor.CodeCtrl.GetFontAndColorFromConfig(self, configPrefix = "Xml")
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 XmlOptionsPanel(STCTextEditor.TextOptionsPanel):
def __init__(self, parent, id):
STCTextEditor.TextOptionsPanel.__init__(self, parent, id, configPrefix = "Xml", label = "XML", hasWordWrap = True, hasTabs = True)
XMLKEYWORDS = [
"ag:connectionstring", "ag:datasource", "ag:editorBounds", "ag:label", "ag:name", "ag:shortLabel", "ag:type",
"element", "fractionDigits", "length", "minOccurs", "name", "objtype", "refer", "schema", "type", "xpath", "xmlns",
"xs:complexType", "xs:element", "xs:enumeration", "xs:field", "xs:key", "xs:keyref", "xs:schema", "xs:selector"
]
#----------------------------------------------------------------------------
# Icon Bitmaps - generated by encode_bitmaps.py
#----------------------------------------------------------------------------
from wx import ImageFromStream, BitmapFromImage
from wx import EmptyIcon
import cStringIO
def getXMLData():
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\x01\x18IDAT8\x8d\xed\x92=N\xc3P\x0c\xc7\x7f~\xc9K\xd2\xa0\x16\xa9\xdc\
\x84+\xf4\x06\x1c\xa1\x12\x133\xa7`\xea\x05\xba\xc0\xc0\xd0\x93\x80*uc``e\t\
\x82\xb6J\xf3Q?3D\x04\x81`\xea\xc2\x80\x17K\xb6\xfc\xff\xb0-ff\x1c\x10\xee\
\x90\xe1\xbf\x01\x10s}\x0em\tu\t\xfb\x06\xcbFP\xad\x11\x17\x81\x196\x18!\xdb\
\x02\xd2#hk\xc8\x8f\t\xc1p\x89g\xb9\\\x11\xdb\xfd-\xbcn\x91\xa8C\x94,\x81\
\xaa\xe9\x19\xe4\x1b\xa3}R\xf3\xf0\x08\x0e\x9f\x81\xef\x9c\x94s\x83\xaa\xe92\
P\xcf\nv\xa7g\xd4\xb3\xa2\xef\xaf\xc5#i\x04\x89#\x8a\x05\'m\r)\x84\r\xe4S\
\xa1\x9c\x1b\xf9\xb4\xe3\xd5\xe1\x18?\xb9@\x87\xe3^\x81\xbe\xb5H\xab`\x013\
\xc3\xa9\xf3h\x15pC\xfa\xe1\x0f\x05\x00\xf1\xd5\xe4\x8b\x85la\x10@[0q\x88]\
\x9e\x18/\x05\xe8/k\xde\x01\x83\x1f\xea\x19,\x9e\x1c\xf1\xcdj\xc3\xae\x01jP\
\x05\x9fv\x07q1\x88\x83(\x8f\xd0\x8d"1h\x05\xba\x077\x80$\x87\xbb\xe7\x80\
\xfc\xbf\xf2\xe1\x00\xef\x8c\xb8x\x06\x07\xd1$\xff\x00\x00\x00\x00IEND\xaeB`\
\x82'
def getXMLBitmap():
return BitmapFromImage(getXMLImage())
def getXMLImage():
stream = cStringIO.StringIO(getXMLData())
return ImageFromStream(stream)
def getXMLIcon():
icon = EmptyIcon()
icon.CopyFromBitmap(getXMLBitmap())
return icon
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,7 @@
Ctrl-Space in any editor does code completion.
Right-clicking on something in the 'Thing' column of the debugger's frame tab may allow you to introspect it for more information.
Right-Mouse-Click in Outline window allows you to change display sorting.
In an editor, you can add line markers via Ctrl-M and jump to the next marker with F4 or previous marker with Shift-F4.
In an editor. you can use the numpad + and - keys to toggle folding.
In 'Find in Directory', if you specify a file, it will display all matches in the Message Window.
Breakpoints for the debugger can be set while the process is running
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,72 @@
import logging
import cStringIO
import traceback
import sys
import string
import os
def classForName(className):
pathList = className.split('.')
moduleName = string.join(pathList[:-1], '.')
code = __import__(moduleName)
for name in pathList[1:]:
code = code.__dict__[name]
return code
def hasattrignorecase(object, name):
for attr in dir(object):
if attr.lower() == name.lower():
return True
for attr in dir(object):
if attr.lower() == '_' + name.lower():
return True
return False
def setattrignorecase(object, name, value):
for attr in object.__dict__:
if attr.lower() == name.lower():
object.__dict__[attr] = value
return
## for attr in dir(object):
## if attr.lower() == '_' + name.lower():
## object.__dict__[attr] = value
## return
object.__dict__[name] = value
def getattrignorecase(object, name):
for attr in object.__dict__:
if attr.lower() == name.lower():
return object.__dict__[attr]
## for attr in dir(object):
## if attr.lower() == '_' + name.lower():
## return object.__dict__[attr]
return object.__dict__[name]
def defaultLoad(fileObject):
xml = fileObject.read()
loadedObject = xmlmarshaller.unmarshal(xml)
if hasattr(fileObject, 'name'):
loadedObject.fileName = os.path.abspath(fileObject.name)
loadedObject.initialize()
return loadedObject
def defaultSave(fileObject, objectToSave):
xml = xmlmarshaller.marshal(objectToSave, prettyPrint=True)
fileObject.write(xml)
def clone(objectToClone):
xml = xmlmarshaller.marshal(objectToClone, prettyPrint=True)
clonedObject = xmlmarshaller.unmarshal(xml)
if hasattr(objectToClone, 'fileName'):
clonedObject.fileName = objectToClone.fileName
clonedObject.initialize()
return clonedObject
def exceptionToString(e):
sio = cStringIO.StringIO()
traceback.print_exception(e.__class__, e, sys.exc_traceback, file=sio)
return sio.getvalue()
@@ -0,0 +1,84 @@
#----------------------------------------------------------------------------
# Name: aglogging.py
# Purpose: Utilities to help with logging
#
# Author: Jeff Norton
#
# Created: 01/04/05
# CVS-ID: $Id$
# Copyright: (c) 2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import sys
import os
import re
import traceback
global agTestMode
agTestMode = False
def setTestMode(mode):
global agTestMode
if (mode):
agTestMode = True
else:
agTestMode = False
def getTestMode():
global agTestMode
return agTestMode
def testMode(normalObj, testObj=None):
if getTestMode():
return testObj
return normalObj
def toDiffableString(value):
s = repr(value)
ds = ""
i = s.find(" at 0x")
start = 0
while (i >= 0):
j = s.find(">", i)
if (j < i):
break
ds += s[start:i]
start = j
i = s.find(" at 0x", start)
return ds + s[start:]
def removeFileRefs(str):
str = re.sub(r'(?<=File ")[^"]*(\\[^\\]*")(, line )[0-9]*', _fileNameReplacement, str)
return str
def _fileNameReplacement(match):
return "...%s" % match.group(1)
def getTraceback():
extype, val, tb = sys.exc_info()
tbs = "\n"
for s in traceback.format_tb(tb):
tbs += s
return tbs
def reportException(out=None, stacktrace=False, diffable=False):
extype, val, t = sys.exc_info()
if (diffable):
exstr = removeFileRefs(str(val))
else:
exstr = str(val)
if (out == None):
print "Got Exception = %s: %s" % (extype, exstr)
else:
print >> out, "Got Exception = %s: %s" % (extype, exstr)
if (stacktrace):
fmt = traceback.format_exception(extype, val, t)
for s in fmt:
if (diffable):
s = removeFileRefs(s)
if (out == None):
print s
else:
print >> out, s
@@ -0,0 +1,87 @@
#----------------------------------------------------------------------------
# Name: cachedloader.py
# Purpose:
#
# Author: Joel Hare
#
# Created: 8/31/04
# CVS-ID: $Id$
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import copy
import os.path
import string
import cStringIO
import time
# TODO: Instantiate the database and create a pool
class CachedLoader(object):
def __init__(self):
self.cache = {}
self.baseLoadDir = None
def fullPath(self, fileName):
if os.path.isabs(fileName):
absPath = fileName
elif self.baseLoadDir:
absPath = os.path.join(self.baseLoadDir, fileName)
else:
absPath = os.path.abspath(fileName)
return absPath
def setPrototype(self, fileName, loadedFile):
absPath = self.fullPath(fileName)
mtime = time.time() + 31536000.0 # Make sure prototypes aren't replaced by files on disk
self.cache[absPath] = (mtime, loadedFile)
def update(self, loader):
self.cache.update(loader.cache)
def clear(self):
self.cache.clear()
def delete(self, fileName):
absPath = self.fullPath(fileName)
del self.cache[absPath]
def needsLoad(self, fileName):
absPath = self.fullPath(fileName)
try:
cached = self.cache[absPath]
cachedTime = cached[0]
if cachedTime >= os.path.getmtime(absPath):
return False
except KeyError:
pass
return True
def load(self, fileName, loader):
absPath = self.fullPath(fileName)
loadedFile = None
try:
cached = self.cache[absPath]
except KeyError:
cached = None
if cached:
cachedTime = cached[0]
# ToDO We might need smarter logic for checking if a file needs to be reloaded
# ToDo We need a way to disable checking if this is a production server
if cachedTime >= os.path.getmtime(absPath):
loadedFile = cached[1]
if not loadedFile:
targetFile = file(absPath)
try:
mtime = os.path.getmtime(absPath)
loadedFile = loader(targetFile)
self.cache[absPath] = (mtime, loadedFile)
finally:
targetFile.close()
return loadedFile
@@ -0,0 +1,145 @@
#----------------------------------------------------------------------------
# Name: dependencymgr.py
# Purpose: Dependency Manager
#
# Author: Jeff Norton
#
# Created: 01/28/05
# CVS-ID: $Id$
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
#----------------------------------------------------------------------------
DM_NO_ID = 0
DM_ID_ATTR = "_DependencyMgr__ID"
##class ManageableObject(object):
##
## def __init__(self):
## self.__id = DM_NO_ID
##
## def __repr__(self):
## return "<ManageableObject id = %s>" % self.__id
##
## def __getID(self):
## return self.__id
##
## def __setID(self, value):
## if (self.__id != DM_NO_ID):
## raise DependencyMgrException("Cannot set the dependency ID on object %s to \"%s\" because it already has one (\"%s\")." % (repr(self), value, self.__id))
## self.__id = value
##
## _DependencyMgr__ID = property(__getID, __setID)
class DependencyMgr(object):
def __init__(self):
self.clear()
def clear(self):
self.__dependencies = {}
self.__lastID = DM_NO_ID
def addDependency(self, parent, child):
pid = self._initObjectID(parent)
try:
parentCollection = self.__dependencies[pid]
except KeyError:
parentCollection = self._newDependencyCollection()
self.__dependencies[pid] = parentCollection
if (child not in parentCollection):
parentCollection.append(child)
def removeDependency(self, parent, child):
pid = self._getObjectID(parent)
if (pid != DM_NO_ID):
try:
parentCollection = self.__dependencies[pid]
parentCollection.remove(child)
if (len(parentCollection) == 0):
del self.__dependencies[pid]
except KeyError, ValueError:
pass
def clearDependencies(self, parent):
"Returns a list of objects or an empty list if no dependencies exist as for getDependencies, and then removes the dependency list."
pid = self._getObjectID(parent)
try:
deps = self.__dependencies[pid]
del self.__dependencies[pid]
return deps
except KeyError:
return []
def hasDependency(self, parent):
"Returns a boolean"
return (self._getObjectID(parent) in self.__dependencies)
def getDependencies(self, parent):
"Returns a list of objects or an empty list if no dependencies exist."
try:
return self.__dependencies[self._getObjectID(parent)]
except KeyError:
return []
def dumpState(self, out):
"Writes the state of the dependency manager (as reported by getState) to out"
for line in self.getState():
print >> out, line
def getState(self):
"Returns the state of the dependency manager including all managed objects as a list of strings"
out = []
out.append("DependencyMgr %s has %i parent objects, last id assigned is %i" % (repr(self), len(self.__dependencies), self.__lastID))
for key, val in self.__dependencies.iteritems():
out.append("Object %s has dependents: %s " % (repr(key), ", ".join([repr(d) for d in val])))
return out
def _initObjectID(self, obj):
try:
id = getattr(obj, DM_ID_ATTR)
except AttributeError:
id = DM_NO_ID
if (id == DM_NO_ID):
id = self._newID()
setattr(obj, DM_ID_ATTR, id)
return id
def _getObjectID(self, obj):
try:
id = getattr(obj, DM_ID_ATTR)
except AttributeError:
id = DM_NO_ID
return id
def _newID(self):
self.__lastID += 1
return self.__lastID
def _newDependencyCollection(self):
return []
globalDM = DependencyMgr()
def addDependency(parent, child):
getGlobalDM().addDependency(parent, child)
def removeDependency(parent, child):
getGlobalDM().removeDependency(parent, child)
def clearDependencies(parent):
return getGlobalDM().clearDependencies(parent)
def hasDependency(parent):
return getGlobalDM().hasDependency(parent)
def getDependencies(parent):
return getGlobalDM().getDependencies(parent)
def getState():
return getGlobalDM().getState()
def dumpState(out):
getGlobalDM().dumpState(out)
def getGlobalDM():
return globalDM
@@ -0,0 +1,39 @@
#----------------------------------------------------------------------------
# Name: fileutils.py
# Purpose: Active grid miscellaneous utilities
#
# Author: Jeff Norton
#
# Created: 12/10/04
# CVS-ID: $Id$
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import os
def createFile(filename, mode='w'):
f = None
try:
f = file(filename, mode)
except:
os.makedirs(filename[:filename.rindex(os.sep)])
f = file(filename, mode)
return f
def compareFiles(file1, file2):
file1.seek(0)
file2.seek(0)
while True:
line1 = file1.readline()
line2 = file2.readline()
if (len(line1) == 0):
if (len(line2) == 0):
return 0
else:
return -1
elif (len(line2) == 0):
return -1
elif (line1 != line2):
return -1
@@ -0,0 +1,36 @@
#----------------------------------------------------------------------------
# Name: gettersetter.py
# Purpose:
#
# Author: Peter Yared
#
# Created: 7/28/04
# CVS-ID: $Id$
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
def gettersetter(list):
for attr in list:
lowercase = attr[0].lower() + attr[1:]
uppercase = attr[0].upper() + attr[1:]
print " def get%s(self):" % uppercase
print " return self._%s" % lowercase
print
print " def set%s(self, %s):" % (uppercase, lowercase)
print " self._%s = %s" % (lowercase, lowercase)
print
def listgettersetter(list):
for attr in list:
lowercase = attr[0].lower() + attr[1:]
uppercase = attr[0].upper() + attr[1:]
print " def get%s(self):" % uppercase
print " return self._%s" % lowercase
print
print " def add%s(self, %s):" % (uppercase[:-1], lowercase[:-1])
print " self._%s.append(%s)" % (lowercase, lowercase[:-1])
print
print " def remove%s(self, %s):" % (uppercase[:-1], lowercase[:-1])
print " self._%s.remove(%s)" % (lowercase, lowercase[:-1])
print
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,183 @@
#----------------------------------------------------------------------------
# Name: xmlmarshallertests.py
# Purpose:
#
# Author: John Spurling
#
# Created: 8/16/04
# CVS-ID: $Id$
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import unittest
import xmlmarshaller
from xmlprettyprinter import xmlprettyprint
marshalledPersonObject = """
<person objtype="Person">
<firstName>Albert</firstName>
<lastName>Camus</lastName>
<address>23 Absurd St.</address>
<city>Ennui</city>
<state>MO</state>
<zip>54321</zip>
<_phoneNumber>808-303-2323</_phoneNumber>
<favoriteWords objtype="list">
<item>angst</item>
<item>ennui</item>
<item>existence</item>
</favoriteWords>
<weight objtype="float">150</weight>
</person>
"""
marshalledint = '''
<item objtype="int">23</item>
'''
marshalledlist = '''
<mylist objtype="list">
<item>foo</item>
<item>bar</item>
</mylist>
'''
## a dummy class taken from the old XmlMarshaller module.
## class Person:
## def __init__(self):
## # These are not necessary but are nice if you want to tailor
## # the Python object <-> XML binding
## # The xml element name to use for this object, otherwise it
## # will use a fully qualified Python name like __main__.Person
## # which can be ugly.
## self.__xmlname__ = "person"
## self.firstName = None
## self.lastName = None
## self.addressLine1 = None
## self.addressLine2 = None
## self.city = None
## self.state = None
## self.zip = None
## self._phoneNumber = None
## self.favoriteWords = None
## self.weight = None
class Person:
__xmlflattensequence__ = {'asequence': ('the_earth_is_flat',)}
class XmlMarshallerTestFunctions(unittest.TestCase):
def setUp(self):
'''common setup code goes here.'''
pass
def testInt(self):
xml = xmlmarshaller.marshal(1)
print "\n#########################################"
print "# testString test case #"
print "#########################################"
print "marshalled int object:\n"
print xmlprettyprint(xml)
def testDict(self):
xml = xmlmarshaller.marshal({'one': 1,
'two': 2,
'three': 3})
print "\n#########################################"
print "# testString test case #"
print "#########################################"
print "marshalled dict object:\n"
print xmlprettyprint(xml)
def testBool(self):
xmltrue = xmlmarshaller.marshal(True)
xmlfalse = xmlmarshaller.marshal(False)
print "\n#########################################"
print "# testBool test case #"
print "#########################################"
print "marshalled boolean true object:\n"
print xmlprettyprint(xmltrue)
print "\nmarshalled boolean false object:\n"
print xmlprettyprint(xmlfalse)
pytrue = xmlmarshaller.unmarshal(xmltrue)
assert pytrue is True
pyfalse = xmlmarshaller.unmarshal(xmlfalse)
assert pyfalse is False
def testString(self):
xml = xmlmarshaller.marshal(
"all your marshalled objects are belong to us")
print "\n#########################################"
print "# testString test case #"
print "#########################################"
print xmlprettyprint(xml)
def testEmptyElement(self):
person = Person()
person.firstName = "Albert"
person.__xmlattributes__ = ('firstName',)
xml = xmlmarshaller.marshal(person, 'person')
print "\n#########################################"
print "# testEmptyElement test case #"
print "#########################################"
print xml
assert (xml == """<person objtype="__main__.Person" firstName="Albert"/>""")
def testXMLFlattenSequence(self):
person = Person()
person.asequence = ('one', 'two')
xml = xmlmarshaller.marshal(person, 'person')
print "\n#########################################"
print "# testXMLFlattenSequence test case #"
print "#########################################"
print xml
assert (xml == """<person objtype="__main__.Person"><the_earth_is_flat>one</the_earth_is_flat><the_earth_is_flat>two</the_earth_is_flat></person>""")
unmarshalledperson = xmlmarshaller.unmarshal(xml)
assert(hasattr(unmarshalledperson, 'asequence'))
assert(len(unmarshalledperson.asequence) == 2)
def testInstance(self):
print "\n#########################################"
print "# testInstance test case #"
print "#########################################"
class Foo:
def __init__(self):
self.alist = [1,2]
self.astring = 'f00'
f = Foo()
xml = xmlmarshaller.marshal(f, 'foo')
print xml
def testPerson(self):
person = Person()
person.firstName = "Albert"
person.lastName = "Camus"
person.addressLine1 = "23 Absurd St."
person.city = "Ennui"
person.state = "MO"
person.zip = "54321"
person._phoneNumber = "808-303-2323"
person.favoriteWords = ['angst', 'ennui', 'existence']
person.weight = 150
# __xmlattributes__ = ('fabulousness',)
person.fabulousness = "tres tres"
xml = xmlmarshaller.marshal(person)
print "\n#########################################"
print "# testPerson test case #"
print "#########################################"
print "Person object marshalled into XML:\n"
print xml
# When encountering a "person" element, use the Person class
## elementMappings = { "person" : Person }
## obj = unmarshal(xml, elementMappings = elementMappings)
## print "Person object recreated from XML with attribute types indicated:"
## print obj.person.__class__
## for (attr, value) in obj.person.__dict__.items():
## if not attr.startswith("__"):
## print attr, "=", value, type(value)
## print
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,63 @@
#----------------------------------------------------------------------------
# Name: xmlprettyprinter.py
# Purpose:
#
# Author: John Spurling
#
# Created: 9/21/04
# CVS-ID: $Id$
# Copyright: (c) 2004-2005 ActiveGrid, Inc.
# License: wxWindows License
#----------------------------------------------------------------------------
import xml.sax
import xml.sax.handler
class XMLPrettyPrinter(xml.sax.ContentHandler):
def __init__(self, indentationChar=' ', newlineChar='\n'):
self.xmlOutput = ''
self.indentationLevel = 0
self.indentationChar = indentationChar
self.elementStack = []
self.newlineChar = newlineChar
self.hitCharData = False
## ContentHandler methods
def startElement(self, name, attrs):
indentation = self.newlineChar + (self.indentationLevel * self.indentationChar)
# build attribute string
attrstring = ''
for attr in attrs.getNames():
value = attrs[attr]
attrstring += ' %s="%s"' % (attr, value)
self.xmlOutput += '%s<%s%s>' % (indentation, name, attrstring)
self.indentationLevel += 1
self.elementStack.append(name)
self.hitCharData = False
def characters(self, content):
self.xmlOutput += content
self.hitCharData = True
def endElement(self, name):
self.indentationLevel -= 1
indentation = ''
if not self.hitCharData:
## indentation += self.newlineChar + (self.indentationLevel * self.indentationChar)
indentation += self.indentationLevel * self.indentationChar
else:
self.hitCharData = False
self.xmlOutput += '%s</%s>%s' % (indentation, self.elementStack.pop(), self.newlineChar)
def getXMLString(self):
return self.xmlOutput[1:]
def xmlprettyprint(xmlstr, spaces=4):
xpp = XMLPrettyPrinter(indentationChar=' ' * spaces)
xml.sax.parseString(xmlstr, xpp)
return xpp.getXMLString()
if __name__ == '__main__':
simpleTestString = """<one>some text<two anattr="booga">two's data</two></one>"""
print prettyprint(simpleTestString)