Commit 40f9b7bd authored by Just van Rossum's avatar Just van Rossum

First Checked In.

parent f59a89b5
import sys
import os
import buildtools
import Res
import py_resource
buildtools.DEBUG=1
template = buildtools.findtemplate()
ide_home = os.path.join(sys.exec_prefix, ":Mac:Tools:IDE")
mainfilename = os.path.join(ide_home, "PythonIDE.py")
dstfilename = os.path.join(sys.exec_prefix, "Python IDE")
buildtools.process(template, mainfilename, dstfilename, 1)
targetref = Res.OpenResFile(dstfilename)
Res.UseResFile(targetref)
files = os.listdir(ide_home)
files = filter(lambda x: x[-3:] == '.py' and x not in ("BuildIDE.py", "PythonIDE.py"), files)
for name in files:
print "adding", name
fullpath = os.path.join(ide_home, name)
id, name = py_resource.frompyfile(fullpath, name[:-3], preload=1,
ispackage=0)
wresref = Res.OpenResFile(os.path.join(ide_home, "Widgets.rsrc"))
buildtools.copyres(wresref, targetref, [], 0)
"""usage:
newsettings = FontDialog(('Chicago', 0, 12, (0, 0, 0))) # font name or id, style flags, size, color (color is ignored)
if newsettings:
fontsettings, tabsettings = newsettings
font, style, size, color = fontsettings # 'font' is always the font name, not the id number
# do something
"""
import W
import PyEdit
import TextEdit
import Qd
import string
import types
import sys
import MacOS
if hasattr(MacOS, "SysBeep"):
SysBeep = MacOS.SysBeep
else:
def SysBeep(*args):
pass
_stylenames = ["Plain", "Bold", "Italic", "Underline", "Outline", "Shadow", "Condensed", "Extended"]
class _FontDialog:
#def __del__(self):
# print "doei!"
def __init__(self, fontsettings, tabsettings):
leftmargin = 60
leftmargin2 = leftmargin - 16
self.w = W.ModalDialog((440, 180), 'Font settings')
self.w.fonttitle = W.TextBox((10, 12, leftmargin2, 14), "Font:", TextEdit.teJustRight)
self.w.pop = W.FontMenu((leftmargin, 10, 16, 16), self.setfont)
self.w.fontname = W.TextBox((leftmargin + 20, 12, 150, 14))
self.w.sizetitle = W.TextBox((10, 38, leftmargin2, 14), "Size:", TextEdit.teJustRight)
self.w.sizeedit = W.EditText((leftmargin, 35, 40, 20), "", self.checksize)
styletop = 64
self.w.styletitle = W.TextBox((10, styletop + 2, leftmargin2, 14), "Style:", TextEdit.teJustRight)
for i in range(len(_stylenames)):
top = styletop + (i % 4) * 20
left = leftmargin + 80 * (i > 3) - 2
if i:
self.w[i] = W.CheckBox((left, top, 76, 16), _stylenames[i], self.dostyle)
else:
self.w[i] = W.CheckBox((left, top, 70, 16), _stylenames[i], self.doplain)
if tabsettings:
self.lasttab, self.tabmode = tabsettings
self.w.tabsizetitle = W.TextBox((10, -26, leftmargin2, 14), "Tabsize:", TextEdit.teJustRight)
self.w.tabsizeedit = W.EditText((leftmargin, -29, 40, 20), "", self.checktab)
self.w.tabsizeedit.set(`self.lasttab`)
radiobuttons = []
self.w.tabsizechars = W.RadioButton((leftmargin + 48, -26, 55, 14), "Spaces",
radiobuttons, self.toggletabmode)
self.w.tabsizepixels = W.RadioButton((leftmargin + 110, -26, 55, 14), "Pixels",
radiobuttons, self.toggletabmode)
if self.tabmode:
self.w.tabsizechars.set(1)
else:
self.w.tabsizepixels.set(1)
else:
self.tabmode = None
self.w.cancelbutton = W.Button((-180, -26, 80, 16), "Cancel", self.cancel)
self.w.donebutton = W.Button((-90, -26, 80, 16), "Done", self.done)
sampletext = "Sample text."
self.w.sample = W.EditText((230, 10, -10, 130), sampletext,
fontsettings = fontsettings, tabsettings = tabsettings)
self.w.setdefaultbutton(self.w.donebutton)
self.w.bind('cmd.', self.w.cancelbutton.push)
self.w.bind('cmdw', self.w.donebutton.push)
self.lastsize = fontsettings[2]
self._rv = None
self.set(fontsettings)
self.w.open()
def toggletabmode(self, onoff):
if self.w.tabsizechars.get():
tabmode = 1
else:
tabmode = 0
if self.tabmode <> tabmode:
port = self.w.wid.GetWindowPort()
(font, style, size, color), (tabsize, dummy) = self.get()
savesettings = W.GetPortFontSettings(port)
W.SetPortFontSettings(port, (font, style, size))
spacewidth = Qd.StringWidth(' ')
W.SetPortFontSettings(port, savesettings)
if tabmode:
# convert pixels to spaces
self.lasttab = int(round(float(tabsize) / spacewidth))
else:
# convert spaces to pixels
self.lasttab = spacewidth * tabsize
self.w.tabsizeedit.set(`self.lasttab`)
self.tabmode = tabmode
self.doit()
def set(self, fontsettings):
font, style, size, color = fontsettings
if type(font) <> types.StringType:
import Res
res = Res.GetResource('FOND', font)
font = res.GetResInfo()[2]
self.w.fontname.set(font)
self.w.sizeedit.set(str(size))
if style:
for i in range(1, len(_stylenames)):
self.w[i].set(style & 0x01)
style = style >> 1
else:
self.w[0].set(1)
def get(self):
font = self.w.fontname.get()
style = 0
if not self.w[0].get():
flag = 0x01
for i in range(1, len(_stylenames)):
if self.w[i].get():
style = style | flag
flag = flag << 1
size = self.lastsize
if self.tabmode is None:
return (font, style, size, (0, 0, 0)), (32, 0)
else:
return (font, style, size, (0, 0, 0)), (self.lasttab, self.tabmode)
def doit(self):
if self.w[0].get():
style = 0
else:
style = 0
for i in range(1, len(_stylenames)):
if self.w[i].get():
style = style | 2 ** (i - 1)
#self.w.sample.set(`style`)
fontsettings, tabsettings = self.get()
self.w.sample.setfontsettings(fontsettings)
self.w.sample.settabsettings(tabsettings)
def checktab(self):
tabsize = self.w.tabsizeedit.get()
if not tabsize:
return
try:
tabsize = string.atoi(tabsize)
except (ValueError, OverflowError):
good = 0
sys.exc_traceback = None
else:
good = 1 <= tabsize <= 500
if good:
if self.lasttab <> tabsize:
self.lasttab = tabsize
self.doit()
else:
SysBeep(0)
self.w.tabsizeedit.set(`self.lasttab`)
self.w.tabsizeedit.selectall()
def checksize(self):
size = self.w.sizeedit.get()
if not size:
return
try:
size = string.atoi(size)
except (ValueError, OverflowError):
good = 0
sys.exc_traceback = None
else:
good = 1 <= size <= 500
if good:
if self.lastsize <> size:
self.lastsize = size
self.doit()
else:
SysBeep(0)
self.w.sizeedit.set(`self.lastsize`)
self.w.sizeedit.selectall()
def doplain(self):
for i in range(1, len(_stylenames)):
self.w[i].set(0)
self.w[0].set(1)
self.doit()
def dostyle(self):
for i in range(1, len(_stylenames)):
if self.w[i].get():
self.w[0].set(0)
break
else:
self.w[0].set(1)
self.doit()
def close(self):
self.w.close()
del self.w
def cancel(self):
self.close()
def done(self):
self._rv = self.get()
self.close()
def setfont(self, fontname):
self.w.fontname.set(fontname)
self.doit()
def FontDialog(fontsettings, tabsettings = (32, 0)):
fd = _FontDialog(fontsettings, tabsettings)
return fd._rv
def test():
print FontDialog(('Zapata-Light', 0, 25, (0, 0, 0)))
import macfs
import marshal
import types
kOnSystemDisk = 0x8000
class PrefObject:
def __init__(self, dict = None):
if dict == None:
self._prefsdict = {}
else:
self._prefsdict = dict
def __len__(self):
return len(self._prefsdict)
def __delattr__(self, attr):
if self._prefsdict.has_key(attr):
del self._prefsdict[attr]
else:
raise AttributeError, 'delete non-existing instance attribute'
def __getattr__(self, attr):
if attr == '__members__':
keys = self._prefsdict.keys()
keys.sort()
return keys
try:
return self._prefsdict[attr]
except KeyError:
raise AttributeError, attr
def __setattr__(self, attr, value):
if attr[0] <> '_':
self._prefsdict[attr] = value
else:
self.__dict__[attr] = value
def getprefsdict(self):
return self._prefsdict
class PrefFile(PrefObject):
def __init__(self, path, creator = 'Pyth'):
# Find the preferences folder and our prefs file, create if needed.
self.__path = path
self.__creator = creator
self._prefsdict = {}
try:
prefdict = marshal.load(open(self.__path, 'rb'))
except IOError:
pass
else:
for key, value in prefdict.items():
if type(value) == types.DictType:
self._prefsdict[key] = PrefObject(value)
else:
self._prefsdict[key] = value
def save(self):
prefdict = {}
for key, value in self._prefsdict.items():
if type(value) == types.InstanceType:
prefdict[key] = value.getprefsdict()
if not prefdict[key]:
del prefdict[key]
else:
prefdict[key] = value
marshal.dump(prefdict, open(self.__path, 'wb'))
fss = macfs.FSSpec(self.__path)
fss.SetCreatorType(self.__creator, 'pref')
def __getattr__(self, attr):
if attr == '__members__':
keys = self._prefsdict.keys()
keys.sort()
return keys
try:
return self._prefsdict[attr]
except KeyError:
if attr[0] <> '_':
self._prefsdict[attr] = PrefObject()
return self._prefsdict[attr]
else:
raise AttributeError, attr
_prefscache = {}
def GetPrefs(prefname, creator = 'Pyth'):
import macostools, os
if _prefscache.has_key(prefname):
return _prefscache[prefname]
# Find the preferences folder and our prefs file, create if needed.
vrefnum, dirid = macfs.FindFolder(kOnSystemDisk, 'pref', 0)
prefsfolder_fss = macfs.FSSpec((vrefnum, dirid, ''))
prefsfolder = prefsfolder_fss.as_pathname()
path = os.path.join(prefsfolder, prefname)
head, tail = os.path.split(path)
# make sure the folder(s) exist
macostools.mkdirs(head)
preffile = PrefFile(path, creator)
_prefscache[prefname] = preffile
return preffile
import W
import sys
import Qd
__version__ = "0.2"
__author__ = "jvr"
class _modulebrowser:
def __init__(self):
self.editmodules = []
self.modules = []
self.window = W.Window((194, 1000), "Module Browser", minsize = (194, 160), maxsize = (340, 20000))
#self.window.bevelbox = W.BevelBox((0, 0, 0, 56))
self.window.openbutton = W.Button((10, 8, 80, 16), "Open", self.openbuttonhit)
self.window.browsebutton = W.Button((100, 8, 80, 16), "Browse", self.browsebuttonhit)
self.window.reloadbutton = W.Button((10, 32, 80, 16), "Reload", self.reloadbuttonhit)
self.window.openotherbutton = W.Button((100, 32, 80, 16), "Open other", self.openother)
self.window.openbutton.enable(0)
self.window.reloadbutton.enable(0)
self.window.browsebutton.enable(0)
self.window.setdefaultbutton(self.window.browsebutton)
self.window.bind("cmdr", self.window.reloadbutton.push)
self.window.bind("cmdb", self.window.browsebutton.push)
self.window.bind("<activate>", self.activate)
self.window.bind("<close>", self.close)
self.window.list = W.List((-1, 56, 1, -14), [], self.listhit)
self.window.open()
self.checkbuttons()
def close(self):
global _browser
_browser = None
def activate(self, onoff):
if onoff:
self.makelist()
def listhit(self, isdbl):
self.checkbuttons()
if isdbl:
if self.window._defaultbutton:
self.window._defaultbutton.push()
def checkbuttons(self):
sel = self.window.list.getselection()
if sel:
for i in sel:
if self.editmodules[i]:
self.window.openbutton.enable(1)
self.window.reloadbutton.enable(1)
self.window.setdefaultbutton(self.window.openbutton)
break
else:
self.window.openbutton.enable(0)
self.window.reloadbutton.enable(0)
self.window.setdefaultbutton(self.window.browsebutton)
self.window.browsebutton.enable(1)
else:
#self.window.setdefaultbutton(self.window.browsebutton)
self.window.openbutton.enable(0)
self.window.reloadbutton.enable(0)
self.window.browsebutton.enable(0)
def openbuttonhit(self):
import imp
sel = self.window.list.getselection()
W.SetCursor("watch")
for i in sel:
modname = self.window.list[i]
try:
self.openscript(sys.modules[modname].__file__, modname)
except IOError:
try:
file, path, description = imp.find_module(modname)
except ImportError:
W.SetCursor("arrow")
W.Message("Cant find file for module %s."
% modname)
else:
self.openscript(path, modname)
def openscript(self, path, modname):
import os
if path[-3:] == '.py':
W.getapplication().openscript(path, modname=modname)
elif path[-4:] in ['.pyc', '.pyo']:
W.getapplication().openscript(path[:-1], modname=modname)
else:
W.Message("Cant edit %s; it might be a shared library or a .pyc file."
% modname)
def openother(self):
import imp
import EasyDialogs
modname = EasyDialogs.AskString("Open module:")
if modname:
try:
file, path, description = imp.find_module(modname)
except ImportError:
if modname in sys.builtin_module_names:
alerttext = "%s is a builtin module, which you cant edit." % modname
else:
alerttext = "No module named %s." % modname
raise W.AlertError, alerttext
self.openscript(path, modname)
def reloadbuttonhit(self):
sel = self.window.list.getselection()
W.SetCursor("watch")
for i in sel:
mname = self.window.list[i]
m = sys.modules[mname]
# Set the __name__ attribute of the module to its real name.
# reload() complains if it's __main__, which is true
# when it recently has been run as a script with "Run as __main__"
# enabled.
m.__name__ = mname
reload(m)
def browsebuttonhit(self):
sel = self.window.list.getselection()
if not sel:
return
import PyBrowser
for i in sel:
PyBrowser.Browser(sys.modules[self.window.list[i]])
def makelist(self):
editmodules, modules = getmoduleslist()
if modules == self.modules:
return
self.editmodules, self.modules = editmodules, modules
self.window.list.setdrawingmode(0)
sel = self.window.list.getselectedobjects()
self.window.list.set(self.modules)
self.window.list.setselectedobjects(sel)
self.window.list.setdrawingmode(1)
def getmoduleslist():
import PyBrowser # for caselesssort function
moduleitems = sys.modules.items()
moduleitems = filter(lambda (name, module): module is not None, moduleitems)
modules = map(lambda (name, module): name, moduleitems)
modules = PyBrowser.caselesssort(modules)
editmodules = []
sysmodules = sys.modules
modulesappend = editmodules.append
for m in modules:
module = sysmodules[m]
try:
if sysmodules[m].__file__[-3:] == '.py' or \
sysmodules[m].__file__[-4:] in ['.pyc', '.pyo']:
modulesappend(1)
else:
modulesappend(0)
except AttributeError:
modulesappend(0)
return editmodules, modules
_browser = None
def ModuleBrowser():
global _browser
if _browser is not None:
_browser.window.select()
else:
_browser = _modulebrowser()
import W
import Evt
import sys
import StringIO
import string
import pstats, fpformat
# increase precision
def f8(x):
return string.rjust(fpformat.fix(x, 4), 8)
pstats.f8 = f8
# hacking around a hack
if sys.version[:3] > '1.4':
timer = Evt.TickCount
else:
def timer(TickCount = Evt.TickCount):
return TickCount() / 60.0
class ProfileBrowser:
def __init__(self, stats = None):
self.sortkeys = ('calls',)
self.setupwidgets()
self.setstats(stats)
def setupwidgets(self):
self.w = W.Window((580, 400), "Profile Statistics", minsize = (200, 100), tabbable = 0)
self.w.divline = W.HorizontalLine((0, 20, 0, 0))
self.w.titlebar = W.TextBox((4, 4, 40, 12), 'Sort by:')
self.buttons = []
self.w.button_calls = W.RadioButton((54, 4, 45, 12), 'calls', self.buttons, self.setsort)
self.w.button_time = W.RadioButton((104, 4, 40, 12), 'time', self.buttons, self.setsort)
self.w.button_cumulative = W.RadioButton((154, 4, 75, 12), 'cumulative', self.buttons, self.setsort)
self.w.button_stdname = W.RadioButton((234, 4, 60, 12), 'stdname', self.buttons, self.setsort)
self.w.button_calls.set(1)
self.w.button_file = W.RadioButton((304, 4, 40, 12), 'file', self.buttons, self.setsort)
self.w.button_line = W.RadioButton((354, 4, 50, 12), 'line', self.buttons, self.setsort)
self.w.button_name = W.RadioButton((404, 4, 50, 12), 'name', self.buttons, self.setsort)
## self.w.button_nfl = W.RadioButton((4, 4, 12, 12), 'nfl', self.buttons, self.setsort)
## self.w.button_pcalls = W.RadioButton((4, 4, 12, 12), 'pcalls', self.buttons, self.setsort)
self.w.text = W.TextEditor((0, 21, -15, -15), inset = (6, 5),
readonly = 1, wrap = 0, fontsettings = ('Monaco', 0, 9, (0, 0, 0)))
self.w._bary = W.Scrollbar((-15, 20, 16, -14), self.w.text.vscroll, max = 32767)
self.w._barx = W.Scrollbar((-1, -15, -14, 16), self.w.text.hscroll, max = 32767)
self.w.open()
def setstats(self, stats):
self.stats = stats
self.stats.strip_dirs()
self.displaystats()
def setsort(self):
# Grmpf. The callback doesn't give us the button:-(
for b in self.buttons:
if b.get():
if b._title == self.sortkeys[0]:
return
self.sortkeys = (b._title,) + self.sortkeys[:3]
break
self.displaystats()
def displaystats(self):
W.SetCursor('watch')
apply(self.stats.sort_stats, self.sortkeys)
saveout = sys.stdout
try:
s = sys.stdout = StringIO.StringIO()
self.stats.print_stats()
finally:
sys.stdout = saveout
text = string.join(string.split(s.getvalue(), '\n'), '\r')
self.w.text.set(text)
def main():
import pstats
args = sys.argv[1:]
for i in args:
stats = pstats.Stats(i)
browser = ProfileBrowser(stats)
else:
import macfs
fss, ok = macfs.PromptGetFile('Profiler data')
if not ok: sys.exit(0)
stats = pstats.Stats(fss.as_pathname())
browser = ProfileBrowser(stats)
if __name__ == '__main__':
main()
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
import aetools
import Standard_Suite
import Required_Suite
import WWW_Suite
import regex
import W
import macfs
import os
import MacPrefs
import MacOS
import string
if hasattr(WWW_Suite, "WWW_Suite"):
WWW = WWW_Suite.WWW_Suite
else:
WWW = WWW_Suite.WorldWideWeb_suite_2c__as_defined_in_Spyglass_spec_2e_
class WebBrowser(aetools.TalkTo,
Standard_Suite.Standard_Suite,
WWW):
def openfile(self, path, activate = 1):
if activate:
self.activate()
self.OpenURL("file:///" + string.join(string.split(path,':'), '/'))
app = W.getapplication()
#SIGNATURE='MSIE' # MS Explorer
SIGNATURE='MOSS' # Netscape
_titlepat = regex.compile('<title>\([^<]*\)</title>')
def sucktitle(path):
f = open(path)
text = f.read(1024) # assume the title is in the first 1024 bytes
f.close()
lowertext = string.lower(text)
if _titlepat.search(lowertext) > 0:
a, b = _titlepat.regs[1]
return text[a:b]
return path
def verifydocpath(docpath):
try:
tut = os.path.join(docpath, "tut")
lib = os.path.join(docpath, "lib")
ref = os.path.join(docpath, "ref")
for path in [tut, lib, ref]:
if not os.path.exists(path):
return 0
except:
return 0
return 1
class TwoLineList(W.List):
LDEF_ID = 468
def createlist(self):
import List
self._calcbounds()
self.SetPort()
rect = self._bounds
rect = rect[0]+1, rect[1]+1, rect[2]-16, rect[3]-1
self._list = List.LNew(rect, (0, 0, 1, 0), (0, 28), self.LDEF_ID, self._parentwindow.wid,
0, 1, 0, 1)
self.set(self.items)
_resultscounter = 1
class Results:
def __init__(self, hits):
global _resultscounter
hits = map(lambda (path, hits): (sucktitle(path), path, hits), hits)
hits.sort()
self.hits = hits
nicehits = map(
lambda (title, path, hits):
title + '\r' + string.join(
map(lambda (c, p): "%s (%d)" % (p, c), hits), ', '), hits)
nicehits.sort()
self.w = W.Window((440, 300), "Search results %d" % _resultscounter, minsize = (200, 100))
self.w.results = TwoLineList((-1, -1, 1, -14), nicehits, self.listhit)
self.w.open()
self.w.bind('return', self.listhit)
self.w.bind('enter', self.listhit)
_resultscounter = _resultscounter + 1
self.browser = None
def listhit(self, isdbl = 1):
if isdbl:
for i in self.w.results.getselection():
if self.browser is None:
self.browser = WebBrowser(SIGNATURE, start = 1)
self.browser.openfile(self.hits[i][1])
class Status:
def __init__(self):
self.w = W.Dialog((440, 64), "Searching")
self.w.searching = W.TextBox((4, 4, -4, 16), "DevDev:PyPyDoc 1.5.1:ext:parseTupleAndKeywords.html")
self.w.hits = W.TextBox((4, 24, -4, 16), "Hits: 0")
self.w.canceltip = W.TextBox((4, 44, -4, 16), "Type cmd-period (.) to cancel.")
self.w.open()
def set(self, path, hits):
self.w.searching.set(path)
self.w.hits.set('Hits: ' + `hits`)
app.breathe()
def close(self):
self.w.close()
def match(text, patterns, all):
hits = []
hitsappend = hits.append
stringcount = string.count
for pat in patterns:
c = stringcount(text, pat)
if c > 0:
hitsappend((c, pat))
elif all:
hits[:] = []
break
hits.sort()
hits.reverse()
return hits
def dosearch(docpath, searchstring, settings):
(docpath, kind, case, word, tut, lib, ref, ext, api) = settings
books = [(tut, 'tut'), (lib, 'lib'), (ref, 'ref'), (ext, 'ext'), (api, 'api')]
if not case:
searchstring = string.lower(searchstring)
if kind == 1:
patterns = string.split(searchstring)
all = 1
elif kind == 2:
patterns = string.split(searchstring)
all = 0
else:
patterns = [searchstring]
all = 0 # not relevant
ospathjoin = os.path.join
stringlower = string.lower
status = Status()
statusset = status.set
_match = match
_open = open
hits = {}
try:
MacOS.EnableAppswitch(0)
try:
for do, name in books:
if not do:
continue
bookpath = ospathjoin(docpath, name)
if not os.path.exists(bookpath):
continue
files = os.listdir(bookpath)
for file in files:
fullpath = ospathjoin(bookpath, file)
if fullpath[-5:] <> '.html':
continue
statusset(fullpath, len(hits))
f = _open(fullpath)
text = f.read()
if not case:
text = stringlower(text)
f.close()
filehits = _match(text, patterns, all)
if filehits:
hits[fullpath] = filehits
finally:
MacOS.EnableAppswitch(-1)
status.close()
except KeyboardInterrupt:
pass
hits = hits.items()
hits.sort()
return hits
class PyDocSearch:
def __init__(self):
prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
try:
(docpath, kind, case, word, tut, lib, ref, ext, api) = prefs.docsearchengine
except:
(docpath, kind, case, word, tut, lib, ref, ext, api) = prefs.docsearchengine = \
("", 0, 0, 0, 1, 1, 0, 0, 0)
if docpath and not verifydocpath(docpath):
docpath = ""
self.w = W.Window((400, 200), "Search the Python Documentation")
self.w.searchtext = W.EditText((10, 10, -100, 20), callback = self.checkbuttons)
self.w.searchbutton = W.Button((-90, 12, 80, 16), "Search", self.search)
buttons = []
gutter = 10
width = 130
bookstart = width + 2 * gutter
self.w.phraseradio = W.RadioButton((10, 38, width, 16), "As a phrase", buttons)
self.w.allwordsradio = W.RadioButton((10, 58, width, 16), "All words", buttons)
self.w.anywordsradio = W.RadioButton((10, 78, width, 16), "Any word", buttons)
self.w.casesens = W.CheckBox((10, 98, width, 16), "Case sensitive")
self.w.wholewords = W.CheckBox((10, 118, width, 16), "Whole words")
self.w.tutorial = W.CheckBox((bookstart, 38, -10, 16), "Tutorial")
self.w.library = W.CheckBox((bookstart, 58, -10, 16), "Library reference")
self.w.langueref = W.CheckBox((bookstart, 78, -10, 16), "Lanuage reference manual")
self.w.extending = W.CheckBox((bookstart, 98, -10, 16), "Extending & embedding")
self.w.api = W.CheckBox((bookstart, 118, -10, 16), "C/C++ API")
self.w.setdocfolderbutton = W.Button((10, -30, 80, 16), "Set doc folder", self.setdocpath)
if docpath:
self.w.setdefaultbutton(self.w.searchbutton)
else:
self.w.setdefaultbutton(self.w.setdocfolderbutton)
self.docpath = docpath
if not docpath:
docpath = "(please select the Python html documentation folder)"
self.w.docfolder = W.TextBox((100, -28, -10, 16), docpath)
[self.w.phraseradio, self.w.allwordsradio, self.w.anywordsradio][kind].set(1)
self.w.casesens.set(case)
self.w.wholewords.set(word)
self.w.tutorial.set(tut)
self.w.library.set(lib)
self.w.langueref.set(ref)
self.w.extending.set(ext)
self.w.api.set(api)
self.w.open()
self.w.wholewords.enable(0)
self.w.bind('<close>', self.close)
self.w.searchbutton.enable(0)
def search(self):
hits = dosearch(self.docpath, self.w.searchtext.get(), self.getsettings())
if hits:
Results(hits)
elif hasattr(MacOS, 'SysBeep'):
MacOS.SysBeep(0)
#import PyBrowser
#PyBrowser.Browser(hits)
def setdocpath(self):
fss, ok = macfs.GetDirectory()
if ok:
docpath = fss.as_pathname()
if not verifydocpath(docpath):
W.Message("This does not seem to be a Python documentation folder...")
else:
self.docpath = docpath
self.w.docfolder.set(docpath)
self.w.setdefaultbutton(self.w.searchbutton)
def close(self):
prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
prefs.docsearchengine = self.getsettings()
def getsettings(self):
radiobuttons = [self.w.phraseradio, self.w.allwordsradio, self.w.anywordsradio]
for i in range(3):
if radiobuttons[i].get():
kind = i
break
docpath = self.docpath
case = self.w.casesens.get()
word = self.w.wholewords.get()
tut = self.w.tutorial.get()
lib = self.w.library.get()
ref = self.w.langueref.get()
ext = self.w.extending.get()
api = self.w.api.get()
return (docpath, kind, case, word, tut, lib, ref, ext, api)
def checkbuttons(self):
self.w.searchbutton.enable(not not self.w.searchtext.get())
This diff is collapsed.
"""Module to analyze Python source code; for syntax coloring tools.
Interface:
tags = fontify(pytext, searchfrom, searchto)
The 'pytext' argument is a string containing Python source code.
The (optional) arguments 'searchfrom' and 'searchto' may contain a slice in pytext.
The returned value is a list of tuples, formatted like this:
[('keyword', 0, 6, None), ('keyword', 11, 17, None), ('comment', 23, 53, None), etc. ]
The tuple contents are always like this:
(tag, startindex, endindex, sublist)
tag is one of 'keyword', 'string', 'comment' or 'identifier'
sublist is not used, hence always None.
"""
# Based on FontText.py by Mitchell S. Chapman,
# which was modified by Zachary Roadhouse,
# then un-Tk'd by Just van Rossum.
# Many thanks for regular expression debugging & authoring are due to:
# Tim (the-incredib-ly y'rs) Peters and Cristian Tismer
# So, who owns the copyright? ;-) How about this:
# Copyright 1996-1997:
# Mitchell S. Chapman,
# Zachary Roadhouse,
# Tim Peters,
# Just van Rossum
__version__ = "0.3.1"
import string, regex
# First a little helper, since I don't like to repeat things. (Tismer speaking)
import string
def replace(where, what, with):
return string.join(string.split(where, what), with)
# This list of keywords is taken from ref/node13.html of the
# Python 1.3 HTML documentation. ("access" is intentionally omitted.)
keywordsList = [
"assert",
"del", "from", "lambda", "return",
"and", "elif", "global", "not", "try",
"break", "else", "if", "or", "while",
"class", "except", "import", "pass",
"continue", "finally", "in", "print",
"def", "for", "is", "raise"]
# Build up a regular expression which will match anything
# interesting, including multi-line triple-quoted strings.
commentPat = "#.*"
pat = "q[^\q\n]*\(\\\\[\000-\377][^\q\n]*\)*q"
quotePat = replace(pat, "q", "'") + "\|" + replace(pat, 'q', '"')
# Way to go, Tim!
pat = """
qqq
[^\\q]*
\(
\( \\\\[\000-\377]
\| q
\( \\\\[\000-\377]
\| [^\\q]
\| q
\( \\\\[\000-\377]
\| [^\\q]
\)
\)
\)
[^\\q]*
\)*
qqq
"""
pat = string.join(string.split(pat), '') # get rid of whitespace
tripleQuotePat = replace(pat, "q", "'") + "\|" + replace(pat, 'q', '"')
# Build up a regular expression which matches all and only
# Python keywords. This will let us skip the uninteresting
# identifier references.
# nonKeyPat identifies characters which may legally precede
# a keyword pattern.
nonKeyPat = "\(^\|[^a-zA-Z0-9_.\"']\)"
keyPat = nonKeyPat + "\("
for keyword in keywordsList:
keyPat = keyPat + keyword + "\|"
keyPat = keyPat[:-2] + "\)" + nonKeyPat
matchPat = keyPat + "\|" + commentPat + "\|" + tripleQuotePat + "\|" + quotePat
matchRE = regex.compile(matchPat)
idKeyPat = "[ \t]*[A-Za-z_][A-Za-z_0-9.]*" # Ident w. leading whitespace.
idRE = regex.compile(idKeyPat)
def fontify(pytext, searchfrom = 0, searchto = None):
if searchto is None:
searchto = len(pytext)
# Cache a few attributes for quicker reference.
search = matchRE.search
group = matchRE.group
idSearch = idRE.search
idGroup = idRE.group
tags = []
tags_append = tags.append
commentTag = 'comment'
stringTag = 'string'
keywordTag = 'keyword'
identifierTag = 'identifier'
start = 0
end = searchfrom
while 1:
start = search(pytext, end)
if start < 0 or start >= searchto:
break # EXIT LOOP
match = group(0)
end = start + len(match)
c = match[0]
if c not in "#'\"":
# Must have matched a keyword.
if start <> searchfrom:
# there's still a redundant char before and after it, strip!
match = match[1:-1]
start = start + 1
else:
# this is the first keyword in the text.
# Only a space at the end.
match = match[:-1]
end = end - 1
tags_append((keywordTag, start, end, None))
# If this was a defining keyword, look ahead to the
# following identifier.
if match in ["def", "class"]:
start = idSearch(pytext, end)
if start == end:
match = idGroup(0)
end = start + len(match)
tags_append((identifierTag, start, end, None))
elif c == "#":
tags_append((commentTag, start, end, None))
else:
tags_append((stringTag, start, end, None))
return tags
def test(path):
f = open(path)
text = f.read()
f.close()
tags = fontify(text)
for tag, start, end, sublist in tags:
print tag, `text[start:end]`
import string
import sys
import traceback
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
def print_exc(limit=None, file=None):
if not file:
file = sys.stderr
# we're going to skip the outermost traceback object, we don't
# want people to see the line which excecuted their code.
tb = sys.exc_traceback
if tb:
tb = tb.tb_next
try:
sys.last_type = sys.exc_type
sys.last_value = sys.exc_value
sys.last_traceback = tb
traceback.print_exception(sys.last_type, sys.last_value,
sys.last_traceback, limit, file)
except:
print '--- hola! ---'
traceback.print_exception(sys.exc_type, sys.exc_value,
sys.exc_traceback, limit, file)
class PyInteractive:
def __init__(self):
self._pybuf = ""
def executeline(self, stuff, out = None, env = None):
if env is None:
import __main__
env = __main__.__dict__
if out:
saveerr, saveout = sys.stderr, sys.stdout
sys.stderr = sys.stdout = out
try:
if self._pybuf:
self._pybuf = self._pybuf + '\n' + stuff
else:
self._pybuf = stuff
# Compile three times: as is, with \n, and with \n\n appended.
# If it compiles as is, it's complete. If it compiles with
# one \n appended, we expect more. If it doesn't compile
# either way, we compare the error we get when compiling with
# \n or \n\n appended. If the errors are the same, the code
# is broken. But if the errors are different, we expect more.
# Not intuitive; not even guaranteed to hold in future
# releases; but this matches the compiler's behavior in Python
# 1.4 and 1.5.
err = err1 = err2 = None
code = code1 = code2 = None
# quickly get out of here when the line is 'empty' or is a comment
stripped = string.strip(self._pybuf)
if not stripped or stripped[0] == '#':
self._pybuf = ''
sys.stdout.write(sys.ps1)
sys.stdout.flush()
return
try:
code = compile(self._pybuf, "<input>", "single")
except SyntaxError, err:
pass
except:
# OverflowError. More?
print_exc()
self._pybuf = ""
sys.stdout.write(sys.ps1)
sys.stdout.flush()
return
try:
code1 = compile(self._pybuf + "\n", "<input>", "single")
except SyntaxError, err1:
pass
try:
code2 = compile(self._pybuf + "\n\n", "<input>", "single")
except SyntaxError, err2:
pass
if code:
try:
exec code in env
except:
print_exc()
self._pybuf = ""
elif code1:
pass
elif err1 == err2 or (not stuff and self._pybuf):
print_exc()
self._pybuf = ""
if self._pybuf:
sys.stdout.write(sys.ps2)
sys.stdout.flush()
else:
sys.stdout.write(sys.ps1)
sys.stdout.flush()
finally:
if out:
sys.stderr, sys.stdout = saveerr, saveout
# copyright 1996-1999 Just van Rossum, Letterror. just@letterror.com
# keep this (__main__) as clean as possible, since we are using
# it like the "normal" interpreter.
__version__ = '1.0b2'
def init():
import MacOS
MacOS.EnableAppswitch(-1)
import Qd, QuickDraw
Qd.SetCursor(Qd.GetCursor(QuickDraw.watchCursor).data)
import Res
try:
Res.GetResource('DITL', 468)
except Res.Error:
# we're not an applet
Res.OpenResFile('Widgets.rsrc')
Res.OpenResFile('PythonIDE.rsrc')
else:
# we're an applet
import sys
if sys.argv[0] not in sys.path:
sys.path[2:2] = [sys.argv[0]]
init()
del init
import PythonIDEMain
# copyright 1997-1998 Just van Rossum, Letterror. just@letterror.com
import Splash
import FrameWork
import Win
import Wapplication
import W
import os
import macfs
class PythonIDE(Wapplication.Application):
def __init__(self):
self.preffilepath = ":Python:PythonIDE preferences"
Wapplication.Application.__init__(self, 'Pyth')
import AE, AppleEvents
AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenApplication,
self.ignoreevent)
AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEPrintDocuments,
self.ignoreevent)
AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenDocuments,
self.opendocsevent)
AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEQuitApplication,
self.quitevent)
import PyConsole, PyEdit
Splash.wait()
Splash.uninstall_importhook()
PyConsole.installoutput()
PyConsole.installconsole()
import sys
for path in sys.argv[1:]:
self.opendoc(path)
self.mainloop()
def makeusermenus(self):
m = Wapplication.Menu(self.menubar, "File")
newitem = FrameWork.MenuItem(m, "New", "N", 'new')
openitem = FrameWork.MenuItem(m, "Open", "O", 'open')
FrameWork.Separator(m)
closeitem = FrameWork.MenuItem(m, "Close", "W", 'close')
saveitem = FrameWork.MenuItem(m, "Save", "S", 'save')
saveasitem = FrameWork.MenuItem(m, "Save as", None, 'save_as')
FrameWork.Separator(m)
saveasappletitem = FrameWork.MenuItem(m, "Save as Applet", None, 'save_as_applet')
FrameWork.Separator(m)
quititem = FrameWork.MenuItem(m, "Quit", "Q", 'quit')
m = Wapplication.Menu(self.menubar, "Edit")
undoitem = FrameWork.MenuItem(m, "Undo", 'Z', "undo")
FrameWork.Separator(m)
cutitem = FrameWork.MenuItem(m, "Cut", 'X', "cut")
copyitem = FrameWork.MenuItem(m, "Copy", "C", "copy")
pasteitem = FrameWork.MenuItem(m, "Paste", "V", "paste")
FrameWork.MenuItem(m, "Clear", None, "clear")
FrameWork.Separator(m)
selallitem = FrameWork.MenuItem(m, "Select all", "A", "selectall")
sellineitem = FrameWork.MenuItem(m, "Select line", "L", "selectline")
FrameWork.Separator(m)
finditem = FrameWork.MenuItem(m, "Find", "F", "find")
findagainitem = FrameWork.MenuItem(m, "Find again", 'G', "findnext")
enterselitem = FrameWork.MenuItem(m, "Enter search string", "E", "entersearchstring")
replaceitem = FrameWork.MenuItem(m, "Replace", None, "replace")
replacefinditem = FrameWork.MenuItem(m, "Replace & find again", 'T', "replacefind")
FrameWork.Separator(m)
shiftleftitem = FrameWork.MenuItem(m, "Shift left", "[", "shiftleft")
shiftrightitem = FrameWork.MenuItem(m, "Shift right", "]", "shiftright")
m = Wapplication.Menu(self.menubar, "Python")
runitem = FrameWork.MenuItem(m, "Run window", "R", 'run')
runselitem = FrameWork.MenuItem(m, "Run selection", None, 'runselection')
FrameWork.Separator(m)
moditem = FrameWork.MenuItem(m, "Module browser", "M", self.domenu_modulebrowser)
FrameWork.Separator(m)
mm = FrameWork.SubMenu(m, "Preferences")
FrameWork.MenuItem(mm, "Set Scripts folder", None, self.do_setscriptsfolder)
FrameWork.MenuItem(mm, "Editor default settings", None, self.do_editorprefs)
self.openwindowsmenu = Wapplication.Menu(self.menubar, 'Windows')
self.makeopenwindowsmenu()
self._menustocheck = [closeitem, saveitem, saveasitem, saveasappletitem,
undoitem, cutitem, copyitem, pasteitem,
selallitem, sellineitem,
finditem, findagainitem, enterselitem, replaceitem, replacefinditem,
shiftleftitem, shiftrightitem,
runitem, runselitem]
prefs = self.getprefs()
try:
fss, fss_changed = macfs.RawAlias(prefs.scriptsfolder).Resolve()
except:
path = os.path.join(os.getcwd(), 'Scripts')
if not os.path.exists(path):
os.mkdir(path)
fss = macfs.FSSpec(path)
self.scriptsfolder = fss.NewAlias()
self.scriptsfoldermodtime = fss.GetDates()[1]
else:
self.scriptsfolder = fss.NewAlias()
self.scriptsfoldermodtime = fss.GetDates()[1]
prefs.scriptsfolder = self.scriptsfolder.data
self._scripts = {}
self.scriptsmenu = None
self.makescriptsmenu()
def quitevent(self, theAppleEvent, theReply):
import AE
AE.AEInteractWithUser(50000000)
self._quit()
def suspendresume(self, onoff):
if onoff:
fss, fss_changed = self.scriptsfolder.Resolve()
modtime = fss.GetDates()[1]
if self.scriptsfoldermodtime <> modtime or fss_changed:
self.scriptsfoldermodtime = modtime
W.SetCursor('watch')
self.makescriptsmenu()
def ignoreevent(self, theAppleEvent, theReply):
pass
def opendocsevent(self, theAppleEvent, theReply):
W.SetCursor('watch')
import aetools
parameters, args = aetools.unpackevent(theAppleEvent)
docs = parameters['----']
if type(docs) <> type([]):
docs = [docs]
for doc in docs:
fss, a = doc.Resolve()
path = fss.as_pathname()
self.opendoc(path)
def opendoc(self, path):
fcreator, ftype = macfs.FSSpec(path).GetCreatorType()
if ftype == 'TEXT':
self.openscript(path)
else:
W.Message("Cant open file of type '%s'." % ftype)
def getabouttext(self):
return "About Python IDE"
def do_about(self, id, item, window, event):
Splash.about()
def do_setscriptsfolder(self, *args):
fss, ok = macfs.GetDirectory("Select Scripts Folder")
if ok:
prefs = self.getprefs()
alis = fss.NewAlias()
prefs.scriptsfolder = alis.data
self.scriptsfolder = alis
self.makescriptsmenu()
prefs.save()
def domenu_modulebrowser(self, *args):
W.SetCursor('watch')
import ModuleBrowser
ModuleBrowser.ModuleBrowser()
def domenu_open(self, *args):
fss, ok = macfs.StandardGetFile("TEXT")
if ok:
self.openscript(fss.as_pathname())
def domenu_new(self, *args):
W.SetCursor('watch')
import PyEdit
return PyEdit.Editor()
def makescriptsmenu(self):
W.SetCursor('watch')
if self._scripts:
for id, item in self._scripts.keys():
if self.menubar.menus.has_key(id):
m = self.menubar.menus[id]
m.delete()
self._scripts = {}
if self.scriptsmenu:
if hasattr(self.scriptsmenu, 'id') and self.menubar.menus.has_key(self.scriptsmenu.id):
self.scriptsmenu.delete()
self.scriptsmenu = FrameWork.Menu(self.menubar, "Scripts")
#FrameWork.MenuItem(self.scriptsmenu, "New script", None, self.domenu_new)
#self.scriptsmenu.addseparator()
fss, fss_changed = self.scriptsfolder.Resolve()
self.scriptswalk(fss.as_pathname(), self.scriptsmenu)
def makeopenwindowsmenu(self):
for i in range(len(self.openwindowsmenu.items)):
self.openwindowsmenu.menu.DeleteMenuItem(1)
self.openwindowsmenu.items = []
windows = []
self._openwindows = {}
for window in self._windows.keys():
title = window.GetWTitle()
if not title:
title = "<no title>"
windows.append(title, window)
windows.sort()
for title, window in windows:
if title == "Python Interactive": # ugly but useful hack by Joe Strout
shortcut = '0'
else:
shortcut = None
item = FrameWork.MenuItem(self.openwindowsmenu, title, shortcut, callback = self.domenu_openwindows)
self._openwindows[item.item] = window
self._openwindowscheckmark = 0
self.checkopenwindowsmenu()
def domenu_openwindows(self, id, item, window, event):
w = self._openwindows[item]
w.ShowWindow()
w.SelectWindow()
def domenu_quit(self):
self._quit()
def domenu_save(self, *args):
print "Save"
def _quit(self):
import PyConsole, PyEdit
PyConsole.console.writeprefs()
PyConsole.output.writeprefs()
PyEdit.searchengine.writeprefs()
for window in self._windows.values():
rv = window.close()
if rv and rv > 0:
return
self.quitting = 1
PythonIDE()
import Dlg
import Res
splash = Dlg.GetNewDialog(468, -1)
splash.DrawDialog()
import Qd, TE, Fm, sys
_real__import__ = None
def install_importhook():
global _real__import__
import __builtin__
if _real__import__ is None:
_real__import__ = __builtin__.__import__
__builtin__.__import__ = my__import__
def uninstall_importhook():
global _real__import__
if _real__import__ is not None:
import __builtin__
__builtin__.__import__ = _real__import__
_real__import__ = None
_progress = 0
def importing(module):
global _progress
Qd.SetPort(splash)
fontID = Fm.GetFNum("Python-Sans")
if not fontID:
fontID = geneva
Qd.TextFont(fontID)
Qd.TextSize(9)
rect = (35, 260, 365, 276)
if module:
TE.TETextBox('Importing: ' + module, rect, 0)
if not _progress:
Qd.FrameRect((35, 276, 365, 284))
pos = min(36 + 330 * _progress / 44, 364)
Qd.PaintRect((36, 277, pos, 283))
_progress = _progress + 1
else:
Qd.EraseRect(rect)
Qd.PaintRect((36, 277, pos, 283))
def my__import__(name, globals=None, locals=None, fromlist=None):
try:
return sys.modules[name]
except KeyError:
try:
importing(name)
except:
try:
rv = _real__import__(name)
finally:
uninstall_importhook()
return rv
return _real__import__(name)
install_importhook()
kHighLevelEvent = 23
import Win
from Fonts import *
from QuickDraw import *
from TextEdit import *
import string
import sys
_keepsplashscreenopen = 0
abouttext1 = """The Python Integrated Developement Environment for the Macintosh
Version: %s
Copyright 1997-98 Just van Rossum, Letterror. <just@letterror.com>
Python %s
%s
Written by Guido van Rossum with Jack Jansen (and others)
See: <http://www.python.org/> for information and documentation."""
flauwekul = [ 'Goodday, Bruce.',
'Whats new?',
'Nudge, nudge, say no more!',
'No, no sir, its not dead. Its resting.',
'Albatros!',
'Its . . .',
'Is your name not Bruce, then?',
"""But Mr F.G. Superman has a secret identity . . .
when trouble strikes at any time . . .
at any place . . . he is ready to become . . .
Bicycle Repair Man!"""
]
def nl2return(text):
return string.join(string.split(text, '\n'), '\r')
def UpdateSplash(drawdialog = 0, what = 0):
if drawdialog:
splash.DrawDialog()
drawtext(what)
Win.ValidRect(splash.GetWindowPort().portRect)
def drawtext(what = 0):
Qd.SetPort(splash)
fontID = Fm.GetFNum("Python-Sans")
if not fontID:
fontID = geneva
Qd.TextFont(fontID)
Qd.TextSize(9)
rect = (10, 125, 390, 260)
if not what:
import __main__
abouttxt = nl2return(abouttext1 \
% (__main__.__version__, sys.version, sys.copyright))
else:
import random
abouttxt = nl2return(random.choice(flauwekul))
TE.TETextBox(abouttxt, rect, teJustCenter)
UpdateSplash(1)
def wait():
import Evt
from Events import *
global splash
try:
splash
except NameError:
return
Qd.InitCursor()
time = Evt.TickCount()
whattext = 0
while _keepsplashscreenopen:
ok, event = Evt.EventAvail(highLevelEventMask)
if ok:
# got apple event, back to mainloop
break
ok, event = Evt.EventAvail(mDownMask | keyDownMask | updateMask)
if ok:
ok, event = Evt.WaitNextEvent(mDownMask | keyDownMask | updateMask, 30)
if ok:
(what, message, when, where, modifiers) = event
if what == updateEvt:
if Win.WhichWindow(message) == splash:
UpdateSplash(1, whattext)
else:
break
if Evt.TickCount() - time > 360:
whattext = not whattext
drawtext(whattext)
time = Evt.TickCount()
del splash
#Res.CloseResFile(splashresfile)
def about():
global splash, splashresfile, _keepsplashscreenopen
_keepsplashscreenopen = 1
splash = Dlg.GetNewDialog(468, -1)
splash.DrawDialog()
wait()
"""Widgets for the Macintosh. Built on top of FrameWork"""
__version__ = "0.3"
from Wbase import *
from Wcontrols import *
from Wtext import *
from Wlists import *
from Wwindows import *
from Wmenus import *
_application = None
_signature = None
AlertError = 'AlertError'
def setapplication(app, sig):
global _application, _signature
_application = app
_signature = sig
def getapplication():
if _application is None:
raise WidgetsError, 'W not properly initialized: unknown Application'
return _application
def Message(text):
import EasyDialogs, Qd, string
Qd.InitCursor()
text = string.replace(text, "\n", "\r")
if not text:
text = '<Alert text not specified>'
EasyDialogs.Message(text)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
spacekey = ' '
returnkey = '\r'
tabkey = '\t'
enterkey = '\003'
backspacekey = '\010'
deletekey = '\177'
helpkey = '\005'
leftarrowkey = '\034'
rightarrowkey = '\035'
uparrowkey = '\036'
downarrowkey = '\037'
arrowkeys = [leftarrowkey, rightarrowkey, uparrowkey, downarrowkey]
topkey = '\001'
bottomkey = '\004'
pageupkey = '\013'
pagedownkey = '\014'
scrollkeys = [topkey, bottomkey, pageupkey, pagedownkey]
navigationkeys = arrowkeys + scrollkeys
keycodes = {
"space" : ' ',
"return" : '\r',
"tab" : '\t',
"enter" : '\003',
"backspace" : '\010',
"delete" : '\177',
"help" : '\005',
"leftarrow" : '\034',
"rightarrow" : '\035',
"uparrow" : '\036',
"downarrow" : '\037',
"top" : '\001',
"bottom" : '\004',
"pageup" : '\013',
"pagedown" : '\014'
}
keynames = {}
for k, v in keycodes.items():
keynames[v] = k
del k, v
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment