Commit a4136e14 authored by Neal Norwitz's avatar Neal Norwitz
parent d609b1a2
A separator ends with '---'
\ No newline at end of file
"""Turn the debugger off."""
import PyDebugger
PyDebugger.cont()
"""This script turns the Python debugger on globally, meaning that
it will then stop at any breakpoint you might have defined."""
import PyDebugger
PyDebugger.startfrombottom()
import sys
import os
import macfs
def walk(top):
names = os.listdir(top)
for name in names:
path = os.path.join(top, name)
if os.path.isdir(path):
walk(path)
else:
if path[-4:] in ['.pyc', '.pyo'] and os.path.exists(path[:-1]):
print "deleting:", path
os.remove(path)
elif path[-4:] == '.pyc':
print "!!! ------ .pyc file without .py file:", path
elif path[-4:] == '.pyo':
print "!!! ------ .pyo file without .py file:", path
fss, ok = macfs.GetDirectory('Select the starting folder:')
if ok:
walk(fss.as_pathname())
import aetools
import Standard_Suite
import Required_Suite
import MacOS
import W
class Toolbox(aetools.TalkTo, Standard_Suite.Standard_Suite):
def LookupTopic(self, _object, _attributes={}, **_arguments):
_code = 'DanR'
_subcode = 'REF '
_arguments['----'] = _object
_reply, _arguments, _attributes = self.send(_code, _subcode,
_arguments, _attributes)
if _arguments.has_key('errn'):
raise MacOS.Error, aetools.decodeerror(_arguments)
class ToolboxAssi:
def __init__(self):
self.talker = None
self.w = W.Window((200, 100), "Toolbox Assistant")
self.w.button = W.Button((-94, -32, 80, 16), "Lookup", self.lookup)
self.w.prompt = W.TextBox((10, 8, -10, 15), "Enter topic:")
self.w.edit = W.EditText((10, 24, -10, 20))
self.w.setdefaultbutton(self.w.button)
self.w.open()
def lookup(self):
if self.talker is None:
try:
self.talker = Toolbox('ALTV', start = 1)
except:
raise W.AlertError, "Cant find Toolbox Assistant"
lookup = self.w.edit.get()
try:
self.talker.LookupTopic(lookup)
except MacOS.Error, detail:
W.Message("Requested topic not found.\r(%d)" % detail[0])
t = ToolboxAssi()
"Hold the option key to open a script instead of running it."
import W
W.Message(__doc__)
import macfs
fss, ok = macfs.StandardGetFile()
if ok:
import W
W.FrontWindowInsert('"%s"' % fss.as_pathname())
import macfs
fss, ok = macfs.GetDirectory()
if ok:
import W
W.FrontWindowInsert('"%s"' % fss.as_pathname())
import PyDocSearch
# set the creator of the browser. 'MSIE' = Exploser, 'MOSS' = Netscape
PyDocSearch.SIGNATURE = 'MOSS'
pds = PyDocSearch.PyDocSearch()
import W
# this demoscript illustrates how to tie a callback to activating or clicking away of the window.
# evb 22 4 99
class ActivateDemo:
def __init__(self):
self.w = W.Window((200, 200), 'Activate demo')
self.w.bind("<activate>", self.my_activate_callback)
self.w.open()
def my_activate_callback(self, onoff):
'''the callback gets 1 parameter which indicates whether the window
has been activated (1) or clicked to the back (0)'''
if onoff == 1:
print "I'm in the front now!"
else:
print "I've been clicked away, Oh No!"
ad = ActivateDemo()
"""Simple W demo -- shows how to make a window, and bind a function to a "key" event."""
import W
# key callback function
def tester(char, event):
text = "%r\r%d\r%s\r%s" % (char, ord(char), hex(ord(chart)), oct(ord(char)))
window.keys.set(text)
# close callback
def close():
window.close()
# new window
window = W.Dialog((180, 100), "Type a character")
# make a frame (a simple rectangle)
window.frame = W.Frame((5, 5, -5, -33))
# some labels, static text
window.captions = W.TextBox((10, 9, 43, -36), "char:\rdecimal:\rhex:\roctal:")
# another static text box
window.keys = W.TextBox((60, 9, 40, -36))
# a button
window.button = W.Button((-69, -24, 60, 16), "Done", close)
# bind the callbacks
window.bind("<key>", tester)
window.bind("cmdw", window.button.push)
# open the window
window.open()
import W
def listhit(isdbl):
if isdbl:
print "double-click in list!"
else:
print "click in list."
window = W.Window((200, 400), "Window with List", minsize = (150, 200))
window.list = W.List((-1, 20, 1, -14), [], listhit)
# or (equivalent):
# window.list = W.List((-1, 20, 1, -14), callback = listhit)
window.list.set(range(13213, 13350))
window.open()
import W
from Carbon import Windows
w = W.ModalDialog((100, 100))
w.ed = W.EditText((10, 10, 80, 50))
w.ok = W.Button((10, 70, 80, 16), "Ok", w.close)
w.setdefaultbutton(w.ok)
w.open()
import W
w = W.Window((600, 400), "Ha!", minsize = (240, 200))
w.panes = W.HorizontalPanes((8, 8, -30, -8), (0.3, 0.3, 0.4))
w.panes.blah1 = W.EditText(None, "eehhh...")
w.panes.blah2 = W.EditText((8, 8, -8, -8), "xxx nou...")
w.panes.panes = W.VerticalPanes(None, (0.3, 0.4, 0.3))
w.panes.panes.blah1 = W.EditText(None, "eehhh...")
w.panes.panes.blah2 = W.Frame(None)
w.panes.panes.blah2.t = W.EditText((0, 0, 0, 0), "nou...")
w.panes.panes.blah3 = W.List(None, ["eehhh...", 'abc', 'def'])
w.open()
import W
w = W.Window((600, 400), "Ha!", minsize = (240, 200))
w.panes = W.HorizontalPanes((8, 8, -8, -20), (0.6, 0.4))
w.panes.panes = W.VerticalPanes(None, (0.3, 0.4, 0.3))
w.panes.panes.blah1 = W.EditText(None, "eehhh...")
w.panes.panes.blah2 = W.EditText(None, "nou...")
w.panes.panes.blah3 = W.List(None, ["eehhh...", 'abc', 'def'])
w.panes.group = W.Group(None)
w.panes.group.mytext = W.EditText((0, 24, 0, 0), "eehhh...")
w.panes.group.button1 = W.Button((0, 0, 80, 16), "A Button")
w.open()
import W
# make a non-sizable window
#window = W.Window((200, 200), "Fixed Size")
# make a sizable window
window = W.Window((200, 300), "Variable Size!", minsize = (200, 200))
# make some edit text widgets
# a scrollbar
window.hbar = W.Scrollbar((-1, -15, -14, 16), max = 100)
window.vbar = W.Scrollbar((-15, -1, 16, -14), max = 100)
#window.vbar = W.Scrollbar((-15, -1, 1, -14), max = 100)
# open the window
window.open()
import W
def twothird(width, height):
return (8, 8, width - 8, 2*height/3 - 4)
def onethird(width, height):
return (8, 2*height/3 + 4, width - 8, height - 22)
def halfbounds1(width, height):
return (0, 0, width/2 - 4, height)
def halfbounds2(width, height):
return (width/2 + 4, 0, width, height)
window = W.Window((400, 400), "Sizable window with two lists", minsize = (200, 200))
window.listgroup = W.Group(twothird)
window.listgroup.list1 = W.List(halfbounds1, range(13213, 13310))
window.listgroup.list2 = W.List(halfbounds2, range(800, 830))
window.et = W.EditText(onethird, "Wat nu weer?")
window.open()
import W
# define some callbacks
def callback():
window.close()
def checkcallback(value):
print "hit the checkbox", value
def radiocallback(value):
print "hit radiobutton #3", value
def scrollcallback(value):
widget = window.hbar
if value == "+":
widget.set(widget.get() - 1)
elif value == "-":
widget.set(widget.get() + 1)
elif value == "++":
widget.set(widget.get() - 10)
elif value == "--":
widget.set(widget.get() + 10)
else: # in thumb
widget.set(value)
print "scroll...", widget.get()
def textcallback():
window.et3.set(window.et1.get())
def cancel():
import EasyDialogs
EasyDialogs.Message("Cancel!")
# make a non-sizable window
#window = W.Window((200, 300), "Fixed Size")
# make a sizable window
window = W.Window((200, 300), "Variable Size!", minsize = (200, 300))
# make some edit text widgets
window.et1 = W.EditText((10, 10, 110, 110), "Hallo!", textcallback)
window.et2 = W.EditText((130, 40, 60, 30), "one!")
window.et3 = W.EditText((130, 80, -10, 40), "two?")
# a button
window.button = W.Button((-70, 10, 60, 16), "Close", callback)
# a checkbox
window.ch = W.CheckBox((10, 130, 160, 16), "Check (command \xa4)", checkcallback)
# set of radio buttons (should become easier/nicer)
thebuttons = []
window.r1 = W.RadioButton((10, 150, 180, 16), "Radio 1 (cmd 1)", thebuttons)
window.r2 = W.RadioButton((10, 170, 180, 16), "Radio 2 (cmd 2)", thebuttons)
window.r3 = W.RadioButton((10, 190, 180, 16), "Radio 3 (cmd 3)", thebuttons, radiocallback)
window.r1.set(1)
# a normal button
window.cancelbutton = W.Button((10, 220, 60, 16), "Cancel", cancel)
# a scrollbar
window.hbar = W.Scrollbar((-1, -15, -14, 16), scrollcallback, max = 100)
# some static text
window.static = W.TextBox((10, 260, 110, 16), "Schtatic")
# bind some keystrokes to functions
window.bind('cmd\xa4', window.ch.push)
window.bind('cmd1', window.r1.push)
window.bind('cmd2', window.r2.push)
window.bind('cmd3', window.r3.push)
window.bind('cmdw', window.button.push)
window.bind('cmd.', window.cancelbutton.push)
window.setdefaultbutton(window.button)
# open the window
window.open()
if 0:
import time
for i in range(20):
window.et2.set(repr(i))
#window.et2.SetPort()
#window.et2.draw()
time.sleep(0.1)
A separator ends with '---'
\ No newline at end of file
Set Defines "-d MPW -d HAVE_CONFIG_H"
Set Includes "-i :: -i ::Include -i ::Mac"
Set SymOptions "-sym off"
Set ModelOptions "-model far"
Set OtherOptions "-warnings off"
Set LinkOptions "{SymOptions} {ModelOptions}"
Set COptions "{OtherOptions} {SymOptions} {ModelOptions} {Defines} {Includes}"
# For compiling code resources; Restrictions apply
Set ResCOptions "{SymOptions} -model near -b {Defines} {Includes} "
Export ResCOptions
Export COptions
Export LinkOptions
# modules with the source in a single sub directory
Date
Directory {Python}
for MODULE in Parser Mac Modules Objects Python
Directory :{MODULE}:
Echo "### `Directory`: make {1}"
make {1} > makefile.out
makefile.out
Directory ::
end
Echo "### `Directory`: make {1}"
make {1} > makefile.out
makefile.out
"""Build a "big" applet for the IDE, and put it in the Python home
directory. It will contain all IDE-specific modules as PYC resources,
which reduces the startup time (especially on slower machines)."""
import sys
import os
import buildtools
from Carbon 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.FSpOpenResFile(dstfilename, 3)
Res.UseResFile(targetref)
files = os.listdir(ide_home)
# skip this script and the main program
files = filter(lambda x: x[-3:] == '.py' and
x not in ("BuildIDE.py", "PythonIDE.py"), files)
# add the modules as PYC resources
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)
# add W resources
wresref = Res.FSpOpenResFile(os.path.join(ide_home, "Widgets.rsrc"), 1)
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
from Carbon import TextEdit
from Carbon 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(repr(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(repr(self.lasttab))
self.tabmode = tabmode
self.doit()
def set(self, fontsettings):
font, style, size, color = fontsettings
if type(font) <> types.StringType:
from Carbon 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(repr(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(repr(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(repr(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 marshal
import types
from Carbon import Folder
from Carbon import Folders
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, ValueError):
# file not found, or currupt marshal data
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'))
try:
MacOS.SetCreatorAndType(self.__path, self.__creator, 'pref')
except:
pass
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.
fsr = Folder.FSFindFolder(Folders.kOnSystemDisk, 'pref', 1)
prefsfolder = fsr.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
from Carbon import Qd
__version__ = "0.2"
__author__ = "jvr"
class _modulebrowser:
def __init__(self):
self.editmodules = []
self.modules = []
self.window = W.Window((210, 1000), "Module Browser", minsize = (210, 160), maxsize = (340, 20000))
self.window.openbutton = W.Button((10, 8, 90, 16), "Open", self.openbuttonhit)
self.window.browsebutton = W.Button((110, 8, 90, 16), "Browse\xc9", self.browsebuttonhit)
self.window.reloadbutton = W.Button((10, 32, 90, 16), "Reload", self.reloadbuttonhit)
self.window.openotherbutton = W.Button((110, 32, 90, 16), "Open other\xc9", 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("Can't 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("Can't 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 can't 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()
This diff was suppressed by a .gitattributes entry.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleDocumentTypes</key>
<array>
</array>
<key>CFBundleExecutable</key>
<string>PackageManager</string>
<key>CFBundleGetInfoString</key>
<string>2.5alpha0, (c) 2004 Python Software Foundation.</string>
<key>CFBundleIconFile</key>
<string>PackageManager.icns</string>
<key>CFBundleIdentifier</key>
<string>org.python.pythonide</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleLongVersionString</key>
<string>2.5alpha0, (c) 2004 Python Software Foundation.</string>
<key>CFBundleName</key>
<string>PythonIDE</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>2.5alpha0</string>
<key>CFBundleSignature</key>
<string>Pide</string>
<key>CFBundleVersion</key>
<string>2.5alpha0</string>
<key>CSResourcesFileMapped</key>
<true/>
<key>LSRequiresCarbon</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>(c) 2004 Python Software Foundation.</string>
</dict>
</plist>
This diff is collapsed.
import W
from Carbon import Evt
import EasyDialogs
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 = []
x = 54
width1 = 50
width2 = 75
for name in ["calls", "time", "cumulative", "stdname", "file", "line", "name"]:
if len(name) > 6:
width = width2
else:
width = width1
self.w["button_" + name] = W.RadioButton((x, 4, width, 12), name, self.buttons, self.setsort)
x += width + 10
self.w.button_calls.set(1)
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:
filename = EasyDialogs.AskFileForOpen(message='Profiler data')
if not filename: sys.exit(0)
stats = pstats.Stats(filename)
browser = ProfileBrowser(stats)
if __name__ == '__main__':
main()
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
import re
import W
import os
import MacPrefs
import MacOS
import string
import webbrowser
import EasyDialogs
app = W.getapplication()
_titlepat = re.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 = text.lower()
matcher = _titlepat.search(lowertext)
if matcher:
return matcher.group(1)
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
_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 = W.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
def listhit(self, isdbl = 1):
if isdbl:
for i in self.w.results.getselection():
path = self.hits[i][1]
url = "file://" + "/".join(path.split(":"))
webbrowser.open(url)
class Status:
def __init__(self):
self.w = W.Dialog((440, 64), "Searching\xc9")
self.w.searching = W.TextBox((4, 4, -4, 16), "")
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: %r' % (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:
if hasattr(MacOS, 'EnableAppswitch'):
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:
if hasattr(MacOS, 'EnableAppswitch'):
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, 100, 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((120, -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)
def setdocpath(self):
docpath = EasyDialogs.AskFolder()
if docpath:
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-2001:
# Mitchell S. Chapman,
# Zachary Roadhouse,
# Tim Peters,
# Just van Rossum
__version__ = "0.4"
import string
import re
# 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", "exec",
"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", "yield"]
# Build up a regular expression which will match anything
# interesting, including multi-line triple-quoted strings.
commentPat = r"#[^\n]*"
pat = r"q[^\\q\n]*(\\[\000-\377][^\\q\n]*)*q"
quotePat = replace(pat, "q", "'") + "|" + replace(pat, 'q', '"')
# Way to go, Tim!
pat = r"""
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 = r"(^|[^a-zA-Z0-9_.\"'])"
keyPat = nonKeyPat + "(" + "|".join(keywordsList) + ")" + nonKeyPat
matchPat = commentPat + "|" + keyPat + "|" + tripleQuotePat + "|" + quotePat
matchRE = re.compile(matchPat)
idKeyPat = "[ \t]*[A-Za-z_][A-Za-z_0-9.]*" # Ident w. leading whitespace.
idRE = re.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
idSearch = idRE.search
tags = []
tags_append = tags.append
commentTag = 'comment'
stringTag = 'string'
keywordTag = 'keyword'
identifierTag = 'identifier'
start = 0
end = searchfrom
while 1:
m = search(pytext, end)
if m is None:
break # EXIT LOOP
start = m.start()
if start >= searchto:
break # EXIT LOOP
match = m.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"]:
m = idSearch(pytext, end)
if m is not None:
start = m.start()
if start == end:
match = m.group(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, repr(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):
import codeop
self._pybuf = ""
self._compile = codeop.Compile()
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 = self._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 = self._compile(self._pybuf + "\n", "<input>", "single")
except SyntaxError, err1:
pass
try:
code2 = self._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
This diff was suppressed by a .gitattributes entry.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>py</string>
</array>
<key>CFBundleTypeIconFile</key>
<string>PythonSource.icns</string>
<key>CFBundleTypeName</key>
<string>Python Module</string>
<key>CFBundleTypeOSTypes</key>
<array>
<string>TEXT</string>
</array>
<key>CFBundleTypeRole</key>
<string>Editor</string>
</dict>
</array>
<key>CFBundleExecutable</key>
<string>PythonIDE</string>
<key>CFBundleGetInfoString</key>
<string>2.5alpha0, (c) 2004 Python Software Foundation.</string>
<key>CFBundleHelpBookFolder</key>
<array>
<string>PythonDocumentation</string>
</array>
<key>CFBundleHelpBookName</key>
<string>Python Help</string>
<key>CFBundleHelpTOCFile</key>
<string>index.html</string>
<key>CFBundleIconFile</key>
<string>PythonIDE.icns</string>
<key>CFBundleIdentifier</key>
<string>org.python.pythonide</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleLongVersionString</key>
<string>2.5alpha0, (c) 2004 Python Software Foundation.</string>
<key>CFBundleName</key>
<string>PythonIDE</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>2.5alpha0</string>
<key>CFBundleSignature</key>
<string>Pide</string>
<key>CFBundleVersion</key>
<string>2.5alpha0</string>
<key>CSResourcesFileMapped</key>
<true/>
<key>LSRequiresCarbon</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>(c) 2004 Python Software Foundation.</string>
</dict>
</plist>
# copyright 1996-2001 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.0.2'
import sys
import os
def init():
import MacOS
if hasattr(MacOS, 'EnableAppswitch'):
MacOS.EnableAppswitch(-1)
try:
import autoGIL
except ImportError:
pass
else:
autoGIL.installAutoGIL()
from Carbon import Qd, QuickDraw
Qd.SetCursor(Qd.GetCursor(QuickDraw.watchCursor).data)
import macresource
import sys, os
macresource.need('DITL', 468, "PythonIDE.rsrc")
widgetrespathsegs = [sys.exec_prefix, "Mac", "Tools", "IDE", "Widgets.rsrc"]
widgetresfile = os.path.join(*widgetrespathsegs)
if not os.path.exists(widgetresfile):
widgetrespathsegs = [os.pardir, "Tools", "IDE", "Widgets.rsrc"]
widgetresfile = os.path.join(*widgetrespathsegs)
refno = macresource.need('CURS', 468, widgetresfile)
if os.environ.has_key('PYTHONIDEPATH'):
# For development set this environment variable
ide_path = os.environ['PYTHONIDEPATH']
elif refno:
# We're not a fullblown application
idepathsegs = [sys.exec_prefix, "Mac", "Tools", "IDE"]
ide_path = os.path.join(*idepathsegs)
if not os.path.exists(ide_path):
idepathsegs = [os.pardir, "Tools", "IDE"]
for p in sys.path:
ide_path = os.path.join(*([p]+idepathsegs))
if os.path.exists(ide_path):
break
else:
# We are a fully frozen application
ide_path = sys.argv[0]
if ide_path not in sys.path:
sys.path.insert(1, ide_path)
init()
del init
import PythonIDEMain as _PythonIDEMain
_PythonIDEMain.PythonIDE()
This diff is collapsed.
from Carbon import Dlg
from Carbon import Res
splash = Dlg.GetNewDialog(468, -1)
splash.DrawDialog()
from Carbon import Qd, TE, Fm
from Carbon import Win
from Carbon.Fonts import *
from Carbon.QuickDraw import *
from Carbon.TextEdit import teJustCenter
import string
import sys
_about_width = 440
_about_height = 340
_keepsplashscreenopen = 0
abouttext1 = """The Python Integrated Development Environment for the Macintosh\xaa
Version: %s
Copyright 1997-2001 Just van Rossum, Letterror. <just@letterror.com>
Python %s
%s
See: <http://www.python.org/> for information and documentation."""
flauwekul = [ "Goodday, Bruce.",
"What's new?",
"Nudge, nudge, say no more!",
"No, no sir, it's not dead. It's resting.",
"Albatros!",
"It's . . .",
"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 skipdoublereturns(text):
return string.replace(text, '\n\n', '\n')
def nl2return(text):
return string.replace(text, '\n', '\r')
def UpdateSplash(drawdialog = 0, what = 0):
if drawdialog:
splash.DrawDialog()
drawtext(what)
splash.GetDialogWindow().ValidWindowRect(splash.GetDialogPort().GetPortBounds())
splash.GetDialogWindow().GetWindowPort().QDFlushPortBuffer(None)
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, 115, _about_width - 10, _about_height - 30)
if not what:
import __main__
abouttxt = nl2return(abouttext1 % (
__main__.__version__, sys.version, skipdoublereturns(sys.copyright)))
else:
import random
abouttxt = nl2return(random.choice(flauwekul))
TE.TETextBox(abouttxt, rect, teJustCenter)
UpdateSplash(1)
def wait():
from Carbon import Evt
from Carbon import Events
global splash
try:
splash
except NameError:
return
Qd.InitCursor()
time = Evt.TickCount()
whattext = 0
drawtext(whattext)
while _keepsplashscreenopen:
ok, event = Evt.EventAvail(Events.highLevelEventMask)
if ok:
# got apple event, back to mainloop
break
ok, event = Evt.EventAvail(Events.mDownMask | Events.keyDownMask | Events.updateMask)
if ok:
ok, event = Evt.WaitNextEvent(Events.mDownMask | Events.keyDownMask | Events.updateMask, 30)
if ok:
(what, message, when, where, modifiers) = event
if what == Events.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
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 getdefaultfont():
prefs = getapplication().getprefs()
if not prefs.defaultfont:
prefs.defaultfont = ("Geneva", 0, 10, (0, 0, 0))
return prefs.defaultfont
def Message(text):
import EasyDialogs, string
from Carbon import Qd
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'
clearkey = '\033'
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.
"""Minimal W application."""
import Wapplication
import macresource
import os
class TestApp(Wapplication.Application):
def __init__(self):
from Carbon import Res
# macresource.open_pathname("Widgets.rsrc")
self._menustocheck = []
self.preffilepath = os.path.join("Python", "PythonIDE preferences")
Wapplication.Application.__init__(self, 'Pyth')
# open a new text editor
import PyEdit
PyEdit.Editor()
# start the mainloop
self.mainloop()
TestApp()
import os
from Carbon import Qd
from Carbon import Win
from Carbon import Qt, QuickTime
import W
from Carbon import File
from Carbon import Evt, Events
_moviesinitialized = 0
def EnterMovies():
global _moviesinitialized
if not _moviesinitialized:
Qt.EnterMovies()
_moviesinitialized = 1
class Movie(W.Widget):
def __init__(self, possize):
EnterMovies()
self.movie = None
self.running = 0
W.Widget.__init__(self, possize)
def adjust(self, oldbounds):
self.SetPort()
self.GetWindow().InvalWindowRect(oldbounds)
self.GetWindow().InvalWindowRect(self._bounds)
self.calcmoviebox()
def set(self, path_or_fss, start = 0):
self.SetPort()
if self.movie:
#self.GetWindow().InvalWindowRect(self.movie.GetMovieBox())
Qd.PaintRect(self.movie.GetMovieBox())
path = File.pathname(path)
self.movietitle = os.path.basename(path)
movieResRef = Qt.OpenMovieFile(path_or_fss, 1)
self.movie, dummy, dummy = Qt.NewMovieFromFile(movieResRef, 0, QuickTime.newMovieActive)
self.moviebox = self.movie.GetMovieBox()
self.calcmoviebox()
Qd.ObscureCursor() # XXX does this work at all?
self.movie.GoToBeginningOfMovie()
if start:
self.movie.StartMovie()
self.running = 1
else:
self.running = 0
self.movie.MoviesTask(0)
def get(self):
return self.movie
def getmovietitle(self):
return self.movietitle
def start(self):
if self.movie:
Qd.ObscureCursor()
self.movie.StartMovie()
self.running = 1
def stop(self):
if self.movie:
self.movie.StopMovie()
self.running = 0
def rewind(self):
if self.movie:
self.movie.GoToBeginningOfMovie()
def calcmoviebox(self):
if not self.movie:
return
ml, mt, mr, mb = self.moviebox
wl, wt, wr, wb = widgetbox = self._bounds
mheight = mb - mt
mwidth = mr - ml
wheight = wb - wt
wwidth = wr - wl
if (mheight * 2 < wheight) and (mwidth * 2 < wwidth):
scale = 2
elif mheight > wheight or mwidth > wwidth:
scale = min(float(wheight) / mheight, float(wwidth) / mwidth)
else:
scale = 1
mwidth, mheight = mwidth * scale, mheight * scale
ml, mt = wl + (wwidth - mwidth) / 2, wt + (wheight - mheight) / 2
mr, mb = ml + mwidth, mt + mheight
self.movie.SetMovieBox((ml, mt, mr, mb))
def idle(self, *args):
if self.movie:
if not self.movie.IsMovieDone() and self.running:
Qd.ObscureCursor()
while 1:
self.movie.MoviesTask(0)
gotone, event = Evt.EventAvail(Events.everyEvent)
if gotone or self.movie.IsMovieDone():
break
elif self.running:
box = self.movie.GetMovieBox()
self.SetPort()
self.GetWindow().InvalWindowRect(box)
self.movie = None
self.running = 0
def draw(self, visRgn = None):
if self._visible:
Qd.PaintRect(self._bounds)
if self.movie:
self.movie.UpdateMovie()
self.movie.MoviesTask(0)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
import re
import os
# The regular expression for freeze directives. These are comments with the
# word macfreeze immedeately followed by a colon, followed by a directive,
# followed by argument(s)
#
# The directives supported are
# include - Include a module or file
# exclude - Exclude a module
# optional - Include a module if it is found, but don't complain if it isn't
# path - Add sys.path entries. Relative paths are relative to the source file.
#
# See the macfreeze.py main program for a real live example.
#
DIRECTIVE_RE=r'^\s*#\s*macfreeze:\s*(\S*)\s*(.*)\s*$'
REPROG=re.compile(DIRECTIVE_RE)
def findfreezedirectives(program):
extra_modules = []
exclude_modules = []
optional_modules = []
extra_path = []
progdir, filename = os.path.split(program)
fp = open(program)
for line in fp.readlines():
match = REPROG.match(line)
if match:
directive = match.group(1)
argument = match.group(2)
if directive == 'include':
extra_modules.append(argument)
elif directive == 'exclude':
exclude_modules.append(argument)
elif directive == 'optional':
optional_modules.append(argument)
elif directive == 'path':
argument = os.path.join(progdir, argument)
extra_path.append(argument)
else:
print '** Unknown directive', line
return extra_modules, exclude_modules, optional_modules, extra_path
import sys
print 'Hello world'
print 'Builtin modules:', sys.builtin_module_names
sys.exit(1)
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
"""macgen_info - Generate informational output"""
def generate(output, module_dict):
for name in module_dict.keys():
print 'Include %-20s\t'%name,
module = module_dict[name]
print module.gettype(), '\t', repr(module)
return 0
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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