Kaydet (Commit) cb5704e6 authored tarafından Jack Jansen's avatar Jack Jansen

Initial revision

üst 7cc5735e
# copyright 1997 Just van Rossum, Letterror. just@knoware.nl
import Splash
import FrameWork
import WFrameWorkPatch
import Win
import W
import os
import macfs
class PythonIDE(WFrameWorkPatch.Application):
def __init__(self):
self.preffilepath = ":Python:PythonIDE preferences"
WFrameWorkPatch.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()
PyConsole.installconsole()
PyConsole.installoutput()
import sys
for path in sys.argv[1:]:
self.opendoc(path)
self.mainloop()
def makeusermenus(self):
m = WFrameWorkPatch.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)
quititem = FrameWork.MenuItem(m, "Quit", "Q", 'quit')
m = WFrameWorkPatch.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 = WFrameWorkPatch.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)
self.openwindowsmenu = WFrameWorkPatch.Menu(self.menubar, 'Windows')
self.makeopenwindowsmenu()
self._menustocheck = [closeitem, saveitem, saveasitem,
undoitem, cutitem, copyitem, pasteitem,
selallitem, sellineitem,
finditem, findagainitem, enterselitem, replaceitem, replacefinditem,
shiftleftitem, shiftrightitem,
runitem, runselitem]
prefs = self.getprefs()
if prefs.scriptsfolder:
fss, fss_changed = macfs.RawAlias(prefs.scriptsfolder).Resolve()
self.scriptsfolder = fss.NewAlias()
prefs.scriptsfolder = self.scriptsfolder.data
self.scriptsfoldermodtime = fss.GetDates()[1]
else:
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]
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:
item = FrameWork.MenuItem(self.openwindowsmenu, title, 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()
PyEdit.searchengine.writeprefs()
for window in self._windows.values():
if window.close() > 0:
return
self.quitting = 1
PythonIDE()
(This file must be converted with BinHex 4.0)
:$&GTC'GPG(-ZFR0bB`"bFh*M8P0&4!%!N!F5HcQ*!*!%!3!!!"%3!!!3%!!!!@X
*!!!!E'PZC@CTC@aNF`N!!!"6Bh*[E'aLBA*c"`!!!!aAD@4RCA4c,R*cFQ0bEfa
c)&"bC@Cc1'XJ-LiiBMGi!!"bFh*M8P0&4!%!rj!%!*!5X6"P#!#3"K*lEhKc#!!
!!'PZCQpdCAKdF`B!!!"#GA4dEfjc!`!!!(*eER-*!!!!FR9ZBR9dG'pZF``!!!"
bG@jcC@aPBh4TEfjc$!!!!(*eER0PE'*eG(4[ER-%!!!!BQPZC(-%!!!!F(9cD(-
0!!!!E@9ZG9pREh4[E'PZCA-*!!!!FfKTCR4XC3!!!-3!a!#3"3X!#`!4![m-!2r
q!!!!5!!!!%J!N!F,!!X!N!8"!!S!N!8,!!X!N!#!"!#3"3X!#`#3#8J!!!")!*!
&!J!"!!)!N!e(IP3!!!!#!!$rN!B!!Cb3"2rr!!)!N!X,!!X!N!8,!!X!!!#!!!!
!S!!!!*J!!!#'!!!!NB!!!)4J!!#4J!!!KJ!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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
import random
_keepsplashscreenopen = 0
abouttext1 = """The Python Integrated Developement Environment for the Macintosh
Version: %s
Copyright 1997 Just van Rossum, Letterror. <just@knoware.nl>
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:
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()
"""usage:
newsettings = print FontDialog(('Chicago', 0, 12, (0, 0, 0))) # font name or id, style flags, size, color (color is ignored)
if newsettings:
font, style, size, color = newsettings # 'font' is always the font name, not the id number
# do something
"""
import W
import PyEdit
import TextEdit
import string
import types
_stylenames = ["Plain", "Bold", "Italic", "Underline", "Outline", "Shadow", "Condensed", "Extended"]
class _FontDialog:
def __init__(self, fontsettings):
leftmargin = 46
self.w = W.ModalDialog((440, 180), 'Font settings')
self.w.fonttitle = W.TextBox((10, 12, 30, 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, 30, 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, 30, 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)
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)
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 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
return (font, style, size, (0, 0, 0))
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`)
self.w.sample.setfontsettings(self.get())
def checksize(self):
size = self.w.sizeedit.get()
if not size:
return
try:
size = string.atoi(size)
except (ValueError, OverflowError):
good = 0
else:
good = 1 <= size <= 500
if good:
if self.lastsize <> size:
self.lastsize = size
self.doit()
else:
# beep!
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 cancel(self):
self.w.close()
def done(self):
self._rv = self.get()
self.w.close()
def setfont(self, fontname):
self.w.fontname.set(fontname)
self.doit()
def FontDialog(fontsettings):
fd = _FontDialog(fontsettings)
return fd._rv
def test():
print FontDialog(('Zapata-Light', 0, 25, (0, 0, 0)))
import macfs
import marshal
import os
import macostools
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'):
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
__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.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):
if path[-3:] == '.py':
W.getapplication().openscript(path)
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:
m = sys.modules[self.window.list[i]]
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
modules = sys.modules.keys()
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':
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
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_module = W.RadioButton((404, 4, 55, 12), 'module', self.buttons, self.setsort)
self.w.button_name = W.RadioButton((464, 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.
import W
import Fm
from WASTEconst import *
from SpecialKeys import *
from types import *
import Events
import string
import sys,os
import traceback
import MacOS
import MacPrefs
import PyInteractive
if not hasattr(sys, 'ps1'):
sys.ps1 = '>>> '
if not hasattr(sys, 'ps2'):
sys.ps2 = '... '
class ConsoleTextWidget(W.EditText):
def __init__(self, *args, **kwargs):
apply(W.EditText.__init__, (self,) + args, kwargs)
self._inputstart = 0
self._buf = ''
self.pyinteractive = PyInteractive.PyInteractive()
import __main__
self._namespace = __main__.__dict__
def insert(self, text):
self.checkselection()
self.ted.WEInsert(text, None, None)
self.changed = 1
self.selchanged = 1
def set_namespace(self, dict):
if type(dict) <> DictionaryType:
raise TypeError, "The namespace needs to be a dictionary"
self._namespace = dict
def open(self):
W.EditText.open(self)
self.write('Python ' + sys.version + '\n' + sys.copyright + '\n')
self.write(sys.ps1)
self.flush()
def key(self, char, event):
(what, message, when, where, modifiers) = event
if self._enabled and not modifiers & Events.cmdKey or char in arrowkeys:
if char not in navigationkeys:
self.checkselection()
if char == enterkey:
char = returnkey
selstart, selend = self.getselection()
if char == backspacekey:
if selstart <= (self._inputstart - (selstart <> selend)):
return
self.ted.WEKey(ord(char), modifiers)
if char not in navigationkeys:
self.changed = 1
if char not in scrollkeys:
self.selchanged = 1
self.updatescrollbars()
if char == returnkey:
text = self.get()[self._inputstart:selstart]
saveyield = MacOS.EnableAppswitch(0)
self.pyinteractive.executeline(text, self, self._namespace)
MacOS.EnableAppswitch(saveyield)
selstart, selend = self.getselection()
self._inputstart = selstart
def domenu_save_as(self, *args):
import macfs
fss, ok = macfs.StandardPutFile('Save console text as:', 'console.txt')
if not ok:
return
f = open(fss.as_pathname(), 'wb')
f.write(self.get())
f.close()
fss.SetCreatorType(W._signature, 'TEXT')
def write(self, text):
self._buf = self._buf + text
if '\n' in self._buf:
self.flush()
def flush(self):
stuff = string.split(self._buf, '\n')
stuff = string.join(stuff, '\r')
self.setselection_at_end()
self.ted.WEInsert(stuff, None, None)
selstart, selend = self.getselection()
self._inputstart = selstart
self._buf = ""
self.ted.WEClearUndo()
self.updatescrollbars()
def selection_ok(self):
selstart, selend = self.getselection()
return not (selstart < self._inputstart or selend < self._inputstart)
def checkselection(self):
if not self.selection_ok():
self.setselection_at_end()
def setselection_at_end(self):
end = self.ted.WEGetTextLength()
self.setselection(end, end)
self.updatescrollbars()
def domenu_cut(self, *args):
if not self.selection_ok():
return
W.EditText.domenu_cut(self)
def domenu_paste(self, *args):
if not self.selection_ok():
self.setselection_at_end()
W.EditText.domenu_paste(self)
def domenu_clear(self, *args):
if not self.selection_ok():
return
W.EditText.domenu_clear(self)
class PyConsole(W.Window):
def __init__(self, bounds, show = 1, fontsettings = ("Monaco", 0, 9, (0, 0, 0)), unclosable = 0):
W.Window.__init__(self,
bounds,
"Python Interactive",
minsize = (200, 100),
tabbable = 0,
show = show)
self._unclosable = unclosable
consoletext = ConsoleTextWidget((-1, -1, -14, 1), inset = (6, 5), fontsettings = fontsettings)
self._bary = W.Scrollbar((-15, 14, 16, -14), consoletext.vscroll, max = 32767)
self.consoletext = consoletext
self.namespacemenu = W.PopupMenu((-15, -1, 16, 16), [], self.consoletext.set_namespace)
self.namespacemenu.bind('<click>', self.makenamespacemenu)
self.open()
def makenamespacemenu(self, *args):
W.SetCursor('watch')
namespacelist = self.getnamespacelist()
self.namespacemenu.set([("Font settings", self.dofontsettings),
["Namespace"] + namespacelist, ("Clear buffer", self.clearbuffer), ("Browse namespace", self.browsenamespace)])
currentname = self.consoletext._namespace["__name__"]
for i in range(len(namespacelist)):
if namespacelist[i][0] == currentname:
break
else:
return
# XXX this functionality should be generally available in Wmenus
submenuid = self.namespacemenu.menu.menu.GetItemMark(2)
menu = self.namespacemenu.menu.bar.menus[submenuid]
menu.menu.CheckItem(i + 1, 1)
def browsenamespace(self):
import PyBrowser, W
W.SetCursor('watch')
PyBrowser.Browser(self.consoletext._namespace, self.consoletext._namespace["__name__"])
def clearbuffer(self):
import Res
self.consoletext.ted.WEUseText(Res.Resource(''))
self.consoletext.write(sys.ps1)
self.consoletext.flush()
def getnamespacelist(self):
import __main__
editors = filter(lambda x: x.__class__.__name__ == "Editor", self.parent._windows.values())
namespaces = [ ("__main__",__main__.__dict__) ]
for ed in editors:
modname = os.path.splitext(ed.title)[0]
if sys.modules.has_key(modname):
module = sys.modules[modname]
namespaces.append((modname, module.__dict__))
else:
if ed.title[-3:] == '.py':
modname = ed.title[:-3]
else:
modname = ed.title
ed.globals["__name__"] = modname
namespaces.append((modname, ed.globals))
return namespaces
def dofontsettings(self):
import FontSettings
fontsettings = FontSettings.FontDialog(self.consoletext.getfontsettings())
if fontsettings:
self.consoletext.setfontsettings(fontsettings)
def show(self, onoff = 1):
W.Window.show(self, onoff)
if onoff:
self.select()
def close(self):
if self._unclosable:
self.show(0)
return -1
W.Window.close(self)
def writeprefs(self):
prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
prefs.console.show = self.isvisible()
prefs.console.windowbounds = self.getbounds()
prefs.console.fontsettings = self.consoletext.getfontsettings()
prefs.save()
class OutputTextWidget(W.EditText):
def _getflags(self):
import WASTEconst
return WASTEconst.weDoAutoScroll | WASTEconst.weDoMonoStyled | \
WASTEconst.weDoUndo
class PyOutput:
def __init__(self):
self.w = None
self.closed = 1
self._buf = ''
# should be able to set this
self.savestdout, self.savestderr = sys.stdout, sys.stderr
sys.stderr = sys.stdout = self
def write(self, text):
self._buf = self._buf + text
if '\n' in self._buf:
self.flush()
def flush(self):
self.show()
stuff = string.split(self._buf, '\n')
stuff = string.join(stuff, '\r')
end = self.w.outputtext.ted.WEGetTextLength()
self.w.outputtext.setselection(end, end)
self.w.outputtext.ted.WEInsert(stuff, None, None)
self._buf = ""
self.w.outputtext.ted.WEClearUndo()
self.w.outputtext.updatescrollbars()
def show(self):
if self.closed:
if not self.w:
self.setupwidgets()
self.w.open()
self.closed = 0
else:
self.w.show(1)
self.closed = 0
self.w.select()
def setupwidgets(self):
self.w = W.Window((450, 200), "Output", minsize = (200, 100), tabbable = 0)
self.w.outputtext = OutputTextWidget((-1, -1, -14, 1), inset = (6, 5))
self.w._bary = W.Scrollbar((-15, -1, 16, -14), self.w.outputtext.vscroll, max = 32767)
self.w.bind("<close>", self.close)
self.w.bind("<activate>", self.activate)
def activate(self, onoff):
if onoff:
self.closed = 0
def close(self):
self.w.show(0)
self.closed = 1
return -1
def installconsole(defaultshow = 1):
global console
prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath)
if not prefs.console or not hasattr(prefs.console, 'show'):
prefs.console.show = defaultshow
if not hasattr(prefs.console, "windowbounds"):
prefs.console.windowbounds = (450, 250)
if not hasattr(prefs.console, "fontsettings"):
prefs.console.fontsettings = ("Monaco", 0, 9, (0, 0, 0))
console = PyConsole(prefs.console.windowbounds, prefs.console.show, prefs.console.fontsettings, 1)
def installoutput():
global output
output = PyOutput()
This diff is collapsed.
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 lists 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 = [
"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
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
"""Widgets for the Macintosh. Built on top of FrameWork"""
__version__ = "0.1"
from Wbase import *
from Wcontrols import *
from Wtext import *
from Wlist 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
Qd.InitCursor()
if text:
EasyDialogs.Message(text)
else:
EasyDialogs.Message('<Alert text not specified>')
import FrameWork
import Win
import Qd
import MacOS
import Events
import traceback
from types import *
import Menu; MenuToolbox = Menu; del Menu
class Application(FrameWork.Application):
def __init__(self, signature = 'Pyth'):
import W
W.setapplication(self, signature)
FrameWork.Application.__init__(self)
self._suspended = 0
self.quitting = 0
self.debugger_quitting = 1
self.DebuggerQuit = 'DebuggerQuitDummyException'
def mainloop(self, mask = FrameWork.everyEvent, wait = 0):
import W
self.quitting = 0
saveyield = MacOS.EnableAppswitch(-1)
try:
while not self.quitting:
try:
self.do1event(mask, wait)
except W.AlertError, detail:
MacOS.EnableAppswitch(-1)
W.Message(detail)
except self.DebuggerQuit:
MacOS.EnableAppswitch(-1)
except:
MacOS.EnableAppswitch(-1)
import PyEdit
PyEdit.tracebackwindow.traceback()
finally:
MacOS.EnableAppswitch(1)
def debugger_mainloop(self, mask = FrameWork.everyEvent, wait = 0):
import W
self.debugger_quitting = 0
saveyield = MacOS.EnableAppswitch(-1)
try:
while not self.quitting and not self.debugger_quitting:
try:
self.do1event(mask, wait)
except W.AlertError, detail:
W.Message(detail)
except:
import PyEdit
PyEdit.tracebackwindow.traceback()
finally:
MacOS.EnableAppswitch(saveyield)
def idle(self, event):
if not self._suspended:
if not self.do_frontWindowMethod("idle", event):
Qd.InitCursor()
def do_frontWindowMethod(self, attr, *args):
wid = Win.FrontWindow()
if wid and self._windows.has_key(wid):
window = self._windows[wid]
if hasattr(window, attr):
handler = getattr(window, attr)
apply(handler, args)
return 1
def appendwindow(self, wid, window):
self._windows[wid] = window
self.makeopenwindowsmenu()
def removewindow(self, wid):
del self._windows[wid]
self.makeopenwindowsmenu()
def do_key(self, event):
(what, message, when, where, modifiers) = event
ch = chr(message & FrameWork.charCodeMask)
rest = message & ~FrameWork.charCodeMask
wid = Win.FrontWindow()
if modifiers & FrameWork.cmdKey:
if wid and self._windows.has_key(wid):
self.checkmenus(self._windows[wid])
else:
self.checkmenus(None)
event = (what, ord(ch) | rest, when, where, modifiers)
result = MenuToolbox.MenuKey(ord(ch))
id = (result>>16) & 0xffff # Hi word
item = result & 0xffff # Lo word
if id:
self.do_rawmenu(id, item, None, event)
return # here! we had a menukey!
#else:
# print "XXX Command-" +`ch`
# See whether the front window wants it
if wid and self._windows.has_key(wid):
window = self._windows[wid]
try:
do_char = window.do_char
except AttributeError:
do_char = self.do_char
do_char(ch, event)
# else it wasn't for us, sigh...
def do_inMenuBar(self, partcode, window, event):
Qd.InitCursor()
(what, message, when, where, modifiers) = event
self.checkopenwindowsmenu()
wid = Win.FrontWindow()
if wid and self._windows.has_key(wid):
self.checkmenus(self._windows[wid])
else:
self.checkmenus(None)
result = MenuToolbox.MenuSelect(where)
id = (result>>16) & 0xffff # Hi word
item = result & 0xffff # Lo word
self.do_rawmenu(id, item, window, event)
def do_updateEvt(self, event):
(what, message, when, where, modifiers) = event
wid = Win.WhichWindow(message)
if wid and self._windows.has_key(wid):
window = self._windows[wid]
window.do_rawupdate(wid, event)
else:
if wid:
wid.HideWindow()
import sys
sys.stderr.write("XXX killed unknown (crashed?) Python window.\n")
else:
MacOS.HandleEvent(event)
def suspendresume(self, onoff):
pass
def do_suspendresume(self, event):
# Is this a good idea???
(what, message, when, where, modifiers) = event
self._suspended = not message & 1
self.suspendresume(message & 1)
w = Win.FrontWindow()
if w:
# XXXX Incorrect, should stuff windowptr into message field
nev = (Events.activateEvt, w, when, where, message&1)
self.do_activateEvt(nev)
def checkopenwindowsmenu(self):
if self._openwindowscheckmark:
self.openwindowsmenu.menu.CheckItem(self._openwindowscheckmark, 0)
window = Win.FrontWindow()
if window:
for item, wid in self._openwindows.items():
if wid == window:
#self.pythonwindowsmenuitem.check(1)
self.openwindowsmenu.menu.CheckItem(item, 1)
self._openwindowscheckmark = item
break
else:
self._openwindowscheckmark = 0
#if self._openwindows:
# self.pythonwindowsmenuitem.enable(1)
#else:
# self.pythonwindowsmenuitem.enable(0)
def checkmenus(self, window):
for item in self._menustocheck:
callback = item.menu.items[item.item-1][2]
if type(callback) <> StringType:
item.enable(1)
elif hasattr(window, "domenu_" + callback):
if hasattr(window, "can_" + callback):
canhandler = getattr(window, "can_" + callback)
if canhandler(item):
item.enable(1)
else:
item.enable(0)
else:
item.enable(1)
else:
item.enable(0)
def makemenubar(self):
self.menubar = MenuBar(self)
FrameWork.AppleMenu(self.menubar, self.getabouttext(), self.do_about)
self.makeusermenus()
def scriptswalk(self, top, menu):
import os, macfs, string
try:
names = os.listdir(top)
except os.error:
FrameWork.MenuItem(menu, '(Scripts Folder not found)', None, None)
return
for name in names:
path = os.path.join(top, name)
name = string.strip(name)
if name[-3:] == '---':
menu.addseparator()
elif os.path.isdir(path):
submenu = FrameWork.SubMenu(menu, name)
self.scriptswalk(path, submenu)
else:
fss = macfs.FSSpec(path)
creator, type = fss.GetCreatorType()
if type == 'TEXT':
if name[-3:] == '.py':
name = name[:-3]
item = FrameWork.MenuItem(menu, name, None, self.domenu_script)
self._scripts[(menu.id, item.item)] = path
def domenu_script(self, id, item, window, event):
(what, message, when, where, modifiers) = event
path = self._scripts[(id, item)]
import os
if not os.path.exists(path):
self.makescriptsmenu()
import W
raise W.AlertError, "File not found."
if modifiers & FrameWork.optionKey:
self.openscript(path)
else:
import W, MacOS, sys
W.SetCursor("watch")
sys.argv = [path]
#cwd = os.getcwd()
#os.chdir(os.path.dirname(path) + ':')
try:
# xxx if there is a script window for this file,
# exec in that window's namespace.
# xxx what to do when it's not saved???
# promt to save?
MacOS.EnableAppswitch(0)
execfile(path, {'__name__': '__main__', '__file__': path})
except W.AlertError, detail:
MacOS.EnableAppswitch(-1)
raise W.AlertError, detail
except KeyboardInterrupt:
MacOS.EnableAppswitch(-1)
except:
MacOS.EnableAppswitch(-1)
import PyEdit
PyEdit.tracebackwindow.traceback(1)
else:
MacOS.EnableAppswitch(-1)
#os.chdir(cwd)
def openscript(self, filename, lineno = None, charoffset = 0):
import os, PyEdit, W
editor = self.getscript(filename)
if editor:
editor.select()
elif os.path.exists(filename):
editor = PyEdit.Editor(filename)
elif filename[-3:] == '.py':
import imp
modname = os.path.basename(filename)[:-3]
try:
f, filename, (suff, mode, dummy) = imp.find_module(modname)
except ImportError:
raise W.AlertError, "Cant find file for %s" % modname
else:
f.close()
if suff == '.py':
self.openscript(filename, lineno, charoffset)
return
else:
raise W.AlertError, "Cant find file for %s" % modname
else:
raise W.AlertError, "Cant find file %s" % filename
if lineno is not None:
editor.selectline(lineno, charoffset)
return editor
def getscript(self, filename):
if filename[:1] == '<' and filename[-1:] == '>':
filename = filename[1:-1]
import string
lowpath = string.lower(filename)
for wid, window in self._windows.items():
if hasattr(window, "path") and lowpath == string.lower(window.path):
return window
elif hasattr(window, "path") and filename == wid.GetWTitle():
return window
def getprefs(self):
import MacPrefs
return MacPrefs.GetPrefs(self.preffilepath)
class MenuBar(FrameWork.MenuBar):
possibleIDs = range(10, 256)
def getnextid(self):
id = self.possibleIDs[0]
del self.possibleIDs[0]
return id
def __init__(self, parent = None):
self.bar = MenuToolbox.GetMenuBar()
MenuToolbox.ClearMenuBar()
self.menus = {}
self.parent = parent
def dispatch(self, id, item, window, event):
if self.menus.has_key(id):
self.menus[id].dispatch(id, item, window, event)
def delmenu(self, id):
MenuToolbox.DeleteMenu(id)
if id in self.possibleIDs:
print "XXX duplicate menu ID!", id
self.possibleIDs.append(id)
class Menu(FrameWork.Menu):
def dispatch(self, id, item, window, event):
title, shortcut, callback, kind = self.items[item-1]
if type(callback) == StringType:
callback = self._getmenuhandler(callback)
if callback:
import W
W.CallbackCall(callback, 0, id, item, window, event)
def _getmenuhandler(self, callback):
menuhandler = None
wid = Win.FrontWindow()
if wid and self.bar.parent._windows.has_key(wid):
window = self.bar.parent._windows[wid]
if hasattr(window, "domenu_" + callback):
menuhandler = getattr(window, "domenu_" + callback)
elif hasattr(self.bar.parent, "domenu_" + callback):
menuhandler = getattr(self.bar.parent, "domenu_" + callback)
elif hasattr(self.bar.parent, "domenu_" + callback):
menuhandler = getattr(self.bar.parent, "domenu_" + callback)
return menuhandler
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
"""grid utility for widgets"""
class Grid:
def __init__(self, ncol = None,
minncol = None,
maxncol = None,
colwidth = None,
mincolwidth = None,
maxcolwidth = None,
width = None,
minwidth = None,
maxwidth = None,
vgrid = 8,
gutter = 10,
leftmargin = None,
rightmargin = None,
topmargin = None,
bottommargin = None
):
if leftmargin == None:
leftmargin = gutter
if rightmargin == None:
rightmargin = gutter
if topmargin == None:
topmargin = vgrid
if bottommargin == None:
bottommargin = vgrid
def getbounds(self, width, height, bounds):
xxx
This diff is collapsed.
This diff is collapsed.
import os
import Qd
import Win
import Qt, QuickTime
import W
import macfs
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()
Win.InvalRect(oldbounds)
Win.InvalRect(self._bounds)
self.calcmoviebox()
def set(self, path_or_fss, start = 0):
self.SetPort()
if self.movie:
#Win.InvalRect(self.movie.GetMovieBox())
Qd.PaintRect(self.movie.GetMovieBox())
if type(path_or_fss) == type(''):
path = path_or_fss
fss = macfs.FSSpec(path)
else:
path = path_or_fss.as_pathname()
fss = path_or_fss
self.movietitle = os.path.basename(path)
movieResRef = Qt.OpenMovieFile(fss, 1)
self.movie, dummy = Qt.NewMovieFromFile(movieResRef, 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()
Win.InvalRect(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.
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