diff options
Diffstat (limited to 'Mac')
153 files changed, 21620 insertions, 21673 deletions
diff --git a/Mac/Demo/PICTbrowse/ICONbrowse.py b/Mac/Demo/PICTbrowse/ICONbrowse.py index 1194b7e..701ef7f 100644 --- a/Mac/Demo/PICTbrowse/ICONbrowse.py +++ b/Mac/Demo/PICTbrowse/ICONbrowse.py @@ -27,137 +27,137 @@ MAXWIDTH=320 MAXHEIGHT=320 def main(): - macresource.need('DLOG', ID_MAIN, "PICTbrowse.rsrc") - ICONbrowse() + macresource.need('DLOG', ID_MAIN, "PICTbrowse.rsrc") + ICONbrowse() class ICONbrowse(FrameWork.Application): - def __init__(self): - # First init menus, etc. - FrameWork.Application.__init__(self) - # Next create our dialog - self.main_dialog = MyDialog(self) - # Now open the dialog - contents = self.findICONresources() - self.main_dialog.open(ID_MAIN, contents) - # Finally, go into the event loop - self.mainloop() - - def makeusermenus(self): - self.filemenu = m = FrameWork.Menu(self.menubar, "File") - self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) - - def quit(self, *args): - self._quit() - - def showICON(self, resid): - w = ICONwindow(self) - w.open(resid) - #EasyDialogs.Message('Show ICON %r' % (resid,)) - - def findICONresources(self): - num = Res.CountResources('ICON') - rv = [] - for i in range(1, num+1): - Res.SetResLoad(0) - try: - r = Res.GetIndResource('ICON', i) - finally: - Res.SetResLoad(1) - id, type, name = r.GetResInfo() - rv.append((id, name)) - return rv - + def __init__(self): + # First init menus, etc. + FrameWork.Application.__init__(self) + # Next create our dialog + self.main_dialog = MyDialog(self) + # Now open the dialog + contents = self.findICONresources() + self.main_dialog.open(ID_MAIN, contents) + # Finally, go into the event loop + self.mainloop() + + def makeusermenus(self): + self.filemenu = m = FrameWork.Menu(self.menubar, "File") + self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) + + def quit(self, *args): + self._quit() + + def showICON(self, resid): + w = ICONwindow(self) + w.open(resid) + #EasyDialogs.Message('Show ICON %r' % (resid,)) + + def findICONresources(self): + num = Res.CountResources('ICON') + rv = [] + for i in range(1, num+1): + Res.SetResLoad(0) + try: + r = Res.GetIndResource('ICON', i) + finally: + Res.SetResLoad(1) + id, type, name = r.GetResInfo() + rv.append((id, name)) + return rv + class ICONwindow(FrameWork.Window): - def open(self, (resid, resname)): - if not resname: - resname = '#%r' % (resid,) - self.resid = resid - self.picture = Icn.GetIcon(self.resid) - l, t, r, b = 0, 0, 32, 32 - self.pictrect = (l, t, r, b) - width = r-l - height = b-t - if width < MINWIDTH: width = MINWIDTH - elif width > MAXWIDTH: width = MAXWIDTH - if height < MINHEIGHT: height = MINHEIGHT - elif height > MAXHEIGHT: height = MAXHEIGHT - bounds = (LEFT, TOP, LEFT+width, TOP+height) - - self.wid = Win.NewWindow(bounds, resname, 1, 0, -1, 1, 0) - self.do_postopen() - - def do_update(self, *args): - currect = self.fitrect() - Icn.PlotIcon(currect, self.picture) - - def fitrect(self): - """Return self.pictrect scaled to fit in window""" - graf = self.wid.GetWindowPort() - screenrect = graf.GetPortBounds() - picwidth = self.pictrect[2] - self.pictrect[0] - picheight = self.pictrect[3] - self.pictrect[1] - if picwidth > screenrect[2] - screenrect[0]: - factor = float(picwidth) / float(screenrect[2]-screenrect[0]) - picwidth = picwidth / factor - picheight = picheight / factor - if picheight > screenrect[3] - screenrect[1]: - factor = float(picheight) / float(screenrect[3]-screenrect[1]) - picwidth = picwidth / factor - picheight = picheight / factor - return (screenrect[0], screenrect[1], screenrect[0]+int(picwidth), - screenrect[1]+int(picheight)) - + def open(self, (resid, resname)): + if not resname: + resname = '#%r' % (resid,) + self.resid = resid + self.picture = Icn.GetIcon(self.resid) + l, t, r, b = 0, 0, 32, 32 + self.pictrect = (l, t, r, b) + width = r-l + height = b-t + if width < MINWIDTH: width = MINWIDTH + elif width > MAXWIDTH: width = MAXWIDTH + if height < MINHEIGHT: height = MINHEIGHT + elif height > MAXHEIGHT: height = MAXHEIGHT + bounds = (LEFT, TOP, LEFT+width, TOP+height) + + self.wid = Win.NewWindow(bounds, resname, 1, 0, -1, 1, 0) + self.do_postopen() + + def do_update(self, *args): + currect = self.fitrect() + Icn.PlotIcon(currect, self.picture) + + def fitrect(self): + """Return self.pictrect scaled to fit in window""" + graf = self.wid.GetWindowPort() + screenrect = graf.GetPortBounds() + picwidth = self.pictrect[2] - self.pictrect[0] + picheight = self.pictrect[3] - self.pictrect[1] + if picwidth > screenrect[2] - screenrect[0]: + factor = float(picwidth) / float(screenrect[2]-screenrect[0]) + picwidth = picwidth / factor + picheight = picheight / factor + if picheight > screenrect[3] - screenrect[1]: + factor = float(picheight) / float(screenrect[3]-screenrect[1]) + picwidth = picwidth / factor + picheight = picheight / factor + return (screenrect[0], screenrect[1], screenrect[0]+int(picwidth), + screenrect[1]+int(picheight)) + class MyDialog(FrameWork.DialogWindow): - "Main dialog window for ICONbrowse" - - def open(self, id, contents): - self.id = id - FrameWork.DialogWindow.open(self, ID_MAIN) - self.dlg.SetDialogDefaultItem(MAIN_SHOW) - self.contents = contents - self.ctl = self.dlg.GetDialogItemAsControl(MAIN_LIST) - h = self.ctl.GetControlData_Handle(Controls.kControlListBoxPart, - Controls.kControlListBoxListHandleTag) - self.list = List.as_List(h) - self.setlist() - - def setlist(self): - self.list.LDelRow(0, 0) - self.list.LSetDrawingMode(0) - if self.contents: - self.list.LAddRow(len(self.contents), 0) - for i in range(len(self.contents)): - v = repr(self.contents[i][0]) - if self.contents[i][1]: - v = v + '"' + self.contents[i][1] + '"' - self.list.LSetCell(v, (0, i)) - self.list.LSetDrawingMode(1) - self.list.LUpdate(self.wid.GetWindowPort().visRgn) - - def getselection(self): - items = [] - point = (0,0) - while 1: - ok, point = self.list.LGetSelect(1, point) - if not ok: - break - items.append(point[1]) - point = point[0], point[1]+1 - values = [] - for i in items: - values.append(self.contents[i]) - return values - - def do_show(self, *args): - selection = self.getselection() - for resid in selection: - self.parent.showICON(resid) - - def do_close(self): - self.close() - - def do_itemhit(self, item, event): - if item == MAIN_SHOW: - self.do_show() + "Main dialog window for ICONbrowse" + + def open(self, id, contents): + self.id = id + FrameWork.DialogWindow.open(self, ID_MAIN) + self.dlg.SetDialogDefaultItem(MAIN_SHOW) + self.contents = contents + self.ctl = self.dlg.GetDialogItemAsControl(MAIN_LIST) + h = self.ctl.GetControlData_Handle(Controls.kControlListBoxPart, + Controls.kControlListBoxListHandleTag) + self.list = List.as_List(h) + self.setlist() + + def setlist(self): + self.list.LDelRow(0, 0) + self.list.LSetDrawingMode(0) + if self.contents: + self.list.LAddRow(len(self.contents), 0) + for i in range(len(self.contents)): + v = repr(self.contents[i][0]) + if self.contents[i][1]: + v = v + '"' + self.contents[i][1] + '"' + self.list.LSetCell(v, (0, i)) + self.list.LSetDrawingMode(1) + self.list.LUpdate(self.wid.GetWindowPort().visRgn) + + def getselection(self): + items = [] + point = (0,0) + while 1: + ok, point = self.list.LGetSelect(1, point) + if not ok: + break + items.append(point[1]) + point = point[0], point[1]+1 + values = [] + for i in items: + values.append(self.contents[i]) + return values + + def do_show(self, *args): + selection = self.getselection() + for resid in selection: + self.parent.showICON(resid) + + def do_close(self): + self.close() + + def do_itemhit(self, item, event): + if item == MAIN_SHOW: + self.do_show() main() diff --git a/Mac/Demo/PICTbrowse/PICTbrowse.py b/Mac/Demo/PICTbrowse/PICTbrowse.py index eace869..0adfc83 100644 --- a/Mac/Demo/PICTbrowse/PICTbrowse.py +++ b/Mac/Demo/PICTbrowse/PICTbrowse.py @@ -22,120 +22,120 @@ LEFT=200 TOP=64 def main(): - macresource.need('DLOG', ID_MAIN, "PICTbrowse.rsrc") - PICTbrowse() + macresource.need('DLOG', ID_MAIN, "PICTbrowse.rsrc") + PICTbrowse() class PICTbrowse(FrameWork.Application): - def __init__(self): - # First init menus, etc. - FrameWork.Application.__init__(self) - # Next create our dialog - self.main_dialog = MyDialog(self) - # Now open the dialog - contents = self.findPICTresources() - self.main_dialog.open(ID_MAIN, contents) - # Finally, go into the event loop - self.mainloop() - - def makeusermenus(self): - self.filemenu = m = FrameWork.Menu(self.menubar, "File") - self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) - - def quit(self, *args): - self._quit() - - def showPICT(self, resid): - w = PICTwindow(self) - w.open(resid) - #EasyDialogs.Message('Show PICT %r' % (resid,)) - - def findPICTresources(self): - num = Res.CountResources('PICT') - rv = [] - for i in range(1, num+1): - Res.SetResLoad(0) - try: - r = Res.GetIndResource('PICT', i) - finally: - Res.SetResLoad(1) - id, type, name = r.GetResInfo() - rv.append((id, name)) - return rv - + def __init__(self): + # First init menus, etc. + FrameWork.Application.__init__(self) + # Next create our dialog + self.main_dialog = MyDialog(self) + # Now open the dialog + contents = self.findPICTresources() + self.main_dialog.open(ID_MAIN, contents) + # Finally, go into the event loop + self.mainloop() + + def makeusermenus(self): + self.filemenu = m = FrameWork.Menu(self.menubar, "File") + self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) + + def quit(self, *args): + self._quit() + + def showPICT(self, resid): + w = PICTwindow(self) + w.open(resid) + #EasyDialogs.Message('Show PICT %r' % (resid,)) + + def findPICTresources(self): + num = Res.CountResources('PICT') + rv = [] + for i in range(1, num+1): + Res.SetResLoad(0) + try: + r = Res.GetIndResource('PICT', i) + finally: + Res.SetResLoad(1) + id, type, name = r.GetResInfo() + rv.append((id, name)) + return rv + class PICTwindow(FrameWork.Window): - def open(self, (resid, resname)): - if not resname: - resname = '#%r' % (resid,) - self.resid = resid - picture = Qd.GetPicture(self.resid) - # Get rect for picture - print repr(picture.data[:16]) - sz, t, l, b, r = struct.unpack('hhhhh', picture.data[:10]) - print 'pict:', t, l, b, r - width = r-l - height = b-t - if width < 64: width = 64 - elif width > 480: width = 480 - if height < 64: height = 64 - elif height > 320: height = 320 - bounds = (LEFT, TOP, LEFT+width, TOP+height) - print 'bounds:', bounds - - self.wid = Win.NewWindow(bounds, resname, 1, 0, -1, 1, 0) - self.wid.SetWindowPic(picture) - self.do_postopen() - + def open(self, (resid, resname)): + if not resname: + resname = '#%r' % (resid,) + self.resid = resid + picture = Qd.GetPicture(self.resid) + # Get rect for picture + print repr(picture.data[:16]) + sz, t, l, b, r = struct.unpack('hhhhh', picture.data[:10]) + print 'pict:', t, l, b, r + width = r-l + height = b-t + if width < 64: width = 64 + elif width > 480: width = 480 + if height < 64: height = 64 + elif height > 320: height = 320 + bounds = (LEFT, TOP, LEFT+width, TOP+height) + print 'bounds:', bounds + + self.wid = Win.NewWindow(bounds, resname, 1, 0, -1, 1, 0) + self.wid.SetWindowPic(picture) + self.do_postopen() + class MyDialog(FrameWork.DialogWindow): - "Main dialog window for PICTbrowse" - - def open(self, id, contents): - self.id = id - FrameWork.DialogWindow.open(self, ID_MAIN) - self.dlg.SetDialogDefaultItem(MAIN_SHOW) - self.contents = contents - self.ctl = self.dlg.GetDialogItemAsControl(MAIN_LIST) - h = self.ctl.GetControlData_Handle(Controls.kControlListBoxPart, - Controls.kControlListBoxListHandleTag) - self.list = List.as_List(h) - self.setlist() - - def setlist(self): - self.list.LDelRow(0, 0) - self.list.LSetDrawingMode(0) - if self.contents: - self.list.LAddRow(len(self.contents), 0) - for i in range(len(self.contents)): - v = repr(self.contents[i][0]) - if self.contents[i][1]: - v = v + '"' + self.contents[i][1] + '"' - self.list.LSetCell(v, (0, i)) - self.list.LSetDrawingMode(1) - self.list.LUpdate(self.wid.GetWindowPort().visRgn) - - def getselection(self): - items = [] - point = (0,0) - while 1: - ok, point = self.list.LGetSelect(1, point) - if not ok: - break - items.append(point[1]) - point = point[0], point[1]+1 - values = [] - for i in items: - values.append(self.contents[i]) - return values - - def do_show(self, *args): - selection = self.getselection() - for resid in selection: - self.parent.showPICT(resid) - - def do_close(self): - self.close() - - def do_itemhit(self, item, event): - if item == MAIN_SHOW: - self.do_show() + "Main dialog window for PICTbrowse" + + def open(self, id, contents): + self.id = id + FrameWork.DialogWindow.open(self, ID_MAIN) + self.dlg.SetDialogDefaultItem(MAIN_SHOW) + self.contents = contents + self.ctl = self.dlg.GetDialogItemAsControl(MAIN_LIST) + h = self.ctl.GetControlData_Handle(Controls.kControlListBoxPart, + Controls.kControlListBoxListHandleTag) + self.list = List.as_List(h) + self.setlist() + + def setlist(self): + self.list.LDelRow(0, 0) + self.list.LSetDrawingMode(0) + if self.contents: + self.list.LAddRow(len(self.contents), 0) + for i in range(len(self.contents)): + v = repr(self.contents[i][0]) + if self.contents[i][1]: + v = v + '"' + self.contents[i][1] + '"' + self.list.LSetCell(v, (0, i)) + self.list.LSetDrawingMode(1) + self.list.LUpdate(self.wid.GetWindowPort().visRgn) + + def getselection(self): + items = [] + point = (0,0) + while 1: + ok, point = self.list.LGetSelect(1, point) + if not ok: + break + items.append(point[1]) + point = point[0], point[1]+1 + values = [] + for i in items: + values.append(self.contents[i]) + return values + + def do_show(self, *args): + selection = self.getselection() + for resid in selection: + self.parent.showPICT(resid) + + def do_close(self): + self.close() + + def do_itemhit(self, item, event): + if item == MAIN_SHOW: + self.do_show() main() diff --git a/Mac/Demo/PICTbrowse/PICTbrowse2.py b/Mac/Demo/PICTbrowse/PICTbrowse2.py index 875c99b..84cf8b8 100644 --- a/Mac/Demo/PICTbrowse/PICTbrowse2.py +++ b/Mac/Demo/PICTbrowse/PICTbrowse2.py @@ -26,138 +26,138 @@ MAXWIDTH=320 MAXHEIGHT=320 def main(): - macresource.need('DLOG', ID_MAIN, "PICTbrowse.rsrc") - PICTbrowse() + macresource.need('DLOG', ID_MAIN, "PICTbrowse.rsrc") + PICTbrowse() class PICTbrowse(FrameWork.Application): - def __init__(self): - # First init menus, etc. - FrameWork.Application.__init__(self) - # Next create our dialog - self.main_dialog = MyDialog(self) - # Now open the dialog - contents = self.findPICTresources() - self.main_dialog.open(ID_MAIN, contents) - # Finally, go into the event loop - self.mainloop() - - def makeusermenus(self): - self.filemenu = m = FrameWork.Menu(self.menubar, "File") - self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) - - def quit(self, *args): - self._quit() - - def showPICT(self, resid): - w = PICTwindow(self) - w.open(resid) - #EasyDialogs.Message('Show PICT %r' % (resid,)) - - def findPICTresources(self): - num = Res.CountResources('PICT') - rv = [] - for i in range(1, num+1): - Res.SetResLoad(0) - try: - r = Res.GetIndResource('PICT', i) - finally: - Res.SetResLoad(1) - id, type, name = r.GetResInfo() - rv.append((id, name)) - return rv - + def __init__(self): + # First init menus, etc. + FrameWork.Application.__init__(self) + # Next create our dialog + self.main_dialog = MyDialog(self) + # Now open the dialog + contents = self.findPICTresources() + self.main_dialog.open(ID_MAIN, contents) + # Finally, go into the event loop + self.mainloop() + + def makeusermenus(self): + self.filemenu = m = FrameWork.Menu(self.menubar, "File") + self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) + + def quit(self, *args): + self._quit() + + def showPICT(self, resid): + w = PICTwindow(self) + w.open(resid) + #EasyDialogs.Message('Show PICT %r' % (resid,)) + + def findPICTresources(self): + num = Res.CountResources('PICT') + rv = [] + for i in range(1, num+1): + Res.SetResLoad(0) + try: + r = Res.GetIndResource('PICT', i) + finally: + Res.SetResLoad(1) + id, type, name = r.GetResInfo() + rv.append((id, name)) + return rv + class PICTwindow(FrameWork.Window): - def open(self, (resid, resname)): - if not resname: - resname = '#%r' % (resid,) - self.resid = resid - self.picture = Qd.GetPicture(self.resid) - # Get rect for picture - sz, t, l, b, r = struct.unpack('hhhhh', self.picture.data[:10]) - self.pictrect = (l, t, r, b) - width = r-l - height = b-t - if width < MINWIDTH: width = MINWIDTH - elif width > MAXWIDTH: width = MAXWIDTH - if height < MINHEIGHT: height = MINHEIGHT - elif height > MAXHEIGHT: height = MAXHEIGHT - bounds = (LEFT, TOP, LEFT+width, TOP+height) - - self.wid = Win.NewWindow(bounds, resname, 1, 0, -1, 1, 0) - self.do_postopen() - - def do_update(self, *args): - currect = self.fitrect() - Qd.DrawPicture(self.picture, currect) - - def fitrect(self): - """Return self.pictrect scaled to fit in window""" - graf = self.dlg.GetWindowPort() - screenrect = graf.GetPortBounds() - picwidth = self.pictrect[2] - self.pictrect[0] - picheight = self.pictrect[3] - self.pictrect[1] - if picwidth > screenrect[2] - screenrect[0]: - factor = float(picwidth) / float(screenrect[2]-screenrect[0]) - picwidth = picwidth / factor - picheight = picheight / factor - if picheight > screenrect[3] - screenrect[1]: - factor = float(picheight) / float(screenrect[3]-screenrect[1]) - picwidth = picwidth / factor - picheight = picheight / factor - return (screenrect[0], screenrect[1], screenrect[0]+int(picwidth), - screenrect[1]+int(picheight)) - + def open(self, (resid, resname)): + if not resname: + resname = '#%r' % (resid,) + self.resid = resid + self.picture = Qd.GetPicture(self.resid) + # Get rect for picture + sz, t, l, b, r = struct.unpack('hhhhh', self.picture.data[:10]) + self.pictrect = (l, t, r, b) + width = r-l + height = b-t + if width < MINWIDTH: width = MINWIDTH + elif width > MAXWIDTH: width = MAXWIDTH + if height < MINHEIGHT: height = MINHEIGHT + elif height > MAXHEIGHT: height = MAXHEIGHT + bounds = (LEFT, TOP, LEFT+width, TOP+height) + + self.wid = Win.NewWindow(bounds, resname, 1, 0, -1, 1, 0) + self.do_postopen() + + def do_update(self, *args): + currect = self.fitrect() + Qd.DrawPicture(self.picture, currect) + + def fitrect(self): + """Return self.pictrect scaled to fit in window""" + graf = self.dlg.GetWindowPort() + screenrect = graf.GetPortBounds() + picwidth = self.pictrect[2] - self.pictrect[0] + picheight = self.pictrect[3] - self.pictrect[1] + if picwidth > screenrect[2] - screenrect[0]: + factor = float(picwidth) / float(screenrect[2]-screenrect[0]) + picwidth = picwidth / factor + picheight = picheight / factor + if picheight > screenrect[3] - screenrect[1]: + factor = float(picheight) / float(screenrect[3]-screenrect[1]) + picwidth = picwidth / factor + picheight = picheight / factor + return (screenrect[0], screenrect[1], screenrect[0]+int(picwidth), + screenrect[1]+int(picheight)) + class MyDialog(FrameWork.DialogWindow): - "Main dialog window for PICTbrowse" - - def open(self, id, contents): - self.id = id - FrameWork.DialogWindow.open(self, ID_MAIN) - self.dlg.SetDialogDefaultItem(MAIN_SHOW) - self.contents = contents - self.ctl = self.dlg.GetDialogItemAsControl(MAIN_LIST) - h = self.ctl.GetControlData_Handle(Controls.kControlListBoxPart, - Controls.kControlListBoxListHandleTag) - self.list = List.as_List(h) - self.setlist() - - def setlist(self): - self.list.LDelRow(0, 0) - self.list.LSetDrawingMode(0) - if self.contents: - self.list.LAddRow(len(self.contents), 0) - for i in range(len(self.contents)): - v = repr(self.contents[i][0]) - if self.contents[i][1]: - v = v + '"' + self.contents[i][1] + '"' - self.list.LSetCell(v, (0, i)) - self.list.LSetDrawingMode(1) - self.list.LUpdate(self.wid.GetWindowPort().visRgn) - - def getselection(self): - items = [] - point = (0,0) - while 1: - ok, point = self.list.LGetSelect(1, point) - if not ok: - break - items.append(point[1]) - point = point[0], point[1]+1 - values = [] - for i in items: - values.append(self.contents[i]) - return values - - def do_show(self, *args): - selection = self.getselection() - for resid in selection: - self.parent.showPICT(resid) - - def do_close(self): - self.close() - - def do_itemhit(self, item, event): - if item == MAIN_SHOW: - self.do_show() + "Main dialog window for PICTbrowse" + + def open(self, id, contents): + self.id = id + FrameWork.DialogWindow.open(self, ID_MAIN) + self.dlg.SetDialogDefaultItem(MAIN_SHOW) + self.contents = contents + self.ctl = self.dlg.GetDialogItemAsControl(MAIN_LIST) + h = self.ctl.GetControlData_Handle(Controls.kControlListBoxPart, + Controls.kControlListBoxListHandleTag) + self.list = List.as_List(h) + self.setlist() + + def setlist(self): + self.list.LDelRow(0, 0) + self.list.LSetDrawingMode(0) + if self.contents: + self.list.LAddRow(len(self.contents), 0) + for i in range(len(self.contents)): + v = repr(self.contents[i][0]) + if self.contents[i][1]: + v = v + '"' + self.contents[i][1] + '"' + self.list.LSetCell(v, (0, i)) + self.list.LSetDrawingMode(1) + self.list.LUpdate(self.wid.GetWindowPort().visRgn) + + def getselection(self): + items = [] + point = (0,0) + while 1: + ok, point = self.list.LGetSelect(1, point) + if not ok: + break + items.append(point[1]) + point = point[0], point[1]+1 + values = [] + for i in items: + values.append(self.contents[i]) + return values + + def do_show(self, *args): + selection = self.getselection() + for resid in selection: + self.parent.showPICT(resid) + + def do_close(self): + self.close() + + def do_itemhit(self, item, event): + if item == MAIN_SHOW: + self.do_show() main() diff --git a/Mac/Demo/PICTbrowse/cicnbrowse.py b/Mac/Demo/PICTbrowse/cicnbrowse.py index e3d7972..d95e7c8 100644 --- a/Mac/Demo/PICTbrowse/cicnbrowse.py +++ b/Mac/Demo/PICTbrowse/cicnbrowse.py @@ -27,137 +27,137 @@ MAXWIDTH=320 MAXHEIGHT=320 def main(): - macresource.need('DLOG', ID_MAIN, "PICTbrowse.rsrc") - CIconbrowse() + macresource.need('DLOG', ID_MAIN, "PICTbrowse.rsrc") + CIconbrowse() class CIconbrowse(FrameWork.Application): - def __init__(self): - # First init menus, etc. - FrameWork.Application.__init__(self) - # Next create our dialog - self.main_dialog = MyDialog(self) - # Now open the dialog - contents = self.findcicnresources() - self.main_dialog.open(ID_MAIN, contents) - # Finally, go into the event loop - self.mainloop() - - def makeusermenus(self): - self.filemenu = m = FrameWork.Menu(self.menubar, "File") - self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) - - def quit(self, *args): - self._quit() - - def showCIcon(self, resid): - w = CIconwindow(self) - w.open(resid) - #EasyDialogs.Message('Show cicn %r' % (resid,)) - - def findcicnresources(self): - num = Res.CountResources('cicn') - rv = [] - for i in range(1, num+1): - Res.SetResLoad(0) - try: - r = Res.GetIndResource('cicn', i) - finally: - Res.SetResLoad(1) - id, type, name = r.GetResInfo() - rv.append((id, name)) - return rv - + def __init__(self): + # First init menus, etc. + FrameWork.Application.__init__(self) + # Next create our dialog + self.main_dialog = MyDialog(self) + # Now open the dialog + contents = self.findcicnresources() + self.main_dialog.open(ID_MAIN, contents) + # Finally, go into the event loop + self.mainloop() + + def makeusermenus(self): + self.filemenu = m = FrameWork.Menu(self.menubar, "File") + self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) + + def quit(self, *args): + self._quit() + + def showCIcon(self, resid): + w = CIconwindow(self) + w.open(resid) + #EasyDialogs.Message('Show cicn %r' % (resid,)) + + def findcicnresources(self): + num = Res.CountResources('cicn') + rv = [] + for i in range(1, num+1): + Res.SetResLoad(0) + try: + r = Res.GetIndResource('cicn', i) + finally: + Res.SetResLoad(1) + id, type, name = r.GetResInfo() + rv.append((id, name)) + return rv + class CIconwindow(FrameWork.Window): - def open(self, (resid, resname)): - if not resname: - resname = '#%r' % (resid,) - self.resid = resid - self.picture = Icn.GetCIcon(self.resid) - l, t, r, b = 0, 0, 32, 32 - self.pictrect = (l, t, r, b) - width = r-l - height = b-t - if width < MINWIDTH: width = MINWIDTH - elif width > MAXWIDTH: width = MAXWIDTH - if height < MINHEIGHT: height = MINHEIGHT - elif height > MAXHEIGHT: height = MAXHEIGHT - bounds = (LEFT, TOP, LEFT+width, TOP+height) - - self.wid = Win.NewWindow(bounds, resname, 1, 0, -1, 1, 0) - self.do_postopen() - - def do_update(self, *args): - currect = self.fitrect() - Icn.PlotCIcon(currect, self.picture) - - def fitrect(self): - """Return self.pictrect scaled to fit in window""" - graf = self.wid.GetWindowPort() - screenrect = graf.GetPortBounds() - picwidth = self.pictrect[2] - self.pictrect[0] - picheight = self.pictrect[3] - self.pictrect[1] - if picwidth > screenrect[2] - screenrect[0]: - factor = float(picwidth) / float(screenrect[2]-screenrect[0]) - picwidth = picwidth / factor - picheight = picheight / factor - if picheight > screenrect[3] - screenrect[1]: - factor = float(picheight) / float(screenrect[3]-screenrect[1]) - picwidth = picwidth / factor - picheight = picheight / factor - return (screenrect[0], screenrect[1], screenrect[0]+int(picwidth), - screenrect[1]+int(picheight)) - + def open(self, (resid, resname)): + if not resname: + resname = '#%r' % (resid,) + self.resid = resid + self.picture = Icn.GetCIcon(self.resid) + l, t, r, b = 0, 0, 32, 32 + self.pictrect = (l, t, r, b) + width = r-l + height = b-t + if width < MINWIDTH: width = MINWIDTH + elif width > MAXWIDTH: width = MAXWIDTH + if height < MINHEIGHT: height = MINHEIGHT + elif height > MAXHEIGHT: height = MAXHEIGHT + bounds = (LEFT, TOP, LEFT+width, TOP+height) + + self.wid = Win.NewWindow(bounds, resname, 1, 0, -1, 1, 0) + self.do_postopen() + + def do_update(self, *args): + currect = self.fitrect() + Icn.PlotCIcon(currect, self.picture) + + def fitrect(self): + """Return self.pictrect scaled to fit in window""" + graf = self.wid.GetWindowPort() + screenrect = graf.GetPortBounds() + picwidth = self.pictrect[2] - self.pictrect[0] + picheight = self.pictrect[3] - self.pictrect[1] + if picwidth > screenrect[2] - screenrect[0]: + factor = float(picwidth) / float(screenrect[2]-screenrect[0]) + picwidth = picwidth / factor + picheight = picheight / factor + if picheight > screenrect[3] - screenrect[1]: + factor = float(picheight) / float(screenrect[3]-screenrect[1]) + picwidth = picwidth / factor + picheight = picheight / factor + return (screenrect[0], screenrect[1], screenrect[0]+int(picwidth), + screenrect[1]+int(picheight)) + class MyDialog(FrameWork.DialogWindow): - "Main dialog window for cicnbrowse" - - def open(self, id, contents): - self.id = id - FrameWork.DialogWindow.open(self, ID_MAIN) - self.dlg.SetDialogDefaultItem(MAIN_SHOW) - self.contents = contents - self.ctl = self.dlg.GetDialogItemAsControl(MAIN_LIST) - h = self.ctl.GetControlData_Handle(Controls.kControlListBoxPart, - Controls.kControlListBoxListHandleTag) - self.list = List.as_List(h) - self.setlist() - - def setlist(self): - self.list.LDelRow(0, 0) - self.list.LSetDrawingMode(0) - if self.contents: - self.list.LAddRow(len(self.contents), 0) - for i in range(len(self.contents)): - v = repr(self.contents[i][0]) - if self.contents[i][1]: - v = v + '"' + self.contents[i][1] + '"' - self.list.LSetCell(v, (0, i)) - self.list.LSetDrawingMode(1) - self.list.LUpdate(self.wid.GetWindowPort().visRgn) - - def getselection(self): - items = [] - point = (0,0) - while 1: - ok, point = self.list.LGetSelect(1, point) - if not ok: - break - items.append(point[1]) - point = point[0], point[1]+1 - values = [] - for i in items: - values.append(self.contents[i]) - return values - - def do_show(self, *args): - selection = self.getselection() - for resid in selection: - self.parent.showCIcon(resid) - - def do_close(self): - self.close() - - def do_itemhit(self, item, event): - if item == MAIN_SHOW: - self.do_show() + "Main dialog window for cicnbrowse" + + def open(self, id, contents): + self.id = id + FrameWork.DialogWindow.open(self, ID_MAIN) + self.dlg.SetDialogDefaultItem(MAIN_SHOW) + self.contents = contents + self.ctl = self.dlg.GetDialogItemAsControl(MAIN_LIST) + h = self.ctl.GetControlData_Handle(Controls.kControlListBoxPart, + Controls.kControlListBoxListHandleTag) + self.list = List.as_List(h) + self.setlist() + + def setlist(self): + self.list.LDelRow(0, 0) + self.list.LSetDrawingMode(0) + if self.contents: + self.list.LAddRow(len(self.contents), 0) + for i in range(len(self.contents)): + v = repr(self.contents[i][0]) + if self.contents[i][1]: + v = v + '"' + self.contents[i][1] + '"' + self.list.LSetCell(v, (0, i)) + self.list.LSetDrawingMode(1) + self.list.LUpdate(self.wid.GetWindowPort().visRgn) + + def getselection(self): + items = [] + point = (0,0) + while 1: + ok, point = self.list.LGetSelect(1, point) + if not ok: + break + items.append(point[1]) + point = point[0], point[1]+1 + values = [] + for i in items: + values.append(self.contents[i]) + return values + + def do_show(self, *args): + selection = self.getselection() + for resid in selection: + self.parent.showCIcon(resid) + + def do_close(self): + self.close() + + def do_itemhit(self, item, event): + if item == MAIN_SHOW: + self.do_show() main() diff --git a/Mac/Demo/PICTbrowse/oldPICTbrowse.py b/Mac/Demo/PICTbrowse/oldPICTbrowse.py index 5f5893c..8600bb2 100644 --- a/Mac/Demo/PICTbrowse/oldPICTbrowse.py +++ b/Mac/Demo/PICTbrowse/oldPICTbrowse.py @@ -21,139 +21,139 @@ LEFT=200 TOP=64 def main(): - macresource.need('DLOG', ID_MAIN, "oldPICTbrowse.rsrc") - PICTbrowse() + macresource.need('DLOG', ID_MAIN, "oldPICTbrowse.rsrc") + PICTbrowse() class PICTbrowse(FrameWork.Application): - def __init__(self): - # First init menus, etc. - FrameWork.Application.__init__(self) - # Next create our dialog - self.main_dialog = MyDialog(self) - # Now open the dialog - contents = self.findPICTresources() - self.main_dialog.open(ID_MAIN, contents) - # Finally, go into the event loop - self.mainloop() - - def makeusermenus(self): - self.filemenu = m = FrameWork.Menu(self.menubar, "File") - self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) - - def quit(self, *args): - self._quit() - - def showPICT(self, resid): - w = PICTwindow(self) - w.open(resid) - #EasyDialogs.Message('Show PICT %r' % (resid,)) - - def findPICTresources(self): - num = Res.CountResources('PICT') - rv = [] - for i in range(1, num+1): - Res.SetResLoad(0) - try: - r = Res.GetIndResource('PICT', i) - finally: - Res.SetResLoad(1) - id, type, name = r.GetResInfo() - rv.append((id, name)) - return rv - + def __init__(self): + # First init menus, etc. + FrameWork.Application.__init__(self) + # Next create our dialog + self.main_dialog = MyDialog(self) + # Now open the dialog + contents = self.findPICTresources() + self.main_dialog.open(ID_MAIN, contents) + # Finally, go into the event loop + self.mainloop() + + def makeusermenus(self): + self.filemenu = m = FrameWork.Menu(self.menubar, "File") + self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) + + def quit(self, *args): + self._quit() + + def showPICT(self, resid): + w = PICTwindow(self) + w.open(resid) + #EasyDialogs.Message('Show PICT %r' % (resid,)) + + def findPICTresources(self): + num = Res.CountResources('PICT') + rv = [] + for i in range(1, num+1): + Res.SetResLoad(0) + try: + r = Res.GetIndResource('PICT', i) + finally: + Res.SetResLoad(1) + id, type, name = r.GetResInfo() + rv.append((id, name)) + return rv + class PICTwindow(FrameWork.Window): - def open(self, (resid, resname)): - if not resname: - resname = '#%r' % (resid,) - self.resid = resid - picture = Qd.GetPicture(self.resid) - # Get rect for picture - print repr(picture.data[:16]) - sz, t, l, b, r = struct.unpack('hhhhh', picture.data[:10]) - print 'pict:', t, l, b, r - width = r-l - height = b-t - if width < 64: width = 64 - elif width > 480: width = 480 - if height < 64: height = 64 - elif height > 320: height = 320 - bounds = (LEFT, TOP, LEFT+width, TOP+height) - print 'bounds:', bounds - - self.wid = Win.NewWindow(bounds, resname, 1, 0, -1, 1, 0) - self.wid.SetWindowPic(picture) - self.do_postopen() - + def open(self, (resid, resname)): + if not resname: + resname = '#%r' % (resid,) + self.resid = resid + picture = Qd.GetPicture(self.resid) + # Get rect for picture + print repr(picture.data[:16]) + sz, t, l, b, r = struct.unpack('hhhhh', picture.data[:10]) + print 'pict:', t, l, b, r + width = r-l + height = b-t + if width < 64: width = 64 + elif width > 480: width = 480 + if height < 64: height = 64 + elif height > 320: height = 320 + bounds = (LEFT, TOP, LEFT+width, TOP+height) + print 'bounds:', bounds + + self.wid = Win.NewWindow(bounds, resname, 1, 0, -1, 1, 0) + self.wid.SetWindowPic(picture) + self.do_postopen() + class MyDialog(FrameWork.DialogWindow): - "Main dialog window for PICTbrowse" - - def open(self, id, contents): - self.id = id - FrameWork.DialogWindow.open(self, ID_MAIN) - self.dlg.SetDialogDefaultItem(MAIN_SHOW) - tp, h, rect = self.dlg.GetDialogItem(MAIN_LIST) - rect2 = rect[0]+1, rect[1]+1, rect[2]-17, rect[3]-17 # Scroll bar space - self.list = List.LNew(rect2, (0, 0, 1, len(contents)), (0,0), 0, self.wid, - 0, 1, 1, 1) - self.contents = contents - self.setlist() - - def setlist(self): - self.list.LDelRow(0, 0) - self.list.LSetDrawingMode(0) - if self.contents: - self.list.LAddRow(len(self.contents), 0) - for i in range(len(self.contents)): - v = repr(self.contents[i][0]) - if self.contents[i][1]: - v = v + '"' + self.contents[i][1] + '"' - self.list.LSetCell(v, (0, i)) - self.list.LSetDrawingMode(1) - self.list.LUpdate(self.wid.GetWindowPort().visRgn) - - def do_listhit(self, event): - (what, message, when, where, modifiers) = event - Qd.SetPort(self.wid) - where = Qd.GlobalToLocal(where) - print 'LISTHIT', where - if self.list.LClick(where, modifiers): - self.do_show() - - def getselection(self): - items = [] - point = (0,0) - while 1: - ok, point = self.list.LGetSelect(1, point) - if not ok: - break - items.append(point[1]) - point = point[0], point[1]+1 - values = [] - for i in items: - values.append(self.contents[i]) - return values - - def do_show(self, *args): - selection = self.getselection() - for resid in selection: - self.parent.showPICT(resid) - - def do_rawupdate(self, window, event): - tp, h, rect = self.dlg.GetDialogItem(MAIN_LIST) - Qd.SetPort(self.wid) - Qd.FrameRect(rect) - self.list.LUpdate(self.wid.GetWindowPort().visRgn) - - def do_activate(self, activate, event): - self.list.LActivate(activate) - - def do_close(self): - self.close() - - def do_itemhit(self, item, event): - if item == MAIN_LIST: - self.do_listhit(event) - if item == MAIN_SHOW: - self.do_show() + "Main dialog window for PICTbrowse" + + def open(self, id, contents): + self.id = id + FrameWork.DialogWindow.open(self, ID_MAIN) + self.dlg.SetDialogDefaultItem(MAIN_SHOW) + tp, h, rect = self.dlg.GetDialogItem(MAIN_LIST) + rect2 = rect[0]+1, rect[1]+1, rect[2]-17, rect[3]-17 # Scroll bar space + self.list = List.LNew(rect2, (0, 0, 1, len(contents)), (0,0), 0, self.wid, + 0, 1, 1, 1) + self.contents = contents + self.setlist() + + def setlist(self): + self.list.LDelRow(0, 0) + self.list.LSetDrawingMode(0) + if self.contents: + self.list.LAddRow(len(self.contents), 0) + for i in range(len(self.contents)): + v = repr(self.contents[i][0]) + if self.contents[i][1]: + v = v + '"' + self.contents[i][1] + '"' + self.list.LSetCell(v, (0, i)) + self.list.LSetDrawingMode(1) + self.list.LUpdate(self.wid.GetWindowPort().visRgn) + + def do_listhit(self, event): + (what, message, when, where, modifiers) = event + Qd.SetPort(self.wid) + where = Qd.GlobalToLocal(where) + print 'LISTHIT', where + if self.list.LClick(where, modifiers): + self.do_show() + + def getselection(self): + items = [] + point = (0,0) + while 1: + ok, point = self.list.LGetSelect(1, point) + if not ok: + break + items.append(point[1]) + point = point[0], point[1]+1 + values = [] + for i in items: + values.append(self.contents[i]) + return values + + def do_show(self, *args): + selection = self.getselection() + for resid in selection: + self.parent.showPICT(resid) + + def do_rawupdate(self, window, event): + tp, h, rect = self.dlg.GetDialogItem(MAIN_LIST) + Qd.SetPort(self.wid) + Qd.FrameRect(rect) + self.list.LUpdate(self.wid.GetWindowPort().visRgn) + + def do_activate(self, activate, event): + self.list.LActivate(activate) + + def do_close(self): + self.close() + + def do_itemhit(self, item, event): + if item == MAIN_LIST: + self.do_listhit(event) + if item == MAIN_SHOW: + self.do_show() main() diff --git a/Mac/Demo/applescript/Disk_Copy/Special_Events.py b/Mac/Demo/applescript/Disk_Copy/Special_Events.py index a98eb8a..a2b0910 100644 --- a/Mac/Demo/applescript/Disk_Copy/Special_Events.py +++ b/Mac/Demo/applescript/Disk_Copy/Special_Events.py @@ -12,385 +12,385 @@ _code = 'ddsk' class Special_Events_Events: - _argmap_mount = { - 'access_mode' : 'Acss', - 'checksum_verification' : 'VChk', - 'signature_verification' : 'VSig', - 'RAM_caching' : 'Cach', - } - - def mount(self, _object, _attributes={}, **_arguments): - """mount: Mounts an Disk Copy image as a disk volume - Required argument: a reference to the disk image to be mounted - Keyword argument access_mode: the access mode for mounted volume (default is "any", i.e. best possible) - Keyword argument checksum_verification: Verify the checksum before mounting? - Keyword argument signature_verification: Verify the DigiSignŽ signature before mounting? - Keyword argument RAM_caching: Cache the disk image in RAM? (if omitted, don't cache) - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a reference to mounted disk - """ - _code = 'ddsk' - _subcode = 'Moun' - - aetools.keysubst(_arguments, self._argmap_mount) - _arguments['----'] = _object - - aetools.enumsubst(_arguments, 'Acss', _Enum_Acss) - aetools.enumsubst(_arguments, 'VChk', _Enum_bool) - aetools.enumsubst(_arguments, 'VSig', _Enum_bool) - aetools.enumsubst(_arguments, 'Cach', _Enum_bool) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_execute_DiskScript = { - 'checksum_verification' : 'VChk', - 'signature_verification' : 'VSig', - } - - def execute_DiskScript(self, _object, _attributes={}, **_arguments): - """execute DiskScript: Executes a Disk Copy-specific DiskScript - Required argument: a reference to the DiskScript to execute - Keyword argument checksum_verification: Should checksums be verified when mounting images referenced in the DiskScript? - Keyword argument signature_verification: Should the DigiSignŽ signature of the DiskScript and the images it references be verified? - Keyword argument _attributes: AppleEvent attribute dictionary - """ - _code = 'ddsk' - _subcode = 'XEQd' - - aetools.keysubst(_arguments, self._argmap_execute_DiskScript) - _arguments['----'] = _object - - aetools.enumsubst(_arguments, 'VChk', _Enum_bool) - aetools.enumsubst(_arguments, 'VSig', _Enum_bool) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - def unmount(self, _object, _attributes={}, **_arguments): - """unmount: Unmount and eject (if necessary) a volume - Required argument: a reference to disk to be unmounted (and ejected) - Keyword argument _attributes: AppleEvent attribute dictionary - """ - _code = 'ddsk' - _subcode = 'Umnt' - - if _arguments: raise TypeError, 'No optional args expected' - _arguments['----'] = _object - - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_create = { - 'saving_as' : 'SvAs', - 'logical_blocks' : 'Blks', - 'zeroing' : 'Zero', - 'leave_image_mounted' : 'Moun', - 'filesystem' : 'Fsys', - } - - def create(self, _object, _attributes={}, **_arguments): - """create: Create a new Disk Copy document - Required argument: the name of the volume to create - Keyword argument saving_as: the disk image to be created - Keyword argument logical_blocks: the number of logical blocks - Keyword argument zeroing: Should all blocks on the disk be set to zero? - Keyword argument leave_image_mounted: Should the image be mounted after it is created? - Keyword argument filesystem: file system to use (Mac OS Standard/compatible, Mac OS Enhanced) - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a reference to newly created disk image (or newly mounted disk) - """ - _code = 'ddsk' - _subcode = 'Crea' - - aetools.keysubst(_arguments, self._argmap_create) - _arguments['----'] = _object - - aetools.enumsubst(_arguments, 'SvAs', _Enum_fss_) - aetools.enumsubst(_arguments, 'Blks', _Enum_long) - aetools.enumsubst(_arguments, 'Zero', _Enum_bool) - aetools.enumsubst(_arguments, 'Moun', _Enum_bool) - aetools.enumsubst(_arguments, 'Fsys', _Enum_Fsys) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - def verify_checksum(self, _object, _attributes={}, **_arguments): - """verify checksum: Verify the checksum of a Disk Copy 4.2 or a Disk Copy 6.0 read-only document - Required argument: the disk image to be verified - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: the result of the checksum verification - """ - _code = 'ddsk' - _subcode = 'Vcrc' - - if _arguments: raise TypeError, 'No optional args expected' - _arguments['----'] = _object - - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - def verify_signature(self, _object, _attributes={}, **_arguments): - """verify signature: Verify the DigiSignŽ signature for a Disk Copy document - Required argument: the disk image to be verified - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: Is the DigiSignŽ signature valid? - """ - _code = 'ddsk' - _subcode = 'Vsig' - - if _arguments: raise TypeError, 'No optional args expected' - _arguments['----'] = _object - - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_sign_image = { - 'using_signer' : 'Sinr', - } - - def sign_image(self, _object, _attributes={}, **_arguments): - """sign image: Add a DigiSignŽ signature to a Disk Copy document - Required argument: the disk image to be signed - Keyword argument using_signer: a reference to signer file to use - Keyword argument _attributes: AppleEvent attribute dictionary - """ - _code = 'ddsk' - _subcode = 'Asig' - - aetools.keysubst(_arguments, self._argmap_sign_image) - _arguments['----'] = _object - - aetools.enumsubst(_arguments, 'Sinr', _Enum_alis) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_create_a_floppy_from = { - 'signature_verification' : 'VSig', - 'erase_confirmation' : 'Cfrm', - 'make_multiple_floppies' : 'Mult', - } - - def create_a_floppy_from(self, _object, _attributes={}, **_arguments): - """create a floppy from: create a floppy disk from a Disk Copy document - Required argument: the disk image to make a floppy from - Keyword argument signature_verification: Should the DigiSignŽ signature be verified before creating a floppy disk? - Keyword argument erase_confirmation: Should the user be asked to confirm the erasure of the previous contents of floppy disks? - Keyword argument make_multiple_floppies: Should the user be prompted to create multiple floppy disks? - Keyword argument _attributes: AppleEvent attribute dictionary - """ - _code = 'ddsk' - _subcode = 'Bfpy' - - aetools.keysubst(_arguments, self._argmap_create_a_floppy_from) - _arguments['----'] = _object - - aetools.enumsubst(_arguments, 'VSig', _Enum_bool) - aetools.enumsubst(_arguments, 'Cfrm', _Enum_bool) - aetools.enumsubst(_arguments, 'Mult', _Enum_bool) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_check_image = { - 'details' : 'ChDe', - } - - def check_image(self, _object, _attributes={}, **_arguments): - """check image: Check the disk imageÕs internal data structures for any inconsistencies. Works on NDIF, Disk Copy 4.2, DARTŽ, or DiskSet images. - Required argument: the disk image to be verified - Keyword argument details: Should the disk image details be displayed? - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a record containing a boolean (true/false) value if the image passes consistency tests, and the numbers of warnings and errors - """ - _code = 'ddsk' - _subcode = 'Chek' - - aetools.keysubst(_arguments, self._argmap_check_image) - _arguments['----'] = _object - - aetools.enumsubst(_arguments, 'ChDe', _Enum_bool) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_segment_image = { - 'segment_count' : 'SGCT', - 'segment_size' : 'SGSZ', - 'segment_name' : 'SGNM', - 'image_ID' : 'SGID', - } - - def segment_image(self, _object, _attributes={}, **_arguments): - """segment image: Segment a NDIF R/W or R/O image into smaller pieces - Required argument: the disk image to be segmented - Keyword argument segment_count: the number of image segments to create - Keyword argument segment_size: the size of image segments (in blocks) to create - Keyword argument segment_name: the root name for each image segment file - Keyword argument image_ID: string used to generate a unique image ID to group the segments - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a list of references to the image segments created - """ - _code = 'ddsk' - _subcode = 'SGMT' - - aetools.keysubst(_arguments, self._argmap_segment_image) - _arguments['----'] = _object - - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_create_SMI = { - 'source_images' : 'SMI1', - 'launching_application' : 'SMI2', - 'launching_document' : 'SMI3', - 'version_string' : 'SMI4', - 'checksum_verification' : 'VChk', - 'signature_verification' : 'VSig', - 'image_signing' : 'SImg', - } - - def create_SMI(self, _object, _attributes={}, **_arguments): - """create SMI: Creates a self-mounting image (SMI) from a list of NDIF disk images - Required argument: the self-mounting image to create - Keyword argument source_images: a list of references to sources images - Keyword argument launching_application: the path to an application to launch - Keyword argument launching_document: the path to a document to open - Keyword argument version_string: sets the 'vers' 1 resource of the self-mounting image - Keyword argument checksum_verification: Should the checksum of the source images be verified before creating the SMI? - Keyword argument signature_verification: Should the DigiSignŽ signature of the source images be verified before creating the SMI? - Keyword argument image_signing: Should the SMI be given a digital signature when it is created? - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a reference to the self-mounting image created - """ - _code = 'ddsk' - _subcode = 'MSMI' - - aetools.keysubst(_arguments, self._argmap_create_SMI) - _arguments['----'] = _object - - aetools.enumsubst(_arguments, 'VChk', _Enum_bool) - aetools.enumsubst(_arguments, 'VSig', _Enum_bool) - aetools.enumsubst(_arguments, 'SImg', _Enum_bool) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] + _argmap_mount = { + 'access_mode' : 'Acss', + 'checksum_verification' : 'VChk', + 'signature_verification' : 'VSig', + 'RAM_caching' : 'Cach', + } + + def mount(self, _object, _attributes={}, **_arguments): + """mount: Mounts an Disk Copy image as a disk volume + Required argument: a reference to the disk image to be mounted + Keyword argument access_mode: the access mode for mounted volume (default is "any", i.e. best possible) + Keyword argument checksum_verification: Verify the checksum before mounting? + Keyword argument signature_verification: Verify the DigiSignŽ signature before mounting? + Keyword argument RAM_caching: Cache the disk image in RAM? (if omitted, don't cache) + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a reference to mounted disk + """ + _code = 'ddsk' + _subcode = 'Moun' + + aetools.keysubst(_arguments, self._argmap_mount) + _arguments['----'] = _object + + aetools.enumsubst(_arguments, 'Acss', _Enum_Acss) + aetools.enumsubst(_arguments, 'VChk', _Enum_bool) + aetools.enumsubst(_arguments, 'VSig', _Enum_bool) + aetools.enumsubst(_arguments, 'Cach', _Enum_bool) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_execute_DiskScript = { + 'checksum_verification' : 'VChk', + 'signature_verification' : 'VSig', + } + + def execute_DiskScript(self, _object, _attributes={}, **_arguments): + """execute DiskScript: Executes a Disk Copy-specific DiskScript + Required argument: a reference to the DiskScript to execute + Keyword argument checksum_verification: Should checksums be verified when mounting images referenced in the DiskScript? + Keyword argument signature_verification: Should the DigiSignŽ signature of the DiskScript and the images it references be verified? + Keyword argument _attributes: AppleEvent attribute dictionary + """ + _code = 'ddsk' + _subcode = 'XEQd' + + aetools.keysubst(_arguments, self._argmap_execute_DiskScript) + _arguments['----'] = _object + + aetools.enumsubst(_arguments, 'VChk', _Enum_bool) + aetools.enumsubst(_arguments, 'VSig', _Enum_bool) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + def unmount(self, _object, _attributes={}, **_arguments): + """unmount: Unmount and eject (if necessary) a volume + Required argument: a reference to disk to be unmounted (and ejected) + Keyword argument _attributes: AppleEvent attribute dictionary + """ + _code = 'ddsk' + _subcode = 'Umnt' + + if _arguments: raise TypeError, 'No optional args expected' + _arguments['----'] = _object + + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_create = { + 'saving_as' : 'SvAs', + 'logical_blocks' : 'Blks', + 'zeroing' : 'Zero', + 'leave_image_mounted' : 'Moun', + 'filesystem' : 'Fsys', + } + + def create(self, _object, _attributes={}, **_arguments): + """create: Create a new Disk Copy document + Required argument: the name of the volume to create + Keyword argument saving_as: the disk image to be created + Keyword argument logical_blocks: the number of logical blocks + Keyword argument zeroing: Should all blocks on the disk be set to zero? + Keyword argument leave_image_mounted: Should the image be mounted after it is created? + Keyword argument filesystem: file system to use (Mac OS Standard/compatible, Mac OS Enhanced) + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a reference to newly created disk image (or newly mounted disk) + """ + _code = 'ddsk' + _subcode = 'Crea' + + aetools.keysubst(_arguments, self._argmap_create) + _arguments['----'] = _object + + aetools.enumsubst(_arguments, 'SvAs', _Enum_fss_) + aetools.enumsubst(_arguments, 'Blks', _Enum_long) + aetools.enumsubst(_arguments, 'Zero', _Enum_bool) + aetools.enumsubst(_arguments, 'Moun', _Enum_bool) + aetools.enumsubst(_arguments, 'Fsys', _Enum_Fsys) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + def verify_checksum(self, _object, _attributes={}, **_arguments): + """verify checksum: Verify the checksum of a Disk Copy 4.2 or a Disk Copy 6.0 read-only document + Required argument: the disk image to be verified + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: the result of the checksum verification + """ + _code = 'ddsk' + _subcode = 'Vcrc' + + if _arguments: raise TypeError, 'No optional args expected' + _arguments['----'] = _object + + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + def verify_signature(self, _object, _attributes={}, **_arguments): + """verify signature: Verify the DigiSignŽ signature for a Disk Copy document + Required argument: the disk image to be verified + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: Is the DigiSignŽ signature valid? + """ + _code = 'ddsk' + _subcode = 'Vsig' + + if _arguments: raise TypeError, 'No optional args expected' + _arguments['----'] = _object + + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_sign_image = { + 'using_signer' : 'Sinr', + } + + def sign_image(self, _object, _attributes={}, **_arguments): + """sign image: Add a DigiSignŽ signature to a Disk Copy document + Required argument: the disk image to be signed + Keyword argument using_signer: a reference to signer file to use + Keyword argument _attributes: AppleEvent attribute dictionary + """ + _code = 'ddsk' + _subcode = 'Asig' + + aetools.keysubst(_arguments, self._argmap_sign_image) + _arguments['----'] = _object + + aetools.enumsubst(_arguments, 'Sinr', _Enum_alis) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_create_a_floppy_from = { + 'signature_verification' : 'VSig', + 'erase_confirmation' : 'Cfrm', + 'make_multiple_floppies' : 'Mult', + } + + def create_a_floppy_from(self, _object, _attributes={}, **_arguments): + """create a floppy from: create a floppy disk from a Disk Copy document + Required argument: the disk image to make a floppy from + Keyword argument signature_verification: Should the DigiSignŽ signature be verified before creating a floppy disk? + Keyword argument erase_confirmation: Should the user be asked to confirm the erasure of the previous contents of floppy disks? + Keyword argument make_multiple_floppies: Should the user be prompted to create multiple floppy disks? + Keyword argument _attributes: AppleEvent attribute dictionary + """ + _code = 'ddsk' + _subcode = 'Bfpy' + + aetools.keysubst(_arguments, self._argmap_create_a_floppy_from) + _arguments['----'] = _object + + aetools.enumsubst(_arguments, 'VSig', _Enum_bool) + aetools.enumsubst(_arguments, 'Cfrm', _Enum_bool) + aetools.enumsubst(_arguments, 'Mult', _Enum_bool) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_check_image = { + 'details' : 'ChDe', + } + + def check_image(self, _object, _attributes={}, **_arguments): + """check image: Check the disk imageÕs internal data structures for any inconsistencies. Works on NDIF, Disk Copy 4.2, DARTŽ, or DiskSet images. + Required argument: the disk image to be verified + Keyword argument details: Should the disk image details be displayed? + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a record containing a boolean (true/false) value if the image passes consistency tests, and the numbers of warnings and errors + """ + _code = 'ddsk' + _subcode = 'Chek' + + aetools.keysubst(_arguments, self._argmap_check_image) + _arguments['----'] = _object + + aetools.enumsubst(_arguments, 'ChDe', _Enum_bool) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_segment_image = { + 'segment_count' : 'SGCT', + 'segment_size' : 'SGSZ', + 'segment_name' : 'SGNM', + 'image_ID' : 'SGID', + } + + def segment_image(self, _object, _attributes={}, **_arguments): + """segment image: Segment a NDIF R/W or R/O image into smaller pieces + Required argument: the disk image to be segmented + Keyword argument segment_count: the number of image segments to create + Keyword argument segment_size: the size of image segments (in blocks) to create + Keyword argument segment_name: the root name for each image segment file + Keyword argument image_ID: string used to generate a unique image ID to group the segments + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a list of references to the image segments created + """ + _code = 'ddsk' + _subcode = 'SGMT' + + aetools.keysubst(_arguments, self._argmap_segment_image) + _arguments['----'] = _object + + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_create_SMI = { + 'source_images' : 'SMI1', + 'launching_application' : 'SMI2', + 'launching_document' : 'SMI3', + 'version_string' : 'SMI4', + 'checksum_verification' : 'VChk', + 'signature_verification' : 'VSig', + 'image_signing' : 'SImg', + } + + def create_SMI(self, _object, _attributes={}, **_arguments): + """create SMI: Creates a self-mounting image (SMI) from a list of NDIF disk images + Required argument: the self-mounting image to create + Keyword argument source_images: a list of references to sources images + Keyword argument launching_application: the path to an application to launch + Keyword argument launching_document: the path to a document to open + Keyword argument version_string: sets the 'vers' 1 resource of the self-mounting image + Keyword argument checksum_verification: Should the checksum of the source images be verified before creating the SMI? + Keyword argument signature_verification: Should the DigiSignŽ signature of the source images be verified before creating the SMI? + Keyword argument image_signing: Should the SMI be given a digital signature when it is created? + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a reference to the self-mounting image created + """ + _code = 'ddsk' + _subcode = 'MSMI' + + aetools.keysubst(_arguments, self._argmap_create_SMI) + _arguments['----'] = _object + + aetools.enumsubst(_arguments, 'VChk', _Enum_bool) + aetools.enumsubst(_arguments, 'VSig', _Enum_bool) + aetools.enumsubst(_arguments, 'SImg', _Enum_bool) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] class Verify_Checksum_reply_record(aetools.ComponentItem): - """Verify Checksum reply record - """ - want = 'Rcrc' + """Verify Checksum reply record - """ + want = 'Rcrc' class validity(aetools.NProperty): - """validity - true if checksum is valid """ - which = 'Vlid' - want = 'bool' + """validity - true if checksum is valid """ + which = 'Vlid' + want = 'bool' class expected_checksum(aetools.NProperty): - """expected checksum - checksum value stored in the image header (in hexadecimal) """ - which = 'crcE' - want = 'TEXT' + """expected checksum - checksum value stored in the image header (in hexadecimal) """ + which = 'crcE' + want = 'TEXT' class calculated_checksum(aetools.NProperty): - """calculated checksum - checksum value actually calculated (in hexadecimal) """ - which = 'crcA' - want = 'TEXT' + """calculated checksum - checksum value actually calculated (in hexadecimal) """ + which = 'crcA' + want = 'TEXT' class Check_Image_reply_record(aetools.ComponentItem): - """Check Image reply record - """ - want = 'Rchk' + """Check Image reply record - """ + want = 'Rchk' class consistency(aetools.NProperty): - """consistency - Does the image pass consistency checks? """ - which = 'Rch1' - want = 'bool' + """consistency - Does the image pass consistency checks? """ + which = 'Rch1' + want = 'bool' class error_count(aetools.NProperty): - """error count - the number of errors recorded """ - which = 'Rch2' - want = 'long' + """error count - the number of errors recorded """ + which = 'Rch2' + want = 'long' class warning_count(aetools.NProperty): - """warning count - the number of warnings recorded """ - which = 'Rch3' - want = 'long' + """warning count - the number of warnings recorded """ + which = 'Rch3' + want = 'long' Verify_Checksum_reply_record._propdict = { - 'validity' : validity, - 'expected_checksum' : expected_checksum, - 'calculated_checksum' : calculated_checksum, + 'validity' : validity, + 'expected_checksum' : expected_checksum, + 'calculated_checksum' : calculated_checksum, } Verify_Checksum_reply_record._elemdict = { } Check_Image_reply_record._propdict = { - 'consistency' : consistency, - 'error_count' : error_count, - 'warning_count' : warning_count, + 'consistency' : consistency, + 'error_count' : error_count, + 'warning_count' : warning_count, } Check_Image_reply_record._elemdict = { } _Enum_Acss = { - 'read_and_write' : 'RdWr', # read/write access - 'read_only' : 'Rdxx', # read-only access - 'any' : 'Anyx', # best possible access + 'read_and_write' : 'RdWr', # read/write access + 'read_only' : 'Rdxx', # read-only access + 'any' : 'Anyx', # best possible access } _Enum_Fsys = { - 'Mac_OS_Standard' : 'Fhfs', # classic HFS file system - 'compatible_Mac_OS_Extended' : 'Fhf+', # new HFS+ file system + 'Mac_OS_Standard' : 'Fhfs', # classic HFS file system + 'compatible_Mac_OS_Extended' : 'Fhf+', # new HFS+ file system } _Enum_alis = None # XXXX enum alis not found!! @@ -402,23 +402,23 @@ _Enum_bool = None # XXXX enum bool not found!! # Indices of types declared in this module # _classdeclarations = { - 'Rchk' : Check_Image_reply_record, - 'Rcrc' : Verify_Checksum_reply_record, + 'Rchk' : Check_Image_reply_record, + 'Rcrc' : Verify_Checksum_reply_record, } _propdeclarations = { - 'crcE' : expected_checksum, - 'Rch2' : error_count, - 'crcA' : calculated_checksum, - 'Rch3' : warning_count, - 'Vlid' : validity, - 'Rch1' : consistency, + 'crcE' : expected_checksum, + 'Rch2' : error_count, + 'crcA' : calculated_checksum, + 'Rch3' : warning_count, + 'Vlid' : validity, + 'Rch1' : consistency, } _compdeclarations = { } _enumdeclarations = { - 'Acss' : _Enum_Acss, - 'Fsys' : _Enum_Fsys, + 'Acss' : _Enum_Acss, + 'Fsys' : _Enum_Fsys, } diff --git a/Mac/Demo/applescript/Disk_Copy/Standard_Suite.py b/Mac/Demo/applescript/Disk_Copy/Standard_Suite.py index 931246e..455e78d 100644 --- a/Mac/Demo/applescript/Disk_Copy/Standard_Suite.py +++ b/Mac/Demo/applescript/Disk_Copy/Standard_Suite.py @@ -12,225 +12,225 @@ _code = 'Core' class Standard_Suite_Events: - _argmap_save = { - '_in' : 'kfil', - 'using_format' : 'SvAs', - 'checksum_verification' : 'VChk', - 'signature_verification' : 'VSig', - 'image_signing' : 'SImg', - 'leave_image_mounted' : 'Moun', - 'percent_free_space' : 'Slop', - 'logical_blocks' : 'Blks', - 'zeroing' : 'Zero', - } - - def save(self, _object, _attributes={}, **_arguments): - """save: Save an object - Required argument: the source object - Keyword argument _in: the target object - Keyword argument using_format: the format for the target - Keyword argument checksum_verification: Should the checksum be verified before saving? - Keyword argument signature_verification: Should the DigiSignŽ signature be verified before saving? - Keyword argument image_signing: Should the image be signed? - Keyword argument leave_image_mounted: Should the image be mounted after saving? - Keyword argument percent_free_space: percent free space to reserve (for image folder operation, 0-255%) - Keyword argument logical_blocks: number of logical blocks in the image (for image folder operation) - Keyword argument zeroing: Should all the blocks in the image be set to zeros? (for image folder operation) - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: the result of the save operation - """ - _code = 'core' - _subcode = 'save' - - aetools.keysubst(_arguments, self._argmap_save) - _arguments['----'] = _object - - aetools.enumsubst(_arguments, 'kfil', _Enum_obj_) - aetools.enumsubst(_arguments, 'SvAs', _Enum_SvAs) - aetools.enumsubst(_arguments, 'VChk', _Enum_bool) - aetools.enumsubst(_arguments, 'VSig', _Enum_bool) - aetools.enumsubst(_arguments, 'SImg', _Enum_bool) - aetools.enumsubst(_arguments, 'Moun', _Enum_bool) - aetools.enumsubst(_arguments, 'Slop', _Enum_long) - aetools.enumsubst(_arguments, 'Blks', _Enum_long) - aetools.enumsubst(_arguments, 'Zero', _Enum_bool) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - def do_script(self, _object, _attributes={}, **_arguments): - """do script: Execute an attached script located in the folder "Scripts" - Required argument: the script to be executed - Keyword argument _attributes: AppleEvent attribute dictionary - """ - _code = 'core' - _subcode = 'dosc' - - if _arguments: raise TypeError, 'No optional args expected' - _arguments['----'] = _object - - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] + _argmap_save = { + '_in' : 'kfil', + 'using_format' : 'SvAs', + 'checksum_verification' : 'VChk', + 'signature_verification' : 'VSig', + 'image_signing' : 'SImg', + 'leave_image_mounted' : 'Moun', + 'percent_free_space' : 'Slop', + 'logical_blocks' : 'Blks', + 'zeroing' : 'Zero', + } + + def save(self, _object, _attributes={}, **_arguments): + """save: Save an object + Required argument: the source object + Keyword argument _in: the target object + Keyword argument using_format: the format for the target + Keyword argument checksum_verification: Should the checksum be verified before saving? + Keyword argument signature_verification: Should the DigiSignŽ signature be verified before saving? + Keyword argument image_signing: Should the image be signed? + Keyword argument leave_image_mounted: Should the image be mounted after saving? + Keyword argument percent_free_space: percent free space to reserve (for image folder operation, 0-255%) + Keyword argument logical_blocks: number of logical blocks in the image (for image folder operation) + Keyword argument zeroing: Should all the blocks in the image be set to zeros? (for image folder operation) + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: the result of the save operation + """ + _code = 'core' + _subcode = 'save' + + aetools.keysubst(_arguments, self._argmap_save) + _arguments['----'] = _object + + aetools.enumsubst(_arguments, 'kfil', _Enum_obj_) + aetools.enumsubst(_arguments, 'SvAs', _Enum_SvAs) + aetools.enumsubst(_arguments, 'VChk', _Enum_bool) + aetools.enumsubst(_arguments, 'VSig', _Enum_bool) + aetools.enumsubst(_arguments, 'SImg', _Enum_bool) + aetools.enumsubst(_arguments, 'Moun', _Enum_bool) + aetools.enumsubst(_arguments, 'Slop', _Enum_long) + aetools.enumsubst(_arguments, 'Blks', _Enum_long) + aetools.enumsubst(_arguments, 'Zero', _Enum_bool) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + def do_script(self, _object, _attributes={}, **_arguments): + """do script: Execute an attached script located in the folder "Scripts" + Required argument: the script to be executed + Keyword argument _attributes: AppleEvent attribute dictionary + """ + _code = 'core' + _subcode = 'dosc' + + if _arguments: raise TypeError, 'No optional args expected' + _arguments['----'] = _object + + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] class application(aetools.ComponentItem): - """application - The Disk Copy application """ - want = 'capp' + """application - The Disk Copy application """ + want = 'capp' class version(aetools.NProperty): - """version - the version of this application """ - which = 'vers' - want = 'vers' + """version - the version of this application """ + which = 'vers' + want = 'vers' class name(aetools.NProperty): - """name - the name of this application """ - which = 'pnam' - want = 'TEXT' + """name - the name of this application """ + which = 'pnam' + want = 'TEXT' class comment(aetools.NProperty): - """comment - the comment associated with the application """ - which = 'comt' - want = 'TEXT' + """comment - the comment associated with the application """ + which = 'comt' + want = 'TEXT' class driver_version(aetools.NProperty): - """driver version - the version of the disk image driver """ - which = 'dVer' - want = 'vers' + """driver version - the version of the disk image driver """ + which = 'dVer' + want = 'vers' class nonejectable_mode(aetools.NProperty): - """nonejectable mode - Should mounted images be non-ejectable? """ - which = 'otto' - want = 'bool' + """nonejectable mode - Should mounted images be non-ejectable? """ + which = 'otto' + want = 'bool' class save_log_file(aetools.NProperty): - """save log file - Should the log file be saved on disk? """ - which = 'PSaL' - want = 'bool' + """save log file - Should the log file be saved on disk? """ + which = 'PSaL' + want = 'bool' class use_speech(aetools.NProperty): - """use speech - Should Disk Copy use spoken feedback? """ - which = 'PTlk' - want = 'bool' + """use speech - Should Disk Copy use spoken feedback? """ + which = 'PTlk' + want = 'bool' class smart_Save_As(aetools.NProperty): - """smart Save As - Should the Save As... dialog box automatically go to the right folder? """ - which = 'PSSP' - want = 'bool' + """smart Save As - Should the Save As... dialog box automatically go to the right folder? """ + which = 'PSSP' + want = 'bool' class checksum_verification(aetools.NProperty): - """checksum verification - Should image checksums be verified? """ - which = 'PVeC' - want = 'bool' + """checksum verification - Should image checksums be verified? """ + which = 'PVeC' + want = 'bool' class signature_verification(aetools.NProperty): - """signature verification - Should digital signatures be verified? """ - which = 'PVeS' - want = 'bool' + """signature verification - Should digital signatures be verified? """ + which = 'PVeS' + want = 'bool' class exclude_DiskScripts(aetools.NProperty): - """exclude DiskScripts - Should images referenced in DiskScripts/DiskSets be excluded from verification? """ - which = 'PExD' - want = 'bool' + """exclude DiskScripts - Should images referenced in DiskScripts/DiskSets be excluded from verification? """ + which = 'PExD' + want = 'bool' class exclude_remote_images(aetools.NProperty): - """exclude remote images - Should images that are located on network volumes be excluded from verification? """ - which = 'PExR' - want = 'bool' + """exclude remote images - Should images that are located on network volumes be excluded from verification? """ + which = 'PExR' + want = 'bool' class image_signing(aetools.NProperty): - """image signing - Should images be signed with a digital signature? """ - which = 'PSiI' - want = 'bool' + """image signing - Should images be signed with a digital signature? """ + which = 'PSiI' + want = 'bool' class leave_image_mounted(aetools.NProperty): - """leave image mounted - Should images be mounted after they are created? """ - which = 'PMoA' - want = 'bool' + """leave image mounted - Should images be mounted after they are created? """ + which = 'PMoA' + want = 'bool' class erase_confirmation(aetools.NProperty): - """erase confirmation - Should the user be required to confirm commands that erase disks? """ - which = 'PCoE' - want = 'bool' + """erase confirmation - Should the user be required to confirm commands that erase disks? """ + which = 'PCoE' + want = 'bool' class zeroing(aetools.NProperty): - """zeroing - Should all blocks of a new image be set to zero? """ - which = 'PZeB' - want = 'bool' + """zeroing - Should all blocks of a new image be set to zero? """ + which = 'PZeB' + want = 'bool' class default_create_size(aetools.NProperty): - """default create size - the default size for a new image, in blocks (512 bytes per block) """ - which = 'PDeS' - want = 'long' + """default create size - the default size for a new image, in blocks (512 bytes per block) """ + which = 'PDeS' + want = 'long' class default_create_name(aetools.NProperty): - """default create name - the default volume name for a new image """ - which = 'PDeN' - want = 'TEXT' + """default create name - the default volume name for a new image """ + which = 'PDeN' + want = 'TEXT' class make_multiple_floppies(aetools.NProperty): - """make multiple floppies - Should the user be prompted to make multiple floppy disk images at a time? """ - which = 'PBuM' - want = 'bool' + """make multiple floppies - Should the user be prompted to make multiple floppy disk images at a time? """ + which = 'PBuM' + want = 'bool' class auto_image_upon_insert(aetools.NProperty): - """auto image upon insert - Should a newly-inserted disk automatically be processed into an image? """ - which = 'Paim' - want = 'bool' + """auto image upon insert - Should a newly-inserted disk automatically be processed into an image? """ + which = 'Paim' + want = 'bool' class eject_after_auto_image(aetools.NProperty): - """eject after auto image - Should auto-imaged disks be ejected afterwards? """ - which = 'Pejc' - want = 'bool' + """eject after auto image - Should auto-imaged disks be ejected afterwards? """ + which = 'Pejc' + want = 'bool' class auto_copy_upon_floppy_insert(aetools.NProperty): - """auto copy upon floppy insert - Instead of auto-imaging, should newly-inserted floppy disks be copied? """ - which = 'Pcpf' - want = 'bool' + """auto copy upon floppy insert - Instead of auto-imaging, should newly-inserted floppy disks be copied? """ + which = 'Pcpf' + want = 'bool' class volume_suffix(aetools.NProperty): - """volume suffix - the default volume name suffix """ - which = 'PDiE' - want = 'TEXT' + """volume suffix - the default volume name suffix """ + which = 'PDiE' + want = 'TEXT' class image_suffix(aetools.NProperty): - """image suffix - the default image name suffix """ - which = 'PImE' - want = 'TEXT' + """image suffix - the default image name suffix """ + which = 'PImE' + want = 'TEXT' class default_file_system(aetools.NProperty): - """default file system - the default file system type for new blank images """ - which = 'Pfsy' - want = 'Fsys' + """default file system - the default file system type for new blank images """ + which = 'Pfsy' + want = 'Fsys' class default_image_format(aetools.NProperty): - """default image format - the default image file format """ - which = 'Pdfm' - want = 'SvAs' + """default image format - the default image file format """ + which = 'Pdfm' + want = 'SvAs' class disk(aetools.ComponentItem): - """disk - A mounted volume """ - want = 'Disk' + """disk - A mounted volume """ + want = 'Disk' name = name comment = comment class locked(aetools.NProperty): - """locked - Is the disk locked? """ - which = 'islk' - want = 'bool' + """locked - Is the disk locked? """ + which = 'islk' + want = 'bool' class creation_date(aetools.NProperty): - """creation date - the creation date of disk """ - which = 'ascd' - want = 'ldt ' + """creation date - the creation date of disk """ + which = 'ascd' + want = 'ldt ' class modification_date(aetools.NProperty): - """modification date - the modification date of disk """ - which = 'asmo' - want = 'ldt ' + """modification date - the modification date of disk """ + which = 'asmo' + want = 'ldt ' class crc32_checksum(aetools.NProperty): - """crc32 checksum - the crc-32 checksum of the disk """ - which = 'Xcrc' - want = 'TEXT' + """crc32 checksum - the crc-32 checksum of the disk """ + which = 'Xcrc' + want = 'TEXT' class disk_copy_4_2e_2_checksum(aetools.NProperty): - """disk copy 4.2 checksum - the Disk Copy 4.2 checksum of the disk """ - which = 'Xc42' - want = 'TEXT' + """disk copy 4.2 checksum - the Disk Copy 4.2 checksum of the disk """ + which = 'Xc42' + want = 'TEXT' class block_count(aetools.NProperty): - """block count - the number of blocks on disk """ - which = 'Xblk' - want = 'long' + """block count - the number of blocks on disk """ + which = 'Xblk' + want = 'long' class file_system(aetools.NProperty): - """file system - the file system used on disk """ - which = 'Xfsi' - want = 'TEXT' + """file system - the file system used on disk """ + which = 'Xfsi' + want = 'TEXT' class folder(aetools.ComponentItem): - """folder - A folder or directory on a disk """ - want = 'Fold' + """folder - A folder or directory on a disk """ + want = 'Fold' name = name @@ -241,8 +241,8 @@ creation_date = creation_date modification_date = modification_date class disk_image(aetools.ComponentItem): - """disk image - A disk image file """ - want = 'DImg' + """disk image - A disk image file """ + want = 'DImg' name = name @@ -254,29 +254,29 @@ creation_date = creation_date modification_date = modification_date class file_format(aetools.NProperty): - """file format - the format of the disk image file """ - which = 'Ifmt' - want = 'TEXT' + """file format - the format of the disk image file """ + which = 'Ifmt' + want = 'TEXT' class signed(aetools.NProperty): - """signed - Does the disk image have a DigiSignŽ signature? """ - which = 'Isin' - want = 'bool' + """signed - Does the disk image have a DigiSignŽ signature? """ + which = 'Isin' + want = 'bool' class compressed(aetools.NProperty): - """compressed - Is the disk image compressed? """ - which = 'Icom' - want = 'bool' + """compressed - Is the disk image compressed? """ + which = 'Icom' + want = 'bool' class segmented(aetools.NProperty): - """segmented - Is the disk image segmented? """ - which = 'Iseg' - want = 'bool' + """segmented - Is the disk image segmented? """ + which = 'Iseg' + want = 'bool' class segments(aetools.NProperty): - """segments - a list of references to other segments that make up a complete image """ - which = 'Isg#' - want = 'fss ' + """segments - a list of references to other segments that make up a complete image """ + which = 'Isg#' + want = 'fss ' class disk_name(aetools.NProperty): - """disk name - the name of the disk this image represents """ - which = 'Idnm' - want = 'TEXT' + """disk name - the name of the disk this image represents """ + which = 'Idnm' + want = 'TEXT' crc32_checksum = crc32_checksum @@ -286,124 +286,124 @@ block_count = block_count file_system = file_system class data_fork_size(aetools.NProperty): - """data fork size - the size (in bytes) of the data fork of the disk image """ - which = 'Idfk' - want = 'long' + """data fork size - the size (in bytes) of the data fork of the disk image """ + which = 'Idfk' + want = 'long' class resource_fork_size(aetools.NProperty): - """resource fork size - the size (in bytes) of the resource fork of the disk image """ - which = 'Irfk' - want = 'long' + """resource fork size - the size (in bytes) of the resource fork of the disk image """ + which = 'Irfk' + want = 'long' class Save_reply_record(aetools.ComponentItem): - """Save reply record - Result from the save operation """ - want = 'cpyR' + """Save reply record - Result from the save operation """ + want = 'cpyR' class resulting_target_object(aetools.NProperty): - """resulting target object - a reference to the target object after it has been saved """ - which = 'rcpO' - want = 'obj ' + """resulting target object - a reference to the target object after it has been saved """ + which = 'rcpO' + want = 'obj ' class copy_type(aetools.NProperty): - """copy type - the way in which the target object was saved """ - which = 'rcpT' - want = 'rcpT' + """copy type - the way in which the target object was saved """ + which = 'rcpT' + want = 'rcpT' application._propdict = { - 'version' : version, - 'name' : name, - 'comment' : comment, - 'driver_version' : driver_version, - 'nonejectable_mode' : nonejectable_mode, - 'save_log_file' : save_log_file, - 'use_speech' : use_speech, - 'smart_Save_As' : smart_Save_As, - 'checksum_verification' : checksum_verification, - 'signature_verification' : signature_verification, - 'exclude_DiskScripts' : exclude_DiskScripts, - 'exclude_remote_images' : exclude_remote_images, - 'image_signing' : image_signing, - 'leave_image_mounted' : leave_image_mounted, - 'erase_confirmation' : erase_confirmation, - 'zeroing' : zeroing, - 'default_create_size' : default_create_size, - 'default_create_name' : default_create_name, - 'make_multiple_floppies' : make_multiple_floppies, - 'auto_image_upon_insert' : auto_image_upon_insert, - 'eject_after_auto_image' : eject_after_auto_image, - 'auto_copy_upon_floppy_insert' : auto_copy_upon_floppy_insert, - 'volume_suffix' : volume_suffix, - 'image_suffix' : image_suffix, - 'default_file_system' : default_file_system, - 'default_image_format' : default_image_format, + 'version' : version, + 'name' : name, + 'comment' : comment, + 'driver_version' : driver_version, + 'nonejectable_mode' : nonejectable_mode, + 'save_log_file' : save_log_file, + 'use_speech' : use_speech, + 'smart_Save_As' : smart_Save_As, + 'checksum_verification' : checksum_verification, + 'signature_verification' : signature_verification, + 'exclude_DiskScripts' : exclude_DiskScripts, + 'exclude_remote_images' : exclude_remote_images, + 'image_signing' : image_signing, + 'leave_image_mounted' : leave_image_mounted, + 'erase_confirmation' : erase_confirmation, + 'zeroing' : zeroing, + 'default_create_size' : default_create_size, + 'default_create_name' : default_create_name, + 'make_multiple_floppies' : make_multiple_floppies, + 'auto_image_upon_insert' : auto_image_upon_insert, + 'eject_after_auto_image' : eject_after_auto_image, + 'auto_copy_upon_floppy_insert' : auto_copy_upon_floppy_insert, + 'volume_suffix' : volume_suffix, + 'image_suffix' : image_suffix, + 'default_file_system' : default_file_system, + 'default_image_format' : default_image_format, } application._elemdict = { } disk._propdict = { - 'name' : name, - 'comment' : comment, - 'locked' : locked, - 'creation_date' : creation_date, - 'modification_date' : modification_date, - 'crc32_checksum' : crc32_checksum, - 'disk_copy_4_2e_2_checksum' : disk_copy_4_2e_2_checksum, - 'block_count' : block_count, - 'file_system' : file_system, + 'name' : name, + 'comment' : comment, + 'locked' : locked, + 'creation_date' : creation_date, + 'modification_date' : modification_date, + 'crc32_checksum' : crc32_checksum, + 'disk_copy_4_2e_2_checksum' : disk_copy_4_2e_2_checksum, + 'block_count' : block_count, + 'file_system' : file_system, } disk._elemdict = { } folder._propdict = { - 'name' : name, - 'comment' : comment, - 'creation_date' : creation_date, - 'modification_date' : modification_date, + 'name' : name, + 'comment' : comment, + 'creation_date' : creation_date, + 'modification_date' : modification_date, } folder._elemdict = { } disk_image._propdict = { - 'name' : name, - 'comment' : comment, - 'locked' : locked, - 'creation_date' : creation_date, - 'modification_date' : modification_date, - 'file_format' : file_format, - 'signed' : signed, - 'compressed' : compressed, - 'segmented' : segmented, - 'segments' : segments, - 'disk_name' : disk_name, - 'crc32_checksum' : crc32_checksum, - 'disk_copy_4_2e_2_checksum' : disk_copy_4_2e_2_checksum, - 'block_count' : block_count, - 'file_system' : file_system, - 'data_fork_size' : data_fork_size, - 'resource_fork_size' : resource_fork_size, + 'name' : name, + 'comment' : comment, + 'locked' : locked, + 'creation_date' : creation_date, + 'modification_date' : modification_date, + 'file_format' : file_format, + 'signed' : signed, + 'compressed' : compressed, + 'segmented' : segmented, + 'segments' : segments, + 'disk_name' : disk_name, + 'crc32_checksum' : crc32_checksum, + 'disk_copy_4_2e_2_checksum' : disk_copy_4_2e_2_checksum, + 'block_count' : block_count, + 'file_system' : file_system, + 'data_fork_size' : data_fork_size, + 'resource_fork_size' : resource_fork_size, } disk_image._elemdict = { } Save_reply_record._propdict = { - 'resulting_target_object' : resulting_target_object, - 'copy_type' : copy_type, + 'resulting_target_object' : resulting_target_object, + 'copy_type' : copy_type, } Save_reply_record._elemdict = { } _Enum_UIAc = { - 'never_interact' : 'eNvr', # DonÕt allow any interaction at all - 'interact_with_self' : 'eInS', # Only allow interaction from internal events - 'interact_with_local' : 'eInL', # Allow interaction from any event originating on this machine - 'interact_with_all' : 'eInA', # Allow interaction from network events + 'never_interact' : 'eNvr', # DonÕt allow any interaction at all + 'interact_with_self' : 'eInS', # Only allow interaction from internal events + 'interact_with_local' : 'eInL', # Allow interaction from any event originating on this machine + 'interact_with_all' : 'eInA', # Allow interaction from network events } _Enum_SvAs = { - 'NDIF_RW' : 'RdWr', # read/write NDIF disk image - 'NDIF_RO' : 'Rdxx', # read-only NDIF disk image - 'NDIF_Compressed' : 'ROCo', # compressed NDIF disk image - 'Disk_Copy_4_2e_2' : 'DC42', # Disk Copy 4.2 disk image + 'NDIF_RW' : 'RdWr', # read/write NDIF disk image + 'NDIF_RO' : 'Rdxx', # read-only NDIF disk image + 'NDIF_Compressed' : 'ROCo', # compressed NDIF disk image + 'Disk_Copy_4_2e_2' : 'DC42', # Disk Copy 4.2 disk image } _Enum_rcpT = { - 'block_disk_copy' : 'cpBl', # block-by-block disk-level copy - 'files_and_file_ID_copy' : 'cpID', # all files including desktop databases and file IDÕs - 'files_and_desktop_info' : 'cpDT', # all files and most desktop information - 'files_only' : 'cpFI', # all files but no desktop information - 'disk_image_conversion' : 'cpCV', # disk image format conversion - 'disk_image_creation' : 'cpCR', # disk image creation + 'block_disk_copy' : 'cpBl', # block-by-block disk-level copy + 'files_and_file_ID_copy' : 'cpID', # all files including desktop databases and file IDÕs + 'files_and_desktop_info' : 'cpDT', # all files and most desktop information + 'files_only' : 'cpFI', # all files but no desktop information + 'disk_image_conversion' : 'cpCV', # disk image format conversion + 'disk_image_creation' : 'cpCR', # disk image creation } _Enum_long = None # XXXX enum long not found!! @@ -414,64 +414,64 @@ _Enum_obj_ = None # XXXX enum obj not found!! # Indices of types declared in this module # _classdeclarations = { - 'DImg' : disk_image, - 'capp' : application, - 'Disk' : disk, - 'Fold' : folder, - 'cpyR' : Save_reply_record, + 'DImg' : disk_image, + 'capp' : application, + 'Disk' : disk, + 'Fold' : folder, + 'cpyR' : Save_reply_record, } _propdeclarations = { - 'Xcrc' : crc32_checksum, - 'PDeS' : default_create_size, - 'Idnm' : disk_name, - 'PSSP' : smart_Save_As, - 'Pcpf' : auto_copy_upon_floppy_insert, - 'pnam' : name, - 'Isin' : signed, - 'otto' : nonejectable_mode, - 'PExD' : exclude_DiskScripts, - 'Iseg' : segmented, - 'islk' : locked, - 'asmo' : modification_date, - 'PTlk' : use_speech, - 'Pfsy' : default_file_system, - 'PVeC' : checksum_verification, - 'Xc42' : disk_copy_4_2e_2_checksum, - 'rcpO' : resulting_target_object, - 'Paim' : auto_image_upon_insert, - 'comt' : comment, - 'PCoE' : erase_confirmation, - 'dVer' : driver_version, - 'PDeN' : default_create_name, - 'PBuM' : make_multiple_floppies, - 'rcpT' : copy_type, - 'PDiE' : volume_suffix, - 'Ifmt' : file_format, - 'Pdfm' : default_image_format, - 'ascd' : creation_date, - 'Pejc' : eject_after_auto_image, - 'PZeB' : zeroing, - 'PExR' : exclude_remote_images, - 'PImE' : image_suffix, - 'PVeS' : signature_verification, - 'PSaL' : save_log_file, - 'Xblk' : block_count, - 'PMoA' : leave_image_mounted, - 'Isg#' : segments, - 'Irfk' : resource_fork_size, - 'Icom' : compressed, - 'Xfsi' : file_system, - 'Idfk' : data_fork_size, - 'vers' : version, - 'PSiI' : image_signing, + 'Xcrc' : crc32_checksum, + 'PDeS' : default_create_size, + 'Idnm' : disk_name, + 'PSSP' : smart_Save_As, + 'Pcpf' : auto_copy_upon_floppy_insert, + 'pnam' : name, + 'Isin' : signed, + 'otto' : nonejectable_mode, + 'PExD' : exclude_DiskScripts, + 'Iseg' : segmented, + 'islk' : locked, + 'asmo' : modification_date, + 'PTlk' : use_speech, + 'Pfsy' : default_file_system, + 'PVeC' : checksum_verification, + 'Xc42' : disk_copy_4_2e_2_checksum, + 'rcpO' : resulting_target_object, + 'Paim' : auto_image_upon_insert, + 'comt' : comment, + 'PCoE' : erase_confirmation, + 'dVer' : driver_version, + 'PDeN' : default_create_name, + 'PBuM' : make_multiple_floppies, + 'rcpT' : copy_type, + 'PDiE' : volume_suffix, + 'Ifmt' : file_format, + 'Pdfm' : default_image_format, + 'ascd' : creation_date, + 'Pejc' : eject_after_auto_image, + 'PZeB' : zeroing, + 'PExR' : exclude_remote_images, + 'PImE' : image_suffix, + 'PVeS' : signature_verification, + 'PSaL' : save_log_file, + 'Xblk' : block_count, + 'PMoA' : leave_image_mounted, + 'Isg#' : segments, + 'Irfk' : resource_fork_size, + 'Icom' : compressed, + 'Xfsi' : file_system, + 'Idfk' : data_fork_size, + 'vers' : version, + 'PSiI' : image_signing, } _compdeclarations = { } _enumdeclarations = { - 'SvAs' : _Enum_SvAs, - 'UIAc' : _Enum_UIAc, - 'rcpT' : _Enum_rcpT, + 'SvAs' : _Enum_SvAs, + 'UIAc' : _Enum_UIAc, + 'rcpT' : _Enum_rcpT, } diff --git a/Mac/Demo/applescript/Disk_Copy/Utility_Events.py b/Mac/Demo/applescript/Disk_Copy/Utility_Events.py index edac8f4..172b408 100644 --- a/Mac/Demo/applescript/Disk_Copy/Utility_Events.py +++ b/Mac/Demo/applescript/Disk_Copy/Utility_Events.py @@ -12,187 +12,187 @@ _code = 'ddsk' class Utility_Events_Events: - _argmap_select_disk_image = { - 'with_prompt' : 'SELp', - } - - def select_disk_image(self, _no_object=None, _attributes={}, **_arguments): - """select disk image: Prompt the user to select a disk image - Keyword argument with_prompt: the prompt string to be displayed - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a reference to a disk image - """ - _code = 'UTIL' - _subcode = 'SEL1' - - aetools.keysubst(_arguments, self._argmap_select_disk_image) - if _no_object != None: raise TypeError, 'No direct arg expected' - - aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_select_DiskScript = { - 'with_prompt' : 'SELp', - } - - def select_DiskScript(self, _no_object=None, _attributes={}, **_arguments): - """select DiskScript: Prompt the user to select a DiskScript - Keyword argument with_prompt: the prompt string to be displayed - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a reference to a DiskScript - """ - _code = 'UTIL' - _subcode = 'SEL2' - - aetools.keysubst(_arguments, self._argmap_select_DiskScript) - if _no_object != None: raise TypeError, 'No direct arg expected' - - aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_select_disk_image_or_DiskScript = { - 'with_prompt' : 'SELp', - } - - def select_disk_image_or_DiskScript(self, _no_object=None, _attributes={}, **_arguments): - """select disk image or DiskScript: Prompt the user to select a disk image or DiskScript - Keyword argument with_prompt: the prompt string to be displayed - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a reference to disk image or a DiskScript - """ - _code = 'UTIL' - _subcode = 'SEL3' - - aetools.keysubst(_arguments, self._argmap_select_disk_image_or_DiskScript) - if _no_object != None: raise TypeError, 'No direct arg expected' - - aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_select_floppy_disk_image = { - 'with_prompt' : 'SELp', - } - - def select_floppy_disk_image(self, _no_object=None, _attributes={}, **_arguments): - """select floppy disk image: Prompt the user to select a floppy disk image - Keyword argument with_prompt: the prompt string to be displayed - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a reference to a floppy disk image - """ - _code = 'UTIL' - _subcode = 'SEL4' - - aetools.keysubst(_arguments, self._argmap_select_floppy_disk_image) - if _no_object != None: raise TypeError, 'No direct arg expected' - - aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_select_disk = { - 'with_prompt' : 'SELp', - } - - def select_disk(self, _no_object=None, _attributes={}, **_arguments): - """select disk: Prompt the user to select a disk volume - Keyword argument with_prompt: the prompt string to be displayed - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a reference to the disk - """ - _code = 'UTIL' - _subcode = 'SEL5' - - aetools.keysubst(_arguments, self._argmap_select_disk) - if _no_object != None: raise TypeError, 'No direct arg expected' - - aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_select_folder = { - 'with_prompt' : 'SELp', - } - - def select_folder(self, _no_object=None, _attributes={}, **_arguments): - """select folder: Prompt the user to select a folder - Keyword argument with_prompt: the prompt string to be displayed - Keyword argument _attributes: AppleEvent attribute dictionary - Returns: a reference to the folder - """ - _code = 'UTIL' - _subcode = 'SEL6' - - aetools.keysubst(_arguments, self._argmap_select_folder) - if _no_object != None: raise TypeError, 'No direct arg expected' - - aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] - - _argmap_log = { - 'time_stamp' : 'TSMP', - } - - def log(self, _object, _attributes={}, **_arguments): - """log: Add a string to the log window - Required argument: the string to add to the log window - Keyword argument time_stamp: Should the log entry be time-stamped? (false if not supplied) - Keyword argument _attributes: AppleEvent attribute dictionary - """ - _code = 'UTIL' - _subcode = 'LOG ' - - aetools.keysubst(_arguments, self._argmap_log) - _arguments['----'] = _object - - aetools.enumsubst(_arguments, 'TSMP', _Enum_bool) - - _reply, _arguments, _attributes = self.send(_code, _subcode, - _arguments, _attributes) - if _arguments.has_key('errn'): - raise aetools.Error, aetools.decodeerror(_arguments) - # XXXX Optionally decode result - if _arguments.has_key('----'): - return _arguments['----'] + _argmap_select_disk_image = { + 'with_prompt' : 'SELp', + } + + def select_disk_image(self, _no_object=None, _attributes={}, **_arguments): + """select disk image: Prompt the user to select a disk image + Keyword argument with_prompt: the prompt string to be displayed + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a reference to a disk image + """ + _code = 'UTIL' + _subcode = 'SEL1' + + aetools.keysubst(_arguments, self._argmap_select_disk_image) + if _no_object != None: raise TypeError, 'No direct arg expected' + + aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_select_DiskScript = { + 'with_prompt' : 'SELp', + } + + def select_DiskScript(self, _no_object=None, _attributes={}, **_arguments): + """select DiskScript: Prompt the user to select a DiskScript + Keyword argument with_prompt: the prompt string to be displayed + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a reference to a DiskScript + """ + _code = 'UTIL' + _subcode = 'SEL2' + + aetools.keysubst(_arguments, self._argmap_select_DiskScript) + if _no_object != None: raise TypeError, 'No direct arg expected' + + aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_select_disk_image_or_DiskScript = { + 'with_prompt' : 'SELp', + } + + def select_disk_image_or_DiskScript(self, _no_object=None, _attributes={}, **_arguments): + """select disk image or DiskScript: Prompt the user to select a disk image or DiskScript + Keyword argument with_prompt: the prompt string to be displayed + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a reference to disk image or a DiskScript + """ + _code = 'UTIL' + _subcode = 'SEL3' + + aetools.keysubst(_arguments, self._argmap_select_disk_image_or_DiskScript) + if _no_object != None: raise TypeError, 'No direct arg expected' + + aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_select_floppy_disk_image = { + 'with_prompt' : 'SELp', + } + + def select_floppy_disk_image(self, _no_object=None, _attributes={}, **_arguments): + """select floppy disk image: Prompt the user to select a floppy disk image + Keyword argument with_prompt: the prompt string to be displayed + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a reference to a floppy disk image + """ + _code = 'UTIL' + _subcode = 'SEL4' + + aetools.keysubst(_arguments, self._argmap_select_floppy_disk_image) + if _no_object != None: raise TypeError, 'No direct arg expected' + + aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_select_disk = { + 'with_prompt' : 'SELp', + } + + def select_disk(self, _no_object=None, _attributes={}, **_arguments): + """select disk: Prompt the user to select a disk volume + Keyword argument with_prompt: the prompt string to be displayed + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a reference to the disk + """ + _code = 'UTIL' + _subcode = 'SEL5' + + aetools.keysubst(_arguments, self._argmap_select_disk) + if _no_object != None: raise TypeError, 'No direct arg expected' + + aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_select_folder = { + 'with_prompt' : 'SELp', + } + + def select_folder(self, _no_object=None, _attributes={}, **_arguments): + """select folder: Prompt the user to select a folder + Keyword argument with_prompt: the prompt string to be displayed + Keyword argument _attributes: AppleEvent attribute dictionary + Returns: a reference to the folder + """ + _code = 'UTIL' + _subcode = 'SEL6' + + aetools.keysubst(_arguments, self._argmap_select_folder) + if _no_object != None: raise TypeError, 'No direct arg expected' + + aetools.enumsubst(_arguments, 'SELp', _Enum_TEXT) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] + + _argmap_log = { + 'time_stamp' : 'TSMP', + } + + def log(self, _object, _attributes={}, **_arguments): + """log: Add a string to the log window + Required argument: the string to add to the log window + Keyword argument time_stamp: Should the log entry be time-stamped? (false if not supplied) + Keyword argument _attributes: AppleEvent attribute dictionary + """ + _code = 'UTIL' + _subcode = 'LOG ' + + aetools.keysubst(_arguments, self._argmap_log) + _arguments['----'] = _object + + aetools.enumsubst(_arguments, 'TSMP', _Enum_bool) + + _reply, _arguments, _attributes = self.send(_code, _subcode, + _arguments, _attributes) + if _arguments.has_key('errn'): + raise aetools.Error, aetools.decodeerror(_arguments) + # XXXX Optionally decode result + if _arguments.has_key('----'): + return _arguments['----'] _Enum_TEXT = None # XXXX enum TEXT not found!! _Enum_bool = None # XXXX enum bool not found!! diff --git a/Mac/Demo/applescript/Disk_Copy/__init__.py b/Mac/Demo/applescript/Disk_Copy/__init__.py index b814056..ac50561 100644 --- a/Mac/Demo/applescript/Disk_Copy/__init__.py +++ b/Mac/Demo/applescript/Disk_Copy/__init__.py @@ -1,6 +1,6 @@ """ Package generated from Macintosh HD:Hulpprogramma's:Disk Copy -Resource aete resid 0 +Resource aete resid 0 """ import aetools Error = aetools.Error @@ -10,17 +10,17 @@ import Utility_Events _code_to_module = { - 'Core' : Standard_Suite, - 'ddsk' : Special_Events, - 'ddsk' : Utility_Events, + 'Core' : Standard_Suite, + 'ddsk' : Special_Events, + 'ddsk' : Utility_Events, } _code_to_fullname = { - 'Core' : ('Disk_Copy.Standard_Suite', 'Standard_Suite'), - 'ddsk' : ('Disk_Copy.Special_Events', 'Special_Events'), - 'ddsk' : ('Disk_Copy.Utility_Events', 'Utility_Events'), + 'Core' : ('Disk_Copy.Standard_Suite', 'Standard_Suite'), + 'ddsk' : ('Disk_Copy.Special_Events', 'Special_Events'), + 'ddsk' : ('Disk_Copy.Utility_Events', 'Utility_Events'), } from Standard_Suite import * @@ -29,8 +29,7 @@ from Utility_Events import * class Disk_Copy(Standard_Suite_Events, - Special_Events_Events, - Utility_Events_Events, - aetools.TalkTo): - _signature = 'ddsk' - + Special_Events_Events, + Utility_Events_Events, + aetools.TalkTo): + _signature = 'ddsk' diff --git a/Mac/Demo/applescript/makedisk.py b/Mac/Demo/applescript/makedisk.py index 3016964..91210ee 100644 --- a/Mac/Demo/applescript/makedisk.py +++ b/Mac/Demo/applescript/makedisk.py @@ -6,10 +6,10 @@ talker = Disk_Copy.Disk_Copy(start=1) talker.activate() filespec = macfs.FSSpec('my disk image.img') try: - objref = talker.create('my disk image', saving_as=filespec, leave_image_mounted=1) + objref = talker.create('my disk image', saving_as=filespec, leave_image_mounted=1) except Disk_Copy.Error, arg: - print "ERROR: my disk image:", arg + print "ERROR: my disk image:", arg else: - print 'objref=', objref + print 'objref=', objref print 'Type return to exit-' sys.stdin.readline() diff --git a/Mac/Demo/calldll/testcalldll.py b/Mac/Demo/calldll/testcalldll.py index d4a4853..e0f6964 100644 --- a/Mac/Demo/calldll/testcalldll.py +++ b/Mac/Demo/calldll/testcalldll.py @@ -8,16 +8,16 @@ fss, ok = macfs.PromptGetFile("Show me calldll.ppc.slb") lib = calldll.getdiskfragment(fss, 'calldll.ppc.slb') -cdll_b_bbbbbbbb = calldll.newcall(lib.cdll_b_bbbbbbbb, 'Byte', 'InByte', 'InByte', - 'InByte', 'InByte','InByte', 'InByte','InByte', 'InByte') -cdll_h_hhhhhhhh = calldll.newcall(lib.cdll_h_hhhhhhhh, 'Short', 'InShort', 'InShort', - 'InShort', 'InShort','InShort', 'InShort','InShort', 'InShort') -cdll_l_llllllll = calldll.newcall(lib.cdll_l_llllllll, 'Long', 'InLong', 'InLong', - 'InLong', 'InLong','InLong', 'InLong','InLong', 'InLong') - +cdll_b_bbbbbbbb = calldll.newcall(lib.cdll_b_bbbbbbbb, 'Byte', 'InByte', 'InByte', + 'InByte', 'InByte','InByte', 'InByte','InByte', 'InByte') +cdll_h_hhhhhhhh = calldll.newcall(lib.cdll_h_hhhhhhhh, 'Short', 'InShort', 'InShort', + 'InShort', 'InShort','InShort', 'InShort','InShort', 'InShort') +cdll_l_llllllll = calldll.newcall(lib.cdll_l_llllllll, 'Long', 'InLong', 'InLong', + 'InLong', 'InLong','InLong', 'InLong','InLong', 'InLong') + cdll_N_ssssssss = calldll.newcall(lib.cdll_N_ssssssss, 'None', 'InString', 'InString', - 'InString', 'InString', 'InString', 'InString', 'InString', 'InString') - + 'InString', 'InString', 'InString', 'InString', 'InString', 'InString') + cdll_o_l = calldll.newcall(lib.cdll_o_l, 'OSErr', 'InLong') cdll_N_pp = calldll.newcall(lib.cdll_N_pp, 'None', 'InPstring', 'OutPstring') @@ -30,103 +30,103 @@ cdll_N_sH = calldll.newcall(lib.cdll_N_sH, 'None', 'InString', 'InHandle') print 'Test cdll_b_bbbbbbbb' rv = cdll_b_bbbbbbbb(1, 2, 3, 4, 5, 6, 7, 8) if rv == 36: - print 'ok.' + print 'ok.' else: - print 'Failed, returned', rv - + print 'Failed, returned', rv + print 'Test cdll_b_bbbbbbbb negative' rv = cdll_b_bbbbbbbb(-1, -2, -3, -4, -5, -6, -7, -8) if rv == -36: - print 'ok.' + print 'ok.' else: - print 'Failed, returned', rv + print 'Failed, returned', rv print 'Test cdll_h_hhhhhhhh' rv = cdll_h_hhhhhhhh(1, 2, 3, 4, 5, 6, 7, 8) if rv == 36: - print 'ok.' + print 'ok.' else: - print 'Failed, returned', rv - + print 'Failed, returned', rv + print 'Test cdll_h_hhhhhhhh negative' rv = cdll_h_hhhhhhhh(-1, -2, -3, -4, -5, -6, -7, -8) if rv == -36: - print 'ok.' + print 'ok.' else: - print 'Failed, returned', rv + print 'Failed, returned', rv print 'Test cdll_l_llllllll' rv = cdll_l_llllllll(1, 2, 3, 4, 5, 6, 7, 8) if rv == 36: - print 'ok.' + print 'ok.' else: - print 'Failed, returned', rv - + print 'Failed, returned', rv + print 'Test cdll_l_llllllll negative' rv = cdll_l_llllllll(-1, -2, -3, -4, -5, -6, -7, -8) if rv == -36: - print 'ok.' + print 'ok.' else: - print 'Failed, returned', rv - + print 'Failed, returned', rv + print 'Test cdll_N_ssssssss' print 'Should print one two three four five six seven eight' rv = cdll_N_ssssssss('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight') if rv == None: - print 'ok.' + print 'ok.' else: - print 'Failed, returned', rv - + print 'Failed, returned', rv + print 'Test cdll_o_l(0)' rv = cdll_o_l(0) if rv == None: - print 'ok.' + print 'ok.' else: - print 'Error, returned', rv - + print 'Error, returned', rv + print 'Test cdll_o_l(-100)' try: - rv = cdll_o_l(-100) - print 'Error, did not raise exception, returned', rv + rv = cdll_o_l(-100) + print 'Error, did not raise exception, returned', rv except MacOS.Error, arg: - if arg[0] == -100: - print 'ok.' - else: - print 'Error, returned incorrect exception arg:', arg[0] - + if arg[0] == -100: + print 'ok.' + else: + print 'Error, returned incorrect exception arg:', arg[0] + print 'Test cdll_N_pp' rv = cdll_N_pp('pascal string') if rv == 'Was: pascal string': - print 'ok.' + print 'ok.' else: - print 'Failed, returned', repr(rv) - + print 'Failed, returned', repr(rv) + print 'Test cdll_N_bb' rv = cdll_N_bb(-100) if rv == -100: - print 'ok.' + print 'ok.' else: - print 'Failed, returned', rv - + print 'Failed, returned', rv + print 'Test cdll_N_hh' rv = cdll_N_hh(-100) if rv == -100: - print 'ok.' + print 'ok.' else: - print 'Failed, returned', rv - + print 'Failed, returned', rv + print 'Test cdll_N_ll' rv = cdll_N_ll(-100) if rv == -100: - print 'ok.' + print 'ok.' else: - print 'Failed, returned', rv + print 'Failed, returned', rv print 'Test cdll_N_sH' h = Res.Resource('xyz') rv = cdll_N_sH('new data', h) if rv == None and h.data == 'new data': - print 'ok.' + print 'ok.' else: - print 'Failed, rv is', rv, 'and handle data is', repr(rv.data) + print 'Failed, rv is', rv, 'and handle data is', repr(rv.data) sys.exit(1) diff --git a/Mac/Demo/example0/checktext.py b/Mac/Demo/example0/checktext.py index a5943a6..25f71e4 100644 --- a/Mac/Demo/example0/checktext.py +++ b/Mac/Demo/example0/checktext.py @@ -5,33 +5,31 @@ import EasyDialogs import string def main(): - pathname = EasyDialogs.AskFileForOpen(message='File to check end-of-lines in:') - if not pathname: - sys.exit(0) - fp = open(pathname, 'rb') - try: - data = fp.read() - except MemoryError: - EasyDialogs.Message('Sorry, file is too big.') - sys.exit(0) - if len(data) == 0: - EasyDialogs.Message('File is empty.') - sys.exit(0) - number_cr = string.count(data, '\r') - number_lf = string.count(data, '\n') - if number_cr == number_lf == 0: - EasyDialogs.Message('File contains no lines.') - if number_cr == 0: - EasyDialogs.Message('File has unix-style line endings') - elif number_lf == 0: - EasyDialogs.Message('File has mac-style line endings') - elif number_cr == number_lf: - EasyDialogs.Message('File probably has MSDOS-style line endings') - else: - EasyDialogs.Message('File has no recognizable line endings (binary file?)') - sys.exit(0) - + pathname = EasyDialogs.AskFileForOpen(message='File to check end-of-lines in:') + if not pathname: + sys.exit(0) + fp = open(pathname, 'rb') + try: + data = fp.read() + except MemoryError: + EasyDialogs.Message('Sorry, file is too big.') + sys.exit(0) + if len(data) == 0: + EasyDialogs.Message('File is empty.') + sys.exit(0) + number_cr = string.count(data, '\r') + number_lf = string.count(data, '\n') + if number_cr == number_lf == 0: + EasyDialogs.Message('File contains no lines.') + if number_cr == 0: + EasyDialogs.Message('File has unix-style line endings') + elif number_lf == 0: + EasyDialogs.Message('File has mac-style line endings') + elif number_cr == number_lf: + EasyDialogs.Message('File probably has MSDOS-style line endings') + else: + EasyDialogs.Message('File has no recognizable line endings (binary file?)') + sys.exit(0) + if __name__ == '__main__': - main() - - + main() diff --git a/Mac/Demo/example1/dnslookup-1.py b/Mac/Demo/example1/dnslookup-1.py index 2aa7c88..2fb8dc4 100644 --- a/Mac/Demo/example1/dnslookup-1.py +++ b/Mac/Demo/example1/dnslookup-1.py @@ -32,7 +32,7 @@ def do_dialog(): txt = Dlg.GetDialogItemText(h) tp, h, rect = my_dlg.GetDialogItem(ITEM_RESULT) - Dlg.SetDialogItemText(h, dnslookup(txt)) + Dlg.SetDialogItemText(h, dnslookup(txt)) elif n == ITEM_QUIT_BUTTON: break @@ -54,4 +54,3 @@ def dnslookup(str): return value main() - diff --git a/Mac/Demo/example2/dnslookup-2.py b/Mac/Demo/example2/dnslookup-2.py index 9747c4a..92cd181 100644 --- a/Mac/Demo/example2/dnslookup-2.py +++ b/Mac/Demo/example2/dnslookup-2.py @@ -18,10 +18,10 @@ ITEM_LOOKUP_BUTTON=3 def main(): macresource.need("DLOG", ID_MAIN, "dnslookup-2.rsrc") DNSLookup() - + class DNSLookup(FrameWork.Application): "Application class for DNS Lookup" - + def __init__(self): # First init menus, etc. FrameWork.Application.__init__(self) @@ -31,27 +31,27 @@ class DNSLookup(FrameWork.Application): self.main_dialog.open(ID_MAIN) # Finally, go into the event loop self.mainloop() - + def makeusermenus(self): self.filemenu = m = FrameWork.Menu(self.menubar, "File") self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) - + def quit(self, *args): self._quit() - + def do_about(self, *args): f = Dlg.GetNewDialog(ID_ABOUT, -1) while 1: n = Dlg.ModalDialog(None) if n == 1: return - + class MyDialog(FrameWork.DialogWindow): "Main dialog window for DNSLookup" def __init__(self, parent): FrameWork.DialogWindow.__init__(self, parent) self.parent = parent - + def do_itemhit(self, item, event): if item == ITEM_LOOKUP_BUTTON: self.dolookup() @@ -64,7 +64,7 @@ class MyDialog(FrameWork.DialogWindow): tp, h, rect = self.dlg.GetDialogItem(ITEM_RESULT) Dlg.SetDialogItemText(h, self.dnslookup(txt)) - + def dnslookup(self, str): """ Perform DNS lookup on str. If first character of digit is numeric, assume that str contains an IP address. Otherwise, assume that str diff --git a/Mac/Demo/imgbrowse/imgbrowse.py b/Mac/Demo/imgbrowse/imgbrowse.py index 262c650..28dffd3 100644 --- a/Mac/Demo/imgbrowse/imgbrowse.py +++ b/Mac/Demo/imgbrowse/imgbrowse.py @@ -25,93 +25,93 @@ MAXHEIGHT=320 def main(): - print 'hello world' - imgbrowse() + print 'hello world' + imgbrowse() class imgbrowse(FrameWork.Application): - def __init__(self): - # First init menus, etc. - FrameWork.Application.__init__(self) - self.lastwin = None - # Finally, go into the event loop - self.mainloop() - - def makeusermenus(self): - self.filemenu = m = FrameWork.Menu(self.menubar, "File") - self.openitem = FrameWork.MenuItem(m, "Open...", "O", self.opendoc) - self.infoitem = FrameWork.MenuItem(m, "Info", "I", self.info) - self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) - - def quit(self, *args): - self._quit() - - def opendoc(self, *args): - pathname = EasyDialogs.AskFileForOpen() # Any file type - if not pathname: - return - bar = EasyDialogs.ProgressBar('Reading and converting...') - try: - rdr = img.reader(imgformat.macrgb16, pathname) - except img.error, arg: - EasyDialogs.Message(repr(arg)) - return - w, h = rdr.width, rdr.height - bar.set(10) - data = rdr.read() - del bar - pixmap = mac_image.mkpixmap(w, h, imgformat.macrgb16, data) - self.showimg(w, h, pixmap, data) - - def showimg(self, w, h, pixmap, data): - win = imgwindow(self) - win.open(w, h, pixmap, data) - self.lastwin = win - - def info(self, *args): - if self.lastwin: - self.lastwin.info() - + def __init__(self): + # First init menus, etc. + FrameWork.Application.__init__(self) + self.lastwin = None + # Finally, go into the event loop + self.mainloop() + + def makeusermenus(self): + self.filemenu = m = FrameWork.Menu(self.menubar, "File") + self.openitem = FrameWork.MenuItem(m, "Open...", "O", self.opendoc) + self.infoitem = FrameWork.MenuItem(m, "Info", "I", self.info) + self.quititem = FrameWork.MenuItem(m, "Quit", "Q", self.quit) + + def quit(self, *args): + self._quit() + + def opendoc(self, *args): + pathname = EasyDialogs.AskFileForOpen() # Any file type + if not pathname: + return + bar = EasyDialogs.ProgressBar('Reading and converting...') + try: + rdr = img.reader(imgformat.macrgb16, pathname) + except img.error, arg: + EasyDialogs.Message(repr(arg)) + return + w, h = rdr.width, rdr.height + bar.set(10) + data = rdr.read() + del bar + pixmap = mac_image.mkpixmap(w, h, imgformat.macrgb16, data) + self.showimg(w, h, pixmap, data) + + def showimg(self, w, h, pixmap, data): + win = imgwindow(self) + win.open(w, h, pixmap, data) + self.lastwin = win + + def info(self, *args): + if self.lastwin: + self.lastwin.info() + class imgwindow(FrameWork.Window): - def open(self, width, height, pixmap, data): - self.pixmap = pixmap - self.data = data - self.pictrect = (0, 0, width, height) - bounds = (LEFT, TOP, LEFT+width, TOP+height) - - self.wid = Win.NewCWindow(bounds, "Picture", 1, 0, -1, 1, 0) - self.do_postopen() - - def do_update(self, *args): - pass - currect = self.fitrect() - print 'PICT:', self.pictrect - print 'WIND:', currect - print 'ARGS:', (self.pixmap, self.wid.GetWindowPort().GetPortBitMapForCopyBits(), self.pictrect, - currect, QuickDraw.srcCopy, None) - self.info() - Qd.CopyBits(self.pixmap, self.wid.GetWindowPort().GetPortBitMapForCopyBits(), self.pictrect, - currect, QuickDraw.srcCopy, None) - - def fitrect(self): - """Return self.pictrect scaled to fit in window""" - graf = self.wid.GetWindowPort() - screenrect = graf.GetPortBounds() - picwidth = self.pictrect[2] - self.pictrect[0] - picheight = self.pictrect[3] - self.pictrect[1] - if picwidth > screenrect[2] - screenrect[0]: - factor = float(picwidth) / float(screenrect[2]-screenrect[0]) - picwidth = picwidth / factor - picheight = picheight / factor - if picheight > screenrect[3] - screenrect[1]: - factor = float(picheight) / float(screenrect[3]-screenrect[1]) - picwidth = picwidth / factor - picheight = picheight / factor - return (screenrect[0], screenrect[1], screenrect[0]+int(picwidth), - screenrect[1]+int(picheight)) - - def info(self): - graf = self.wid.GetWindowPort() - bits = graf.GetPortBitMapForCopyBits() - mac_image.dumppixmap(bits.pixmap_data) + def open(self, width, height, pixmap, data): + self.pixmap = pixmap + self.data = data + self.pictrect = (0, 0, width, height) + bounds = (LEFT, TOP, LEFT+width, TOP+height) + + self.wid = Win.NewCWindow(bounds, "Picture", 1, 0, -1, 1, 0) + self.do_postopen() + + def do_update(self, *args): + pass + currect = self.fitrect() + print 'PICT:', self.pictrect + print 'WIND:', currect + print 'ARGS:', (self.pixmap, self.wid.GetWindowPort().GetPortBitMapForCopyBits(), self.pictrect, + currect, QuickDraw.srcCopy, None) + self.info() + Qd.CopyBits(self.pixmap, self.wid.GetWindowPort().GetPortBitMapForCopyBits(), self.pictrect, + currect, QuickDraw.srcCopy, None) + + def fitrect(self): + """Return self.pictrect scaled to fit in window""" + graf = self.wid.GetWindowPort() + screenrect = graf.GetPortBounds() + picwidth = self.pictrect[2] - self.pictrect[0] + picheight = self.pictrect[3] - self.pictrect[1] + if picwidth > screenrect[2] - screenrect[0]: + factor = float(picwidth) / float(screenrect[2]-screenrect[0]) + picwidth = picwidth / factor + picheight = picheight / factor + if picheight > screenrect[3] - screenrect[1]: + factor = float(picheight) / float(screenrect[3]-screenrect[1]) + picwidth = picwidth / factor + picheight = picheight / factor + return (screenrect[0], screenrect[1], screenrect[0]+int(picwidth), + screenrect[1]+int(picheight)) + + def info(self): + graf = self.wid.GetWindowPort() + bits = graf.GetPortBitMapForCopyBits() + mac_image.dumppixmap(bits.pixmap_data) main() diff --git a/Mac/Demo/imgbrowse/mac_image.py b/Mac/Demo/imgbrowse/mac_image.py index 094c58e..9c9eeb7 100644 --- a/Mac/Demo/imgbrowse/mac_image.py +++ b/Mac/Demo/imgbrowse/mac_image.py @@ -6,51 +6,51 @@ import struct import MacOS _fmt_to_mac = { - imgformat.macrgb16 : (16, 16, 3, 5), + imgformat.macrgb16 : (16, 16, 3, 5), } def mkpixmap(w, h, fmt, data): - """kludge a pixmap together""" - fmtinfo = _fmt_to_mac[fmt] - - rv = struct.pack("lHhhhhhhlllhhhhlll", - id(data)+MacOS.string_id_to_buffer, # HACK HACK!! - w*2 + 0x8000, - 0, 0, h, w, - 0, - 0, 0, # XXXX? - 72<<16, 72<<16, - fmtinfo[0], fmtinfo[1], - fmtinfo[2], fmtinfo[3], - 0, 0, 0) -## print 'Our pixmap, size %d:'%len(rv) -## dumppixmap(rv) - return Qd.RawBitMap(rv) + """kludge a pixmap together""" + fmtinfo = _fmt_to_mac[fmt] + + rv = struct.pack("lHhhhhhhlllhhhhlll", + id(data)+MacOS.string_id_to_buffer, # HACK HACK!! + w*2 + 0x8000, + 0, 0, h, w, + 0, + 0, 0, # XXXX? + 72<<16, 72<<16, + fmtinfo[0], fmtinfo[1], + fmtinfo[2], fmtinfo[3], + 0, 0, 0) +## print 'Our pixmap, size %d:'%len(rv) +## dumppixmap(rv) + return Qd.RawBitMap(rv) def dumppixmap(data): - baseAddr, \ - rowBytes, \ - t, l, b, r, \ - pmVersion, \ - packType, packSize, \ - hRes, vRes, \ - pixelType, pixelSize, \ - cmpCount, cmpSize, \ - planeBytes, pmTable, pmReserved \ - = struct.unpack("lhhhhhhhlllhhhhlll", data) - print 'Base: 0x%x'%baseAddr - print 'rowBytes: %d (0x%x)'%(rowBytes&0x3fff, rowBytes) - print 'rect: %d, %d, %d, %d'%(t, l, b, r) - print 'pmVersion: 0x%x'%pmVersion - print 'packing: %d %d'%(packType, packSize) - print 'resolution: %f x %f'%(float(hRes)/0x10000, float(vRes)/0x10000) - print 'pixeltype: %d, size %d'%(pixelType, pixelSize) - print 'components: %d, size %d'%(cmpCount, cmpSize) - print 'planeBytes: %d (0x%x)'%(planeBytes, planeBytes) - print 'pmTable: 0x%x'%pmTable - print 'pmReserved: 0x%x'%pmReserved - for i in range(0, len(data), 16): - for j in range(16): - if i + j < len(data): - print '%02.2x'%ord(data[i+j]), - print + baseAddr, \ + rowBytes, \ + t, l, b, r, \ + pmVersion, \ + packType, packSize, \ + hRes, vRes, \ + pixelType, pixelSize, \ + cmpCount, cmpSize, \ + planeBytes, pmTable, pmReserved \ + = struct.unpack("lhhhhhhhlllhhhhlll", data) + print 'Base: 0x%x'%baseAddr + print 'rowBytes: %d (0x%x)'%(rowBytes&0x3fff, rowBytes) + print 'rect: %d, %d, %d, %d'%(t, l, b, r) + print 'pmVersion: 0x%x'%pmVersion + print 'packing: %d %d'%(packType, packSize) + print 'resolution: %f x %f'%(float(hRes)/0x10000, float(vRes)/0x10000) + print 'pixeltype: %d, size %d'%(pixelType, pixelSize) + print 'components: %d, size %d'%(cmpCount, cmpSize) + print 'planeBytes: %d (0x%x)'%(planeBytes, planeBytes) + print 'pmTable: 0x%x'%pmTable + print 'pmReserved: 0x%x'%pmReserved + for i in range(0, len(data), 16): + for j in range(16): + if i + j < len(data): + print '%02.2x'%ord(data[i+j]), + print diff --git a/Mac/Demo/mlte/mlted.py b/Mac/Demo/mlte/mlted.py index 381345a..323ea62 100644 --- a/Mac/Demo/mlte/mlted.py +++ b/Mac/Demo/mlte/mlted.py @@ -15,361 +15,360 @@ from Carbon import MacTextEditor from Carbon import Mlte UNDOLABELS = [ # Indexed by MLTECanUndo() value - "Typing", "Cut", "Paste", "Clear", "Font Change", "Color Change", "Size Change", - "Style Change", "Align Left", "Align Center", "Align Right", "Drop", "Move"] - + "Typing", "Cut", "Paste", "Clear", "Font Change", "Color Change", "Size Change", + "Style Change", "Align Left", "Align Center", "Align Right", "Drop", "Move"] + class MlteWindow(Window): - def open(self, path, name, data): - self.path = path - self.name = name - r = windowbounds(400, 400) - w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) - self.wid = w - flags = MacTextEditor.kTXNDrawGrowIconMask|MacTextEditor.kTXNWantHScrollBarMask| \ - MacTextEditor.kTXNWantVScrollBarMask - self.ted, self.frameid = Mlte.TXNNewObject(None, w, None, flags, MacTextEditor.kTXNTextEditStyleFrameType, - MacTextEditor.kTXNTextFile, MacTextEditor.kTXNMacOSEncoding) - self.ted.TXNSetData(MacTextEditor.kTXNTextData, data, 0, 0x7fffffff) - self.changed = 0 - self.do_postopen() - self.do_activate(1, None) - - def do_idle(self, event): - self.ted.TXNIdle() - self.ted.TXNAdjustCursor(None) - - - - def do_activate(self, onoff, evt): - if onoff: -## self.ted.TXNActivate(self.frameid, 0) - self.ted.TXNFocus(1) - self.parent.active = self - else: - self.ted.TXNFocus(0) - self.parent.active = None - self.parent.updatemenubar() - - def do_update(self, wid, event): - self.ted.TXNDraw(None) - - def do_postresize(self, width, height, window): - self.ted.TXNResizeFrame(width, height, self.frameid) - - def do_contentclick(self, local, modifiers, evt): - self.ted.TXNClick(evt) - self.parent.updatemenubar() - - def do_char(self, ch, event): - self.ted.TXNKeyDown(event) - self.parent.updatemenubar() - - def close(self): - if self.changed: - save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?'%self.name, 1) - if save > 0: - self.menu_save() - elif save < 0: - return - if self.parent.active == self: - self.parent.active = None - self.ted.TXNDeleteObject() - del self.ted -## del self.tedtexthandle - self.do_postclose() - - def menu_save(self): - if not self.path: - self.menu_save_as() - return # Will call us recursively - dhandle = self.ted.TXNGetData(0, 0x7fffffff) - data = dhandle.data - fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line - fp.write(data) - if data[-1] <> '\r': fp.write('\r') - fp.close() - self.changed = 0 - - def menu_save_as(self): - path = EasyDialogs.AskFileForSave(message='Save as:') - if not path: return - self.path = path - self.name = os.path.split(self.path)[-1] - self.wid.SetWTitle(self.name) - self.menu_save() - - def menu_cut(self): -## self.ted.WESelView() - self.ted.TXNCut() -### Mlte.ConvertToPublicScrap() -## Scrap.ZeroScrap() -## self.ted.WECut() -## self.updatescrollbars() - self.parent.updatemenubar() - self.changed = 1 - - def menu_copy(self): -## Scrap.ZeroScrap() - self.ted.TXNCopy() -### Mlte.ConvertToPublicScrap() -## self.updatescrollbars() - self.parent.updatemenubar() - - def menu_paste(self): -### Mlte.ConvertFromPublicScrap() - self.ted.TXNPaste() -## self.updatescrollbars() - self.parent.updatemenubar() - self.changed = 1 - - def menu_clear(self): -## self.ted.WESelView() - self.ted.TXNClear() -## self.updatescrollbars() - self.parent.updatemenubar() - self.changed = 1 - - def menu_undo(self): - self.ted.TXNUndo() -## self.updatescrollbars() - self.parent.updatemenubar() - - def menu_redo(self): - self.ted.TXNRedo() -## self.updatescrollbars() - self.parent.updatemenubar() - - def have_selection(self): - start, stop = self.ted.TXNGetSelection() - return start < stop - - def can_paste(self): - return Mlte.TXNIsScrapPastable() - - def can_undo(self): - can, which = self.ted.TXNCanUndo() - if not can: - return None - if which >= len(UNDOLABELS): - # Unspecified undo - return "Undo" - which = UNDOLABELS[which] - - return "Undo "+which - - def can_redo(self): - can, which = self.ted.TXNCanRedo() - if not can: - return None - if which >= len(UNDOLABELS): - # Unspecified undo - return "Redo" - which = UNDOLABELS[which] - - return "Redo "+which + def open(self, path, name, data): + self.path = path + self.name = name + r = windowbounds(400, 400) + w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) + self.wid = w + flags = MacTextEditor.kTXNDrawGrowIconMask|MacTextEditor.kTXNWantHScrollBarMask| \ + MacTextEditor.kTXNWantVScrollBarMask + self.ted, self.frameid = Mlte.TXNNewObject(None, w, None, flags, MacTextEditor.kTXNTextEditStyleFrameType, + MacTextEditor.kTXNTextFile, MacTextEditor.kTXNMacOSEncoding) + self.ted.TXNSetData(MacTextEditor.kTXNTextData, data, 0, 0x7fffffff) + self.changed = 0 + self.do_postopen() + self.do_activate(1, None) + + def do_idle(self, event): + self.ted.TXNIdle() + self.ted.TXNAdjustCursor(None) + + + + def do_activate(self, onoff, evt): + if onoff: +## self.ted.TXNActivate(self.frameid, 0) + self.ted.TXNFocus(1) + self.parent.active = self + else: + self.ted.TXNFocus(0) + self.parent.active = None + self.parent.updatemenubar() + + def do_update(self, wid, event): + self.ted.TXNDraw(None) + + def do_postresize(self, width, height, window): + self.ted.TXNResizeFrame(width, height, self.frameid) + + def do_contentclick(self, local, modifiers, evt): + self.ted.TXNClick(evt) + self.parent.updatemenubar() + + def do_char(self, ch, event): + self.ted.TXNKeyDown(event) + self.parent.updatemenubar() + + def close(self): + if self.changed: + save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?'%self.name, 1) + if save > 0: + self.menu_save() + elif save < 0: + return + if self.parent.active == self: + self.parent.active = None + self.ted.TXNDeleteObject() + del self.ted +## del self.tedtexthandle + self.do_postclose() + + def menu_save(self): + if not self.path: + self.menu_save_as() + return # Will call us recursively + dhandle = self.ted.TXNGetData(0, 0x7fffffff) + data = dhandle.data + fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line + fp.write(data) + if data[-1] <> '\r': fp.write('\r') + fp.close() + self.changed = 0 + + def menu_save_as(self): + path = EasyDialogs.AskFileForSave(message='Save as:') + if not path: return + self.path = path + self.name = os.path.split(self.path)[-1] + self.wid.SetWTitle(self.name) + self.menu_save() + + def menu_cut(self): +## self.ted.WESelView() + self.ted.TXNCut() +### Mlte.ConvertToPublicScrap() +## Scrap.ZeroScrap() +## self.ted.WECut() +## self.updatescrollbars() + self.parent.updatemenubar() + self.changed = 1 + + def menu_copy(self): +## Scrap.ZeroScrap() + self.ted.TXNCopy() +### Mlte.ConvertToPublicScrap() +## self.updatescrollbars() + self.parent.updatemenubar() + + def menu_paste(self): +### Mlte.ConvertFromPublicScrap() + self.ted.TXNPaste() +## self.updatescrollbars() + self.parent.updatemenubar() + self.changed = 1 + + def menu_clear(self): +## self.ted.WESelView() + self.ted.TXNClear() +## self.updatescrollbars() + self.parent.updatemenubar() + self.changed = 1 + + def menu_undo(self): + self.ted.TXNUndo() +## self.updatescrollbars() + self.parent.updatemenubar() + + def menu_redo(self): + self.ted.TXNRedo() +## self.updatescrollbars() + self.parent.updatemenubar() + + def have_selection(self): + start, stop = self.ted.TXNGetSelection() + return start < stop + + def can_paste(self): + return Mlte.TXNIsScrapPastable() + + def can_undo(self): + can, which = self.ted.TXNCanUndo() + if not can: + return None + if which >= len(UNDOLABELS): + # Unspecified undo + return "Undo" + which = UNDOLABELS[which] + + return "Undo "+which + + def can_redo(self): + can, which = self.ted.TXNCanRedo() + if not can: + return None + if which >= len(UNDOLABELS): + # Unspecified undo + return "Redo" + which = UNDOLABELS[which] + + return "Redo "+which class Mlted(Application): - def __init__(self): - Application.__init__(self) - self.num = 0 - self.active = None - self.updatemenubar() - - def makeusermenus(self): - self.filemenu = m = Menu(self.menubar, "File") - self.newitem = MenuItem(m, "New window", "N", self.open) - self.openitem = MenuItem(m, "Open...", "O", self.openfile) - self.closeitem = MenuItem(m, "Close", "W", self.closewin) - m.addseparator() - self.saveitem = MenuItem(m, "Save", "S", self.save) - self.saveasitem = MenuItem(m, "Save as...", "", self.saveas) - m.addseparator() - self.quititem = MenuItem(m, "Quit", "Q", self.quit) - - self.editmenu = m = Menu(self.menubar, "Edit") - self.undoitem = MenuItem(m, "Undo", "Z", self.undo) - self.redoitem = MenuItem(m, "Redo", None, self.redo) - m.addseparator() - self.cutitem = MenuItem(m, "Cut", "X", self.cut) - self.copyitem = MenuItem(m, "Copy", "C", self.copy) - self.pasteitem = MenuItem(m, "Paste", "V", self.paste) - self.clearitem = MenuItem(m, "Clear", "", self.clear) - - # Groups of items enabled together: - self.windowgroup = [self.closeitem, self.saveitem, self.saveasitem, self.editmenu] - self.focusgroup = [self.cutitem, self.copyitem, self.clearitem] - self.windowgroup_on = -1 - self.focusgroup_on = -1 - self.pastegroup_on = -1 - self.undo_label = "never" - self.redo_label = "never" - - def updatemenubar(self): - changed = 0 - on = (self.active <> None) - if on <> self.windowgroup_on: - for m in self.windowgroup: - m.enable(on) - self.windowgroup_on = on - changed = 1 - if on: - # only if we have an edit menu - on = self.active.have_selection() - if on <> self.focusgroup_on: - for m in self.focusgroup: - m.enable(on) - self.focusgroup_on = on - changed = 1 - on = self.active.can_paste() - if on <> self.pastegroup_on: - self.pasteitem.enable(on) - self.pastegroup_on = on - changed = 1 - on = self.active.can_undo() - if on <> self.undo_label: - if on: - self.undoitem.enable(1) - self.undoitem.settext(on) - self.undo_label = on - else: - self.undoitem.settext("Nothing to undo") - self.undoitem.enable(0) - changed = 1 - on = self.active.can_redo() - if on <> self.redo_label: - if on: - self.redoitem.enable(1) - self.redoitem.settext(on) - self.redo_label = on - else: - self.redoitem.settext("Nothing to redo") - self.redoitem.enable(0) - changed = 1 - if changed: - DrawMenuBar() - - # - # Apple menu - # - - def do_about(self, id, item, window, event): - EasyDialogs.Message("A simple single-font text editor based on MacTextEditor") - - # - # File menu - # - - def open(self, *args): - self._open(0) - - def openfile(self, *args): - self._open(1) - - def _open(self, askfile): - if askfile: - path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) - if not path: - return - name = os.path.split(path)[-1] - try: - fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line - data = fp.read() - fp.close() - except IOError, arg: - EasyDialogs.Message("IOERROR: %r" % (arg,)) - return - else: - path = None - name = "Untitled %d"%self.num - data = '' - w = MlteWindow(self) - w.open(path, name, data) - self.num = self.num + 1 - - def closewin(self, *args): - if self.active: - self.active.close() - else: - EasyDialogs.Message("No active window?") - - def save(self, *args): - if self.active: - self.active.menu_save() - else: - EasyDialogs.Message("No active window?") - - def saveas(self, *args): - if self.active: - self.active.menu_save_as() - else: - EasyDialogs.Message("No active window?") - - - def quit(self, *args): - for w in self._windows.values(): - w.close() - if self._windows: - return - self._quit() - - # - # Edit menu - # - - def undo(self, *args): - if self.active: - self.active.menu_undo() - else: - EasyDialogs.Message("No active window?") - - def redo(self, *args): - if self.active: - self.active.menu_redo() - else: - EasyDialogs.Message("No active window?") - - def cut(self, *args): - if self.active: - self.active.menu_cut() - else: - EasyDialogs.Message("No active window?") - - def copy(self, *args): - if self.active: - self.active.menu_copy() - else: - EasyDialogs.Message("No active window?") - - def paste(self, *args): - if self.active: - self.active.menu_paste() - else: - EasyDialogs.Message("No active window?") - - def clear(self, *args): - if self.active: - self.active.menu_clear() - else: - EasyDialogs.Message("No active window?") - - # - # Other stuff - # - - def idle(self, event): - if self.active: - self.active.do_idle(event) - else: - Qd.SetCursor(Qd.GetQDGlobalsArrow()) + def __init__(self): + Application.__init__(self) + self.num = 0 + self.active = None + self.updatemenubar() + + def makeusermenus(self): + self.filemenu = m = Menu(self.menubar, "File") + self.newitem = MenuItem(m, "New window", "N", self.open) + self.openitem = MenuItem(m, "Open...", "O", self.openfile) + self.closeitem = MenuItem(m, "Close", "W", self.closewin) + m.addseparator() + self.saveitem = MenuItem(m, "Save", "S", self.save) + self.saveasitem = MenuItem(m, "Save as...", "", self.saveas) + m.addseparator() + self.quititem = MenuItem(m, "Quit", "Q", self.quit) + + self.editmenu = m = Menu(self.menubar, "Edit") + self.undoitem = MenuItem(m, "Undo", "Z", self.undo) + self.redoitem = MenuItem(m, "Redo", None, self.redo) + m.addseparator() + self.cutitem = MenuItem(m, "Cut", "X", self.cut) + self.copyitem = MenuItem(m, "Copy", "C", self.copy) + self.pasteitem = MenuItem(m, "Paste", "V", self.paste) + self.clearitem = MenuItem(m, "Clear", "", self.clear) + + # Groups of items enabled together: + self.windowgroup = [self.closeitem, self.saveitem, self.saveasitem, self.editmenu] + self.focusgroup = [self.cutitem, self.copyitem, self.clearitem] + self.windowgroup_on = -1 + self.focusgroup_on = -1 + self.pastegroup_on = -1 + self.undo_label = "never" + self.redo_label = "never" + + def updatemenubar(self): + changed = 0 + on = (self.active <> None) + if on <> self.windowgroup_on: + for m in self.windowgroup: + m.enable(on) + self.windowgroup_on = on + changed = 1 + if on: + # only if we have an edit menu + on = self.active.have_selection() + if on <> self.focusgroup_on: + for m in self.focusgroup: + m.enable(on) + self.focusgroup_on = on + changed = 1 + on = self.active.can_paste() + if on <> self.pastegroup_on: + self.pasteitem.enable(on) + self.pastegroup_on = on + changed = 1 + on = self.active.can_undo() + if on <> self.undo_label: + if on: + self.undoitem.enable(1) + self.undoitem.settext(on) + self.undo_label = on + else: + self.undoitem.settext("Nothing to undo") + self.undoitem.enable(0) + changed = 1 + on = self.active.can_redo() + if on <> self.redo_label: + if on: + self.redoitem.enable(1) + self.redoitem.settext(on) + self.redo_label = on + else: + self.redoitem.settext("Nothing to redo") + self.redoitem.enable(0) + changed = 1 + if changed: + DrawMenuBar() + + # + # Apple menu + # + + def do_about(self, id, item, window, event): + EasyDialogs.Message("A simple single-font text editor based on MacTextEditor") + + # + # File menu + # + + def open(self, *args): + self._open(0) + + def openfile(self, *args): + self._open(1) + + def _open(self, askfile): + if askfile: + path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) + if not path: + return + name = os.path.split(path)[-1] + try: + fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line + data = fp.read() + fp.close() + except IOError, arg: + EasyDialogs.Message("IOERROR: %r" % (arg,)) + return + else: + path = None + name = "Untitled %d"%self.num + data = '' + w = MlteWindow(self) + w.open(path, name, data) + self.num = self.num + 1 + + def closewin(self, *args): + if self.active: + self.active.close() + else: + EasyDialogs.Message("No active window?") + + def save(self, *args): + if self.active: + self.active.menu_save() + else: + EasyDialogs.Message("No active window?") + + def saveas(self, *args): + if self.active: + self.active.menu_save_as() + else: + EasyDialogs.Message("No active window?") + + + def quit(self, *args): + for w in self._windows.values(): + w.close() + if self._windows: + return + self._quit() + + # + # Edit menu + # + + def undo(self, *args): + if self.active: + self.active.menu_undo() + else: + EasyDialogs.Message("No active window?") + + def redo(self, *args): + if self.active: + self.active.menu_redo() + else: + EasyDialogs.Message("No active window?") + + def cut(self, *args): + if self.active: + self.active.menu_cut() + else: + EasyDialogs.Message("No active window?") + + def copy(self, *args): + if self.active: + self.active.menu_copy() + else: + EasyDialogs.Message("No active window?") + + def paste(self, *args): + if self.active: + self.active.menu_paste() + else: + EasyDialogs.Message("No active window?") + + def clear(self, *args): + if self.active: + self.active.menu_clear() + else: + EasyDialogs.Message("No active window?") + + # + # Other stuff + # + + def idle(self, event): + if self.active: + self.active.do_idle(event) + else: + Qd.SetCursor(Qd.GetQDGlobalsArrow()) def main(): - Mlte.TXNInitTextension(0) - try: - App = Mlted() - App.mainloop() - finally: - Mlte.TXNTerminateTextension() - + Mlte.TXNInitTextension(0) + try: + App = Mlted() + App.mainloop() + finally: + Mlte.TXNTerminateTextension() + if __name__ == '__main__': - main() - + main() diff --git a/Mac/Demo/quicktime/MovieInWindow.py b/Mac/Demo/quicktime/MovieInWindow.py index ec4beae..00f596e 100644 --- a/Mac/Demo/quicktime/MovieInWindow.py +++ b/Mac/Demo/quicktime/MovieInWindow.py @@ -18,54 +18,53 @@ import os def main(): - # skip the toolbox initializations, already done - # XXXX Should use gestalt here to check for quicktime version - Qt.EnterMovies() - - # Get the movie file - if len(sys.argv) > 1: - filename = sys.argv[1] - else: - filename = EasyDialogs.AskFileForOpen() # Was: QuickTime.MovieFileType - if not filename: - sys.exit(0) - - # Open the window - bounds = (175, 75, 175+160, 75+120) - theWindow = Win.NewCWindow(bounds, os.path.split(filename)[1], 1, 0, -1, 0, 0) - Qd.SetPort(theWindow) - # XXXX Needed? SetGWorld((CGrafPtr)theWindow, nil) - - playMovieInWindow(theWindow, filename, theWindow.GetWindowPort().GetPortBounds()) - + # skip the toolbox initializations, already done + # XXXX Should use gestalt here to check for quicktime version + Qt.EnterMovies() + + # Get the movie file + if len(sys.argv) > 1: + filename = sys.argv[1] + else: + filename = EasyDialogs.AskFileForOpen() # Was: QuickTime.MovieFileType + if not filename: + sys.exit(0) + + # Open the window + bounds = (175, 75, 175+160, 75+120) + theWindow = Win.NewCWindow(bounds, os.path.split(filename)[1], 1, 0, -1, 0, 0) + Qd.SetPort(theWindow) + # XXXX Needed? SetGWorld((CGrafPtr)theWindow, nil) + + playMovieInWindow(theWindow, filename, theWindow.GetWindowPort().GetPortBounds()) + def playMovieInWindow(theWindow, theFile, movieBox): - """Play a movie in a window""" - # XXXX Needed? SetGWorld((CGrafPtr)theWindow, nil); - - # Get the movie - theMovie = loadMovie(theFile) - - # Set where we want it - theMovie.SetMovieBox(movieBox) - - # Start at the beginning - theMovie.GoToBeginningOfMovie() - - # Give a little time to preroll - theMovie.MoviesTask(0) - - # Start playing - theMovie.StartMovie() - - while not theMovie.IsMovieDone() and not Evt.Button(): - theMovie.MoviesTask(0) - + """Play a movie in a window""" + # XXXX Needed? SetGWorld((CGrafPtr)theWindow, nil); + + # Get the movie + theMovie = loadMovie(theFile) + + # Set where we want it + theMovie.SetMovieBox(movieBox) + + # Start at the beginning + theMovie.GoToBeginningOfMovie() + + # Give a little time to preroll + theMovie.MoviesTask(0) + + # Start playing + theMovie.StartMovie() + + while not theMovie.IsMovieDone() and not Evt.Button(): + theMovie.MoviesTask(0) + def loadMovie(theFile): - """Load a movie given an fsspec. Return the movie object""" - movieResRef = Qt.OpenMovieFile(theFile, 1) - movie, d1, d2 = Qt.NewMovieFromFile(movieResRef, 0, QuickTime.newMovieActive) - return movie - + """Load a movie given an fsspec. Return the movie object""" + movieResRef = Qt.OpenMovieFile(theFile, 1) + movie, d1, d2 = Qt.NewMovieFromFile(movieResRef, 0, QuickTime.newMovieActive) + return movie + if __name__ == '__main__': - main() - + main() diff --git a/Mac/Demo/quicktime/VerySimplePlayer.py b/Mac/Demo/quicktime/VerySimplePlayer.py index de64e3f..2930eac 100644 --- a/Mac/Demo/quicktime/VerySimplePlayer.py +++ b/Mac/Demo/quicktime/VerySimplePlayer.py @@ -18,76 +18,75 @@ import sys # XXXX maxbounds = (40, 40, 1000, 1000) def main(): - print 'hello world' # XXXX - # skip the toolbox initializations, already done - # XXXX Should use gestalt here to check for quicktime version - Qt.EnterMovies() - - # Get the movie file - fss = EasyDialogs.AskFileForOpen(wanted=File.FSSpec) # Was: QuickTime.MovieFileType - if not fss: - sys.exit(0) - - # Open the window - bounds = (175, 75, 175+160, 75+120) - theWindow = Win.NewCWindow(bounds, fss.as_tuple()[2], 0, 0, -1, 1, 0) - # XXXX Needed? SetGWorld((CGrafPtr)theWindow, nil) - Qd.SetPort(theWindow) - - # Get the movie - theMovie = loadMovie(fss) - - # Relocate to (0, 0) - bounds = theMovie.GetMovieBox() - bounds = 0, 0, bounds[2]-bounds[0], bounds[3]-bounds[1] - theMovie.SetMovieBox(bounds) - - # Create a controller - theController = theMovie.NewMovieController(bounds, QuickTime.mcTopLeftMovie) - - # Get movie size and update window parameters - rv, bounds = theController.MCGetControllerBoundsRect() - theWindow.SizeWindow(bounds[2], bounds[3], 0) # XXXX or [3] [2]? - Qt.AlignWindow(theWindow, 0) - theWindow.ShowWindow() - - # XXXX MCDoAction(theController, mcActionSetGrowBoxBounds, &maxBounds) - theController.MCDoAction(QuickTime.mcActionSetKeysEnabled, '1') - - # XXXX MCSetActionFilterWithRefCon(theController, movieControllerEventFilter, (long)theWindow) - - done = 0 - while not done: - gotone, evt = Evt.WaitNextEvent(0xffff, 0) - (what, message, when, where, modifiers) = evt -## print what, message, when, where, modifiers # XXXX - - if theController.MCIsPlayerEvent(evt): - continue - - if what == Events.mouseDown: - part, whichWindow = Win.FindWindow(where) - if part == Windows.inGoAway: - done = whichWindow.TrackGoAway(where) - elif part == Windows.inDrag: - Qt.DragAlignedWindow(whichWindow, where, (0, 0, 4000, 4000)) - elif what == Events.updateEvt: - whichWindow = Win.WhichWindow(message) - if not whichWindow: - # Probably the console window. Print something, hope it helps. - print 'update' - else: - Qd.SetPort(whichWindow) - whichWindow.BeginUpdate() - Qd.EraseRect(whichWindow.GetWindowPort().GetPortBounds()) - whichWindow.EndUpdate() - + print 'hello world' # XXXX + # skip the toolbox initializations, already done + # XXXX Should use gestalt here to check for quicktime version + Qt.EnterMovies() + + # Get the movie file + fss = EasyDialogs.AskFileForOpen(wanted=File.FSSpec) # Was: QuickTime.MovieFileType + if not fss: + sys.exit(0) + + # Open the window + bounds = (175, 75, 175+160, 75+120) + theWindow = Win.NewCWindow(bounds, fss.as_tuple()[2], 0, 0, -1, 1, 0) + # XXXX Needed? SetGWorld((CGrafPtr)theWindow, nil) + Qd.SetPort(theWindow) + + # Get the movie + theMovie = loadMovie(fss) + + # Relocate to (0, 0) + bounds = theMovie.GetMovieBox() + bounds = 0, 0, bounds[2]-bounds[0], bounds[3]-bounds[1] + theMovie.SetMovieBox(bounds) + + # Create a controller + theController = theMovie.NewMovieController(bounds, QuickTime.mcTopLeftMovie) + + # Get movie size and update window parameters + rv, bounds = theController.MCGetControllerBoundsRect() + theWindow.SizeWindow(bounds[2], bounds[3], 0) # XXXX or [3] [2]? + Qt.AlignWindow(theWindow, 0) + theWindow.ShowWindow() + + # XXXX MCDoAction(theController, mcActionSetGrowBoxBounds, &maxBounds) + theController.MCDoAction(QuickTime.mcActionSetKeysEnabled, '1') + + # XXXX MCSetActionFilterWithRefCon(theController, movieControllerEventFilter, (long)theWindow) + + done = 0 + while not done: + gotone, evt = Evt.WaitNextEvent(0xffff, 0) + (what, message, when, where, modifiers) = evt +## print what, message, when, where, modifiers # XXXX + + if theController.MCIsPlayerEvent(evt): + continue + + if what == Events.mouseDown: + part, whichWindow = Win.FindWindow(where) + if part == Windows.inGoAway: + done = whichWindow.TrackGoAway(where) + elif part == Windows.inDrag: + Qt.DragAlignedWindow(whichWindow, where, (0, 0, 4000, 4000)) + elif what == Events.updateEvt: + whichWindow = Win.WhichWindow(message) + if not whichWindow: + # Probably the console window. Print something, hope it helps. + print 'update' + else: + Qd.SetPort(whichWindow) + whichWindow.BeginUpdate() + Qd.EraseRect(whichWindow.GetWindowPort().GetPortBounds()) + whichWindow.EndUpdate() + def loadMovie(theFile): - """Load a movie given an fsspec. Return the movie object""" - movieResRef = Qt.OpenMovieFile(theFile, 1) - movie, d1, d2 = Qt.NewMovieFromFile(movieResRef, 0, QuickTime.newMovieActive) - return movie - + """Load a movie given an fsspec. Return the movie object""" + movieResRef = Qt.OpenMovieFile(theFile, 1) + movie, d1, d2 = Qt.NewMovieFromFile(movieResRef, 0, QuickTime.newMovieActive) + return movie + if __name__ == '__main__': - main() - + main() diff --git a/Mac/Demo/resources/copyres.py b/Mac/Demo/resources/copyres.py index ae627ef..528ff16 100644 --- a/Mac/Demo/resources/copyres.py +++ b/Mac/Demo/resources/copyres.py @@ -7,51 +7,51 @@ WRITE = 2 smAllScripts = -3 def copyres(src, dst): - """Copy resource from src file to dst file.""" - - cur = CurResFile() - ctor, type = MacOS.GetCreatorAndType(src) - input = FSpOpenResFile(src, READ) - try: - FSpCreateResFile(dst, ctor, type, smAllScripts) - except: - raw_input("%s already exists... CR to write anyway! " % dst) - output = FSpOpenResFile(dst, WRITE) - UseResFile(input) - ntypes = Count1Types() - for itype in range(1, 1+ntypes): - type = Get1IndType(itype) - nresources = Count1Resources(type) - for ires in range(1, 1+nresources): - res = Get1IndResource(type, ires) - res.LoadResource() - id, type, name = res.GetResInfo() - size = res.SizeResource() - attrs = res.GetResAttrs() - print id, type, name, size, hex(attrs) - res.DetachResource() - UseResFile(output) - try: - res2 = Get1Resource(type, id) - except (RuntimeError, Res.Error), msg: - res2 = None - if res2: - print "Duplicate type+id, not copied" - print (res2.size, res2.data) - print res2.GetResInfo() - if res2.HomeResFile() == output: - 'OK' - elif res2.HomeResFile() == input: - 'BAD!' - else: - print 'Home:', res2.HomeResFile() - else: - res.AddResource(type, id, name) - #res.SetResAttrs(attrs) - res.WriteResource() - UseResFile(input) - UseResFile(cur) - CloseResFile(output) - CloseResFile(input) + """Copy resource from src file to dst file.""" + + cur = CurResFile() + ctor, type = MacOS.GetCreatorAndType(src) + input = FSpOpenResFile(src, READ) + try: + FSpCreateResFile(dst, ctor, type, smAllScripts) + except: + raw_input("%s already exists... CR to write anyway! " % dst) + output = FSpOpenResFile(dst, WRITE) + UseResFile(input) + ntypes = Count1Types() + for itype in range(1, 1+ntypes): + type = Get1IndType(itype) + nresources = Count1Resources(type) + for ires in range(1, 1+nresources): + res = Get1IndResource(type, ires) + res.LoadResource() + id, type, name = res.GetResInfo() + size = res.SizeResource() + attrs = res.GetResAttrs() + print id, type, name, size, hex(attrs) + res.DetachResource() + UseResFile(output) + try: + res2 = Get1Resource(type, id) + except (RuntimeError, Res.Error), msg: + res2 = None + if res2: + print "Duplicate type+id, not copied" + print (res2.size, res2.data) + print res2.GetResInfo() + if res2.HomeResFile() == output: + 'OK' + elif res2.HomeResFile() == input: + 'BAD!' + else: + print 'Home:', res2.HomeResFile() + else: + res.AddResource(type, id, name) + #res.SetResAttrs(attrs) + res.WriteResource() + UseResFile(input) + UseResFile(cur) + CloseResFile(output) + CloseResFile(input) copyres('::python.¹.rsrc', '::foo.rsrc') diff --git a/Mac/Demo/resources/listres.py b/Mac/Demo/resources/listres.py index eacf2b7..6ce5779 100644 --- a/Mac/Demo/resources/listres.py +++ b/Mac/Demo/resources/listres.py @@ -4,57 +4,57 @@ from Carbon import Res from Carbon.Resources import * def list1resources(): - ntypes = Res.Count1Types() - for itype in range(1, 1+ntypes): - type = Res.Get1IndType(itype) - print "Type:", repr(type) - nresources = Res.Count1Resources(type) - for i in range(1, 1 + nresources): - Res.SetResLoad(0) - res = Res.Get1IndResource(type, i) - Res.SetResLoad(1) - info(res) + ntypes = Res.Count1Types() + for itype in range(1, 1+ntypes): + type = Res.Get1IndType(itype) + print "Type:", repr(type) + nresources = Res.Count1Resources(type) + for i in range(1, 1 + nresources): + Res.SetResLoad(0) + res = Res.Get1IndResource(type, i) + Res.SetResLoad(1) + info(res) def listresources(): - ntypes = Res.CountTypes() - for itype in range(1, 1+ntypes): - type = Res.GetIndType(itype) - print "Type:", repr(type) - nresources = Res.CountResources(type) - for i in range(1, 1 + nresources): - Res.SetResLoad(0) - res = Res.GetIndResource(type, i) - Res.SetResLoad(1) - info(res) + ntypes = Res.CountTypes() + for itype in range(1, 1+ntypes): + type = Res.GetIndType(itype) + print "Type:", repr(type) + nresources = Res.CountResources(type) + for i in range(1, 1 + nresources): + Res.SetResLoad(0) + res = Res.GetIndResource(type, i) + Res.SetResLoad(1) + info(res) def info(res): - print res.GetResInfo(), res.SizeResource(), decodeattrs(res.GetResAttrs()) + print res.GetResInfo(), res.SizeResource(), decodeattrs(res.GetResAttrs()) attrnames = { - resChanged: 'Changed', - resPreload: 'Preload', - resProtected: 'Protected', - resLocked: 'Locked', - resPurgeable: 'Purgeable', - resSysHeap: 'SysHeap', + resChanged: 'Changed', + resPreload: 'Preload', + resProtected: 'Protected', + resLocked: 'Locked', + resPurgeable: 'Purgeable', + resSysHeap: 'SysHeap', } def decodeattrs(attrs): - names = [] - for bit in range(16): - mask = 1<<bit - if attrs & mask: - if attrnames.has_key(mask): - names.append(attrnames[mask]) - else: - names.append(hex(mask)) - return names + names = [] + for bit in range(16): + mask = 1<<bit + if attrs & mask: + if attrnames.has_key(mask): + names.append(attrnames[mask]) + else: + names.append(hex(mask)) + return names def test(): - print "=== Local resourcess ===" - list1resources() - print "=== All resources ===" - listresources() + print "=== Local resourcess ===" + list1resources() + print "=== All resources ===" + listresources() if __name__ == '__main__': - test() + test() diff --git a/Mac/Demo/sound/morse.py b/Mac/Demo/sound/morse.py index bf5fa5f..b26d554 100644 --- a/Mac/Demo/sound/morse.py +++ b/Mac/Demo/sound/morse.py @@ -2,61 +2,61 @@ import sys, math, audiodev DOT = 30 DAH = 80 -OCTAVE = 2 # 1 == 441 Hz, 2 == 882 Hz, ... +OCTAVE = 2 # 1 == 441 Hz, 2 == 882 Hz, ... SAMPWIDTH = 2 FRAMERATE = 44100 BASEFREQ = 441 QSIZE = 20000 morsetab = { - 'A': '.-', 'a': '.-', - 'B': '-...', 'b': '-...', - 'C': '-.-.', 'c': '-.-.', - 'D': '-..', 'd': '-..', - 'E': '.', 'e': '.', - 'F': '..-.', 'f': '..-.', - 'G': '--.', 'g': '--.', - 'H': '....', 'h': '....', - 'I': '..', 'i': '..', - 'J': '.---', 'j': '.---', - 'K': '-.-', 'k': '-.-', - 'L': '.-..', 'l': '.-..', - 'M': '--', 'm': '--', - 'N': '-.', 'n': '-.', - 'O': '---', 'o': '---', - 'P': '.--.', 'p': '.--.', - 'Q': '--.-', 'q': '--.-', - 'R': '.-.', 'r': '.-.', - 'S': '...', 's': '...', - 'T': '-', 't': '-', - 'U': '..-', 'u': '..-', - 'V': '...-', 'v': '...-', - 'W': '.--', 'w': '.--', - 'X': '-..-', 'x': '-..-', - 'Y': '-.--', 'y': '-.--', - 'Z': '--..', 'z': '--..', - '0': '-----', - '1': '.----', - '2': '..---', - '3': '...--', - '4': '....-', - '5': '.....', - '6': '-....', - '7': '--...', - '8': '---..', - '9': '----.', - ',': '--..--', - '.': '.-.-.-', - '?': '..--..', - ';': '-.-.-.', - ':': '---...', - "'": '.----.', - '-': '-....-', - '/': '-..-.', - '(': '-.--.-', - ')': '-.--.-', - '_': '..--.-', - ' ': ' ' + 'A': '.-', 'a': '.-', + 'B': '-...', 'b': '-...', + 'C': '-.-.', 'c': '-.-.', + 'D': '-..', 'd': '-..', + 'E': '.', 'e': '.', + 'F': '..-.', 'f': '..-.', + 'G': '--.', 'g': '--.', + 'H': '....', 'h': '....', + 'I': '..', 'i': '..', + 'J': '.---', 'j': '.---', + 'K': '-.-', 'k': '-.-', + 'L': '.-..', 'l': '.-..', + 'M': '--', 'm': '--', + 'N': '-.', 'n': '-.', + 'O': '---', 'o': '---', + 'P': '.--.', 'p': '.--.', + 'Q': '--.-', 'q': '--.-', + 'R': '.-.', 'r': '.-.', + 'S': '...', 's': '...', + 'T': '-', 't': '-', + 'U': '..-', 'u': '..-', + 'V': '...-', 'v': '...-', + 'W': '.--', 'w': '.--', + 'X': '-..-', 'x': '-..-', + 'Y': '-.--', 'y': '-.--', + 'Z': '--..', 'z': '--..', + '0': '-----', + '1': '.----', + '2': '..---', + '3': '...--', + '4': '....-', + '5': '.....', + '6': '-....', + '7': '--...', + '8': '---..', + '9': '----.', + ',': '--..--', + '.': '.-.-.-', + '?': '..--..', + ';': '-.-.-.', + ':': '---...', + "'": '.----.', + '-': '-....-', + '/': '-..-.', + '(': '-.--.-', + ')': '-.--.-', + '_': '..--.-', + ' ': ' ' } # If we play at 44.1 kHz (which we do), then if we produce one sine @@ -64,117 +64,117 @@ morsetab = { # sine waves in these 100 samples, we get a tone of 882 Hz. 882 Hz # appears to be a nice one for playing morse code. def mkwave(octave): - global sinewave, nowave - sinewave = '' - n = int(FRAMERATE / BASEFREQ) - for i in range(n): - val = int(math.sin(2 * math.pi * i * octave / n) * 0x7fff) - sample = chr((val >> 8) & 255) + chr(val & 255) - sinewave = sinewave + sample[:SAMPWIDTH] - nowave = '\0' * (n*SAMPWIDTH) + global sinewave, nowave + sinewave = '' + n = int(FRAMERATE / BASEFREQ) + for i in range(n): + val = int(math.sin(2 * math.pi * i * octave / n) * 0x7fff) + sample = chr((val >> 8) & 255) + chr(val & 255) + sinewave = sinewave + sample[:SAMPWIDTH] + nowave = '\0' * (n*SAMPWIDTH) mkwave(OCTAVE) class BufferedAudioDev: - def __init__(self, *args): - import audiodev - self._base = apply(audiodev.AudioDev, args) - self._buffer = [] - self._filled = 0 - self._addmethods(self._base, self._base.__class__) - def _addmethods(self, inst, cls): - for name in cls.__dict__.keys(): - if not hasattr(self, name): - try: - setattr(self, name, getattr(inst, name)) - except: - pass - for basecls in cls.__bases__: - self._addmethods(self, inst, basecls) - def writeframesraw(self, frames): - self._buffer.append(frames) - self._filled = self._filled + len(frames) - if self._filled >= QSIZE: - self.flush() - def wait(self): - self.flush() - self._base.wait() - def flush(self): - print 'flush: %d blocks, %d bytes' % (len(self._buffer), self._filled) - if self._buffer: - import string - self._base.writeframes(string.joinfields(self._buffer, '')) - self._buffer = [] - self._filled = 0 + def __init__(self, *args): + import audiodev + self._base = apply(audiodev.AudioDev, args) + self._buffer = [] + self._filled = 0 + self._addmethods(self._base, self._base.__class__) + def _addmethods(self, inst, cls): + for name in cls.__dict__.keys(): + if not hasattr(self, name): + try: + setattr(self, name, getattr(inst, name)) + except: + pass + for basecls in cls.__bases__: + self._addmethods(self, inst, basecls) + def writeframesraw(self, frames): + self._buffer.append(frames) + self._filled = self._filled + len(frames) + if self._filled >= QSIZE: + self.flush() + def wait(self): + self.flush() + self._base.wait() + def flush(self): + print 'flush: %d blocks, %d bytes' % (len(self._buffer), self._filled) + if self._buffer: + import string + self._base.writeframes(string.joinfields(self._buffer, '')) + self._buffer = [] + self._filled = 0 def main(args = sys.argv[1:]): - import getopt, string - try: - opts, args = getopt.getopt(args, 'o:p:') - except getopt.error: - sys.stderr.write('Usage ' + sys.argv[0] + - ' [ -o outfile ] [ args ] ...\n') - sys.exit(1) - dev = None - for o, a in opts: - if o == '-o': - import aifc - dev = aifc.open(a, 'w') - dev.setframerate(FRAMERATE) - dev.setsampwidth(SAMPWIDTH) - dev.setnchannels(1) - if o == '-p': - mkwave(string.atoi(a)) - if not dev: - dev = BufferedAudioDev() - dev.setoutrate(FRAMERATE) - dev.setsampwidth(SAMPWIDTH) - dev.setnchannels(1) - dev.close = dev.stop - if args: - line = string.join(args) - else: - line = sys.stdin.readline() - while line: - print line - mline = morse(line) - print mline - play(mline, dev) - if hasattr(dev, 'wait'): - dev.wait() - if not args: - line = sys.stdin.readline() - else: - line = '' - dev.close() + import getopt, string + try: + opts, args = getopt.getopt(args, 'o:p:') + except getopt.error: + sys.stderr.write('Usage ' + sys.argv[0] + + ' [ -o outfile ] [ args ] ...\n') + sys.exit(1) + dev = None + for o, a in opts: + if o == '-o': + import aifc + dev = aifc.open(a, 'w') + dev.setframerate(FRAMERATE) + dev.setsampwidth(SAMPWIDTH) + dev.setnchannels(1) + if o == '-p': + mkwave(string.atoi(a)) + if not dev: + dev = BufferedAudioDev() + dev.setoutrate(FRAMERATE) + dev.setsampwidth(SAMPWIDTH) + dev.setnchannels(1) + dev.close = dev.stop + if args: + line = string.join(args) + else: + line = sys.stdin.readline() + while line: + print line + mline = morse(line) + print mline + play(mline, dev) + if hasattr(dev, 'wait'): + dev.wait() + if not args: + line = sys.stdin.readline() + else: + line = '' + dev.close() # Convert a string to morse code with \001 between the characters in # the string. def morse(line): - res = '' - for c in line: - try: - res = res + morsetab[c] + '\001' - except KeyError: - pass - return res + res = '' + for c in line: + try: + res = res + morsetab[c] + '\001' + except KeyError: + pass + return res # Play a line of morse code. def play(line, dev): - for c in line: - if c == '.': - sine(dev, DOT) - elif c == '-': - sine(dev, DAH) - else: - pause(dev, DAH) - pause(dev, DOT) + for c in line: + if c == '.': + sine(dev, DOT) + elif c == '-': + sine(dev, DAH) + else: + pause(dev, DAH) + pause(dev, DOT) def sine(dev, length): - dev.writeframesraw(sinewave*length) + dev.writeframesraw(sinewave*length) def pause(dev, length): - dev.writeframesraw(nowave*length) + dev.writeframesraw(nowave*length) if __name__ == '__main__' or sys.argv[0] == __name__: - main() + main() diff --git a/Mac/Demo/sound/morselib.py b/Mac/Demo/sound/morselib.py index 6f8eed6..98e2590 100644 --- a/Mac/Demo/sound/morselib.py +++ b/Mac/Demo/sound/morselib.py @@ -10,179 +10,179 @@ DOT = 30 DAH = 80 morsetab = { - 'a': '.-', - 'b': '-...', - 'c': '-.-.', - 'd': '-..', - 'e': '.', - 'f': '..-.', - 'g': '--.', - 'h': '....', - 'i': '..', - 'j': '.---', - 'k': '-.-', - 'l': '.-..', - 'm': '--', - 'n': '-.', - 'o': '---', - 'p': '.--.', - 'q': '--.-', - 'r': '.-.', - 's': '...', - 't': '-', - 'u': '..-', - 'v': '...-', - 'w': '.--', - 'x': '-..-', - 'y': '-.--', - 'z': '--..', - '0': '-----', - '1': '.----', - '2': '..---', - '3': '...--', - '4': '....-', - '5': '.....', - '6': '-....', - '7': '--...', - '8': '---..', - '9': '----.', - ',': '--..--', - '.': '.-.-.-', - '?': '..--..', - ';': '-.-.-.', - ':': '---...', - "'": '.----.', - '-': '-....-', - '/': '-..-.', - '(': '-.--.-', - ')': '-.--.-', # XXX same as code for '(' ??? - '_': '..--.-', - ' ': ' ' + 'a': '.-', + 'b': '-...', + 'c': '-.-.', + 'd': '-..', + 'e': '.', + 'f': '..-.', + 'g': '--.', + 'h': '....', + 'i': '..', + 'j': '.---', + 'k': '-.-', + 'l': '.-..', + 'm': '--', + 'n': '-.', + 'o': '---', + 'p': '.--.', + 'q': '--.-', + 'r': '.-.', + 's': '...', + 't': '-', + 'u': '..-', + 'v': '...-', + 'w': '.--', + 'x': '-..-', + 'y': '-.--', + 'z': '--..', + '0': '-----', + '1': '.----', + '2': '..---', + '3': '...--', + '4': '....-', + '5': '.....', + '6': '-....', + '7': '--...', + '8': '---..', + '9': '----.', + ',': '--..--', + '.': '.-.-.-', + '?': '..--..', + ';': '-.-.-.', + ':': '---...', + "'": '.----.', + '-': '-....-', + '/': '-..-.', + '(': '-.--.-', + ')': '-.--.-', # XXX same as code for '(' ??? + '_': '..--.-', + ' ': ' ' } def morsecode(s): - from string import lower - m = '' - for c in s: - c = lower(c) - if morsetab.has_key(c): - c = morsetab[c] + ' ' - else: - c = '? ' - m = m + c - return m + from string import lower + m = '' + for c in s: + c = lower(c) + if morsetab.has_key(c): + c = morsetab[c] + ' ' + else: + c = '? ' + m = m + c + return m class BaseMorse: - "base class for morse transmissions" - - def __init__(self): - "constructor" - self.dots = DOT - self.dahs = DAH - - def noise(self, duration): - "beep for given duration" - pass - - def pause(self, duration): - "pause for given duration" - pass - - def dot(self): - "short beep" - self.noise(self.dots) - - def dah(self): - "long beep" - self.noise(self.dahs) - - def pdot(self): - "pause as long as a dot" - self.pause(self.dots) - - def pdah(self): - "pause as long as a dah" - self.pause(self.dahs) - - def sendmorse(self, s): - for c in s: - if c == '.': self.dot() - elif c == '-': self.dah() - else: self.pdah() - self.pdot() - - def sendascii(self, s): - self.sendmorse(morsecode(s)) - - def send(self, s): - self.sendascii(s) + "base class for morse transmissions" + + def __init__(self): + "constructor" + self.dots = DOT + self.dahs = DAH + + def noise(self, duration): + "beep for given duration" + pass + + def pause(self, duration): + "pause for given duration" + pass + + def dot(self): + "short beep" + self.noise(self.dots) + + def dah(self): + "long beep" + self.noise(self.dahs) + + def pdot(self): + "pause as long as a dot" + self.pause(self.dots) + + def pdah(self): + "pause as long as a dah" + self.pause(self.dahs) + + def sendmorse(self, s): + for c in s: + if c == '.': self.dot() + elif c == '-': self.dah() + else: self.pdah() + self.pdot() + + def sendascii(self, s): + self.sendmorse(morsecode(s)) + + def send(self, s): + self.sendascii(s) import Audio_mac class MyAudio(Audio_mac.Play_Audio_mac): - def _callback(self, *args): - if hasattr(self, 'usercallback'): self.usercallback() - apply(Audio_mac.Play_Audio_mac._callback, (self,) + args) + def _callback(self, *args): + if hasattr(self, 'usercallback'): self.usercallback() + apply(Audio_mac.Play_Audio_mac._callback, (self,) + args) class MacMorse(BaseMorse): - "Mac specific class to play Morse code" - - def __init__(self): - BaseMorse.__init__(self) - self.dev = MyAudio() - self.dev.setoutrate(FRAMERATE) - self.dev.setsampwidth(SAMPWIDTH) - self.dev.setnchannels(1) - self.dev.usercallback = self.usercallback - sinewave = '' - n = int(FRAMERATE / BASEFREQ) - octave = OCTAVE - from math import sin, pi - for i in range(n): - val = int(sin(2 * pi * i * octave / n) * 0x7fff) - sample = chr((val >> 8) & 255) + chr(val & 255) - sinewave = sinewave + sample[:SAMPWIDTH] - self.sinewave = sinewave - self.silence = '\0' * (n*SAMPWIDTH) - self.morsequeue = '' - - def __del__(self): - self.close() - - def close(self): - self.dev = None - - def pause(self, duration): - self.dev.writeframes(self.silence * duration) - - def noise(self, duration): - self.dev.writeframes(self.sinewave * duration) - - def sendmorse(self, s): - self.morsequeue = self.morsequeue + s - self.dev.usercallback() - self.dev.usercallback() - self.dev.usercallback() - - def usercallback(self): - if self.morsequeue: - c, self.morsequeue = self.morsequeue[0], self.morsequeue[1:] - if c == '.': self.dot() - elif c == '-': self.dah() - else: self.pdah() - self.pdot() + "Mac specific class to play Morse code" + + def __init__(self): + BaseMorse.__init__(self) + self.dev = MyAudio() + self.dev.setoutrate(FRAMERATE) + self.dev.setsampwidth(SAMPWIDTH) + self.dev.setnchannels(1) + self.dev.usercallback = self.usercallback + sinewave = '' + n = int(FRAMERATE / BASEFREQ) + octave = OCTAVE + from math import sin, pi + for i in range(n): + val = int(sin(2 * pi * i * octave / n) * 0x7fff) + sample = chr((val >> 8) & 255) + chr(val & 255) + sinewave = sinewave + sample[:SAMPWIDTH] + self.sinewave = sinewave + self.silence = '\0' * (n*SAMPWIDTH) + self.morsequeue = '' + + def __del__(self): + self.close() + + def close(self): + self.dev = None + + def pause(self, duration): + self.dev.writeframes(self.silence * duration) + + def noise(self, duration): + self.dev.writeframes(self.sinewave * duration) + + def sendmorse(self, s): + self.morsequeue = self.morsequeue + s + self.dev.usercallback() + self.dev.usercallback() + self.dev.usercallback() + + def usercallback(self): + if self.morsequeue: + c, self.morsequeue = self.morsequeue[0], self.morsequeue[1:] + if c == '.': self.dot() + elif c == '-': self.dah() + else: self.pdah() + self.pdot() def test(): - m = MacMorse() - while 1: - try: - line = raw_input('Morse line: ') - except (EOFError, KeyboardInterrupt): - break - m.send(line) - while m.morsequeue: pass + m = MacMorse() + while 1: + try: + line = raw_input('Morse line: ') + except (EOFError, KeyboardInterrupt): + break + m.send(line) + while m.morsequeue: pass test() diff --git a/Mac/Demo/textedit/ped.py b/Mac/Demo/textedit/ped.py index eee848b..3e91b32 100644 --- a/Mac/Demo/textedit/ped.py +++ b/Mac/Demo/textedit/ped.py @@ -15,346 +15,345 @@ import os import macfs class TEWindow(ScrolledWindow): - def open(self, path, name, data): - self.path = path - self.name = name - r = windowbounds(400, 400) - w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) - self.wid = w - x0, y0, x1, y1 = self.wid.GetWindowPort().GetPortBounds() - x0 = x0 + 4 - y0 = y0 + 4 - x1 = x1 - 20 - y1 = y1 - 20 - vr = dr = x0, y0, x1, y1 - ##vr = 4, 0, r[2]-r[0]-15, r[3]-r[1]-15 - ##dr = (0, 0, vr[2], 0) - Qd.SetPort(w) - Qd.TextFont(4) - Qd.TextSize(9) - self.ted = TE.TENew(dr, vr) - self.ted.TEAutoView(1) - self.ted.TESetText(data) - w.DrawGrowIcon() - self.scrollbars() - self.changed = 0 - self.do_postopen() - self.do_activate(1, None) - - def do_idle(self): - self.ted.TEIdle() - - def getscrollbarvalues(self): - dr = self.ted.destRect - vr = self.ted.viewRect - height = self.ted.nLines * self.ted.lineHeight - vx = self.scalebarvalue(dr[0], dr[2]-dr[0], vr[0], vr[2]) - vy = self.scalebarvalue(dr[1], dr[1]+height, vr[1], vr[3]) - print dr, vr, height, vx, vy - return None, vy - - def scrollbar_callback(self, which, what, value): - if which == 'y': - if what == 'set': - height = self.ted.nLines * self.ted.lineHeight - cur = self.getscrollbarvalues()[1] - delta = (cur-value)*height/32767 - if what == '-': - delta = self.ted.lineHeight - elif what == '--': - delta = (self.ted.viewRect[3]-self.ted.lineHeight) - if delta <= 0: - delta = self.ted.lineHeight - elif what == '+': - delta = -self.ted.lineHeight - elif what == '++': - delta = -(self.ted.viewRect[3]-self.ted.lineHeight) - if delta >= 0: - delta = -self.ted.lineHeight - self.ted.TEPinScroll(0, delta) - print 'SCROLL Y', delta - else: - pass # No horizontal scrolling - - def do_activate(self, onoff, evt): - print "ACTIVATE", onoff - ScrolledWindow.do_activate(self, onoff, evt) - if onoff: - self.ted.TEActivate() - self.parent.active = self - self.parent.updatemenubar() - else: - self.ted.TEDeactivate() - - def do_update(self, wid, event): - Qd.EraseRect(wid.GetWindowPort().GetPortBounds()) - self.ted.TEUpdate(wid.GetWindowPort().GetPortBounds()) - self.updatescrollbars() - - def do_contentclick(self, local, modifiers, evt): - shifted = (modifiers & 0x200) - self.ted.TEClick(local, shifted) - self.updatescrollbars() - self.parent.updatemenubar() - - def do_char(self, ch, event): - self.ted.TESelView() - self.ted.TEKey(ord(ch)) - self.changed = 1 - self.updatescrollbars() - self.parent.updatemenubar() - - def close(self): - if self.changed: - save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?'%self.name, 1) - if save > 0: - self.menu_save() - elif save < 0: - return - if self.parent.active == self: - self.parent.active = None - self.parent.updatemenubar() - del self.ted - self.do_postclose() - - def menu_save(self): - if not self.path: - self.menu_save_as() - return # Will call us recursively - print 'Saving to ', self.path - dhandle = self.ted.TEGetText() - data = dhandle.data - fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line - fp.write(data) - if data[-1] <> '\r': fp.write('\r') - fp.close() - self.changed = 0 - - def menu_save_as(self): - path = EasyDialogs.AskFileForSave(message='Save as:') - if not path: return - self.path = path - self.name = os.path.split(self.path)[-1] - self.wid.SetWTitle(self.name) - self.menu_save() - - def menu_cut(self): - self.ted.TESelView() - self.ted.TECut() - if hasattr(Scrap, 'ZeroScrap'): - Scrap.ZeroScrap() - else: - Scrap.ClearCurrentScrap() - TE.TEToScrap() - self.updatescrollbars() - self.parent.updatemenubar() - self.changed = 1 - - def menu_copy(self): - self.ted.TECopy() - if hasattr(Scrap, 'ZeroScrap'): - Scrap.ZeroScrap() - else: - Scrap.ClearCurrentScrap() - TE.TEToScrap() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_paste(self): - TE.TEFromScrap() - self.ted.TESelView() - self.ted.TEPaste() - self.updatescrollbars() - self.parent.updatemenubar() - self.changed = 1 - - def menu_clear(self): - self.ted.TESelView() - self.ted.TEDelete() - self.updatescrollbars() - self.parent.updatemenubar() - self.changed = 1 - - def have_selection(self): - return (self.ted.selStart < self.ted.selEnd) + def open(self, path, name, data): + self.path = path + self.name = name + r = windowbounds(400, 400) + w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) + self.wid = w + x0, y0, x1, y1 = self.wid.GetWindowPort().GetPortBounds() + x0 = x0 + 4 + y0 = y0 + 4 + x1 = x1 - 20 + y1 = y1 - 20 + vr = dr = x0, y0, x1, y1 + ##vr = 4, 0, r[2]-r[0]-15, r[3]-r[1]-15 + ##dr = (0, 0, vr[2], 0) + Qd.SetPort(w) + Qd.TextFont(4) + Qd.TextSize(9) + self.ted = TE.TENew(dr, vr) + self.ted.TEAutoView(1) + self.ted.TESetText(data) + w.DrawGrowIcon() + self.scrollbars() + self.changed = 0 + self.do_postopen() + self.do_activate(1, None) + + def do_idle(self): + self.ted.TEIdle() + + def getscrollbarvalues(self): + dr = self.ted.destRect + vr = self.ted.viewRect + height = self.ted.nLines * self.ted.lineHeight + vx = self.scalebarvalue(dr[0], dr[2]-dr[0], vr[0], vr[2]) + vy = self.scalebarvalue(dr[1], dr[1]+height, vr[1], vr[3]) + print dr, vr, height, vx, vy + return None, vy + + def scrollbar_callback(self, which, what, value): + if which == 'y': + if what == 'set': + height = self.ted.nLines * self.ted.lineHeight + cur = self.getscrollbarvalues()[1] + delta = (cur-value)*height/32767 + if what == '-': + delta = self.ted.lineHeight + elif what == '--': + delta = (self.ted.viewRect[3]-self.ted.lineHeight) + if delta <= 0: + delta = self.ted.lineHeight + elif what == '+': + delta = -self.ted.lineHeight + elif what == '++': + delta = -(self.ted.viewRect[3]-self.ted.lineHeight) + if delta >= 0: + delta = -self.ted.lineHeight + self.ted.TEPinScroll(0, delta) + print 'SCROLL Y', delta + else: + pass # No horizontal scrolling + + def do_activate(self, onoff, evt): + print "ACTIVATE", onoff + ScrolledWindow.do_activate(self, onoff, evt) + if onoff: + self.ted.TEActivate() + self.parent.active = self + self.parent.updatemenubar() + else: + self.ted.TEDeactivate() + + def do_update(self, wid, event): + Qd.EraseRect(wid.GetWindowPort().GetPortBounds()) + self.ted.TEUpdate(wid.GetWindowPort().GetPortBounds()) + self.updatescrollbars() + + def do_contentclick(self, local, modifiers, evt): + shifted = (modifiers & 0x200) + self.ted.TEClick(local, shifted) + self.updatescrollbars() + self.parent.updatemenubar() + + def do_char(self, ch, event): + self.ted.TESelView() + self.ted.TEKey(ord(ch)) + self.changed = 1 + self.updatescrollbars() + self.parent.updatemenubar() + + def close(self): + if self.changed: + save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?'%self.name, 1) + if save > 0: + self.menu_save() + elif save < 0: + return + if self.parent.active == self: + self.parent.active = None + self.parent.updatemenubar() + del self.ted + self.do_postclose() + + def menu_save(self): + if not self.path: + self.menu_save_as() + return # Will call us recursively + print 'Saving to ', self.path + dhandle = self.ted.TEGetText() + data = dhandle.data + fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line + fp.write(data) + if data[-1] <> '\r': fp.write('\r') + fp.close() + self.changed = 0 + + def menu_save_as(self): + path = EasyDialogs.AskFileForSave(message='Save as:') + if not path: return + self.path = path + self.name = os.path.split(self.path)[-1] + self.wid.SetWTitle(self.name) + self.menu_save() + + def menu_cut(self): + self.ted.TESelView() + self.ted.TECut() + if hasattr(Scrap, 'ZeroScrap'): + Scrap.ZeroScrap() + else: + Scrap.ClearCurrentScrap() + TE.TEToScrap() + self.updatescrollbars() + self.parent.updatemenubar() + self.changed = 1 + + def menu_copy(self): + self.ted.TECopy() + if hasattr(Scrap, 'ZeroScrap'): + Scrap.ZeroScrap() + else: + Scrap.ClearCurrentScrap() + TE.TEToScrap() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_paste(self): + TE.TEFromScrap() + self.ted.TESelView() + self.ted.TEPaste() + self.updatescrollbars() + self.parent.updatemenubar() + self.changed = 1 + + def menu_clear(self): + self.ted.TESelView() + self.ted.TEDelete() + self.updatescrollbars() + self.parent.updatemenubar() + self.changed = 1 + + def have_selection(self): + return (self.ted.selStart < self.ted.selEnd) class Ped(Application): - def __init__(self): - Application.__init__(self) - self.num = 0 - self.active = None - self.updatemenubar() - - def makeusermenus(self): - self.filemenu = m = Menu(self.menubar, "File") - self.newitem = MenuItem(m, "New window", "N", self.open) - self.openitem = MenuItem(m, "Open...", "O", self.openfile) - self.closeitem = MenuItem(m, "Close", "W", self.closewin) - m.addseparator() - self.saveitem = MenuItem(m, "Save", "S", self.save) - self.saveasitem = MenuItem(m, "Save as...", "", self.saveas) - m.addseparator() - self.quititem = MenuItem(m, "Quit", "Q", self.quit) - - self.editmenu = m = Menu(self.menubar, "Edit") - self.undoitem = MenuItem(m, "Undo", "Z", self.undo) - self.cutitem = MenuItem(m, "Cut", "X", self.cut) - self.copyitem = MenuItem(m, "Copy", "C", self.copy) - self.pasteitem = MenuItem(m, "Paste", "V", self.paste) - self.clearitem = MenuItem(m, "Clear", "", self.clear) - - # Not yet implemented: - self.undoitem.enable(0) - - # Groups of items enabled together: - self.windowgroup = [self.closeitem, self.saveitem, self.saveasitem, self.editmenu] - self.focusgroup = [self.cutitem, self.copyitem, self.clearitem] - self.windowgroup_on = -1 - self.focusgroup_on = -1 - self.pastegroup_on = -1 - - def updatemenubar(self): - changed = 0 - on = (self.active <> None) - if on <> self.windowgroup_on: - for m in self.windowgroup: - m.enable(on) - self.windowgroup_on = on - changed = 1 - if on: - # only if we have an edit menu - on = self.active.have_selection() - if on <> self.focusgroup_on: - for m in self.focusgroup: - m.enable(on) - self.focusgroup_on = on - changed = 1 - if hasattr(Scrap, 'InfoScrap'): - on = (Scrap.InfoScrap()[0] <> 0) - else: - flavors = Scrap.GetCurrentScrap().GetScrapFlavorInfoList() - for tp, info in flavors: - if tp == 'TEXT': - on = 1 - break - else: - on = 0 - if on <> self.pastegroup_on: - self.pasteitem.enable(on) - self.pastegroup_on = on - changed = 1 - if changed: - DrawMenuBar() - - # - # Apple menu - # - - def do_about(self, id, item, window, event): - EasyDialogs.Message("A simple single-font text editor") - - # - # File menu - # - - def open(self, *args): - self._open(0) - - def openfile(self, *args): - self._open(1) - - def _open(self, askfile): - if askfile: - path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) - if not path: - return - name = os.path.split(path)[-1] - try: - fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line - data = fp.read() - fp.close() - except IOError, arg: - EasyDialogs.Message("IOERROR: %r" % (arg,)) - return - else: - path = None - name = "Untitled %d"%self.num - data = '' - w = TEWindow(self) - w.open(path, name, data) - self.num = self.num + 1 - - def closewin(self, *args): - if self.active: - self.active.close() - else: - EasyDialogs.Message("No active window?") - - def save(self, *args): - if self.active: - self.active.menu_save() - else: - EasyDialogs.Message("No active window?") - - def saveas(self, *args): - if self.active: - self.active.menu_save_as() - else: - EasyDialogs.Message("No active window?") - - - def quit(self, *args): - for w in self._windows.values(): - w.close() - if self._windows: - return - self._quit() - - # - # Edit menu - # - - def undo(self, *args): - pass - - def cut(self, *args): - if self.active: - self.active.menu_cut() - else: - EasyDialogs.Message("No active window?") - - def copy(self, *args): - if self.active: - self.active.menu_copy() - else: - EasyDialogs.Message("No active window?") - - def paste(self, *args): - if self.active: - self.active.menu_paste() - else: - EasyDialogs.Message("No active window?") - - def clear(self, *args): - if self.active: - self.active.menu_clear() - else: - EasyDialogs.Message("No active window?") - - # - # Other stuff - # - - def idle(self, *args): - if self.active: - self.active.do_idle() - else: - Qd.SetCursor(Qd.GetQDGlobalsArrow()) + def __init__(self): + Application.__init__(self) + self.num = 0 + self.active = None + self.updatemenubar() + + def makeusermenus(self): + self.filemenu = m = Menu(self.menubar, "File") + self.newitem = MenuItem(m, "New window", "N", self.open) + self.openitem = MenuItem(m, "Open...", "O", self.openfile) + self.closeitem = MenuItem(m, "Close", "W", self.closewin) + m.addseparator() + self.saveitem = MenuItem(m, "Save", "S", self.save) + self.saveasitem = MenuItem(m, "Save as...", "", self.saveas) + m.addseparator() + self.quititem = MenuItem(m, "Quit", "Q", self.quit) + + self.editmenu = m = Menu(self.menubar, "Edit") + self.undoitem = MenuItem(m, "Undo", "Z", self.undo) + self.cutitem = MenuItem(m, "Cut", "X", self.cut) + self.copyitem = MenuItem(m, "Copy", "C", self.copy) + self.pasteitem = MenuItem(m, "Paste", "V", self.paste) + self.clearitem = MenuItem(m, "Clear", "", self.clear) + + # Not yet implemented: + self.undoitem.enable(0) + + # Groups of items enabled together: + self.windowgroup = [self.closeitem, self.saveitem, self.saveasitem, self.editmenu] + self.focusgroup = [self.cutitem, self.copyitem, self.clearitem] + self.windowgroup_on = -1 + self.focusgroup_on = -1 + self.pastegroup_on = -1 + + def updatemenubar(self): + changed = 0 + on = (self.active <> None) + if on <> self.windowgroup_on: + for m in self.windowgroup: + m.enable(on) + self.windowgroup_on = on + changed = 1 + if on: + # only if we have an edit menu + on = self.active.have_selection() + if on <> self.focusgroup_on: + for m in self.focusgroup: + m.enable(on) + self.focusgroup_on = on + changed = 1 + if hasattr(Scrap, 'InfoScrap'): + on = (Scrap.InfoScrap()[0] <> 0) + else: + flavors = Scrap.GetCurrentScrap().GetScrapFlavorInfoList() + for tp, info in flavors: + if tp == 'TEXT': + on = 1 + break + else: + on = 0 + if on <> self.pastegroup_on: + self.pasteitem.enable(on) + self.pastegroup_on = on + changed = 1 + if changed: + DrawMenuBar() + + # + # Apple menu + # + + def do_about(self, id, item, window, event): + EasyDialogs.Message("A simple single-font text editor") + + # + # File menu + # + + def open(self, *args): + self._open(0) + + def openfile(self, *args): + self._open(1) + + def _open(self, askfile): + if askfile: + path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) + if not path: + return + name = os.path.split(path)[-1] + try: + fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line + data = fp.read() + fp.close() + except IOError, arg: + EasyDialogs.Message("IOERROR: %r" % (arg,)) + return + else: + path = None + name = "Untitled %d"%self.num + data = '' + w = TEWindow(self) + w.open(path, name, data) + self.num = self.num + 1 + + def closewin(self, *args): + if self.active: + self.active.close() + else: + EasyDialogs.Message("No active window?") + + def save(self, *args): + if self.active: + self.active.menu_save() + else: + EasyDialogs.Message("No active window?") + + def saveas(self, *args): + if self.active: + self.active.menu_save_as() + else: + EasyDialogs.Message("No active window?") + + + def quit(self, *args): + for w in self._windows.values(): + w.close() + if self._windows: + return + self._quit() + + # + # Edit menu + # + + def undo(self, *args): + pass + + def cut(self, *args): + if self.active: + self.active.menu_cut() + else: + EasyDialogs.Message("No active window?") + + def copy(self, *args): + if self.active: + self.active.menu_copy() + else: + EasyDialogs.Message("No active window?") + + def paste(self, *args): + if self.active: + self.active.menu_paste() + else: + EasyDialogs.Message("No active window?") + + def clear(self, *args): + if self.active: + self.active.menu_clear() + else: + EasyDialogs.Message("No active window?") + + # + # Other stuff + # + + def idle(self, *args): + if self.active: + self.active.do_idle() + else: + Qd.SetCursor(Qd.GetQDGlobalsArrow()) def main(): - App = Ped() - App.mainloop() - + App = Ped() + App.mainloop() + if __name__ == '__main__': - main() - + main() diff --git a/Mac/Demo/waste/htmled.py b/Mac/Demo/waste/htmled.py index 8710766..d8cea1b 100644 --- a/Mac/Demo/waste/htmled.py +++ b/Mac/Demo/waste/htmled.py @@ -23,809 +23,808 @@ WATCH = Qd.GetCursor(4).data LEFTMARGIN=0 UNDOLABELS = [ # Indexed by WEGetUndoInfo() value - None, "", "typing", "Cut", "Paste", "Clear", "Drag", "Style"] - + None, "", "typing", "Cut", "Paste", "Clear", "Drag", "Style"] + # Style and size menu. Note that style order is important (tied to bit values) STYLES = [ - ("Bold", "B"), ("Italic", "I"), ("Underline", "U"), ("Outline", "O"), - ("Shadow", ""), ("Condensed", ""), ("Extended", "") - ] + ("Bold", "B"), ("Italic", "I"), ("Underline", "U"), ("Outline", "O"), + ("Shadow", ""), ("Condensed", ""), ("Extended", "") + ] SIZES = [ 9, 10, 12, 14, 18, 24] # Sizes for HTML tag types HTML_SIZE={ - 'h1': 18, - 'h2': 14 + 'h1': 18, + 'h2': 14 } - + BIGREGION=Qd.NewRgn() Qd.SetRectRgn(BIGREGION, -16000, -16000, 16000, 16000) class WasteWindow(ScrolledWindow): - def open(self, path, name, data): - self.path = path - self.name = name - r = windowbounds(400, 400) - w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) - self.wid = w - vr = LEFTMARGIN, 0, r[2]-r[0]-15, r[3]-r[1]-15 - dr = (0, 0, vr[2], 0) - Qd.SetPort(w) - Qd.TextFont(4) - Qd.TextSize(9) - flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoOutlineHilite | \ - WASTEconst.weDoMonoStyled | WASTEconst.weDoUndo - self.ted = waste.WENew(dr, vr, flags) - self.ted.WEInstallTabHooks() - style, soup = self.getstylesoup(self.path) - self.ted.WEInsert(data, style, soup) - self.ted.WESetSelection(0,0) - self.ted.WECalText() - self.ted.WEResetModCount() - w.DrawGrowIcon() - self.scrollbars() - self.do_postopen() - self.do_activate(1, None) - - def getstylesoup(self, pathname): - if not pathname: - return None, None - oldrf = Res.CurResFile() - try: - rf = Res.FSpOpenResFile(self.path, 1) - except Res.Error: - return None, None - try: - hstyle = Res.Get1Resource('styl', 128) - hstyle.DetachResource() - except Res.Error: - hstyle = None - try: - hsoup = Res.Get1Resource('SOUP', 128) - hsoup.DetachResource() - except Res.Error: - hsoup = None - Res.CloseResFile(rf) - Res.UseResFile(oldrf) - return hstyle, hsoup - - def do_idle(self, event): - (what, message, when, where, modifiers) = event - Qd.SetPort(self.wid) - self.ted.WEIdle() - if self.ted.WEAdjustCursor(where, BIGREGION): - return - Qd.SetCursor(Qd.GetQDGlobalsArrow()) - - def getscrollbarvalues(self): - dr = self.ted.WEGetDestRect() - vr = self.ted.WEGetViewRect() - vx = self.scalebarvalue(dr[0], dr[2], vr[0], vr[2]) - vy = self.scalebarvalue(dr[1], dr[3], vr[1], vr[3]) - return vx, vy - - def scrollbar_callback(self, which, what, value): - if which == 'y': - # - # "line" size is minimum of top and bottom line size - # - topline_off,dummy = self.ted.WEGetOffset((1,1)) - topline_num = self.ted.WEOffsetToLine(topline_off) - toplineheight = self.ted.WEGetHeight(topline_num, topline_num+1) - - botlinepos = self.ted.WEGetViewRect()[3] - botline_off, dummy = self.ted.WEGetOffset((1, botlinepos-1)) - botline_num = self.ted.WEOffsetToLine(botline_off) - botlineheight = self.ted.WEGetHeight(botline_num, botline_num+1) - - if botlineheight == 0: - botlineheight = self.ted.WEGetHeight(botline_num-1, botline_num) - if botlineheight < toplineheight: - lineheight = botlineheight - else: - lineheight = toplineheight - if lineheight <= 0: - lineheight = 1 - # - # Now do the command. - # - if what == 'set': - height = self.ted.WEGetHeight(0, 0x3fffffff) - cur = self.getscrollbarvalues()[1] - delta = (cur-value)*height/32767 - if what == '-': - delta = lineheight - elif what == '--': - delta = (self.ted.WEGetViewRect()[3]-lineheight) - if delta <= 0: - delta = lineheight - elif what == '+': - delta = -lineheight - elif what == '++': - delta = -(self.ted.WEGetViewRect()[3]-lineheight) - if delta >= 0: - delta = -lineheight - self.ted.WEScroll(0, delta) - else: - if what == 'set': - return # XXXX - vr = self.ted.WEGetViewRect() - winwidth = vr[2]-vr[0] - if what == '-': - delta = winwidth/10 - elif what == '--': - delta = winwidth/2 - elif what == '+': - delta = -winwidth/10 - elif what == '++': - delta = -winwidth/2 - self.ted.WEScroll(delta, 0) - # Pin the scroll - l, t, r, b = self.ted.WEGetDestRect() - vl, vt, vr, vb = self.ted.WEGetViewRect() - if t > 0 or l > 0: - dx = dy = 0 - if t > 0: dy = -t - if l > 0: dx = -l - self.ted.WEScroll(dx, dy) - elif b < vb: - self.ted.WEScroll(0, vb-b) - - - def do_activate(self, onoff, evt): - Qd.SetPort(self.wid) - ScrolledWindow.do_activate(self, onoff, evt) - if onoff: - self.ted.WEActivate() - self.parent.active = self - self.parent.updatemenubar() - else: - self.ted.WEDeactivate() - - def do_update(self, wid, event): - region = wid.GetWindowPort().visRgn - if Qd.EmptyRgn(region): - return - Qd.EraseRgn(region) - self.ted.WEUpdate(region) - self.updatescrollbars() - - def do_postresize(self, width, height, window): - l, t, r, b = self.ted.WEGetViewRect() - vr = (l, t, l+width-15, t+height-15) - self.ted.WESetViewRect(vr) - self.wid.InvalWindowRect(vr) - ScrolledWindow.do_postresize(self, width, height, window) - - def do_contentclick(self, local, modifiers, evt): - (what, message, when, where, modifiers) = evt - self.ted.WEClick(local, modifiers, when) - self.updatescrollbars() - self.parent.updatemenubar() - - def do_char(self, ch, event): - self.ted.WESelView() - (what, message, when, where, modifiers) = event - self.ted.WEKey(ord(ch), modifiers) - self.updatescrollbars() - self.parent.updatemenubar() - - def close(self): - if self.ted.WEGetModCount(): - save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?'%self.name, 1) - if save > 0: - self.menu_save() - elif save < 0: - return - if self.parent.active == self: - self.parent.active = None - self.parent.updatemenubar() - del self.ted - self.do_postclose() - - def menu_save(self): - if not self.path: - self.menu_save_as() - return # Will call us recursively - # - # First save data - # - dhandle = self.ted.WEGetText() - data = dhandle.data - fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line - fp.write(data) - if data[-1] <> '\r': fp.write('\r') - fp.close() - # - # Now save style and soup - # - oldresfile = Res.CurResFile() - try: - rf = Res.FSpOpenResFile(self.path, 3) - except Res.Error: - Res.FSpCreateResFile(self.path, '????', 'TEXT', macfs.smAllScripts) - rf = Res.FSpOpenResFile(self.path, 3) - styles = Res.Resource('') - soup = Res.Resource('') - self.ted.WECopyRange(0, 0x3fffffff, None, styles, soup) - styles.AddResource('styl', 128, '') - soup.AddResource('SOUP', 128, '') - Res.CloseResFile(rf) - Res.UseResFile(oldresfile) - - self.ted.WEResetModCount() - - def menu_save_as(self): - path = EasyDialogs.AskFileForSave(message='Save as:') - if not path: return - self.path = path - self.name = os.path.split(self.path)[-1] - self.wid.SetWTitle(self.name) - self.menu_save() - - def menu_insert(self, fp): - self.ted.WESelView() - data = fp.read() - self.ted.WEInsert(data, None, None) - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_insert_html(self, fp): - import htmllib - import formatter - f = formatter.AbstractFormatter(self) - - # Remember where we are, and don't update - Qd.SetCursor(WATCH) - start, dummy = self.ted.WEGetSelection() - self.ted.WEFeatureFlag(WASTEconst.weFInhibitRecal, 1) - - self.html_init() - p = MyHTMLParser(f) - p.feed(fp.read()) - - # Restore updating, recalc, set focus - dummy, end = self.ted.WEGetSelection() - self.ted.WECalText() - self.ted.WESetSelection(start, end) - self.ted.WESelView() - self.ted.WEFeatureFlag(WASTEconst.weFInhibitRecal, 0) - self.wid.InvalWindowRect(self.ted.WEGetViewRect()) - - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_cut(self): - self.ted.WESelView() - if hasattr(Scrap, 'ZeroScrap'): - Scrap.ZeroScrap() - else: - Scrap.ClearCurrentScrap() - self.ted.WECut() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_copy(self): - if hasattr(Scrap, 'ZeroScrap'): - Scrap.ZeroScrap() - else: - Scrap.ClearCurrentScrap() - self.ted.WECopy() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_paste(self): - self.ted.WESelView() - self.ted.WEPaste() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_clear(self): - self.ted.WESelView() - self.ted.WEDelete() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_undo(self): - self.ted.WEUndo() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_setfont(self, font): - font = Fm.GetFNum(font) - self.mysetstyle(WASTEconst.weDoFont, (font, 0, 0, (0,0,0))) - self.parent.updatemenubar() - - def menu_modface(self, face): - self.mysetstyle(WASTEconst.weDoFace|WASTEconst.weDoToggleFace, - (0, face, 0, (0,0,0))) - - def menu_setface(self, face): - self.mysetstyle(WASTEconst.weDoFace|WASTEconst.weDoReplaceFace, - (0, face, 0, (0,0,0))) - - def menu_setsize(self, size): - self.mysetstyle(WASTEconst.weDoSize, (0, 0, size, (0,0,0))) - - def menu_incsize(self, size): - self.mysetstyle(WASTEconst.weDoAddSize, (0, 0, size, (0,0,0))) - - def mysetstyle(self, which, how): - self.ted.WESelView() - self.ted.WESetStyle(which, how) - self.parent.updatemenubar() - - def have_selection(self): - start, stop = self.ted.WEGetSelection() - return start < stop - - def can_paste(self): - return self.ted.WECanPaste() - - def can_undo(self): - which, redo = self.ted.WEGetUndoInfo() - which = UNDOLABELS[which] - if which == None: return None - if redo: - return "Redo "+which - else: - return "Undo "+which - - def getruninfo(self): - all = (WASTEconst.weDoFont | WASTEconst.weDoFace | WASTEconst.weDoSize) - dummy, mode, (font, face, size, color) = self.ted.WEContinuousStyle(all) - if not (mode & WASTEconst.weDoFont): - font = None - else: - font = Fm.GetFontName(font) - if not (mode & WASTEconst.weDoFace): fact = None - if not (mode & WASTEconst.weDoSize): size = None - return font, face, size - - # - # Methods for writer class for html formatter - # - - def html_init(self): - self.html_font = [12, 0, 0, 0] - self.html_style = 0 - self.html_color = (0,0,0) - self.new_font(self.html_font) - - def new_font(self, font): - if font == None: - font = (12, 0, 0, 0) - font = map(lambda x:x, font) - for i in range(len(font)): - if font[i] == None: - font[i] = self.html_font[i] - [size, italic, bold, tt] = font - self.html_font = font[:] - if tt: - font = Fm.GetFNum('Courier') - else: - font = Fm.GetFNum('Times') - if HTML_SIZE.has_key(size): - size = HTML_SIZE[size] - else: - size = 12 - face = 0 - if bold: face = face | 1 - if italic: face = face | 2 - face = face | self.html_style - self.ted.WESetStyle(WASTEconst.weDoFont | WASTEconst.weDoFace | - WASTEconst.weDoSize | WASTEconst.weDoColor, - (font, face, size, self.html_color)) - - def new_margin(self, margin, level): - self.ted.WEInsert('[Margin %s %s]'%(margin, level), None, None) - - def new_spacing(self, spacing): - self.ted.WEInsert('[spacing %s]'%spacing, None, None) - - def new_styles(self, styles): - self.html_style = 0 - self.html_color = (0,0,0) - if 'anchor' in styles: - self.html_style = self.html_style | 4 - self.html_color = (0xffff, 0, 0) - self.new_font(self.html_font) - - def send_paragraph(self, blankline): - self.ted.WEInsert('\r'*(blankline+1), None, None) - - def send_line_break(self): - self.ted.WEInsert('\r', None, None) - - def send_hor_rule(self, *args, **kw): - # Ignore ruler options, for now - dummydata = Res.Resource('') - self.ted.WEInsertObject('rulr', dummydata, (0,0)) - - def send_label_data(self, data): - self.ted.WEInsert(data, None, None) - - def send_flowing_data(self, data): - self.ted.WEInsert(data, None, None) - - def send_literal_data(self, data): - data = string.replace(data, '\n', '\r') - data = string.expandtabs(data) - self.ted.WEInsert(data, None, None) - + def open(self, path, name, data): + self.path = path + self.name = name + r = windowbounds(400, 400) + w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) + self.wid = w + vr = LEFTMARGIN, 0, r[2]-r[0]-15, r[3]-r[1]-15 + dr = (0, 0, vr[2], 0) + Qd.SetPort(w) + Qd.TextFont(4) + Qd.TextSize(9) + flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoOutlineHilite | \ + WASTEconst.weDoMonoStyled | WASTEconst.weDoUndo + self.ted = waste.WENew(dr, vr, flags) + self.ted.WEInstallTabHooks() + style, soup = self.getstylesoup(self.path) + self.ted.WEInsert(data, style, soup) + self.ted.WESetSelection(0,0) + self.ted.WECalText() + self.ted.WEResetModCount() + w.DrawGrowIcon() + self.scrollbars() + self.do_postopen() + self.do_activate(1, None) + + def getstylesoup(self, pathname): + if not pathname: + return None, None + oldrf = Res.CurResFile() + try: + rf = Res.FSpOpenResFile(self.path, 1) + except Res.Error: + return None, None + try: + hstyle = Res.Get1Resource('styl', 128) + hstyle.DetachResource() + except Res.Error: + hstyle = None + try: + hsoup = Res.Get1Resource('SOUP', 128) + hsoup.DetachResource() + except Res.Error: + hsoup = None + Res.CloseResFile(rf) + Res.UseResFile(oldrf) + return hstyle, hsoup + + def do_idle(self, event): + (what, message, when, where, modifiers) = event + Qd.SetPort(self.wid) + self.ted.WEIdle() + if self.ted.WEAdjustCursor(where, BIGREGION): + return + Qd.SetCursor(Qd.GetQDGlobalsArrow()) + + def getscrollbarvalues(self): + dr = self.ted.WEGetDestRect() + vr = self.ted.WEGetViewRect() + vx = self.scalebarvalue(dr[0], dr[2], vr[0], vr[2]) + vy = self.scalebarvalue(dr[1], dr[3], vr[1], vr[3]) + return vx, vy + + def scrollbar_callback(self, which, what, value): + if which == 'y': + # + # "line" size is minimum of top and bottom line size + # + topline_off,dummy = self.ted.WEGetOffset((1,1)) + topline_num = self.ted.WEOffsetToLine(topline_off) + toplineheight = self.ted.WEGetHeight(topline_num, topline_num+1) + + botlinepos = self.ted.WEGetViewRect()[3] + botline_off, dummy = self.ted.WEGetOffset((1, botlinepos-1)) + botline_num = self.ted.WEOffsetToLine(botline_off) + botlineheight = self.ted.WEGetHeight(botline_num, botline_num+1) + + if botlineheight == 0: + botlineheight = self.ted.WEGetHeight(botline_num-1, botline_num) + if botlineheight < toplineheight: + lineheight = botlineheight + else: + lineheight = toplineheight + if lineheight <= 0: + lineheight = 1 + # + # Now do the command. + # + if what == 'set': + height = self.ted.WEGetHeight(0, 0x3fffffff) + cur = self.getscrollbarvalues()[1] + delta = (cur-value)*height/32767 + if what == '-': + delta = lineheight + elif what == '--': + delta = (self.ted.WEGetViewRect()[3]-lineheight) + if delta <= 0: + delta = lineheight + elif what == '+': + delta = -lineheight + elif what == '++': + delta = -(self.ted.WEGetViewRect()[3]-lineheight) + if delta >= 0: + delta = -lineheight + self.ted.WEScroll(0, delta) + else: + if what == 'set': + return # XXXX + vr = self.ted.WEGetViewRect() + winwidth = vr[2]-vr[0] + if what == '-': + delta = winwidth/10 + elif what == '--': + delta = winwidth/2 + elif what == '+': + delta = -winwidth/10 + elif what == '++': + delta = -winwidth/2 + self.ted.WEScroll(delta, 0) + # Pin the scroll + l, t, r, b = self.ted.WEGetDestRect() + vl, vt, vr, vb = self.ted.WEGetViewRect() + if t > 0 or l > 0: + dx = dy = 0 + if t > 0: dy = -t + if l > 0: dx = -l + self.ted.WEScroll(dx, dy) + elif b < vb: + self.ted.WEScroll(0, vb-b) + + + def do_activate(self, onoff, evt): + Qd.SetPort(self.wid) + ScrolledWindow.do_activate(self, onoff, evt) + if onoff: + self.ted.WEActivate() + self.parent.active = self + self.parent.updatemenubar() + else: + self.ted.WEDeactivate() + + def do_update(self, wid, event): + region = wid.GetWindowPort().visRgn + if Qd.EmptyRgn(region): + return + Qd.EraseRgn(region) + self.ted.WEUpdate(region) + self.updatescrollbars() + + def do_postresize(self, width, height, window): + l, t, r, b = self.ted.WEGetViewRect() + vr = (l, t, l+width-15, t+height-15) + self.ted.WESetViewRect(vr) + self.wid.InvalWindowRect(vr) + ScrolledWindow.do_postresize(self, width, height, window) + + def do_contentclick(self, local, modifiers, evt): + (what, message, when, where, modifiers) = evt + self.ted.WEClick(local, modifiers, when) + self.updatescrollbars() + self.parent.updatemenubar() + + def do_char(self, ch, event): + self.ted.WESelView() + (what, message, when, where, modifiers) = event + self.ted.WEKey(ord(ch), modifiers) + self.updatescrollbars() + self.parent.updatemenubar() + + def close(self): + if self.ted.WEGetModCount(): + save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?'%self.name, 1) + if save > 0: + self.menu_save() + elif save < 0: + return + if self.parent.active == self: + self.parent.active = None + self.parent.updatemenubar() + del self.ted + self.do_postclose() + + def menu_save(self): + if not self.path: + self.menu_save_as() + return # Will call us recursively + # + # First save data + # + dhandle = self.ted.WEGetText() + data = dhandle.data + fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line + fp.write(data) + if data[-1] <> '\r': fp.write('\r') + fp.close() + # + # Now save style and soup + # + oldresfile = Res.CurResFile() + try: + rf = Res.FSpOpenResFile(self.path, 3) + except Res.Error: + Res.FSpCreateResFile(self.path, '????', 'TEXT', macfs.smAllScripts) + rf = Res.FSpOpenResFile(self.path, 3) + styles = Res.Resource('') + soup = Res.Resource('') + self.ted.WECopyRange(0, 0x3fffffff, None, styles, soup) + styles.AddResource('styl', 128, '') + soup.AddResource('SOUP', 128, '') + Res.CloseResFile(rf) + Res.UseResFile(oldresfile) + + self.ted.WEResetModCount() + + def menu_save_as(self): + path = EasyDialogs.AskFileForSave(message='Save as:') + if not path: return + self.path = path + self.name = os.path.split(self.path)[-1] + self.wid.SetWTitle(self.name) + self.menu_save() + + def menu_insert(self, fp): + self.ted.WESelView() + data = fp.read() + self.ted.WEInsert(data, None, None) + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_insert_html(self, fp): + import htmllib + import formatter + f = formatter.AbstractFormatter(self) + + # Remember where we are, and don't update + Qd.SetCursor(WATCH) + start, dummy = self.ted.WEGetSelection() + self.ted.WEFeatureFlag(WASTEconst.weFInhibitRecal, 1) + + self.html_init() + p = MyHTMLParser(f) + p.feed(fp.read()) + + # Restore updating, recalc, set focus + dummy, end = self.ted.WEGetSelection() + self.ted.WECalText() + self.ted.WESetSelection(start, end) + self.ted.WESelView() + self.ted.WEFeatureFlag(WASTEconst.weFInhibitRecal, 0) + self.wid.InvalWindowRect(self.ted.WEGetViewRect()) + + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_cut(self): + self.ted.WESelView() + if hasattr(Scrap, 'ZeroScrap'): + Scrap.ZeroScrap() + else: + Scrap.ClearCurrentScrap() + self.ted.WECut() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_copy(self): + if hasattr(Scrap, 'ZeroScrap'): + Scrap.ZeroScrap() + else: + Scrap.ClearCurrentScrap() + self.ted.WECopy() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_paste(self): + self.ted.WESelView() + self.ted.WEPaste() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_clear(self): + self.ted.WESelView() + self.ted.WEDelete() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_undo(self): + self.ted.WEUndo() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_setfont(self, font): + font = Fm.GetFNum(font) + self.mysetstyle(WASTEconst.weDoFont, (font, 0, 0, (0,0,0))) + self.parent.updatemenubar() + + def menu_modface(self, face): + self.mysetstyle(WASTEconst.weDoFace|WASTEconst.weDoToggleFace, + (0, face, 0, (0,0,0))) + + def menu_setface(self, face): + self.mysetstyle(WASTEconst.weDoFace|WASTEconst.weDoReplaceFace, + (0, face, 0, (0,0,0))) + + def menu_setsize(self, size): + self.mysetstyle(WASTEconst.weDoSize, (0, 0, size, (0,0,0))) + + def menu_incsize(self, size): + self.mysetstyle(WASTEconst.weDoAddSize, (0, 0, size, (0,0,0))) + + def mysetstyle(self, which, how): + self.ted.WESelView() + self.ted.WESetStyle(which, how) + self.parent.updatemenubar() + + def have_selection(self): + start, stop = self.ted.WEGetSelection() + return start < stop + + def can_paste(self): + return self.ted.WECanPaste() + + def can_undo(self): + which, redo = self.ted.WEGetUndoInfo() + which = UNDOLABELS[which] + if which == None: return None + if redo: + return "Redo "+which + else: + return "Undo "+which + + def getruninfo(self): + all = (WASTEconst.weDoFont | WASTEconst.weDoFace | WASTEconst.weDoSize) + dummy, mode, (font, face, size, color) = self.ted.WEContinuousStyle(all) + if not (mode & WASTEconst.weDoFont): + font = None + else: + font = Fm.GetFontName(font) + if not (mode & WASTEconst.weDoFace): fact = None + if not (mode & WASTEconst.weDoSize): size = None + return font, face, size + + # + # Methods for writer class for html formatter + # + + def html_init(self): + self.html_font = [12, 0, 0, 0] + self.html_style = 0 + self.html_color = (0,0,0) + self.new_font(self.html_font) + + def new_font(self, font): + if font == None: + font = (12, 0, 0, 0) + font = map(lambda x:x, font) + for i in range(len(font)): + if font[i] == None: + font[i] = self.html_font[i] + [size, italic, bold, tt] = font + self.html_font = font[:] + if tt: + font = Fm.GetFNum('Courier') + else: + font = Fm.GetFNum('Times') + if HTML_SIZE.has_key(size): + size = HTML_SIZE[size] + else: + size = 12 + face = 0 + if bold: face = face | 1 + if italic: face = face | 2 + face = face | self.html_style + self.ted.WESetStyle(WASTEconst.weDoFont | WASTEconst.weDoFace | + WASTEconst.weDoSize | WASTEconst.weDoColor, + (font, face, size, self.html_color)) + + def new_margin(self, margin, level): + self.ted.WEInsert('[Margin %s %s]'%(margin, level), None, None) + + def new_spacing(self, spacing): + self.ted.WEInsert('[spacing %s]'%spacing, None, None) + + def new_styles(self, styles): + self.html_style = 0 + self.html_color = (0,0,0) + if 'anchor' in styles: + self.html_style = self.html_style | 4 + self.html_color = (0xffff, 0, 0) + self.new_font(self.html_font) + + def send_paragraph(self, blankline): + self.ted.WEInsert('\r'*(blankline+1), None, None) + + def send_line_break(self): + self.ted.WEInsert('\r', None, None) + + def send_hor_rule(self, *args, **kw): + # Ignore ruler options, for now + dummydata = Res.Resource('') + self.ted.WEInsertObject('rulr', dummydata, (0,0)) + + def send_label_data(self, data): + self.ted.WEInsert(data, None, None) + + def send_flowing_data(self, data): + self.ted.WEInsert(data, None, None) + + def send_literal_data(self, data): + data = string.replace(data, '\n', '\r') + data = string.expandtabs(data) + self.ted.WEInsert(data, None, None) + class Wed(Application): - def __init__(self): - Application.__init__(self) - self.num = 0 - self.active = None - self.updatemenubar() - waste.STDObjectHandlers() - # Handler for horizontal ruler - waste.WEInstallObjectHandler('rulr', 'new ', self.newRuler) - waste.WEInstallObjectHandler('rulr', 'draw', self.drawRuler) - - def makeusermenus(self): - self.filemenu = m = Menu(self.menubar, "File") - self.newitem = MenuItem(m, "New window", "N", self.open) - self.openitem = MenuItem(m, "Open...", "O", self.openfile) - self.closeitem = MenuItem(m, "Close", "W", self.closewin) - m.addseparator() - self.saveitem = MenuItem(m, "Save", "S", self.save) - self.saveasitem = MenuItem(m, "Save as...", "", self.saveas) - m.addseparator() - self.insertitem = MenuItem(m, "Insert plaintext...", "", self.insertfile) - self.htmlitem = MenuItem(m, "Insert HTML...", "", self.inserthtml) - m.addseparator() - self.quititem = MenuItem(m, "Quit", "Q", self.quit) - - self.editmenu = m = Menu(self.menubar, "Edit") - self.undoitem = MenuItem(m, "Undo", "Z", self.undo) - self.cutitem = MenuItem(m, "Cut", "X", self.cut) - self.copyitem = MenuItem(m, "Copy", "C", self.copy) - self.pasteitem = MenuItem(m, "Paste", "V", self.paste) - self.clearitem = MenuItem(m, "Clear", "", self.clear) - - self.makefontmenu() - - # Groups of items enabled together: - self.windowgroup = [self.closeitem, self.saveitem, self.saveasitem, - self.editmenu, self.fontmenu, self.facemenu, self.sizemenu, - self.insertitem] - self.focusgroup = [self.cutitem, self.copyitem, self.clearitem] - self.windowgroup_on = -1 - self.focusgroup_on = -1 - self.pastegroup_on = -1 - self.undo_label = "never" - self.ffs_values = () - - def makefontmenu(self): - self.fontmenu = Menu(self.menubar, "Font") - self.fontnames = getfontnames() - self.fontitems = [] - for n in self.fontnames: - m = MenuItem(self.fontmenu, n, "", self.selfont) - self.fontitems.append(m) - self.facemenu = Menu(self.menubar, "Style") - self.faceitems = [] - for n, shortcut in STYLES: - m = MenuItem(self.facemenu, n, shortcut, self.selface) - self.faceitems.append(m) - self.facemenu.addseparator() - self.faceitem_normal = MenuItem(self.facemenu, "Normal", "N", - self.selfacenormal) - self.sizemenu = Menu(self.menubar, "Size") - self.sizeitems = [] - for n in SIZES: - m = MenuItem(self.sizemenu, repr(n), "", self.selsize) - self.sizeitems.append(m) - self.sizemenu.addseparator() - self.sizeitem_bigger = MenuItem(self.sizemenu, "Bigger", "+", - self.selsizebigger) - self.sizeitem_smaller = MenuItem(self.sizemenu, "Smaller", "-", - self.selsizesmaller) - - def selfont(self, id, item, *rest): - if self.active: - font = self.fontnames[item-1] - self.active.menu_setfont(font) - else: - EasyDialogs.Message("No active window?") - - def selface(self, id, item, *rest): - if self.active: - face = (1<<(item-1)) - self.active.menu_modface(face) - else: - EasyDialogs.Message("No active window?") - - def selfacenormal(self, *rest): - if self.active: - self.active.menu_setface(0) - else: - EasyDialogs.Message("No active window?") - - def selsize(self, id, item, *rest): - if self.active: - size = SIZES[item-1] - self.active.menu_setsize(size) - else: - EasyDialogs.Message("No active window?") - - def selsizebigger(self, *rest): - if self.active: - self.active.menu_incsize(2) - else: - EasyDialogs.Message("No active window?") - - def selsizesmaller(self, *rest): - if self.active: - self.active.menu_incsize(-2) - else: - EasyDialogs.Message("No active window?") - - def updatemenubar(self): - changed = 0 - on = (self.active <> None) - if on <> self.windowgroup_on: - for m in self.windowgroup: - m.enable(on) - self.windowgroup_on = on - changed = 1 - if on: - # only if we have an edit menu - on = self.active.have_selection() - if on <> self.focusgroup_on: - for m in self.focusgroup: - m.enable(on) - self.focusgroup_on = on - changed = 1 - on = self.active.can_paste() - if on <> self.pastegroup_on: - self.pasteitem.enable(on) - self.pastegroup_on = on - changed = 1 - on = self.active.can_undo() - if on <> self.undo_label: - if on: - self.undoitem.enable(1) - self.undoitem.settext(on) - self.undo_label = on - else: - self.undoitem.settext("Nothing to undo") - self.undoitem.enable(0) - changed = 1 - if self.updatefontmenus(): - changed = 1 - if changed: - DrawMenuBar() - - def updatefontmenus(self): - info = self.active.getruninfo() - if info == self.ffs_values: - return 0 - # Remove old checkmarks - if self.ffs_values == (): - self.ffs_values = (None, None, None) - font, face, size = self.ffs_values - if font <> None: - fnum = self.fontnames.index(font) - self.fontitems[fnum].check(0) - if face <> None: - for i in range(len(self.faceitems)): - if face & (1<<i): - self.faceitems[i].check(0) - if size <> None: - for i in range(len(self.sizeitems)): - if SIZES[i] == size: - self.sizeitems[i].check(0) - - self.ffs_values = info - # Set new checkmarks - font, face, size = self.ffs_values - if font <> None: - fnum = self.fontnames.index(font) - self.fontitems[fnum].check(1) - if face <> None: - for i in range(len(self.faceitems)): - if face & (1<<i): - self.faceitems[i].check(1) - if size <> None: - for i in range(len(self.sizeitems)): - if SIZES[i] == size: - self.sizeitems[i].check(1) - # Set outline/normal for sizes - if font: - exists = getfontsizes(font, SIZES) - for i in range(len(self.sizeitems)): - if exists[i]: - self.sizeitems[i].setstyle(0) - else: - self.sizeitems[i].setstyle(8) - - # - # Apple menu - # - - def do_about(self, id, item, window, event): - EasyDialogs.Message("A simple single-font text editor based on WASTE") - - # - # File menu - # - - def open(self, *args): - self._open(0) - - def openfile(self, *args): - self._open(1) - - def _open(self, askfile): - if askfile: - path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) - if not path: - return - name = os.path.split(path)[-1] - try: - fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line - data = fp.read() - fp.close() - except IOError, arg: - EasyDialogs.Message("IOERROR: %r" % (arg,)) - return - else: - path = None - name = "Untitled %d"%self.num - data = '' - w = WasteWindow(self) - w.open(path, name, data) - self.num = self.num + 1 - - def insertfile(self, *args): - if self.active: - path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) - if not path: - return - try: - fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line - except IOError, arg: - EasyDialogs.Message("IOERROR: %r" % (args,)) - return - self.active.menu_insert(fp) - else: - EasyDialogs.Message("No active window?") - - def inserthtml(self, *args): - if self.active: - path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) - if not path: - return - try: - fp = open(path, 'r') - except IOError, arg: - EasyDialogs.Message("IOERROR: %r" % (arg,)) - return - self.active.menu_insert_html(fp) - else: - EasyDialogs.Message("No active window?") - - - def closewin(self, *args): - if self.active: - self.active.close() - else: - EasyDialogs.Message("No active window?") - - def save(self, *args): - if self.active: - self.active.menu_save() - else: - EasyDialogs.Message("No active window?") - - def saveas(self, *args): - if self.active: - self.active.menu_save_as() - else: - EasyDialogs.Message("No active window?") - - - def quit(self, *args): - for w in self._windows.values(): - w.close() - if self._windows: - return - self._quit() - - # - # Edit menu - # - - def undo(self, *args): - if self.active: - self.active.menu_undo() - else: - EasyDialogs.Message("No active window?") - - def cut(self, *args): - if self.active: - self.active.menu_cut() - else: - EasyDialogs.Message("No active window?") - - def copy(self, *args): - if self.active: - self.active.menu_copy() - else: - EasyDialogs.Message("No active window?") - - def paste(self, *args): - if self.active: - self.active.menu_paste() - else: - EasyDialogs.Message("No active window?") - - def clear(self, *args): - if self.active: - self.active.menu_clear() - else: - EasyDialogs.Message("No active window?") - - # - # Other stuff - # - - def idle(self, event): - if self.active: - self.active.do_idle(event) - else: - Qd.SetCursor(Qd.GetQDGlobalsArrow()) - - def newRuler(self, obj): - """Insert a new ruler. Make it as wide as the window minus 2 pxls""" - ted = obj.WEGetObjectOwner() - l, t, r, b = ted.WEGetDestRect() - return r-l, 4 - - def drawRuler(self, (l, t, r, b), obj): - y = (t+b)/2 - Qd.MoveTo(l+2, y) - Qd.LineTo(r-2, y) - return 0 - + def __init__(self): + Application.__init__(self) + self.num = 0 + self.active = None + self.updatemenubar() + waste.STDObjectHandlers() + # Handler for horizontal ruler + waste.WEInstallObjectHandler('rulr', 'new ', self.newRuler) + waste.WEInstallObjectHandler('rulr', 'draw', self.drawRuler) + + def makeusermenus(self): + self.filemenu = m = Menu(self.menubar, "File") + self.newitem = MenuItem(m, "New window", "N", self.open) + self.openitem = MenuItem(m, "Open...", "O", self.openfile) + self.closeitem = MenuItem(m, "Close", "W", self.closewin) + m.addseparator() + self.saveitem = MenuItem(m, "Save", "S", self.save) + self.saveasitem = MenuItem(m, "Save as...", "", self.saveas) + m.addseparator() + self.insertitem = MenuItem(m, "Insert plaintext...", "", self.insertfile) + self.htmlitem = MenuItem(m, "Insert HTML...", "", self.inserthtml) + m.addseparator() + self.quititem = MenuItem(m, "Quit", "Q", self.quit) + + self.editmenu = m = Menu(self.menubar, "Edit") + self.undoitem = MenuItem(m, "Undo", "Z", self.undo) + self.cutitem = MenuItem(m, "Cut", "X", self.cut) + self.copyitem = MenuItem(m, "Copy", "C", self.copy) + self.pasteitem = MenuItem(m, "Paste", "V", self.paste) + self.clearitem = MenuItem(m, "Clear", "", self.clear) + + self.makefontmenu() + + # Groups of items enabled together: + self.windowgroup = [self.closeitem, self.saveitem, self.saveasitem, + self.editmenu, self.fontmenu, self.facemenu, self.sizemenu, + self.insertitem] + self.focusgroup = [self.cutitem, self.copyitem, self.clearitem] + self.windowgroup_on = -1 + self.focusgroup_on = -1 + self.pastegroup_on = -1 + self.undo_label = "never" + self.ffs_values = () + + def makefontmenu(self): + self.fontmenu = Menu(self.menubar, "Font") + self.fontnames = getfontnames() + self.fontitems = [] + for n in self.fontnames: + m = MenuItem(self.fontmenu, n, "", self.selfont) + self.fontitems.append(m) + self.facemenu = Menu(self.menubar, "Style") + self.faceitems = [] + for n, shortcut in STYLES: + m = MenuItem(self.facemenu, n, shortcut, self.selface) + self.faceitems.append(m) + self.facemenu.addseparator() + self.faceitem_normal = MenuItem(self.facemenu, "Normal", "N", + self.selfacenormal) + self.sizemenu = Menu(self.menubar, "Size") + self.sizeitems = [] + for n in SIZES: + m = MenuItem(self.sizemenu, repr(n), "", self.selsize) + self.sizeitems.append(m) + self.sizemenu.addseparator() + self.sizeitem_bigger = MenuItem(self.sizemenu, "Bigger", "+", + self.selsizebigger) + self.sizeitem_smaller = MenuItem(self.sizemenu, "Smaller", "-", + self.selsizesmaller) + + def selfont(self, id, item, *rest): + if self.active: + font = self.fontnames[item-1] + self.active.menu_setfont(font) + else: + EasyDialogs.Message("No active window?") + + def selface(self, id, item, *rest): + if self.active: + face = (1<<(item-1)) + self.active.menu_modface(face) + else: + EasyDialogs.Message("No active window?") + + def selfacenormal(self, *rest): + if self.active: + self.active.menu_setface(0) + else: + EasyDialogs.Message("No active window?") + + def selsize(self, id, item, *rest): + if self.active: + size = SIZES[item-1] + self.active.menu_setsize(size) + else: + EasyDialogs.Message("No active window?") + + def selsizebigger(self, *rest): + if self.active: + self.active.menu_incsize(2) + else: + EasyDialogs.Message("No active window?") + + def selsizesmaller(self, *rest): + if self.active: + self.active.menu_incsize(-2) + else: + EasyDialogs.Message("No active window?") + + def updatemenubar(self): + changed = 0 + on = (self.active <> None) + if on <> self.windowgroup_on: + for m in self.windowgroup: + m.enable(on) + self.windowgroup_on = on + changed = 1 + if on: + # only if we have an edit menu + on = self.active.have_selection() + if on <> self.focusgroup_on: + for m in self.focusgroup: + m.enable(on) + self.focusgroup_on = on + changed = 1 + on = self.active.can_paste() + if on <> self.pastegroup_on: + self.pasteitem.enable(on) + self.pastegroup_on = on + changed = 1 + on = self.active.can_undo() + if on <> self.undo_label: + if on: + self.undoitem.enable(1) + self.undoitem.settext(on) + self.undo_label = on + else: + self.undoitem.settext("Nothing to undo") + self.undoitem.enable(0) + changed = 1 + if self.updatefontmenus(): + changed = 1 + if changed: + DrawMenuBar() + + def updatefontmenus(self): + info = self.active.getruninfo() + if info == self.ffs_values: + return 0 + # Remove old checkmarks + if self.ffs_values == (): + self.ffs_values = (None, None, None) + font, face, size = self.ffs_values + if font <> None: + fnum = self.fontnames.index(font) + self.fontitems[fnum].check(0) + if face <> None: + for i in range(len(self.faceitems)): + if face & (1<<i): + self.faceitems[i].check(0) + if size <> None: + for i in range(len(self.sizeitems)): + if SIZES[i] == size: + self.sizeitems[i].check(0) + + self.ffs_values = info + # Set new checkmarks + font, face, size = self.ffs_values + if font <> None: + fnum = self.fontnames.index(font) + self.fontitems[fnum].check(1) + if face <> None: + for i in range(len(self.faceitems)): + if face & (1<<i): + self.faceitems[i].check(1) + if size <> None: + for i in range(len(self.sizeitems)): + if SIZES[i] == size: + self.sizeitems[i].check(1) + # Set outline/normal for sizes + if font: + exists = getfontsizes(font, SIZES) + for i in range(len(self.sizeitems)): + if exists[i]: + self.sizeitems[i].setstyle(0) + else: + self.sizeitems[i].setstyle(8) + + # + # Apple menu + # + + def do_about(self, id, item, window, event): + EasyDialogs.Message("A simple single-font text editor based on WASTE") + + # + # File menu + # + + def open(self, *args): + self._open(0) + + def openfile(self, *args): + self._open(1) + + def _open(self, askfile): + if askfile: + path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) + if not path: + return + name = os.path.split(path)[-1] + try: + fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line + data = fp.read() + fp.close() + except IOError, arg: + EasyDialogs.Message("IOERROR: %r" % (arg,)) + return + else: + path = None + name = "Untitled %d"%self.num + data = '' + w = WasteWindow(self) + w.open(path, name, data) + self.num = self.num + 1 + + def insertfile(self, *args): + if self.active: + path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) + if not path: + return + try: + fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line + except IOError, arg: + EasyDialogs.Message("IOERROR: %r" % (args,)) + return + self.active.menu_insert(fp) + else: + EasyDialogs.Message("No active window?") + + def inserthtml(self, *args): + if self.active: + path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) + if not path: + return + try: + fp = open(path, 'r') + except IOError, arg: + EasyDialogs.Message("IOERROR: %r" % (arg,)) + return + self.active.menu_insert_html(fp) + else: + EasyDialogs.Message("No active window?") + + + def closewin(self, *args): + if self.active: + self.active.close() + else: + EasyDialogs.Message("No active window?") + + def save(self, *args): + if self.active: + self.active.menu_save() + else: + EasyDialogs.Message("No active window?") + + def saveas(self, *args): + if self.active: + self.active.menu_save_as() + else: + EasyDialogs.Message("No active window?") + + + def quit(self, *args): + for w in self._windows.values(): + w.close() + if self._windows: + return + self._quit() + + # + # Edit menu + # + + def undo(self, *args): + if self.active: + self.active.menu_undo() + else: + EasyDialogs.Message("No active window?") + + def cut(self, *args): + if self.active: + self.active.menu_cut() + else: + EasyDialogs.Message("No active window?") + + def copy(self, *args): + if self.active: + self.active.menu_copy() + else: + EasyDialogs.Message("No active window?") + + def paste(self, *args): + if self.active: + self.active.menu_paste() + else: + EasyDialogs.Message("No active window?") + + def clear(self, *args): + if self.active: + self.active.menu_clear() + else: + EasyDialogs.Message("No active window?") + + # + # Other stuff + # + + def idle(self, event): + if self.active: + self.active.do_idle(event) + else: + Qd.SetCursor(Qd.GetQDGlobalsArrow()) + + def newRuler(self, obj): + """Insert a new ruler. Make it as wide as the window minus 2 pxls""" + ted = obj.WEGetObjectOwner() + l, t, r, b = ted.WEGetDestRect() + return r-l, 4 + + def drawRuler(self, (l, t, r, b), obj): + y = (t+b)/2 + Qd.MoveTo(l+2, y) + Qd.LineTo(r-2, y) + return 0 + class MyHTMLParser(htmllib.HTMLParser): - + def anchor_bgn(self, href, name, type): - self.anchor = href - if self.anchor: - self.anchorlist.append(href) - self.formatter.push_style('anchor') + self.anchor = href + if self.anchor: + self.anchorlist.append(href) + self.formatter.push_style('anchor') def anchor_end(self): - if self.anchor: - self.anchor = None - self.formatter.pop_style() + if self.anchor: + self.anchor = None + self.formatter.pop_style() + - def getfontnames(): - names = [] - for i in range(256): - n = Fm.GetFontName(i) - if n: names.append(n) - return names - + names = [] + for i in range(256): + n = Fm.GetFontName(i) + if n: names.append(n) + return names + def getfontsizes(name, sizes): - exist = [] - num = Fm.GetFNum(name) - for sz in sizes: - if Fm.RealFont(num, sz): - exist.append(1) - else: - exist.append(0) - return exist + exist = [] + num = Fm.GetFNum(name) + for sz in sizes: + if Fm.RealFont(num, sz): + exist.append(1) + else: + exist.append(0) + return exist def main(): - App = Wed() - App.mainloop() - + App = Wed() + App.mainloop() + if __name__ == '__main__': - main() - + main() diff --git a/Mac/Demo/waste/swed.py b/Mac/Demo/waste/swed.py index ca77293..2078cce 100644 --- a/Mac/Demo/waste/swed.py +++ b/Mac/Demo/waste/swed.py @@ -16,620 +16,619 @@ import os import macfs UNDOLABELS = [ # Indexed by WEGetUndoInfo() value - None, "", "typing", "Cut", "Paste", "Clear", "Drag", "Style"] - + None, "", "typing", "Cut", "Paste", "Clear", "Drag", "Style"] + # Style and size menu. Note that style order is important (tied to bit values) STYLES = [ - ("Bold", "B"), ("Italic", "I"), ("Underline", "U"), ("Outline", "O"), - ("Shadow", ""), ("Condensed", ""), ("Extended", "") - ] + ("Bold", "B"), ("Italic", "I"), ("Underline", "U"), ("Outline", "O"), + ("Shadow", ""), ("Condensed", ""), ("Extended", "") + ] SIZES = [ 9, 10, 12, 14, 18, 24] - + BIGREGION=Qd.NewRgn() Qd.SetRectRgn(BIGREGION, -16000, -16000, 16000, 16000) class WasteWindow(ScrolledWindow): - def open(self, path, name, data): - self.path = path - self.name = name - r = windowbounds(400, 400) - w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) - self.wid = w - vr = 0, 0, r[2]-r[0]-15, r[3]-r[1]-15 - dr = (0, 0, 10240, 0) - Qd.SetPort(w) - Qd.TextFont(4) - Qd.TextSize(9) - flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoOutlineHilite | \ - WASTEconst.weDoUndo - self.ted = waste.WENew(dr, vr, flags) - self.ted.WEInstallTabHooks() - style, soup = self.getstylesoup() - self.ted.WEInsert(data, style, soup) - self.ted.WESetSelection(0,0) - self.ted.WECalText() - self.ted.WEResetModCount() - w.DrawGrowIcon() - self.scrollbars() - self.do_postopen() - self.do_activate(1, None) - - def getstylesoup(self): - if not self.path: - return None, None - oldrf = Res.CurResFile() - try: - rf = Res.FSpOpenResFile(self.path, 1) - except Res.Error: - return None, None - try: - hstyle = Res.Get1Resource('styl', 128) - hstyle.DetachResource() - except Res.Error: - hstyle = None - try: - hsoup = Res.Get1Resource('SOUP', 128) - hsoup.DetachResource() - except Res.Error: - hsoup = None - Res.CloseResFile(rf) - Res.UseResFile(oldrf) - return hstyle, hsoup - - def do_idle(self, event): - (what, message, when, where, modifiers) = event - Qd.SetPort(self.wid) - self.ted.WEIdle() - if self.ted.WEAdjustCursor(where, BIGREGION): - return - Qd.SetCursor(Qd.GetQDGlobalsArrow()) - - def getscrollbarvalues(self): - dr = self.ted.WEGetDestRect() - vr = self.ted.WEGetViewRect() - vx = self.scalebarvalue(dr[0], dr[2], vr[0], vr[2]) - vy = self.scalebarvalue(dr[1], dr[3], vr[1], vr[3]) - return vx, vy - - def scrollbar_callback(self, which, what, value): - if which == 'y': - if what == 'set': - height = self.ted.WEGetHeight(0, 0x3fffffff) - cur = self.getscrollbarvalues()[1] - delta = (cur-value)*height/32767 - if what == '-': - topline_off,dummy = self.ted.WEGetOffset((1,1)) - topline_num = self.ted.WEOffsetToLine(topline_off) - delta = self.ted.WEGetHeight(topline_num, topline_num+1) - elif what == '--': - delta = (self.ted.WEGetViewRect()[3]-10) - if delta <= 0: - delta = 10 # Random value - elif what == '+': - # XXXX Wrong: should be bottom line size - topline_off,dummy = self.ted.WEGetOffset((1,1)) - topline_num = self.ted.WEOffsetToLine(topline_off) - delta = -self.ted.WEGetHeight(topline_num, topline_num+1) - elif what == '++': - delta = -(self.ted.WEGetViewRect()[3]-10) - if delta >= 0: - delta = -10 - self.ted.WEScroll(0, delta) - else: - if what == 'set': - return # XXXX - vr = self.ted.WEGetViewRect() - winwidth = vr[2]-vr[0] - if what == '-': - delta = winwidth/10 - elif what == '--': - delta = winwidth/2 - elif what == '+': - delta = -winwidth/10 - elif what == '++': - delta = -winwidth/2 - self.ted.WEScroll(delta, 0) - # Pin the scroll - l, t, r, b = self.ted.WEGetDestRect() - vl, vt, vr, vb = self.ted.WEGetViewRect() - if t > 0 or l > 0: - dx = dy = 0 - if t > 0: dy = -t - if l > 0: dx = -l - self.ted.WEScroll(dx, dy) - elif b < vb: - self.ted.WEScroll(0, b-vb) - - - def do_activate(self, onoff, evt): - Qd.SetPort(self.wid) - ScrolledWindow.do_activate(self, onoff, evt) - if onoff: - self.ted.WEActivate() - self.parent.active = self - self.parent.updatemenubar() - else: - self.ted.WEDeactivate() - - def do_update(self, wid, event): - region = wid.GetWindowPort().visRgn - if Qd.EmptyRgn(region): - return - Qd.EraseRgn(region) - self.ted.WEUpdate(region) - self.updatescrollbars() - - def do_postresize(self, width, height, window): - l, t, r, b = self.ted.WEGetViewRect() - vr = (l, t, l+width-15, t+height-15) - self.ted.WESetViewRect(vr) - self.wid.InvalWindowRect(vr) - ScrolledWindow.do_postresize(self, width, height, window) - - def do_contentclick(self, local, modifiers, evt): - (what, message, when, where, modifiers) = evt - self.ted.WEClick(local, modifiers, when) - self.updatescrollbars() - self.parent.updatemenubar() - - def do_char(self, ch, event): - self.ted.WESelView() - (what, message, when, where, modifiers) = event - self.ted.WEKey(ord(ch), modifiers) - self.updatescrollbars() - self.parent.updatemenubar() - - def close(self): - if self.ted.WEGetModCount(): - save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?'%self.name, 1) - if save > 0: - self.menu_save() - elif save < 0: - return - if self.parent.active == self: - self.parent.active = None - self.parent.updatemenubar() - del self.ted - self.do_postclose() - - def menu_save(self): - if not self.path: - self.menu_save_as() - return # Will call us recursively - # - # First save data - # - dhandle = self.ted.WEGetText() - data = dhandle.data - fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line - fp.write(data) - if data[-1] <> '\r': fp.write('\r') - fp.close() - # - # Now save style and soup - # - oldresfile = Res.CurResFile() - try: - rf = Res.FSpOpenResFile(self.path, 3) - except Res.Error: - Res.FSpCreateResFile(self.path, '????', 'TEXT', macfs.smAllScripts) - rf = Res.FSpOpenResFile(self.path, 3) - styles = Res.Resource('') - soup = Res.Resource('') - self.ted.WECopyRange(0, 0x3fffffff, None, styles, soup) - styles.AddResource('styl', 128, '') - soup.AddResource('SOUP', 128, '') - Res.CloseResFile(rf) - Res.UseResFile(oldresfile) - - self.ted.WEResetModCount() - - def menu_save_as(self): - path = EasyDialogs.AskFileForSave(message='Save as:') - if not path: return - self.path = path - self.name = os.path.split(self.path)[-1] - self.wid.SetWTitle(self.name) - self.menu_save() - - def menu_cut(self): - self.ted.WESelView() - if hasattr(Scrap, 'ZeroScrap'): - Scrap.ZeroScrap() - else: - Scrap.ClearCurrentScrap() - self.ted.WECut() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_copy(self): - if hasattr(Scrap, 'ZeroScrap'): - Scrap.ZeroScrap() - else: - Scrap.ClearCurrentScrap() - self.ted.WECopy() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_paste(self): - self.ted.WESelView() - self.ted.WEPaste() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_clear(self): - self.ted.WESelView() - self.ted.WEDelete() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_undo(self): - self.ted.WEUndo() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_setfont(self, font): - font = Fm.GetFNum(font) - self.mysetstyle(WASTEconst.weDoFont, (font, 0, 0, (0,0,0))) - self.parent.updatemenubar() - - def menu_modface(self, face): - self.mysetstyle(WASTEconst.weDoFace|WASTEconst.weDoToggleFace, - (0, face, 0, (0,0,0))) - - def menu_setface(self, face): - self.mysetstyle(WASTEconst.weDoFace|WASTEconst.weDoReplaceFace, - (0, face, 0, (0,0,0))) - - def menu_setsize(self, size): - self.mysetstyle(WASTEconst.weDoSize, (0, 0, size, (0,0,0))) - - def menu_incsize(self, size): - self.mysetstyle(WASTEconst.weDoAddSize, (0, 0, size, (0,0,0))) - - def mysetstyle(self, which, how): - self.ted.WESelView() - self.ted.WESetStyle(which, how) - self.parent.updatemenubar() - - def have_selection(self): - start, stop = self.ted.WEGetSelection() - return start < stop - - def can_paste(self): - return self.ted.WECanPaste() - - def can_undo(self): - which, redo = self.ted.WEGetUndoInfo() - which = UNDOLABELS[which] - if which == None: return None - if redo: - return "Redo "+which - else: - return "Undo "+which - - def getruninfo(self): - all = (WASTEconst.weDoFont | WASTEconst.weDoFace | WASTEconst.weDoSize) - dummy, mode, (font, face, size, color) = self.ted.WEContinuousStyle(all) - if not (mode & WASTEconst.weDoFont): - font = None - else: - font = Fm.GetFontName(font) - if not (mode & WASTEconst.weDoFace): fact = None - if not (mode & WASTEconst.weDoSize): size = None - return font, face, size + def open(self, path, name, data): + self.path = path + self.name = name + r = windowbounds(400, 400) + w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) + self.wid = w + vr = 0, 0, r[2]-r[0]-15, r[3]-r[1]-15 + dr = (0, 0, 10240, 0) + Qd.SetPort(w) + Qd.TextFont(4) + Qd.TextSize(9) + flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoOutlineHilite | \ + WASTEconst.weDoUndo + self.ted = waste.WENew(dr, vr, flags) + self.ted.WEInstallTabHooks() + style, soup = self.getstylesoup() + self.ted.WEInsert(data, style, soup) + self.ted.WESetSelection(0,0) + self.ted.WECalText() + self.ted.WEResetModCount() + w.DrawGrowIcon() + self.scrollbars() + self.do_postopen() + self.do_activate(1, None) + + def getstylesoup(self): + if not self.path: + return None, None + oldrf = Res.CurResFile() + try: + rf = Res.FSpOpenResFile(self.path, 1) + except Res.Error: + return None, None + try: + hstyle = Res.Get1Resource('styl', 128) + hstyle.DetachResource() + except Res.Error: + hstyle = None + try: + hsoup = Res.Get1Resource('SOUP', 128) + hsoup.DetachResource() + except Res.Error: + hsoup = None + Res.CloseResFile(rf) + Res.UseResFile(oldrf) + return hstyle, hsoup + + def do_idle(self, event): + (what, message, when, where, modifiers) = event + Qd.SetPort(self.wid) + self.ted.WEIdle() + if self.ted.WEAdjustCursor(where, BIGREGION): + return + Qd.SetCursor(Qd.GetQDGlobalsArrow()) + + def getscrollbarvalues(self): + dr = self.ted.WEGetDestRect() + vr = self.ted.WEGetViewRect() + vx = self.scalebarvalue(dr[0], dr[2], vr[0], vr[2]) + vy = self.scalebarvalue(dr[1], dr[3], vr[1], vr[3]) + return vx, vy + + def scrollbar_callback(self, which, what, value): + if which == 'y': + if what == 'set': + height = self.ted.WEGetHeight(0, 0x3fffffff) + cur = self.getscrollbarvalues()[1] + delta = (cur-value)*height/32767 + if what == '-': + topline_off,dummy = self.ted.WEGetOffset((1,1)) + topline_num = self.ted.WEOffsetToLine(topline_off) + delta = self.ted.WEGetHeight(topline_num, topline_num+1) + elif what == '--': + delta = (self.ted.WEGetViewRect()[3]-10) + if delta <= 0: + delta = 10 # Random value + elif what == '+': + # XXXX Wrong: should be bottom line size + topline_off,dummy = self.ted.WEGetOffset((1,1)) + topline_num = self.ted.WEOffsetToLine(topline_off) + delta = -self.ted.WEGetHeight(topline_num, topline_num+1) + elif what == '++': + delta = -(self.ted.WEGetViewRect()[3]-10) + if delta >= 0: + delta = -10 + self.ted.WEScroll(0, delta) + else: + if what == 'set': + return # XXXX + vr = self.ted.WEGetViewRect() + winwidth = vr[2]-vr[0] + if what == '-': + delta = winwidth/10 + elif what == '--': + delta = winwidth/2 + elif what == '+': + delta = -winwidth/10 + elif what == '++': + delta = -winwidth/2 + self.ted.WEScroll(delta, 0) + # Pin the scroll + l, t, r, b = self.ted.WEGetDestRect() + vl, vt, vr, vb = self.ted.WEGetViewRect() + if t > 0 or l > 0: + dx = dy = 0 + if t > 0: dy = -t + if l > 0: dx = -l + self.ted.WEScroll(dx, dy) + elif b < vb: + self.ted.WEScroll(0, b-vb) + + + def do_activate(self, onoff, evt): + Qd.SetPort(self.wid) + ScrolledWindow.do_activate(self, onoff, evt) + if onoff: + self.ted.WEActivate() + self.parent.active = self + self.parent.updatemenubar() + else: + self.ted.WEDeactivate() + + def do_update(self, wid, event): + region = wid.GetWindowPort().visRgn + if Qd.EmptyRgn(region): + return + Qd.EraseRgn(region) + self.ted.WEUpdate(region) + self.updatescrollbars() + + def do_postresize(self, width, height, window): + l, t, r, b = self.ted.WEGetViewRect() + vr = (l, t, l+width-15, t+height-15) + self.ted.WESetViewRect(vr) + self.wid.InvalWindowRect(vr) + ScrolledWindow.do_postresize(self, width, height, window) + + def do_contentclick(self, local, modifiers, evt): + (what, message, when, where, modifiers) = evt + self.ted.WEClick(local, modifiers, when) + self.updatescrollbars() + self.parent.updatemenubar() + + def do_char(self, ch, event): + self.ted.WESelView() + (what, message, when, where, modifiers) = event + self.ted.WEKey(ord(ch), modifiers) + self.updatescrollbars() + self.parent.updatemenubar() + + def close(self): + if self.ted.WEGetModCount(): + save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?'%self.name, 1) + if save > 0: + self.menu_save() + elif save < 0: + return + if self.parent.active == self: + self.parent.active = None + self.parent.updatemenubar() + del self.ted + self.do_postclose() + + def menu_save(self): + if not self.path: + self.menu_save_as() + return # Will call us recursively + # + # First save data + # + dhandle = self.ted.WEGetText() + data = dhandle.data + fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line + fp.write(data) + if data[-1] <> '\r': fp.write('\r') + fp.close() + # + # Now save style and soup + # + oldresfile = Res.CurResFile() + try: + rf = Res.FSpOpenResFile(self.path, 3) + except Res.Error: + Res.FSpCreateResFile(self.path, '????', 'TEXT', macfs.smAllScripts) + rf = Res.FSpOpenResFile(self.path, 3) + styles = Res.Resource('') + soup = Res.Resource('') + self.ted.WECopyRange(0, 0x3fffffff, None, styles, soup) + styles.AddResource('styl', 128, '') + soup.AddResource('SOUP', 128, '') + Res.CloseResFile(rf) + Res.UseResFile(oldresfile) + + self.ted.WEResetModCount() + + def menu_save_as(self): + path = EasyDialogs.AskFileForSave(message='Save as:') + if not path: return + self.path = path + self.name = os.path.split(self.path)[-1] + self.wid.SetWTitle(self.name) + self.menu_save() + + def menu_cut(self): + self.ted.WESelView() + if hasattr(Scrap, 'ZeroScrap'): + Scrap.ZeroScrap() + else: + Scrap.ClearCurrentScrap() + self.ted.WECut() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_copy(self): + if hasattr(Scrap, 'ZeroScrap'): + Scrap.ZeroScrap() + else: + Scrap.ClearCurrentScrap() + self.ted.WECopy() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_paste(self): + self.ted.WESelView() + self.ted.WEPaste() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_clear(self): + self.ted.WESelView() + self.ted.WEDelete() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_undo(self): + self.ted.WEUndo() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_setfont(self, font): + font = Fm.GetFNum(font) + self.mysetstyle(WASTEconst.weDoFont, (font, 0, 0, (0,0,0))) + self.parent.updatemenubar() + + def menu_modface(self, face): + self.mysetstyle(WASTEconst.weDoFace|WASTEconst.weDoToggleFace, + (0, face, 0, (0,0,0))) + + def menu_setface(self, face): + self.mysetstyle(WASTEconst.weDoFace|WASTEconst.weDoReplaceFace, + (0, face, 0, (0,0,0))) + + def menu_setsize(self, size): + self.mysetstyle(WASTEconst.weDoSize, (0, 0, size, (0,0,0))) + + def menu_incsize(self, size): + self.mysetstyle(WASTEconst.weDoAddSize, (0, 0, size, (0,0,0))) + + def mysetstyle(self, which, how): + self.ted.WESelView() + self.ted.WESetStyle(which, how) + self.parent.updatemenubar() + + def have_selection(self): + start, stop = self.ted.WEGetSelection() + return start < stop + + def can_paste(self): + return self.ted.WECanPaste() + + def can_undo(self): + which, redo = self.ted.WEGetUndoInfo() + which = UNDOLABELS[which] + if which == None: return None + if redo: + return "Redo "+which + else: + return "Undo "+which + + def getruninfo(self): + all = (WASTEconst.weDoFont | WASTEconst.weDoFace | WASTEconst.weDoSize) + dummy, mode, (font, face, size, color) = self.ted.WEContinuousStyle(all) + if not (mode & WASTEconst.weDoFont): + font = None + else: + font = Fm.GetFontName(font) + if not (mode & WASTEconst.weDoFace): fact = None + if not (mode & WASTEconst.weDoSize): size = None + return font, face, size class Wed(Application): - def __init__(self): - Application.__init__(self) - self.num = 0 - self.active = None - self.updatemenubar() - waste.STDObjectHandlers() - - def makeusermenus(self): - self.filemenu = m = Menu(self.menubar, "File") - self.newitem = MenuItem(m, "New window", "N", self.open) - self.openitem = MenuItem(m, "Open...", "O", self.openfile) - self.closeitem = MenuItem(m, "Close", "W", self.closewin) - m.addseparator() - self.saveitem = MenuItem(m, "Save", "S", self.save) - self.saveasitem = MenuItem(m, "Save as...", "", self.saveas) - m.addseparator() - self.quititem = MenuItem(m, "Quit", "Q", self.quit) - - self.editmenu = m = Menu(self.menubar, "Edit") - self.undoitem = MenuItem(m, "Undo", "Z", self.undo) - self.cutitem = MenuItem(m, "Cut", "X", self.cut) - self.copyitem = MenuItem(m, "Copy", "C", self.copy) - self.pasteitem = MenuItem(m, "Paste", "V", self.paste) - self.clearitem = MenuItem(m, "Clear", "", self.clear) - - self.makefontmenu() - - # Groups of items enabled together: - self.windowgroup = [self.closeitem, self.saveitem, self.saveasitem, - self.editmenu, self.fontmenu, self.facemenu, self.sizemenu] - self.focusgroup = [self.cutitem, self.copyitem, self.clearitem] - self.windowgroup_on = -1 - self.focusgroup_on = -1 - self.pastegroup_on = -1 - self.undo_label = "never" - self.ffs_values = () - - def makefontmenu(self): - self.fontmenu = Menu(self.menubar, "Font") - self.fontnames = getfontnames() - self.fontitems = [] - for n in self.fontnames: - m = MenuItem(self.fontmenu, n, "", self.selfont) - self.fontitems.append(m) - self.facemenu = Menu(self.menubar, "Style") - self.faceitems = [] - for n, shortcut in STYLES: - m = MenuItem(self.facemenu, n, shortcut, self.selface) - self.faceitems.append(m) - self.facemenu.addseparator() - self.faceitem_normal = MenuItem(self.facemenu, "Normal", "N", - self.selfacenormal) - self.sizemenu = Menu(self.menubar, "Size") - self.sizeitems = [] - for n in SIZES: - m = MenuItem(self.sizemenu, repr(n), "", self.selsize) - self.sizeitems.append(m) - self.sizemenu.addseparator() - self.sizeitem_bigger = MenuItem(self.sizemenu, "Bigger", "+", - self.selsizebigger) - self.sizeitem_smaller = MenuItem(self.sizemenu, "Smaller", "-", - self.selsizesmaller) - - def selfont(self, id, item, *rest): - if self.active: - font = self.fontnames[item-1] - self.active.menu_setfont(font) - else: - EasyDialogs.Message("No active window?") - - def selface(self, id, item, *rest): - if self.active: - face = (1<<(item-1)) - self.active.menu_modface(face) - else: - EasyDialogs.Message("No active window?") - - def selfacenormal(self, *rest): - if self.active: - self.active.menu_setface(0) - else: - EasyDialogs.Message("No active window?") - - def selsize(self, id, item, *rest): - if self.active: - size = SIZES[item-1] - self.active.menu_setsize(size) - else: - EasyDialogs.Message("No active window?") - - def selsizebigger(self, *rest): - if self.active: - self.active.menu_incsize(2) - else: - EasyDialogs.Message("No active window?") - - def selsizesmaller(self, *rest): - if self.active: - self.active.menu_incsize(-2) - else: - EasyDialogs.Message("No active window?") - - def updatemenubar(self): - changed = 0 - on = (self.active <> None) - if on <> self.windowgroup_on: - for m in self.windowgroup: - m.enable(on) - self.windowgroup_on = on - changed = 1 - if on: - # only if we have an edit menu - on = self.active.have_selection() - if on <> self.focusgroup_on: - for m in self.focusgroup: - m.enable(on) - self.focusgroup_on = on - changed = 1 - on = self.active.can_paste() - if on <> self.pastegroup_on: - self.pasteitem.enable(on) - self.pastegroup_on = on - changed = 1 - on = self.active.can_undo() - if on <> self.undo_label: - if on: - self.undoitem.enable(1) - self.undoitem.settext(on) - self.undo_label = on - else: - self.undoitem.settext("Nothing to undo") - self.undoitem.enable(0) - changed = 1 - if self.updatefontmenus(): - changed = 1 - if changed: - DrawMenuBar() - - def updatefontmenus(self): - info = self.active.getruninfo() - if info == self.ffs_values: - return 0 - # Remove old checkmarks - if self.ffs_values == (): - self.ffs_values = (None, None, None) - font, face, size = self.ffs_values - if font <> None: - fnum = self.fontnames.index(font) - self.fontitems[fnum].check(0) - if face <> None: - for i in range(len(self.faceitems)): - if face & (1<<i): - self.faceitems[i].check(0) - if size <> None: - for i in range(len(self.sizeitems)): - if SIZES[i] == size: - self.sizeitems[i].check(0) - - self.ffs_values = info - # Set new checkmarks - font, face, size = self.ffs_values - if font <> None: - fnum = self.fontnames.index(font) - self.fontitems[fnum].check(1) - if face <> None: - for i in range(len(self.faceitems)): - if face & (1<<i): - self.faceitems[i].check(1) - if size <> None: - for i in range(len(self.sizeitems)): - if SIZES[i] == size: - self.sizeitems[i].check(1) - # Set outline/normal for sizes - if font: - exists = getfontsizes(font, SIZES) - for i in range(len(self.sizeitems)): - if exists[i]: - self.sizeitems[i].setstyle(0) - else: - self.sizeitems[i].setstyle(8) - - # - # Apple menu - # - - def do_about(self, id, item, window, event): - EasyDialogs.Message("A simple single-font text editor based on WASTE") - - # - # File menu - # - - def open(self, *args): - self._open(0) - - def openfile(self, *args): - self._open(1) - - def _open(self, askfile): - if askfile: - path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) - if not path: - return - name = os.path.split(path)[-1] - try: - fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line - data = fp.read() - fp.close() - except IOError, arg: - EasyDialogs.Message("IOERROR: %r" % (arg,)) - return - else: - path = None - name = "Untitled %d"%self.num - data = '' - w = WasteWindow(self) - w.open(path, name, data) - self.num = self.num + 1 - - def closewin(self, *args): - if self.active: - self.active.close() - else: - EasyDialogs.Message("No active window?") - - def save(self, *args): - if self.active: - self.active.menu_save() - else: - EasyDialogs.Message("No active window?") - - def saveas(self, *args): - if self.active: - self.active.menu_save_as() - else: - EasyDialogs.Message("No active window?") - - - def quit(self, *args): - for w in self._windows.values(): - w.close() - if self._windows: - return - self._quit() - - # - # Edit menu - # - - def undo(self, *args): - if self.active: - self.active.menu_undo() - else: - EasyDialogs.Message("No active window?") - - def cut(self, *args): - if self.active: - self.active.menu_cut() - else: - EasyDialogs.Message("No active window?") - - def copy(self, *args): - if self.active: - self.active.menu_copy() - else: - EasyDialogs.Message("No active window?") - - def paste(self, *args): - if self.active: - self.active.menu_paste() - else: - EasyDialogs.Message("No active window?") - - def clear(self, *args): - if self.active: - self.active.menu_clear() - else: - EasyDialogs.Message("No active window?") - - # - # Other stuff - # - - def idle(self, event): - if self.active: - self.active.do_idle(event) - else: - Qd.SetCursor(Qd.GetQDGlobalsArrow()) - + def __init__(self): + Application.__init__(self) + self.num = 0 + self.active = None + self.updatemenubar() + waste.STDObjectHandlers() + + def makeusermenus(self): + self.filemenu = m = Menu(self.menubar, "File") + self.newitem = MenuItem(m, "New window", "N", self.open) + self.openitem = MenuItem(m, "Open...", "O", self.openfile) + self.closeitem = MenuItem(m, "Close", "W", self.closewin) + m.addseparator() + self.saveitem = MenuItem(m, "Save", "S", self.save) + self.saveasitem = MenuItem(m, "Save as...", "", self.saveas) + m.addseparator() + self.quititem = MenuItem(m, "Quit", "Q", self.quit) + + self.editmenu = m = Menu(self.menubar, "Edit") + self.undoitem = MenuItem(m, "Undo", "Z", self.undo) + self.cutitem = MenuItem(m, "Cut", "X", self.cut) + self.copyitem = MenuItem(m, "Copy", "C", self.copy) + self.pasteitem = MenuItem(m, "Paste", "V", self.paste) + self.clearitem = MenuItem(m, "Clear", "", self.clear) + + self.makefontmenu() + + # Groups of items enabled together: + self.windowgroup = [self.closeitem, self.saveitem, self.saveasitem, + self.editmenu, self.fontmenu, self.facemenu, self.sizemenu] + self.focusgroup = [self.cutitem, self.copyitem, self.clearitem] + self.windowgroup_on = -1 + self.focusgroup_on = -1 + self.pastegroup_on = -1 + self.undo_label = "never" + self.ffs_values = () + + def makefontmenu(self): + self.fontmenu = Menu(self.menubar, "Font") + self.fontnames = getfontnames() + self.fontitems = [] + for n in self.fontnames: + m = MenuItem(self.fontmenu, n, "", self.selfont) + self.fontitems.append(m) + self.facemenu = Menu(self.menubar, "Style") + self.faceitems = [] + for n, shortcut in STYLES: + m = MenuItem(self.facemenu, n, shortcut, self.selface) + self.faceitems.append(m) + self.facemenu.addseparator() + self.faceitem_normal = MenuItem(self.facemenu, "Normal", "N", + self.selfacenormal) + self.sizemenu = Menu(self.menubar, "Size") + self.sizeitems = [] + for n in SIZES: + m = MenuItem(self.sizemenu, repr(n), "", self.selsize) + self.sizeitems.append(m) + self.sizemenu.addseparator() + self.sizeitem_bigger = MenuItem(self.sizemenu, "Bigger", "+", + self.selsizebigger) + self.sizeitem_smaller = MenuItem(self.sizemenu, "Smaller", "-", + self.selsizesmaller) + + def selfont(self, id, item, *rest): + if self.active: + font = self.fontnames[item-1] + self.active.menu_setfont(font) + else: + EasyDialogs.Message("No active window?") + + def selface(self, id, item, *rest): + if self.active: + face = (1<<(item-1)) + self.active.menu_modface(face) + else: + EasyDialogs.Message("No active window?") + + def selfacenormal(self, *rest): + if self.active: + self.active.menu_setface(0) + else: + EasyDialogs.Message("No active window?") + + def selsize(self, id, item, *rest): + if self.active: + size = SIZES[item-1] + self.active.menu_setsize(size) + else: + EasyDialogs.Message("No active window?") + + def selsizebigger(self, *rest): + if self.active: + self.active.menu_incsize(2) + else: + EasyDialogs.Message("No active window?") + + def selsizesmaller(self, *rest): + if self.active: + self.active.menu_incsize(-2) + else: + EasyDialogs.Message("No active window?") + + def updatemenubar(self): + changed = 0 + on = (self.active <> None) + if on <> self.windowgroup_on: + for m in self.windowgroup: + m.enable(on) + self.windowgroup_on = on + changed = 1 + if on: + # only if we have an edit menu + on = self.active.have_selection() + if on <> self.focusgroup_on: + for m in self.focusgroup: + m.enable(on) + self.focusgroup_on = on + changed = 1 + on = self.active.can_paste() + if on <> self.pastegroup_on: + self.pasteitem.enable(on) + self.pastegroup_on = on + changed = 1 + on = self.active.can_undo() + if on <> self.undo_label: + if on: + self.undoitem.enable(1) + self.undoitem.settext(on) + self.undo_label = on + else: + self.undoitem.settext("Nothing to undo") + self.undoitem.enable(0) + changed = 1 + if self.updatefontmenus(): + changed = 1 + if changed: + DrawMenuBar() + + def updatefontmenus(self): + info = self.active.getruninfo() + if info == self.ffs_values: + return 0 + # Remove old checkmarks + if self.ffs_values == (): + self.ffs_values = (None, None, None) + font, face, size = self.ffs_values + if font <> None: + fnum = self.fontnames.index(font) + self.fontitems[fnum].check(0) + if face <> None: + for i in range(len(self.faceitems)): + if face & (1<<i): + self.faceitems[i].check(0) + if size <> None: + for i in range(len(self.sizeitems)): + if SIZES[i] == size: + self.sizeitems[i].check(0) + + self.ffs_values = info + # Set new checkmarks + font, face, size = self.ffs_values + if font <> None: + fnum = self.fontnames.index(font) + self.fontitems[fnum].check(1) + if face <> None: + for i in range(len(self.faceitems)): + if face & (1<<i): + self.faceitems[i].check(1) + if size <> None: + for i in range(len(self.sizeitems)): + if SIZES[i] == size: + self.sizeitems[i].check(1) + # Set outline/normal for sizes + if font: + exists = getfontsizes(font, SIZES) + for i in range(len(self.sizeitems)): + if exists[i]: + self.sizeitems[i].setstyle(0) + else: + self.sizeitems[i].setstyle(8) + + # + # Apple menu + # + + def do_about(self, id, item, window, event): + EasyDialogs.Message("A simple single-font text editor based on WASTE") + + # + # File menu + # + + def open(self, *args): + self._open(0) + + def openfile(self, *args): + self._open(1) + + def _open(self, askfile): + if askfile: + path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) + if not path: + return + name = os.path.split(path)[-1] + try: + fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line + data = fp.read() + fp.close() + except IOError, arg: + EasyDialogs.Message("IOERROR: %r" % (arg,)) + return + else: + path = None + name = "Untitled %d"%self.num + data = '' + w = WasteWindow(self) + w.open(path, name, data) + self.num = self.num + 1 + + def closewin(self, *args): + if self.active: + self.active.close() + else: + EasyDialogs.Message("No active window?") + + def save(self, *args): + if self.active: + self.active.menu_save() + else: + EasyDialogs.Message("No active window?") + + def saveas(self, *args): + if self.active: + self.active.menu_save_as() + else: + EasyDialogs.Message("No active window?") + + + def quit(self, *args): + for w in self._windows.values(): + w.close() + if self._windows: + return + self._quit() + + # + # Edit menu + # + + def undo(self, *args): + if self.active: + self.active.menu_undo() + else: + EasyDialogs.Message("No active window?") + + def cut(self, *args): + if self.active: + self.active.menu_cut() + else: + EasyDialogs.Message("No active window?") + + def copy(self, *args): + if self.active: + self.active.menu_copy() + else: + EasyDialogs.Message("No active window?") + + def paste(self, *args): + if self.active: + self.active.menu_paste() + else: + EasyDialogs.Message("No active window?") + + def clear(self, *args): + if self.active: + self.active.menu_clear() + else: + EasyDialogs.Message("No active window?") + + # + # Other stuff + # + + def idle(self, event): + if self.active: + self.active.do_idle(event) + else: + Qd.SetCursor(Qd.GetQDGlobalsArrow()) + def getfontnames(): - names = [] - for i in range(256): - n = Fm.GetFontName(i) - if n: names.append(n) - return names - + names = [] + for i in range(256): + n = Fm.GetFontName(i) + if n: names.append(n) + return names + def getfontsizes(name, sizes): - exist = [] - num = Fm.GetFNum(name) - for sz in sizes: - if Fm.RealFont(num, sz): - exist.append(1) - else: - exist.append(0) - return exist + exist = [] + num = Fm.GetFNum(name) + for sz in sizes: + if Fm.RealFont(num, sz): + exist.append(1) + else: + exist.append(0) + return exist def main(): - App = Wed() - App.mainloop() - + App = Wed() + App.mainloop() + if __name__ == '__main__': - main() - + main() diff --git a/Mac/Demo/waste/wed.py b/Mac/Demo/waste/wed.py index 5d84b40..28ee938 100644 --- a/Mac/Demo/waste/wed.py +++ b/Mac/Demo/waste/wed.py @@ -15,413 +15,412 @@ import os import EasyDialogs UNDOLABELS = [ # Indexed by WEGetUndoInfo() value - None, "", "typing", "Cut", "Paste", "Clear", "Drag", "Style"] - + None, "", "typing", "Cut", "Paste", "Clear", "Drag", "Style"] + BIGREGION=Qd.NewRgn() Qd.SetRectRgn(BIGREGION, -16000, -16000, 16000, 16000) class WasteWindow(ScrolledWindow): - def open(self, path, name, data): - self.path = path - self.name = name - r = windowbounds(400, 400) - w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) - self.wid = w - vr = 0, 0, r[2]-r[0]-15, r[3]-r[1]-15 - dr = (0, 0, 10240, 0) - Qd.SetPort(w) - Qd.TextFont(4) - Qd.TextSize(9) - flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoOutlineHilite | \ - WASTEconst.weDoMonoStyled | WASTEconst.weDoUndo - self.ted = waste.WENew(dr, vr, flags) - self.tedtexthandle = Res.Resource(data) - self.ted.WEUseText(self.tedtexthandle) - self.ted.WECalText() - w.DrawGrowIcon() - self.scrollbars() - self.changed = 0 - self.do_postopen() - self.do_activate(1, None) - - def do_idle(self, event): - (what, message, when, where, modifiers) = event - Qd.SetPort(self.wid) - self.ted.WEIdle() - if self.ted.WEAdjustCursor(where, BIGREGION): - return - Qd.SetCursor(Qd.GetQDGlobalsArrow()) - - def getscrollbarvalues(self): - dr = self.ted.WEGetDestRect() - vr = self.ted.WEGetViewRect() - vx = self.scalebarvalue(dr[0], dr[2], vr[0], vr[2]) - vy = self.scalebarvalue(dr[1], dr[3], vr[1], vr[3]) -## print dr, vr, vx, vy - return vx, vy - - def scrollbar_callback(self, which, what, value): - if which == 'y': - if what == 'set': - height = self.ted.WEGetHeight(0, 0x3fffffff) - cur = self.getscrollbarvalues()[1] - delta = (cur-value)*height/32767 - if what == '-': - topline_off,dummy = self.ted.WEGetOffset((1,1)) - topline_num = self.ted.WEOffsetToLine(topline_off) - delta = self.ted.WEGetHeight(topline_num, topline_num+1) - elif what == '--': - delta = (self.ted.WEGetViewRect()[3]-10) - if delta <= 0: - delta = 10 # Random value - elif what == '+': - # XXXX Wrong: should be bottom line size - topline_off,dummy = self.ted.WEGetOffset((1,1)) - topline_num = self.ted.WEOffsetToLine(topline_off) - delta = -self.ted.WEGetHeight(topline_num, topline_num+1) - elif what == '++': - delta = -(self.ted.WEGetViewRect()[3]-10) - if delta >= 0: - delta = -10 - self.ted.WEScroll(0, delta) -## print 'SCROLL Y', delta - else: - if what == 'set': - return # XXXX - vr = self.ted.WEGetViewRect() - winwidth = vr[2]-vr[0] - if what == '-': - delta = winwidth/10 - elif what == '--': - delta = winwidth/2 - elif what == '+': - delta = -winwidth/10 - elif what == '++': - delta = -winwidth/2 - self.ted.WEScroll(delta, 0) - # Pin the scroll - l, t, r, b = self.ted.WEGetDestRect() - vl, vt, vr, vb = self.ted.WEGetViewRect() - if t > 0 or l > 0: - dx = dy = 0 - if t > 0: dy = -t - if l > 0: dx = -l -## print 'Extra scroll', dx, dy - self.ted.WEScroll(dx, dy) - elif b < vb: -## print 'Extra downscroll', b-vb - self.ted.WEScroll(0, b-vb) - - - def do_activate(self, onoff, evt): -## print "ACTIVATE", onoff - Qd.SetPort(self.wid) - ScrolledWindow.do_activate(self, onoff, evt) - if onoff: - self.ted.WEActivate() - self.parent.active = self - self.parent.updatemenubar() - else: - self.ted.WEDeactivate() - - def do_update(self, wid, event): - region = wid.GetWindowPort().visRgn - if Qd.EmptyRgn(region): - return - Qd.EraseRgn(region) - self.ted.WEUpdate(region) - self.updatescrollbars() - - def do_postresize(self, width, height, window): - l, t, r, b = self.ted.WEGetViewRect() - vr = (l, t, l+width-15, t+height-15) - self.ted.WESetViewRect(vr) - self.wid.InvalWindowRect(vr) - ScrolledWindow.do_postresize(self, width, height, window) - - def do_contentclick(self, local, modifiers, evt): - (what, message, when, where, modifiers) = evt - self.ted.WEClick(local, modifiers, when) - self.updatescrollbars() - self.parent.updatemenubar() - - def do_char(self, ch, event): - self.ted.WESelView() - (what, message, when, where, modifiers) = event - self.ted.WEKey(ord(ch), modifiers) - self.changed = 1 - self.updatescrollbars() - self.parent.updatemenubar() - - def close(self): - if self.changed: - save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?'%self.name, 1) - if save > 0: - self.menu_save() - elif save < 0: - return - if self.parent.active == self: - self.parent.active = None - self.parent.updatemenubar() - del self.ted - del self.tedtexthandle - self.do_postclose() - - def menu_save(self): - if not self.path: - self.menu_save_as() - return # Will call us recursively -## print 'Saving to ', self.path - dhandle = self.ted.WEGetText() - data = dhandle.data - fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line - fp.write(data) - if data[-1] <> '\r': fp.write('\r') - fp.close() - self.changed = 0 - - def menu_save_as(self): - path = EasyDialogs.AskFileForSave(message='Save as:') - if not path: return - self.path = path - self.name = os.path.split(self.path)[-1] - self.wid.SetWTitle(self.name) - self.menu_save() - - def menu_cut(self): - self.ted.WESelView() - if hasattr(Scrap, 'ZeroScrap'): - Scrap.ZeroScrap() - else: - Scrap.ClearCurrentScrap() - self.ted.WECut() - self.updatescrollbars() - self.parent.updatemenubar() - self.changed = 1 - - def menu_copy(self): - if hasattr(Scrap, 'ZeroScrap'): - Scrap.ZeroScrap() - else: - Scrap.ClearCurrentScrap() - self.ted.WECopy() - self.updatescrollbars() - self.parent.updatemenubar() - - def menu_paste(self): - self.ted.WESelView() - self.ted.WEPaste() - self.updatescrollbars() - self.parent.updatemenubar() - self.changed = 1 - - def menu_clear(self): - self.ted.WESelView() - self.ted.WEDelete() - self.updatescrollbars() - self.parent.updatemenubar() - self.changed = 1 - - def menu_undo(self): - self.ted.WEUndo() - self.updatescrollbars() - self.parent.updatemenubar() - - def have_selection(self): - start, stop = self.ted.WEGetSelection() - return start < stop - - def can_paste(self): - return self.ted.WECanPaste() - - def can_undo(self): - which, redo = self.ted.WEGetUndoInfo() - which = UNDOLABELS[which] - if which == None: return None - if redo: - return "Redo "+which - else: - return "Undo "+which + def open(self, path, name, data): + self.path = path + self.name = name + r = windowbounds(400, 400) + w = Win.NewWindow(r, name, 1, 0, -1, 1, 0) + self.wid = w + vr = 0, 0, r[2]-r[0]-15, r[3]-r[1]-15 + dr = (0, 0, 10240, 0) + Qd.SetPort(w) + Qd.TextFont(4) + Qd.TextSize(9) + flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoOutlineHilite | \ + WASTEconst.weDoMonoStyled | WASTEconst.weDoUndo + self.ted = waste.WENew(dr, vr, flags) + self.tedtexthandle = Res.Resource(data) + self.ted.WEUseText(self.tedtexthandle) + self.ted.WECalText() + w.DrawGrowIcon() + self.scrollbars() + self.changed = 0 + self.do_postopen() + self.do_activate(1, None) + + def do_idle(self, event): + (what, message, when, where, modifiers) = event + Qd.SetPort(self.wid) + self.ted.WEIdle() + if self.ted.WEAdjustCursor(where, BIGREGION): + return + Qd.SetCursor(Qd.GetQDGlobalsArrow()) + + def getscrollbarvalues(self): + dr = self.ted.WEGetDestRect() + vr = self.ted.WEGetViewRect() + vx = self.scalebarvalue(dr[0], dr[2], vr[0], vr[2]) + vy = self.scalebarvalue(dr[1], dr[3], vr[1], vr[3]) +## print dr, vr, vx, vy + return vx, vy + + def scrollbar_callback(self, which, what, value): + if which == 'y': + if what == 'set': + height = self.ted.WEGetHeight(0, 0x3fffffff) + cur = self.getscrollbarvalues()[1] + delta = (cur-value)*height/32767 + if what == '-': + topline_off,dummy = self.ted.WEGetOffset((1,1)) + topline_num = self.ted.WEOffsetToLine(topline_off) + delta = self.ted.WEGetHeight(topline_num, topline_num+1) + elif what == '--': + delta = (self.ted.WEGetViewRect()[3]-10) + if delta <= 0: + delta = 10 # Random value + elif what == '+': + # XXXX Wrong: should be bottom line size + topline_off,dummy = self.ted.WEGetOffset((1,1)) + topline_num = self.ted.WEOffsetToLine(topline_off) + delta = -self.ted.WEGetHeight(topline_num, topline_num+1) + elif what == '++': + delta = -(self.ted.WEGetViewRect()[3]-10) + if delta >= 0: + delta = -10 + self.ted.WEScroll(0, delta) +## print 'SCROLL Y', delta + else: + if what == 'set': + return # XXXX + vr = self.ted.WEGetViewRect() + winwidth = vr[2]-vr[0] + if what == '-': + delta = winwidth/10 + elif what == '--': + delta = winwidth/2 + elif what == '+': + delta = -winwidth/10 + elif what == '++': + delta = -winwidth/2 + self.ted.WEScroll(delta, 0) + # Pin the scroll + l, t, r, b = self.ted.WEGetDestRect() + vl, vt, vr, vb = self.ted.WEGetViewRect() + if t > 0 or l > 0: + dx = dy = 0 + if t > 0: dy = -t + if l > 0: dx = -l +## print 'Extra scroll', dx, dy + self.ted.WEScroll(dx, dy) + elif b < vb: +## print 'Extra downscroll', b-vb + self.ted.WEScroll(0, b-vb) + + + def do_activate(self, onoff, evt): +## print "ACTIVATE", onoff + Qd.SetPort(self.wid) + ScrolledWindow.do_activate(self, onoff, evt) + if onoff: + self.ted.WEActivate() + self.parent.active = self + self.parent.updatemenubar() + else: + self.ted.WEDeactivate() + + def do_update(self, wid, event): + region = wid.GetWindowPort().visRgn + if Qd.EmptyRgn(region): + return + Qd.EraseRgn(region) + self.ted.WEUpdate(region) + self.updatescrollbars() + + def do_postresize(self, width, height, window): + l, t, r, b = self.ted.WEGetViewRect() + vr = (l, t, l+width-15, t+height-15) + self.ted.WESetViewRect(vr) + self.wid.InvalWindowRect(vr) + ScrolledWindow.do_postresize(self, width, height, window) + + def do_contentclick(self, local, modifiers, evt): + (what, message, when, where, modifiers) = evt + self.ted.WEClick(local, modifiers, when) + self.updatescrollbars() + self.parent.updatemenubar() + + def do_char(self, ch, event): + self.ted.WESelView() + (what, message, when, where, modifiers) = event + self.ted.WEKey(ord(ch), modifiers) + self.changed = 1 + self.updatescrollbars() + self.parent.updatemenubar() + + def close(self): + if self.changed: + save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?'%self.name, 1) + if save > 0: + self.menu_save() + elif save < 0: + return + if self.parent.active == self: + self.parent.active = None + self.parent.updatemenubar() + del self.ted + del self.tedtexthandle + self.do_postclose() + + def menu_save(self): + if not self.path: + self.menu_save_as() + return # Will call us recursively +## print 'Saving to ', self.path + dhandle = self.ted.WEGetText() + data = dhandle.data + fp = open(self.path, 'wb') # NOTE: wb, because data has CR for end-of-line + fp.write(data) + if data[-1] <> '\r': fp.write('\r') + fp.close() + self.changed = 0 + + def menu_save_as(self): + path = EasyDialogs.AskFileForSave(message='Save as:') + if not path: return + self.path = path + self.name = os.path.split(self.path)[-1] + self.wid.SetWTitle(self.name) + self.menu_save() + + def menu_cut(self): + self.ted.WESelView() + if hasattr(Scrap, 'ZeroScrap'): + Scrap.ZeroScrap() + else: + Scrap.ClearCurrentScrap() + self.ted.WECut() + self.updatescrollbars() + self.parent.updatemenubar() + self.changed = 1 + + def menu_copy(self): + if hasattr(Scrap, 'ZeroScrap'): + Scrap.ZeroScrap() + else: + Scrap.ClearCurrentScrap() + self.ted.WECopy() + self.updatescrollbars() + self.parent.updatemenubar() + + def menu_paste(self): + self.ted.WESelView() + self.ted.WEPaste() + self.updatescrollbars() + self.parent.updatemenubar() + self.changed = 1 + + def menu_clear(self): + self.ted.WESelView() + self.ted.WEDelete() + self.updatescrollbars() + self.parent.updatemenubar() + self.changed = 1 + + def menu_undo(self): + self.ted.WEUndo() + self.updatescrollbars() + self.parent.updatemenubar() + + def have_selection(self): + start, stop = self.ted.WEGetSelection() + return start < stop + + def can_paste(self): + return self.ted.WECanPaste() + + def can_undo(self): + which, redo = self.ted.WEGetUndoInfo() + which = UNDOLABELS[which] + if which == None: return None + if redo: + return "Redo "+which + else: + return "Undo "+which class Wed(Application): - def __init__(self): - Application.__init__(self) - self.num = 0 - self.active = None - self.updatemenubar() - - def makeusermenus(self): - self.filemenu = m = Menu(self.menubar, "File") - self.newitem = MenuItem(m, "New window", "N", self.open) - self.openitem = MenuItem(m, "Open...", "O", self.openfile) - self.closeitem = MenuItem(m, "Close", "W", self.closewin) - m.addseparator() - self.saveitem = MenuItem(m, "Save", "S", self.save) - self.saveasitem = MenuItem(m, "Save as...", "", self.saveas) - m.addseparator() - self.quititem = MenuItem(m, "Quit", "Q", self.quit) - - self.editmenu = m = Menu(self.menubar, "Edit") - self.undoitem = MenuItem(m, "Undo", "Z", self.undo) - self.cutitem = MenuItem(m, "Cut", "X", self.cut) - self.copyitem = MenuItem(m, "Copy", "C", self.copy) - self.pasteitem = MenuItem(m, "Paste", "V", self.paste) - self.clearitem = MenuItem(m, "Clear", "", self.clear) - - # Groups of items enabled together: - self.windowgroup = [self.closeitem, self.saveitem, self.saveasitem, self.editmenu] - self.focusgroup = [self.cutitem, self.copyitem, self.clearitem] - self.windowgroup_on = -1 - self.focusgroup_on = -1 - self.pastegroup_on = -1 - self.undo_label = "never" - - def updatemenubar(self): - changed = 0 - on = (self.active <> None) - if on <> self.windowgroup_on: - for m in self.windowgroup: - m.enable(on) - self.windowgroup_on = on - changed = 1 - if on: - # only if we have an edit menu - on = self.active.have_selection() - if on <> self.focusgroup_on: - for m in self.focusgroup: - m.enable(on) - self.focusgroup_on = on - changed = 1 - on = self.active.can_paste() - if on <> self.pastegroup_on: - self.pasteitem.enable(on) - self.pastegroup_on = on - changed = 1 - on = self.active.can_undo() - if on <> self.undo_label: - if on: - self.undoitem.enable(1) - self.undoitem.settext(on) - self.undo_label = on - else: - self.undoitem.settext("Nothing to undo") - self.undoitem.enable(0) - changed = 1 - if changed: - DrawMenuBar() - - # - # Apple menu - # - - def do_about(self, id, item, window, event): - EasyDialogs.Message("A simple single-font text editor based on WASTE") - - # - # File menu - # - - def open(self, *args): - self._open(0) - - def openfile(self, *args): - self._open(1) - - def _open(self, askfile): - if askfile: - path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) - if not path: - return - name = os.path.split(path)[-1] - try: - fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line - data = fp.read() - fp.close() - except IOError, arg: - EasyDialogs.Message("IOERROR: %r" % (arg,)) - return - else: - path = None - name = "Untitled %d"%self.num - data = '' - w = WasteWindow(self) - w.open(path, name, data) - self.num = self.num + 1 - - def closewin(self, *args): - if self.active: - self.active.close() - else: - EasyDialogs.Message("No active window?") - - def save(self, *args): - if self.active: - self.active.menu_save() - else: - EasyDialogs.Message("No active window?") - - def saveas(self, *args): - if self.active: - self.active.menu_save_as() - else: - EasyDialogs.Message("No active window?") - - - def quit(self, *args): - for w in self._windows.values(): - w.close() - if self._windows: - return - self._quit() - - # - # Edit menu - # - - def undo(self, *args): - if self.active: - self.active.menu_undo() - else: - EasyDialogs.Message("No active window?") - - def cut(self, *args): - if self.active: - self.active.menu_cut() - else: - EasyDialogs.Message("No active window?") - - def copy(self, *args): - if self.active: - self.active.menu_copy() - else: - EasyDialogs.Message("No active window?") - - def paste(self, *args): - if self.active: - self.active.menu_paste() - else: - EasyDialogs.Message("No active window?") - - def clear(self, *args): - if self.active: - self.active.menu_clear() - else: - EasyDialogs.Message("No active window?") - - # - # Other stuff - # - - def idle(self, event): - if self.active: - self.active.do_idle(event) - else: - Qd.SetCursor(Qd.GetQDGlobalsArrow()) + def __init__(self): + Application.__init__(self) + self.num = 0 + self.active = None + self.updatemenubar() + + def makeusermenus(self): + self.filemenu = m = Menu(self.menubar, "File") + self.newitem = MenuItem(m, "New window", "N", self.open) + self.openitem = MenuItem(m, "Open...", "O", self.openfile) + self.closeitem = MenuItem(m, "Close", "W", self.closewin) + m.addseparator() + self.saveitem = MenuItem(m, "Save", "S", self.save) + self.saveasitem = MenuItem(m, "Save as...", "", self.saveas) + m.addseparator() + self.quititem = MenuItem(m, "Quit", "Q", self.quit) + + self.editmenu = m = Menu(self.menubar, "Edit") + self.undoitem = MenuItem(m, "Undo", "Z", self.undo) + self.cutitem = MenuItem(m, "Cut", "X", self.cut) + self.copyitem = MenuItem(m, "Copy", "C", self.copy) + self.pasteitem = MenuItem(m, "Paste", "V", self.paste) + self.clearitem = MenuItem(m, "Clear", "", self.clear) + + # Groups of items enabled together: + self.windowgroup = [self.closeitem, self.saveitem, self.saveasitem, self.editmenu] + self.focusgroup = [self.cutitem, self.copyitem, self.clearitem] + self.windowgroup_on = -1 + self.focusgroup_on = -1 + self.pastegroup_on = -1 + self.undo_label = "never" + + def updatemenubar(self): + changed = 0 + on = (self.active <> None) + if on <> self.windowgroup_on: + for m in self.windowgroup: + m.enable(on) + self.windowgroup_on = on + changed = 1 + if on: + # only if we have an edit menu + on = self.active.have_selection() + if on <> self.focusgroup_on: + for m in self.focusgroup: + m.enable(on) + self.focusgroup_on = on + changed = 1 + on = self.active.can_paste() + if on <> self.pastegroup_on: + self.pasteitem.enable(on) + self.pastegroup_on = on + changed = 1 + on = self.active.can_undo() + if on <> self.undo_label: + if on: + self.undoitem.enable(1) + self.undoitem.settext(on) + self.undo_label = on + else: + self.undoitem.settext("Nothing to undo") + self.undoitem.enable(0) + changed = 1 + if changed: + DrawMenuBar() + + # + # Apple menu + # + + def do_about(self, id, item, window, event): + EasyDialogs.Message("A simple single-font text editor based on WASTE") + + # + # File menu + # + + def open(self, *args): + self._open(0) + + def openfile(self, *args): + self._open(1) + + def _open(self, askfile): + if askfile: + path = EasyDialogs.AskFileForOpen(typeList=('TEXT',)) + if not path: + return + name = os.path.split(path)[-1] + try: + fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line + data = fp.read() + fp.close() + except IOError, arg: + EasyDialogs.Message("IOERROR: %r" % (arg,)) + return + else: + path = None + name = "Untitled %d"%self.num + data = '' + w = WasteWindow(self) + w.open(path, name, data) + self.num = self.num + 1 + + def closewin(self, *args): + if self.active: + self.active.close() + else: + EasyDialogs.Message("No active window?") + + def save(self, *args): + if self.active: + self.active.menu_save() + else: + EasyDialogs.Message("No active window?") + + def saveas(self, *args): + if self.active: + self.active.menu_save_as() + else: + EasyDialogs.Message("No active window?") + + + def quit(self, *args): + for w in self._windows.values(): + w.close() + if self._windows: + return + self._quit() + + # + # Edit menu + # + + def undo(self, *args): + if self.active: + self.active.menu_undo() + else: + EasyDialogs.Message("No active window?") + + def cut(self, *args): + if self.active: + self.active.menu_cut() + else: + EasyDialogs.Message("No active window?") + + def copy(self, *args): + if self.active: + self.active.menu_copy() + else: + EasyDialogs.Message("No active window?") + + def paste(self, *args): + if self.active: + self.active.menu_paste() + else: + EasyDialogs.Message("No active window?") + + def clear(self, *args): + if self.active: + self.active.menu_clear() + else: + EasyDialogs.Message("No active window?") + + # + # Other stuff + # + + def idle(self, event): + if self.active: + self.active.do_idle(event) + else: + Qd.SetCursor(Qd.GetQDGlobalsArrow()) def main(): - App = Wed() - App.mainloop() - + App = Wed() + App.mainloop() + if __name__ == '__main__': - main() - + main() diff --git a/Mac/IDE scripts/Widget demos/ActivateWindowDemo.py b/Mac/IDE scripts/Widget demos/ActivateWindowDemo.py index 3cd832b..d8fc946 100644 --- a/Mac/IDE scripts/Widget demos/ActivateWindowDemo.py +++ b/Mac/IDE scripts/Widget demos/ActivateWindowDemo.py @@ -4,18 +4,18 @@ import W # 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!" + + 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() diff --git a/Mac/IDE scripts/Widget demos/KeyTester.py b/Mac/IDE scripts/Widget demos/KeyTester.py index a9f3140..ae47550 100644 --- a/Mac/IDE scripts/Widget demos/KeyTester.py +++ b/Mac/IDE scripts/Widget demos/KeyTester.py @@ -4,12 +4,12 @@ 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) + 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() + window.close() # new window window = W.Dialog((180, 100), "Type a character") diff --git a/Mac/IDE scripts/Widget demos/ListWindow.py b/Mac/IDE scripts/Widget demos/ListWindow.py index ef066b9..f78b4b8 100644 --- a/Mac/IDE scripts/Widget demos/ListWindow.py +++ b/Mac/IDE scripts/Widget demos/ListWindow.py @@ -1,10 +1,10 @@ import W def listhit(isdbl): - if isdbl: - print "double-click in list!" - else: - print "click in list." + if isdbl: + print "double-click in list!" + else: + print "click in list." window = W.Window((200, 400), "Window with List", minsize = (150, 200)) diff --git a/Mac/IDE scripts/Widget demos/TwoLists.py b/Mac/IDE scripts/Widget demos/TwoLists.py index ee52c89..f1b58f2 100644 --- a/Mac/IDE scripts/Widget demos/TwoLists.py +++ b/Mac/IDE scripts/Widget demos/TwoLists.py @@ -1,16 +1,16 @@ import W def twothird(width, height): - return (8, 8, width - 8, 2*height/3 - 4) + return (8, 8, width - 8, 2*height/3 - 4) def onethird(width, height): - return (8, 2*height/3 + 4, width - 8, height - 22) + return (8, 2*height/3 + 4, width - 8, height - 22) def halfbounds1(width, height): - return (0, 0, width/2 - 4, height) + return (0, 0, width/2 - 4, height) def halfbounds2(width, height): - return (width/2 + 4, 0, width, height) + return (width/2 + 4, 0, width, height) window = W.Window((400, 400), "Sizable window with two lists", minsize = (200, 200)) diff --git a/Mac/IDE scripts/Widget demos/WidgetTest.py b/Mac/IDE scripts/Widget demos/WidgetTest.py index 424e70d..a2e8d08 100644 --- a/Mac/IDE scripts/Widget demos/WidgetTest.py +++ b/Mac/IDE scripts/Widget demos/WidgetTest.py @@ -2,34 +2,34 @@ import W # define some callbacks def callback(): - window.close() + window.close() def checkcallback(value): - print "hit the checkbox", value + print "hit the checkbox", value def radiocallback(value): - print "hit radiobutton #3", 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() + 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()) + window.et3.set(window.et1.get()) def cancel(): - import EasyDialogs - EasyDialogs.Message("Cancel!") + import EasyDialogs + EasyDialogs.Message("Cancel!") # make a non-sizable window #window = W.Window((200, 300), "Fixed Size") @@ -77,9 +77,9 @@ window.setdefaultbutton(window.button) 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) + import time + for i in range(20): + window.et2.set(repr(i)) + #window.et2.SetPort() + #window.et2.draw() + time.sleep(0.1) diff --git a/Mac/Modules/ae/aescan.py b/Mac/Modules/ae/aescan.py index 80c198c..1283c1d 100644 --- a/Mac/Modules/ae/aescan.py +++ b/Mac/Modules/ae/aescan.py @@ -13,87 +13,87 @@ sys.path.append(BGENDIR) from scantools import Scanner def main(): - print "=== Scanning AEDataModel.h, AppleEvents.h, AERegistry.h, AEObjects.h ===" - input = ["AEDataModel.h", "AEInteraction.h", "AppleEvents.h", "AERegistry.h", "AEObjects.h"] - output = "aegen.py" - defsoutput = TOOLBOXDIR + "AppleEvents.py" - scanner = AppleEventsScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done Scanning and Generating, now doing 'import aesupport' ===" - import aesupport - print "=== Done 'import aesupport'. It's up to you to compile AEmodule.c ===" + print "=== Scanning AEDataModel.h, AppleEvents.h, AERegistry.h, AEObjects.h ===" + input = ["AEDataModel.h", "AEInteraction.h", "AppleEvents.h", "AERegistry.h", "AEObjects.h"] + output = "aegen.py" + defsoutput = TOOLBOXDIR + "AppleEvents.py" + scanner = AppleEventsScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done Scanning and Generating, now doing 'import aesupport' ===" + import aesupport + print "=== Done 'import aesupport'. It's up to you to compile AEmodule.c ===" class AppleEventsScanner(Scanner): - def destination(self, type, name, arglist): - classname = "AEFunction" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t[-4:] == "_ptr" and m == "InMode" and \ - t[:-4] in ("AEDesc", "AEAddressDesc", "AEDescList", - "AERecord", "AppleEvent"): - classname = "AEMethod" - listname = "aedescmethods" - return classname, listname - - def makeblacklistnames(self): - return [ - "AEDisposeDesc", -# "AEGetEventHandler", - "AEGetDescData", # Use object.data - "AEGetSpecialHandler", - # Constants with funny definitions - "kAEDontDisposeOnResume", - "kAEUseStandardDispatch", - ] - - def makeblacklisttypes(self): - return [ - "ProcPtr", - "AEArrayType", - "AECoercionHandlerUPP", - "UniversalProcPtr", - "OSLCompareUPP", - "OSLAccessorUPP", - ] - - def makerepairinstructions(self): - return [ - ([("Boolean", "isSysHandler", "InMode")], - [("AlwaysFalse", "*", "*")]), - - ([("void_ptr", "*", "InMode"), ("Size", "*", "InMode")], - [("InBuffer", "*", "*")]), - - ([("EventHandlerProcPtr", "*", "InMode"), ("long", "*", "InMode")], - [("EventHandler", "*", "*")]), - - ([("EventHandlerProcPtr", "*", "OutMode"), ("long", "*", "OutMode")], - [("EventHandler", "*", "*")]), - - ([("AEEventHandlerUPP", "*", "InMode"), ("long", "*", "InMode")], - [("EventHandler", "*", "*")]), - - ([("AEEventHandlerUPP", "*", "OutMode"), ("long", "*", "OutMode")], - [("EventHandler", "*", "*")]), - - ([("void", "*", "OutMode"), ("Size", "*", "InMode"), - ("Size", "*", "OutMode")], - [("VarVarOutBuffer", "*", "InOutMode")]), - - ([("AppleEvent", "theAppleEvent", "OutMode")], - [("AppleEvent_ptr", "*", "InMode")]), - - ([("AEDescList", "theAEDescList", "OutMode")], - [("AEDescList_ptr", "*", "InMode")]), - ] - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + def destination(self, type, name, arglist): + classname = "AEFunction" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t[-4:] == "_ptr" and m == "InMode" and \ + t[:-4] in ("AEDesc", "AEAddressDesc", "AEDescList", + "AERecord", "AppleEvent"): + classname = "AEMethod" + listname = "aedescmethods" + return classname, listname + + def makeblacklistnames(self): + return [ + "AEDisposeDesc", +# "AEGetEventHandler", + "AEGetDescData", # Use object.data + "AEGetSpecialHandler", + # Constants with funny definitions + "kAEDontDisposeOnResume", + "kAEUseStandardDispatch", + ] + + def makeblacklisttypes(self): + return [ + "ProcPtr", + "AEArrayType", + "AECoercionHandlerUPP", + "UniversalProcPtr", + "OSLCompareUPP", + "OSLAccessorUPP", + ] + + def makerepairinstructions(self): + return [ + ([("Boolean", "isSysHandler", "InMode")], + [("AlwaysFalse", "*", "*")]), + + ([("void_ptr", "*", "InMode"), ("Size", "*", "InMode")], + [("InBuffer", "*", "*")]), + + ([("EventHandlerProcPtr", "*", "InMode"), ("long", "*", "InMode")], + [("EventHandler", "*", "*")]), + + ([("EventHandlerProcPtr", "*", "OutMode"), ("long", "*", "OutMode")], + [("EventHandler", "*", "*")]), + + ([("AEEventHandlerUPP", "*", "InMode"), ("long", "*", "InMode")], + [("EventHandler", "*", "*")]), + + ([("AEEventHandlerUPP", "*", "OutMode"), ("long", "*", "OutMode")], + [("EventHandler", "*", "*")]), + + ([("void", "*", "OutMode"), ("Size", "*", "InMode"), + ("Size", "*", "OutMode")], + [("VarVarOutBuffer", "*", "InOutMode")]), + + ([("AppleEvent", "theAppleEvent", "OutMode")], + [("AppleEvent_ptr", "*", "InMode")]), + + ([("AEDescList", "theAEDescList", "OutMode")], + [("AEDescList_ptr", "*", "InMode")]), + ] + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/ae/aesupport.py b/Mac/Modules/ae/aesupport.py index 17184db..91c5b82 100644 --- a/Mac/Modules/ae/aesupport.py +++ b/Mac/Modules/ae/aesupport.py @@ -39,29 +39,29 @@ AppleEvent_ptr = OpaqueType('AppleEvent', 'AEDesc') class EHType(Type): - def __init__(self, name = 'EventHandler', format = ''): - Type.__init__(self, name, format) - def declare(self, name): - Output("AEEventHandlerUPP %s__proc__ = upp_GenericEventHandler;", name) - Output("PyObject *%s;", name) - def getargsFormat(self): - return "O" - def getargsArgs(self, name): - return "&%s" % name - def passInput(self, name): - return "%s__proc__, (long)%s" % (name, name) - def passOutput(self, name): - return "&%s__proc__, (long *)&%s" % (name, name) - def mkvalueFormat(self): - return "O" - def mkvalueArgs(self, name): - return name - def cleanup(self, name): - Output("Py_INCREF(%s); /* XXX leak, but needed */", name) + def __init__(self, name = 'EventHandler', format = ''): + Type.__init__(self, name, format) + def declare(self, name): + Output("AEEventHandlerUPP %s__proc__ = upp_GenericEventHandler;", name) + Output("PyObject *%s;", name) + def getargsFormat(self): + return "O" + def getargsArgs(self, name): + return "&%s" % name + def passInput(self, name): + return "%s__proc__, (long)%s" % (name, name) + def passOutput(self, name): + return "&%s__proc__, (long *)&%s" % (name, name) + def mkvalueFormat(self): + return "O" + def mkvalueArgs(self, name): + return name + def cleanup(self, name): + Output("Py_INCREF(%s); /* XXX leak, but needed */", name) class EHNoRefConType(EHType): - def passInput(self, name): - return "upp_GenericEventHandler" + def passInput(self, name): + return "upp_GenericEventHandler" EventHandler = EHType() EventHandlerNoRefCon = EHNoRefConType() @@ -101,9 +101,9 @@ AEEventHandlerUPP upp_GenericEventHandler; static pascal Boolean AEIdleProc(EventRecord *theEvent, long *sleepTime, RgnHandle *mouseRgn) { - if ( PyOS_InterruptOccurred() ) - return 1; - return 0; + if ( PyOS_InterruptOccurred() ) + return 1; + return 0; } AEIdleUPP upp_AEIdleProc; @@ -113,99 +113,99 @@ finalstuff = finalstuff + """ static pascal OSErr GenericEventHandler(const AppleEvent *request, AppleEvent *reply, refcontype refcon) { - PyObject *handler = (PyObject *)refcon; - AEDescObject *requestObject, *replyObject; - PyObject *args, *res; - if ((requestObject = (AEDescObject *)AEDesc_New((AppleEvent *)request)) == NULL) { - return -1; - } - if ((replyObject = (AEDescObject *)AEDesc_New(reply)) == NULL) { - Py_DECREF(requestObject); - return -1; - } - if ((args = Py_BuildValue("OO", requestObject, replyObject)) == NULL) { - Py_DECREF(requestObject); - Py_DECREF(replyObject); - return -1; - } - res = PyEval_CallObject(handler, args); - requestObject->ob_itself.descriptorType = 'null'; - requestObject->ob_itself.dataHandle = NULL; - replyObject->ob_itself.descriptorType = 'null'; - replyObject->ob_itself.dataHandle = NULL; - Py_DECREF(args); - if (res == NULL) { - PySys_WriteStderr("Exception in AE event handler function\\n"); - PyErr_Print(); - return -1; - } - Py_DECREF(res); - return noErr; + PyObject *handler = (PyObject *)refcon; + AEDescObject *requestObject, *replyObject; + PyObject *args, *res; + if ((requestObject = (AEDescObject *)AEDesc_New((AppleEvent *)request)) == NULL) { + return -1; + } + if ((replyObject = (AEDescObject *)AEDesc_New(reply)) == NULL) { + Py_DECREF(requestObject); + return -1; + } + if ((args = Py_BuildValue("OO", requestObject, replyObject)) == NULL) { + Py_DECREF(requestObject); + Py_DECREF(replyObject); + return -1; + } + res = PyEval_CallObject(handler, args); + requestObject->ob_itself.descriptorType = 'null'; + requestObject->ob_itself.dataHandle = NULL; + replyObject->ob_itself.descriptorType = 'null'; + replyObject->ob_itself.dataHandle = NULL; + Py_DECREF(args); + if (res == NULL) { + PySys_WriteStderr("Exception in AE event handler function\\n"); + PyErr_Print(); + return -1; + } + Py_DECREF(res); + return noErr; } PyObject *AEDesc_NewBorrowed(AEDesc *itself) { - PyObject *it; - - it = AEDesc_New(itself); - if (it) - ((AEDescObject *)it)->ob_owned = 0; - return (PyObject *)it; + PyObject *it; + + it = AEDesc_New(itself); + if (it) + ((AEDescObject *)it)->ob_owned = 0; + return (PyObject *)it; } """ initstuff = initstuff + """ - upp_AEIdleProc = NewAEIdleUPP(AEIdleProc); - upp_GenericEventHandler = NewAEEventHandlerUPP(GenericEventHandler); - PyMac_INIT_TOOLBOX_OBJECT_NEW(AEDesc *, AEDesc_New); - PyMac_INIT_TOOLBOX_OBJECT_NEW(AEDesc *, AEDesc_NewBorrowed); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(AEDesc, AEDesc_Convert); + upp_AEIdleProc = NewAEIdleUPP(AEIdleProc); + upp_GenericEventHandler = NewAEEventHandlerUPP(GenericEventHandler); + PyMac_INIT_TOOLBOX_OBJECT_NEW(AEDesc *, AEDesc_New); + PyMac_INIT_TOOLBOX_OBJECT_NEW(AEDesc *, AEDesc_NewBorrowed); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(AEDesc, AEDesc_Convert); """ module = MacModule('_AE', 'AE', includestuff, finalstuff, initstuff) class AEDescDefinition(PEP253Mixin, GlobalObjectDefinition): - getsetlist = [( - 'type', - 'return PyMac_BuildOSType(self->ob_itself.descriptorType);', - None, - 'Type of this AEDesc' - ), ( - 'data', - """ - PyObject *res; - Size size; - char *ptr; - OSErr err; - - size = AEGetDescDataSize(&self->ob_itself); - if ( (res = PyString_FromStringAndSize(NULL, size)) == NULL ) - return NULL; - if ( (ptr = PyString_AsString(res)) == NULL ) - return NULL; - if ( (err=AEGetDescData(&self->ob_itself, ptr, size)) < 0 ) - return PyMac_Error(err); - return res; - """, - None, - 'The raw data in this AEDesc' - )] - - def __init__(self, name, prefix = None, itselftype = None): - GlobalObjectDefinition.__init__(self, name, prefix or name, itselftype or name) - self.argref = "*" - - def outputStructMembers(self): - GlobalObjectDefinition.outputStructMembers(self) - Output("int ob_owned;") - - def outputInitStructMembers(self): - GlobalObjectDefinition.outputInitStructMembers(self) - Output("it->ob_owned = 1;") - - def outputCleanupStructMembers(self): - Output("if (self->ob_owned) AEDisposeDesc(&self->ob_itself);") + getsetlist = [( + 'type', + 'return PyMac_BuildOSType(self->ob_itself.descriptorType);', + None, + 'Type of this AEDesc' + ), ( + 'data', + """ + PyObject *res; + Size size; + char *ptr; + OSErr err; + + size = AEGetDescDataSize(&self->ob_itself); + if ( (res = PyString_FromStringAndSize(NULL, size)) == NULL ) + return NULL; + if ( (ptr = PyString_AsString(res)) == NULL ) + return NULL; + if ( (err=AEGetDescData(&self->ob_itself, ptr, size)) < 0 ) + return PyMac_Error(err); + return res; + """, + None, + 'The raw data in this AEDesc' + )] + + def __init__(self, name, prefix = None, itselftype = None): + GlobalObjectDefinition.__init__(self, name, prefix or name, itselftype or name) + self.argref = "*" + + def outputStructMembers(self): + GlobalObjectDefinition.outputStructMembers(self) + Output("int ob_owned;") + + def outputInitStructMembers(self): + GlobalObjectDefinition.outputInitStructMembers(self) + Output("it->ob_owned = 1;") + + def outputCleanupStructMembers(self): + Output("if (self->ob_owned) AEDisposeDesc(&self->ob_itself);") aedescobject = AEDescDefinition('AEDesc') module.addobject(aedescobject) diff --git a/Mac/Modules/ah/ahscan.py b/Mac/Modules/ah/ahscan.py index cced19f..0b7fe08 100644 --- a/Mac/Modules/ah/ahscan.py +++ b/Mac/Modules/ah/ahscan.py @@ -11,42 +11,42 @@ SHORT = "ah" OBJECT = "NOTUSED" def main(): - input = LONG + ".h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = LONG + ".h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner_OSX): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - # This is non-functional today - if t == OBJECT and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname - - def makeblacklistnames(self): - return [ - ] - - def makeblacklisttypes(self): - return [ - ] - - def makerepairinstructions(self): - return [ - ] - + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + # This is non-functional today + if t == OBJECT and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname + + def makeblacklistnames(self): + return [ + ] + + def makeblacklisttypes(self): + return [ + ] + + def makerepairinstructions(self): + return [ + ] + if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/ah/ahsupport.py b/Mac/Modules/ah/ahsupport.py index c91c298..c5f24be 100644 --- a/Mac/Modules/ah/ahsupport.py +++ b/Mac/Modules/ah/ahsupport.py @@ -6,13 +6,13 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'AppleHelp.h' # The Apple header file -MODNAME = '_AH' # The name of the module +MACHEADERFILE = 'AppleHelp.h' # The Apple header file +MODNAME = '_AH' # The name of the module # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Ah' # The prefix for module-wide routines +MODPREFIX = 'Ah' # The prefix for module-wide routines INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -43,4 +43,3 @@ for f in functions: module.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/app/appscan.py b/Mac/Modules/app/appscan.py index 822651d..1b04859 100644 --- a/Mac/Modules/app/appscan.py +++ b/Mac/Modules/app/appscan.py @@ -11,71 +11,71 @@ SHORT = "app" OBJECT = "ThemeDrawingState" def main(): - input = LONG + ".h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = LONG + ".h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - # This is non-functional today - if t == OBJECT and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + # This is non-functional today + if t == OBJECT and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - def makeblacklistnames(self): - return [ - "GetThemeFont", # Funny stringbuffer in/out parameter, I think... - # Constants with funny definitions - "appearanceBadBrushIndexErr", - "appearanceProcessRegisteredErr", - "appearanceProcessNotRegisteredErr", - "appearanceBadTextColorIndexErr", - "appearanceThemeHasNoAccents", - "appearanceBadCursorIndexErr", - ] + def makeblacklistnames(self): + return [ + "GetThemeFont", # Funny stringbuffer in/out parameter, I think... + # Constants with funny definitions + "appearanceBadBrushIndexErr", + "appearanceProcessRegisteredErr", + "appearanceProcessNotRegisteredErr", + "appearanceBadTextColorIndexErr", + "appearanceThemeHasNoAccents", + "appearanceBadCursorIndexErr", + ] - def makeblacklisttypes(self): - return [ - "MenuTitleDrawingUPP", - "MenuItemDrawingUPP", - "ThemeIteratorUPP", - "ThemeTabTitleDrawUPP", -# "ThemeEraseUPP", -# "ThemeButtonDrawUPP", - "WindowTitleDrawingUPP", - "ProcessSerialNumber_ptr", # Too much work for now. - "ThemeTrackDrawInfo_ptr", # Too much work -# "ThemeButtonDrawInfo_ptr", # ditto - "ThemeWindowMetrics_ptr", # ditto -# "ThemeDrawingState", # This is an opaque pointer, so it should be simple. Later. - "Collection", # No interface to collection mgr yet. - "BytePtr", # Not yet. - ] + def makeblacklisttypes(self): + return [ + "MenuTitleDrawingUPP", + "MenuItemDrawingUPP", + "ThemeIteratorUPP", + "ThemeTabTitleDrawUPP", +# "ThemeEraseUPP", +# "ThemeButtonDrawUPP", + "WindowTitleDrawingUPP", + "ProcessSerialNumber_ptr", # Too much work for now. + "ThemeTrackDrawInfo_ptr", # Too much work +# "ThemeButtonDrawInfo_ptr", # ditto + "ThemeWindowMetrics_ptr", # ditto +# "ThemeDrawingState", # This is an opaque pointer, so it should be simple. Later. + "Collection", # No interface to collection mgr yet. + "BytePtr", # Not yet. + ] + + def makerepairinstructions(self): + return [ + ([("void", 'inContext', "OutMode")], + [("NULL", 'inContext', "InMode")]), + ([("Point", 'ioBounds', "OutMode")], + [("Point", 'ioBounds', "InOutMode")]), + ] - def makerepairinstructions(self): - return [ - ([("void", 'inContext', "OutMode")], - [("NULL", 'inContext', "InMode")]), - ([("Point", 'ioBounds', "OutMode")], - [("Point", 'ioBounds', "InOutMode")]), - ] - if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/app/appsupport.py b/Mac/Modules/app/appsupport.py index a9d8768..177dfd5 100644 --- a/Mac/Modules/app/appsupport.py +++ b/Mac/Modules/app/appsupport.py @@ -6,17 +6,17 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Appearance.h' # The Apple header file -MODNAME = '_App' # The name of the module -OBJECTNAME = 'ThemeDrawingState' # The basic name of the objects used here -KIND = '' # Usually 'Ptr' or 'Handle' +MACHEADERFILE = 'Appearance.h' # The Apple header file +MODNAME = '_App' # The name of the module +OBJECTNAME = 'ThemeDrawingState' # The basic name of the objects used here +KIND = '' # Usually 'Ptr' or 'Handle' # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'App' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + KIND # The C type used to represent them -OBJECTPREFIX = OBJECTNAME + 'Obj' # The prefix for object methods +MODPREFIX = 'App' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + KIND # The C type used to represent them +OBJECTPREFIX = OBJECTNAME + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -84,24 +84,24 @@ includestuff = includestuff + """ int ThemeButtonDrawInfo_Convert(PyObject *v, ThemeButtonDrawInfo *p_itself) { - return PyArg_Parse(v, "(iHH)", &p_itself->state, &p_itself->value, &p_itself->adornment); + return PyArg_Parse(v, "(iHH)", &p_itself->state, &p_itself->value, &p_itself->adornment); } """ class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - pass -## def outputCheckNewArg(self): -## Output("if (itself == NULL) return PyMac_Error(resNotFound);") -## def outputCheckConvertArg(self): -## OutLbrace("if (DlgObj_Check(v))") -## Output("*p_itself = ((WindowObject *)v)->ob_itself;") -## Output("return 1;") -## OutRbrace() -## Out(""" -## if (v == Py_None) { *p_itself = NULL; return 1; } -## if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; } -## """) + pass +## def outputCheckNewArg(self): +## Output("if (itself == NULL) return PyMac_Error(resNotFound);") +## def outputCheckConvertArg(self): +## OutLbrace("if (DlgObj_Check(v))") +## Output("*p_itself = ((WindowObject *)v)->ob_itself;") +## Output("return 1;") +## OutRbrace() +## Out(""" +## if (v == Py_None) { *p_itself = NULL; return 1; } +## if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; } +## """) # From here on it's basically all boiler plate... @@ -131,4 +131,3 @@ for f in methods: object.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/carbonevt/CarbonEvtscan.py b/Mac/Modules/carbonevt/CarbonEvtscan.py index c6bf93f..e3c72ae 100644 --- a/Mac/Modules/carbonevt/CarbonEvtscan.py +++ b/Mac/Modules/carbonevt/CarbonEvtscan.py @@ -12,106 +12,106 @@ sys.path.append(BGENDIR) from scantools import Scanner, Scanner_OSX def main(): - print "---Scanning CarbonEvents.h---" - input = ["CarbonEvents.h"] - output = "CarbonEventsgen.py" - defsoutput = TOOLBOXDIR + "CarbonEvents.py" - scanner = CarbonEvents_Scanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "--done scanning, importing--" - import CarbonEvtsupport - print "done" + print "---Scanning CarbonEvents.h---" + input = ["CarbonEvents.h"] + output = "CarbonEventsgen.py" + defsoutput = TOOLBOXDIR + "CarbonEvents.py" + scanner = CarbonEvents_Scanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "--done scanning, importing--" + import CarbonEvtsupport + print "done" -RefObjectTypes = ["EventRef", - "EventQueueRef", - "EventLoopRef", - "EventLoopTimerRef", - "EventHandlerRef", - "EventHandlerCallRef", - "EventTargetRef", - "EventHotKeyRef", - ] +RefObjectTypes = ["EventRef", + "EventQueueRef", + "EventLoopRef", + "EventLoopTimerRef", + "EventHandlerRef", + "EventHandlerCallRef", + "EventTargetRef", + "EventHotKeyRef", + ] class CarbonEvents_Scanner(Scanner_OSX): - def destination(self, type, name, arglist): - classname = "CarbonEventsFunction" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t in RefObjectTypes and m == "InMode": - if t == "EventHandlerRef": - classname = "EventHandlerRefMethod" - else: - classname = "CarbonEventsMethod" - listname = t + "methods" - #else: - # print "not method" - return classname, listname + def destination(self, type, name, arglist): + classname = "CarbonEventsFunction" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t in RefObjectTypes and m == "InMode": + if t == "EventHandlerRef": + classname = "EventHandlerRefMethod" + else: + classname = "CarbonEventsMethod" + listname = t + "methods" + #else: + # print "not method" + return classname, listname - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("false = 0\n") - self.defsfile.write("true = 1\n") - self.defsfile.write("keyAEEventClass = FOUR_CHAR_CODE('evcl')\n") - self.defsfile.write("keyAEEventID = FOUR_CHAR_CODE('evti')\n") - - def makeblacklistnames(self): - return [ - "sHandler", - "MacCreateEvent", -# "TrackMouseLocationWithOptions", -# "TrackMouseLocation", -# "TrackMouseRegion", - "RegisterToolboxObjectClass", - "UnregisterToolboxObjectClass", - "ProcessHICommand", - "GetCFRunLoopFromEventLoop", - - "InvokeEventHandlerUPP", - "InvokeEventComparatorUPP", - "InvokeEventLoopTimerUPP", - "NewEventComparatorUPP", - "NewEventLoopTimerUPP", - "NewEventHandlerUPP", - "DisposeEventComparatorUPP", - "DisposeEventLoopTimerUPP", - "DisposeEventHandlerUPP", + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("false = 0\n") + self.defsfile.write("true = 1\n") + self.defsfile.write("keyAEEventClass = FOUR_CHAR_CODE('evcl')\n") + self.defsfile.write("keyAEEventID = FOUR_CHAR_CODE('evti')\n") - # Wrote by hand - "InstallEventHandler", - "RemoveEventHandler", - - # Write by hand? - "GetEventParameter", - "FlushSpecificEventsFromQueue", - "FindSpecificEventInQueue", - "InstallEventLoopTimer", + def makeblacklistnames(self): + return [ + "sHandler", + "MacCreateEvent", +# "TrackMouseLocationWithOptions", +# "TrackMouseLocation", +# "TrackMouseRegion", + "RegisterToolboxObjectClass", + "UnregisterToolboxObjectClass", + "ProcessHICommand", + "GetCFRunLoopFromEventLoop", - # Don't do these because they require a CFRelease - "CreateTypeStringWithOSType", - "CopyEvent", - ] + "InvokeEventHandlerUPP", + "InvokeEventComparatorUPP", + "InvokeEventLoopTimerUPP", + "NewEventComparatorUPP", + "NewEventLoopTimerUPP", + "NewEventHandlerUPP", + "DisposeEventComparatorUPP", + "DisposeEventLoopTimerUPP", + "DisposeEventHandlerUPP", -# def makeblacklisttypes(self): -# return ["EventComparatorUPP", -# "EventLoopTimerUPP", -# #"EventHandlerUPP", -# "EventComparatorProcPtr", -# "EventLoopTimerProcPtr", -# "EventHandlerProcPtr", -# ] + # Wrote by hand + "InstallEventHandler", + "RemoveEventHandler", - def makerepairinstructions(self): - return [ - ([("UInt32", 'inSize', "InMode"), ("void_ptr", 'inDataPtr', "InMode")], - [("MyInBuffer", 'inDataPtr', "InMode")]), - ([("Boolean", 'ioWasInRgn', "OutMode")], - [("Boolean", 'ioWasInRgn', "InOutMode")]), - ] + # Write by hand? + "GetEventParameter", + "FlushSpecificEventsFromQueue", + "FindSpecificEventInQueue", + "InstallEventLoopTimer", + + # Don't do these because they require a CFRelease + "CreateTypeStringWithOSType", + "CopyEvent", + ] + +# def makeblacklisttypes(self): +# return ["EventComparatorUPP", +# "EventLoopTimerUPP", +# #"EventHandlerUPP", +# "EventComparatorProcPtr", +# "EventLoopTimerProcPtr", +# "EventHandlerProcPtr", +# ] + + def makerepairinstructions(self): + return [ + ([("UInt32", 'inSize', "InMode"), ("void_ptr", 'inDataPtr', "InMode")], + [("MyInBuffer", 'inDataPtr', "InMode")]), + ([("Boolean", 'ioWasInRgn', "OutMode")], + [("Boolean", 'ioWasInRgn', "InOutMode")]), + ] if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/carbonevt/CarbonEvtsupport.py b/Mac/Modules/carbonevt/CarbonEvtsupport.py index 3cc1672..77d12b6 100644 --- a/Mac/Modules/carbonevt/CarbonEvtsupport.py +++ b/Mac/Modules/carbonevt/CarbonEvtsupport.py @@ -8,23 +8,23 @@ from CarbonEvtscan import RefObjectTypes CFStringRef = OpaqueByValueType('CFStringRef') for typ in RefObjectTypes: - execstr = "%(name)s = OpaqueByValueType('%(name)s')" % {"name": typ} - exec execstr + execstr = "%(name)s = OpaqueByValueType('%(name)s')" % {"name": typ} + exec execstr if 0: - # these types will have no methods and will merely be opaque blobs - # should write getattr and setattr for them? + # these types will have no methods and will merely be opaque blobs + # should write getattr and setattr for them? - StructObjectTypes = ["EventTypeSpec", - "HIPoint", - "HICommand", - "EventHotKeyID", - ] + StructObjectTypes = ["EventTypeSpec", + "HIPoint", + "HICommand", + "EventHotKeyID", + ] - for typ in StructObjectTypes: - execstr = "%(name)s = OpaqueType('%(name)s')" % {"name": typ} - exec execstr + for typ in StructObjectTypes: + execstr = "%(name)s = OpaqueType('%(name)s')" % {"name": typ} + exec execstr EventHotKeyID = OpaqueByValueType("EventHotKeyID", "EventHotKeyID") EventTypeSpec_ptr = OpaqueType("EventTypeSpec", "EventTypeSpec") @@ -35,10 +35,10 @@ void_ptr = stringptr # here are some types that are really other types class MyVarInputBufferType(VarInputBufferType): - def passInput(self, name): - return "%s__len__, %s__in__" % (name, name) + def passInput(self, name): + return "%s__len__, %s__in__" % (name, name) -MyInBuffer = MyVarInputBufferType('char', 'long', 'l') # (buf, len) +MyInBuffer = MyVarInputBufferType('char', 'long', 'l') # (buf, len) EventTime = double EventTimeout = EventTime @@ -61,11 +61,11 @@ CarbonEventsFunction = OSErrFunctionGenerator CarbonEventsMethod = OSErrMethodGenerator class EventHandlerRefMethod(OSErrMethodGenerator): - def precheck(self): - OutLbrace('if (_self->ob_itself == NULL)') - Output('PyErr_SetString(CarbonEvents_Error, "Handler has been removed");') - Output('return NULL;') - OutRbrace() + def precheck(self): + OutLbrace('if (_self->ob_itself == NULL)') + Output('PyErr_SetString(CarbonEvents_Error, "Handler has been removed");') + Output('return NULL;') + OutRbrace() RgnHandle = OpaqueByValueType("RgnHandle", "ResObj") @@ -89,17 +89,17 @@ PyObject *EventRef_New(EventRef itself); static PyObject* EventTypeSpec_New(EventTypeSpec *in) { - return Py_BuildValue("ll", in->eventClass, in->eventKind); + return Py_BuildValue("ll", in->eventClass, in->eventKind); } static int EventTypeSpec_Convert(PyObject *v, EventTypeSpec *out) { - if (PyArg_Parse(v, "(O&l)", - PyMac_GetOSType, &(out->eventClass), - &(out->eventKind))) - return 1; - return NULL; + if (PyArg_Parse(v, "(O&l)", + PyMac_GetOSType, &(out->eventClass), + &(out->eventKind))) + return 1; + return NULL; } /********** end EventTypeSpec *******/ @@ -110,15 +110,15 @@ EventTypeSpec_Convert(PyObject *v, EventTypeSpec *out) static PyObject* HIPoint_New(HIPoint *in) { - return Py_BuildValue("ff", in->x, in->y); + return Py_BuildValue("ff", in->x, in->y); } static int HIPoint_Convert(PyObject *v, HIPoint *out) { - if (PyArg_ParseTuple(v, "ff", &(out->x), &(out->y))) - return 1; - return NULL; + if (PyArg_ParseTuple(v, "ff", &(out->x), &(out->y))) + return 1; + return NULL; } #endif @@ -129,15 +129,15 @@ HIPoint_Convert(PyObject *v, HIPoint *out) static PyObject* EventHotKeyID_New(EventHotKeyID *in) { - return Py_BuildValue("ll", in->signature, in->id); + return Py_BuildValue("ll", in->signature, in->id); } static int EventHotKeyID_Convert(PyObject *v, EventHotKeyID *out) { - if (PyArg_ParseTuple(v, "ll", &out->signature, &out->id)) - return 1; - return NULL; + if (PyArg_ParseTuple(v, "ll", &out->signature, &out->id)) + return 1; + return NULL; } /********** end EventHotKeyID *******/ @@ -148,27 +148,27 @@ static EventHandlerUPP myEventHandlerUPP; static pascal OSStatus myEventHandler(EventHandlerCallRef handlerRef, EventRef event, void *outPyObject) { - PyObject *retValue; - int status; - - retValue = PyObject_CallFunction((PyObject *)outPyObject, "O&O&", - EventHandlerCallRef_New, handlerRef, - EventRef_New, event); - if (retValue == NULL) { - PySys_WriteStderr("Error in event handler callback:\n"); - PyErr_Print(); /* this also clears the error */ - status = noErr; /* complain? how? */ - } else { - if (retValue == Py_None) - status = noErr; - else if (PyInt_Check(retValue)) { - status = PyInt_AsLong(retValue); - } else - status = noErr; /* wrong object type, complain? */ - Py_DECREF(retValue); - } - - return status; + PyObject *retValue; + int status; + + retValue = PyObject_CallFunction((PyObject *)outPyObject, "O&O&", + EventHandlerCallRef_New, handlerRef, + EventRef_New, event); + if (retValue == NULL) { + PySys_WriteStderr("Error in event handler callback:\n"); + PyErr_Print(); /* this also clears the error */ + status = noErr; /* complain? how? */ + } else { + if (retValue == Py_None) + status = noErr; + else if (PyInt_Check(retValue)) { + status = PyInt_AsLong(retValue); + } else + status = noErr; /* wrong object type, complain? */ + Py_DECREF(retValue); + } + + return status; } /******** end myEventHandler ***********/ @@ -184,56 +184,56 @@ module = MacModule('_CarbonEvt', 'CarbonEvents', includestuff, finalstuff, inits class EventHandlerRefObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputStructMembers(self): - Output("%s ob_itself;", self.itselftype) - Output("PyObject *ob_callback;") - def outputInitStructMembers(self): - Output("it->ob_itself = %sitself;", self.argref) - Output("it->ob_callback = NULL;") - def outputFreeIt(self, name): - OutLbrace("if (self->ob_itself != NULL)") - Output("RemoveEventHandler(self->ob_itself);") - Output("Py_DECREF(self->ob_callback);") - OutRbrace() - + def outputStructMembers(self): + Output("%s ob_itself;", self.itselftype) + Output("PyObject *ob_callback;") + def outputInitStructMembers(self): + Output("it->ob_itself = %sitself;", self.argref) + Output("it->ob_callback = NULL;") + def outputFreeIt(self, name): + OutLbrace("if (self->ob_itself != NULL)") + Output("RemoveEventHandler(self->ob_itself);") + Output("Py_DECREF(self->ob_callback);") + OutRbrace() + class MyGlobalObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - pass + pass for typ in RefObjectTypes: - if typ == 'EventHandlerRef': - EventHandlerRefobject = EventHandlerRefObjectDefinition('EventHandlerRef') - else: - execstr = typ + 'object = MyGlobalObjectDefinition(typ)' - exec execstr - module.addobject(eval(typ + 'object')) + if typ == 'EventHandlerRef': + EventHandlerRefobject = EventHandlerRefObjectDefinition('EventHandlerRef') + else: + execstr = typ + 'object = MyGlobalObjectDefinition(typ)' + exec execstr + module.addobject(eval(typ + 'object')) functions = [] for typ in RefObjectTypes: ## go thru all ObjectTypes as defined in CarbonEventsscan.py - # initialize the lists for carbongen to fill - execstr = typ + 'methods = []' - exec execstr + # initialize the lists for carbongen to fill + execstr = typ + 'methods = []' + exec execstr execfile('CarbonEventsgen.py') -for f in functions: module.add(f) # add all the functions carboneventsgen put in the list +for f in functions: module.add(f) # add all the functions carboneventsgen put in the list -for typ in RefObjectTypes: ## go thru all ObjectTypes as defined in CarbonEventsscan.py - methods = eval(typ + 'methods') ## get a reference to the method list from the main namespace - obj = eval(typ + 'object') ## get a reference to the object - for m in methods: obj.add(m) ## add each method in the list to the object +for typ in RefObjectTypes: ## go thru all ObjectTypes as defined in CarbonEventsscan.py + methods = eval(typ + 'methods') ## get a reference to the method list from the main namespace + obj = eval(typ + 'object') ## get a reference to the object + for m in methods: obj.add(m) ## add each method in the list to the object removeeventhandler = """ OSStatus _err; if (_self->ob_itself == NULL) { - PyErr_SetString(CarbonEvents_Error, "Handler has been removed"); - return NULL; + PyErr_SetString(CarbonEvents_Error, "Handler has been removed"); + return NULL; } if (!PyArg_ParseTuple(_args, "")) - return NULL; + return NULL; _err = RemoveEventHandler(_self->ob_itself); if (_err != noErr) return PyMac_Error(_err); _self->ob_itself = NULL; @@ -255,15 +255,15 @@ EventHandlerRef outRef; OSStatus _err; if (!PyArg_ParseTuple(_args, "O&O", EventTypeSpec_Convert, &inSpec, &callback)) - return NULL; + return NULL; _err = InstallEventHandler(_self->ob_itself, myEventHandlerUPP, 1, &inSpec, (void *)callback, &outRef); if (_err != noErr) return PyMac_Error(_err); _res = EventHandlerRef_New(outRef); if (_res != NULL) { - ((EventHandlerRefObject*)_res)->ob_callback = callback; - Py_INCREF(callback); + ((EventHandlerRefObject*)_res)->ob_callback = callback; + Py_INCREF(callback); } return _res;""" diff --git a/Mac/Modules/cf/cfscan.py b/Mac/Modules/cf/cfscan.py index aa0ea3d..d2de92e 100644 --- a/Mac/Modules/cf/cfscan.py +++ b/Mac/Modules/cf/cfscan.py @@ -8,135 +8,135 @@ from scantools import Scanner_OSX LONG = "CoreFoundation" SHORT = "cf" -OBJECTS = ("CFTypeRef", - "CFArrayRef", "CFMutableArrayRef", - "CFDataRef", "CFMutableDataRef", - "CFDictionaryRef", "CFMutableDictionaryRef", - "CFStringRef", "CFMutableStringRef", - "CFURLRef", -## "CFPropertyListRef", - ) +OBJECTS = ("CFTypeRef", + "CFArrayRef", "CFMutableArrayRef", + "CFDataRef", "CFMutableDataRef", + "CFDictionaryRef", "CFMutableDictionaryRef", + "CFStringRef", "CFMutableStringRef", + "CFURLRef", +## "CFPropertyListRef", + ) # ADD object typenames here def main(): - input = [ - "CFBase.h", - "CFArray.h", -## "CFBag.h", -## "CFBundle.h", -## "CFCharacterSet.h", - "CFData.h", -## "CFDate.h", - "CFDictionary.h", -## "CFNumber.h", -## "CFPlugIn.h", - "CFPreferences.h", - "CFPropertyList.h", -## "CFSet.h", - "CFString.h", -## "CFStringEncodingExt.h", -## "CFTimeZone.h", - "CFURL.h", - ] - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.gentypetest(SHORT+"typetest.py") - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = [ + "CFBase.h", + "CFArray.h", +## "CFBag.h", +## "CFBundle.h", +## "CFCharacterSet.h", + "CFData.h", +## "CFDate.h", + "CFDictionary.h", +## "CFNumber.h", +## "CFPlugIn.h", + "CFPreferences.h", + "CFPropertyList.h", +## "CFSet.h", + "CFString.h", +## "CFStringEncodingExt.h", +## "CFTimeZone.h", + "CFURL.h", + ] + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.gentypetest(SHORT+"typetest.py") + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner_OSX): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist and name[:13] != 'CFPreferences': - t, n, m = arglist[0] - if t in OBJECTS and m == "InMode": - classname = "Method" - listname = t + "_methods" - # Special case for the silly first AllocatorRef argument - if t == 'CFAllocatorRef' and m == 'InMode' and len(arglist) > 1: - t, n, m = arglist[1] - if t in OBJECTS and m == "InMode": - classname = "MethodSkipArg1" - listname = t + "_methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist and name[:13] != 'CFPreferences': + t, n, m = arglist[0] + if t in OBJECTS and m == "InMode": + classname = "Method" + listname = t + "_methods" + # Special case for the silly first AllocatorRef argument + if t == 'CFAllocatorRef' and m == 'InMode' and len(arglist) > 1: + t, n, m = arglist[1] + if t in OBJECTS and m == "InMode": + classname = "MethodSkipArg1" + listname = t + "_methods" + return classname, listname - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - def makeblacklistnames(self): - return [ - # Memory allocator functions - "CFAllocatorGetDefault", - "CFAllocatorSetDefault", - "CFAllocatorAllocate", - "CFAllocatorReallocate", - "CFAllocatorDeallocate", - "CFGetAllocator", - # Array functions we skip for now. - "CFArrayGetValueAtIndex", - # Data pointer functions. Skip for now. - "CFDataGetBytePtr", - "CFDataGetMutableBytePtr", - "CFDataGetBytes", # XXXX Should support this one - # String functions - "CFStringGetPascalString", # Use the C-string methods. - "CFStringGetPascalStringPtr", # TBD automatically - "CFStringGetCStringPtr", - "CFStringGetCharactersPtr", - "CFStringGetCString", - "CFStringGetCharacters", - "CFURLCreateStringWithFileSystemPath", # Gone in later releases - "CFStringCreateMutableWithExternalCharactersNoCopy", # Not a clue... - "CFStringSetExternalCharactersNoCopy", - "CFStringGetCharacterAtIndex", # No format for single unichars yet. - "kCFStringEncodingInvalidId", # incompatible constant declaration - "CFPropertyListCreateFromXMLData", # Manually generated - ] + def makeblacklistnames(self): + return [ + # Memory allocator functions + "CFAllocatorGetDefault", + "CFAllocatorSetDefault", + "CFAllocatorAllocate", + "CFAllocatorReallocate", + "CFAllocatorDeallocate", + "CFGetAllocator", + # Array functions we skip for now. + "CFArrayGetValueAtIndex", + # Data pointer functions. Skip for now. + "CFDataGetBytePtr", + "CFDataGetMutableBytePtr", + "CFDataGetBytes", # XXXX Should support this one + # String functions + "CFStringGetPascalString", # Use the C-string methods. + "CFStringGetPascalStringPtr", # TBD automatically + "CFStringGetCStringPtr", + "CFStringGetCharactersPtr", + "CFStringGetCString", + "CFStringGetCharacters", + "CFURLCreateStringWithFileSystemPath", # Gone in later releases + "CFStringCreateMutableWithExternalCharactersNoCopy", # Not a clue... + "CFStringSetExternalCharactersNoCopy", + "CFStringGetCharacterAtIndex", # No format for single unichars yet. + "kCFStringEncodingInvalidId", # incompatible constant declaration + "CFPropertyListCreateFromXMLData", # Manually generated + ] - def makegreylist(self): - return [] + def makegreylist(self): + return [] - def makeblacklisttypes(self): - return [ - "CFComparatorFunction", # Callback function pointer - "CFAllocatorContext", # Not interested in providing our own allocator - "void_ptr_ptr", # Tricky. This is the initializer for arrays... - "void_ptr", # Ditto for various array lookup methods - "CFArrayApplierFunction", # Callback function pointer - "CFDictionaryApplierFunction", # Callback function pointer - "va_list", # For printf-to-a-cfstring. Use Python. - "const_CFStringEncoding_ptr", # To be done, I guess - ] + def makeblacklisttypes(self): + return [ + "CFComparatorFunction", # Callback function pointer + "CFAllocatorContext", # Not interested in providing our own allocator + "void_ptr_ptr", # Tricky. This is the initializer for arrays... + "void_ptr", # Ditto for various array lookup methods + "CFArrayApplierFunction", # Callback function pointer + "CFDictionaryApplierFunction", # Callback function pointer + "va_list", # For printf-to-a-cfstring. Use Python. + "const_CFStringEncoding_ptr", # To be done, I guess + ] - def makerepairinstructions(self): - return [ - # Buffers in CF seem to be passed as UInt8 * normally. - ([("UInt8_ptr", "*", "InMode"), ("CFIndex", "*", "InMode")], - [("UcharInBuffer", "*", "*")]), - - ([("UniChar_ptr", "*", "InMode"), ("CFIndex", "*", "InMode")], - [("UnicodeInBuffer", "*", "*")]), + def makerepairinstructions(self): + return [ + # Buffers in CF seem to be passed as UInt8 * normally. + ([("UInt8_ptr", "*", "InMode"), ("CFIndex", "*", "InMode")], + [("UcharInBuffer", "*", "*")]), + + ([("UniChar_ptr", "*", "InMode"), ("CFIndex", "*", "InMode")], + [("UnicodeInBuffer", "*", "*")]), + + # Some functions return a const char *. Don't worry, we won't modify it. + ([("const_char_ptr", "*", "ReturnMode")], + [("return_stringptr", "*", "*")]), + + # base URLs are optional (pass None for NULL) + ([("CFURLRef", "baseURL", "InMode")], + [("OptionalCFURLRef", "*", "*")]), + + # We handle CFPropertyListRef objects as plain CFTypeRef + ([("CFPropertyListRef", "*", "*")], + [("CFTypeRef", "*", "*")]), + ] - # Some functions return a const char *. Don't worry, we won't modify it. - ([("const_char_ptr", "*", "ReturnMode")], - [("return_stringptr", "*", "*")]), - - # base URLs are optional (pass None for NULL) - ([("CFURLRef", "baseURL", "InMode")], - [("OptionalCFURLRef", "*", "*")]), - - # We handle CFPropertyListRef objects as plain CFTypeRef - ([("CFPropertyListRef", "*", "*")], - [("CFTypeRef", "*", "*")]), - ] - if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/cf/cfsupport.py b/Mac/Modules/cf/cfsupport.py index 95aeaa7..87b9a6f 100644 --- a/Mac/Modules/cf/cfsupport.py +++ b/Mac/Modules/cf/cfsupport.py @@ -8,35 +8,35 @@ import string # Declarations that change for each manager -MODNAME = '_CF' # The name of the module +MODNAME = '_CF' # The name of the module # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'CF' # The prefix for module-wide routines +MODPREFIX = 'CF' # The prefix for module-wide routines INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * # Special case generator for the functions that have an AllocatorRef first argument, # which we skip anyway, and the object as the second arg. class MethodSkipArg1(MethodGenerator): - """Similar to MethodGenerator, but has self as last argument""" - - def parseArgumentList(self, args): - if len(args) < 2: - raise ValueError, "MethodSkipArg1 expects at least 2 args" - a0, a1, args = args[0], args[1], args[2:] - t0, n0, m0 = a0 - if t0 != "CFAllocatorRef" and m0 != InMode: - raise ValueError, "MethodSkipArg1 should have dummy AllocatorRef first arg" - t1, n1, m1 = a1 - if m1 != InMode: - raise ValueError, "method's 'self' must be 'InMode'" - dummy = Variable(t0, n0, m0) - self.argumentList.append(dummy) - self.itself = Variable(t1, "_self->ob_itself", SelfMode) - self.argumentList.append(self.itself) - FunctionGenerator.parseArgumentList(self, args) + """Similar to MethodGenerator, but has self as last argument""" + + def parseArgumentList(self, args): + if len(args) < 2: + raise ValueError, "MethodSkipArg1 expects at least 2 args" + a0, a1, args = args[0], args[1], args[2:] + t0, n0, m0 = a0 + if t0 != "CFAllocatorRef" and m0 != InMode: + raise ValueError, "MethodSkipArg1 should have dummy AllocatorRef first arg" + t1, n1, m1 = a1 + if m1 != InMode: + raise ValueError, "method's 'self' must be 'InMode'" + dummy = Variable(t0, n0, m0) + self.argumentList.append(dummy) + self.itself = Variable(t1, "_self->ob_itself", SelfMode) + self.argumentList.append(self.itself) + FunctionGenerator.parseArgumentList(self, args) # Create the type objects @@ -111,19 +111,19 @@ extern int _OptionalCFURLRefObj_Convert(PyObject *, CFURLRef *); PyObject *CFRange_New(CFRange *itself) { - return Py_BuildValue("ll", (long)itself->location, (long)itself->length); + return Py_BuildValue("ll", (long)itself->location, (long)itself->length); } int CFRange_Convert(PyObject *v, CFRange *p_itself) { - long location, length; - - if( !PyArg_ParseTuple(v, "ll", &location, &length) ) - return 0; - p_itself->location = (CFIndex)location; - p_itself->length = (CFIndex)length; - return 1; + long location, length; + + if( !PyArg_ParseTuple(v, "ll", &location, &length) ) + return 0; + p_itself->location = (CFIndex)location; + p_itself->length = (CFIndex)length; + return 1; } /* Optional CFURL argument or None (passed as NULL) */ @@ -131,8 +131,8 @@ int OptionalCFURLRefObj_Convert(PyObject *v, CFURLRef *p_itself) { if ( v == Py_None ) { - p_itself = NULL; - return 1; + p_itself = NULL; + return 1; } return CFURLRefObj_Convert(v, p_itself); } @@ -143,42 +143,42 @@ finalstuff = finalstuff + """ /* Routines to convert any CF type to/from the corresponding CFxxxObj */ PyObject *CFObj_New(CFTypeRef itself) { - if (itself == NULL) - { - PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL"); - return NULL; - } - if (CFGetTypeID(itself) == CFArrayGetTypeID()) return CFArrayRefObj_New((CFArrayRef)itself); - if (CFGetTypeID(itself) == CFDictionaryGetTypeID()) return CFDictionaryRefObj_New((CFDictionaryRef)itself); - if (CFGetTypeID(itself) == CFDataGetTypeID()) return CFDataRefObj_New((CFDataRef)itself); - if (CFGetTypeID(itself) == CFStringGetTypeID()) return CFStringRefObj_New((CFStringRef)itself); - if (CFGetTypeID(itself) == CFURLGetTypeID()) return CFURLRefObj_New((CFURLRef)itself); - /* XXXX Or should we use PyCF_CF2Python here?? */ - return CFTypeRefObj_New(itself); + if (itself == NULL) + { + PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL"); + return NULL; + } + if (CFGetTypeID(itself) == CFArrayGetTypeID()) return CFArrayRefObj_New((CFArrayRef)itself); + if (CFGetTypeID(itself) == CFDictionaryGetTypeID()) return CFDictionaryRefObj_New((CFDictionaryRef)itself); + if (CFGetTypeID(itself) == CFDataGetTypeID()) return CFDataRefObj_New((CFDataRef)itself); + if (CFGetTypeID(itself) == CFStringGetTypeID()) return CFStringRefObj_New((CFStringRef)itself); + if (CFGetTypeID(itself) == CFURLGetTypeID()) return CFURLRefObj_New((CFURLRef)itself); + /* XXXX Or should we use PyCF_CF2Python here?? */ + return CFTypeRefObj_New(itself); } int CFObj_Convert(PyObject *v, CFTypeRef *p_itself) { - if (v == Py_None) { *p_itself = NULL; return 1; } - /* Check for other CF objects here */ - - if (!CFTypeRefObj_Check(v) && - !CFArrayRefObj_Check(v) && - !CFMutableArrayRefObj_Check(v) && - !CFDictionaryRefObj_Check(v) && - !CFMutableDictionaryRefObj_Check(v) && - !CFDataRefObj_Check(v) && - !CFMutableDataRefObj_Check(v) && - !CFStringRefObj_Check(v) && - !CFMutableStringRefObj_Check(v) && - !CFURLRefObj_Check(v) ) - { - /* XXXX Or should we use PyCF_Python2CF here?? */ - PyErr_SetString(PyExc_TypeError, "CF object required"); - return 0; - } - *p_itself = ((CFTypeRefObject *)v)->ob_itself; - return 1; + if (v == Py_None) { *p_itself = NULL; return 1; } + /* Check for other CF objects here */ + + if (!CFTypeRefObj_Check(v) && + !CFArrayRefObj_Check(v) && + !CFMutableArrayRefObj_Check(v) && + !CFDictionaryRefObj_Check(v) && + !CFMutableDictionaryRefObj_Check(v) && + !CFDataRefObj_Check(v) && + !CFMutableDataRefObj_Check(v) && + !CFStringRefObj_Check(v) && + !CFMutableStringRefObj_Check(v) && + !CFURLRefObj_Check(v) ) + { + /* XXXX Or should we use PyCF_Python2CF here?? */ + PyErr_SetString(PyExc_TypeError, "CF object required"); + return 0; + } + *p_itself = ((CFTypeRefObject *)v)->ob_itself; + return 1; } """ @@ -225,7 +225,7 @@ CFComparisonResult = Type("CFComparisonResult", "l") # a bit dangerous, it's an CFURLPathStyle = Type("CFURLPathStyle", "l") # a bit dangerous, it's an enum char_ptr = stringptr -return_stringptr = Type("char *", "s") # ONLY FOR RETURN VALUES!! +return_stringptr = Type("char *", "s") # ONLY FOR RETURN VALUES!! CFAllocatorRef = FakeType("(CFAllocatorRef)NULL") CFArrayCallBacks_ptr = FakeType("&kCFTypeArrayCallBacks") @@ -251,233 +251,233 @@ OptionalCFURLRef = OpaqueByValueType("CFURLRef", "OptionalCFURLRefObj") # Our (opaque) objects class MyGlobalObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output('if (itself == NULL)') - OutLbrace() - Output('PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");') - Output('return NULL;') - OutRbrace() - def outputStructMembers(self): - GlobalObjectDefinition.outputStructMembers(self) - Output("void (*ob_freeit)(CFTypeRef ptr);") - def outputInitStructMembers(self): - GlobalObjectDefinition.outputInitStructMembers(self) -## Output("it->ob_freeit = NULL;") - Output("it->ob_freeit = CFRelease;") - def outputCheckConvertArg(self): - Out(""" - if (v == Py_None) { *p_itself = NULL; return 1; } - /* Check for other CF objects here */ - """) - def outputCleanupStructMembers(self): - Output("if (self->ob_freeit && self->ob_itself)") - OutLbrace() - Output("self->ob_freeit((CFTypeRef)self->ob_itself);") - Output("self->ob_itself = NULL;") - OutRbrace() - - def outputCompare(self): - Output() - Output("static int %s_compare(%s *self, %s *other)", self.prefix, self.objecttype, self.objecttype) - OutLbrace() - Output("/* XXXX Or should we use CFEqual?? */") - Output("if ( self->ob_itself > other->ob_itself ) return 1;") - Output("if ( self->ob_itself < other->ob_itself ) return -1;") - Output("return 0;") - OutRbrace() - - def outputHash(self): - Output() - Output("static int %s_hash(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("/* XXXX Or should we use CFHash?? */") - Output("return (int)self->ob_itself;") - OutRbrace() - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<CFTypeRef type-%%d object at 0x%%8.8x for 0x%%8.8x>", (int)CFGetTypeID(self->ob_itself), (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() - - def output_tp_newBody(self): - Output("PyObject *self;") - Output - Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") - Output("((%s *)self)->ob_itself = NULL;", self.objecttype) - Output("((%s *)self)->ob_freeit = CFRelease;", self.objecttype) - Output("return self;") - - def output_tp_initBody(self): - Output("%s itself;", self.itselftype) - Output("char *kw[] = {\"itself\", 0};") - Output() - Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"O&\", kw, %s_Convert, &itself))", - self.prefix) - OutLbrace() - Output("((%s *)self)->ob_itself = itself;", self.objecttype) - Output("return 0;") - OutRbrace() - if self.prefix != 'CFTypeRefObj': - Output() - Output("/* Any CFTypeRef descendent is allowed as initializer too */") - Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"O&\", kw, CFTypeRefObj_Convert, &itself))") - OutLbrace() - Output("((%s *)self)->ob_itself = itself;", self.objecttype) - Output("return 0;") - OutRbrace() - Output("return -1;") + def outputCheckNewArg(self): + Output('if (itself == NULL)') + OutLbrace() + Output('PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");') + Output('return NULL;') + OutRbrace() + def outputStructMembers(self): + GlobalObjectDefinition.outputStructMembers(self) + Output("void (*ob_freeit)(CFTypeRef ptr);") + def outputInitStructMembers(self): + GlobalObjectDefinition.outputInitStructMembers(self) +## Output("it->ob_freeit = NULL;") + Output("it->ob_freeit = CFRelease;") + def outputCheckConvertArg(self): + Out(""" + if (v == Py_None) { *p_itself = NULL; return 1; } + /* Check for other CF objects here */ + """) + def outputCleanupStructMembers(self): + Output("if (self->ob_freeit && self->ob_itself)") + OutLbrace() + Output("self->ob_freeit((CFTypeRef)self->ob_itself);") + Output("self->ob_itself = NULL;") + OutRbrace() + + def outputCompare(self): + Output() + Output("static int %s_compare(%s *self, %s *other)", self.prefix, self.objecttype, self.objecttype) + OutLbrace() + Output("/* XXXX Or should we use CFEqual?? */") + Output("if ( self->ob_itself > other->ob_itself ) return 1;") + Output("if ( self->ob_itself < other->ob_itself ) return -1;") + Output("return 0;") + OutRbrace() + + def outputHash(self): + Output() + Output("static int %s_hash(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("/* XXXX Or should we use CFHash?? */") + Output("return (int)self->ob_itself;") + OutRbrace() + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<CFTypeRef type-%%d object at 0x%%8.8x for 0x%%8.8x>", (int)CFGetTypeID(self->ob_itself), (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() + + def output_tp_newBody(self): + Output("PyObject *self;") + Output + Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") + Output("((%s *)self)->ob_itself = NULL;", self.objecttype) + Output("((%s *)self)->ob_freeit = CFRelease;", self.objecttype) + Output("return self;") + + def output_tp_initBody(self): + Output("%s itself;", self.itselftype) + Output("char *kw[] = {\"itself\", 0};") + Output() + Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"O&\", kw, %s_Convert, &itself))", + self.prefix) + OutLbrace() + Output("((%s *)self)->ob_itself = itself;", self.objecttype) + Output("return 0;") + OutRbrace() + if self.prefix != 'CFTypeRefObj': + Output() + Output("/* Any CFTypeRef descendent is allowed as initializer too */") + Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"O&\", kw, CFTypeRefObj_Convert, &itself))") + OutLbrace() + Output("((%s *)self)->ob_itself = itself;", self.objecttype) + Output("return 0;") + OutRbrace() + Output("return -1;") class CFTypeRefObjectDefinition(MyGlobalObjectDefinition): - pass - + pass + class CFArrayRefObjectDefinition(MyGlobalObjectDefinition): - basetype = "CFTypeRef_Type" - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<CFArrayRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() - + basetype = "CFTypeRef_Type" + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<CFArrayRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() + class CFMutableArrayRefObjectDefinition(MyGlobalObjectDefinition): - basetype = "CFArrayRef_Type" - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<CFMutableArrayRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() - + basetype = "CFArrayRef_Type" + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<CFMutableArrayRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() + class CFDictionaryRefObjectDefinition(MyGlobalObjectDefinition): - basetype = "CFTypeRef_Type" - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<CFDictionaryRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() - + basetype = "CFTypeRef_Type" + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<CFDictionaryRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() + class CFMutableDictionaryRefObjectDefinition(MyGlobalObjectDefinition): - basetype = "CFDictionaryRef_Type" - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<CFMutableDictionaryRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() - + basetype = "CFDictionaryRef_Type" + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<CFMutableDictionaryRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() + class CFDataRefObjectDefinition(MyGlobalObjectDefinition): - basetype = "CFTypeRef_Type" - - def outputCheckConvertArg(self): - Out(""" - if (v == Py_None) { *p_itself = NULL; return 1; } - if (PyString_Check(v)) { - char *cStr; - int cLen; - if( PyString_AsStringAndSize(v, &cStr, &cLen) < 0 ) return 0; - *p_itself = CFDataCreate((CFAllocatorRef)NULL, (unsigned char *)cStr, cLen); - return 1; - } - """) - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<CFDataRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() - + basetype = "CFTypeRef_Type" + + def outputCheckConvertArg(self): + Out(""" + if (v == Py_None) { *p_itself = NULL; return 1; } + if (PyString_Check(v)) { + char *cStr; + int cLen; + if( PyString_AsStringAndSize(v, &cStr, &cLen) < 0 ) return 0; + *p_itself = CFDataCreate((CFAllocatorRef)NULL, (unsigned char *)cStr, cLen); + return 1; + } + """) + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<CFDataRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() + class CFMutableDataRefObjectDefinition(MyGlobalObjectDefinition): - basetype = "CFDataRef_Type" - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<CFMutableDataRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() + basetype = "CFDataRef_Type" + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<CFMutableDataRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() class CFStringRefObjectDefinition(MyGlobalObjectDefinition): - basetype = "CFTypeRef_Type" - - def outputCheckConvertArg(self): - Out(""" - if (v == Py_None) { *p_itself = NULL; return 1; } - if (PyString_Check(v)) { - char *cStr; - if (!PyArg_Parse(v, "es", "ascii", &cStr)) - return NULL; - *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII); - return 1; - } - if (PyUnicode_Check(v)) { - /* We use the CF types here, if Python was configured differently that will give an error */ - CFIndex size = PyUnicode_GetSize(v); - UniChar *unichars = PyUnicode_AsUnicode(v); - if (!unichars) return 0; - *p_itself = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size); - return 1; - } - - """) - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<CFStringRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() + basetype = "CFTypeRef_Type" + + def outputCheckConvertArg(self): + Out(""" + if (v == Py_None) { *p_itself = NULL; return 1; } + if (PyString_Check(v)) { + char *cStr; + if (!PyArg_Parse(v, "es", "ascii", &cStr)) + return NULL; + *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII); + return 1; + } + if (PyUnicode_Check(v)) { + /* We use the CF types here, if Python was configured differently that will give an error */ + CFIndex size = PyUnicode_GetSize(v); + UniChar *unichars = PyUnicode_AsUnicode(v); + if (!unichars) return 0; + *p_itself = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size); + return 1; + } + + """) + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<CFStringRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() class CFMutableStringRefObjectDefinition(CFStringRefObjectDefinition): - basetype = "CFStringRef_Type" - - def outputCheckConvertArg(self): - # Mutable, don't allow Python strings - return MyGlobalObjectDefinition.outputCheckConvertArg(self) - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<CFMutableStringRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() + basetype = "CFStringRef_Type" + + def outputCheckConvertArg(self): + # Mutable, don't allow Python strings + return MyGlobalObjectDefinition.outputCheckConvertArg(self) + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<CFMutableStringRef object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() class CFURLRefObjectDefinition(MyGlobalObjectDefinition): - basetype = "CFTypeRef_Type" - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<CFURL object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() + basetype = "CFTypeRef_Type" + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<CFURL object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() # ADD object class here @@ -554,10 +554,10 @@ char *data = malloc(size); if( data == NULL ) return PyErr_NoMemory(); if ( CFStringGetCString(_self->ob_itself, data, size, 0) ) { - _res = (PyObject *)PyString_FromString(data); + _res = (PyObject *)PyString_FromString(data); } else { - PyErr_SetString(PyExc_RuntimeError, "CFStringGetCString could not fit the string"); - _res = NULL; + PyErr_SetString(PyExc_RuntimeError, "CFStringGetCString could not fit the string"); + _res = NULL; } free(data); return _res; @@ -605,16 +605,16 @@ CFOptionFlags mutabilityOption; CFStringRef errorString; if (!PyArg_ParseTuple(_args, "l", &mutabilityOption)) - return NULL; + return NULL; _rv = CFPropertyListCreateFromXMLData((CFAllocatorRef)NULL, _self->ob_itself, mutabilityOption, &errorString); if (errorString) - CFRelease(errorString); + CFRelease(errorString); if (_rv == NULL) { - PyErr_SetString(PyExc_RuntimeError, "Parse error in XML data"); - return NULL; + PyErr_SetString(PyExc_RuntimeError, "Parse error in XML data"); + return NULL; } _res = Py_BuildValue("O&", CFTypeRefObj_New, _rv); @@ -639,17 +639,17 @@ CFTypeRef rv; CFTypeID typeid; if (!PyArg_ParseTuple(_args, "O&", PyCF_Python2CF, &rv)) - return NULL; + return NULL; typeid = CFGetTypeID(rv); if (typeid == CFStringGetTypeID()) - return Py_BuildValue("O&", CFStringRefObj_New, rv); + return Py_BuildValue("O&", CFStringRefObj_New, rv); if (typeid == CFArrayGetTypeID()) - return Py_BuildValue("O&", CFArrayRefObj_New, rv); + return Py_BuildValue("O&", CFArrayRefObj_New, rv); if (typeid == CFDictionaryGetTypeID()) - return Py_BuildValue("O&", CFDictionaryRefObj_New, rv); + return Py_BuildValue("O&", CFDictionaryRefObj_New, rv); if (typeid == CFURLGetTypeID()) - return Py_BuildValue("O&", CFURLRefObj_New, rv); + return Py_BuildValue("O&", CFURLRefObj_New, rv); _res = Py_BuildValue("O&", CFTypeRefObj_New, rv); return _res; @@ -663,4 +663,3 @@ module.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/cg/cgscan.py b/Mac/Modules/cg/cgscan.py index 5d84500..b2e7946 100755 --- a/Mac/Modules/cg/cgscan.py +++ b/Mac/Modules/cg/cgscan.py @@ -8,77 +8,77 @@ from scantools import Scanner_OSX LONG = "CoreGraphics" SHORT = "cg" -OBJECTS = ("CGContextRef", - ) +OBJECTS = ("CGContextRef", + ) # ADD object typenames here def main(): - input = [ - "CGContext.h", - ] - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.gentypetest(SHORT+"typetest.py") - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = [ + "CGContext.h", + ] + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.gentypetest(SHORT+"typetest.py") + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner_OSX): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t in OBJECTS and m == "InMode": - classname = "Method" - listname = t + "_methods" - # Special case for the silly first AllocatorRef argument - if t == 'CFAllocatorRef' and m == 'InMode' and len(arglist) > 1: - t, n, m = arglist[1] - if t in OBJECTS and m == "InMode": - classname = "MethodSkipArg1" - listname = t + "_methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t in OBJECTS and m == "InMode": + classname = "Method" + listname = t + "_methods" + # Special case for the silly first AllocatorRef argument + if t == 'CFAllocatorRef' and m == 'InMode' and len(arglist) > 1: + t, n, m = arglist[1] + if t in OBJECTS and m == "InMode": + classname = "MethodSkipArg1" + listname = t + "_methods" + return classname, listname - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - def makeblacklistnames(self): - return [ - "CGContextRetain", - "CGContextRelease", - ] + def makeblacklistnames(self): + return [ + "CGContextRetain", + "CGContextRelease", + ] - def makegreylist(self): - return [] + def makegreylist(self): + return [] - def makeblacklisttypes(self): - return [ - "float_ptr", - "CGRect_ptr", - "CGPoint_ptr", - "CGColorSpaceRef", - "CGColorRenderingIntent", - "CGFontRef", -# "char_ptr", - "CGGlyph_ptr", - "CGImageRef", - "CGPDFDocumentRef", - ] + def makeblacklisttypes(self): + return [ + "float_ptr", + "CGRect_ptr", + "CGPoint_ptr", + "CGColorSpaceRef", + "CGColorRenderingIntent", + "CGFontRef", +# "char_ptr", + "CGGlyph_ptr", + "CGImageRef", + "CGPDFDocumentRef", + ] + + def makerepairinstructions(self): + return [ + ([("char_ptr", "cstring", "InMode"), ("size_t", "length", "InMode")], + [("InBuffer", "*", "*")]), +# ([("char_ptr", "name", "InMode"),], +# [("CCCCC", "*", "*")]), + ] - def makerepairinstructions(self): - return [ - ([("char_ptr", "cstring", "InMode"), ("size_t", "length", "InMode")], - [("InBuffer", "*", "*")]), -# ([("char_ptr", "name", "InMode"),], -# [("CCCCC", "*", "*")]), - ] - if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/cg/cgsupport.py b/Mac/Modules/cg/cgsupport.py index 7dc2d54..6eedfbe 100755 --- a/Mac/Modules/cg/cgsupport.py +++ b/Mac/Modules/cg/cgsupport.py @@ -8,12 +8,12 @@ import string # Declarations that change for each manager -MODNAME = '_CG' # The name of the module +MODNAME = '_CG' # The name of the module # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'CG' # The prefix for module-wide routines +MODPREFIX = 'CG' # The prefix for module-wide routines INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -34,74 +34,74 @@ extern int GrafObj_Convert(PyObject *, GrafPtr *); PyObject *CGPoint_New(CGPoint *itself) { - return Py_BuildValue("(ff)", - itself->x, - itself->y); + return Py_BuildValue("(ff)", + itself->x, + itself->y); } int CGPoint_Convert(PyObject *v, CGPoint *p_itself) { - if( !PyArg_Parse(v, "(ff)", - &p_itself->x, - &p_itself->y) ) - return 0; - return 1; + if( !PyArg_Parse(v, "(ff)", + &p_itself->x, + &p_itself->y) ) + return 0; + return 1; } PyObject *CGRect_New(CGRect *itself) { - return Py_BuildValue("(ffff)", - itself->origin.x, - itself->origin.y, - itself->size.width, - itself->size.height); + return Py_BuildValue("(ffff)", + itself->origin.x, + itself->origin.y, + itself->size.width, + itself->size.height); } int CGRect_Convert(PyObject *v, CGRect *p_itself) { - if( !PyArg_Parse(v, "(ffff)", - &p_itself->origin.x, - &p_itself->origin.y, - &p_itself->size.width, - &p_itself->size.height) ) - return 0; - return 1; + if( !PyArg_Parse(v, "(ffff)", + &p_itself->origin.x, + &p_itself->origin.y, + &p_itself->size.width, + &p_itself->size.height) ) + return 0; + return 1; } PyObject *CGAffineTransform_New(CGAffineTransform *itself) { - return Py_BuildValue("(ffffff)", - itself->a, - itself->b, - itself->c, - itself->d, - itself->tx, - itself->ty); + return Py_BuildValue("(ffffff)", + itself->a, + itself->b, + itself->c, + itself->d, + itself->tx, + itself->ty); } int CGAffineTransform_Convert(PyObject *v, CGAffineTransform *p_itself) { - if( !PyArg_Parse(v, "(ffffff)", - &p_itself->a, - &p_itself->b, - &p_itself->c, - &p_itself->d, - &p_itself->tx, - &p_itself->ty) ) - return 0; - return 1; + if( !PyArg_Parse(v, "(ffffff)", + &p_itself->a, + &p_itself->b, + &p_itself->c, + &p_itself->d, + &p_itself->tx, + &p_itself->ty) ) + return 0; + return 1; } """ class MyOpaqueByValueType(OpaqueByValueType): - """Sort of a mix between OpaqueByValueType and OpaqueType.""" - def mkvalueArgs(self, name): - return "%s, &%s" % (self.new, name) + """Sort of a mix between OpaqueByValueType and OpaqueType.""" + def mkvalueArgs(self, name): + return "%s, &%s" % (self.new, name) CGPoint = MyOpaqueByValueType('CGPoint', 'CGPoint') CGRect = MyOpaqueByValueType('CGRect', 'CGRect') @@ -121,10 +121,10 @@ CGContextRef = OpaqueByValueType("CGContextRef", "CGContextRefObj") class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputStructMembers(self): - ObjectDefinition.outputStructMembers(self) - def outputCleanupStructMembers(self): - Output("CGContextRelease(self->ob_itself);") + def outputStructMembers(self): + ObjectDefinition.outputStructMembers(self) + def outputCleanupStructMembers(self): + Output("CGContextRelease(self->ob_itself);") # Create the generator groups and link them @@ -169,11 +169,11 @@ CGContextRef ctx; OSStatus _err; if (!PyArg_ParseTuple(_args, "O&", GrafObj_Convert, &port)) - return NULL; + return NULL; _err = CreateCGContextForPort(port, &ctx); if (_err != noErr) - if (_err != noErr) return PyMac_Error(_err); + if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("O&", CGContextRefObj_New, ctx); return _res; """ @@ -185,9 +185,8 @@ module.add(f) # ADD add forloop here for f in CGContextRef_methods: - CGContextRef_object.add(f) + CGContextRef_object.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/cm/cmscan.py b/Mac/Modules/cm/cmscan.py index 6e56cb2..087f239 100644 --- a/Mac/Modules/cm/cmscan.py +++ b/Mac/Modules/cm/cmscan.py @@ -10,80 +10,80 @@ LONG = "Components" SHORT = "cm" def main(): - input = "Components.h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = "Components.h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - # - # FindNextComponent is a special case, since it call also be called - # with None as the argument. Hence, we make it a function - # - if t == "Component" and m == "InMode" and name != "FindNextComponent": - classname = "Method" - listname = "c_methods" - elif t == "ComponentInstance" and m == "InMode": - classname = "Method" - listname = "ci_methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + # + # FindNextComponent is a special case, since it call also be called + # with None as the argument. Hence, we make it a function + # + if t == "Component" and m == "InMode" and name != "FindNextComponent": + classname = "Method" + listname = "c_methods" + elif t == "ComponentInstance" and m == "InMode": + classname = "Method" + listname = "ci_methods" + return classname, listname - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - def makeblacklistnames(self): - return [ - "OpenADefaultComponent", - "GetComponentTypeModSeed", - "OpenAComponentResFile", - "CallComponentUnregister", - "CallComponentTarget", - "CallComponentRegister", - "CallComponentVersion", - "CallComponentCanDo", - "CallComponentClose", - "CallComponentOpen", - "OpenAComponent", - "GetComponentPublicResource", # Missing in CW Pro 6 - "CallComponentGetPublicResource", # Missing in CW Pro 6 - 'SetComponentInstanceA5', - 'GetComponentInstanceA5', - ] + def makeblacklistnames(self): + return [ + "OpenADefaultComponent", + "GetComponentTypeModSeed", + "OpenAComponentResFile", + "CallComponentUnregister", + "CallComponentTarget", + "CallComponentRegister", + "CallComponentVersion", + "CallComponentCanDo", + "CallComponentClose", + "CallComponentOpen", + "OpenAComponent", + "GetComponentPublicResource", # Missing in CW Pro 6 + "CallComponentGetPublicResource", # Missing in CW Pro 6 + 'SetComponentInstanceA5', + 'GetComponentInstanceA5', + ] - def makeblacklisttypes(self): - return [ - "ResourceSpec", - "ComponentResource", - "ComponentPlatformInfo", - "ComponentResourceExtension", - "ComponentPlatformInfoArray", - "ExtComponentResource", - "ComponentParameters", - - "ComponentRoutineUPP", - "ComponentMPWorkFunctionUPP", - "ComponentFunctionUPP", - "GetMissingComponentResourceUPP", - ] + def makeblacklisttypes(self): + return [ + "ResourceSpec", + "ComponentResource", + "ComponentPlatformInfo", + "ComponentResourceExtension", + "ComponentPlatformInfoArray", + "ExtComponentResource", + "ComponentParameters", + + "ComponentRoutineUPP", + "ComponentMPWorkFunctionUPP", + "ComponentFunctionUPP", + "GetMissingComponentResourceUPP", + ] + + def makerepairinstructions(self): + return [ + ([('ComponentDescription', 'looking', 'OutMode')], + [('ComponentDescription', '*', 'InMode')]), + ] - def makerepairinstructions(self): - return [ - ([('ComponentDescription', 'looking', 'OutMode')], - [('ComponentDescription', '*', 'InMode')]), - ] - if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/cm/cmsupport.py b/Mac/Modules/cm/cmsupport.py index 98018c4..4109dba 100644 --- a/Mac/Modules/cm/cmsupport.py +++ b/Mac/Modules/cm/cmsupport.py @@ -6,15 +6,15 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Components.h' # The Apple header file -MODNAME = '_Cm' # The name of the module +MACHEADERFILE = 'Components.h' # The Apple header file +MODNAME = '_Cm' # The name of the module # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Cm' # The prefix for module-wide routines -C_OBJECTPREFIX = 'CmpObj' # The prefix for object methods +MODPREFIX = 'Cm' # The prefix for module-wide routines +C_OBJECTPREFIX = 'CmpObj' # The prefix for object methods CI_OBJECTPREFIX = 'CmpInstObj' INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -42,30 +42,30 @@ static PyObject * CmpDesc_New(ComponentDescription *itself) { - return Py_BuildValue("O&O&O&ll", - PyMac_BuildOSType, itself->componentType, - PyMac_BuildOSType, itself->componentSubType, - PyMac_BuildOSType, itself->componentManufacturer, - itself->componentFlags, itself->componentFlagsMask); + return Py_BuildValue("O&O&O&ll", + PyMac_BuildOSType, itself->componentType, + PyMac_BuildOSType, itself->componentSubType, + PyMac_BuildOSType, itself->componentManufacturer, + itself->componentFlags, itself->componentFlagsMask); } static int CmpDesc_Convert(PyObject *v, ComponentDescription *p_itself) { - return PyArg_ParseTuple(v, "O&O&O&ll", - PyMac_GetOSType, &p_itself->componentType, - PyMac_GetOSType, &p_itself->componentSubType, - PyMac_GetOSType, &p_itself->componentManufacturer, - &p_itself->componentFlags, &p_itself->componentFlagsMask); + return PyArg_ParseTuple(v, "O&O&O&ll", + PyMac_GetOSType, &p_itself->componentType, + PyMac_GetOSType, &p_itself->componentSubType, + PyMac_GetOSType, &p_itself->componentManufacturer, + &p_itself->componentFlags, &p_itself->componentFlagsMask); } """ initstuff = initstuff + """ - PyMac_INIT_TOOLBOX_OBJECT_NEW(Component, CmpObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Component, CmpObj_Convert); - PyMac_INIT_TOOLBOX_OBJECT_NEW(ComponentInstance, CmpInstObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ComponentInstance, CmpInstObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(Component, CmpObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Component, CmpObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(ComponentInstance, CmpInstObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ComponentInstance, CmpInstObj_Convert); """ ComponentDescription = OpaqueType('ComponentDescription', 'CmpDesc') @@ -76,30 +76,30 @@ ComponentResult = Type("ComponentResult", "l") ComponentResourceHandle = OpaqueByValueType("ComponentResourceHandle", "ResObj") class MyCIObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("""if (itself == NULL) { - PyErr_SetString(Cm_Error,"NULL ComponentInstance"); - return NULL; - }""") + def outputCheckNewArg(self): + Output("""if (itself == NULL) { + PyErr_SetString(Cm_Error,"NULL ComponentInstance"); + return NULL; + }""") class MyCObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("""if (itself == NULL) { - /* XXXX Or should we return None? */ - PyErr_SetString(Cm_Error,"No such component"); - return NULL; - }""") - - def outputCheckConvertArg(self): - Output("""if ( v == Py_None ) { - *p_itself = 0; - return 1; - }""") + def outputCheckNewArg(self): + Output("""if (itself == NULL) { + /* XXXX Or should we return None? */ + PyErr_SetString(Cm_Error,"No such component"); + return NULL; + }""") + + def outputCheckConvertArg(self): + Output("""if ( v == Py_None ) { + *p_itself = 0; + return 1; + }""") # Create the generator groups and link them module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff) ci_object = MyCIObjectDefinition('ComponentInstance', CI_OBJECTPREFIX, - 'ComponentInstance') + 'ComponentInstance') c_object = MyCObjectDefinition('Component', C_OBJECTPREFIX, 'Component') module.addobject(ci_object) module.addobject(c_object) @@ -123,4 +123,3 @@ for f in ci_methods: ci_object.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/ctl/ctledit.py b/Mac/Modules/ctl/ctledit.py index 6ba024b..fdd9712 100644 --- a/Mac/Modules/ctl/ctledit.py +++ b/Mac/Modules/ctl/ctledit.py @@ -8,7 +8,7 @@ f = Function(ExistingControlHandle, 'FindControlUnderMouse', functions.append(f) f = Function(ControlHandle, 'as_Control', - (Handle, 'h', InMode)) + (Handle, 'h', InMode)) functions.append(f) f = Method(Handle, 'as_Resource', (ControlHandle, 'ctl', InMode)) @@ -18,16 +18,16 @@ f = Method(void, 'GetControlRect', (ControlHandle, 'ctl', InMode), (Rect, 'rect' methods.append(f) DisposeControl_body = """ - if (!PyArg_ParseTuple(_args, "")) - return NULL; - if ( _self->ob_itself ) { - SetControlReference(_self->ob_itself, (long)0); /* Make it forget about us */ - DisposeControl(_self->ob_itself); - _self->ob_itself = NULL; - } - Py_INCREF(Py_None); - _res = Py_None; - return _res; + if (!PyArg_ParseTuple(_args, "")) + return NULL; + if ( _self->ob_itself ) { + SetControlReference(_self->ob_itself, (long)0); /* Make it forget about us */ + DisposeControl(_self->ob_itself); + _self->ob_itself = NULL; + } + Py_INCREF(Py_None); + _res = Py_None; + return _res; """ f = ManualGenerator("DisposeControl", DisposeControl_body) @@ -39,7 +39,7 @@ methods.append(f) # parameter; these should however be managed by us (we're creating them # after all), so set the type to ControlRef. for f in functions: - if f.name.startswith("Create"): - v = f.argumentList[-1] - if v.type == ExistingControlHandle: - v.type = ControlRef + if f.name.startswith("Create"): + v = f.argumentList[-1] + if v.type == ExistingControlHandle: + v.type = ControlRef diff --git a/Mac/Modules/ctl/ctlscan.py b/Mac/Modules/ctl/ctlscan.py index 818541e..25333f1 100644 --- a/Mac/Modules/ctl/ctlscan.py +++ b/Mac/Modules/ctl/ctlscan.py @@ -7,166 +7,166 @@ sys.path.append(BGENDIR) from scantools import Scanner def main(): -# input = "Controls.h" # Universal Headers < 3.3 - input = ["Controls.h", "ControlDefinitions.h"] # Universal Headers >= 3.3 - output = "ctlgen.py" - defsoutput = TOOLBOXDIR + "Controls.py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now doing 'import ctlsupport' ===" - import ctlsupport - print "=== Done. It's up to you to compile Ctlmodule.c ===" +# input = "Controls.h" # Universal Headers < 3.3 + input = ["Controls.h", "ControlDefinitions.h"] # Universal Headers >= 3.3 + output = "ctlgen.py" + defsoutput = TOOLBOXDIR + "Controls.py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now doing 'import ctlsupport' ===" + import ctlsupport + print "=== Done. It's up to you to compile Ctlmodule.c ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t in ("ControlHandle", "ControlRef") and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("from Carbon.TextEdit import *\n") - self.defsfile.write("from Carbon.QuickDraw import *\n") - self.defsfile.write("from Carbon.Dragconst import *\n") - self.defsfile.write("from Carbon.CarbonEvents import *\n") - self.defsfile.write("from Carbon.Appearance import *\n") - self.defsfile.write("kDataBrowserItemAnyState = -1\n") - self.defsfile.write("kControlBevelButtonCenterPopupGlyphTag = -1\n") - self.defsfile.write("kDataBrowserClientPropertyFlagsMask = 0xFF000000\n") - self.defsfile.write("\n") - - def makeblacklistnames(self): - return [ - 'FindControlUnderMouse', # Generated manually, returns an existing control, not a new one. - 'DisposeControl', # Generated manually - 'KillControls', # Implied by close of dialog - 'SetCtlAction', - 'TrackControl', # Generated manually - 'HandleControlClick', # Generated manually - 'SetControlData', # Generated manually - 'GetControlData', # Generated manually - 'kControlBevelButtonCenterPopupGlyphTag', # Constant with funny definition - 'kDataBrowserClientPropertyFlagsMask', # ditto - 'kDataBrowserItemAnyState', # and ditto - # The following are unavailable for static 68k (appearance manager) -## 'GetBevelButtonMenuValue', -## 'SetBevelButtonMenuValue', -## 'GetBevelButtonMenuHandle', -## 'SetBevelButtonTransform', - 'SetBevelButtonGraphicAlignment', - 'SetBevelButtonTextAlignment', - 'SetBevelButtonTextPlacement', -## 'SetImageWellTransform', -## 'GetTabContentRect', -## 'SetTabEnabled', -## 'SetDisclosureTriangleLastValue', -## # Unavailable in CW Pro 3 libraries -## 'SetUpControlTextColor', -## # Unavailable in Jack's CW Pro 5.1 libraries -## 'GetControlRegion', -## 'RemoveControlProperty', -## 'IsValidControlHandle', -## 'SetControl32BitMinimum', -## 'GetControl32BitMinimum', -## 'SetControl32BitMaximum', -## 'GetControl32BitMaximum', -## 'SetControl32BitValue', -## 'GetControl32BitValue', -## 'SetControlViewSize', -## 'GetControlViewSize', - # Generally Bad News - 'GetControlProperty', - 'SetControlProperty', - 'GetControlPropertySize', - 'SendControlMessage', # Parameter changed from long to void* from UH3.3 to UH3.4 - 'CreateTabsControl', # wrote manually - 'GetControlAction', # too much effort for too little usefulness - - # too lazy for now - 'GetImageWellContentInfo', - 'GetBevelButtonContentInfo', - # OS8 only - 'GetAuxiliaryControlRecord', - 'SetControlColor', - ] - - def makeblacklisttypes(self): - return [ - 'ProcPtr', -# 'ControlActionUPP', - 'Ptr', - 'ControlDefSpec', # Don't know how to do this yet - 'ControlDefSpec_ptr', # ditto - 'Collection', # Ditto - # not-yet-supported stuff in Universal Headers 3.4: - 'ControlColorUPP', - 'ControlKind', # XXX easy: 2-tuple containing 2 OSType's -# 'ControlTabEntry_ptr', # XXX needed for tabs -# 'ControlButtonContentInfoPtr', -# 'ControlButtonContentInfo', # XXX ugh: a union -# 'ControlButtonContentInfo_ptr', # XXX ugh: a union - 'ListDefSpec_ptr', # XXX see _Listmodule.c, tricky but possible - 'DataBrowserItemID_ptr', # XXX array of UInt32, for BrowserView - 'DataBrowserItemUPP', - 'DataBrowserItemDataRef', # XXX void * - 'DataBrowserCallbacks', # difficult struct - 'DataBrowserCallbacks_ptr', - 'DataBrowserCustomCallbacks', - 'DataBrowserCustomCallbacks_ptr', -## 'DataBrowserTableViewColumnDesc', -## 'DataBrowserListViewColumnDesc', - 'CFDataRef', - 'DataBrowserListViewHeaderDesc', # difficult struct - ] - - def makerepairinstructions(self): - return [ - ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], - [("InBuffer", "*", "*")]), - - ([("void", "*", "OutMode"), ("long", "*", "InMode"), - ("long", "*", "OutMode")], - [("VarVarOutBuffer", "*", "InOutMode")]), - -## # For TrackControl -## ([("ProcPtr", "actionProc", "InMode")], -## [("FakeType('(ControlActionUPP)0')", "*", "*")]), -## ([("ControlActionUPP", "actionProc", "InMode")], -## [("FakeType('(ControlActionUPP)0')", "*", "*")]), - - # For GetControlTitle - ([('Str255', 'title', 'InMode')], - [('Str255', 'title', 'OutMode')]), - - ([("ControlHandle", "*", "OutMode")], - [("ExistingControlHandle", "*", "*")]), - ([("ControlRef", "*", "OutMode")], # Ditto, for Universal Headers - [("ExistingControlHandle", "*", "*")]), - - ([("Rect_ptr", "*", "ReturnMode")], # GetControlBounds - [("void", "*", "ReturnMode")]), - - ([("DataBrowserListViewColumnDesc", "*", "OutMode")], - [("DataBrowserListViewColumnDesc", "*", "InMode")]), - - ([("ControlButtonContentInfoPtr", 'outContent', "InMode")], - [("ControlButtonContentInfoPtr", '*', "OutMode")]), - - ([("ControlButtonContentInfo", '*', "OutMode")], - [("ControlButtonContentInfo", '*', "InMode")]), - - ([("ControlActionUPP", 'liveTrackingProc', "InMode")], - [("ControlActionUPPNewControl", 'liveTrackingProc', "InMode")]), - ] + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t in ("ControlHandle", "ControlRef") and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("from Carbon.TextEdit import *\n") + self.defsfile.write("from Carbon.QuickDraw import *\n") + self.defsfile.write("from Carbon.Dragconst import *\n") + self.defsfile.write("from Carbon.CarbonEvents import *\n") + self.defsfile.write("from Carbon.Appearance import *\n") + self.defsfile.write("kDataBrowserItemAnyState = -1\n") + self.defsfile.write("kControlBevelButtonCenterPopupGlyphTag = -1\n") + self.defsfile.write("kDataBrowserClientPropertyFlagsMask = 0xFF000000\n") + self.defsfile.write("\n") + + def makeblacklistnames(self): + return [ + 'FindControlUnderMouse', # Generated manually, returns an existing control, not a new one. + 'DisposeControl', # Generated manually + 'KillControls', # Implied by close of dialog + 'SetCtlAction', + 'TrackControl', # Generated manually + 'HandleControlClick', # Generated manually + 'SetControlData', # Generated manually + 'GetControlData', # Generated manually + 'kControlBevelButtonCenterPopupGlyphTag', # Constant with funny definition + 'kDataBrowserClientPropertyFlagsMask', # ditto + 'kDataBrowserItemAnyState', # and ditto + # The following are unavailable for static 68k (appearance manager) +## 'GetBevelButtonMenuValue', +## 'SetBevelButtonMenuValue', +## 'GetBevelButtonMenuHandle', +## 'SetBevelButtonTransform', + 'SetBevelButtonGraphicAlignment', + 'SetBevelButtonTextAlignment', + 'SetBevelButtonTextPlacement', +## 'SetImageWellTransform', +## 'GetTabContentRect', +## 'SetTabEnabled', +## 'SetDisclosureTriangleLastValue', +## # Unavailable in CW Pro 3 libraries +## 'SetUpControlTextColor', +## # Unavailable in Jack's CW Pro 5.1 libraries +## 'GetControlRegion', +## 'RemoveControlProperty', +## 'IsValidControlHandle', +## 'SetControl32BitMinimum', +## 'GetControl32BitMinimum', +## 'SetControl32BitMaximum', +## 'GetControl32BitMaximum', +## 'SetControl32BitValue', +## 'GetControl32BitValue', +## 'SetControlViewSize', +## 'GetControlViewSize', + # Generally Bad News + 'GetControlProperty', + 'SetControlProperty', + 'GetControlPropertySize', + 'SendControlMessage', # Parameter changed from long to void* from UH3.3 to UH3.4 + 'CreateTabsControl', # wrote manually + 'GetControlAction', # too much effort for too little usefulness + + # too lazy for now + 'GetImageWellContentInfo', + 'GetBevelButtonContentInfo', + # OS8 only + 'GetAuxiliaryControlRecord', + 'SetControlColor', + ] + + def makeblacklisttypes(self): + return [ + 'ProcPtr', +# 'ControlActionUPP', + 'Ptr', + 'ControlDefSpec', # Don't know how to do this yet + 'ControlDefSpec_ptr', # ditto + 'Collection', # Ditto + # not-yet-supported stuff in Universal Headers 3.4: + 'ControlColorUPP', + 'ControlKind', # XXX easy: 2-tuple containing 2 OSType's +# 'ControlTabEntry_ptr', # XXX needed for tabs +# 'ControlButtonContentInfoPtr', +# 'ControlButtonContentInfo', # XXX ugh: a union +# 'ControlButtonContentInfo_ptr', # XXX ugh: a union + 'ListDefSpec_ptr', # XXX see _Listmodule.c, tricky but possible + 'DataBrowserItemID_ptr', # XXX array of UInt32, for BrowserView + 'DataBrowserItemUPP', + 'DataBrowserItemDataRef', # XXX void * + 'DataBrowserCallbacks', # difficult struct + 'DataBrowserCallbacks_ptr', + 'DataBrowserCustomCallbacks', + 'DataBrowserCustomCallbacks_ptr', +## 'DataBrowserTableViewColumnDesc', +## 'DataBrowserListViewColumnDesc', + 'CFDataRef', + 'DataBrowserListViewHeaderDesc', # difficult struct + ] + + def makerepairinstructions(self): + return [ + ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], + [("InBuffer", "*", "*")]), + + ([("void", "*", "OutMode"), ("long", "*", "InMode"), + ("long", "*", "OutMode")], + [("VarVarOutBuffer", "*", "InOutMode")]), + +## # For TrackControl +## ([("ProcPtr", "actionProc", "InMode")], +## [("FakeType('(ControlActionUPP)0')", "*", "*")]), +## ([("ControlActionUPP", "actionProc", "InMode")], +## [("FakeType('(ControlActionUPP)0')", "*", "*")]), + + # For GetControlTitle + ([('Str255', 'title', 'InMode')], + [('Str255', 'title', 'OutMode')]), + + ([("ControlHandle", "*", "OutMode")], + [("ExistingControlHandle", "*", "*")]), + ([("ControlRef", "*", "OutMode")], # Ditto, for Universal Headers + [("ExistingControlHandle", "*", "*")]), + + ([("Rect_ptr", "*", "ReturnMode")], # GetControlBounds + [("void", "*", "ReturnMode")]), + + ([("DataBrowserListViewColumnDesc", "*", "OutMode")], + [("DataBrowserListViewColumnDesc", "*", "InMode")]), + + ([("ControlButtonContentInfoPtr", 'outContent', "InMode")], + [("ControlButtonContentInfoPtr", '*', "OutMode")]), + + ([("ControlButtonContentInfo", '*', "OutMode")], + [("ControlButtonContentInfo", '*', "InMode")]), + + ([("ControlActionUPP", 'liveTrackingProc', "InMode")], + [("ControlActionUPPNewControl", 'liveTrackingProc', "InMode")]), + ] if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/ctl/ctlsupport.py b/Mac/Modules/ctl/ctlsupport.py index b2d9ad5..d354d94 100644 --- a/Mac/Modules/ctl/ctlsupport.py +++ b/Mac/Modules/ctl/ctlsupport.py @@ -6,16 +6,16 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Controls.h' # The Apple header file -MODNAME = '_Ctl' # The name of the module -OBJECTNAME = 'Control' # The basic name of the objects used here +MACHEADERFILE = 'Controls.h' # The Apple header file +MODNAME = '_Ctl' # The name of the module +OBJECTNAME = 'Control' # The basic name of the objects used here # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Ctl' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + 'Handle' # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Ctl' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + 'Handle' # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -79,11 +79,11 @@ DataBrowserPropertyType = OSType ControlDisclosureTriangleOrientation = UInt16 DataBrowserTableViewColumnDesc = OpaqueType("DataBrowserTableViewColumnDesc", - "DataBrowserTableViewColumnDesc") + "DataBrowserTableViewColumnDesc") DataBrowserListViewColumnDesc = OpaqueType("DataBrowserListViewColumnDesc", - "DataBrowserListViewColumnDesc") + "DataBrowserListViewColumnDesc") ControlButtonContentInfo = OpaqueType("ControlButtonContentInfo", - "ControlButtonContentInfo") + "ControlButtonContentInfo") ControlButtonContentInfoPtr = ControlButtonContentInfo_ptr = ControlButtonContentInfo ControlTabEntry_ptr = OpaqueType("ControlTabEntry", "ControlTabEntry") @@ -95,17 +95,17 @@ ControlBevelButtonMenuPlacement = UInt16 ControlPushButtonIconAlignment = UInt16 class ControlActionDefinition(Type): - def declare(self, name): - Output("%s %s;", self.typeName, name) - Output("UniversalProcPtr c_callback;") - def passInput(self, name): - return "myactionproc_upp" - def cleanup(self, name): - Output("setcallback((PyObject*)_self, kMyControlActionProcTag, actionProc, &c_callback);") + def declare(self, name): + Output("%s %s;", self.typeName, name) + Output("UniversalProcPtr c_callback;") + def passInput(self, name): + return "myactionproc_upp" + def cleanup(self, name): + Output("setcallback((PyObject*)_self, kMyControlActionProcTag, actionProc, &c_callback);") class ControlActionDefinitionNewControl(ControlActionDefinition): - def cleanup(self, name): - Output("setcallback(_res, kMyControlActionProcTag, liveTrackingProc, &c_callback);") + def cleanup(self, name): + Output("setcallback(_res, kMyControlActionProcTag, liveTrackingProc, &c_callback);") ControlActionUPP = ControlActionDefinition("PyObject*", "O") ControlActionUPPNewControl = ControlActionDefinitionNewControl("PyObject*", "O") @@ -138,19 +138,19 @@ static PyObject * ControlFontStyle_New(ControlFontStyleRec *itself) { - return Py_BuildValue("hhhhhhO&O&", itself->flags, itself->font, - itself->size, itself->style, itself->mode, itself->just, - QdRGB_New, &itself->foreColor, QdRGB_New, &itself->backColor); + return Py_BuildValue("hhhhhhO&O&", itself->flags, itself->font, + itself->size, itself->style, itself->mode, itself->just, + QdRGB_New, &itself->foreColor, QdRGB_New, &itself->backColor); } #endif static int ControlFontStyle_Convert(PyObject *v, ControlFontStyleRec *itself) { - return PyArg_Parse(v, "(hhhhhhO&O&)", &itself->flags, - &itself->font, &itself->size, &itself->style, &itself->mode, - &itself->just, QdRGB_Convert, &itself->foreColor, - QdRGB_Convert, &itself->backColor); + return PyArg_Parse(v, "(hhhhhhO&O&)", &itself->flags, + &itself->font, &itself->size, &itself->style, &itself->mode, + &itself->just, QdRGB_Convert, &itself->foreColor, + QdRGB_Convert, &itself->backColor); } /* @@ -160,13 +160,13 @@ static PyObject * PyControlID_New(ControlID *itself) { - return Py_BuildValue("O&l", PyMac_BuildOSType, itself->signature, itself->id); + return Py_BuildValue("O&l", PyMac_BuildOSType, itself->signature, itself->id); } static int PyControlID_Convert(PyObject *v, ControlID *itself) { - return PyArg_Parse(v, "(O&l)", PyMac_GetOSType, &itself->signature, &itself->id); + return PyArg_Parse(v, "(O&l)", PyMac_GetOSType, &itself->signature, &itself->id); } /* @@ -175,40 +175,40 @@ PyControlID_Convert(PyObject *v, ControlID *itself) static int DataBrowserTableViewColumnDesc_Convert(PyObject *v, DataBrowserTableViewColumnDesc *itself) { - return PyArg_Parse(v, "(lO&l)", - &itself->propertyID, - PyMac_GetOSType, &itself->propertyType, - &itself->propertyFlags); + return PyArg_Parse(v, "(lO&l)", + &itself->propertyID, + PyMac_GetOSType, &itself->propertyType, + &itself->propertyFlags); } static int ControlButtonContentInfo_Convert(PyObject *v, ControlButtonContentInfo *itself) { - return PyArg_Parse(v, "(hO&)", - &itself->contentType, - OptResObj_Convert, &itself->u.iconSuite); + return PyArg_Parse(v, "(hO&)", + &itself->contentType, + OptResObj_Convert, &itself->u.iconSuite); } static int DataBrowserListViewHeaderDesc_Convert(PyObject *v, DataBrowserListViewHeaderDesc *itself) { - itself->version = kDataBrowserListViewLatestHeaderDesc; - return PyArg_Parse(v, "(HHhO&HO&O&)", - &itself->minimumWidth, - &itself->maximumWidth, - &itself->titleOffset, - CFStringRefObj_Convert, &itself->titleString, - &itself->initialOrder, - ControlFontStyle_Convert, &itself->btnFontStyle, - ControlButtonContentInfo_Convert, &itself->btnContentInfo); + itself->version = kDataBrowserListViewLatestHeaderDesc; + return PyArg_Parse(v, "(HHhO&HO&O&)", + &itself->minimumWidth, + &itself->maximumWidth, + &itself->titleOffset, + CFStringRefObj_Convert, &itself->titleString, + &itself->initialOrder, + ControlFontStyle_Convert, &itself->btnFontStyle, + ControlButtonContentInfo_Convert, &itself->btnContentInfo); } static int DataBrowserListViewColumnDesc_Convert(PyObject *v, DataBrowserListViewColumnDesc *itself) { - return PyArg_Parse(v, "(O&O&)", - DataBrowserTableViewColumnDesc_Convert, &itself->propertyDesc, - DataBrowserListViewHeaderDesc_Convert, &itself->headerBtnDesc); + return PyArg_Parse(v, "(O&O&)", + DataBrowserTableViewColumnDesc_Convert, &itself->propertyDesc, + DataBrowserListViewHeaderDesc_Convert, &itself->headerBtnDesc); } /* TrackControl and HandleControlClick callback support */ @@ -223,8 +223,8 @@ static ControlUserPaneIdleUPP myidleproc_upp; static ControlUserPaneHitTestUPP myhittestproc_upp; static ControlUserPaneTrackingUPP mytrackingproc_upp; -static int settrackfunc(PyObject *); /* forward */ -static void clrtrackfunc(void); /* forward */ +static int settrackfunc(PyObject *); /* forward */ +static void clrtrackfunc(void); /* forward */ static int setcallback(PyObject *, OSType, PyObject *, UniversalProcPtr *); """ @@ -232,239 +232,239 @@ finalstuff = finalstuff + """ static PyObject * CtlObj_NewUnmanaged(ControlHandle itself) { - ControlObject *it; - if (itself == NULL) return PyMac_Error(resNotFound); - it = PyObject_NEW(ControlObject, &Control_Type); - if (it == NULL) return NULL; - it->ob_itself = itself; - it->ob_callbackdict = NULL; - return (PyObject *)it; + ControlObject *it; + if (itself == NULL) return PyMac_Error(resNotFound); + it = PyObject_NEW(ControlObject, &Control_Type); + if (it == NULL) return NULL; + it->ob_itself = itself; + it->ob_callbackdict = NULL; + return (PyObject *)it; } static PyObject * CtlObj_WhichControl(ControlHandle c) { - PyObject *it; - - if (c == NULL) - it = Py_None; - else { - it = (PyObject *) GetControlReference(c); - /* - ** If the refcon is zero or doesn't point back to the Python object - ** the control is not ours. Return a temporary object. - */ - if (it == NULL || ((ControlObject *)it)->ob_itself != c) - return CtlObj_NewUnmanaged(c); - } - Py_INCREF(it); - return it; + PyObject *it; + + if (c == NULL) + it = Py_None; + else { + it = (PyObject *) GetControlReference(c); + /* + ** If the refcon is zero or doesn't point back to the Python object + ** the control is not ours. Return a temporary object. + */ + if (it == NULL || ((ControlObject *)it)->ob_itself != c) + return CtlObj_NewUnmanaged(c); + } + Py_INCREF(it); + return it; } static int settrackfunc(PyObject *obj) { - if (tracker) { - PyErr_SetString(Ctl_Error, "Tracker function in use"); - return 0; - } - tracker = obj; - Py_INCREF(tracker); - return 1; + if (tracker) { + PyErr_SetString(Ctl_Error, "Tracker function in use"); + return 0; + } + tracker = obj; + Py_INCREF(tracker); + return 1; } static void clrtrackfunc(void) { - Py_XDECREF(tracker); - tracker = 0; + Py_XDECREF(tracker); + tracker = 0; } static pascal void mytracker(ControlHandle ctl, short part) { - PyObject *args, *rv=0; - - args = Py_BuildValue("(O&i)", CtlObj_WhichControl, ctl, (int)part); - if (args && tracker) { - rv = PyEval_CallObject(tracker, args); - Py_DECREF(args); - } - if (rv) - Py_DECREF(rv); - else { - PySys_WriteStderr("TrackControl or HandleControlClick: exception in tracker function\\n"); - PyErr_Print(); - } + PyObject *args, *rv=0; + + args = Py_BuildValue("(O&i)", CtlObj_WhichControl, ctl, (int)part); + if (args && tracker) { + rv = PyEval_CallObject(tracker, args); + Py_DECREF(args); + } + if (rv) + Py_DECREF(rv); + else { + PySys_WriteStderr("TrackControl or HandleControlClick: exception in tracker function\\n"); + PyErr_Print(); + } } static int setcallback(PyObject *myself, OSType which, PyObject *callback, UniversalProcPtr *uppp) { - ControlObject *self = (ControlObject *)myself; - char keybuf[9]; - - if ( which == kMyControlActionProcTag ) - *uppp = (UniversalProcPtr)myactionproc_upp; - else if ( which == kControlUserPaneKeyDownProcTag ) - *uppp = (UniversalProcPtr)mykeydownproc_upp; - else if ( which == kControlUserPaneFocusProcTag ) - *uppp = (UniversalProcPtr)myfocusproc_upp; - else if ( which == kControlUserPaneDrawProcTag ) - *uppp = (UniversalProcPtr)mydrawproc_upp; - else if ( which == kControlUserPaneIdleProcTag ) - *uppp = (UniversalProcPtr)myidleproc_upp; - else if ( which == kControlUserPaneHitTestProcTag ) - *uppp = (UniversalProcPtr)myhittestproc_upp; - else if ( which == kControlUserPaneTrackingProcTag ) - *uppp = (UniversalProcPtr)mytrackingproc_upp; - else - return -1; - /* Only now do we test for clearing of the callback: */ - if ( callback == Py_None ) - *uppp = NULL; - /* Create the dict if it doesn't exist yet (so we don't get such a dict for every control) */ - if ( self->ob_callbackdict == NULL ) - if ( (self->ob_callbackdict = PyDict_New()) == NULL ) - return -1; - /* And store the Python callback */ - sprintf(keybuf, "%x", (unsigned)which); - if (PyDict_SetItemString(self->ob_callbackdict, keybuf, callback) < 0) - return -1; - return 0; + ControlObject *self = (ControlObject *)myself; + char keybuf[9]; + + if ( which == kMyControlActionProcTag ) + *uppp = (UniversalProcPtr)myactionproc_upp; + else if ( which == kControlUserPaneKeyDownProcTag ) + *uppp = (UniversalProcPtr)mykeydownproc_upp; + else if ( which == kControlUserPaneFocusProcTag ) + *uppp = (UniversalProcPtr)myfocusproc_upp; + else if ( which == kControlUserPaneDrawProcTag ) + *uppp = (UniversalProcPtr)mydrawproc_upp; + else if ( which == kControlUserPaneIdleProcTag ) + *uppp = (UniversalProcPtr)myidleproc_upp; + else if ( which == kControlUserPaneHitTestProcTag ) + *uppp = (UniversalProcPtr)myhittestproc_upp; + else if ( which == kControlUserPaneTrackingProcTag ) + *uppp = (UniversalProcPtr)mytrackingproc_upp; + else + return -1; + /* Only now do we test for clearing of the callback: */ + if ( callback == Py_None ) + *uppp = NULL; + /* Create the dict if it doesn't exist yet (so we don't get such a dict for every control) */ + if ( self->ob_callbackdict == NULL ) + if ( (self->ob_callbackdict = PyDict_New()) == NULL ) + return -1; + /* And store the Python callback */ + sprintf(keybuf, "%x", (unsigned)which); + if (PyDict_SetItemString(self->ob_callbackdict, keybuf, callback) < 0) + return -1; + return 0; } static PyObject * callcallback(ControlObject *self, OSType which, PyObject *arglist) { - char keybuf[9]; - PyObject *func, *rv; - - sprintf(keybuf, "%x", (unsigned)which); - if ( self->ob_callbackdict == NULL || - (func = PyDict_GetItemString(self->ob_callbackdict, keybuf)) == NULL ) { - PySys_WriteStderr("Control callback %x without callback object\\n", (unsigned)which); - return NULL; - } - rv = PyEval_CallObject(func, arglist); - if ( rv == NULL ) { - PySys_WriteStderr("Exception in control callback %x handler\\n", (unsigned)which); - PyErr_Print(); - } - return rv; + char keybuf[9]; + PyObject *func, *rv; + + sprintf(keybuf, "%x", (unsigned)which); + if ( self->ob_callbackdict == NULL || + (func = PyDict_GetItemString(self->ob_callbackdict, keybuf)) == NULL ) { + PySys_WriteStderr("Control callback %x without callback object\\n", (unsigned)which); + return NULL; + } + rv = PyEval_CallObject(func, arglist); + if ( rv == NULL ) { + PySys_WriteStderr("Exception in control callback %x handler\\n", (unsigned)which); + PyErr_Print(); + } + return rv; } static pascal void myactionproc(ControlHandle control, SInt16 part) { - ControlObject *ctl_obj; - PyObject *arglist, *rv; - - ctl_obj = (ControlObject *)CtlObj_WhichControl(control); - arglist = Py_BuildValue("Oh", ctl_obj, part); - rv = callcallback(ctl_obj, kMyControlActionProcTag, arglist); - Py_XDECREF(arglist); - Py_XDECREF(rv); + ControlObject *ctl_obj; + PyObject *arglist, *rv; + + ctl_obj = (ControlObject *)CtlObj_WhichControl(control); + arglist = Py_BuildValue("Oh", ctl_obj, part); + rv = callcallback(ctl_obj, kMyControlActionProcTag, arglist); + Py_XDECREF(arglist); + Py_XDECREF(rv); } static pascal ControlPartCode mykeydownproc(ControlHandle control, SInt16 keyCode, SInt16 charCode, SInt16 modifiers) { - ControlObject *ctl_obj; - PyObject *arglist, *rv; - short c_rv = 0; - - ctl_obj = (ControlObject *)CtlObj_WhichControl(control); - arglist = Py_BuildValue("Ohhh", ctl_obj, keyCode, charCode, modifiers); - rv = callcallback(ctl_obj, kControlUserPaneKeyDownProcTag, arglist); - Py_XDECREF(arglist); - if ( rv ) - if (!PyArg_Parse(rv, "h", &c_rv)) - PyErr_Clear(); - Py_XDECREF(rv); - return (ControlPartCode)c_rv; + ControlObject *ctl_obj; + PyObject *arglist, *rv; + short c_rv = 0; + + ctl_obj = (ControlObject *)CtlObj_WhichControl(control); + arglist = Py_BuildValue("Ohhh", ctl_obj, keyCode, charCode, modifiers); + rv = callcallback(ctl_obj, kControlUserPaneKeyDownProcTag, arglist); + Py_XDECREF(arglist); + if ( rv ) + if (!PyArg_Parse(rv, "h", &c_rv)) + PyErr_Clear(); + Py_XDECREF(rv); + return (ControlPartCode)c_rv; } static pascal ControlPartCode myfocusproc(ControlHandle control, ControlPartCode part) { - ControlObject *ctl_obj; - PyObject *arglist, *rv; - short c_rv = kControlFocusNoPart; - - ctl_obj = (ControlObject *)CtlObj_WhichControl(control); - arglist = Py_BuildValue("Oh", ctl_obj, part); - rv = callcallback(ctl_obj, kControlUserPaneFocusProcTag, arglist); - Py_XDECREF(arglist); - if ( rv ) - if (!PyArg_Parse(rv, "h", &c_rv)) - PyErr_Clear(); - Py_XDECREF(rv); - return (ControlPartCode)c_rv; + ControlObject *ctl_obj; + PyObject *arglist, *rv; + short c_rv = kControlFocusNoPart; + + ctl_obj = (ControlObject *)CtlObj_WhichControl(control); + arglist = Py_BuildValue("Oh", ctl_obj, part); + rv = callcallback(ctl_obj, kControlUserPaneFocusProcTag, arglist); + Py_XDECREF(arglist); + if ( rv ) + if (!PyArg_Parse(rv, "h", &c_rv)) + PyErr_Clear(); + Py_XDECREF(rv); + return (ControlPartCode)c_rv; } static pascal void mydrawproc(ControlHandle control, SInt16 part) { - ControlObject *ctl_obj; - PyObject *arglist, *rv; - - ctl_obj = (ControlObject *)CtlObj_WhichControl(control); - arglist = Py_BuildValue("Oh", ctl_obj, part); - rv = callcallback(ctl_obj, kControlUserPaneDrawProcTag, arglist); - Py_XDECREF(arglist); - Py_XDECREF(rv); + ControlObject *ctl_obj; + PyObject *arglist, *rv; + + ctl_obj = (ControlObject *)CtlObj_WhichControl(control); + arglist = Py_BuildValue("Oh", ctl_obj, part); + rv = callcallback(ctl_obj, kControlUserPaneDrawProcTag, arglist); + Py_XDECREF(arglist); + Py_XDECREF(rv); } static pascal void myidleproc(ControlHandle control) { - ControlObject *ctl_obj; - PyObject *arglist, *rv; - - ctl_obj = (ControlObject *)CtlObj_WhichControl(control); - arglist = Py_BuildValue("O", ctl_obj); - rv = callcallback(ctl_obj, kControlUserPaneIdleProcTag, arglist); - Py_XDECREF(arglist); - Py_XDECREF(rv); + ControlObject *ctl_obj; + PyObject *arglist, *rv; + + ctl_obj = (ControlObject *)CtlObj_WhichControl(control); + arglist = Py_BuildValue("O", ctl_obj); + rv = callcallback(ctl_obj, kControlUserPaneIdleProcTag, arglist); + Py_XDECREF(arglist); + Py_XDECREF(rv); } static pascal ControlPartCode myhittestproc(ControlHandle control, Point where) { - ControlObject *ctl_obj; - PyObject *arglist, *rv; - short c_rv = -1; - - ctl_obj = (ControlObject *)CtlObj_WhichControl(control); - arglist = Py_BuildValue("OO&", ctl_obj, PyMac_BuildPoint, where); - rv = callcallback(ctl_obj, kControlUserPaneHitTestProcTag, arglist); - Py_XDECREF(arglist); - /* Ignore errors, nothing we can do about them */ - if ( rv ) - if (!PyArg_Parse(rv, "h", &c_rv)) - PyErr_Clear(); - Py_XDECREF(rv); - return (ControlPartCode)c_rv; + ControlObject *ctl_obj; + PyObject *arglist, *rv; + short c_rv = -1; + + ctl_obj = (ControlObject *)CtlObj_WhichControl(control); + arglist = Py_BuildValue("OO&", ctl_obj, PyMac_BuildPoint, where); + rv = callcallback(ctl_obj, kControlUserPaneHitTestProcTag, arglist); + Py_XDECREF(arglist); + /* Ignore errors, nothing we can do about them */ + if ( rv ) + if (!PyArg_Parse(rv, "h", &c_rv)) + PyErr_Clear(); + Py_XDECREF(rv); + return (ControlPartCode)c_rv; } static pascal ControlPartCode mytrackingproc(ControlHandle control, Point startPt, ControlActionUPP actionProc) { - ControlObject *ctl_obj; - PyObject *arglist, *rv; - short c_rv = -1; - - ctl_obj = (ControlObject *)CtlObj_WhichControl(control); - /* We cannot pass the actionProc without lots of work */ - arglist = Py_BuildValue("OO&", ctl_obj, PyMac_BuildPoint, startPt); - rv = callcallback(ctl_obj, kControlUserPaneTrackingProcTag, arglist); - Py_XDECREF(arglist); - if ( rv ) - if (!PyArg_Parse(rv, "h", &c_rv)) - PyErr_Clear(); - Py_XDECREF(rv); - return (ControlPartCode)c_rv; + ControlObject *ctl_obj; + PyObject *arglist, *rv; + short c_rv = -1; + + ctl_obj = (ControlObject *)CtlObj_WhichControl(control); + /* We cannot pass the actionProc without lots of work */ + arglist = Py_BuildValue("OO&", ctl_obj, PyMac_BuildPoint, startPt); + rv = callcallback(ctl_obj, kControlUserPaneTrackingProcTag, arglist); + Py_XDECREF(arglist); + if ( rv ) + if (!PyArg_Parse(rv, "h", &c_rv)) + PyErr_Clear(); + Py_XDECREF(rv); + return (ControlPartCode)c_rv; } """ @@ -482,18 +482,18 @@ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ControlHandle, CtlObj_Convert); """ class MyObjectDefinition(PEP253Mixin, ObjectIdentityMixin, GlobalObjectDefinition): - def outputStructMembers(self): - GlobalObjectDefinition.outputStructMembers(self) - Output("PyObject *ob_callbackdict;") - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - def outputInitStructMembers(self): - GlobalObjectDefinition.outputInitStructMembers(self) - Output("SetControlReference(itself, (long)it);") - Output("it->ob_callbackdict = NULL;") - def outputCleanupStructMembers(self): - Output("Py_XDECREF(self->ob_callbackdict);") - Output("if (self->ob_itself)SetControlReference(self->ob_itself, (long)0); /* Make it forget about us */") + def outputStructMembers(self): + GlobalObjectDefinition.outputStructMembers(self) + Output("PyObject *ob_callbackdict;") + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + def outputInitStructMembers(self): + GlobalObjectDefinition.outputInitStructMembers(self) + Output("SetControlReference(itself, (long)it);") + Output("it->ob_callbackdict = NULL;") + def outputCleanupStructMembers(self): + Output("Py_XDECREF(self->ob_callbackdict);") + Output("if (self->ob_itself)SetControlReference(self->ob_itself, (long)0); /* Make it forget about us */") # Create the generator groups and link them module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff) @@ -523,14 +523,14 @@ PyObject *callback = 0; if (!PyArg_ParseTuple(_args, "O&|O", PyMac_GetPoint, &startPoint, &callback)) - return NULL; + return NULL; if (callback && callback != Py_None) { - if (PyInt_Check(callback) && PyInt_AS_LONG(callback) == -1) - upp = (ControlActionUPP)-1; - else { - settrackfunc(callback); - upp = mytracker_upp; - } + if (PyInt_Check(callback) && PyInt_AS_LONG(callback) == -1) + upp = (ControlActionUPP)-1; + else { + settrackfunc(callback); + upp = mytracker_upp; + } } _rv = TrackControl(_self->ob_itself, startPoint, @@ -558,14 +558,14 @@ if (!PyArg_ParseTuple(_args, "O&h|O", PyMac_GetPoint, &startPoint, &modifiers, &callback)) - return NULL; + return NULL; if (callback && callback != Py_None) { - if (PyInt_Check(callback) && PyInt_AS_LONG(callback) == -1) - upp = (ControlActionUPP)-1; - else { - settrackfunc(callback); - upp = mytracker_upp; - } + if (PyInt_Check(callback) && PyInt_AS_LONG(callback) == -1) + upp = (ControlActionUPP)-1; + else { + settrackfunc(callback); + upp = mytracker_upp; + } } _rv = HandleControlClick(_self->ob_itself, startPoint, @@ -593,16 +593,16 @@ if (!PyArg_ParseTuple(_args, "hO&s#", &inPart, PyMac_GetOSType, &inTagName, &buffer, &bufferSize)) - return NULL; + return NULL; _err = SetControlData(_self->ob_itself, - inPart, - inTagName, - bufferSize, + inPart, + inTagName, + bufferSize, buffer); if (_err != noErr) - return PyMac_Error(_err); + return PyMac_Error(_err); _res = Py_None; return _res; """ @@ -623,29 +623,29 @@ Size outSize; if (!PyArg_ParseTuple(_args, "hO&", &inPart, PyMac_GetOSType, &inTagName)) - return NULL; + return NULL; /* allocate a buffer for the data */ _err = GetControlDataSize(_self->ob_itself, - inPart, - inTagName, + inPart, + inTagName, &bufferSize); if (_err != noErr) - return PyMac_Error(_err); + return PyMac_Error(_err); buffer = PyMem_NEW(char, bufferSize); if (buffer == NULL) - return PyErr_NoMemory(); + return PyErr_NoMemory(); _err = GetControlData(_self->ob_itself, - inPart, - inTagName, - bufferSize, + inPart, + inTagName, + bufferSize, buffer, &outSize); if (_err != noErr) { - PyMem_DEL(buffer); - return PyMac_Error(_err); + PyMem_DEL(buffer); + return PyMac_Error(_err); } _res = Py_BuildValue("s#", buffer, outSize); PyMem_DEL(buffer); @@ -667,16 +667,16 @@ if (!PyArg_ParseTuple(_args, "hO&O&", &inPart, PyMac_GetOSType, &inTagName, OptResObj_Convert, &buffer)) - return NULL; + return NULL; _err = SetControlData(_self->ob_itself, - inPart, - inTagName, - sizeof(buffer), + inPart, + inTagName, + sizeof(buffer), (Ptr)&buffer); if (_err != noErr) - return PyMac_Error(_err); + return PyMac_Error(_err); _res = Py_None; return _res; """ @@ -696,29 +696,29 @@ Handle hdl; if (!PyArg_ParseTuple(_args, "hO&", &inPart, PyMac_GetOSType, &inTagName)) - return NULL; + return NULL; /* Check it is handle-sized */ _err = GetControlDataSize(_self->ob_itself, - inPart, - inTagName, + inPart, + inTagName, &bufferSize); if (_err != noErr) - return PyMac_Error(_err); + return PyMac_Error(_err); if (bufferSize != sizeof(Handle)) { - PyErr_SetString(Ctl_Error, "GetControlDataSize() != sizeof(Handle)"); - return NULL; + PyErr_SetString(Ctl_Error, "GetControlDataSize() != sizeof(Handle)"); + return NULL; } _err = GetControlData(_self->ob_itself, - inPart, - inTagName, - sizeof(Handle), + inPart, + inTagName, + sizeof(Handle), (Ptr)&hdl, &bufferSize); if (_err != noErr) { - return PyMac_Error(_err); + return PyMac_Error(_err); } _res = Py_BuildValue("O&", OptResObj_New, hdl); return _res; @@ -740,18 +740,18 @@ if (!PyArg_ParseTuple(_args, "hO&O", &inPart, PyMac_GetOSType, &inTagName, &callback)) - return NULL; + return NULL; if ( setcallback((PyObject *)_self, inTagName, callback, &c_callback) < 0 ) - return NULL; + return NULL; _err = SetControlData(_self->ob_itself, - inPart, - inTagName, - sizeof(c_callback), + inPart, + inTagName, + sizeof(c_callback), (Ptr)&c_callback); if (_err != noErr) - return PyMac_Error(_err); + return PyMac_Error(_err); _res = Py_None; return _res; """ @@ -783,26 +783,26 @@ if (!PyArg_ParseTuple(_args, "O&O&HHO", &size, &direction, &tabArrayObj)) - return NULL; + return NULL; i = PySequence_Length(tabArrayObj); if (i == -1) - return NULL; + return NULL; if (i > MAXTABS) { - PyErr_SetString(Ctl_Error, "Too many tabs"); - return NULL; + PyErr_SetString(Ctl_Error, "Too many tabs"); + return NULL; } numTabs = i; for (i=0; i<numTabs; i++) { - tabEntry = PySequence_GetItem(tabArrayObj, i); - if (tabEntry == NULL) - return NULL; - if (!PyArg_Parse(tabEntry, "(O&O&B)", - ControlButtonContentInfo_Convert, &tabArray[i].icon, - CFStringRefObj_Convert, &tabArray[i].name, - &tabArray[i].enabled - )) - return NULL; + tabEntry = PySequence_GetItem(tabArrayObj, i); + if (tabEntry == NULL) + return NULL; + if (!PyArg_Parse(tabEntry, "(O&O&B)", + ControlButtonContentInfo_Convert, &tabArray[i].icon, + CFStringRefObj_Convert, &tabArray[i].name, + &tabArray[i].enabled + )) + return NULL; } _err = CreateTabsControl(window, diff --git a/Mac/Modules/dlg/dlgscan.py b/Mac/Modules/dlg/dlgscan.py index 3710d5d..7fb68f7 100644 --- a/Mac/Modules/dlg/dlgscan.py +++ b/Mac/Modules/dlg/dlgscan.py @@ -12,105 +12,105 @@ SHORT = "dlg" OBJECT = "DialogPtr" def main(): - input = LONG + ".h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = LONG + ".h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t in ("DialogPtr", "DialogRef") and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname - - def makeblacklistnames(self): - return [ - 'InitDialogs', - 'ErrorSound', - # Dialogs are disposed when the object is deleted - 'CloseDialog', - 'DisposDialog', - 'DisposeDialog', - 'UpdtDialog', - 'CouldAlert', - 'FreeAlert', - 'CouldDialog', - 'FreeDialog', - 'GetStdFilterProc', - 'GetDialogParent', -## # Can't find these in the CW Pro 3 libraries - 'SetDialogMovableModal', - 'GetDialogControlNotificationProc', - 'SetGrafPortOfDialog', # Funny, and probably not useful - # Can't find these: - 'CloseStandardSheet', - 'RunStandardAlert', - ] - - def makeblacklisttypes(self): - return [ - "AlertStdAlertParamPtr", # Too much work, for now - "AlertStdAlertParamRec", # ditto - "AlertStdAlertParamRec_ptr", # ditto - "AlertStdCFStringAlertParamPtr", # ditto - "AlertStdCFStringAlertParamRec", - "AlertStdCFStringAlertParamRec_ptr", - "QTModelessCallbackProcPtr", - ] - - def makerepairinstructions(self): - return [ - ([("Str255", "*", "InMode")], - [("*", "*", "OutMode")]), - - ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], - [("InBuffer", "*", "*")]), - - ([("void", "*", "OutMode"), ("long", "*", "InMode"), - ("long", "*", "OutMode")], - [("VarVarOutBuffer", "*", "InOutMode")]), - - # GetDialogItem return handle is optional - ([("Handle", "item", "OutMode")], - [("OptHandle", "item", "OutMode")]), - - # NewDialog ETC. - ([("void", "*", "OutMode")], - [("NullStorage", "*", "InMode")]), - - ([("DialogPtr", "*", "OutMode")], - [("ExistingDialogPtr", "*", "*")]), - ([("DialogRef", "*", "OutMode")], - [("ExistingDialogPtr", "*", "*")]), - ([("WindowPtr", "*", "OutMode")], - [("ExistingWindowPtr", "*", "*")]), - ([("WindowPtr", "*", "ReturnMode")], - [("ExistingWindowPtr", "*", "*")]), - - # StdFilterProc - ([('EventRecord', 'event', 'OutMode'), - ('DialogItemIndex', 'itemHit', 'OutMode')], - [('EventRecord', 'event', 'InOutMode'), - ('DialogItemIndex', 'itemHit', 'InOutMode')]) - - ] - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t in ("DialogPtr", "DialogRef") and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname + + def makeblacklistnames(self): + return [ + 'InitDialogs', + 'ErrorSound', + # Dialogs are disposed when the object is deleted + 'CloseDialog', + 'DisposDialog', + 'DisposeDialog', + 'UpdtDialog', + 'CouldAlert', + 'FreeAlert', + 'CouldDialog', + 'FreeDialog', + 'GetStdFilterProc', + 'GetDialogParent', +## # Can't find these in the CW Pro 3 libraries + 'SetDialogMovableModal', + 'GetDialogControlNotificationProc', + 'SetGrafPortOfDialog', # Funny, and probably not useful + # Can't find these: + 'CloseStandardSheet', + 'RunStandardAlert', + ] + + def makeblacklisttypes(self): + return [ + "AlertStdAlertParamPtr", # Too much work, for now + "AlertStdAlertParamRec", # ditto + "AlertStdAlertParamRec_ptr", # ditto + "AlertStdCFStringAlertParamPtr", # ditto + "AlertStdCFStringAlertParamRec", + "AlertStdCFStringAlertParamRec_ptr", + "QTModelessCallbackProcPtr", + ] + + def makerepairinstructions(self): + return [ + ([("Str255", "*", "InMode")], + [("*", "*", "OutMode")]), + + ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], + [("InBuffer", "*", "*")]), + + ([("void", "*", "OutMode"), ("long", "*", "InMode"), + ("long", "*", "OutMode")], + [("VarVarOutBuffer", "*", "InOutMode")]), + + # GetDialogItem return handle is optional + ([("Handle", "item", "OutMode")], + [("OptHandle", "item", "OutMode")]), + + # NewDialog ETC. + ([("void", "*", "OutMode")], + [("NullStorage", "*", "InMode")]), + + ([("DialogPtr", "*", "OutMode")], + [("ExistingDialogPtr", "*", "*")]), + ([("DialogRef", "*", "OutMode")], + [("ExistingDialogPtr", "*", "*")]), + ([("WindowPtr", "*", "OutMode")], + [("ExistingWindowPtr", "*", "*")]), + ([("WindowPtr", "*", "ReturnMode")], + [("ExistingWindowPtr", "*", "*")]), + + # StdFilterProc + ([('EventRecord', 'event', 'OutMode'), + ('DialogItemIndex', 'itemHit', 'OutMode')], + [('EventRecord', 'event', 'InOutMode'), + ('DialogItemIndex', 'itemHit', 'InOutMode')]) + + ] + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/dlg/dlgsupport.py b/Mac/Modules/dlg/dlgsupport.py index 85bc607..1c0cc6a 100644 --- a/Mac/Modules/dlg/dlgsupport.py +++ b/Mac/Modules/dlg/dlgsupport.py @@ -50,55 +50,55 @@ static pascal Boolean Dlg_UnivFilterProc(DialogPtr dialog, EventRecord *event, short *itemHit) { - Boolean rv; - PyObject *args, *res; - PyObject *callback = Dlg_FilterProc_callback; - if (callback == NULL) - return 0; /* Default behavior */ - Dlg_FilterProc_callback = NULL; /* We'll restore it when call successful */ - args = Py_BuildValue("O&O&", DlgObj_WhichDialog, dialog, PyMac_BuildEventRecord, event); - if (args == NULL) - res = NULL; - else { - res = PyEval_CallObject(callback, args); - Py_DECREF(args); - } - if (res == NULL) { - PySys_WriteStderr("Exception in Dialog Filter\\n"); - PyErr_Print(); - *itemHit = -1; /* Fake return item */ - return 1; /* We handled it */ - } - else { - Dlg_FilterProc_callback = callback; - if (PyInt_Check(res)) { - *itemHit = PyInt_AsLong(res); - rv = 1; - } - else - rv = PyObject_IsTrue(res); - } - Py_DECREF(res); - return rv; + Boolean rv; + PyObject *args, *res; + PyObject *callback = Dlg_FilterProc_callback; + if (callback == NULL) + return 0; /* Default behavior */ + Dlg_FilterProc_callback = NULL; /* We'll restore it when call successful */ + args = Py_BuildValue("O&O&", DlgObj_WhichDialog, dialog, PyMac_BuildEventRecord, event); + if (args == NULL) + res = NULL; + else { + res = PyEval_CallObject(callback, args); + Py_DECREF(args); + } + if (res == NULL) { + PySys_WriteStderr("Exception in Dialog Filter\\n"); + PyErr_Print(); + *itemHit = -1; /* Fake return item */ + return 1; /* We handled it */ + } + else { + Dlg_FilterProc_callback = callback; + if (PyInt_Check(res)) { + *itemHit = PyInt_AsLong(res); + rv = 1; + } + else + rv = PyObject_IsTrue(res); + } + Py_DECREF(res); + return rv; } static ModalFilterUPP Dlg_PassFilterProc(PyObject *callback) { - PyObject *tmp = Dlg_FilterProc_callback; - static ModalFilterUPP UnivFilterUpp = NULL; - - Dlg_FilterProc_callback = NULL; - if (callback == Py_None) { - Py_XDECREF(tmp); - return NULL; - } - Py_INCREF(callback); - Dlg_FilterProc_callback = callback; - Py_XDECREF(tmp); - if ( UnivFilterUpp == NULL ) - UnivFilterUpp = NewModalFilterUPP(&Dlg_UnivFilterProc); - return UnivFilterUpp; + PyObject *tmp = Dlg_FilterProc_callback; + static ModalFilterUPP UnivFilterUpp = NULL; + + Dlg_FilterProc_callback = NULL; + if (callback == Py_None) { + Py_XDECREF(tmp); + return NULL; + } + Py_INCREF(callback); + Dlg_FilterProc_callback = callback; + Py_XDECREF(tmp); + if ( UnivFilterUpp == NULL ) + UnivFilterUpp = NewModalFilterUPP(&Dlg_UnivFilterProc); + return UnivFilterUpp; } static PyObject *Dlg_UserItemProc_callback = NULL; @@ -106,24 +106,24 @@ static PyObject *Dlg_UserItemProc_callback = NULL; static pascal void Dlg_UnivUserItemProc(DialogPtr dialog, short item) { - PyObject *args, *res; - - if (Dlg_UserItemProc_callback == NULL) - return; /* Default behavior */ - Dlg_FilterProc_callback = NULL; /* We'll restore it when call successful */ - args = Py_BuildValue("O&h", DlgObj_WhichDialog, dialog, item); - if (args == NULL) - res = NULL; - else { - res = PyEval_CallObject(Dlg_UserItemProc_callback, args); - Py_DECREF(args); - } - if (res == NULL) { - PySys_WriteStderr("Exception in Dialog UserItem proc\\n"); - PyErr_Print(); - } - Py_XDECREF(res); - return; + PyObject *args, *res; + + if (Dlg_UserItemProc_callback == NULL) + return; /* Default behavior */ + Dlg_FilterProc_callback = NULL; /* We'll restore it when call successful */ + args = Py_BuildValue("O&h", DlgObj_WhichDialog, dialog, item); + if (args == NULL) + res = NULL; + else { + res = PyEval_CallObject(Dlg_UserItemProc_callback, args); + Py_DECREF(args); + } + if (res == NULL) { + PySys_WriteStderr("Exception in Dialog UserItem proc\\n"); + PyErr_Print(); + } + Py_XDECREF(res); + return; } #if 0 @@ -146,9 +146,9 @@ finalstuff = finalstuff + """ WindowPtr DlgObj_ConvertToWindow(PyObject *self) { - if ( DlgObj_Check(self) ) - return GetDialogWindow(((DialogObject *)self)->ob_itself); - return NULL; + if ( DlgObj_Check(self) ) + return GetDialogWindow(((DialogObject *)self)->ob_itself); + return NULL; } #endif /* Return the object corresponding to the dialog, or None */ @@ -156,77 +156,77 @@ DlgObj_ConvertToWindow(PyObject *self) PyObject * DlgObj_WhichDialog(DialogPtr d) { - PyObject *it; - - if (d == NULL) { - it = Py_None; - Py_INCREF(it); - } else { - WindowPtr w = GetDialogWindow(d); - - it = (PyObject *) GetWRefCon(w); - if (it == NULL || ((DialogObject *)it)->ob_itself != d || !DlgObj_Check(it)) { + PyObject *it; + + if (d == NULL) { + it = Py_None; + Py_INCREF(it); + } else { + WindowPtr w = GetDialogWindow(d); + + it = (PyObject *) GetWRefCon(w); + if (it == NULL || ((DialogObject *)it)->ob_itself != d || !DlgObj_Check(it)) { #if 0 - /* Should do this, but we don't have an ob_freeit for dialogs yet. */ - it = WinObj_New(w); - ((WindowObject *)it)->ob_freeit = NULL; + /* Should do this, but we don't have an ob_freeit for dialogs yet. */ + it = WinObj_New(w); + ((WindowObject *)it)->ob_freeit = NULL; #else - it = Py_None; - Py_INCREF(it); + it = Py_None; + Py_INCREF(it); #endif - } else { - Py_INCREF(it); - } - } - return it; + } else { + Py_INCREF(it); + } + } + return it; } """ initstuff = initstuff + """ - PyMac_INIT_TOOLBOX_OBJECT_NEW(DialogPtr, DlgObj_New); - PyMac_INIT_TOOLBOX_OBJECT_NEW(DialogPtr, DlgObj_WhichDialog); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(DialogPtr, DlgObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(DialogPtr, DlgObj_New); + PyMac_INIT_TOOLBOX_OBJECT_NEW(DialogPtr, DlgObj_WhichDialog); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(DialogPtr, DlgObj_Convert); """ # Define a class which specializes our object definition class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def __init__(self, name, prefix = None, itselftype = None): - GlobalObjectDefinition.__init__(self, name, prefix, itselftype) + def __init__(self, name, prefix = None, itselftype = None): + GlobalObjectDefinition.__init__(self, name, prefix, itselftype) ## This won't work in Carbon, so we disable it for all MacPythons:-( ## But see the comment above:-(( -## self.basechain = "&WinObj_chain" - - def outputInitStructMembers(self): - GlobalObjectDefinition.outputInitStructMembers(self) - Output("SetWRefCon(GetDialogWindow(itself), (long)it);") - - def outputCheckNewArg(self): - Output("if (itself == NULL) return Py_None;") - - def outputCheckConvertArg(self): - Output("if (v == Py_None) { *p_itself = NULL; return 1; }") - Output("if (PyInt_Check(v)) { *p_itself = (DialogPtr)PyInt_AsLong(v);") - Output(" return 1; }") - - def outputCompare(self): - Output() - Output("static int %s_compare(%s *self, %s *other)", self.prefix, self.objecttype, self.objecttype) - OutLbrace() - Output("if ( self->ob_itself > other->ob_itself ) return 1;") - Output("if ( self->ob_itself < other->ob_itself ) return -1;") - Output("return 0;") - OutRbrace() - - def outputHash(self): - Output() - Output("static int %s_hash(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("return (int)self->ob_itself;") - OutRbrace() - - def outputFreeIt(self, itselfname): - Output("DisposeDialog(%s);", itselfname) +## self.basechain = "&WinObj_chain" + + def outputInitStructMembers(self): + GlobalObjectDefinition.outputInitStructMembers(self) + Output("SetWRefCon(GetDialogWindow(itself), (long)it);") + + def outputCheckNewArg(self): + Output("if (itself == NULL) return Py_None;") + + def outputCheckConvertArg(self): + Output("if (v == Py_None) { *p_itself = NULL; return 1; }") + Output("if (PyInt_Check(v)) { *p_itself = (DialogPtr)PyInt_AsLong(v);") + Output(" return 1; }") + + def outputCompare(self): + Output() + Output("static int %s_compare(%s *self, %s *other)", self.prefix, self.objecttype, self.objecttype) + OutLbrace() + Output("if ( self->ob_itself > other->ob_itself ) return 1;") + Output("if ( self->ob_itself < other->ob_itself ) return -1;") + Output("return 0;") + OutRbrace() + + def outputHash(self): + Output() + Output("static int %s_hash(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("return (int)self->ob_itself;") + OutRbrace() + + def outputFreeIt(self, itselfname): + Output("DisposeDialog(%s);", itselfname) # Create the generator groups and link them module = MacModule('_Dlg', 'Dlg', includestuff, finalstuff, initstuff) @@ -247,28 +247,28 @@ for f in functions: module.add(f) for f in methods: object.add(f) setuseritembody = """ - PyObject *new = NULL; - - - if (!PyArg_ParseTuple(_args, "|O", &new)) - return NULL; - - if (Dlg_UserItemProc_callback && new && new != Py_None) { - PyErr_SetString(Dlg_Error, "Another UserItemProc is already installed"); - return NULL; - } - - if (new == NULL || new == Py_None) { - new = NULL; - _res = Py_None; - Py_INCREF(Py_None); - } else { - Py_INCREF(new); - _res = Py_BuildValue("O&", ResObj_New, (Handle)NewUserItemUPP(Dlg_UnivUserItemProc)); - } - - Dlg_UserItemProc_callback = new; - return _res; + PyObject *new = NULL; + + + if (!PyArg_ParseTuple(_args, "|O", &new)) + return NULL; + + if (Dlg_UserItemProc_callback && new && new != Py_None) { + PyErr_SetString(Dlg_Error, "Another UserItemProc is already installed"); + return NULL; + } + + if (new == NULL || new == Py_None) { + new = NULL; + _res = Py_None; + Py_INCREF(Py_None); + } else { + Py_INCREF(new); + _res = Py_BuildValue("O&", ResObj_New, (Handle)NewUserItemUPP(Dlg_UnivUserItemProc)); + } + + Dlg_UserItemProc_callback = new; + return _res; """ f = ManualGenerator("SetUserItemHandler", setuseritembody) module.add(f) diff --git a/Mac/Modules/drag/dragscan.py b/Mac/Modules/drag/dragscan.py index 282728e..923a56b 100644 --- a/Mac/Modules/drag/dragscan.py +++ b/Mac/Modules/drag/dragscan.py @@ -7,74 +7,74 @@ sys.path.append(BGENDIR) from scantools import Scanner MISSING_DEFINES=""" -kDragHasLeftSenderWindow = (1 << 0) +kDragHasLeftSenderWindow = (1 << 0) kDragInsideSenderApplication = (1 << 1) -kDragInsideSenderWindow = (1 << 2) -kDragRegionAndImage = (1 << 4) -flavorSenderOnly = (1 << 0) -flavorSenderTranslated = (1 << 1) -flavorNotSaved = (1 << 2) -flavorSystemTranslated = (1 << 8) +kDragInsideSenderWindow = (1 << 2) +kDragRegionAndImage = (1 << 4) +flavorSenderOnly = (1 << 0) +flavorSenderTranslated = (1 << 1) +flavorNotSaved = (1 << 2) +flavorSystemTranslated = (1 << 8) """ def main(): - input = INCLUDEDIR + "Drag.h" - output = "draggen.py" - defsoutput = TOOLBOXDIR + "Dragconst.py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now doing 'import dragsupport' ===" - import dragsupport - print "=== Done. It's up to you to compile Dragmodule.c ===" + input = INCLUDEDIR + "Drag.h" + output = "draggen.py" + defsoutput = TOOLBOXDIR + "Dragconst.py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now doing 'import dragsupport' ===" + import dragsupport + print "=== Done. It's up to you to compile Dragmodule.c ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t in ('DragReference', 'DragRef') and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t in ('DragReference', 'DragRef') and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("from Carbon.TextEdit import *\n") - self.defsfile.write("from Carbon.QuickDraw import *\n") - self.defsfile.write("fkDragActionAll = -1\n") - self.defsfile.write("\n") - # Defines unparseable in Drag.h - self.defsfile.write(MISSING_DEFINES) + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("from Carbon.TextEdit import *\n") + self.defsfile.write("from Carbon.QuickDraw import *\n") + self.defsfile.write("fkDragActionAll = -1\n") + self.defsfile.write("\n") + # Defines unparseable in Drag.h + self.defsfile.write(MISSING_DEFINES) - def makeblacklistnames(self): - return [ - "kDragActionAll", - ] + def makeblacklistnames(self): + return [ + "kDragActionAll", + ] - def makeblacklisttypes(self): - return [ - "DragTrackingHandlerUPP", - "DragReceiveHandlerUPP", - "DragSendDataUPP", - "DragInputUPP", - "DragDrawingUPP", - ] + def makeblacklisttypes(self): + return [ + "DragTrackingHandlerUPP", + "DragReceiveHandlerUPP", + "DragSendDataUPP", + "DragInputUPP", + "DragDrawingUPP", + ] - def makerepairinstructions(self): - return [ - ([("void_ptr", "*", "InMode"), ("Size", "*", "InMode")], - [("OptionalInBuffer", "*", "*")]), - - ([("void", "*", "OutMode"), ("Size", "*", "OutMode")], - [("VarOutBuffer", "*", "InOutMode")]), - - ] + def makerepairinstructions(self): + return [ + ([("void_ptr", "*", "InMode"), ("Size", "*", "InMode")], + [("OptionalInBuffer", "*", "*")]), + + ([("void", "*", "OutMode"), ("Size", "*", "OutMode")], + [("VarOutBuffer", "*", "InOutMode")]), + + ] if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/drag/dragsupport.py b/Mac/Modules/drag/dragsupport.py index c200950..45838ef 100644 --- a/Mac/Modules/drag/dragsupport.py +++ b/Mac/Modules/drag/dragsupport.py @@ -6,16 +6,16 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Drag.h' # The Apple header file -MODNAME = '_Drag' # The name of the module -OBJECTNAME = 'DragObj' # The basic name of the objects used here +MACHEADERFILE = 'Drag.h' # The Apple header file +MODNAME = '_Drag' # The name of the module +OBJECTNAME = 'DragObj' # The basic name of the objects used here # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Drag' # The prefix for module-wide routines -OBJECTTYPE = 'DragRef' # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Drag' # The prefix for module-wide routines +OBJECTTYPE = 'DragRef' # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -69,81 +69,81 @@ static pascal OSErr dragglue_TrackingHandler(DragTrackingMessage theMessage, WindowPtr theWindow, void *handlerRefCon, DragReference theDrag) { - PyObject *args, *rv; - int i; - - args = Py_BuildValue("hO&O&", theMessage, DragObj_New, theDrag, WinObj_WhichWindow, theWindow); - if ( args == NULL ) - return -1; - rv = PyEval_CallObject((PyObject *)handlerRefCon, args); - Py_DECREF(args); - if ( rv == NULL ) { - PySys_WriteStderr("Drag: Exception in TrackingHandler\\n"); - PyErr_Print(); - return -1; - } - i = -1; - if ( rv == Py_None ) - i = 0; - else - PyArg_Parse(rv, "l", &i); - Py_DECREF(rv); - return i; + PyObject *args, *rv; + int i; + + args = Py_BuildValue("hO&O&", theMessage, DragObj_New, theDrag, WinObj_WhichWindow, theWindow); + if ( args == NULL ) + return -1; + rv = PyEval_CallObject((PyObject *)handlerRefCon, args); + Py_DECREF(args); + if ( rv == NULL ) { + PySys_WriteStderr("Drag: Exception in TrackingHandler\\n"); + PyErr_Print(); + return -1; + } + i = -1; + if ( rv == Py_None ) + i = 0; + else + PyArg_Parse(rv, "l", &i); + Py_DECREF(rv); + return i; } static pascal OSErr dragglue_ReceiveHandler(WindowPtr theWindow, void *handlerRefCon, DragReference theDrag) { - PyObject *args, *rv; - int i; - - args = Py_BuildValue("O&O&", DragObj_New, theDrag, WinObj_WhichWindow, theWindow); - if ( args == NULL ) - return -1; - rv = PyEval_CallObject((PyObject *)handlerRefCon, args); - Py_DECREF(args); - if ( rv == NULL ) { - PySys_WriteStderr("Drag: Exception in ReceiveHandler\\n"); - PyErr_Print(); - return -1; - } - i = -1; - if ( rv == Py_None ) - i = 0; - else - PyArg_Parse(rv, "l", &i); - Py_DECREF(rv); - return i; + PyObject *args, *rv; + int i; + + args = Py_BuildValue("O&O&", DragObj_New, theDrag, WinObj_WhichWindow, theWindow); + if ( args == NULL ) + return -1; + rv = PyEval_CallObject((PyObject *)handlerRefCon, args); + Py_DECREF(args); + if ( rv == NULL ) { + PySys_WriteStderr("Drag: Exception in ReceiveHandler\\n"); + PyErr_Print(); + return -1; + } + i = -1; + if ( rv == Py_None ) + i = 0; + else + PyArg_Parse(rv, "l", &i); + Py_DECREF(rv); + return i; } static pascal OSErr dragglue_SendData(FlavorType theType, void *dragSendRefCon, ItemReference theItem, DragReference theDrag) { - DragObjObject *self = (DragObjObject *)dragSendRefCon; - PyObject *args, *rv; - int i; - - if ( self->sendproc == NULL ) - return -1; - args = Py_BuildValue("O&l", PyMac_BuildOSType, theType, theItem); - if ( args == NULL ) - return -1; - rv = PyEval_CallObject(self->sendproc, args); - Py_DECREF(args); - if ( rv == NULL ) { - PySys_WriteStderr("Drag: Exception in SendDataHandler\\n"); - PyErr_Print(); - return -1; - } - i = -1; - if ( rv == Py_None ) - i = 0; - else - PyArg_Parse(rv, "l", &i); - Py_DECREF(rv); - return i; + DragObjObject *self = (DragObjObject *)dragSendRefCon; + PyObject *args, *rv; + int i; + + if ( self->sendproc == NULL ) + return -1; + args = Py_BuildValue("O&l", PyMac_BuildOSType, theType, theItem); + if ( args == NULL ) + return -1; + rv = PyEval_CallObject(self->sendproc, args); + Py_DECREF(args); + if ( rv == NULL ) { + PySys_WriteStderr("Drag: Exception in SendDataHandler\\n"); + PyErr_Print(); + return -1; + } + i = -1; + if ( rv == Py_None ) + i = 0; + else + PyArg_Parse(rv, "l", &i); + Py_DECREF(rv); + return i; } #if 0 @@ -165,8 +165,8 @@ dragglue_Drawing(xxxx """ initstuff = initstuff + """ - PyMac_INIT_TOOLBOX_OBJECT_NEW(DragRef, DragObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(DragRef, DragObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(DragRef, DragObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(DragRef, DragObj_Convert); """ variablestuff = """ @@ -177,33 +177,33 @@ dragglue_SendDataUPP = NewDragSendDataUPP(dragglue_SendData); dragglue_InputUPP = NewDragInputUPP(dragglue_Input); dragglue_DrawingUPP = NewDragDrawingUPP(dragglue_Drawing); #endif -""" +""" class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("""if (itself == NULL) { - PyErr_SetString(Drag_Error,"Cannot create null Drag"); - return NULL; - }""") - def outputFreeIt(self, itselfname): - ## Output("DisposeDrag(%s);", itselfname) - Output("Py_XDECREF(self->sendproc);") - ## Output("Py_XDECREF(self->inputproc);") - ## Output("Py_XDECREF(self->drawingproc);") - - def outputStructMembers(self): - GlobalObjectDefinition.outputStructMembers(self) - Output("PyObject *sendproc;") - ## Output("PyObject *inputproc;") - ## Output("PyObject *drawingproc;") - - def outputInitStructMembers(self): - GlobalObjectDefinition.outputInitStructMembers(self) - Output("it->sendproc = NULL;") - ## Output("it->inputproc = NULL;") - ## Output("it->drawingproc = NULL;") - - + def outputCheckNewArg(self): + Output("""if (itself == NULL) { + PyErr_SetString(Drag_Error,"Cannot create null Drag"); + return NULL; + }""") + def outputFreeIt(self, itselfname): + ## Output("DisposeDrag(%s);", itselfname) + Output("Py_XDECREF(self->sendproc);") + ## Output("Py_XDECREF(self->inputproc);") + ## Output("Py_XDECREF(self->drawingproc);") + + def outputStructMembers(self): + GlobalObjectDefinition.outputStructMembers(self) + Output("PyObject *sendproc;") + ## Output("PyObject *inputproc;") + ## Output("PyObject *drawingproc;") + + def outputInitStructMembers(self): + GlobalObjectDefinition.outputInitStructMembers(self) + Output("it->sendproc = NULL;") + ## Output("it->inputproc = NULL;") + ## Output("it->drawingproc = NULL;") + + # Create the generator groups and link them module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff, variablestuff) object = MyObjectDefinition(OBJECTNAME, OBJECTPREFIX, OBJECTTYPE) @@ -228,15 +228,15 @@ installtracking_body = """ PyObject *callback; WindowPtr theWindow = NULL; OSErr _err; - + if ( !PyArg_ParseTuple(_args, "O|O&", &callback, WinObj_Convert, &theWindow) ) - return NULL; - Py_INCREF(callback); /* Cannot decref later, too bad */ + return NULL; + Py_INCREF(callback); /* Cannot decref later, too bad */ _err = InstallTrackingHandler(dragglue_TrackingHandlerUPP, theWindow, (void *)callback); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; + if (_err != noErr) return PyMac_Error(_err); + Py_INCREF(Py_None); + _res = Py_None; + return _res; """ installtracking = ManualGenerator("InstallTrackingHandler", installtracking_body) module.add(installtracking) @@ -245,15 +245,15 @@ installreceive_body = """ PyObject *callback; WindowPtr theWindow = NULL; OSErr _err; - + if ( !PyArg_ParseTuple(_args, "O|O&", &callback, WinObj_Convert, &theWindow) ) - return NULL; - Py_INCREF(callback); /* Cannot decref later, too bad */ + return NULL; + Py_INCREF(callback); /* Cannot decref later, too bad */ _err = InstallReceiveHandler(dragglue_ReceiveHandlerUPP, theWindow, (void *)callback); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; + if (_err != noErr) return PyMac_Error(_err); + Py_INCREF(Py_None); + _res = Py_None; + return _res; """ installreceive = ManualGenerator("InstallReceiveHandler", installreceive_body) module.add(installreceive) @@ -261,14 +261,14 @@ module.add(installreceive) removetracking_body = """ WindowPtr theWindow = NULL; OSErr _err; - + if ( !PyArg_ParseTuple(_args, "|O&", WinObj_Convert, &theWindow) ) - return NULL; + return NULL; _err = RemoveTrackingHandler(dragglue_TrackingHandlerUPP, theWindow); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; + if (_err != noErr) return PyMac_Error(_err); + Py_INCREF(Py_None); + _res = Py_None; + return _res; """ removetracking = ManualGenerator("RemoveTrackingHandler", removetracking_body) module.add(removetracking) @@ -276,14 +276,14 @@ module.add(removetracking) removereceive_body = """ WindowPtr theWindow = NULL; OSErr _err; - + if ( !PyArg_ParseTuple(_args, "|O&", WinObj_Convert, &theWindow) ) - return NULL; + return NULL; _err = RemoveReceiveHandler(dragglue_ReceiveHandlerUPP, theWindow); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; + if (_err != noErr) return PyMac_Error(_err); + Py_INCREF(Py_None); + _res = Py_None; + return _res; """ removereceive = ManualGenerator("RemoveReceiveHandler", removereceive_body) module.add(removereceive) diff --git a/Mac/Modules/evt/evtedit.py b/Mac/Modules/evt/evtedit.py index 3426b70..02087e1 100644 --- a/Mac/Modules/evt/evtedit.py +++ b/Mac/Modules/evt/evtedit.py @@ -7,4 +7,3 @@ functions.append(f) f = Function(UInt32, 'TickCount', ) functions.append(f) - diff --git a/Mac/Modules/evt/evtscan.py b/Mac/Modules/evt/evtscan.py index e5762d9..0d0c9ec 100644 --- a/Mac/Modules/evt/evtscan.py +++ b/Mac/Modules/evt/evtscan.py @@ -11,71 +11,71 @@ SHORT = "evt" OBJECT = "NOTUSED" def main(): - input = LONG + ".h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = LONG + ".h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - # This is non-functional today - if t == OBJECT and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + # This is non-functional today + if t == OBJECT and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname - def makeblacklistnames(self): - return [ - "KeyTranslate", - "GetEventMask", # I cannot seem to find this routine... - "WaitNextEvent", # Manually generated because of optional region - # Constants with funny definitions - "osEvtMessageMask", - # OS8 calls - 'SystemEvent', - 'SystemTask', - 'SystemClick', - 'GetOSEvent', - 'OSEventAvail', - ] + def makeblacklistnames(self): + return [ + "KeyTranslate", + "GetEventMask", # I cannot seem to find this routine... + "WaitNextEvent", # Manually generated because of optional region + # Constants with funny definitions + "osEvtMessageMask", + # OS8 calls + 'SystemEvent', + 'SystemTask', + 'SystemClick', + 'GetOSEvent', + 'OSEventAvail', + ] - def makeblacklisttypes(self): - return [ - "EvQElPtr", "QHdrPtr" - ] + def makeblacklisttypes(self): + return [ + "EvQElPtr", "QHdrPtr" + ] + + def makerepairinstructions(self): + return [ + ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], + [("InBuffer", "*", "*")]), + + ([("void", "*", "OutMode"), ("long", "*", "InMode"), + ("long", "*", "OutMode")], + [("VarVarOutBuffer", "*", "InOutMode")]), + + ([("void", "wStorage", "OutMode")], + [("NullStorage", "*", "InMode")]), + + # GetKeys + ([('KeyMap', 'theKeys', 'InMode')], + [('*', '*', 'OutMode')]), + + # GetTicker + ([('unsigned long', '*', '*')], + [('unsigned_long', '*', '*')]), + ] - def makerepairinstructions(self): - return [ - ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], - [("InBuffer", "*", "*")]), - - ([("void", "*", "OutMode"), ("long", "*", "InMode"), - ("long", "*", "OutMode")], - [("VarVarOutBuffer", "*", "InOutMode")]), - - ([("void", "wStorage", "OutMode")], - [("NullStorage", "*", "InMode")]), - - # GetKeys - ([('KeyMap', 'theKeys', 'InMode')], - [('*', '*', 'OutMode')]), - - # GetTicker - ([('unsigned long', '*', '*')], - [('unsigned_long', '*', '*')]), - ] - if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/evt/evtsupport.py b/Mac/Modules/evt/evtsupport.py index ccdc1c5..f58da14 100644 --- a/Mac/Modules/evt/evtsupport.py +++ b/Mac/Modules/evt/evtsupport.py @@ -6,17 +6,17 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Events.h' # The Apple header file -MODNAME = '_Evt' # The name of the module -OBJECTNAME = 'Event' # The basic name of the objects used here -KIND = 'Record' # Usually 'Ptr' or 'Handle' +MACHEADERFILE = 'Events.h' # The Apple header file +MODNAME = '_Evt' # The name of the module +OBJECTNAME = 'Event' # The basic name of the objects used here +KIND = 'Record' # Usually 'Ptr' or 'Handle' # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Evt' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + KIND # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Evt' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + KIND # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -72,7 +72,7 @@ if (!PyArg_ParseTuple(_args, "Hl|O&", &eventMask, &sleep, OptResObj_Convert, &mouseregion)) - return NULL; + return NULL; _rv = WaitNextEvent(eventMask, &theEvent, sleep, @@ -90,4 +90,3 @@ module.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/file/filescan.py b/Mac/Modules/file/filescan.py index f8b5ba2..8ebc69f 100644 --- a/Mac/Modules/file/filescan.py +++ b/Mac/Modules/file/filescan.py @@ -10,190 +10,190 @@ LONG = "Files" SHORT = "file" def main(): - input = ["Files.h", "Aliases.h", "Finder.h"] - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - scanner.gentypetest(SHORT+"typetest.py") - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = ["Files.h", "Aliases.h", "Finder.h"] + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + scanner.gentypetest(SHORT+"typetest.py") + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner_OSX): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - # Funny special case - if len(arglist) > 2: - t, n, m = arglist[1] - if t == "AliasHandle" and m == "InMode": - classname = "Arg2MethodGenerator" - listname = "alias_methods" - return classname, listname - # Normal cases - t, n, m = arglist[0] - if t == "AliasHandle" and m == "InMode": - classname = "Method" - listname = "alias_methods" - if t == "FSSpec_ptr" and m == "InMode": - classname = "Method" - listname = "fsspec_methods" - if t == "FSRef_ptr" and m == "InMode": - classname = "Method" - listname = "fsref_methods" - return classname, listname - - def makeblacklistnames(self): - return [ - # Constants with incompatible definitions - "kioACAccessOwnerMask", - "kFSCatInfoReserved", - "kFSIterateReserved", - "kSystemFolderType", - - "FSRefMakePath", # Do this manually -# "ResolveAlias", # Do this manually -# "ResolveAliasWithMountFlags", # Do this manually -# "FollowFinderAlias", # Do this manually - - "FSRead", # Couldn't be bothered - "FSWrite", # ditto - "FSReadFork", # ditto - "FSWriteFork", # ditto - - # Old routines: - "GetWDInfo", - "OpenWD", - "CloseWD", - "FInitQueue", - "rstflock", - "setflock", - "setfinfo", - "fsrename", - "fsdelete", - "create", - "flushvol", - "eject", - "umountvol", - "setvol", - "getvol", - "getfinfo", - "getvinfo", - "fsopen", - "RstFLock", - "SetFLock", - "SetFInfo", - "Rename", - "OpenRF", - "FSDelete", - "Create", - "GetVol", - "GetFInfo", - "GetVInfo", - "FSOpen", - "Eject", - "SetVol", - "openrf", - "unmountvol", - "OpenDF", - - ] - - def makeblacklisttypes(self): - return [ - "CInfoPBPtr", # Old stuff - "CMovePBPtr", # Old stuff - "ParmBlkPtr", # Old stuff - "HParmBlkPtr", # Old stuff - "DTPBPtr", # Old stuff - "FCBPBPtr", # Old stuff - "QHdrPtr", # Old stuff - "CSParamPtr", # Old stuff - "FSCatalogBulkParam", # old stuff - "FSForkCBInfoParam", # old stuff - "FSForkIOParam", # old stuff - "FSRefParam", # old stuff - "FSVolumeInfoParam", # old stuff - "WDPBPtr", # old stuff - "XCInfoPBPtr", # old stuff - "XVolumeParamPtr", # old stuff - - - "CatPositionRec", # State variable, not too difficult - "FSIterator", # Should become an object - "FSForkInfo", # Lots of fields, difficult struct - "FSSearchParams", # Also catsearch stuff - "FSVolumeInfo", # big struct - "FSVolumeInfo_ptr", # big struct - - "IOCompletionProcPtr", # proc pointer - "IOCompletionUPP", # Proc pointer - "AliasFilterProcPtr", - "AliasFilterUPP", - "FNSubscriptionUPP", - - "FNSubscriptionRef", # Lazy, for now. - ] - - def makerepairinstructions(self): - return [ - # Various ways to give pathnames - ([('char_ptr', '*', 'InMode')], - [('stringptr', '*', 'InMode')] - ), - - # Unicode filenames passed as length, buffer - ([('UniCharCount', '*', 'InMode'), - ('UniChar_ptr', '*', 'InMode')], - [('UnicodeReverseInBuffer', '*', 'InMode')] - ), - # Wrong guess - ([('Str63', 'theString', 'InMode')], - [('Str63', 'theString', 'OutMode')]), - - # Yet another way to give a pathname:-) - ([('short', 'fullPathLength', 'InMode'), - ('void_ptr', 'fullPath', 'InMode')], - [('FullPathName', 'fullPath', 'InMode')]), - - # Various ResolveAliasFileXXXX functions - ([('FSSpec', 'theSpec', 'OutMode')], - [('FSSpec_ptr', 'theSpec', 'InOutMode')]), - - ([('FSRef', 'theRef', 'OutMode')], - [('FSRef_ptr', 'theRef', 'InOutMode')]), - - # The optional FSSpec to all ResolveAlias and NewAlias methods - ([('FSSpec_ptr', 'fromFile', 'InMode')], - [('OptFSSpecPtr', 'fromFile', 'InMode')]), - - ([('FSRef_ptr', 'fromFile', 'InMode')], - [('OptFSRefPtr', 'fromFile', 'InMode')]), - -## # FSCatalogInfo input handling -## ([('FSCatalogInfoBitmap', 'whichInfo', 'InMode'), -## ('FSCatalogInfo_ptr', 'catalogInfo', 'InMode')], -## [('FSCatalogInfoAndBitmap_in', 'catalogInfo', 'InMode')]), -## -## # FSCatalogInfo output handling -## ([('FSCatalogInfoBitmap', 'whichInfo', 'InMode'), -## ('FSCatalogInfo', 'catalogInfo', 'OutMode')], -## [('FSCatalogInfoAndBitmap_out', 'catalogInfo', 'InOutMode')]), -## - - ] - - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("true = True\n") - self.defsfile.write("false = False\n") - + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + # Funny special case + if len(arglist) > 2: + t, n, m = arglist[1] + if t == "AliasHandle" and m == "InMode": + classname = "Arg2MethodGenerator" + listname = "alias_methods" + return classname, listname + # Normal cases + t, n, m = arglist[0] + if t == "AliasHandle" and m == "InMode": + classname = "Method" + listname = "alias_methods" + if t == "FSSpec_ptr" and m == "InMode": + classname = "Method" + listname = "fsspec_methods" + if t == "FSRef_ptr" and m == "InMode": + classname = "Method" + listname = "fsref_methods" + return classname, listname + + def makeblacklistnames(self): + return [ + # Constants with incompatible definitions + "kioACAccessOwnerMask", + "kFSCatInfoReserved", + "kFSIterateReserved", + "kSystemFolderType", + + "FSRefMakePath", # Do this manually +# "ResolveAlias", # Do this manually +# "ResolveAliasWithMountFlags", # Do this manually +# "FollowFinderAlias", # Do this manually + + "FSRead", # Couldn't be bothered + "FSWrite", # ditto + "FSReadFork", # ditto + "FSWriteFork", # ditto + + # Old routines: + "GetWDInfo", + "OpenWD", + "CloseWD", + "FInitQueue", + "rstflock", + "setflock", + "setfinfo", + "fsrename", + "fsdelete", + "create", + "flushvol", + "eject", + "umountvol", + "setvol", + "getvol", + "getfinfo", + "getvinfo", + "fsopen", + "RstFLock", + "SetFLock", + "SetFInfo", + "Rename", + "OpenRF", + "FSDelete", + "Create", + "GetVol", + "GetFInfo", + "GetVInfo", + "FSOpen", + "Eject", + "SetVol", + "openrf", + "unmountvol", + "OpenDF", + + ] + + def makeblacklisttypes(self): + return [ + "CInfoPBPtr", # Old stuff + "CMovePBPtr", # Old stuff + "ParmBlkPtr", # Old stuff + "HParmBlkPtr", # Old stuff + "DTPBPtr", # Old stuff + "FCBPBPtr", # Old stuff + "QHdrPtr", # Old stuff + "CSParamPtr", # Old stuff + "FSCatalogBulkParam", # old stuff + "FSForkCBInfoParam", # old stuff + "FSForkIOParam", # old stuff + "FSRefParam", # old stuff + "FSVolumeInfoParam", # old stuff + "WDPBPtr", # old stuff + "XCInfoPBPtr", # old stuff + "XVolumeParamPtr", # old stuff + + + "CatPositionRec", # State variable, not too difficult + "FSIterator", # Should become an object + "FSForkInfo", # Lots of fields, difficult struct + "FSSearchParams", # Also catsearch stuff + "FSVolumeInfo", # big struct + "FSVolumeInfo_ptr", # big struct + + "IOCompletionProcPtr", # proc pointer + "IOCompletionUPP", # Proc pointer + "AliasFilterProcPtr", + "AliasFilterUPP", + "FNSubscriptionUPP", + + "FNSubscriptionRef", # Lazy, for now. + ] + + def makerepairinstructions(self): + return [ + # Various ways to give pathnames + ([('char_ptr', '*', 'InMode')], + [('stringptr', '*', 'InMode')] + ), + + # Unicode filenames passed as length, buffer + ([('UniCharCount', '*', 'InMode'), + ('UniChar_ptr', '*', 'InMode')], + [('UnicodeReverseInBuffer', '*', 'InMode')] + ), + # Wrong guess + ([('Str63', 'theString', 'InMode')], + [('Str63', 'theString', 'OutMode')]), + + # Yet another way to give a pathname:-) + ([('short', 'fullPathLength', 'InMode'), + ('void_ptr', 'fullPath', 'InMode')], + [('FullPathName', 'fullPath', 'InMode')]), + + # Various ResolveAliasFileXXXX functions + ([('FSSpec', 'theSpec', 'OutMode')], + [('FSSpec_ptr', 'theSpec', 'InOutMode')]), + + ([('FSRef', 'theRef', 'OutMode')], + [('FSRef_ptr', 'theRef', 'InOutMode')]), + + # The optional FSSpec to all ResolveAlias and NewAlias methods + ([('FSSpec_ptr', 'fromFile', 'InMode')], + [('OptFSSpecPtr', 'fromFile', 'InMode')]), + + ([('FSRef_ptr', 'fromFile', 'InMode')], + [('OptFSRefPtr', 'fromFile', 'InMode')]), + +## # FSCatalogInfo input handling +## ([('FSCatalogInfoBitmap', 'whichInfo', 'InMode'), +## ('FSCatalogInfo_ptr', 'catalogInfo', 'InMode')], +## [('FSCatalogInfoAndBitmap_in', 'catalogInfo', 'InMode')]), +## +## # FSCatalogInfo output handling +## ([('FSCatalogInfoBitmap', 'whichInfo', 'InMode'), +## ('FSCatalogInfo', 'catalogInfo', 'OutMode')], +## [('FSCatalogInfoAndBitmap_out', 'catalogInfo', 'InOutMode')]), +## + + ] + + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("true = True\n") + self.defsfile.write("false = False\n") + if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/file/filesupport.py b/Mac/Modules/file/filesupport.py index f06bbb8..dac706d 100644 --- a/Mac/Modules/file/filesupport.py +++ b/Mac/Modules/file/filesupport.py @@ -10,14 +10,14 @@ import string # Declarations that change for each manager -#MACHEADERFILE = 'Files.h' # The Apple header file -MODNAME = '_File' # The name of the module -LONGMODNAME = 'Carbon.File' # The "normal" external name of the module +#MACHEADERFILE = 'Files.h' # The Apple header file +MODNAME = '_File' # The name of the module +LONGMODNAME = 'Carbon.File' # The "normal" external name of the module # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'File' # The prefix for module-wide routines +MODPREFIX = 'File' # The prefix for module-wide routines INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -33,9 +33,9 @@ AliasInfoType = Type("AliasInfoType", "h") # Various types of strings: #class UniCharCountBuffer(InputOnlyType): -# pass +# pass class VarReverseInputBufferType(ReverseInputBufferMixin, VarInputBufferType): - pass + pass FullPathName = VarReverseInputBufferType() ConstStr31Param = OpaqueArrayType("Str31", "PyMac_BuildStr255", "PyMac_GetStr255") ConstStr32Param = OpaqueArrayType("Str32", "PyMac_BuildStr255", "PyMac_GetStr255") @@ -47,60 +47,60 @@ UInt8_ptr = InputOnlyType("UInt8 *", "s") # Other types: class OptionalFSxxxType(OpaqueByValueType): - def declare(self, name): - Output("%s %s__buf__;", self.typeName, name) - Output("%s *%s = &%s__buf__;", self.typeName, name, name) + def declare(self, name): + Output("%s %s__buf__;", self.typeName, name) + Output("%s *%s = &%s__buf__;", self.typeName, name, name) class FSCatalogInfoAndBitmapType(InputOnlyType): - - def __init__(self): - InputOnlyType.__init__(self, "BUG", "BUG") - - def declare(self, name): - Output("PyObject *%s__object = NULL;", name) - Output("FSCatalogInfoBitmap %s__bitmap = 0;", name) - Output("FSCatalogInfo %s;", name) - - def getargsFormat(self): - return "lO" - - def getargsArgs(self, name): - return "%s__bitmap, %s__object"%(name, name) - - def getargsCheck(self, name): - Output("if (!convert_FSCatalogInfo(%s__object, %s__bitmap, &%s)) return NULL;", name, name, name) - - def passInput(self, name): - return "%s__bitmap, &%s"% (name, name) - - def passOutput(self, name): - return "%s__bitmap, &%s"% (name, name) - - def mkvalueFormat(self): - return "O" - - def mkvalueArgs(self, name): - return "%s__object" % (name) - - def xxxxmkvalueCheck(self, name): - Output("if ((%s__object = new_FSCatalogInfo(%s__bitmap, &%s)) == NULL) return NULL;", name, name) - + + def __init__(self): + InputOnlyType.__init__(self, "BUG", "BUG") + + def declare(self, name): + Output("PyObject *%s__object = NULL;", name) + Output("FSCatalogInfoBitmap %s__bitmap = 0;", name) + Output("FSCatalogInfo %s;", name) + + def getargsFormat(self): + return "lO" + + def getargsArgs(self, name): + return "%s__bitmap, %s__object"%(name, name) + + def getargsCheck(self, name): + Output("if (!convert_FSCatalogInfo(%s__object, %s__bitmap, &%s)) return NULL;", name, name, name) + + def passInput(self, name): + return "%s__bitmap, &%s"% (name, name) + + def passOutput(self, name): + return "%s__bitmap, &%s"% (name, name) + + def mkvalueFormat(self): + return "O" + + def mkvalueArgs(self, name): + return "%s__object" % (name) + + def xxxxmkvalueCheck(self, name): + Output("if ((%s__object = new_FSCatalogInfo(%s__bitmap, &%s)) == NULL) return NULL;", name, name) + class FSCatalogInfoAndBitmap_inType(FSCatalogInfoAndBitmapType, InputOnlyMixIn): - - def xxxxmkvalueCheck(self, name): - pass - + + def xxxxmkvalueCheck(self, name): + pass + class FSCatalogInfoAndBitmap_outType(FSCatalogInfoAndBitmapType): - def getargsFormat(self): - return "l" - - def getargsArgs(self, name): - return "%s__bitmap" % name - - def getargsCheck(self, name): - pass - + def getargsFormat(self): + return "l" + + def getargsArgs(self, name): + return "%s__bitmap" % name + + def getargsCheck(self, name): + pass + FInfo = OpaqueType("FInfo", "FInfo") FInfo_ptr = OpaqueType("FInfo", "FInfo") AliasHandle = OpaqueByValueType("AliasHandle", "Alias") @@ -157,13 +157,13 @@ static int Alias_Convert(PyObject *v, AliasHandle *p_itself); static int UTCDateTime_Convert(PyObject *v, UTCDateTime *ptr) { - return PyArg_Parse(v, "(HlH)", &ptr->highSeconds, &ptr->lowSeconds, &ptr->fraction); + return PyArg_Parse(v, "(HlH)", &ptr->highSeconds, &ptr->lowSeconds, &ptr->fraction); } static PyObject * UTCDateTime_New(UTCDateTime *ptr) { - return Py_BuildValue("(HlH)", ptr->highSeconds, ptr->lowSeconds, ptr->fraction); + return Py_BuildValue("(HlH)", ptr->highSeconds, ptr->lowSeconds, ptr->fraction); } /* @@ -172,21 +172,21 @@ UTCDateTime_New(UTCDateTime *ptr) static int myPyMac_GetOptFSSpecPtr(PyObject *v, FSSpec **spec) { - if (v == Py_None) { - *spec = NULL; - return 1; - } - return PyMac_GetFSSpec(v, *spec); + if (v == Py_None) { + *spec = NULL; + return 1; + } + return PyMac_GetFSSpec(v, *spec); } static int myPyMac_GetOptFSRefPtr(PyObject *v, FSRef **ref) { - if (v == Py_None) { - *ref = NULL; - return 1; - } - return PyMac_GetFSRef(v, *ref); + if (v == Py_None) { + *ref = NULL; + return 1; + } + return PyMac_GetFSRef(v, *ref); } /* @@ -196,7 +196,7 @@ static PyObject * PyMac_BuildHFSUniStr255(HFSUniStr255 *itself) { - return Py_BuildValue("u#", itself->unicode, itself->length); + return Py_BuildValue("u#", itself->unicode, itself->length); } """ @@ -204,86 +204,86 @@ finalstuff = finalstuff + """ int PyMac_GetFSSpec(PyObject *v, FSSpec *spec) { - Str255 path; - short refnum; - long parid; - OSErr err; - FSRef fsr; - - if (FSSpec_Check(v)) { - *spec = ((FSSpecObject *)v)->ob_itself; - return 1; - } - - if (PyArg_Parse(v, "(hlO&)", - &refnum, &parid, PyMac_GetStr255, &path)) { - err = FSMakeFSSpec(refnum, parid, path, spec); - if ( err && err != fnfErr ) { - PyMac_Error(err); - return 0; - } - return 1; - } - PyErr_Clear(); - /* Otherwise we try to go via an FSRef. On OSX we go all the way, - ** on OS9 we accept only a real FSRef object - */ - if ( PyMac_GetFSRef(v, &fsr) ) { - err = FSGetCatalogInfo(&fsr, kFSCatInfoNone, NULL, NULL, spec, NULL); - if (err != noErr) { - PyMac_Error(err); - return 0; - } - return 1; - } - return 0; + Str255 path; + short refnum; + long parid; + OSErr err; + FSRef fsr; + + if (FSSpec_Check(v)) { + *spec = ((FSSpecObject *)v)->ob_itself; + return 1; + } + + if (PyArg_Parse(v, "(hlO&)", + &refnum, &parid, PyMac_GetStr255, &path)) { + err = FSMakeFSSpec(refnum, parid, path, spec); + if ( err && err != fnfErr ) { + PyMac_Error(err); + return 0; + } + return 1; + } + PyErr_Clear(); + /* Otherwise we try to go via an FSRef. On OSX we go all the way, + ** on OS9 we accept only a real FSRef object + */ + if ( PyMac_GetFSRef(v, &fsr) ) { + err = FSGetCatalogInfo(&fsr, kFSCatInfoNone, NULL, NULL, spec, NULL); + if (err != noErr) { + PyMac_Error(err); + return 0; + } + return 1; + } + return 0; } int PyMac_GetFSRef(PyObject *v, FSRef *fsr) { - OSStatus err; - FSSpec fss; - - if (FSRef_Check(v)) { - *fsr = ((FSRefObject *)v)->ob_itself; - return 1; - } - - /* On OSX we now try a pathname */ - if ( PyString_Check(v) || PyUnicode_Check(v)) { - char *path = NULL; - if (!PyArg_Parse(v, "et", Py_FileSystemDefaultEncoding, &path)) - return NULL; - if ( (err=FSPathMakeRef(path, fsr, NULL)) ) { - PyMac_Error(err); - return 0; - } - return 1; - } - /* XXXX Should try unicode here too */ - /* Otherwise we try to go via an FSSpec */ - if (FSSpec_Check(v)) { - fss = ((FSSpecObject *)v)->ob_itself; - if ((err=FSpMakeFSRef(&fss, fsr)) == 0) - return 1; - PyMac_Error(err); - return 0; - } - PyErr_SetString(PyExc_TypeError, "FSRef, FSSpec or pathname required"); - return 0; + OSStatus err; + FSSpec fss; + + if (FSRef_Check(v)) { + *fsr = ((FSRefObject *)v)->ob_itself; + return 1; + } + + /* On OSX we now try a pathname */ + if ( PyString_Check(v) || PyUnicode_Check(v)) { + char *path = NULL; + if (!PyArg_Parse(v, "et", Py_FileSystemDefaultEncoding, &path)) + return NULL; + if ( (err=FSPathMakeRef(path, fsr, NULL)) ) { + PyMac_Error(err); + return 0; + } + return 1; + } + /* XXXX Should try unicode here too */ + /* Otherwise we try to go via an FSSpec */ + if (FSSpec_Check(v)) { + fss = ((FSSpecObject *)v)->ob_itself; + if ((err=FSpMakeFSRef(&fss, fsr)) == 0) + return 1; + PyMac_Error(err); + return 0; + } + PyErr_SetString(PyExc_TypeError, "FSRef, FSSpec or pathname required"); + return 0; } extern PyObject * PyMac_BuildFSSpec(FSSpec *spec) { - return FSSpec_New(spec); + return FSSpec_New(spec); } extern PyObject * PyMac_BuildFSRef(FSRef *spec) { - return FSRef_New(spec); + return FSRef_New(spec); } """ @@ -298,446 +298,446 @@ execfile(string.lower(MODPREFIX) + 'typetest.py') # Our object types: class FSCatalogInfoDefinition(PEP253Mixin, ObjectDefinition): - getsetlist = [ - ("nodeFlags", - "return Py_BuildValue(\"H\", self->ob_itself.nodeFlags);", - "return PyArg_Parse(v, \"H\", &self->ob_itself.nodeFlags)-1;", - None - ), - ("volume", - "return Py_BuildValue(\"h\", self->ob_itself.volume);", - "return PyArg_Parse(v, \"h\", &self->ob_itself.volume)-1;", - None - ), - ("parentDirID", - "return Py_BuildValue(\"l\", self->ob_itself.parentDirID);", - "return PyArg_Parse(v, \"l\", &self->ob_itself.parentDirID)-1;", - None - ), - ("nodeID", - "return Py_BuildValue(\"l\", self->ob_itself.nodeID);", - "return PyArg_Parse(v, \"l\", &self->ob_itself.nodeID)-1;", - None - ), - ("createDate", - "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.createDate);", - "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.createDate)-1;", - None - ), - ("contentModDate", - "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.contentModDate);", - "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.contentModDate)-1;", - None - ), - ("attributeModDate", - "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.attributeModDate);", - "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.attributeModDate)-1;", - None - ), - ("accessDate", - "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.accessDate);", - "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.accessDate)-1;", - None - ), - ("backupDate", - "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.backupDate);", - "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.backupDate)-1;", - None - ), - ("permissions", - "return Py_BuildValue(\"(llll)\", self->ob_itself.permissions[0], self->ob_itself.permissions[1], self->ob_itself.permissions[2], self->ob_itself.permissions[3]);", - "return PyArg_Parse(v, \"(llll)\", &self->ob_itself.permissions[0], &self->ob_itself.permissions[1], &self->ob_itself.permissions[2], &self->ob_itself.permissions[3])-1;", - None - ), - # XXXX FinderInfo TBD - # XXXX FinderXInfo TBD - ("valence", - "return Py_BuildValue(\"l\", self->ob_itself.valence);", - "return PyArg_Parse(v, \"l\", &self->ob_itself.valence)-1;", - None - ), - ("dataLogicalSize", - "return Py_BuildValue(\"l\", self->ob_itself.dataLogicalSize);", - "return PyArg_Parse(v, \"l\", &self->ob_itself.dataLogicalSize)-1;", - None - ), - ("dataPhysicalSize", - "return Py_BuildValue(\"l\", self->ob_itself.dataPhysicalSize);", - "return PyArg_Parse(v, \"l\", &self->ob_itself.dataPhysicalSize)-1;", - None - ), - ("rsrcLogicalSize", - "return Py_BuildValue(\"l\", self->ob_itself.rsrcLogicalSize);", - "return PyArg_Parse(v, \"l\", &self->ob_itself.rsrcLogicalSize)-1;", - None - ), - ("rsrcPhysicalSize", - "return Py_BuildValue(\"l\", self->ob_itself.rsrcPhysicalSize);", - "return PyArg_Parse(v, \"l\", &self->ob_itself.rsrcPhysicalSize)-1;", - None - ), - ("sharingFlags", - "return Py_BuildValue(\"l\", self->ob_itself.sharingFlags);", - "return PyArg_Parse(v, \"l\", &self->ob_itself.sharingFlags)-1;", - None - ), - ("userPrivileges", - "return Py_BuildValue(\"b\", self->ob_itself.userPrivileges);", - "return PyArg_Parse(v, \"b\", &self->ob_itself.userPrivileges)-1;", - None - ), - ] - # The same info, but in a different form - INITFORMAT = "HhllO&O&O&O&O&llllllb" - INITARGS = """&((FSCatalogInfoObject *)self)->ob_itself.nodeFlags, - &((FSCatalogInfoObject *)self)->ob_itself.volume, - &((FSCatalogInfoObject *)self)->ob_itself.parentDirID, - &((FSCatalogInfoObject *)self)->ob_itself.nodeID, - UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.createDate, - UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.contentModDate, - UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.attributeModDate, - UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.accessDate, - UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.backupDate, - &((FSCatalogInfoObject *)self)->ob_itself.valence, - &((FSCatalogInfoObject *)self)->ob_itself.dataLogicalSize, - &((FSCatalogInfoObject *)self)->ob_itself.dataPhysicalSize, - &((FSCatalogInfoObject *)self)->ob_itself.rsrcLogicalSize, - &((FSCatalogInfoObject *)self)->ob_itself.rsrcPhysicalSize, - &((FSCatalogInfoObject *)self)->ob_itself.sharingFlags, - &((FSCatalogInfoObject *)self)->ob_itself.userPrivileges""" - INITNAMES = """ - "nodeFlags", - "volume", - "parentDirID", - "nodeID", - "createDate", - "contentModDate", - "atributeModDate", - "accessDate", - "backupDate", - "valence", - "dataLogicalSize", - "dataPhysicalSize", - "rsrcLogicalSize", - "rsrcPhysicalSize", - "sharingFlags", - "userPrivileges" - """ - - def __init__(self, name, prefix, itselftype): - ObjectDefinition.__init__(self, name, prefix, itselftype) - self.argref = "*" # Store FSSpecs, but pass them by address - - def outputCheckNewArg(self): - Output("if (itself == NULL) return Py_None;") - - def output_tp_newBody(self): - Output("PyObject *self;"); - Output() - Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") - Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));", - self.objecttype, self.itselftype) - Output("return self;") - - def output_tp_initBody(self): - Output("static char *kw[] = {%s, 0};", self.INITNAMES) - Output() - Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|%s\", kw, %s))", - self.INITFORMAT, self.INITARGS) - OutLbrace() - Output("return -1;") - OutRbrace() - Output("return 0;") - + getsetlist = [ + ("nodeFlags", + "return Py_BuildValue(\"H\", self->ob_itself.nodeFlags);", + "return PyArg_Parse(v, \"H\", &self->ob_itself.nodeFlags)-1;", + None + ), + ("volume", + "return Py_BuildValue(\"h\", self->ob_itself.volume);", + "return PyArg_Parse(v, \"h\", &self->ob_itself.volume)-1;", + None + ), + ("parentDirID", + "return Py_BuildValue(\"l\", self->ob_itself.parentDirID);", + "return PyArg_Parse(v, \"l\", &self->ob_itself.parentDirID)-1;", + None + ), + ("nodeID", + "return Py_BuildValue(\"l\", self->ob_itself.nodeID);", + "return PyArg_Parse(v, \"l\", &self->ob_itself.nodeID)-1;", + None + ), + ("createDate", + "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.createDate);", + "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.createDate)-1;", + None + ), + ("contentModDate", + "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.contentModDate);", + "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.contentModDate)-1;", + None + ), + ("attributeModDate", + "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.attributeModDate);", + "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.attributeModDate)-1;", + None + ), + ("accessDate", + "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.accessDate);", + "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.accessDate)-1;", + None + ), + ("backupDate", + "return Py_BuildValue(\"O&\", UTCDateTime_New, &self->ob_itself.backupDate);", + "return PyArg_Parse(v, \"O&\", UTCDateTime_Convert, &self->ob_itself.backupDate)-1;", + None + ), + ("permissions", + "return Py_BuildValue(\"(llll)\", self->ob_itself.permissions[0], self->ob_itself.permissions[1], self->ob_itself.permissions[2], self->ob_itself.permissions[3]);", + "return PyArg_Parse(v, \"(llll)\", &self->ob_itself.permissions[0], &self->ob_itself.permissions[1], &self->ob_itself.permissions[2], &self->ob_itself.permissions[3])-1;", + None + ), + # XXXX FinderInfo TBD + # XXXX FinderXInfo TBD + ("valence", + "return Py_BuildValue(\"l\", self->ob_itself.valence);", + "return PyArg_Parse(v, \"l\", &self->ob_itself.valence)-1;", + None + ), + ("dataLogicalSize", + "return Py_BuildValue(\"l\", self->ob_itself.dataLogicalSize);", + "return PyArg_Parse(v, \"l\", &self->ob_itself.dataLogicalSize)-1;", + None + ), + ("dataPhysicalSize", + "return Py_BuildValue(\"l\", self->ob_itself.dataPhysicalSize);", + "return PyArg_Parse(v, \"l\", &self->ob_itself.dataPhysicalSize)-1;", + None + ), + ("rsrcLogicalSize", + "return Py_BuildValue(\"l\", self->ob_itself.rsrcLogicalSize);", + "return PyArg_Parse(v, \"l\", &self->ob_itself.rsrcLogicalSize)-1;", + None + ), + ("rsrcPhysicalSize", + "return Py_BuildValue(\"l\", self->ob_itself.rsrcPhysicalSize);", + "return PyArg_Parse(v, \"l\", &self->ob_itself.rsrcPhysicalSize)-1;", + None + ), + ("sharingFlags", + "return Py_BuildValue(\"l\", self->ob_itself.sharingFlags);", + "return PyArg_Parse(v, \"l\", &self->ob_itself.sharingFlags)-1;", + None + ), + ("userPrivileges", + "return Py_BuildValue(\"b\", self->ob_itself.userPrivileges);", + "return PyArg_Parse(v, \"b\", &self->ob_itself.userPrivileges)-1;", + None + ), + ] + # The same info, but in a different form + INITFORMAT = "HhllO&O&O&O&O&llllllb" + INITARGS = """&((FSCatalogInfoObject *)self)->ob_itself.nodeFlags, + &((FSCatalogInfoObject *)self)->ob_itself.volume, + &((FSCatalogInfoObject *)self)->ob_itself.parentDirID, + &((FSCatalogInfoObject *)self)->ob_itself.nodeID, + UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.createDate, + UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.contentModDate, + UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.attributeModDate, + UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.accessDate, + UTCDateTime_Convert, &((FSCatalogInfoObject *)self)->ob_itself.backupDate, + &((FSCatalogInfoObject *)self)->ob_itself.valence, + &((FSCatalogInfoObject *)self)->ob_itself.dataLogicalSize, + &((FSCatalogInfoObject *)self)->ob_itself.dataPhysicalSize, + &((FSCatalogInfoObject *)self)->ob_itself.rsrcLogicalSize, + &((FSCatalogInfoObject *)self)->ob_itself.rsrcPhysicalSize, + &((FSCatalogInfoObject *)self)->ob_itself.sharingFlags, + &((FSCatalogInfoObject *)self)->ob_itself.userPrivileges""" + INITNAMES = """ + "nodeFlags", + "volume", + "parentDirID", + "nodeID", + "createDate", + "contentModDate", + "atributeModDate", + "accessDate", + "backupDate", + "valence", + "dataLogicalSize", + "dataPhysicalSize", + "rsrcLogicalSize", + "rsrcPhysicalSize", + "sharingFlags", + "userPrivileges" + """ + + def __init__(self, name, prefix, itselftype): + ObjectDefinition.__init__(self, name, prefix, itselftype) + self.argref = "*" # Store FSSpecs, but pass them by address + + def outputCheckNewArg(self): + Output("if (itself == NULL) return Py_None;") + + def output_tp_newBody(self): + Output("PyObject *self;"); + Output() + Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") + Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));", + self.objecttype, self.itselftype) + Output("return self;") + + def output_tp_initBody(self): + Output("static char *kw[] = {%s, 0};", self.INITNAMES) + Output() + Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|%s\", kw, %s))", + self.INITFORMAT, self.INITARGS) + OutLbrace() + Output("return -1;") + OutRbrace() + Output("return 0;") + class FInfoDefinition(PEP253Mixin, ObjectDefinition): - getsetlist = [ - ("Type", - "return Py_BuildValue(\"O&\", PyMac_BuildOSType, self->ob_itself.fdType);", - "return PyArg_Parse(v, \"O&\", PyMac_GetOSType, &self->ob_itself.fdType)-1;", - "4-char file type" - ), - ("Creator", - "return Py_BuildValue(\"O&\", PyMac_BuildOSType, self->ob_itself.fdCreator);", - "return PyArg_Parse(v, \"O&\", PyMac_GetOSType, &self->ob_itself.fdCreator)-1;", - "4-char file creator" - ), - ("Flags", - "return Py_BuildValue(\"H\", self->ob_itself.fdFlags);", - "return PyArg_Parse(v, \"H\", &self->ob_itself.fdFlags)-1;", - "Finder flag bits" - ), - ("Location", - "return Py_BuildValue(\"O&\", PyMac_BuildPoint, self->ob_itself.fdLocation);", - "return PyArg_Parse(v, \"O&\", PyMac_GetPoint, &self->ob_itself.fdLocation)-1;", - "(x, y) location of the file's icon in its parent finder window" - ), - ("Fldr", - "return Py_BuildValue(\"h\", self->ob_itself.fdFldr);", - "return PyArg_Parse(v, \"h\", &self->ob_itself.fdFldr)-1;", - "Original folder, for 'put away'" - ), - - ] - - def __init__(self, name, prefix, itselftype): - ObjectDefinition.__init__(self, name, prefix, itselftype) - self.argref = "*" # Store FSSpecs, but pass them by address - - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - - def output_tp_newBody(self): - Output("PyObject *self;"); - Output() - Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") - Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));", - self.objecttype, self.itselftype) - Output("return self;") - - def output_tp_initBody(self): - Output("%s *itself = NULL;", self.itselftype) - Output("static char *kw[] = {\"itself\", 0};") - Output() - Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"|O&\", kw, FInfo_Convert, &itself))") - OutLbrace() - Output("if (itself) memcpy(&((%s *)self)->ob_itself, itself, sizeof(%s));", - self.objecttype, self.itselftype) - Output("return 0;") - OutRbrace() - Output("return -1;") + getsetlist = [ + ("Type", + "return Py_BuildValue(\"O&\", PyMac_BuildOSType, self->ob_itself.fdType);", + "return PyArg_Parse(v, \"O&\", PyMac_GetOSType, &self->ob_itself.fdType)-1;", + "4-char file type" + ), + ("Creator", + "return Py_BuildValue(\"O&\", PyMac_BuildOSType, self->ob_itself.fdCreator);", + "return PyArg_Parse(v, \"O&\", PyMac_GetOSType, &self->ob_itself.fdCreator)-1;", + "4-char file creator" + ), + ("Flags", + "return Py_BuildValue(\"H\", self->ob_itself.fdFlags);", + "return PyArg_Parse(v, \"H\", &self->ob_itself.fdFlags)-1;", + "Finder flag bits" + ), + ("Location", + "return Py_BuildValue(\"O&\", PyMac_BuildPoint, self->ob_itself.fdLocation);", + "return PyArg_Parse(v, \"O&\", PyMac_GetPoint, &self->ob_itself.fdLocation)-1;", + "(x, y) location of the file's icon in its parent finder window" + ), + ("Fldr", + "return Py_BuildValue(\"h\", self->ob_itself.fdFldr);", + "return PyArg_Parse(v, \"h\", &self->ob_itself.fdFldr)-1;", + "Original folder, for 'put away'" + ), + + ] + + def __init__(self, name, prefix, itselftype): + ObjectDefinition.__init__(self, name, prefix, itselftype) + self.argref = "*" # Store FSSpecs, but pass them by address + + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + + def output_tp_newBody(self): + Output("PyObject *self;"); + Output() + Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") + Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));", + self.objecttype, self.itselftype) + Output("return self;") + + def output_tp_initBody(self): + Output("%s *itself = NULL;", self.itselftype) + Output("static char *kw[] = {\"itself\", 0};") + Output() + Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"|O&\", kw, FInfo_Convert, &itself))") + OutLbrace() + Output("if (itself) memcpy(&((%s *)self)->ob_itself, itself, sizeof(%s));", + self.objecttype, self.itselftype) + Output("return 0;") + OutRbrace() + Output("return -1;") class FSSpecDefinition(PEP253Mixin, ObjectDefinition): - getsetlist = [ - ("data", - "return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));", - None, - "Raw data of the FSSpec object" - ) - ] - - def __init__(self, name, prefix, itselftype): - ObjectDefinition.__init__(self, name, prefix, itselftype) - self.argref = "*" # Store FSSpecs, but pass them by address - - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - - # We do Convert ourselves (with PyMac_GetFSxxx) - def outputConvert(self): - pass - - def output_tp_newBody(self): - Output("PyObject *self;"); - Output() - Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") - Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));", - self.objecttype, self.itselftype) - Output("return self;") - - def output_tp_initBody(self): - Output("PyObject *v = NULL;") - Output("char *rawdata = NULL;") - Output("int rawdatalen = 0;") - Output("static char *kw[] = {\"itself\", \"rawdata\", 0};") - Output() - Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))") - Output("return -1;") - Output("if (v && rawdata)") - OutLbrace() - Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");") - Output("return -1;") - OutRbrace() - Output("if (!v && !rawdata)") - OutLbrace() - Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");") - Output("return -1;") - OutRbrace() - Output("if (rawdata)") - OutLbrace() - Output("if (rawdatalen != sizeof(%s))", self.itselftype) - OutLbrace() - Output("PyErr_SetString(PyExc_TypeError, \"%s rawdata incorrect size\");", - self.itselftype) - Output("return -1;") - OutRbrace() - Output("memcpy(&((%s *)self)->ob_itself, rawdata, rawdatalen);", self.objecttype) - Output("return 0;") - OutRbrace() - Output("if (PyMac_GetFSSpec(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype) - Output("return -1;") - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[512];") - Output("""PyOS_snprintf(buf, sizeof(buf), \"%%s((%%d, %%ld, '%%.*s'))\", - self->ob_type->tp_name, - self->ob_itself.vRefNum, - self->ob_itself.parID, - self->ob_itself.name[0], self->ob_itself.name+1);""") - Output("return PyString_FromString(buf);") - OutRbrace() - + getsetlist = [ + ("data", + "return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));", + None, + "Raw data of the FSSpec object" + ) + ] + + def __init__(self, name, prefix, itselftype): + ObjectDefinition.__init__(self, name, prefix, itselftype) + self.argref = "*" # Store FSSpecs, but pass them by address + + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + + # We do Convert ourselves (with PyMac_GetFSxxx) + def outputConvert(self): + pass + + def output_tp_newBody(self): + Output("PyObject *self;"); + Output() + Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") + Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));", + self.objecttype, self.itselftype) + Output("return self;") + + def output_tp_initBody(self): + Output("PyObject *v = NULL;") + Output("char *rawdata = NULL;") + Output("int rawdatalen = 0;") + Output("static char *kw[] = {\"itself\", \"rawdata\", 0};") + Output() + Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))") + Output("return -1;") + Output("if (v && rawdata)") + OutLbrace() + Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");") + Output("return -1;") + OutRbrace() + Output("if (!v && !rawdata)") + OutLbrace() + Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");") + Output("return -1;") + OutRbrace() + Output("if (rawdata)") + OutLbrace() + Output("if (rawdatalen != sizeof(%s))", self.itselftype) + OutLbrace() + Output("PyErr_SetString(PyExc_TypeError, \"%s rawdata incorrect size\");", + self.itselftype) + Output("return -1;") + OutRbrace() + Output("memcpy(&((%s *)self)->ob_itself, rawdata, rawdatalen);", self.objecttype) + Output("return 0;") + OutRbrace() + Output("if (PyMac_GetFSSpec(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype) + Output("return -1;") + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[512];") + Output("""PyOS_snprintf(buf, sizeof(buf), \"%%s((%%d, %%ld, '%%.*s'))\", + self->ob_type->tp_name, + self->ob_itself.vRefNum, + self->ob_itself.parID, + self->ob_itself.name[0], self->ob_itself.name+1);""") + Output("return PyString_FromString(buf);") + OutRbrace() + class FSRefDefinition(PEP253Mixin, ObjectDefinition): - getsetlist = [ - ("data", - "return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));", - None, - "Raw data of the FSRef object" - ) - ] - - def __init__(self, name, prefix, itselftype): - ObjectDefinition.__init__(self, name, prefix, itselftype) - self.argref = "*" # Store FSRefs, but pass them by address - - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - - # We do Convert ourselves (with PyMac_GetFSxxx) - def outputConvert(self): - pass - - def output_tp_newBody(self): - Output("PyObject *self;"); - Output() - Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") - Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));", - self.objecttype, self.itselftype) - Output("return self;") - - def output_tp_initBody(self): - Output("PyObject *v = NULL;") - Output("char *rawdata = NULL;") - Output("int rawdatalen = 0;") - Output("static char *kw[] = {\"itself\", \"rawdata\", 0};") - Output() - Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))") - Output("return -1;") - Output("if (v && rawdata)") - OutLbrace() - Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");") - Output("return -1;") - OutRbrace() - Output("if (!v && !rawdata)") - OutLbrace() - Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");") - Output("return -1;") - OutRbrace() - Output("if (rawdata)") - OutLbrace() - Output("if (rawdatalen != sizeof(%s))", self.itselftype) - OutLbrace() - Output("PyErr_SetString(PyExc_TypeError, \"%s rawdata incorrect size\");", - self.itselftype) - Output("return -1;") - OutRbrace() - Output("memcpy(&((%s *)self)->ob_itself, rawdata, rawdatalen);", self.objecttype) - Output("return 0;") - OutRbrace() - Output("if (PyMac_GetFSRef(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype) - Output("return -1;") - + getsetlist = [ + ("data", + "return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));", + None, + "Raw data of the FSRef object" + ) + ] + + def __init__(self, name, prefix, itselftype): + ObjectDefinition.__init__(self, name, prefix, itselftype) + self.argref = "*" # Store FSRefs, but pass them by address + + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + + # We do Convert ourselves (with PyMac_GetFSxxx) + def outputConvert(self): + pass + + def output_tp_newBody(self): + Output("PyObject *self;"); + Output() + Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") + Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));", + self.objecttype, self.itselftype) + Output("return self;") + + def output_tp_initBody(self): + Output("PyObject *v = NULL;") + Output("char *rawdata = NULL;") + Output("int rawdatalen = 0;") + Output("static char *kw[] = {\"itself\", \"rawdata\", 0};") + Output() + Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))") + Output("return -1;") + Output("if (v && rawdata)") + OutLbrace() + Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");") + Output("return -1;") + OutRbrace() + Output("if (!v && !rawdata)") + OutLbrace() + Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");") + Output("return -1;") + OutRbrace() + Output("if (rawdata)") + OutLbrace() + Output("if (rawdatalen != sizeof(%s))", self.itselftype) + OutLbrace() + Output("PyErr_SetString(PyExc_TypeError, \"%s rawdata incorrect size\");", + self.itselftype) + Output("return -1;") + OutRbrace() + Output("memcpy(&((%s *)self)->ob_itself, rawdata, rawdatalen);", self.objecttype) + Output("return 0;") + OutRbrace() + Output("if (PyMac_GetFSRef(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype) + Output("return -1;") + class AliasDefinition(PEP253Mixin, ObjectDefinition): - # XXXX Should inherit from resource? - getsetlist = [ - ("data", - """int size; - PyObject *rv; - - size = GetHandleSize((Handle)self->ob_itself); - HLock((Handle)self->ob_itself); - rv = PyString_FromStringAndSize(*(Handle)self->ob_itself, size); - HUnlock((Handle)self->ob_itself); - return rv; - """, - None, - "Raw data of the alias object" - ) - ] - - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - - def outputStructMembers(self): - ObjectDefinition.outputStructMembers(self) - Output("void (*ob_freeit)(%s ptr);", self.itselftype) - - def outputInitStructMembers(self): - ObjectDefinition.outputInitStructMembers(self) - Output("it->ob_freeit = NULL;") - - def outputCleanupStructMembers(self): - Output("if (self->ob_freeit && self->ob_itself)") - OutLbrace() - Output("self->ob_freeit(self->ob_itself);") - OutRbrace() - Output("self->ob_itself = NULL;") - - def output_tp_newBody(self): - Output("PyObject *self;"); - Output() - Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") - Output("((%s *)self)->ob_itself = NULL;", self.objecttype) - Output("return self;") - - def output_tp_initBody(self): - Output("%s itself = NULL;", self.itselftype) - Output("char *rawdata = NULL;") - Output("int rawdatalen = 0;") - Output("Handle h;") - Output("static char *kw[] = {\"itself\", \"rawdata\", 0};") - Output() - Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|O&s#\", kw, %s_Convert, &itself, &rawdata, &rawdatalen))", - self.prefix) - Output("return -1;") - Output("if (itself && rawdata)") - OutLbrace() - Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");") - Output("return -1;") - OutRbrace() - Output("if (!itself && !rawdata)") - OutLbrace() - Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");") - Output("return -1;") - OutRbrace() - Output("if (rawdata)") - OutLbrace() - Output("if ((h = NewHandle(rawdatalen)) == NULL)") - OutLbrace() - Output("PyErr_NoMemory();") - Output("return -1;") - OutRbrace() - Output("HLock(h);") - Output("memcpy((char *)*h, rawdata, rawdatalen);") - Output("HUnlock(h);") - Output("((%s *)self)->ob_itself = (%s)h;", self.objecttype, self.itselftype) - Output("return 0;") - OutRbrace() - Output("((%s *)self)->ob_itself = itself;", self.objecttype) - Output("return 0;") - + # XXXX Should inherit from resource? + getsetlist = [ + ("data", + """int size; + PyObject *rv; + + size = GetHandleSize((Handle)self->ob_itself); + HLock((Handle)self->ob_itself); + rv = PyString_FromStringAndSize(*(Handle)self->ob_itself, size); + HUnlock((Handle)self->ob_itself); + return rv; + """, + None, + "Raw data of the alias object" + ) + ] + + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + + def outputStructMembers(self): + ObjectDefinition.outputStructMembers(self) + Output("void (*ob_freeit)(%s ptr);", self.itselftype) + + def outputInitStructMembers(self): + ObjectDefinition.outputInitStructMembers(self) + Output("it->ob_freeit = NULL;") + + def outputCleanupStructMembers(self): + Output("if (self->ob_freeit && self->ob_itself)") + OutLbrace() + Output("self->ob_freeit(self->ob_itself);") + OutRbrace() + Output("self->ob_itself = NULL;") + + def output_tp_newBody(self): + Output("PyObject *self;"); + Output() + Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") + Output("((%s *)self)->ob_itself = NULL;", self.objecttype) + Output("return self;") + + def output_tp_initBody(self): + Output("%s itself = NULL;", self.itselftype) + Output("char *rawdata = NULL;") + Output("int rawdatalen = 0;") + Output("Handle h;") + Output("static char *kw[] = {\"itself\", \"rawdata\", 0};") + Output() + Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|O&s#\", kw, %s_Convert, &itself, &rawdata, &rawdatalen))", + self.prefix) + Output("return -1;") + Output("if (itself && rawdata)") + OutLbrace() + Output("PyErr_SetString(PyExc_TypeError, \"Only one of itself or rawdata may be specified\");") + Output("return -1;") + OutRbrace() + Output("if (!itself && !rawdata)") + OutLbrace() + Output("PyErr_SetString(PyExc_TypeError, \"One of itself or rawdata must be specified\");") + Output("return -1;") + OutRbrace() + Output("if (rawdata)") + OutLbrace() + Output("if ((h = NewHandle(rawdatalen)) == NULL)") + OutLbrace() + Output("PyErr_NoMemory();") + Output("return -1;") + OutRbrace() + Output("HLock(h);") + Output("memcpy((char *)*h, rawdata, rawdatalen);") + Output("HUnlock(h);") + Output("((%s *)self)->ob_itself = (%s)h;", self.objecttype, self.itselftype) + Output("return 0;") + OutRbrace() + Output("((%s *)self)->ob_itself = itself;", self.objecttype) + Output("return 0;") + # Alias methods come in two flavors: those with the alias as arg1 and # those with the alias as arg 2. class Arg2MethodGenerator(OSErrMethodGenerator): - """Similar to MethodGenerator, but has self as second argument""" - - def parseArgumentList(self, args): - args0, arg1, argsrest = args[:1], args[1], args[2:] - t0, n0, m0 = arg1 - args = args0 + argsrest - if m0 != InMode: - raise ValueError, "method's 'self' must be 'InMode'" - self.itself = Variable(t0, "_self->ob_itself", SelfMode) - FunctionGenerator.parseArgumentList(self, args) - self.argumentList.insert(2, self.itself) + """Similar to MethodGenerator, but has self as second argument""" + + def parseArgumentList(self, args): + args0, arg1, argsrest = args[:1], args[1], args[2:] + t0, n0, m0 = arg1 + args = args0 + argsrest + if m0 != InMode: + raise ValueError, "method's 'self' must be 'InMode'" + self.itself = Variable(t0, "_self->ob_itself", SelfMode) + FunctionGenerator.parseArgumentList(self, args) + self.argumentList.insert(2, self.itself) # From here on it's basically all boiler plate... # Create the generator groups and link them module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff, - longname=LONGMODNAME) + longname=LONGMODNAME) fscataloginfoobject = FSCatalogInfoDefinition('FSCatalogInfo', 'FSCatalogInfo', 'FSCatalogInfo') finfoobject = FInfoDefinition('FInfo', 'FInfo', 'FInfo') @@ -770,10 +770,10 @@ UInt8 path[MAXPATHNAME]; UInt32 maxPathSize = MAXPATHNAME; if (!PyArg_ParseTuple(_args, "")) - return NULL; + return NULL; _err = FSRefMakePath(&_self->ob_itself, - path, - maxPathSize); + path, + maxPathSize); if (_err != noErr) return PyMac_Error(_err); _res = Py_BuildValue("s", path); return _res; @@ -784,7 +784,7 @@ fsref_methods.append(f) FSRef_as_pathname_body = """ if (!PyArg_ParseTuple(_args, "")) - return NULL; + return NULL; _res = FSRef_FSRefMakePath(_self, _args); return _res; """ @@ -797,11 +797,11 @@ char strbuf[1024]; OSErr err; if (!PyArg_ParseTuple(_args, "")) - return NULL; + return NULL; err = PyMac_GetFullPathname(&_self->ob_itself, strbuf, sizeof(strbuf)); if ( err ) { - PyMac_Error(err); - return NULL; + PyMac_Error(err); + return NULL; } _res = PyString_FromString(strbuf); return _res; @@ -812,9 +812,9 @@ fsspec_methods.append(f) FSSpec_as_tuple_body = """ if (!PyArg_ParseTuple(_args, "")) - return NULL; -_res = Py_BuildValue("(iis#)", _self->ob_itself.vRefNum, _self->ob_itself.parID, - &_self->ob_itself.name[1], _self->ob_itself.name[0]); + return NULL; +_res = Py_BuildValue("(iis#)", _self->ob_itself.vRefNum, _self->ob_itself.parID, + &_self->ob_itself.name[1], _self->ob_itself.name[0]); return _res; """ f = ManualGenerator("as_tuple", FSSpec_as_tuple_body) @@ -825,13 +825,13 @@ pathname_body = """ PyObject *obj; if (!PyArg_ParseTuple(_args, "O", &obj)) - return NULL; + return NULL; if (PyString_Check(obj)) { - Py_INCREF(obj); - return obj; + Py_INCREF(obj); + return obj; } if (PyUnicode_Check(obj)) - return PyUnicode_AsEncodedString(obj, "utf8", "strict"); + return PyUnicode_AsEncodedString(obj, "utf8", "strict"); _res = PyObject_CallMethod(obj, "as_pathname", NULL); return _res; """ @@ -849,4 +849,3 @@ for f in fsref_methods: fsrefobject.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/fm/fmscan.py b/Mac/Modules/fm/fmscan.py index 73aad3e..334d5ec 100644 --- a/Mac/Modules/fm/fmscan.py +++ b/Mac/Modules/fm/fmscan.py @@ -10,63 +10,63 @@ LONG = "Fonts" SHORT = "fm" def main(): - input = "Fonts.h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = "Fonts.h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + return classname, listname - def makeblacklistnames(self): - return [ - "OutlineMetrics", # Too complicated - "AntiTextIsAntiAliased", # XXXX Missing from library... - "AntiTextGetEnabled", - "AntiTextSetEnabled", - "AntiTextGetApplicationAware", - "AntiTextSetApplicationAware", - # These are tricky: they're not Carbon dependent or anything, but they - # exist only on 8.6 or later (both in Carbon and Classic). - # Disabling them is the easiest path. - 'SetAntiAliasedTextEnabled', - 'IsAntiAliasedTextEnabled', - # OS8-only - 'InitFonts', - 'SetFontLock', - 'FlushFonts', - ] + def makeblacklistnames(self): + return [ + "OutlineMetrics", # Too complicated + "AntiTextIsAntiAliased", # XXXX Missing from library... + "AntiTextGetEnabled", + "AntiTextSetEnabled", + "AntiTextGetApplicationAware", + "AntiTextSetApplicationAware", + # These are tricky: they're not Carbon dependent or anything, but they + # exist only on 8.6 or later (both in Carbon and Classic). + # Disabling them is the easiest path. + 'SetAntiAliasedTextEnabled', + 'IsAntiAliasedTextEnabled', + # OS8-only + 'InitFonts', + 'SetFontLock', + 'FlushFonts', + ] - def makeblacklisttypes(self): - return [ - "FMInput_ptr", # Not needed for now - "FMOutPtr", # Ditto -## "void_ptr", # Don't know how to do this right now - "FontInfo", # Ditto - ] + def makeblacklisttypes(self): + return [ + "FMInput_ptr", # Not needed for now + "FMOutPtr", # Ditto +## "void_ptr", # Don't know how to do this right now + "FontInfo", # Ditto + ] - def makerepairinstructions(self): - return [ - ([('Str255', '*', 'InMode')], [('Str255', '*', 'OutMode')]), - ([('FMetricRecPtr', 'theMetrics', 'InMode')], [('FMetricRecPtr', 'theMetrics', 'OutMode')]), - ([('short', 'byteCount', 'InMode'), ('void_ptr', 'textAddr', 'InMode'),], - [('TextBuffer', 'inText', 'InMode')]), - ] - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("kNilOptions = 0\n") + def makerepairinstructions(self): + return [ + ([('Str255', '*', 'InMode')], [('Str255', '*', 'OutMode')]), + ([('FMetricRecPtr', 'theMetrics', 'InMode')], [('FMetricRecPtr', 'theMetrics', 'OutMode')]), + ([('short', 'byteCount', 'InMode'), ('void_ptr', 'textAddr', 'InMode'),], + [('TextBuffer', 'inText', 'InMode')]), + ] + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("kNilOptions = 0\n") if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/fm/fmsupport.py b/Mac/Modules/fm/fmsupport.py index 07b944e..e692053 100644 --- a/Mac/Modules/fm/fmsupport.py +++ b/Mac/Modules/fm/fmsupport.py @@ -6,21 +6,21 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Fonts.h' # The Apple header file -MODNAME = '_Fm' # The name of the module +MACHEADERFILE = 'Fonts.h' # The Apple header file +MODNAME = '_Fm' # The name of the module # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Fm' # The prefix for module-wide routines +MODPREFIX = 'Fm' # The prefix for module-wide routines INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * # Create the type objects class RevVarInputBufferType(VarInputBufferType): - def passInput(self, name): - return "%s__len__, %s__in__" % (name, name) + def passInput(self, name): + return "%s__len__, %s__in__" % (name, name) TextBuffer = RevVarInputBufferType() @@ -36,12 +36,12 @@ static PyObject * FMRec_New(FMetricRec *itself) { - return Py_BuildValue("O&O&O&O&O&", - PyMac_BuildFixed, itself->ascent, - PyMac_BuildFixed, itself->descent, - PyMac_BuildFixed, itself->leading, - PyMac_BuildFixed, itself->widMax, - ResObj_New, itself->wTabHandle); + return Py_BuildValue("O&O&O&O&O&", + PyMac_BuildFixed, itself->ascent, + PyMac_BuildFixed, itself->descent, + PyMac_BuildFixed, itself->leading, + PyMac_BuildFixed, itself->widMax, + ResObj_New, itself->wTabHandle); } #if 0 @@ -49,12 +49,12 @@ FMRec_New(FMetricRec *itself) static int FMRec_Convert(PyObject *v, FMetricRec *p_itself) { - return PyArg_ParseTuple(v, "O&O&O&O&O&", - PyMac_GetFixed, &itself->ascent, - PyMac_GetFixed, &itself->descent, - PyMac_GetFixed, &itself->leading, - PyMac_GetFixed, &itself->widMax, - ResObj_Convert, &itself->wTabHandle); + return PyArg_ParseTuple(v, "O&O&O&O&O&", + PyMac_GetFixed, &itself->ascent, + PyMac_GetFixed, &itself->descent, + PyMac_GetFixed, &itself->leading, + PyMac_GetFixed, &itself->widMax, + ResObj_Convert, &itself->wTabHandle); } #endif @@ -79,4 +79,3 @@ for f in functions: module.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/folder/folderscan.py b/Mac/Modules/folder/folderscan.py index 39b5a05..8c94893 100644 --- a/Mac/Modules/folder/folderscan.py +++ b/Mac/Modules/folder/folderscan.py @@ -11,58 +11,58 @@ SHORT = "folder" OBJECT = "NOTUSED" def main(): - input = LONG + ".h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - scanner.gentypetest(SHORT+"typetest.py") - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = LONG + ".h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + scanner.gentypetest(SHORT+"typetest.py") + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner_OSX): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - # This is non-functional today - if t == OBJECT and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + # This is non-functional today + if t == OBJECT and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname - def makeblacklistnames(self): - return [ - "FindFolderExtended", # Has funny void* argument - "FSFindFolderExtended", # ditto - "FolderManagerRegisterCallNotificationProcs", # ditto - - "FindFolderEx", # Non-MacOS routine - ] + def makeblacklistnames(self): + return [ + "FindFolderExtended", # Has funny void* argument + "FSFindFolderExtended", # ditto + "FolderManagerRegisterCallNotificationProcs", # ditto - def makeblacklisttypes(self): - return [ - "FolderManagerNotificationProcPtr", - "FolderManagerNotificationUPP", - "FolderRouting", # To be done, not difficult - "FolderDesc", # To be done, not difficult - - ] + "FindFolderEx", # Non-MacOS routine + ] + + def makeblacklisttypes(self): + return [ + "FolderManagerNotificationProcPtr", + "FolderManagerNotificationUPP", + "FolderRouting", # To be done, not difficult + "FolderDesc", # To be done, not difficult + + ] + + def makerepairinstructions(self): + return [ + ] + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("true = True\n") + self.defsfile.write("false = False\n") - def makerepairinstructions(self): - return [ - ] - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("true = True\n") - self.defsfile.write("false = False\n") - if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/folder/foldersupport.py b/Mac/Modules/folder/foldersupport.py index b924615..b9b64bf 100644 --- a/Mac/Modules/folder/foldersupport.py +++ b/Mac/Modules/folder/foldersupport.py @@ -6,13 +6,13 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Folders.h' # The Apple header file -MODNAME = '_Folder' # The name of the module +MACHEADERFILE = 'Folders.h' # The Apple header file +MODNAME = '_Folder' # The name of the module # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Folder' # The prefix for module-wide routines +MODPREFIX = 'Folder' # The prefix for module-wide routines INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -54,4 +54,3 @@ for f in functions: module.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/help/helpscan.py b/Mac/Modules/help/helpscan.py index 32a759a..50e0919 100644 --- a/Mac/Modules/help/helpscan.py +++ b/Mac/Modules/help/helpscan.py @@ -11,57 +11,57 @@ SHORT = "help" OBJECT = "NOTUSED" def main(): - input = LONG + ".h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = LONG + ".h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - # This is non-functional today - if t == OBJECT and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + # This is non-functional today + if t == OBJECT and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - def makeblacklistnames(self): - return [ - ] + def makeblacklistnames(self): + return [ + ] - def makeblacklisttypes(self): - return [ -## "TipFunctionUPP", -## "HMMessageRecord", -## "HMMessageRecord_ptr", - "HMWindowContentUPP", - "HMMenuTitleContentUPP", - "HMControlContentUPP", - "HMMenuItemContentUPP", - # For the moment - "HMHelpContentRec", - "HMHelpContentRec_ptr", - ] + def makeblacklisttypes(self): + return [ +## "TipFunctionUPP", +## "HMMessageRecord", +## "HMMessageRecord_ptr", + "HMWindowContentUPP", + "HMMenuTitleContentUPP", + "HMControlContentUPP", + "HMMenuItemContentUPP", + # For the moment + "HMHelpContentRec", + "HMHelpContentRec_ptr", + ] + + def makerepairinstructions(self): + return [ +## ([("WindowPtr", "*", "OutMode")], +## [("ExistingWindowPtr", "*", "*")]), + ] - def makerepairinstructions(self): - return [ -## ([("WindowPtr", "*", "OutMode")], -## [("ExistingWindowPtr", "*", "*")]), - ] - if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/help/helpsupport.py b/Mac/Modules/help/helpsupport.py index a630603..77f5c2e 100644 --- a/Mac/Modules/help/helpsupport.py +++ b/Mac/Modules/help/helpsupport.py @@ -6,16 +6,16 @@ import string # Declarations that change for each manager -MODNAME = '_Help' # The name of the module -OBJECTNAME = 'UNUSED' # The basic name of the objects used here -KIND = 'Record' # Usually 'Ptr' or 'Handle' +MODNAME = '_Help' # The name of the module +OBJECTNAME = 'UNUSED' # The basic name of the objects used here +KIND = 'Record' # Usually 'Ptr' or 'Handle' # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Help' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + KIND # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Help' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + KIND # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -40,17 +40,17 @@ includestuff = includestuff + """ """ class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - def outputCheckConvertArg(self): - OutLbrace("if (DlgObj_Check(v))") - Output("*p_itself = ((WindowObject *)v)->ob_itself;") - Output("return 1;") - OutRbrace() - Out(""" - if (v == Py_None) { *p_itself = NULL; return 1; } - if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; } - """) + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + def outputCheckConvertArg(self): + OutLbrace("if (DlgObj_Check(v))") + Output("*p_itself = ((WindowObject *)v)->ob_itself;") + Output("return 1;") + OutRbrace() + Out(""" + if (v == Py_None) { *p_itself = NULL; return 1; } + if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; } + """) # From here on it's basically all boiler plate... @@ -76,4 +76,3 @@ for f in functions: module.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/ibcarbon/IBCarbonscan.py b/Mac/Modules/ibcarbon/IBCarbonscan.py index 1f05217..84e4f1e 100644 --- a/Mac/Modules/ibcarbon/IBCarbonscan.py +++ b/Mac/Modules/ibcarbon/IBCarbonscan.py @@ -10,40 +10,40 @@ sys.path.append(BGENDIR) from scantools import Scanner_OSX def main(): - print "---Scanning IBCarbonRuntime.h---" - input = ["IBCarbonRuntime.h"] - output = "IBCarbongen.py" - defsoutput = TOOLBOXDIR + "IBCarbonRuntime.py" - scanner = IBCarbon_Scanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "--done scanning, importing--" - import IBCarbonsupport - print "done" + print "---Scanning IBCarbonRuntime.h---" + input = ["IBCarbonRuntime.h"] + output = "IBCarbongen.py" + defsoutput = TOOLBOXDIR + "IBCarbonRuntime.py" + scanner = IBCarbon_Scanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "--done scanning, importing--" + import IBCarbonsupport + print "done" class IBCarbon_Scanner(Scanner_OSX): - def destination(self, type, name, arglist): - classname = "IBCarbonFunction" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t == "IBNibRef" and m == "InMode": - classname = "IBCarbonMethod" - listname = "methods" - return classname, listname - - def makeblacklistnames(self): - return [ - "DisposeNibReference", # taken care of by destructor - "CreateNibReferenceWithCFBundle", ## need to wrap CFBundle.h properly first - ] - - def makerepairinstructions(self): - return [] + def destination(self, type, name, arglist): + classname = "IBCarbonFunction" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t == "IBNibRef" and m == "InMode": + classname = "IBCarbonMethod" + listname = "methods" + return classname, listname + + def makeblacklistnames(self): + return [ + "DisposeNibReference", # taken care of by destructor + "CreateNibReferenceWithCFBundle", ## need to wrap CFBundle.h properly first + ] + + def makerepairinstructions(self): + return [] if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/ibcarbon/IBCarbonsupport.py b/Mac/Modules/ibcarbon/IBCarbonsupport.py index 5d07be1..5f41328 100644 --- a/Mac/Modules/ibcarbon/IBCarbonsupport.py +++ b/Mac/Modules/ibcarbon/IBCarbonsupport.py @@ -25,12 +25,12 @@ initstuff = """ module = MacModule('_IBCarbon', 'IBCarbon', includestuff, finalstuff, initstuff) class CFReleaserObject(PEP253Mixin, GlobalObjectDefinition): - def outputFreeIt(self, name): - Output("CFRelease(%s);" % name) + def outputFreeIt(self, name): + Output("CFRelease(%s);" % name) class CFNibDesc(PEP253Mixin, GlobalObjectDefinition): - def outputFreeIt(self, name): - Output("DisposeNibReference(%s);" % name) + def outputFreeIt(self, name): + Output("DisposeNibReference(%s);" % name) #cfstringobject = CFReleaserObject("CFStringRef") #module.addobject(cfstringobject) diff --git a/Mac/Modules/icn/icnscan.py b/Mac/Modules/icn/icnscan.py index c6a39f3..bdc3b84 100644 --- a/Mac/Modules/icn/icnscan.py +++ b/Mac/Modules/icn/icnscan.py @@ -11,62 +11,62 @@ SHORT = "icn" OBJECT = "NOTUSED" def main(): - input = LONG + ".h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = LONG + ".h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - # This is non-functional today - if t == OBJECT and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + # This is non-functional today + if t == OBJECT and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname - def makeblacklistnames(self): - return [ - "GetIconCacheData", - "SetIconCacheData", - # Constants with funny definitions - "kSelectorAllHugeData", - "kSelectorAllAvailableData", - "svAllAvailableData", - # Something in a comment accidentally seen as a const definition - "err", - # OS8 only - 'IconServicesTerminate', - # Lazy, right now. - "GetIconRefFromFileInfo" - ] + def makeblacklistnames(self): + return [ + "GetIconCacheData", + "SetIconCacheData", + # Constants with funny definitions + "kSelectorAllHugeData", + "kSelectorAllAvailableData", + "svAllAvailableData", + # Something in a comment accidentally seen as a const definition + "err", + # OS8 only + 'IconServicesTerminate', + # Lazy, right now. + "GetIconRefFromFileInfo" + ] - def makeblacklisttypes(self): - return [ - "IconActionUPP", - "IconGetterUPP", - "CFragInitBlockPtr", - "CGRect_ptr", - ] + def makeblacklisttypes(self): + return [ + "IconActionUPP", + "IconGetterUPP", + "CFragInitBlockPtr", + "CGRect_ptr", + ] - def makerepairinstructions(self): - return [ - ] + def makerepairinstructions(self): + return [ + ] + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("from Carbon.Files import *\n") - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("from Carbon.Files import *\n") - if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/icn/icnsupport.py b/Mac/Modules/icn/icnsupport.py index ef1dbf3..1b15385 100644 --- a/Mac/Modules/icn/icnsupport.py +++ b/Mac/Modules/icn/icnsupport.py @@ -6,17 +6,17 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Icons.h' # The Apple header file -MODNAME = '_Icn' # The name of the module -OBJECTNAME = 'Icon' # The basic name of the objects used here -KIND = 'Handle' # Usually 'Ptr' or 'Handle' +MACHEADERFILE = 'Icons.h' # The Apple header file +MODNAME = '_Icn' # The name of the module +OBJECTNAME = 'Icon' # The basic name of the objects used here +KIND = 'Handle' # Usually 'Ptr' or 'Handle' # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Icn' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + KIND # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Icn' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + KIND # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -52,17 +52,17 @@ includestuff = includestuff + """ """ class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - def outputCheckConvertArg(self): - OutLbrace("if (DlgObj_Check(v))") - Output("*p_itself = ((WindowObject *)v)->ob_itself;") - Output("return 1;") - OutRbrace() - Out(""" - if (v == Py_None) { *p_itself = NULL; return 1; } - if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; } - """) + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + def outputCheckConvertArg(self): + OutLbrace("if (DlgObj_Check(v))") + Output("*p_itself = ((WindowObject *)v)->ob_itself;") + Output("return 1;") + OutRbrace() + Out(""" + if (v == Py_None) { *p_itself = NULL; return 1; } + if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; } + """) # From here on it's basically all boiler plate... @@ -88,4 +88,3 @@ for f in functions: module.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/launch/launchscan.py b/Mac/Modules/launch/launchscan.py index bdda1de..621033b 100644 --- a/Mac/Modules/launch/launchscan.py +++ b/Mac/Modules/launch/launchscan.py @@ -11,76 +11,76 @@ SHORT = "launch" OBJECT = "NOTUSED" def main(): - input = LONG + ".h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - scanner.gentypetest(SHORT+"typetest.py") - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = LONG + ".h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + scanner.gentypetest(SHORT+"typetest.py") + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - # This is non-functional today - if t == OBJECT and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + # This is non-functional today + if t == OBJECT and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("from Carbon.Files import *\n") - self.defsfile.write("kLSRequestAllInfo = -1\n") - self.defsfile.write("kLSRolesAll = -1\n") - self.defsfile.write("kLSUnknownType = FOUR_CHAR_CODE('\\0\\0\\0\\0')\n") - self.defsfile.write("kLSUnknownCreator = FOUR_CHAR_CODE('\\0\\0\\0\\0')\n") - self.defsfile.write("kLSInvalidExtensionIndex = -1\n") + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("from Carbon.Files import *\n") + self.defsfile.write("kLSRequestAllInfo = -1\n") + self.defsfile.write("kLSRolesAll = -1\n") + self.defsfile.write("kLSUnknownType = FOUR_CHAR_CODE('\\0\\0\\0\\0')\n") + self.defsfile.write("kLSUnknownCreator = FOUR_CHAR_CODE('\\0\\0\\0\\0')\n") + self.defsfile.write("kLSInvalidExtensionIndex = -1\n") - def makeblacklistnames(self): - return [ - "LSInit", - "LSTerm", - "kLSRequestAllInfo", - "kLSRolesAll", - "kLSInvalidExtensionIndex", - "kLSUnknownType", - "kLSUnknownCreator" - ] + def makeblacklistnames(self): + return [ + "LSInit", + "LSTerm", + "kLSRequestAllInfo", + "kLSRolesAll", + "kLSInvalidExtensionIndex", + "kLSUnknownType", + "kLSUnknownCreator" + ] - def makeblacklisttypes(self): - return [ - "LSLaunchFSRefSpec_ptr", - "LSLaunchURLSpec_ptr", - ] + def makeblacklisttypes(self): + return [ + "LSLaunchFSRefSpec_ptr", + "LSLaunchURLSpec_ptr", + ] - def makerepairinstructions(self): - return [ - # LSGetApplicationForInfo - ([('CFStringRef', 'inExtension', 'InMode')], - [('OptCFStringRef', 'inExtension', 'InMode')]), - - # LSFindApplicationForInfo - ([('CFStringRef', 'inBundleID', 'InMode')], - [('OptCFStringRef', 'inBundleID', 'InMode')]), - ([('CFStringRef', 'inName', 'InMode')], - [('OptCFStringRef', 'inName', 'InMode')]), + def makerepairinstructions(self): + return [ + # LSGetApplicationForInfo + ([('CFStringRef', 'inExtension', 'InMode')], + [('OptCFStringRef', 'inExtension', 'InMode')]), + + # LSFindApplicationForInfo + ([('CFStringRef', 'inBundleID', 'InMode')], + [('OptCFStringRef', 'inBundleID', 'InMode')]), + ([('CFStringRef', 'inName', 'InMode')], + [('OptCFStringRef', 'inName', 'InMode')]), + + # Unicode filenames passed as length, buffer. LSGetExtensionInfo + ([('UniCharCount', '*', 'InMode'), + ('UniChar_ptr', '*', 'InMode')], + [('UnicodeReverseInBuffer', '*', 'InMode')] + ), + ] - # Unicode filenames passed as length, buffer. LSGetExtensionInfo - ([('UniCharCount', '*', 'InMode'), - ('UniChar_ptr', '*', 'InMode')], - [('UnicodeReverseInBuffer', '*', 'InMode')] - ), - ] - if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/launch/launchsupport.py b/Mac/Modules/launch/launchsupport.py index 122278c..34c2efb 100644 --- a/Mac/Modules/launch/launchsupport.py +++ b/Mac/Modules/launch/launchsupport.py @@ -6,16 +6,16 @@ import string # Declarations that change for each manager -MODNAME = '_Launch' # The name of the module -OBJECTNAME = 'UNUSED' # The basic name of the objects used here -KIND = 'Record' # Usually 'Ptr' or 'Handle' +MODNAME = '_Launch' # The name of the module +OBJECTNAME = 'UNUSED' # The basic name of the objects used here +KIND = 'Record' # Usually 'Ptr' or 'Handle' # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Launch' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + KIND # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Launch' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + KIND # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -41,21 +41,21 @@ PyObject *PyMac_GetOSErrException(void); static int OptCFStringRefObj_Convert(PyObject *v, CFStringRef *spec) { - if (v == Py_None) { - *spec = NULL; - return 1; - } - return CFStringRefObj_Convert(v, spec); + if (v == Py_None) { + *spec = NULL; + return 1; + } + return CFStringRefObj_Convert(v, spec); } PyObject * OptCFStringRefObj_New(CFStringRef it) { - if (it == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return CFStringRefObj_New(it); + if (it == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return CFStringRefObj_New(it); } /* @@ -64,13 +64,13 @@ OptCFStringRefObj_New(CFStringRef it) PyObject * LSItemInfoRecord_New(LSItemInfoRecord *it) { - return Py_BuildValue("{s:is:O&s:O&s:O&s:O&s:i}", - "flags", it->flags, - "filetype", PyMac_BuildOSType, it->filetype, - "creator", PyMac_BuildOSType, it->creator, - "extension", OptCFStringRefObj_New, it->extension, - "iconFileName", OptCFStringRefObj_New, it->iconFileName, - "kindID", it->kindID); + return Py_BuildValue("{s:is:O&s:O&s:O&s:O&s:i}", + "flags", it->flags, + "filetype", PyMac_BuildOSType, it->filetype, + "creator", PyMac_BuildOSType, it->creator, + "extension", OptCFStringRefObj_New, it->extension, + "iconFileName", OptCFStringRefObj_New, it->iconFileName, + "kindID", it->kindID); } """ @@ -99,4 +99,3 @@ for f in functions: module.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/launch/setup.py b/Mac/Modules/launch/setup.py index ccf8ee7..2054195 100644 --- a/Mac/Modules/launch/setup.py +++ b/Mac/Modules/launch/setup.py @@ -4,10 +4,10 @@ from distutils.core import Extension, setup setup(name="LaunchServices", version="0.2", - ext_modules=[ - Extension('_Launch', ['_Launchmodule.c'], - extra_link_args=['-framework', 'ApplicationServices']) - ], - py_modules=['LaunchServices.Launch', 'LaunchServices.LaunchServices'], - package_dir={'LaunchServices':'../../../Lib/plat-mac/Carbon'} - ) + ext_modules=[ + Extension('_Launch', ['_Launchmodule.c'], + extra_link_args=['-framework', 'ApplicationServices']) + ], + py_modules=['LaunchServices.Launch', 'LaunchServices.LaunchServices'], + package_dir={'LaunchServices':'../../../Lib/plat-mac/Carbon'} + ) diff --git a/Mac/Modules/list/listscan.py b/Mac/Modules/list/listscan.py index 66cb2ad..877f6cb 100644 --- a/Mac/Modules/list/listscan.py +++ b/Mac/Modules/list/listscan.py @@ -11,78 +11,78 @@ SHORT = "list" OBJECT = "ListHandle" def main(): - input = LONG + ".h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = LONG + ".h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[-1] - # This is non-functional today - if t in ('ListHandle', 'ListRef') and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname - - def makeblacklistnames(self): - return [ - "LDispose", # Done by removing the object - "LSearch", # We don't want to handle procs just yet - "CreateCustomList", # done manually - "SetListDefinitionProc", - - # These have funny argument/return values - "GetListViewBounds", - "GetListCellIndent", - "GetListCellSize", - "GetListVisibleCells", - "GetListClickLocation", - "GetListMouseLocation", - "GetListDataBounds", - "SetListLastClick", - ] - - def makeblacklisttypes(self): - return [ - "ListClickLoopUPP", # Too difficult for now - "ListDefSpecPtr", # later - ] - - def makerepairinstructions(self): - return [ - ([('ListBounds_ptr', '*', 'InMode')], - [('Rect_ptr', '*', 'InMode')]), - - ([("Cell", "theCell", "OutMode")], - [("Cell", "theCell", "InOutMode")]), - - ([("void_ptr", "*", "InMode"), ("short", "*", "InMode")], - [("InBufferShortsize", "*", "*")]), - - ([("void", "*", "OutMode"), ("short", "*", "OutMode")], - [("VarOutBufferShortsize", "*", "InOutMode")]), - - # SetListCellIndent doesn't have const - ([("Point", "indent", "OutMode")], - [("Point_ptr", "indent", "InMode")]), - - ] - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - - + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[-1] + # This is non-functional today + if t in ('ListHandle', 'ListRef') and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname + + def makeblacklistnames(self): + return [ + "LDispose", # Done by removing the object + "LSearch", # We don't want to handle procs just yet + "CreateCustomList", # done manually + "SetListDefinitionProc", + + # These have funny argument/return values + "GetListViewBounds", + "GetListCellIndent", + "GetListCellSize", + "GetListVisibleCells", + "GetListClickLocation", + "GetListMouseLocation", + "GetListDataBounds", + "SetListLastClick", + ] + + def makeblacklisttypes(self): + return [ + "ListClickLoopUPP", # Too difficult for now + "ListDefSpecPtr", # later + ] + + def makerepairinstructions(self): + return [ + ([('ListBounds_ptr', '*', 'InMode')], + [('Rect_ptr', '*', 'InMode')]), + + ([("Cell", "theCell", "OutMode")], + [("Cell", "theCell", "InOutMode")]), + + ([("void_ptr", "*", "InMode"), ("short", "*", "InMode")], + [("InBufferShortsize", "*", "*")]), + + ([("void", "*", "OutMode"), ("short", "*", "OutMode")], + [("VarOutBufferShortsize", "*", "InOutMode")]), + + # SetListCellIndent doesn't have const + ([("Point", "indent", "OutMode")], + [("Point_ptr", "indent", "InMode")]), + + ] + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + + if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/list/listsupport.py b/Mac/Modules/list/listsupport.py index e44317a..93baede 100644 --- a/Mac/Modules/list/listsupport.py +++ b/Mac/Modules/list/listsupport.py @@ -6,17 +6,17 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Lists.h' # The Apple header file -MODNAME = '_List' # The name of the module -OBJECTNAME = 'List' # The basic name of the objects used here -KIND = 'Handle' # Usually 'Ptr' or 'Handle' +MACHEADERFILE = 'Lists.h' # The Apple header file +MODNAME = '_List' # The name of the module +OBJECTNAME = 'List' # The basic name of the objects used here +KIND = 'Handle' # Usually 'Ptr' or 'Handle' # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'List' # The prefix for module-wide routines -OBJECTTYPE = "ListHandle" # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'List' # The prefix for module-wide routines +OBJECTTYPE = "ListHandle" # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -29,8 +29,8 @@ ListBounds_ptr = Rect_ptr ListDefSpec = ListDefSpec_ptr = OpaqueType("ListDefSpec", "PyMac_BuildListDefSpec", "PyMac_GetListDefSpec") -VarOutBufferShortsize = VarHeapOutputBufferType('char', 'short', 's') # (buf, &len) -InBufferShortsize = VarInputBufferType('char', 'short', 's') # (buf, len) +VarOutBufferShortsize = VarHeapOutputBufferType('char', 'short', 's') # (buf, &len) +InBufferShortsize = VarInputBufferType('char', 'short', 's') # (buf, len) RgnHandle = OpaqueByValueType("RgnHandle", "ResObj") DataHandle = OpaqueByValueType("DataHandle", "ResObj") @@ -64,59 +64,59 @@ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ListHandle, ListObj_Convert); """ class ListMethodGenerator(MethodGenerator): - """Similar to MethodGenerator, but has self as last argument""" + """Similar to MethodGenerator, but has self as last argument""" - def parseArgumentList(self, args): - args, a0 = args[:-1], args[-1] - t0, n0, m0 = a0 - if m0 != InMode: - raise ValueError, "method's 'self' must be 'InMode'" - self.itself = Variable(t0, "_self->ob_itself", SelfMode) - FunctionGenerator.parseArgumentList(self, args) - self.argumentList.append(self.itself) + def parseArgumentList(self, args): + args, a0 = args[:-1], args[-1] + t0, n0, m0 = a0 + if m0 != InMode: + raise ValueError, "method's 'self' must be 'InMode'" + self.itself = Variable(t0, "_self->ob_itself", SelfMode) + FunctionGenerator.parseArgumentList(self, args) + self.argumentList.append(self.itself) class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - # XXXX Should inherit from Resource - getsetlist = [( - 'listFlags', - 'return Py_BuildValue("l", (long)GetListFlags(self->ob_itself) & 0xff);', - 'if (!PyArg_Parse(v, "B", &(*self->ob_itself)->listFlags)) return -1;', - None, - ), ( - 'selFlags', - 'return Py_BuildValue("l", (long)GetListSelectionFlags(self->ob_itself) & 0xff);', - 'if (!PyArg_Parse(v, "B", &(*self->ob_itself)->selFlags)) return -1;', - None, - ), ( - 'cellSize', - 'return Py_BuildValue("O&", PyMac_BuildPoint, (*self->ob_itself)->cellSize);', - 'if (!PyArg_Parse(v, "O&", PyMac_GetPoint, &(*self->ob_itself)->cellSize)) return -1;', - None - )] - - def outputStructMembers(self): - ObjectDefinition.outputStructMembers(self) - Output("PyObject *ob_ldef_func;") - Output("int ob_must_be_disposed;") - - def outputCheckNewArg(self): - Output("""if (itself == NULL) { - PyErr_SetString(List_Error,"Cannot create null List"); - return NULL; - }""") - - def outputInitStructMembers(self): - ObjectDefinition.outputInitStructMembers(self) - Output("it->ob_ldef_func = NULL;") - Output("it->ob_must_be_disposed = 1;") - Output("SetListRefCon(itself, (long)it);") - - def outputFreeIt(self, itselfname): - Output("Py_XDECREF(self->ob_ldef_func);") - Output("self->ob_ldef_func = NULL;") - Output("SetListRefCon(self->ob_itself, (long)0);") - Output("if (self->ob_must_be_disposed && %s) LDispose(%s);", itselfname, itselfname) - + # XXXX Should inherit from Resource + getsetlist = [( + 'listFlags', + 'return Py_BuildValue("l", (long)GetListFlags(self->ob_itself) & 0xff);', + 'if (!PyArg_Parse(v, "B", &(*self->ob_itself)->listFlags)) return -1;', + None, + ), ( + 'selFlags', + 'return Py_BuildValue("l", (long)GetListSelectionFlags(self->ob_itself) & 0xff);', + 'if (!PyArg_Parse(v, "B", &(*self->ob_itself)->selFlags)) return -1;', + None, + ), ( + 'cellSize', + 'return Py_BuildValue("O&", PyMac_BuildPoint, (*self->ob_itself)->cellSize);', + 'if (!PyArg_Parse(v, "O&", PyMac_GetPoint, &(*self->ob_itself)->cellSize)) return -1;', + None + )] + + def outputStructMembers(self): + ObjectDefinition.outputStructMembers(self) + Output("PyObject *ob_ldef_func;") + Output("int ob_must_be_disposed;") + + def outputCheckNewArg(self): + Output("""if (itself == NULL) { + PyErr_SetString(List_Error,"Cannot create null List"); + return NULL; + }""") + + def outputInitStructMembers(self): + ObjectDefinition.outputInitStructMembers(self) + Output("it->ob_ldef_func = NULL;") + Output("it->ob_must_be_disposed = 1;") + Output("SetListRefCon(itself, (long)it);") + + def outputFreeIt(self, itselfname): + Output("Py_XDECREF(self->ob_ldef_func);") + Output("self->ob_ldef_func = NULL;") + Output("SetListRefCon(self->ob_itself, (long)0);") + Output("if (self->ob_must_be_disposed && %s) LDispose(%s);", itselfname, itselfname) + # From here on it's basically all boiler plate... finalstuff = finalstuff + """ @@ -126,34 +126,34 @@ static void myListDefFunction(SInt16 message, Cell theCell, SInt16 dataOffset, SInt16 dataLen, - ListHandle theList) + ListHandle theList) { - PyObject *listDefFunc, *args, *rv=NULL; - ListObject *self; - - self = (ListObject*)GetListRefCon(theList); - if (self == NULL || self->ob_itself != theList) - return; /* nothing we can do */ - listDefFunc = self->ob_ldef_func; - if (listDefFunc == NULL) - return; /* nothing we can do */ - args = Py_BuildValue("hbO&O&hhO", message, - selected, - PyMac_BuildRect, cellRect, - PyMac_BuildPoint, theCell, - dataOffset, - dataLen, - self); - if (args != NULL) { - rv = PyEval_CallObject(listDefFunc, args); - Py_DECREF(args); - } - if (rv == NULL) { - PySys_WriteStderr("error in list definition callback:\\n"); - PyErr_Print(); - } else { - Py_DECREF(rv); - } + PyObject *listDefFunc, *args, *rv=NULL; + ListObject *self; + + self = (ListObject*)GetListRefCon(theList); + if (self == NULL || self->ob_itself != theList) + return; /* nothing we can do */ + listDefFunc = self->ob_ldef_func; + if (listDefFunc == NULL) + return; /* nothing we can do */ + args = Py_BuildValue("hbO&O&hhO", message, + selected, + PyMac_BuildRect, cellRect, + PyMac_BuildPoint, theCell, + dataOffset, + dataLen, + self); + if (args != NULL) { + rv = PyEval_CallObject(listDefFunc, args); + Py_DECREF(args); + } + if (rv == NULL) { + PySys_WriteStderr("error in list definition callback:\\n"); + PyErr_Print(); + } else { + Py_DECREF(rv); + } } """ @@ -177,7 +177,7 @@ as_List_body = """ Handle h; ListObject *l; if (!PyArg_ParseTuple(_args, "O&", ResObj_Convert, &h)) - return NULL; + return NULL; l = (ListObject *)ListObj_New(as_List(h)); l->ob_must_be_disposed = 0; _res = Py_BuildValue("O", l); @@ -215,10 +215,10 @@ if (!PyArg_ParseTuple(_args, "O&O&O&(iO)O&bbbb", &hasGrow, &scrollHoriz, &scrollVert)) - return NULL; + return NULL; -/* Carbon applications use the CreateCustomList API */ +/* Carbon applications use the CreateCustomList API */ theSpec.u.userProc = myListDefFunctionUPP; CreateCustomList(&rView, &dataBounds, @@ -234,7 +234,7 @@ CreateCustomList(&rView, _res = ListObj_New(outList); if (_res == NULL) - return NULL; + return NULL; Py_INCREF(listDefFunc); ((ListObject*)_res)->ob_ldef_func = listDefFunc; return _res;\ @@ -253,4 +253,3 @@ for f in methods: object.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/menu/menuedit.py b/Mac/Modules/menu/menuedit.py index f613d8b..b74301d 100644 --- a/Mac/Modules/menu/menuedit.py +++ b/Mac/Modules/menu/menuedit.py @@ -121,4 +121,3 @@ f = Function(OSStatus, 'RemoveMenuCommandProperty', (OSType, 'inPropertyTag', InMode), ) functions.append(f) - diff --git a/Mac/Modules/menu/menuscan.py b/Mac/Modules/menu/menuscan.py index 281cc86..ae9465e 100644 --- a/Mac/Modules/menu/menuscan.py +++ b/Mac/Modules/menu/menuscan.py @@ -7,91 +7,91 @@ sys.path.append(BGENDIR) from scantools import Scanner def main(): - input = "Menus.h" - output = "menugen.py" - defsoutput = TOOLBOXDIR + "Menus.py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now doing 'import menusupport' ===" - import menusupport - print "=== Done. It's up to you to compile Menumodule.c ===" + input = "Menus.h" + output = "menugen.py" + defsoutput = TOOLBOXDIR + "Menus.py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now doing 'import menusupport' ===" + import menusupport + print "=== Done. It's up to you to compile Menumodule.c ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t in ("MenuHandle", "MenuRef") and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t in ("MenuHandle", "MenuRef") and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname - def makeblacklistnames(self): - return [ -## "IsShowContextualMenuClick", # Can't find it in the library -## "InitContextualMenus", # ditto - "GetMenuItemProperty", # difficult for the moment - "GetMenuItemPropertySize", - "SetMenuItemProperty", - "RemoveMenuItemProperty", - "SetMenuCommandProperty", - "GetMenuCommandProperty", - "GetMenuTitle", # Funny arg/returnvalue - "SetMenuTitle", - "SetMenuTitleIcon", # void* - # OS8 calls: - 'GetMenuItemRefCon2', - 'SetMenuItemRefCon2', - 'EnableItem', - 'DisableItem', - 'CheckItem', - 'CountMItems', - 'OpenDeskAcc', - 'SystemEdit', - 'SystemMenu', - 'SetMenuFlash', - 'InitMenus', - 'InitProcMenu', - ] + def makeblacklistnames(self): + return [ +## "IsShowContextualMenuClick", # Can't find it in the library +## "InitContextualMenus", # ditto + "GetMenuItemProperty", # difficult for the moment + "GetMenuItemPropertySize", + "SetMenuItemProperty", + "RemoveMenuItemProperty", + "SetMenuCommandProperty", + "GetMenuCommandProperty", + "GetMenuTitle", # Funny arg/returnvalue + "SetMenuTitle", + "SetMenuTitleIcon", # void* + # OS8 calls: + 'GetMenuItemRefCon2', + 'SetMenuItemRefCon2', + 'EnableItem', + 'DisableItem', + 'CheckItem', + 'CountMItems', + 'OpenDeskAcc', + 'SystemEdit', + 'SystemMenu', + 'SetMenuFlash', + 'InitMenus', + 'InitProcMenu', + ] - def makeblacklisttypes(self): - return [ - 'MCTableHandle', - 'MCEntryPtr', - 'MCTablePtr', - 'AEDesc_ptr', # For now: doable, but not easy - 'ProcessSerialNumber', # ditto - "MenuDefSpecPtr", # Too difficult for now - "MenuDefSpec_ptr", # ditto - "MenuTrackingData", - "void_ptr", # Don't know yet. - "EventRef", # For now, not exported yet. - "MenuItemDataPtr", # Not yet. - "MenuItemDataRec_ptr", - ] + def makeblacklisttypes(self): + return [ + 'MCTableHandle', + 'MCEntryPtr', + 'MCTablePtr', + 'AEDesc_ptr', # For now: doable, but not easy + 'ProcessSerialNumber', # ditto + "MenuDefSpecPtr", # Too difficult for now + "MenuDefSpec_ptr", # ditto + "MenuTrackingData", + "void_ptr", # Don't know yet. + "EventRef", # For now, not exported yet. + "MenuItemDataPtr", # Not yet. + "MenuItemDataRec_ptr", + ] - def makerepairinstructions(self): - return [ - ([("Str255", "itemString", "InMode")], - [("*", "*", "OutMode")]), - - ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], - [("InBuffer", "*", "*")]), - - ([("void", "*", "OutMode"), ("long", "*", "InMode"), - ("long", "*", "OutMode")], - [("VarVarOutBuffer", "*", "InOutMode")]), - ([("MenuRef", 'outHierMenu', "OutMode")], - [("OptMenuRef", 'outHierMenu', "OutMode")]), - ] + def makerepairinstructions(self): + return [ + ([("Str255", "itemString", "InMode")], + [("*", "*", "OutMode")]), - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], + [("InBuffer", "*", "*")]), + + ([("void", "*", "OutMode"), ("long", "*", "InMode"), + ("long", "*", "OutMode")], + [("VarVarOutBuffer", "*", "InOutMode")]), + ([("MenuRef", 'outHierMenu', "OutMode")], + [("OptMenuRef", 'outHierMenu', "OutMode")]), + ] + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/menu/menusupport.py b/Mac/Modules/menu/menusupport.py index 7c4ae0d..a04b755 100644 --- a/Mac/Modules/menu/menusupport.py +++ b/Mac/Modules/menu/menusupport.py @@ -6,17 +6,17 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Menus.h' # The Apple header file -MODNAME = '_Menu' # The name of the module -OBJECTNAME = 'Menu' # The basic name of the objects used here +MACHEADERFILE = 'Menus.h' # The Apple header file +MODNAME = '_Menu' # The name of the module +OBJECTNAME = 'Menu' # The basic name of the objects used here # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Menu' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + 'Handle' # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Menu' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + 'Handle' # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner EXTRAFILE = string.lower(MODPREFIX) + 'edit.py' # A similar file but hand-made -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -48,7 +48,7 @@ extern PyObject *_MenuObj_New(MenuHandle); extern int _MenuObj_Convert(PyObject *, MenuHandle *); #define MenuObj_New _MenuObj_New -#define MenuObj_Convert _MenuObj_Convert +#define MenuObj_Convert _MenuObj_Convert #endif #define as_Menu(h) ((MenuHandle)h) @@ -58,31 +58,31 @@ extern int _MenuObj_Convert(PyObject *, MenuHandle *); /* Alternative version of MenuObj_New, which returns None for NULL argument */ PyObject *OptMenuObj_New(MenuRef itself) { - if (itself == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return MenuObj_New(itself); + if (itself == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return MenuObj_New(itself); } /* Alternative version of MenuObj_Convert, which returns NULL for a None argument */ int OptMenuObj_Convert(PyObject *v, MenuRef *p_itself) { - if ( v == Py_None ) { - *p_itself = NULL; - return 1; - } - return MenuObj_Convert(v, p_itself); + if ( v == Py_None ) { + *p_itself = NULL; + return 1; + } + return MenuObj_Convert(v, p_itself); } """ initstuff = initstuff + """ - PyMac_INIT_TOOLBOX_OBJECT_NEW(MenuHandle, MenuObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(MenuHandle, MenuObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(MenuHandle, MenuObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(MenuHandle, MenuObj_Convert); """ class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - pass + pass # Create the generator groups and link them module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff) diff --git a/Mac/Modules/mlte/mltescan.py b/Mac/Modules/mlte/mltescan.py index 134bffa..adecb4f 100644 --- a/Mac/Modules/mlte/mltescan.py +++ b/Mac/Modules/mlte/mltescan.py @@ -12,33 +12,33 @@ OBJECTS = ("TXNObject", "TXNFontMenuObject") # ADD object typenames here def main(): - input = "MacTextEditor.h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.gentypetest(SHORT+"typetest.py") - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = "MacTextEditor.h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.gentypetest(SHORT+"typetest.py") + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner_OSX): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t in OBJECTS and m == "InMode": - classname = "Method" - listname = t + "_methods" - return classname, listname - - def writeinitialdefs(self): - self.defsfile.write(""" + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t in OBJECTS and m == "InMode": + classname = "Method" + listname = t + "_methods" + return classname, listname + + def writeinitialdefs(self): + self.defsfile.write(""" def FOUR_CHAR_CODE(x): return x false = 0 true = 1 @@ -55,89 +55,89 @@ kTXNFontSizeAttributeSize = 4 normal = 0 """) - def makeblacklistnames(self): - return [ - "TXNGetFontDefaults", # Arg is too difficult - "TXNSetFontDefaults", # Arg is too difficult - "TXNInitTextension", # done manually - - # Constants with funny definitions - "kTXNClearThisControl", - "kTXNClearTheseFontFeatures", - "kTXNDontCareTypeSize", - "kTXNDecrementTypeSize", - "kTXNUseCurrentSelection", - "kTXNStartOffset", - "kTXNEndOffset", - "kTXNQDFontNameAttributeSize", - "kTXNQDFontFamilyIDAttributeSize", - "kTXNQDFontSizeAttributeSize", - "kTXNQDFontStyleAttributeSize", - "kTXNQDFontColorAttributeSize", - "kTXNTextEncodingAttributeSize", - "kTXNUseEncodingWordRulesMask", - "kTXNFontSizeAttributeSize", - "status", - "justification", - 'TXNTSMCheck', # OS8 - ] - - def makeblacklisttypes(self): - return [ - "TXNTab", # TBD - "TXNMargins", # TBD - "TXNControlData", #TBD - "TXNATSUIFeatures", #TBD - "TXNATSUIVariations", #TBD - "TXNAttributeData", #TBD - "TXNTypeAttributes", #TBD - "TXNMatchTextRecord", #TBD - "TXNBackground", #TBD - "TXNFindUPP", - "ATSUStyle", #TBD - "TXNBackground_ptr", #TBD - "TXNControlData_ptr", #TBD - "TXNControlTag_ptr", #TBD - "TXNLongRect", #TBD - "TXNLongRect_ptr", #TBD - "TXNTypeAttributes_ptr", #TBD - - "TXNActionKeyMapperProcPtr", - "TXNActionKeyMapperUPP", - "TXNTextBoxOptionsData", - "TXNCountOptions", - "void_ptr", - ] - - def makerepairinstructions(self): - return [ - # TXNNewObject has a lot of optional parameters - ([("FSSpec_ptr", "iFileSpec", "InMode")], - [("OptFSSpecPtr", "*", "*")]), - ([("Rect", "iFrame", "OutMode")], - [("OptRectPtr", "*", "InMode")]), - - # In UH 332 some of the "const" are missing for input parameters passed - # by reference. We fix that up here. - ([("EventRecord", "iEvent", "OutMode")], - [("EventRecord_ptr", "*", "InMode")]), - ([("FSSpec", "iFileSpecification", "OutMode")], - [("FSSpec_ptr", "*", "InMode")]), - ([("TXNMacOSPreferredFontDescription", "iFontDefaults", "OutMode")], - [("TXNMacOSPreferredFontDescription_ptr", "*", "InMode")]), - - # In buffers are passed as void * - ([("void", "*", "OutMode"), ("ByteCount", "*", "InMode")], - [("MlteInBuffer", "*", "InMode")]), - - # The AdjustCursor region handle is optional - ([("RgnHandle", "ioCursorRgn", "InMode")], - [("OptRgnHandle", "*", "*")]), - - # The GWorld for TXNDraw is optional - ([('GWorldPtr', 'iDrawPort', 'InMode')], - [('OptGWorldPtr', '*', '*')]), - ] - + def makeblacklistnames(self): + return [ + "TXNGetFontDefaults", # Arg is too difficult + "TXNSetFontDefaults", # Arg is too difficult + "TXNInitTextension", # done manually + + # Constants with funny definitions + "kTXNClearThisControl", + "kTXNClearTheseFontFeatures", + "kTXNDontCareTypeSize", + "kTXNDecrementTypeSize", + "kTXNUseCurrentSelection", + "kTXNStartOffset", + "kTXNEndOffset", + "kTXNQDFontNameAttributeSize", + "kTXNQDFontFamilyIDAttributeSize", + "kTXNQDFontSizeAttributeSize", + "kTXNQDFontStyleAttributeSize", + "kTXNQDFontColorAttributeSize", + "kTXNTextEncodingAttributeSize", + "kTXNUseEncodingWordRulesMask", + "kTXNFontSizeAttributeSize", + "status", + "justification", + 'TXNTSMCheck', # OS8 + ] + + def makeblacklisttypes(self): + return [ + "TXNTab", # TBD + "TXNMargins", # TBD + "TXNControlData", #TBD + "TXNATSUIFeatures", #TBD + "TXNATSUIVariations", #TBD + "TXNAttributeData", #TBD + "TXNTypeAttributes", #TBD + "TXNMatchTextRecord", #TBD + "TXNBackground", #TBD + "TXNFindUPP", + "ATSUStyle", #TBD + "TXNBackground_ptr", #TBD + "TXNControlData_ptr", #TBD + "TXNControlTag_ptr", #TBD + "TXNLongRect", #TBD + "TXNLongRect_ptr", #TBD + "TXNTypeAttributes_ptr", #TBD + + "TXNActionKeyMapperProcPtr", + "TXNActionKeyMapperUPP", + "TXNTextBoxOptionsData", + "TXNCountOptions", + "void_ptr", + ] + + def makerepairinstructions(self): + return [ + # TXNNewObject has a lot of optional parameters + ([("FSSpec_ptr", "iFileSpec", "InMode")], + [("OptFSSpecPtr", "*", "*")]), + ([("Rect", "iFrame", "OutMode")], + [("OptRectPtr", "*", "InMode")]), + + # In UH 332 some of the "const" are missing for input parameters passed + # by reference. We fix that up here. + ([("EventRecord", "iEvent", "OutMode")], + [("EventRecord_ptr", "*", "InMode")]), + ([("FSSpec", "iFileSpecification", "OutMode")], + [("FSSpec_ptr", "*", "InMode")]), + ([("TXNMacOSPreferredFontDescription", "iFontDefaults", "OutMode")], + [("TXNMacOSPreferredFontDescription_ptr", "*", "InMode")]), + + # In buffers are passed as void * + ([("void", "*", "OutMode"), ("ByteCount", "*", "InMode")], + [("MlteInBuffer", "*", "InMode")]), + + # The AdjustCursor region handle is optional + ([("RgnHandle", "ioCursorRgn", "InMode")], + [("OptRgnHandle", "*", "*")]), + + # The GWorld for TXNDraw is optional + ([('GWorldPtr', 'iDrawPort', 'InMode')], + [('OptGWorldPtr', '*', '*')]), + ] + if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/mlte/mltesupport.py b/Mac/Modules/mlte/mltesupport.py index 862d0bc..8dcbed5 100644 --- a/Mac/Modules/mlte/mltesupport.py +++ b/Mac/Modules/mlte/mltesupport.py @@ -8,12 +8,12 @@ import string # Declarations that change for each manager -MODNAME = '_Mlte' # The name of the module +MODNAME = '_Mlte' # The name of the module # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Mlte' # The prefix for module-wide routines +MODPREFIX = 'Mlte' # The prefix for module-wide routines INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -43,14 +43,14 @@ static int TXNFontMenuObj_Convert(PyObject *, TXNFontMenuObject *); static int OptFSSpecPtr_Convert(PyObject *v, FSSpec **p_itself) { - static FSSpec fss; - if (v == Py_None) - { - *p_itself = NULL; - return 1; - } - *p_itself = &fss; - return PyMac_GetFSSpec(v, *p_itself); + static FSSpec fss; + if (v == Py_None) + { + *p_itself = NULL; + return 1; + } + *p_itself = &fss; + return PyMac_GetFSSpec(v, *p_itself); } /* @@ -59,15 +59,15 @@ OptFSSpecPtr_Convert(PyObject *v, FSSpec **p_itself) static int OptRectPtr_Convert(PyObject *v, Rect **p_itself) { - static Rect r; - - if (v == Py_None) - { - *p_itself = NULL; - return 1; - } - *p_itself = &r; - return PyMac_GetRect(v, *p_itself); + static Rect r; + + if (v == Py_None) + { + *p_itself = NULL; + return 1; + } + *p_itself = &r; + return PyMac_GetRect(v, *p_itself); } /* @@ -75,19 +75,19 @@ OptRectPtr_Convert(PyObject *v, Rect **p_itself) */ static int OptGWorldObj_Convert(PyObject *v, GWorldPtr *p_itself) -{ - if (v == Py_None) - { - *p_itself = NULL; - return 1; - } - return GWorldObj_Convert(v, p_itself); +{ + if (v == Py_None) + { + *p_itself = NULL; + return 1; + } + return GWorldObj_Convert(v, p_itself); } """ initstuff = initstuff + """ -// PyMac_INIT_TOOLBOX_OBJECT_NEW(xxxx); +// PyMac_INIT_TOOLBOX_OBJECT_NEW(xxxx); """ TXNObject = OpaqueByValueType("TXNObject", "TXNObj") TXNFontMenuObject = OpaqueByValueType("TXNFontMenuObject", "TXNFontMenuObj") @@ -133,12 +133,12 @@ execfile("mltetypetest.py") # Our (opaque) objects class TXNObjDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") class TXNFontMenuObjDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") # ADD object class here @@ -183,7 +183,7 @@ ItemCount iCountDefaultFonts = 0; TXNInitOptions iUsageFlags; PyMac_PRECHECK(TXNInitTextension); if (!PyArg_ParseTuple(_args, "l", &iUsageFlags)) - return NULL; + return NULL; _err = TXNInitTextension(iDefaultFonts, iCountDefaultFonts, iUsageFlags); @@ -200,4 +200,3 @@ module.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/osa/osascan.py b/Mac/Modules/osa/osascan.py index 75e1a08..fb8196f 100644 --- a/Mac/Modules/osa/osascan.py +++ b/Mac/Modules/osa/osascan.py @@ -10,53 +10,53 @@ LONG = "OSAconst" SHORT = "osa" def main(): - input = "OSA.h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - scanner.gentypetest(SHORT+"typetest.py") - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = "OSA.h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + scanner.gentypetest(SHORT+"typetest.py") + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t == "ComponentInstance" and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("from Carbon.AppleEvents import *\n") - self.defsfile.write("kAEUseStandardDispatch = -1\n") - - def makeblacklistnames(self): - return [ - "OSACopyScript", - ] - - def makeblacklisttypes(self): - return [ - "OSALocalOrGlobal", - "OSACreateAppleEventUPP", - "OSAActiveUPP", - "AEEventHandlerUPP", - "OSASendUPP", - ] - - def makerepairinstructions(self): - return [ - ] - + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t == "ComponentInstance" and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("from Carbon.AppleEvents import *\n") + self.defsfile.write("kAEUseStandardDispatch = -1\n") + + def makeblacklistnames(self): + return [ + "OSACopyScript", + ] + + def makeblacklisttypes(self): + return [ + "OSALocalOrGlobal", + "OSACreateAppleEventUPP", + "OSAActiveUPP", + "AEEventHandlerUPP", + "OSASendUPP", + ] + + def makerepairinstructions(self): + return [ + ] + if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/osa/osasupport.py b/Mac/Modules/osa/osasupport.py index b0e7f4c..8369932 100644 --- a/Mac/Modules/osa/osasupport.py +++ b/Mac/Modules/osa/osasupport.py @@ -6,14 +6,14 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'OSA.h' # The Apple header file -MODNAME = '_OSA' # The name of the module +MACHEADERFILE = 'OSA.h' # The Apple header file +MODNAME = '_OSA' # The name of the module # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'OSA' # The prefix for module-wide routines -OBJECTPREFIX = 'OSAObj' # The prefix for object methods +MODPREFIX = 'OSA' # The prefix for module-wide routines +OBJECTPREFIX = 'OSAObj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -36,8 +36,8 @@ extern int _OSAObj_Convert(PyObject *, ComponentInstance *); initstuff = initstuff + """ /* - PyMac_INIT_TOOLBOX_OBJECT_NEW(ComponentInstance, OSAObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ComponentInstance, OSAObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(ComponentInstance, OSAObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ComponentInstance, OSAObj_Convert); */ """ @@ -63,24 +63,24 @@ AppleEvent_ptr = OpaqueType('AppleEvent', 'AEDesc') # NOTE: at the moment OSA.ComponentInstance is not a subclass # of Cm.ComponentInstance. If this is a problem it can be fixed. class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("""if (itself == NULL) { - PyErr_SetString(OSA_Error,"NULL ComponentInstance"); - return NULL; - }""") - - def outputCheckConvertArg(self): - Output(""" - if (CmpInstObj_Convert(v, p_itself)) - return 1; - PyErr_Clear(); - """) - + def outputCheckNewArg(self): + Output("""if (itself == NULL) { + PyErr_SetString(OSA_Error,"NULL ComponentInstance"); + return NULL; + }""") + + def outputCheckConvertArg(self): + Output(""" + if (CmpInstObj_Convert(v, p_itself)) + return 1; + PyErr_Clear(); + """) + # Create the generator groups and link them module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff) object = MyObjectDefinition('OSAComponentInstance', OBJECTPREFIX, - 'ComponentInstance') + 'ComponentInstance') module.addobject(object) # Create the generator classes used to populate the lists @@ -103,4 +103,3 @@ for f in methods: object.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/osa/setup.py b/Mac/Modules/osa/setup.py index 82e7742..635114e 100644 --- a/Mac/Modules/osa/setup.py +++ b/Mac/Modules/osa/setup.py @@ -4,10 +4,10 @@ from distutils.core import Extension, setup setup(name="OSA", version="0.1", - ext_modules=[ - Extension('_OSA', ['_OSAmodule.c'], - extra_link_args=['-framework', 'Carbon']) - ], - py_modules=['OSA.OSA', 'OSA.OSAconst'], - package_dir={'OSA':'../../../Lib/plat-mac/Carbon'} - ) + ext_modules=[ + Extension('_OSA', ['_OSAmodule.c'], + extra_link_args=['-framework', 'Carbon']) + ], + py_modules=['OSA.OSA', 'OSA.OSAconst'], + package_dir={'OSA':'../../../Lib/plat-mac/Carbon'} + ) diff --git a/Mac/Modules/qd/qdedit.py b/Mac/Modules/qd/qdedit.py index d9e4a15..83d81ed 100644 --- a/Mac/Modules/qd/qdedit.py +++ b/Mac/Modules/qd/qdedit.py @@ -1,5 +1,5 @@ f = Function(void, 'SetPort', - (GrafPtr, 'thePort', InMode), + (GrafPtr, 'thePort', InMode), ) functions.append(f) @@ -156,4 +156,3 @@ f = Function(void, 'DrawText', (short, 'byteCount', InMode), ) functions.append(f) - diff --git a/Mac/Modules/qd/qdscan.py b/Mac/Modules/qd/qdscan.py index f58bb22..85a8cdc 100644 --- a/Mac/Modules/qd/qdscan.py +++ b/Mac/Modules/qd/qdscan.py @@ -8,228 +8,228 @@ sys.path.append(BGENDIR) from scantools import Scanner def main(): - input = "QuickDraw.h" - output = "qdgen.py" - defsoutput = TOOLBOXDIR + "QuickDraw.py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - - # Grmpf. Universal Headers have Text-stuff in a different include file... - input = "QuickDrawText.h" - output = "@qdgentext.py" - defsoutput = "@QuickDrawText.py" - have_extra = 0 - try: - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - have_extra = 1 - except IOError: - pass - if have_extra: - print "=== Copying QuickDrawText stuff into main files... ===" - ifp = open("@qdgentext.py") - ofp = open("qdgen.py", "a") - ofp.write(ifp.read()) - ifp.close() - ofp.close() - ifp = open("@QuickDrawText.py") - ofp = open(TOOLBOXDIR + "QuickDraw.py", "a") - ofp.write(ifp.read()) - ifp.close() - ofp.close() - - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - import qdsupport - print "=== Done. It's up to you to compile it now! ===" + input = "QuickDraw.h" + output = "qdgen.py" + defsoutput = TOOLBOXDIR + "QuickDraw.py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + + # Grmpf. Universal Headers have Text-stuff in a different include file... + input = "QuickDrawText.h" + output = "@qdgentext.py" + defsoutput = "@QuickDrawText.py" + have_extra = 0 + try: + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + have_extra = 1 + except IOError: + pass + if have_extra: + print "=== Copying QuickDrawText stuff into main files... ===" + ifp = open("@qdgentext.py") + ofp = open("qdgen.py", "a") + ofp.write(ifp.read()) + ifp.close() + ofp.close() + ifp = open("@QuickDrawText.py") + ofp = open(TOOLBOXDIR + "QuickDraw.py", "a") + ofp.write(ifp.read()) + ifp.close() + ofp.close() + + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + import qdsupport + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t in ('GrafPtr', 'CGrafPtr') and m == 'InMode': - classname = "Method" - listname = "gr_methods" - elif t == 'BitMapPtr' and m == 'InMode': - classname = "Method" - listname = "bm_methods" -## elif t == "PolyHandle" and m == "InMode": -## classname = "Method" -## listname = "p_methods" -## elif t == "RgnHandle" and m == "InMode": -## classname = "Method" -## listname = "r_methods" - return classname, listname - - - def writeinitialdefs(self): - self.defsfile.write(""" + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t in ('GrafPtr', 'CGrafPtr') and m == 'InMode': + classname = "Method" + listname = "gr_methods" + elif t == 'BitMapPtr' and m == 'InMode': + classname = "Method" + listname = "bm_methods" +## elif t == "PolyHandle" and m == "InMode": +## classname = "Method" +## listname = "p_methods" +## elif t == "RgnHandle" and m == "InMode": +## classname = "Method" +## listname = "r_methods" + return classname, listname + + + def writeinitialdefs(self): + self.defsfile.write(""" def FOUR_CHAR_CODE(x): return x -normal = 0 -bold = 1 -italic = 2 -underline = 4 -outline = 8 -shadow = 0x10 -condense = 0x20 -extend = 0x40 +normal = 0 +bold = 1 +italic = 2 +underline = 4 +outline = 8 +shadow = 0x10 +condense = 0x20 +extend = 0x40 """) - def makeblacklistnames(self): - return [ - 'InitGraf', - 'StuffHex', - 'StdLine', - 'StdComment', - 'StdGetPic', - 'OpenPort', - 'InitPort', - 'ClosePort', - 'OpenCPort', - 'InitCPort', - 'CloseCPort', - 'BitMapToRegionGlue', - 'StdOpcode', # XXXX Missing from library... - # The following are for non-macos use: - 'LockPortBits', - 'UnlockPortBits', - 'UpdatePort', - 'GetPortNativeWindow', - 'GetNativeWindowPort', - 'NativeRegionToMacRegion', - 'MacRegionToNativeRegion', - 'GetPortHWND', - 'GetHWNDPort', - 'GetPICTFromDIB', - - 'HandleToRgn', # Funny signature - - # Need Cm, which we don't want to drag in just yet - 'OpenCursorComponent', - 'CloseCursorComponent', - 'SetCursorComponent', - 'CursorComponentChanged', - 'CursorComponentSetData', - ] - - def makeblacklisttypes(self): - return [ - "QDRegionBitsRef", # Should do this, but too lazy now. - 'CIconHandle', # Obsolete - 'CQDProcs', - 'CQDProcsPtr', - 'CSpecArray', - 'ColorComplementProcPtr', - 'ColorComplementUPP', - 'ColorSearchProcPtr', - 'ColorSearchUPP', - 'ConstPatternParam', - 'DeviceLoopDrawingProcPtr', - 'DeviceLoopFlags', - 'GrafVerb', - 'OpenCPicParams_ptr', - 'Ptr', - 'QDProcs', - 'ReqListRec', - 'void_ptr', - 'CustomXFerProcPtr', - ] - - def makerepairinstructions(self): - return [ - ([('void_ptr', 'textBuf', 'InMode'), - ('short', 'firstByte', 'InMode'), - ('short', 'byteCount', 'InMode')], - [('TextThingie', '*', '*'), ('*', '*', '*'), ('*', '*', '*')]), - - # GetPen and SetPt use a point-pointer as output-only: - ('GetPen', [('Point', '*', 'OutMode')], [('*', '*', 'OutMode')]), - ('SetPt', [('Point', '*', 'OutMode')], [('*', '*', 'OutMode')]), - - # All others use it as input/output: - ([('Point', '*', 'OutMode')], - [('*', '*', 'InOutMode')]), - - # InsetRect, OffsetRect - ([('Rect', 'r', 'OutMode'), - ('short', 'dh', 'InMode'), - ('short', 'dv', 'InMode')], - [('Rect', 'r', 'InOutMode'), - ('short', 'dh', 'InMode'), - ('short', 'dv', 'InMode')]), - - # MapRect - ([('Rect', 'r', 'OutMode'), - ('Rect_ptr', 'srcRect', 'InMode'), - ('Rect_ptr', 'dstRect', 'InMode')], - [('Rect', 'r', 'InOutMode'), - ('Rect_ptr', 'srcRect', 'InMode'), - ('Rect_ptr', 'dstRect', 'InMode')]), - - # CopyBits and friends - ([('RgnHandle', 'maskRgn', 'InMode')], - [('OptRgnHandle', 'maskRgn', 'InMode')]), - - ('QDFlushPortBuffer', - [('RgnHandle', '*', 'InMode')], - [('OptRgnHandle', '*', 'InMode')]), - - # Accessors with reference argument also returned. - ([('Rect_ptr', 'GetPortBounds', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('RGBColor_ptr', 'GetPortForeColor', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('RGBColor_ptr', 'GetPortBackColor', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('RGBColor_ptr', 'GetPortOpColor', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('RGBColor_ptr', 'GetPortHiliteColor', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('Point_ptr', 'GetPortPenSize', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('Point_ptr', 'GetPortPenLocation', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('Rect_ptr', 'GetPixBounds', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('BitMap_ptr', 'GetQDGlobalsScreenBits', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('Cursor_ptr', 'GetQDGlobalsArrow', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('Rect_ptr', 'GetRegionBounds', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('Pattern_ptr', '*', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('Point_ptr', 'QDLocalToGlobalPoint', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('Rect_ptr', 'QDLocalToGlobalRect', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('Point_ptr', 'QDGlobalToLocalPoint', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ([('Rect_ptr', 'QDGlobalToLocalRect', 'ReturnMode')], - [('void', '*', 'ReturnMode')]), - - ] + def makeblacklistnames(self): + return [ + 'InitGraf', + 'StuffHex', + 'StdLine', + 'StdComment', + 'StdGetPic', + 'OpenPort', + 'InitPort', + 'ClosePort', + 'OpenCPort', + 'InitCPort', + 'CloseCPort', + 'BitMapToRegionGlue', + 'StdOpcode', # XXXX Missing from library... + # The following are for non-macos use: + 'LockPortBits', + 'UnlockPortBits', + 'UpdatePort', + 'GetPortNativeWindow', + 'GetNativeWindowPort', + 'NativeRegionToMacRegion', + 'MacRegionToNativeRegion', + 'GetPortHWND', + 'GetHWNDPort', + 'GetPICTFromDIB', + + 'HandleToRgn', # Funny signature + + # Need Cm, which we don't want to drag in just yet + 'OpenCursorComponent', + 'CloseCursorComponent', + 'SetCursorComponent', + 'CursorComponentChanged', + 'CursorComponentSetData', + ] + + def makeblacklisttypes(self): + return [ + "QDRegionBitsRef", # Should do this, but too lazy now. + 'CIconHandle', # Obsolete + 'CQDProcs', + 'CQDProcsPtr', + 'CSpecArray', + 'ColorComplementProcPtr', + 'ColorComplementUPP', + 'ColorSearchProcPtr', + 'ColorSearchUPP', + 'ConstPatternParam', + 'DeviceLoopDrawingProcPtr', + 'DeviceLoopFlags', + 'GrafVerb', + 'OpenCPicParams_ptr', + 'Ptr', + 'QDProcs', + 'ReqListRec', + 'void_ptr', + 'CustomXFerProcPtr', + ] + + def makerepairinstructions(self): + return [ + ([('void_ptr', 'textBuf', 'InMode'), + ('short', 'firstByte', 'InMode'), + ('short', 'byteCount', 'InMode')], + [('TextThingie', '*', '*'), ('*', '*', '*'), ('*', '*', '*')]), + + # GetPen and SetPt use a point-pointer as output-only: + ('GetPen', [('Point', '*', 'OutMode')], [('*', '*', 'OutMode')]), + ('SetPt', [('Point', '*', 'OutMode')], [('*', '*', 'OutMode')]), + + # All others use it as input/output: + ([('Point', '*', 'OutMode')], + [('*', '*', 'InOutMode')]), + + # InsetRect, OffsetRect + ([('Rect', 'r', 'OutMode'), + ('short', 'dh', 'InMode'), + ('short', 'dv', 'InMode')], + [('Rect', 'r', 'InOutMode'), + ('short', 'dh', 'InMode'), + ('short', 'dv', 'InMode')]), + + # MapRect + ([('Rect', 'r', 'OutMode'), + ('Rect_ptr', 'srcRect', 'InMode'), + ('Rect_ptr', 'dstRect', 'InMode')], + [('Rect', 'r', 'InOutMode'), + ('Rect_ptr', 'srcRect', 'InMode'), + ('Rect_ptr', 'dstRect', 'InMode')]), + + # CopyBits and friends + ([('RgnHandle', 'maskRgn', 'InMode')], + [('OptRgnHandle', 'maskRgn', 'InMode')]), + + ('QDFlushPortBuffer', + [('RgnHandle', '*', 'InMode')], + [('OptRgnHandle', '*', 'InMode')]), + + # Accessors with reference argument also returned. + ([('Rect_ptr', 'GetPortBounds', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('RGBColor_ptr', 'GetPortForeColor', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('RGBColor_ptr', 'GetPortBackColor', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('RGBColor_ptr', 'GetPortOpColor', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('RGBColor_ptr', 'GetPortHiliteColor', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('Point_ptr', 'GetPortPenSize', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('Point_ptr', 'GetPortPenLocation', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('Rect_ptr', 'GetPixBounds', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('BitMap_ptr', 'GetQDGlobalsScreenBits', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('Cursor_ptr', 'GetQDGlobalsArrow', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('Rect_ptr', 'GetRegionBounds', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('Pattern_ptr', '*', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('Point_ptr', 'QDLocalToGlobalPoint', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('Rect_ptr', 'QDLocalToGlobalRect', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('Point_ptr', 'QDGlobalToLocalPoint', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ([('Rect_ptr', 'QDGlobalToLocalRect', 'ReturnMode')], + [('void', '*', 'ReturnMode')]), + + ] if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/qd/qdsupport.py b/Mac/Modules/qd/qdsupport.py index e361c01..d078ac6 100644 --- a/Mac/Modules/qd/qdsupport.py +++ b/Mac/Modules/qd/qdsupport.py @@ -6,29 +6,29 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'QuickDraw.h' # The Apple header file -MODNAME = '_Qd' # The name of the module -OBJECTNAME = 'Graf' # The basic name of the objects used here +MACHEADERFILE = 'QuickDraw.h' # The Apple header file +MODNAME = '_Qd' # The name of the module +OBJECTNAME = 'Graf' # The basic name of the objects used here # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Qd' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + 'Ptr' # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Qd' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + 'Ptr' # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner EXTRAFILE = string.lower(MODPREFIX) + 'edit.py' # A similar file but hand-made -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * # Create the type objects class TextThingieClass(FixedInputBufferType): - def getargsCheck(self, name): - Output("/* Fool compiler warnings */") - Output("%s__in_len__ = %s__in_len__;", name, name) + def getargsCheck(self, name): + Output("/* Fool compiler warnings */") + Output("%s__in_len__ = %s__in_len__;", name, name) - def declareSize(self, name): - Output("int %s__in_len__;", name) + def declareSize(self, name): + Output("int %s__in_len__;", name) TextThingie = TextThingieClass(None) @@ -92,19 +92,19 @@ static PyObject *BMObj_NewCopied(BitMapPtr); PyObject *QdRGB_New(RGBColorPtr itself) { - return Py_BuildValue("lll", (long)itself->red, (long)itself->green, (long)itself->blue); + return Py_BuildValue("lll", (long)itself->red, (long)itself->green, (long)itself->blue); } int QdRGB_Convert(PyObject *v, RGBColorPtr p_itself) { - long red, green, blue; - - if( !PyArg_ParseTuple(v, "lll", &red, &green, &blue) ) - return 0; - p_itself->red = (unsigned short)red; - p_itself->green = (unsigned short)green; - p_itself->blue = (unsigned short)blue; - return 1; + long red, green, blue; + + if( !PyArg_ParseTuple(v, "lll", &red, &green, &blue) ) + return 0; + p_itself->red = (unsigned short)red; + p_itself->green = (unsigned short)green; + p_itself->blue = (unsigned short)blue; + return 1; } /* @@ -114,8 +114,8 @@ static PyObject *QdFI_New(FontInfo *itself) { - return Py_BuildValue("hhhh", itself->ascent, itself->descent, - itself->widMax, itself->leading); + return Py_BuildValue("hhhh", itself->ascent, itself->descent, + itself->widMax, itself->leading); } """ @@ -125,15 +125,15 @@ finalstuff = finalstuff + """ */ PyObject *BMObj_NewCopied(BitMapPtr itself) { - BitMapObject *it; - BitMapPtr itself_copy; - - if ((itself_copy=(BitMapPtr)malloc(sizeof(BitMap))) == NULL) - return PyErr_NoMemory(); - *itself_copy = *itself; - it = (BitMapObject *)BMObj_New(itself_copy); - it->referred_bitmap = itself_copy; - return (PyObject *)it; + BitMapObject *it; + BitMapPtr itself_copy; + + if ((itself_copy=(BitMapPtr)malloc(sizeof(BitMap))) == NULL) + return PyErr_NoMemory(); + *itself_copy = *itself; + it = (BitMapObject *)BMObj_New(itself_copy); + it->referred_bitmap = itself_copy; + return (PyObject *)it; } """ @@ -141,112 +141,112 @@ PyObject *BMObj_NewCopied(BitMapPtr itself) variablestuff = "" initstuff = initstuff + """ - PyMac_INIT_TOOLBOX_OBJECT_NEW(BitMapPtr, BMObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(BitMapPtr, BMObj_Convert); - PyMac_INIT_TOOLBOX_OBJECT_NEW(GrafPtr, GrafObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(GrafPtr, GrafObj_Convert); - PyMac_INIT_TOOLBOX_OBJECT_NEW(RGBColorPtr, QdRGB_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(RGBColor, QdRGB_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(BitMapPtr, BMObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(BitMapPtr, BMObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(GrafPtr, GrafObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(GrafPtr, GrafObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(RGBColorPtr, QdRGB_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(RGBColor, QdRGB_Convert); """ ## not yet... ## ##class Region_ObjectDefinition(GlobalObjectDefinition): -## def outputCheckNewArg(self): -## Output("if (itself == NULL) return PyMac_Error(resNotFound);") -## def outputFreeIt(self, itselfname): -## Output("DisposeRegion(%s);", itselfname) +## def outputCheckNewArg(self): +## Output("if (itself == NULL) return PyMac_Error(resNotFound);") +## def outputFreeIt(self, itselfname): +## Output("DisposeRegion(%s);", itselfname) ## ##class Polygon_ObjectDefinition(GlobalObjectDefinition): -## def outputCheckNewArg(self): -## Output("if (itself == NULL) return PyMac_Error(resNotFound);") -## def outputFreeIt(self, itselfname): -## Output("KillPoly(%s);", itselfname) +## def outputCheckNewArg(self): +## Output("if (itself == NULL) return PyMac_Error(resNotFound);") +## def outputFreeIt(self, itselfname): +## Output("KillPoly(%s);", itselfname) class MyGRObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - getsetlist = [ - ('visRgn', - """RgnHandle h=NewRgn(); /* XXXX wrong dispose routine */ - return Py_BuildValue("O&", ResObj_New, (Handle)GetPortVisibleRegion(self->ob_itself, h)); - """, - None, - "Convenience attribute: return a copy of the visible region" - ), ( - 'clipRgn', - """RgnHandle h=NewRgn(); /* XXXX wrong dispose routine */ - return Py_BuildValue("O&", ResObj_New, (Handle)GetPortClipRegion(self->ob_itself, h)); - """, - None, - "Convenience attribute: return a copy of the clipping region" - )] - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - def outputCheckConvertArg(self): - Output("#if 1") - OutLbrace() - Output("WindowRef win;") - OutLbrace("if (WinObj_Convert(v, &win) && v)") - Output("*p_itself = (GrafPtr)GetWindowPort(win);") - Output("return 1;") - OutRbrace() - Output("PyErr_Clear();") - OutRbrace() - Output("#else") - OutLbrace("if (DlgObj_Check(v))") - Output("DialogRef dlg = (DialogRef)((GrafPortObject *)v)->ob_itself;") - Output("*p_itself = (GrafPtr)GetWindowPort(GetDialogWindow(dlg));") - Output("return 1;") - OutRbrace() - OutLbrace("if (WinObj_Check(v))") - Output("WindowRef win = (WindowRef)((GrafPortObject *)v)->ob_itself;") - Output("*p_itself = (GrafPtr)GetWindowPort(win);") - Output("return 1;") - OutRbrace() - Output("#endif") + getsetlist = [ + ('visRgn', + """RgnHandle h=NewRgn(); /* XXXX wrong dispose routine */ + return Py_BuildValue("O&", ResObj_New, (Handle)GetPortVisibleRegion(self->ob_itself, h)); + """, + None, + "Convenience attribute: return a copy of the visible region" + ), ( + 'clipRgn', + """RgnHandle h=NewRgn(); /* XXXX wrong dispose routine */ + return Py_BuildValue("O&", ResObj_New, (Handle)GetPortClipRegion(self->ob_itself, h)); + """, + None, + "Convenience attribute: return a copy of the clipping region" + )] + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + def outputCheckConvertArg(self): + Output("#if 1") + OutLbrace() + Output("WindowRef win;") + OutLbrace("if (WinObj_Convert(v, &win) && v)") + Output("*p_itself = (GrafPtr)GetWindowPort(win);") + Output("return 1;") + OutRbrace() + Output("PyErr_Clear();") + OutRbrace() + Output("#else") + OutLbrace("if (DlgObj_Check(v))") + Output("DialogRef dlg = (DialogRef)((GrafPortObject *)v)->ob_itself;") + Output("*p_itself = (GrafPtr)GetWindowPort(GetDialogWindow(dlg));") + Output("return 1;") + OutRbrace() + OutLbrace("if (WinObj_Check(v))") + Output("WindowRef win = (WindowRef)((GrafPortObject *)v)->ob_itself;") + Output("*p_itself = (GrafPtr)GetWindowPort(win);") + Output("return 1;") + OutRbrace() + Output("#endif") class MyBMObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - getsetlist = [ - ( - 'baseAddr', - 'return PyInt_FromLong((long)self->ob_itself->baseAddr);', - None, - None - ), ( - 'rowBytes', - 'return PyInt_FromLong((long)self->ob_itself->rowBytes);', - None, - None - ), ( - 'bounds', - 'return Py_BuildValue("O&", PyMac_BuildRect, &self->ob_itself->bounds);', - None, - None - ), ( - 'bitmap_data', - 'return PyString_FromStringAndSize((char *)self->ob_itself, sizeof(BitMap));', - None, - None - ), ( - 'pixmap_data', - 'return PyString_FromStringAndSize((char *)self->ob_itself, sizeof(PixMap));', - None, - None - )] - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - def outputStructMembers(self): - # We need to more items: a pointer to privately allocated data - # and a python object we're referring to. - Output("%s ob_itself;", self.itselftype) - Output("PyObject *referred_object;") - Output("BitMap *referred_bitmap;") - def outputInitStructMembers(self): - Output("it->ob_itself = %sitself;", self.argref) - Output("it->referred_object = NULL;") - Output("it->referred_bitmap = NULL;") - def outputCleanupStructMembers(self): - Output("Py_XDECREF(self->referred_object);") - Output("if (self->referred_bitmap) free(self->referred_bitmap);") + getsetlist = [ + ( + 'baseAddr', + 'return PyInt_FromLong((long)self->ob_itself->baseAddr);', + None, + None + ), ( + 'rowBytes', + 'return PyInt_FromLong((long)self->ob_itself->rowBytes);', + None, + None + ), ( + 'bounds', + 'return Py_BuildValue("O&", PyMac_BuildRect, &self->ob_itself->bounds);', + None, + None + ), ( + 'bitmap_data', + 'return PyString_FromStringAndSize((char *)self->ob_itself, sizeof(BitMap));', + None, + None + ), ( + 'pixmap_data', + 'return PyString_FromStringAndSize((char *)self->ob_itself, sizeof(PixMap));', + None, + None + )] + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + def outputStructMembers(self): + # We need to more items: a pointer to privately allocated data + # and a python object we're referring to. + Output("%s ob_itself;", self.itselftype) + Output("PyObject *referred_object;") + Output("BitMap *referred_bitmap;") + def outputInitStructMembers(self): + Output("it->ob_itself = %sitself;", self.argref) + Output("it->referred_object = NULL;") + Output("it->referred_bitmap = NULL;") + def outputCleanupStructMembers(self): + Output("Py_XDECREF(self->referred_object);") + Output("if (self->referred_bitmap) free(self->referred_bitmap);") # Create the generator groups and link them module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff, variablestuff) @@ -284,7 +284,7 @@ int from, length; char *cp; if ( !PyArg_ParseTuple(_args, "ii", &from, &length) ) - return NULL; + return NULL; cp = _self->ob_itself->baseAddr+from; _res = PyString_FromStringAndSize(cp, length); return _res; @@ -299,7 +299,7 @@ int from, length; char *cp, *icp; if ( !PyArg_ParseTuple(_args, "is#", &from, &icp, &length) ) - return NULL; + return NULL; cp = _self->ob_itself->baseAddr+from; memcpy(cp, icp, length); Py_INCREF(Py_None); @@ -321,24 +321,24 @@ int rowbytes; char *data; if ( !PyArg_ParseTuple(_args, "O!iO&", &PyString_Type, &source, &rowbytes, PyMac_GetRect, - &bounds) ) - return NULL; + &bounds) ) + return NULL; data = PyString_AsString(source); if ((ptr=(BitMap *)malloc(sizeof(BitMap))) == NULL ) - return PyErr_NoMemory(); + return PyErr_NoMemory(); ptr->baseAddr = (Ptr)data; ptr->rowBytes = rowbytes; ptr->bounds = bounds; if ( (_res = BMObj_New(ptr)) == NULL ) { - free(ptr); - return NULL; + free(ptr); + return NULL; } ((BitMapObject *)_res)->referred_object = source; Py_INCREF(source); ((BitMapObject *)_res)->referred_bitmap = ptr; return _res; """ - + f = ManualGenerator("BitMap", BitMap_body) f.docstring = lambda: """Take (string, int, Rect) argument and create BitMap""" module.add(f) @@ -351,22 +351,22 @@ BitMap *ptr; PyObject *source; if ( !PyArg_ParseTuple(_args, "O!", &PyString_Type, &source) ) - return NULL; + return NULL; if ( PyString_Size(source) != sizeof(BitMap) && PyString_Size(source) != sizeof(PixMap) ) { - PyErr_Format(PyExc_TypeError, - "Argument size was %d, should be %d (sizeof BitMap) or %d (sizeof PixMap)", - PyString_Size(source), sizeof(BitMap), sizeof(PixMap)); - return NULL; + PyErr_Format(PyExc_TypeError, + "Argument size was %d, should be %d (sizeof BitMap) or %d (sizeof PixMap)", + PyString_Size(source), sizeof(BitMap), sizeof(PixMap)); + return NULL; } ptr = (BitMapPtr)PyString_AsString(source); if ( (_res = BMObj_New(ptr)) == NULL ) { - return NULL; + return NULL; } ((BitMapObject *)_res)->referred_object = source; Py_INCREF(source); return _res; """ - + f = ManualGenerator("RawBitMap", RawBitMap_body) f.docstring = lambda: """Take string BitMap and turn into BitMap object""" module.add(f) diff --git a/Mac/Modules/qdoffs/qdoffsscan.py b/Mac/Modules/qdoffs/qdoffsscan.py index ae70707..d456e00 100644 --- a/Mac/Modules/qdoffs/qdoffsscan.py +++ b/Mac/Modules/qdoffs/qdoffsscan.py @@ -7,61 +7,60 @@ sys.path.append(BGENDIR) from scantools import Scanner def main(): - input = "QDOffscreen.h" - output = "qdoffsgen.py" - defsoutput = TOOLBOXDIR + "QDOffscreen.py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - import qdoffssupport - print "=== Done. It's up to you to compile it now! ===" + input = "QDOffscreen.h" + output = "qdoffsgen.py" + defsoutput = TOOLBOXDIR + "QDOffscreen.py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + import qdoffssupport + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t == "GWorldPtr" and m in ("InMode", "InOutMode"): - classname = "Method" - listname = "methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t == "GWorldPtr" and m in ("InMode", "InOutMode"): + classname = "Method" + listname = "methods" + return classname, listname - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - def makeblacklistnames(self): - return [ - 'DisposeGWorld', # Implied when the object is deleted - 'NewGWorldFromHBITMAP', # Don't know what the args do - 'GetGDeviceAttributes', # Windows-only - ] + def makeblacklistnames(self): + return [ + 'DisposeGWorld', # Implied when the object is deleted + 'NewGWorldFromHBITMAP', # Don't know what the args do + 'GetGDeviceAttributes', # Windows-only + ] - def makeblacklisttypes(self): - return [ - "void_ptr", # GetGDeviceSurface, blacklisted for now - "Ptr", # Again, for now (array is probably ok here) - ] + def makeblacklisttypes(self): + return [ + "void_ptr", # GetGDeviceSurface, blacklisted for now + "Ptr", # Again, for now (array is probably ok here) + ] - def makerepairinstructions(self): - return [ - -## ("UpdateGWorld", -## [("GWorldPtr", "*", "OutMode")], -## [("*", "*", "InOutMode")]), - - # This one is incorrect: we say that all input gdevices are - # optional, but some are not. Most are, however, so users passing - # None for non-optional gdevices will get a qd error, I guess, in - # stead of a python argument error. - ([("GDHandle", "*", "InMode")], - [("OptGDHandle", "*", "InMode")]), - ] + def makerepairinstructions(self): + return [ -if __name__ == "__main__": - main() +## ("UpdateGWorld", +## [("GWorldPtr", "*", "OutMode")], +## [("*", "*", "InOutMode")]), + + # This one is incorrect: we say that all input gdevices are + # optional, but some are not. Most are, however, so users passing + # None for non-optional gdevices will get a qd error, I guess, in + # stead of a python argument error. + ([("GDHandle", "*", "InMode")], + [("OptGDHandle", "*", "InMode")]), + ] +if __name__ == "__main__": + main() diff --git a/Mac/Modules/qdoffs/qdoffssupport.py b/Mac/Modules/qdoffs/qdoffssupport.py index 1bd8f5a..1617773 100644 --- a/Mac/Modules/qdoffs/qdoffssupport.py +++ b/Mac/Modules/qdoffs/qdoffssupport.py @@ -6,17 +6,17 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'QDOffscreen.h' # The Apple header file -MODNAME = '_Qdoffs' # The name of the module -OBJECTNAME = 'GWorld' # The basic name of the objects used here +MACHEADERFILE = 'QDOffscreen.h' # The Apple header file +MODNAME = '_Qdoffs' # The name of the module +OBJECTNAME = 'GWorld' # The basic name of the objects used here # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Qdoffs' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + 'Ptr' # The C type used to represent them -OBJECTPREFIX = OBJECTNAME + 'Obj' # The prefix for object methods +MODPREFIX = 'Qdoffs' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + 'Ptr' # The C type used to represent them +OBJECTPREFIX = OBJECTNAME + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner #EDITFILE = string.lower(MODPREFIX) + 'edit.py' # The manual definitions -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -49,28 +49,28 @@ extern int _GWorldObj_Convert(PyObject *, GWorldPtr *); """ initstuff = initstuff + """ - PyMac_INIT_TOOLBOX_OBJECT_NEW(GWorldPtr, GWorldObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(GWorldPtr, GWorldObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(GWorldPtr, GWorldObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(GWorldPtr, GWorldObj_Convert); """ class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - # XXXX Should inherit from GrafPtr? - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") -## def outputInitStructMembers(self): -## GlobalObjectDefinition.outputInitStructMembers(self) -## Output("SetWRefCon(itself, (long)it);") -## def outputCheckConvertArg(self): -## OutLbrace("if (DlgObj_Check(v))") -## Output("*p_itself = ((WindowObject *)v)->ob_itself;") -## Output("return 1;") -## OutRbrace() -## Out(""" -## if (v == Py_None) { *p_itself = NULL; return 1; } -## if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; } -## """) - def outputFreeIt(self, itselfname): - Output("DisposeGWorld(%s);", itselfname) + # XXXX Should inherit from GrafPtr? + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") +## def outputInitStructMembers(self): +## GlobalObjectDefinition.outputInitStructMembers(self) +## Output("SetWRefCon(itself, (long)it);") +## def outputCheckConvertArg(self): +## OutLbrace("if (DlgObj_Check(v))") +## Output("*p_itself = ((WindowObject *)v)->ob_itself;") +## Output("return 1;") +## OutRbrace() +## Out(""" +## if (v == Py_None) { *p_itself = NULL; return 1; } +## if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; } +## """) + def outputFreeIt(self, itselfname): + Output("DisposeGWorld(%s);", itselfname) # From here on it's basically all boiler plate... # Create the generator groups and link them @@ -100,7 +100,7 @@ int from, length; char *cp; if ( !PyArg_ParseTuple(_args, "O&ii", ResObj_Convert, &pm, &from, &length) ) - return NULL; + return NULL; cp = GetPixBaseAddr(pm)+from; _res = PyString_FromStringAndSize(cp, length); return _res; @@ -116,7 +116,7 @@ int from, length; char *cp, *icp; if ( !PyArg_ParseTuple(_args, "O&is#", ResObj_Convert, &pm, &from, &icp, &length) ) - return NULL; + return NULL; cp = GetPixBaseAddr(pm)+from; memcpy(cp, icp, length); Py_INCREF(Py_None); diff --git a/Mac/Modules/qt/qtscan.py b/Mac/Modules/qt/qtscan.py index b756bfe..a2dba15 100644 --- a/Mac/Modules/qt/qtscan.py +++ b/Mac/Modules/qt/qtscan.py @@ -9,311 +9,311 @@ from scantools import Scanner LONG = "QuickTime" SHORT = "qt" HEADERFILES= ( -# "Components.h" -- In Carbon.Cm - "Movies.h", - "ImageCompression.h", - "QuickTimeComponents.h", -# "ImageCodec.h" -- seems not too useful, and difficult. -# "IsochronousDataHandlers.h" -- Is this useful? - "MediaHandlers.h", -# "QTML.h", -- Windows only, needs separate module -# "QuickTimeStreaming.h", -- Difficult -# "QTStreamingComponents.h", -- Needs QTStreaming - "QuickTimeMusic.h", -# "QuickTimeVR.h", -- Not done yet -# "Sound.h", -- In Carbon.Snd - ) -OBJECTS = ("Movie", "Track", "Media", "UserData", "TimeBase", "MovieController", - "IdleManager", "SGOutput") +# "Components.h" -- In Carbon.Cm + "Movies.h", + "ImageCompression.h", + "QuickTimeComponents.h", +# "ImageCodec.h" -- seems not too useful, and difficult. +# "IsochronousDataHandlers.h" -- Is this useful? + "MediaHandlers.h", +# "QTML.h", -- Windows only, needs separate module +# "QuickTimeStreaming.h", -- Difficult +# "QTStreamingComponents.h", -- Needs QTStreaming + "QuickTimeMusic.h", +# "QuickTimeVR.h", -- Not done yet +# "Sound.h", -- In Carbon.Snd + ) +OBJECTS = ("Movie", "Track", "Media", "UserData", "TimeBase", "MovieController", + "IdleManager", "SGOutput") def main(): - input = HEADERFILES - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - scanner.gentypetest(SHORT+"typetest.py") - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = HEADERFILES + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + scanner.gentypetest(SHORT+"typetest.py") + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t in OBJECTS and m == "InMode": - classname = "Method" - listname = t + "_methods" - return classname, listname - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("xmlIdentifierUnrecognized = -1\n") - self.defsfile.write("kControllerMinimum = -0xf777\n") - self.defsfile.write("notImplementedMusicOSErr = -2071\n") - self.defsfile.write("cantSendToSynthesizerOSErr = -2072\n") - self.defsfile.write("cantReceiveFromSynthesizerOSErr = -2073\n") - self.defsfile.write("illegalVoiceAllocationOSErr = -2074\n") - self.defsfile.write("illegalPartOSErr = -2075\n") - self.defsfile.write("illegalChannelOSErr = -2076\n") - self.defsfile.write("illegalKnobOSErr = -2077\n") - self.defsfile.write("illegalKnobValueOSErr = -2078\n") - self.defsfile.write("illegalInstrumentOSErr = -2079\n") - self.defsfile.write("illegalControllerOSErr = -2080\n") - self.defsfile.write("midiManagerAbsentOSErr = -2081\n") - self.defsfile.write("synthesizerNotRespondingOSErr = -2082\n") - self.defsfile.write("synthesizerOSErr = -2083\n") - self.defsfile.write("illegalNoteChannelOSErr = -2084\n") - self.defsfile.write("noteChannelNotAllocatedOSErr = -2085\n") - self.defsfile.write("tunePlayerFullOSErr = -2086\n") - self.defsfile.write("tuneParseOSErr = -2087\n") - - def makeblacklistnames(self): - return [ - "xmlIdentifierUnrecognized", # const with incompatible definition - "DisposeMovie", # Done on python-object disposal - "DisposeMovieTrack", # ditto - "DisposeTrackMedia", # ditto - "DisposeUserData", # ditto -# "DisposeTimeBase", # ditto - "DisposeMovieController", # ditto - - # The following 4 use 'void *' in an uncontrolled way - # TBD when I've read the manual... - "GetUserDataItem", - "SetUserDataItem", - "SetTextSampleData", - "BeginFullScreen", - # bgen gets the argument in/out wrong.. - "AddTextSample", - "AddTESample", - "AddHiliteSample", - "HiliteTextSample", - - "MakeTrackTimeTable", # Uses long * return? - "MakeMediaTimeTable", # ditto -## "VideoMediaGetStallCount", # Undefined in CW Pro 3 library - # OS8 only: - 'SpriteMediaGetIndImageProperty', # XXXX Why isn't this in carbon? - 'CheckQuickTimeRegistration', - 'SetMovieAnchorDataRef', - 'GetMovieAnchorDataRef', - 'GetMovieLoadState', - 'OpenADataHandler', - 'MovieMediaGetCurrentMovieProperty', - 'MovieMediaGetCurrentTrackProperty', - 'MovieMediaGetChildMovieDataReference', - 'MovieMediaSetChildMovieDataReference', - 'MovieMediaLoadChildMovieFromDataReference', - 'Media3DGetViewObject', - - # these are ImageCompression blacklists - "GraphicsExportGetInputPtr", - - # QuickTimeComponents - # These two need some help: the first returns a point to a databuffer that - # the second disposes. Generate manually? - "VDCompressDone", - "VDReleaseCompressBuffer", - "QTVideoOutputGetGWorldParameters", # How useful is this? - - # MediaHandlers - "MediaMakeMediaTimeTable", # just lazy - "MediaGetSampleDataPointer", # funny output pointer - - # QuickTimeMusic - "kControllerMinimum", - # These are artefacts of a macro definition - "ulen", - "_ext", - "x", - "w1", - "w2", - ] - - def makeblacklisttypes(self): - return [ - # I don't think we want to do these - "QTSyncTaskPtr", - # We dont do callbacks yet, so no need for these - "QTCallBack", - # Skipped for now, due to laziness - "TrackEditState", - "MovieEditState", - "MatrixRecord", - "MatrixRecord_ptr", - "SampleReferencePtr", - "QTTweener", - "QTErrorReplacementPtr", - "QTRestrictionSet", - "QTUUID", - "QTUUID_ptr", - - # Routine pointers, not yet. - "MoviesErrorUPP", - "MoviePreviewCallOutUPP", - "MovieDrawingCompleteUPP", - "QTCallBackUPP", - "TextMediaUPP", - "MovieProgressUPP", - "MovieRgnCoverUPP", - "MCActionFilterUPP", - "MCActionFilterWithRefConUPP", - "GetMovieUPP", - "ModalFilterUPP", - "TrackTransferUPP", - "MoviePrePrerollCompleteUPP", - "MovieExecuteWiredActionsUPP", - "QTBandwidthNotificationUPP", - "DoMCActionUPP", - "QTNextTaskNeededSoonerCallbackUPP", - - "SampleReference64Ptr", # Don't know what this does, yet - "QTRuntimeSpriteDescPtr", - "QTBandwidthReference", - "QTScheduledBandwidthReference", - "QTAtomContainer", - "SpriteWorld", - "Sprite", - - # these are ImageCompression blacklists - "ICMDataUPP", - "ICMFlushUPP", - "ICMCompletionUPP", - "ICMProgressUPP", - "StdPixUPP", - "QDPixUPP", - "ICMAlignmentUPP", - "ICMCursorShieldedUPP", - "ICMMemoryDisposedUPP", - "ICMConvertDataFormatUPP", - "ModalFilterYDUPP", - "FileFilterUPP", - - "CodecNameSpecListPtr", - "CodecInfo", - "ImageSequence", - "MatrixRecordPtr", - "ICMDataProcRecordPtr", - "OpenCPicParams", - "ICMProgressProcRecordPtr", - "ICMAlignmentProcRecordPtr", - "ICMPixelFormatInfoPtr", - "ImageSequenceDataSource", - "ConstStrFileNameParam", - "ImageTranscodeSequence", - "ImageFieldSequence", - "Fract", - "PixMapPtr", - "GWorldFlags", - "void_ptr", # XXX Being lazy, this one is doable. - - # These are from QuickTimeComponents - "CDataHandlerUPP", - "CharDataHandlerUPP", - "CommentHandlerUPP", - "DataHCompletionUPP", - "'MovieExportGetDataUPP", - "MovieExportGetPropertyUPP", - "PreprocessInstructionHandlerUPP", - "SGModalFilterUPP", - "StartDocumentHandlerUPP", - "StartElementHandlerUPP", - "VdigIntUPP", - "SGDataUPP", - "EndDocumentHandlerUPP", - "EndElementHandlerUPP", - "VideoBottles", # Record full of UPPs - - "SCParams", - "ICMCompletionProcRecordPtr", - "DataHVolumeList", - "DigitizerInfo", - "SGCompressInfo", - "SeqGrabExtendedFrameInfoPtr", - "SeqGrabFrameInfoPtr", - "TCTextOptionsPtr", - "SGCompressInfo_ptr", - "SGDeviceList", - "TextDisplayData", - "TimeCodeDef", - "TimeCodeRecord", - "TweenRecord", - "VDGamRecPtr", - "ToneDescription", # XXXX Just lazy: this one is easy. - "XMLDoc", - "UInt64", # XXXX lazy - "UInt64_ptr", # XXXX lazy - - # From MediaHandlers - "ActionsUPP", - "PrePrerollCompleteUPP", - "CodecComponentHandle", # Difficult: handle containing list of components. - "GetMovieCompleteParams", # Immense struct - "LevelMeterInfoPtr", # Lazy. Also: can be an output parameter!! - "MediaEQSpectrumBandsRecordPtr", # ditto - - # From QuickTimeMusic - "MusicMIDISendUPP", - "MusicOfflineDataUPP", - "TuneCallBackUPP", - "TunePlayCallBackUPP", - "GCPart", # Struct with lots of fields - "GCPart_ptr", - "GenericKnobDescription", # Struct with lots of fields - "KnobDescription", # Struct with lots of fields - "InstrumentAboutInfo", # Struct, not too difficult - "NoteChannel", # XXXX Lazy. Could be opaque, I think - "NoteRequest", # XXXX Lazy. Not-too-difficult struct - "SynthesizerConnections", # Struct with lots of fields - "SynthesizerDescription", # Struct with lots of fields - "TuneStatus", # Struct with lots of fields - - ] - - def makerepairinstructions(self): - return [ - ([('FSSpec', '*', 'OutMode')], [('FSSpec_ptr', '*', 'InMode')]), - - # Movie controller creation - ([('ComponentInstance', 'NewMovieController', 'ReturnMode')], - [('MovieController', '*', 'ReturnMode')]), - - # NewMovieFromFile - ([('short', 'resId', 'OutMode'), ('StringPtr', 'resName', 'InMode')], - [('short', 'resId', 'InOutMode'), ('dummyStringPtr', 'resName', 'InMode')]), - - # MCDoAction and more - ([('void', '*', 'OutMode')], [('mcactionparams', '*', 'InMode')]), - - # SetTimeBaseZero. Does not handle NULLs, unfortunately - ([('TimeRecord', 'zero', 'OutMode')], [('TimeRecord', 'zero', 'InMode')]), - - # ConvertTime and ConvertTimeScale - ([('TimeRecord', 'inout', 'OutMode')], [('TimeRecord', 'inout', 'InOutMode')]), - ([('TimeRecord', 'theTime', 'OutMode')], [('TimeRecord', 'theTime', 'InOutMode')]), - - # AddTime and SubtractTime - ([('TimeRecord', 'dst', 'OutMode')], [('TimeRecord', 'dst', 'InOutMode')]), - - # Funny definitions - ([('char_ptr', '*', 'InMode')], [('stringptr', '*', 'InMode')]), - ([('FSSpecPtr', '*', 'InMode')], [('FSSpec_ptr', '*', 'InMode')]), - ([('unsigned_char', 'swfVersion', 'OutMode')], [('UInt8', 'swfVersion', 'OutMode')]), - - # It seems MusicMIDIPacket if never flagged with const but always used - # for sending only. If that ever changes this needs to be fixed. - ([('MusicMIDIPacket', '*', 'OutMode')], [('MusicMIDIPacket_ptr', '*', 'InMode')]), - - # QTMusic const-less input parameters - ([('unsigned_long', 'header', 'OutMode')], [('UnsignedLongPtr', 'header', 'InMode')]), - ] - + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t in OBJECTS and m == "InMode": + classname = "Method" + listname = t + "_methods" + return classname, listname + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("xmlIdentifierUnrecognized = -1\n") + self.defsfile.write("kControllerMinimum = -0xf777\n") + self.defsfile.write("notImplementedMusicOSErr = -2071\n") + self.defsfile.write("cantSendToSynthesizerOSErr = -2072\n") + self.defsfile.write("cantReceiveFromSynthesizerOSErr = -2073\n") + self.defsfile.write("illegalVoiceAllocationOSErr = -2074\n") + self.defsfile.write("illegalPartOSErr = -2075\n") + self.defsfile.write("illegalChannelOSErr = -2076\n") + self.defsfile.write("illegalKnobOSErr = -2077\n") + self.defsfile.write("illegalKnobValueOSErr = -2078\n") + self.defsfile.write("illegalInstrumentOSErr = -2079\n") + self.defsfile.write("illegalControllerOSErr = -2080\n") + self.defsfile.write("midiManagerAbsentOSErr = -2081\n") + self.defsfile.write("synthesizerNotRespondingOSErr = -2082\n") + self.defsfile.write("synthesizerOSErr = -2083\n") + self.defsfile.write("illegalNoteChannelOSErr = -2084\n") + self.defsfile.write("noteChannelNotAllocatedOSErr = -2085\n") + self.defsfile.write("tunePlayerFullOSErr = -2086\n") + self.defsfile.write("tuneParseOSErr = -2087\n") + + def makeblacklistnames(self): + return [ + "xmlIdentifierUnrecognized", # const with incompatible definition + "DisposeMovie", # Done on python-object disposal + "DisposeMovieTrack", # ditto + "DisposeTrackMedia", # ditto + "DisposeUserData", # ditto +# "DisposeTimeBase", # ditto + "DisposeMovieController", # ditto + + # The following 4 use 'void *' in an uncontrolled way + # TBD when I've read the manual... + "GetUserDataItem", + "SetUserDataItem", + "SetTextSampleData", + "BeginFullScreen", + # bgen gets the argument in/out wrong.. + "AddTextSample", + "AddTESample", + "AddHiliteSample", + "HiliteTextSample", + + "MakeTrackTimeTable", # Uses long * return? + "MakeMediaTimeTable", # ditto +## "VideoMediaGetStallCount", # Undefined in CW Pro 3 library + # OS8 only: + 'SpriteMediaGetIndImageProperty', # XXXX Why isn't this in carbon? + 'CheckQuickTimeRegistration', + 'SetMovieAnchorDataRef', + 'GetMovieAnchorDataRef', + 'GetMovieLoadState', + 'OpenADataHandler', + 'MovieMediaGetCurrentMovieProperty', + 'MovieMediaGetCurrentTrackProperty', + 'MovieMediaGetChildMovieDataReference', + 'MovieMediaSetChildMovieDataReference', + 'MovieMediaLoadChildMovieFromDataReference', + 'Media3DGetViewObject', + + # these are ImageCompression blacklists + "GraphicsExportGetInputPtr", + + # QuickTimeComponents + # These two need some help: the first returns a point to a databuffer that + # the second disposes. Generate manually? + "VDCompressDone", + "VDReleaseCompressBuffer", + "QTVideoOutputGetGWorldParameters", # How useful is this? + + # MediaHandlers + "MediaMakeMediaTimeTable", # just lazy + "MediaGetSampleDataPointer", # funny output pointer + + # QuickTimeMusic + "kControllerMinimum", + # These are artefacts of a macro definition + "ulen", + "_ext", + "x", + "w1", + "w2", + ] + + def makeblacklisttypes(self): + return [ + # I don't think we want to do these + "QTSyncTaskPtr", + # We dont do callbacks yet, so no need for these + "QTCallBack", + # Skipped for now, due to laziness + "TrackEditState", + "MovieEditState", + "MatrixRecord", + "MatrixRecord_ptr", + "SampleReferencePtr", + "QTTweener", + "QTErrorReplacementPtr", + "QTRestrictionSet", + "QTUUID", + "QTUUID_ptr", + + # Routine pointers, not yet. + "MoviesErrorUPP", + "MoviePreviewCallOutUPP", + "MovieDrawingCompleteUPP", + "QTCallBackUPP", + "TextMediaUPP", + "MovieProgressUPP", + "MovieRgnCoverUPP", + "MCActionFilterUPP", + "MCActionFilterWithRefConUPP", + "GetMovieUPP", + "ModalFilterUPP", + "TrackTransferUPP", + "MoviePrePrerollCompleteUPP", + "MovieExecuteWiredActionsUPP", + "QTBandwidthNotificationUPP", + "DoMCActionUPP", + "QTNextTaskNeededSoonerCallbackUPP", + + "SampleReference64Ptr", # Don't know what this does, yet + "QTRuntimeSpriteDescPtr", + "QTBandwidthReference", + "QTScheduledBandwidthReference", + "QTAtomContainer", + "SpriteWorld", + "Sprite", + + # these are ImageCompression blacklists + "ICMDataUPP", + "ICMFlushUPP", + "ICMCompletionUPP", + "ICMProgressUPP", + "StdPixUPP", + "QDPixUPP", + "ICMAlignmentUPP", + "ICMCursorShieldedUPP", + "ICMMemoryDisposedUPP", + "ICMConvertDataFormatUPP", + "ModalFilterYDUPP", + "FileFilterUPP", + + "CodecNameSpecListPtr", + "CodecInfo", + "ImageSequence", + "MatrixRecordPtr", + "ICMDataProcRecordPtr", + "OpenCPicParams", + "ICMProgressProcRecordPtr", + "ICMAlignmentProcRecordPtr", + "ICMPixelFormatInfoPtr", + "ImageSequenceDataSource", + "ConstStrFileNameParam", + "ImageTranscodeSequence", + "ImageFieldSequence", + "Fract", + "PixMapPtr", + "GWorldFlags", + "void_ptr", # XXX Being lazy, this one is doable. + + # These are from QuickTimeComponents + "CDataHandlerUPP", + "CharDataHandlerUPP", + "CommentHandlerUPP", + "DataHCompletionUPP", + "'MovieExportGetDataUPP", + "MovieExportGetPropertyUPP", + "PreprocessInstructionHandlerUPP", + "SGModalFilterUPP", + "StartDocumentHandlerUPP", + "StartElementHandlerUPP", + "VdigIntUPP", + "SGDataUPP", + "EndDocumentHandlerUPP", + "EndElementHandlerUPP", + "VideoBottles", # Record full of UPPs + + "SCParams", + "ICMCompletionProcRecordPtr", + "DataHVolumeList", + "DigitizerInfo", + "SGCompressInfo", + "SeqGrabExtendedFrameInfoPtr", + "SeqGrabFrameInfoPtr", + "TCTextOptionsPtr", + "SGCompressInfo_ptr", + "SGDeviceList", + "TextDisplayData", + "TimeCodeDef", + "TimeCodeRecord", + "TweenRecord", + "VDGamRecPtr", + "ToneDescription", # XXXX Just lazy: this one is easy. + "XMLDoc", + "UInt64", # XXXX lazy + "UInt64_ptr", # XXXX lazy + + # From MediaHandlers + "ActionsUPP", + "PrePrerollCompleteUPP", + "CodecComponentHandle", # Difficult: handle containing list of components. + "GetMovieCompleteParams", # Immense struct + "LevelMeterInfoPtr", # Lazy. Also: can be an output parameter!! + "MediaEQSpectrumBandsRecordPtr", # ditto + + # From QuickTimeMusic + "MusicMIDISendUPP", + "MusicOfflineDataUPP", + "TuneCallBackUPP", + "TunePlayCallBackUPP", + "GCPart", # Struct with lots of fields + "GCPart_ptr", + "GenericKnobDescription", # Struct with lots of fields + "KnobDescription", # Struct with lots of fields + "InstrumentAboutInfo", # Struct, not too difficult + "NoteChannel", # XXXX Lazy. Could be opaque, I think + "NoteRequest", # XXXX Lazy. Not-too-difficult struct + "SynthesizerConnections", # Struct with lots of fields + "SynthesizerDescription", # Struct with lots of fields + "TuneStatus", # Struct with lots of fields + + ] + + def makerepairinstructions(self): + return [ + ([('FSSpec', '*', 'OutMode')], [('FSSpec_ptr', '*', 'InMode')]), + + # Movie controller creation + ([('ComponentInstance', 'NewMovieController', 'ReturnMode')], + [('MovieController', '*', 'ReturnMode')]), + + # NewMovieFromFile + ([('short', 'resId', 'OutMode'), ('StringPtr', 'resName', 'InMode')], + [('short', 'resId', 'InOutMode'), ('dummyStringPtr', 'resName', 'InMode')]), + + # MCDoAction and more + ([('void', '*', 'OutMode')], [('mcactionparams', '*', 'InMode')]), + + # SetTimeBaseZero. Does not handle NULLs, unfortunately + ([('TimeRecord', 'zero', 'OutMode')], [('TimeRecord', 'zero', 'InMode')]), + + # ConvertTime and ConvertTimeScale + ([('TimeRecord', 'inout', 'OutMode')], [('TimeRecord', 'inout', 'InOutMode')]), + ([('TimeRecord', 'theTime', 'OutMode')], [('TimeRecord', 'theTime', 'InOutMode')]), + + # AddTime and SubtractTime + ([('TimeRecord', 'dst', 'OutMode')], [('TimeRecord', 'dst', 'InOutMode')]), + + # Funny definitions + ([('char_ptr', '*', 'InMode')], [('stringptr', '*', 'InMode')]), + ([('FSSpecPtr', '*', 'InMode')], [('FSSpec_ptr', '*', 'InMode')]), + ([('unsigned_char', 'swfVersion', 'OutMode')], [('UInt8', 'swfVersion', 'OutMode')]), + + # It seems MusicMIDIPacket if never flagged with const but always used + # for sending only. If that ever changes this needs to be fixed. + ([('MusicMIDIPacket', '*', 'OutMode')], [('MusicMIDIPacket_ptr', '*', 'InMode')]), + + # QTMusic const-less input parameters + ([('unsigned_long', 'header', 'OutMode')], [('UnsignedLongPtr', 'header', 'InMode')]), + ] + if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/qt/qtsupport.py b/Mac/Modules/qt/qtsupport.py index 20304c9..132c2b4 100644 --- a/Mac/Modules/qt/qtsupport.py +++ b/Mac/Modules/qt/qtsupport.py @@ -8,16 +8,16 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Movies.h' # The Apple header file -MODNAME = '_Qt' # The name of the module -OBJECTNAME = 'Movie' # The basic name of the objects used here +MACHEADERFILE = 'Movies.h' # The Apple header file +MODNAME = '_Qt' # The name of the module +OBJECTNAME = 'Movie' # The basic name of the objects used here # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Qt' # The prefix for module-wide routines -OBJECTTYPE = "Movie" # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Qt' # The prefix for module-wide routines +OBJECTTYPE = "Movie" # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -57,45 +57,45 @@ extern int _MediaObj_Convert(PyObject *, Media *); /* Macro to allow us to GetNextInterestingTime without duration */ #define GetMediaNextInterestingTimeOnly(media, flags, time, rate, rv) \ - GetMediaNextInterestingTime(media, flags, time, rate, rv, NULL) - + GetMediaNextInterestingTime(media, flags, time, rate, rv, NULL) + /* ** Parse/generate time records */ static PyObject * QtTimeRecord_New(TimeRecord *itself) { - if (itself->base) - return Py_BuildValue("O&lO&", PyMac_Buildwide, &itself->value, itself->scale, - TimeBaseObj_New, itself->base); - else - return Py_BuildValue("O&lO", PyMac_Buildwide, &itself->value, itself->scale, - Py_None); + if (itself->base) + return Py_BuildValue("O&lO&", PyMac_Buildwide, &itself->value, itself->scale, + TimeBaseObj_New, itself->base); + else + return Py_BuildValue("O&lO", PyMac_Buildwide, &itself->value, itself->scale, + Py_None); } static int QtTimeRecord_Convert(PyObject *v, TimeRecord *p_itself) { - PyObject *base = NULL; - if( !PyArg_ParseTuple(v, "O&l|O", PyMac_Getwide, &p_itself->value, &p_itself->scale, - &base) ) - return 0; - if ( base == NULL || base == Py_None ) - p_itself->base = NULL; - else - if ( !TimeBaseObj_Convert(base, &p_itself->base) ) - return 0; - return 1; + PyObject *base = NULL; + if( !PyArg_ParseTuple(v, "O&l|O", PyMac_Getwide, &p_itself->value, &p_itself->scale, + &base) ) + return 0; + if ( base == NULL || base == Py_None ) + p_itself->base = NULL; + else + if ( !TimeBaseObj_Convert(base, &p_itself->base) ) + return 0; + return 1; } static int QtMusicMIDIPacket_Convert(PyObject *v, MusicMIDIPacket *p_itself) { - int dummy; - - if( !PyArg_ParseTuple(v, "hls#", &p_itself->length, &p_itself->reserved, p_itself->data, dummy) ) - return 0; - return 1; + int dummy; + + if( !PyArg_ParseTuple(v, "hls#", &p_itself->length, &p_itself->reserved, p_itself->data, dummy) ) + return 0; + return 1; } @@ -103,18 +103,18 @@ QtMusicMIDIPacket_Convert(PyObject *v, MusicMIDIPacket *p_itself) """ initstuff = initstuff + """ - PyMac_INIT_TOOLBOX_OBJECT_NEW(Track, TrackObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Track, TrackObj_Convert); - PyMac_INIT_TOOLBOX_OBJECT_NEW(Movie, MovieObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Movie, MovieObj_Convert); - PyMac_INIT_TOOLBOX_OBJECT_NEW(MovieController, MovieCtlObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(MovieController, MovieCtlObj_Convert); - PyMac_INIT_TOOLBOX_OBJECT_NEW(TimeBase, TimeBaseObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(TimeBase, TimeBaseObj_Convert); - PyMac_INIT_TOOLBOX_OBJECT_NEW(UserData, UserDataObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(UserData, UserDataObj_Convert); - PyMac_INIT_TOOLBOX_OBJECT_NEW(Media, MediaObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Media, MediaObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(Track, TrackObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Track, TrackObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(Movie, MovieObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Movie, MovieObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(MovieController, MovieCtlObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(MovieController, MovieCtlObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(TimeBase, TimeBaseObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(TimeBase, TimeBaseObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(UserData, UserDataObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(UserData, UserDataObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(Media, MediaObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Media, MediaObj_Convert); """ # Our (opaque) objects @@ -232,56 +232,56 @@ AtomicInstrumentPtr = InputOnlyType("AtomicInstrumentPtr", "s") # XXXX Need to override output_tp_newBody() to allow for None initializer. class QtGlobalObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - # We don't allow NULL pointers to be returned by QuickTime API calls, - # in stead we raise an exception - Output("""if (itself == NULL) { - PyErr_SetString(Qt_Error,"Cannot create %s from NULL pointer"); - return NULL; - }""", self.name) - - def outputCheckConvertArg(self): - # But what we do allow is passing None whereever a quicktime object is - # expected, and pass this as NULL to the API routines. Note you can - # call methods too by creating an object with None as the initializer. - Output("if (v == Py_None)") - OutLbrace() - Output("*p_itself = NULL;") - Output("return 1;") - OutRbrace() - + def outputCheckNewArg(self): + # We don't allow NULL pointers to be returned by QuickTime API calls, + # in stead we raise an exception + Output("""if (itself == NULL) { + PyErr_SetString(Qt_Error,"Cannot create %s from NULL pointer"); + return NULL; + }""", self.name) + + def outputCheckConvertArg(self): + # But what we do allow is passing None whereever a quicktime object is + # expected, and pass this as NULL to the API routines. Note you can + # call methods too by creating an object with None as the initializer. + Output("if (v == Py_None)") + OutLbrace() + Output("*p_itself = NULL;") + Output("return 1;") + OutRbrace() + class MovieObjectDefinition(QtGlobalObjectDefinition): - def outputFreeIt(self, itselfname): - Output("if (%s) DisposeMovie(%s);", itselfname, itselfname) + def outputFreeIt(self, itselfname): + Output("if (%s) DisposeMovie(%s);", itselfname, itselfname) class TrackObjectDefinition(QtGlobalObjectDefinition): - def outputFreeIt(self, itselfname): - Output("if (%s) DisposeMovieTrack(%s);", itselfname, itselfname) + def outputFreeIt(self, itselfname): + Output("if (%s) DisposeMovieTrack(%s);", itselfname, itselfname) class MediaObjectDefinition(QtGlobalObjectDefinition): - def outputFreeIt(self, itselfname): - Output("if (%s) DisposeTrackMedia(%s);", itselfname, itselfname) + def outputFreeIt(self, itselfname): + Output("if (%s) DisposeTrackMedia(%s);", itselfname, itselfname) class UserDataObjectDefinition(QtGlobalObjectDefinition): - def outputFreeIt(self, itselfname): - Output("if (%s) DisposeUserData(%s);", itselfname, itselfname) + def outputFreeIt(self, itselfname): + Output("if (%s) DisposeUserData(%s);", itselfname, itselfname) class TimeBaseObjectDefinition(QtGlobalObjectDefinition): - pass - + pass + class MovieCtlObjectDefinition(QtGlobalObjectDefinition): - def outputFreeIt(self, itselfname): - Output("if (%s) DisposeMovieController(%s);", itselfname, itselfname) + def outputFreeIt(self, itselfname): + Output("if (%s) DisposeMovieController(%s);", itselfname, itselfname) class IdleManagerObjectDefinition(QtGlobalObjectDefinition): - pass - + pass + class SGOutputObjectDefinition(QtGlobalObjectDefinition): - # XXXX I'm not sure I fully understand how SGOutput works. It seems it's always tied - # to a specific SeqGrabComponent, but I'm not 100% sure. Also, I'm not sure all the - # routines that return an SGOutput actually return a *new* SGOutput. Need to read up on - # this. - pass + # XXXX I'm not sure I fully understand how SGOutput works. It seems it's always tied + # to a specific SeqGrabComponent, but I'm not 100% sure. Also, I'm not sure all the + # routines that return an SGOutput actually return a *new* SGOutput. Need to read up on + # this. + pass # From here on it's basically all boiler plate... @@ -331,19 +331,19 @@ ICMAlignmentProcRecordPtr = FakeType('(ICMAlignmentProcRecordPtr)0') dummyRect = FakeType('(Rect *)0') f = Function(void, 'AlignWindow', - (WindowPtr, 'wp', InMode), - (Boolean, 'front', InMode), - (dummyRect, 'alignmentRect', InMode), - (ICMAlignmentProcRecordPtr, 'alignmentProc', InMode), + (WindowPtr, 'wp', InMode), + (Boolean, 'front', InMode), + (dummyRect, 'alignmentRect', InMode), + (ICMAlignmentProcRecordPtr, 'alignmentProc', InMode), ) functions.append(f) f = Function(void, 'DragAlignedWindow', - (WindowPtr, 'wp', InMode), - (Point, 'startPt', InMode), - (Rect_ptr, 'boundsRect', InMode), - (dummyRect, 'alignmentRect', InMode), - (ICMAlignmentProcRecordPtr, 'alignmentProc', InMode), + (WindowPtr, 'wp', InMode), + (Point, 'startPt', InMode), + (Rect_ptr, 'boundsRect', InMode), + (dummyRect, 'alignmentRect', InMode), + (ICMAlignmentProcRecordPtr, 'alignmentProc', InMode), ) functions.append(f) @@ -377,4 +377,3 @@ for f in Movie_methods: Movie_object.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/qt/setup.py b/Mac/Modules/qt/setup.py index 98d836d..8442011 100755 --- a/Mac/Modules/qt/setup.py +++ b/Mac/Modules/qt/setup.py @@ -4,10 +4,10 @@ from distutils.core import Extension, setup setup(name="QuickTime", version="0.2", - ext_modules=[ - Extension('QuickTime._Qt', ['_Qtmodule.c'], - extra_link_args=['-framework', 'Carbon', '-framework', 'QuickTime']) - ], - py_modules=['QuickTime.Qt', 'QuickTime.QuickTime'], - package_dir={'QuickTime':'../../../Lib/plat-mac/Carbon'} - ) + ext_modules=[ + Extension('QuickTime._Qt', ['_Qtmodule.c'], + extra_link_args=['-framework', 'Carbon', '-framework', 'QuickTime']) + ], + py_modules=['QuickTime.Qt', 'QuickTime.QuickTime'], + package_dir={'QuickTime':'../../../Lib/plat-mac/Carbon'} + ) diff --git a/Mac/Modules/res/resedit.py b/Mac/Modules/res/resedit.py index ab60b34..b3ef790 100644 --- a/Mac/Modules/res/resedit.py +++ b/Mac/Modules/res/resedit.py @@ -4,11 +4,11 @@ ##Handle h; ## ##if (!PyArg_ParseTuple(_args, "s#", &buf, &len)) -## return NULL; +## return NULL; ##h = NewHandle(len); ##if ( h == NULL ) { -## PyErr_NoMemory(); -## return NULL; +## PyErr_NoMemory(); +## return NULL; ##} ##HLock(h); ##memcpy(*h, buf, len); @@ -33,11 +33,11 @@ Handle h; ResourceObject *rv; if (!PyArg_ParseTuple(_args, "s#", &buf, &len)) - return NULL; + return NULL; h = NewHandle(len); if ( h == NULL ) { - PyErr_NoMemory(); - return NULL; + PyErr_NoMemory(); + return NULL; } HLock(h); memcpy(*h, buf, len); @@ -66,10 +66,10 @@ return _res; def genresconverter(longname, shortname): - f = ManualGenerator("as_%s"%longname, as_xxx_body%(shortname, longname)) - docstring = "Return this resource/handle as a %s"%longname - f.docstring = lambda docstring=docstring: docstring - return f + f = ManualGenerator("as_%s"%longname, as_xxx_body%(shortname, longname)) + docstring = "Return this resource/handle as a %s"%longname + f.docstring = lambda docstring=docstring: docstring + return f resmethods.append(genresconverter("Control", "Ctl")) resmethods.append(genresconverter("Menu", "Menu")) @@ -87,13 +87,13 @@ resmethods.append(f) AutoDispose_body = """ int onoff, old = 0; if (!PyArg_ParseTuple(_args, "i", &onoff)) - return NULL; + return NULL; if ( _self->ob_freeit ) - old = 1; + old = 1; if ( onoff ) - _self->ob_freeit = PyMac_AutoDisposeHandle; + _self->ob_freeit = PyMac_AutoDisposeHandle; else - _self->ob_freeit = NULL; + _self->ob_freeit = NULL; _res = Py_BuildValue("i", old); return _res; """ diff --git a/Mac/Modules/res/resscan.py b/Mac/Modules/res/resscan.py index 47a19a6..47a97e4 100644 --- a/Mac/Modules/res/resscan.py +++ b/Mac/Modules/res/resscan.py @@ -13,73 +13,73 @@ sys.path.append(BGENDIR) from scantools import Scanner def main(): - input = "Resources.h" - output = "resgen.py" - defsoutput = TOOLBOXDIR + "Resources.py" - scanner = ResourcesScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now doing 'import ressupport' ===" - import ressupport - print "=== Done 'import ressupport'. It's up to you to compile Resmodule.c ===" + input = "Resources.h" + output = "resgen.py" + defsoutput = TOOLBOXDIR + "Resources.py" + scanner = ResourcesScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now doing 'import ressupport' ===" + import ressupport + print "=== Done 'import ressupport'. It's up to you to compile Resmodule.c ===" class ResourcesScanner(Scanner): - def destination(self, type, name, arglist): - classname = "ResFunction" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t == "Handle" and m == "InMode": - classname = "ResMethod" - listname = "resmethods" - return classname, listname - - def makeblacklistnames(self): - return [ - "ReadPartialResource", - "WritePartialResource", - "TempInsertROMMap", -## "RmveResource", # RemoveResource -## "SizeResource", # GetResourceSizeOnDisk -## "MaxSizeRsrc", # GetMaxResourceSize - # OS8 only - 'RGetResource', - 'OpenResFile', - 'CreateResFile', - 'RsrcZoneInit', - 'InitResources', - 'RsrcMapEntry', - ] - - def makeblacklisttypes(self): - return [ - ] - - def makerepairinstructions(self): - return [ - ([("Str255", "*", "InMode")], - [("*", "*", "OutMode")]), - - ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], - [("InBuffer", "*", "*")]), - - ([("void", "*", "OutMode"), ("long", "*", "InMode")], - [("InOutBuffer", "*", "*")]), - - ([("void", "*", "OutMode"), ("long", "*", "InMode"), - ("long", "*", "OutMode")], - [("OutBuffer", "*", "InOutMode")]), - - ([("SInt8", "*", "*")], - [("SignedByte", "*", "*")]), - - - ([("UniCharCount", "*", "InMode"), ("UniChar_ptr", "*", "InMode")], - [("UnicodeReverseInBuffer", "*", "*")]), - ] + def destination(self, type, name, arglist): + classname = "ResFunction" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t == "Handle" and m == "InMode": + classname = "ResMethod" + listname = "resmethods" + return classname, listname + + def makeblacklistnames(self): + return [ + "ReadPartialResource", + "WritePartialResource", + "TempInsertROMMap", +## "RmveResource", # RemoveResource +## "SizeResource", # GetResourceSizeOnDisk +## "MaxSizeRsrc", # GetMaxResourceSize + # OS8 only + 'RGetResource', + 'OpenResFile', + 'CreateResFile', + 'RsrcZoneInit', + 'InitResources', + 'RsrcMapEntry', + ] + + def makeblacklisttypes(self): + return [ + ] + + def makerepairinstructions(self): + return [ + ([("Str255", "*", "InMode")], + [("*", "*", "OutMode")]), + + ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], + [("InBuffer", "*", "*")]), + + ([("void", "*", "OutMode"), ("long", "*", "InMode")], + [("InOutBuffer", "*", "*")]), + + ([("void", "*", "OutMode"), ("long", "*", "InMode"), + ("long", "*", "OutMode")], + [("OutBuffer", "*", "InOutMode")]), + + ([("SInt8", "*", "*")], + [("SignedByte", "*", "*")]), + + + ([("UniCharCount", "*", "InMode"), ("UniChar_ptr", "*", "InMode")], + [("UnicodeReverseInBuffer", "*", "*")]), + ] if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/res/ressupport.py b/Mac/Modules/res/ressupport.py index 6135560..04a1821 100644 --- a/Mac/Modules/res/ressupport.py +++ b/Mac/Modules/res/ressupport.py @@ -7,13 +7,13 @@ from macsupport import * class ResMixIn: - def checkit(self): - if self.returntype.__class__ != OSErrType: - OutLbrace() - Output("OSErr _err = ResError();") - Output("if (_err != noErr) return PyMac_Error(_err);") - OutRbrace() - FunctionGenerator.checkit(self) # XXX + def checkit(self): + if self.returntype.__class__ != OSErrType: + OutLbrace() + Output("OSErr _err = ResError();") + Output("if (_err != noErr) return PyMac_Error(_err);") + OutRbrace() + FunctionGenerator.checkit(self) # XXX class ResFunction(ResMixIn, OSErrWeakLinkFunctionGenerator): pass class ResMethod(ResMixIn, OSErrWeakLinkMethodGenerator): pass @@ -42,7 +42,7 @@ extern int _OptResObj_Convert(PyObject *, Handle *); static void PyMac_AutoDisposeHandle(Handle h) { - DisposeHandle(h); + DisposeHandle(h); } """ @@ -51,159 +51,159 @@ finalstuff = finalstuff + """ /* Alternative version of ResObj_New, which returns None for null argument */ PyObject *OptResObj_New(Handle itself) { - if (itself == NULL) { - Py_INCREF(Py_None); - return Py_None; - } - return ResObj_New(itself); + if (itself == NULL) { + Py_INCREF(Py_None); + return Py_None; + } + return ResObj_New(itself); } int OptResObj_Convert(PyObject *v, Handle *p_itself) { - PyObject *tmp; - - if ( v == Py_None ) { - *p_itself = NULL; - return 1; - } - if (ResObj_Check(v)) - { - *p_itself = ((ResourceObject *)v)->ob_itself; - return 1; - } - /* If it isn't a resource yet see whether it is convertible */ - if ( (tmp=PyObject_CallMethod(v, "as_Resource", "")) ) { - *p_itself = ((ResourceObject *)tmp)->ob_itself; - Py_DECREF(tmp); - return 1; - } - PyErr_Clear(); - PyErr_SetString(PyExc_TypeError, "Resource required"); - return 0; + PyObject *tmp; + + if ( v == Py_None ) { + *p_itself = NULL; + return 1; + } + if (ResObj_Check(v)) + { + *p_itself = ((ResourceObject *)v)->ob_itself; + return 1; + } + /* If it isn't a resource yet see whether it is convertible */ + if ( (tmp=PyObject_CallMethod(v, "as_Resource", "")) ) { + *p_itself = ((ResourceObject *)tmp)->ob_itself; + Py_DECREF(tmp); + return 1; + } + PyErr_Clear(); + PyErr_SetString(PyExc_TypeError, "Resource required"); + return 0; } """ initstuff = initstuff + """ - PyMac_INIT_TOOLBOX_OBJECT_NEW(Handle, ResObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Handle, ResObj_Convert); - PyMac_INIT_TOOLBOX_OBJECT_NEW(Handle, OptResObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Handle, OptResObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(Handle, ResObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Handle, ResObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(Handle, OptResObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Handle, OptResObj_Convert); """ module = MacModule('_Res', 'Res', includestuff, finalstuff, initstuff) class ResDefinition(PEP253Mixin, GlobalObjectDefinition): - getsetlist = [ - ('data', - """ - PyObject *res; - char state; - - state = HGetState(self->ob_itself); - HLock(self->ob_itself); - res = PyString_FromStringAndSize( - *self->ob_itself, - GetHandleSize(self->ob_itself)); - HUnlock(self->ob_itself); - HSetState(self->ob_itself, state); - return res; - """, - """ - char *data; - long size; - - if ( v == NULL ) - return -1; - if ( !PyString_Check(v) ) - return -1; - size = PyString_Size(v); - data = PyString_AsString(v); - /* XXXX Do I need the GetState/SetState calls? */ - SetHandleSize(self->ob_itself, size); - if ( MemError()) - return -1; - HLock(self->ob_itself); - memcpy((char *)*self->ob_itself, data, size); - HUnlock(self->ob_itself); - /* XXXX Should I do the Changed call immedeately? */ - return 0; - """, - 'The resource data' - ), ( - 'size', - 'return PyInt_FromLong(GetHandleSize(self->ob_itself));', - None, - 'The length of the resource data' - )] - - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - - def outputCheckConvertArg(self): - # if it isn't a resource we may be able to coerce it - Output("if (!%s_Check(v))", self.prefix) - OutLbrace() - Output("PyObject *tmp;") - Output('if ( (tmp=PyObject_CallMethod(v, "as_Resource", "")) )') - OutLbrace() - Output("*p_itself = ((ResourceObject *)tmp)->ob_itself;") - Output("Py_DECREF(tmp);") - Output("return 1;") - OutRbrace() - Output("PyErr_Clear();") - OutRbrace() - - def outputStructMembers(self): - GlobalObjectDefinition.outputStructMembers(self) - Output("void (*ob_freeit)(%s ptr);", self.itselftype) - - def outputInitStructMembers(self): - GlobalObjectDefinition.outputInitStructMembers(self) - Output("it->ob_freeit = NULL;") - - def outputCleanupStructMembers(self): - Output("if (self->ob_freeit && self->ob_itself)") - OutLbrace() - Output("self->ob_freeit(self->ob_itself);") - OutRbrace() - Output("self->ob_itself = NULL;") - - def output_tp_newBody(self): - Output("PyObject *self;") - Output - Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") - Output("((%s *)self)->ob_itself = NULL;", self.objecttype) - Output("((%s *)self)->ob_freeit = NULL;", self.objecttype) - Output("return self;") - - def output_tp_initBody(self): - Output("char *srcdata = NULL;") - Output("int srclen = 0;") - Output("%s itself;", self.itselftype); - Output("char *kw[] = {\"itself\", 0};") - Output() - Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"O&\", kw, %s_Convert, &itself))", - self.prefix); - OutLbrace() - Output("((%s *)self)->ob_itself = itself;", self.objecttype) - Output("return 0;") - OutRbrace() - Output("PyErr_Clear();") - Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|s#\", kw, &srcdata, &srclen)) return -1;") - Output("if ((itself = NewHandle(srclen)) == NULL)") - OutLbrace() - Output("PyErr_NoMemory();") - Output("return 0;") - OutRbrace() - Output("((%s *)self)->ob_itself = itself;", self.objecttype) -# XXXX Output("((%s *)self)->ob_freeit = PyMac_AutoDisposeHandle;") - Output("if (srclen && srcdata)") - OutLbrace() - Output("HLock(itself);") - Output("memcpy(*itself, srcdata, srclen);") - Output("HUnlock(itself);") - OutRbrace() - Output("return 0;") + getsetlist = [ + ('data', + """ + PyObject *res; + char state; + + state = HGetState(self->ob_itself); + HLock(self->ob_itself); + res = PyString_FromStringAndSize( + *self->ob_itself, + GetHandleSize(self->ob_itself)); + HUnlock(self->ob_itself); + HSetState(self->ob_itself, state); + return res; + """, + """ + char *data; + long size; + + if ( v == NULL ) + return -1; + if ( !PyString_Check(v) ) + return -1; + size = PyString_Size(v); + data = PyString_AsString(v); + /* XXXX Do I need the GetState/SetState calls? */ + SetHandleSize(self->ob_itself, size); + if ( MemError()) + return -1; + HLock(self->ob_itself); + memcpy((char *)*self->ob_itself, data, size); + HUnlock(self->ob_itself); + /* XXXX Should I do the Changed call immedeately? */ + return 0; + """, + 'The resource data' + ), ( + 'size', + 'return PyInt_FromLong(GetHandleSize(self->ob_itself));', + None, + 'The length of the resource data' + )] + + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + + def outputCheckConvertArg(self): + # if it isn't a resource we may be able to coerce it + Output("if (!%s_Check(v))", self.prefix) + OutLbrace() + Output("PyObject *tmp;") + Output('if ( (tmp=PyObject_CallMethod(v, "as_Resource", "")) )') + OutLbrace() + Output("*p_itself = ((ResourceObject *)tmp)->ob_itself;") + Output("Py_DECREF(tmp);") + Output("return 1;") + OutRbrace() + Output("PyErr_Clear();") + OutRbrace() + + def outputStructMembers(self): + GlobalObjectDefinition.outputStructMembers(self) + Output("void (*ob_freeit)(%s ptr);", self.itselftype) + + def outputInitStructMembers(self): + GlobalObjectDefinition.outputInitStructMembers(self) + Output("it->ob_freeit = NULL;") + + def outputCleanupStructMembers(self): + Output("if (self->ob_freeit && self->ob_itself)") + OutLbrace() + Output("self->ob_freeit(self->ob_itself);") + OutRbrace() + Output("self->ob_itself = NULL;") + + def output_tp_newBody(self): + Output("PyObject *self;") + Output + Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") + Output("((%s *)self)->ob_itself = NULL;", self.objecttype) + Output("((%s *)self)->ob_freeit = NULL;", self.objecttype) + Output("return self;") + + def output_tp_initBody(self): + Output("char *srcdata = NULL;") + Output("int srclen = 0;") + Output("%s itself;", self.itselftype); + Output("char *kw[] = {\"itself\", 0};") + Output() + Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"O&\", kw, %s_Convert, &itself))", + self.prefix); + OutLbrace() + Output("((%s *)self)->ob_itself = itself;", self.objecttype) + Output("return 0;") + OutRbrace() + Output("PyErr_Clear();") + Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|s#\", kw, &srcdata, &srclen)) return -1;") + Output("if ((itself = NewHandle(srclen)) == NULL)") + OutLbrace() + Output("PyErr_NoMemory();") + Output("return 0;") + OutRbrace() + Output("((%s *)self)->ob_itself = itself;", self.objecttype) +# XXXX Output("((%s *)self)->ob_freeit = PyMac_AutoDisposeHandle;") + Output("if (srclen && srcdata)") + OutLbrace() + Output("HLock(itself);") + Output("memcpy(*itself, srcdata, srclen);") + Output("HUnlock(itself);") + OutRbrace() + Output("return 0;") resobject = ResDefinition('Resource', 'ResObj', 'Handle') module.addobject(resobject) diff --git a/Mac/Modules/scrap/scrapscan.py b/Mac/Modules/scrap/scrapscan.py index 0b173a4..1fc8191 100644 --- a/Mac/Modules/scrap/scrapscan.py +++ b/Mac/Modules/scrap/scrapscan.py @@ -13,49 +13,49 @@ LONG = "Scrap" SHORT = "scrap" def main(): - input = "Scrap.h" - output = SHORT + "gen.py" - defsoutput = "@Scrap.py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() -## print "=== Testing definitions output code ===" -## execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = "Scrap.h" + output = SHORT + "gen.py" + defsoutput = "@Scrap.py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() +## print "=== Testing definitions output code ===" +## execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t == 'ScrapRef' and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname - - def makeblacklistnames(self): - return [ - "GetScrapFlavorInfoList", - 'InfoScrap', - 'GetScrap', - 'ZeroScrap', - 'PutScrap', - ] - - def makeblacklisttypes(self): - return [ - 'ScrapPromiseKeeperUPP', - ] - - def makerepairinstructions(self): - return [ - ([('void', '*', 'OutMode')], [('putscrapbuffer', '*', 'InMode')]), - ([('void_ptr', '*', 'InMode')], [('putscrapbuffer', '*', 'InMode')]), - ] - + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t == 'ScrapRef' and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname + + def makeblacklistnames(self): + return [ + "GetScrapFlavorInfoList", + 'InfoScrap', + 'GetScrap', + 'ZeroScrap', + 'PutScrap', + ] + + def makeblacklisttypes(self): + return [ + 'ScrapPromiseKeeperUPP', + ] + + def makerepairinstructions(self): + return [ + ([('void', '*', 'OutMode')], [('putscrapbuffer', '*', 'InMode')]), + ([('void_ptr', '*', 'InMode')], [('putscrapbuffer', '*', 'InMode')]), + ] + if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/scrap/scrapsupport.py b/Mac/Modules/scrap/scrapsupport.py index 634a439..84a75d2 100644 --- a/Mac/Modules/scrap/scrapsupport.py +++ b/Mac/Modules/scrap/scrapsupport.py @@ -9,16 +9,16 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Scrap.h' # The Apple header file -MODNAME = '_Scrap' # The name of the module -OBJECTNAME = 'Scrap' # The basic name of the objects used here +MACHEADERFILE = 'Scrap.h' # The Apple header file +MODNAME = '_Scrap' # The name of the module +OBJECTNAME = 'Scrap' # The basic name of the objects used here # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Scrap' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + 'Ref' # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Scrap' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + 'Ref' # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = '@' + MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = '@' + MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -33,12 +33,12 @@ includestuff = includestuff + """ */ static PyObject * SCRRec_New(itself) - ScrapStuff *itself; + ScrapStuff *itself; { - return Py_BuildValue("lO&hhO&", itself->scrapSize, - ResObj_New, itself->scrapHandle, itself->scrapCount, itself->scrapState, - PyMac_BuildStr255, itself->scrapName); + return Py_BuildValue("lO&hhO&", itself->scrapSize, + ResObj_New, itself->scrapHandle, itself->scrapCount, itself->scrapState, + PyMac_BuildStr255, itself->scrapName); } """ @@ -49,7 +49,7 @@ ScrapFlavorFlags = Type('ScrapFlavorFlags', 'l') putscrapbuffer = FixedInputBufferType('void *') class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - pass + pass # Create the generator groups and link them module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff) @@ -73,4 +73,3 @@ for f in methods: object.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/snd/sndscan.py b/Mac/Modules/snd/sndscan.py index a287c73..c4a8266 100644 --- a/Mac/Modules/snd/sndscan.py +++ b/Mac/Modules/snd/sndscan.py @@ -10,119 +10,119 @@ sys.path.append(BGENDIR) from scantools import Scanner def main(): - input = "Sound.h" - output = "sndgen.py" - defsoutput = TOOLBOXDIR + "Sound.py" - scanner = SoundScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now doing 'import sndsupport' ===" - import sndsupport - print "=== Done. It's up to you to compile Sndmodule.c ===" + input = "Sound.h" + output = "sndgen.py" + defsoutput = TOOLBOXDIR + "Sound.py" + scanner = SoundScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now doing 'import sndsupport' ===" + import sndsupport + print "=== Done. It's up to you to compile Sndmodule.c ===" class SoundScanner(Scanner): - def destination(self, type, name, arglist): - classname = "SndFunction" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t == "SndChannelPtr" and m == "InMode": - classname = "SndMethod" - listname = "sndmethods" - return classname, listname - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - - def makeblacklistnames(self): - return [ - 'SndDisposeChannel', # automatic on deallocation - 'SndAddModifier', # for internal use only - 'SndPlayDoubleBuffer', # very low level routine - # Missing from libraries (UH332) - 'SoundManagerSetInfo', - 'SoundManagerGetInfo', - # Constants with funny definitions - 'rate48khz', - 'rate44khz', - 'kInvalidSource', - # OS8 only: - 'MACEVersion', - 'SPBRecordToFile', - 'Exp1to6', - 'Comp6to1', - 'Exp1to3', - 'Comp3to1', - 'SndControl', - 'SndStopFilePlay', - 'SndStartFilePlay', - 'SndPauseFilePlay', - 'SndRecordToFile', - - ] - - def makeblacklisttypes(self): - return [ - "GetSoundVol", - "SetSoundVol", - "UnsignedFixed", - # Don't have the time to dig into this... - "Component", - "ComponentInstance", - "SoundComponentDataPtr", - "SoundComponentData", - "SoundComponentData_ptr", - "SoundConverter", - ] - - def makerepairinstructions(self): - return [ - ([("Str255", "*", "InMode")], - [("*", "*", "OutMode")]), - - ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], - [("InBuffer", "*", "*")]), - - ([("void", "*", "OutMode"), ("long", "*", "InMode"), - ("long", "*", "OutMode")], - [("VarVarOutBuffer", "*", "InOutMode")]), - - ([("SCStatusPtr", "*", "InMode")], - [("SCStatus", "*", "OutMode")]), - - ([("SMStatusPtr", "*", "InMode")], - [("SMStatus", "*", "OutMode")]), - - ([("CompressionInfoPtr", "*", "InMode")], - [("CompressionInfo", "*", "OutMode")]), - - # For SndPlay's SndListHandle argument - ([("Handle", "sndHdl", "InMode")], - [("SndListHandle", "*", "*")]), - - # For SndStartFilePlay - ([("long", "bufferSize", "InMode"), ("void", "theBuffer", "OutMode")], - [("*", "*", "*"), ("FakeType('0')", "*", "InMode")]), - - # For Comp3to1 etc. - ([("void_ptr", "inBuffer", "InMode"), - ("void", "outBuffer", "OutMode"), - ("unsigned_long", "cnt", "InMode")], - [("InOutBuffer", "buffer", "InOutMode")]), - - # Ditto -## ([("void_ptr", "inState", "InMode"), ("void", "outState", "OutMode")], -## [("InOutBuf128", "state", "InOutMode")]), - ([("StateBlockPtr", "inState", "InMode"), ("StateBlockPtr", "outState", "InMode")], - [("StateBlock", "state", "InOutMode")]), - - # Catch-all for the last couple of void pointers - ([("void", "*", "OutMode")], - [("void_ptr", "*", "InMode")]), - ] + def destination(self, type, name, arglist): + classname = "SndFunction" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t == "SndChannelPtr" and m == "InMode": + classname = "SndMethod" + listname = "sndmethods" + return classname, listname + + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + + def makeblacklistnames(self): + return [ + 'SndDisposeChannel', # automatic on deallocation + 'SndAddModifier', # for internal use only + 'SndPlayDoubleBuffer', # very low level routine + # Missing from libraries (UH332) + 'SoundManagerSetInfo', + 'SoundManagerGetInfo', + # Constants with funny definitions + 'rate48khz', + 'rate44khz', + 'kInvalidSource', + # OS8 only: + 'MACEVersion', + 'SPBRecordToFile', + 'Exp1to6', + 'Comp6to1', + 'Exp1to3', + 'Comp3to1', + 'SndControl', + 'SndStopFilePlay', + 'SndStartFilePlay', + 'SndPauseFilePlay', + 'SndRecordToFile', + + ] + + def makeblacklisttypes(self): + return [ + "GetSoundVol", + "SetSoundVol", + "UnsignedFixed", + # Don't have the time to dig into this... + "Component", + "ComponentInstance", + "SoundComponentDataPtr", + "SoundComponentData", + "SoundComponentData_ptr", + "SoundConverter", + ] + + def makerepairinstructions(self): + return [ + ([("Str255", "*", "InMode")], + [("*", "*", "OutMode")]), + + ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], + [("InBuffer", "*", "*")]), + + ([("void", "*", "OutMode"), ("long", "*", "InMode"), + ("long", "*", "OutMode")], + [("VarVarOutBuffer", "*", "InOutMode")]), + + ([("SCStatusPtr", "*", "InMode")], + [("SCStatus", "*", "OutMode")]), + + ([("SMStatusPtr", "*", "InMode")], + [("SMStatus", "*", "OutMode")]), + + ([("CompressionInfoPtr", "*", "InMode")], + [("CompressionInfo", "*", "OutMode")]), + + # For SndPlay's SndListHandle argument + ([("Handle", "sndHdl", "InMode")], + [("SndListHandle", "*", "*")]), + + # For SndStartFilePlay + ([("long", "bufferSize", "InMode"), ("void", "theBuffer", "OutMode")], + [("*", "*", "*"), ("FakeType('0')", "*", "InMode")]), + + # For Comp3to1 etc. + ([("void_ptr", "inBuffer", "InMode"), + ("void", "outBuffer", "OutMode"), + ("unsigned_long", "cnt", "InMode")], + [("InOutBuffer", "buffer", "InOutMode")]), + + # Ditto +## ([("void_ptr", "inState", "InMode"), ("void", "outState", "OutMode")], +## [("InOutBuf128", "state", "InOutMode")]), + ([("StateBlockPtr", "inState", "InMode"), ("StateBlockPtr", "outState", "InMode")], + [("StateBlock", "state", "InOutMode")]), + + # Catch-all for the last couple of void pointers + ([("void", "*", "OutMode")], + [("void_ptr", "*", "InMode")]), + ] if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/snd/sndsupport.py b/Mac/Modules/snd/sndsupport.py index 99df5be..cf0fa6c 100644 --- a/Mac/Modules/snd/sndsupport.py +++ b/Mac/Modules/snd/sndsupport.py @@ -27,12 +27,12 @@ initstuff = initstuff + """ # define types used for arguments (in addition to standard and macsupport types) class SndChannelPtrType(OpaqueByValueType): - def declare(self, name): - # Initializing all SndChannelPtr objects to 0 saves - # special-casing NewSndChannel(), where it is formally an - # input-output parameter but we treat it as output-only - # (since Python users are not supposed to allocate memory) - Output("SndChannelPtr %s = 0;", name) + def declare(self, name): + # Initializing all SndChannelPtr objects to 0 saves + # special-casing NewSndChannel(), where it is formally an + # input-output parameter but we treat it as output-only + # (since Python users are not supposed to allocate memory) + Output("SndChannelPtr %s = 0;", name) SndChannelPtr = SndChannelPtrType('SndChannelPtr', 'SndCh') @@ -49,28 +49,28 @@ ModalFilterUPP = FakeType("(ModalFilterUPP)0") void_ptr = Type("void *", "w") class SndCallBackType(InputOnlyType): - def __init__(self): - Type.__init__(self, 'PyObject*', 'O') - def getargsCheck(self, name): - Output("if (%s != Py_None && !PyCallable_Check(%s))", name, name) - OutLbrace() - Output('PyErr_SetString(PyExc_TypeError, "callback must be callable");') - Output("goto %s__error__;", name) - OutRbrace() - def passInput(self, name): - return "NewSndCallBackUPP(SndCh_UserRoutine)" - def cleanup(self, name): - # XXX This knows it is executing inside the SndNewChannel wrapper - Output("if (_res != NULL && %s != Py_None)", name) - OutLbrace() - Output("SndChannelObject *p = (SndChannelObject *)_res;") - Output("p->ob_itself->userInfo = (long)p;") - Output("Py_INCREF(%s);", name) - Output("p->ob_callback = %s;", name) - OutRbrace() - DedentLevel() - Output(" %s__error__: ;", name) - IndentLevel() + def __init__(self): + Type.__init__(self, 'PyObject*', 'O') + def getargsCheck(self, name): + Output("if (%s != Py_None && !PyCallable_Check(%s))", name, name) + OutLbrace() + Output('PyErr_SetString(PyExc_TypeError, "callback must be callable");') + Output("goto %s__error__;", name) + OutRbrace() + def passInput(self, name): + return "NewSndCallBackUPP(SndCh_UserRoutine)" + def cleanup(self, name): + # XXX This knows it is executing inside the SndNewChannel wrapper + Output("if (_res != NULL && %s != Py_None)", name) + OutLbrace() + Output("SndChannelObject *p = (SndChannelObject *)_res;") + Output("p->ob_itself->userInfo = (long)p;") + Output("Py_INCREF(%s);", name) + Output("p->ob_callback = %s;", name) + OutRbrace() + DedentLevel() + Output(" %s__error__: ;", name) + IndentLevel() SndCallBackProcPtr = SndCallBackType() SndCallBackUPP = SndCallBackProcPtr @@ -95,16 +95,16 @@ includestuff = includestuff + """ static int SndCmd_Convert(PyObject *v, SndCommand *pc) { - int len; - pc->param1 = 0; - pc->param2 = 0; - if (PyTuple_Check(v)) { - if (PyArg_ParseTuple(v, "h|hl", &pc->cmd, &pc->param1, &pc->param2)) - return 1; - PyErr_Clear(); - return PyArg_ParseTuple(v, "Hhs#", &pc->cmd, &pc->param1, &pc->param2, &len); - } - return PyArg_Parse(v, "H", &pc->cmd); + int len; + pc->param1 = 0; + pc->param2 = 0; + if (PyTuple_Check(v)) { + if (PyArg_ParseTuple(v, "h|hl", &pc->cmd, &pc->param1, &pc->param2)) + return 1; + PyErr_Clear(); + return PyArg_ParseTuple(v, "Hhs#", &pc->cmd, &pc->param1, &pc->param2, &len); + } + return PyArg_Parse(v, "H", &pc->cmd); } static pascal void SndCh_UserRoutine(SndChannelPtr chan, SndCommand *cmd); /* Forward */ @@ -117,62 +117,62 @@ finalstuff = finalstuff + """ static int SndCh_CallCallBack(void *arg) { - SndChannelObject *p = (SndChannelObject *)arg; - PyObject *args; - PyObject *res; - args = Py_BuildValue("(O(hhl))", - p, p->ob_cmd.cmd, p->ob_cmd.param1, p->ob_cmd.param2); - res = PyEval_CallObject(p->ob_callback, args); - Py_DECREF(args); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + SndChannelObject *p = (SndChannelObject *)arg; + PyObject *args; + PyObject *res; + args = Py_BuildValue("(O(hhl))", + p, p->ob_cmd.cmd, p->ob_cmd.param1, p->ob_cmd.param2); + res = PyEval_CallObject(p->ob_callback, args); + Py_DECREF(args); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } /* Routine passed to NewSndChannel -- schedule a call to SndCh_CallCallBack */ static pascal void SndCh_UserRoutine(SndChannelPtr chan, SndCommand *cmd) { - SndChannelObject *p = (SndChannelObject *)(chan->userInfo); - if (p->ob_callback != NULL) { - long A5 = SetA5(p->ob_A5); - p->ob_cmd = *cmd; - Py_AddPendingCall(SndCh_CallCallBack, (void *)p); - SetA5(A5); - } + SndChannelObject *p = (SndChannelObject *)(chan->userInfo); + if (p->ob_callback != NULL) { + long A5 = SetA5(p->ob_A5); + p->ob_cmd = *cmd; + Py_AddPendingCall(SndCh_CallCallBack, (void *)p); + SetA5(A5); + } } /* SPB callbacks - Schedule callbacks to Python */ static int SPB_CallCallBack(void *arg) { - SPBObject *p = (SPBObject *)arg; - PyObject *args; - PyObject *res; - - if ( p->ob_thiscallback == 0 ) return 0; - args = Py_BuildValue("(O)", p); - res = PyEval_CallObject(p->ob_thiscallback, args); - p->ob_thiscallback = 0; - Py_DECREF(args); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; + SPBObject *p = (SPBObject *)arg; + PyObject *args; + PyObject *res; + + if ( p->ob_thiscallback == 0 ) return 0; + args = Py_BuildValue("(O)", p); + res = PyEval_CallObject(p->ob_thiscallback, args); + p->ob_thiscallback = 0; + Py_DECREF(args); + if (res == NULL) + return -1; + Py_DECREF(res); + return 0; } static pascal void SPB_completion(SPBPtr my_spb) { - SPBObject *p = (SPBObject *)(my_spb->userLong); - - if (p && p->ob_completion) { - long A5 = SetA5(p->ob_A5); - p->ob_thiscallback = p->ob_completion; /* Hope we cannot get two at the same time */ - Py_AddPendingCall(SPB_CallCallBack, (void *)p); - SetA5(A5); - } + SPBObject *p = (SPBObject *)(my_spb->userLong); + + if (p && p->ob_completion) { + long A5 = SetA5(p->ob_A5); + p->ob_thiscallback = p->ob_completion; /* Hope we cannot get two at the same time */ + Py_AddPendingCall(SPB_CallCallBack, (void *)p); + SetA5(A5); + } } """ @@ -182,110 +182,110 @@ SPB_completion(SPBPtr my_spb) class SndObjectDefinition(PEP252Mixin, ObjectDefinition): - def outputStructMembers(self): - ObjectDefinition.outputStructMembers(self) - Output("/* Members used to implement callbacks: */") - Output("PyObject *ob_callback;") - Output("long ob_A5;"); - Output("SndCommand ob_cmd;") - - def outputInitStructMembers(self): - ObjectDefinition.outputInitStructMembers(self) - Output("it->ob_callback = NULL;") - Output("it->ob_A5 = SetCurrentA5();"); - - def outputCleanupStructMembers(self): - ObjectDefinition.outputCleanupStructMembers(self) - Output("Py_XDECREF(self->ob_callback);") - - def outputFreeIt(self, itselfname): - Output("SndDisposeChannel(%s, 1);", itselfname) - - def outputConvert(self): - pass # Not needed - + def outputStructMembers(self): + ObjectDefinition.outputStructMembers(self) + Output("/* Members used to implement callbacks: */") + Output("PyObject *ob_callback;") + Output("long ob_A5;"); + Output("SndCommand ob_cmd;") + + def outputInitStructMembers(self): + ObjectDefinition.outputInitStructMembers(self) + Output("it->ob_callback = NULL;") + Output("it->ob_A5 = SetCurrentA5();"); + + def outputCleanupStructMembers(self): + ObjectDefinition.outputCleanupStructMembers(self) + Output("Py_XDECREF(self->ob_callback);") + + def outputFreeIt(self, itselfname): + Output("SndDisposeChannel(%s, 1);", itselfname) + + def outputConvert(self): + pass # Not needed + # class SpbObjectDefinition(PEP252Mixin, ObjectDefinition): - getsetlist = [ - ( - 'inRefNum', - 'return Py_BuildValue("l", self->ob_spb.inRefNum);', - 'return -1 + PyArg_Parse(v, "l", &self->ob_spb.inRefNum);', - None, - ), ( - 'count', - 'return Py_BuildValue("l", self->ob_spb.count);', - 'return -1 + PyArg_Parse(v, "l", &self->ob_spb.count);', - None - ), ( - 'milliseconds', - 'return Py_BuildValue("l", self->ob_spb.milliseconds);', - 'return -1 + PyArg_Parse(v, "l", &self->ob_spb.milliseconds);', - None, - ), ( - 'error', - 'return Py_BuildValue("h", self->ob_spb.error);', - None, - None - ), ( - 'completionRoutine', - None, - """self->ob_spb.completionRoutine = NewSICompletionUPP(SPB_completion); - self->ob_completion = v; - Py_INCREF(v); - return 0;""", - None, - )] - - def outputStructMembers(self): - Output("/* Members used to implement callbacks: */") - Output("PyObject *ob_completion;") - Output("PyObject *ob_interrupt;") - Output("PyObject *ob_thiscallback;"); - Output("long ob_A5;") - Output("SPB ob_spb;") - - def outputNew(self): - Output() - Output("%sPyObject *%s_New(void)", self.static, self.prefix) - OutLbrace() - Output("%s *it;", self.objecttype) - self.outputCheckNewArg() - Output("it = PyObject_NEW(%s, &%s);", self.objecttype, self.typename) - Output("if (it == NULL) return NULL;") - self.outputInitStructMembers() - Output("return (PyObject *)it;") - OutRbrace() - - def outputInitStructMembers(self): - Output("it->ob_completion = NULL;") - Output("it->ob_interrupt = NULL;") - Output("it->ob_thiscallback = NULL;") - Output("it->ob_A5 = SetCurrentA5();") - Output("memset((char *)&it->ob_spb, 0, sizeof(it->ob_spb));") - Output("it->ob_spb.userLong = (long)it;") - - def outputCleanupStructMembers(self): - ObjectDefinition.outputCleanupStructMembers(self) - Output("self->ob_spb.userLong = 0;") - Output("self->ob_thiscallback = 0;") - Output("Py_XDECREF(self->ob_completion);") - Output("Py_XDECREF(self->ob_interrupt);") - - def outputConvert(self): - Output("%sint %s_Convert(PyObject *v, %s *p_itself)", self.static, self.prefix, self.itselftype) - OutLbrace() - self.outputCheckConvertArg() - Output("if (!%s_Check(v))", self.prefix) - OutLbrace() - Output('PyErr_SetString(PyExc_TypeError, "%s required");', self.name) - Output("return 0;") - OutRbrace() - Output("*p_itself = &((%s *)v)->ob_spb;", self.objecttype) - Output("return 1;") - OutRbrace() - + getsetlist = [ + ( + 'inRefNum', + 'return Py_BuildValue("l", self->ob_spb.inRefNum);', + 'return -1 + PyArg_Parse(v, "l", &self->ob_spb.inRefNum);', + None, + ), ( + 'count', + 'return Py_BuildValue("l", self->ob_spb.count);', + 'return -1 + PyArg_Parse(v, "l", &self->ob_spb.count);', + None + ), ( + 'milliseconds', + 'return Py_BuildValue("l", self->ob_spb.milliseconds);', + 'return -1 + PyArg_Parse(v, "l", &self->ob_spb.milliseconds);', + None, + ), ( + 'error', + 'return Py_BuildValue("h", self->ob_spb.error);', + None, + None + ), ( + 'completionRoutine', + None, + """self->ob_spb.completionRoutine = NewSICompletionUPP(SPB_completion); + self->ob_completion = v; + Py_INCREF(v); + return 0;""", + None, + )] + + def outputStructMembers(self): + Output("/* Members used to implement callbacks: */") + Output("PyObject *ob_completion;") + Output("PyObject *ob_interrupt;") + Output("PyObject *ob_thiscallback;"); + Output("long ob_A5;") + Output("SPB ob_spb;") + + def outputNew(self): + Output() + Output("%sPyObject *%s_New(void)", self.static, self.prefix) + OutLbrace() + Output("%s *it;", self.objecttype) + self.outputCheckNewArg() + Output("it = PyObject_NEW(%s, &%s);", self.objecttype, self.typename) + Output("if (it == NULL) return NULL;") + self.outputInitStructMembers() + Output("return (PyObject *)it;") + OutRbrace() + + def outputInitStructMembers(self): + Output("it->ob_completion = NULL;") + Output("it->ob_interrupt = NULL;") + Output("it->ob_thiscallback = NULL;") + Output("it->ob_A5 = SetCurrentA5();") + Output("memset((char *)&it->ob_spb, 0, sizeof(it->ob_spb));") + Output("it->ob_spb.userLong = (long)it;") + + def outputCleanupStructMembers(self): + ObjectDefinition.outputCleanupStructMembers(self) + Output("self->ob_spb.userLong = 0;") + Output("self->ob_thiscallback = 0;") + Output("Py_XDECREF(self->ob_completion);") + Output("Py_XDECREF(self->ob_interrupt);") + + def outputConvert(self): + Output("%sint %s_Convert(PyObject *v, %s *p_itself)", self.static, self.prefix, self.itselftype) + OutLbrace() + self.outputCheckConvertArg() + Output("if (!%s_Check(v))", self.prefix) + OutLbrace() + Output('PyErr_SetString(PyExc_TypeError, "%s required");', self.name) + Output("return 0;") + OutRbrace() + Output("*p_itself = &((%s *)v)->ob_spb;", self.objecttype) + Output("return 1;") + OutRbrace() + sndobject = SndObjectDefinition('SndChannel', 'SndCh', 'SndChannelPtr') spbobject = SpbObjectDefinition('SPB', 'SPBObj', 'SPBPtr') diff --git a/Mac/Modules/te/tescan.py b/Mac/Modules/te/tescan.py index c81a8bf..f5b6fff 100644 --- a/Mac/Modules/te/tescan.py +++ b/Mac/Modules/te/tescan.py @@ -11,57 +11,57 @@ SHORT = "te" OBJECT = "TEHandle" def main(): - input = LONG + ".h" - output = SHORT + "gen.py" - defsoutput = TOOLBOXDIR + LONG + ".py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = LONG + ".h" + output = SHORT + "gen.py" + defsoutput = TOOLBOXDIR + LONG + ".py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[-1] - # This is non-functional today - if t == OBJECT and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[-1] + # This is non-functional today + if t == OBJECT and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname - def makeblacklistnames(self): - return [ - "TEDispose", - "TEInit", -## "TEGetHiliteRgn", - ] + def makeblacklistnames(self): + return [ + "TEDispose", + "TEInit", +## "TEGetHiliteRgn", + ] - def makeblacklisttypes(self): - return [ - "TEClickLoopUPP", - "UniversalProcPtr", - "WordBreakUPP", - "TEDoTextUPP", - "TERecalcUPP", - "TEFindWordUPP", - ] + def makeblacklisttypes(self): + return [ + "TEClickLoopUPP", + "UniversalProcPtr", + "WordBreakUPP", + "TEDoTextUPP", + "TERecalcUPP", + "TEFindWordUPP", + ] + + def makerepairinstructions(self): + return [ + ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], + [("InBuffer", "*", "*")]), + + # TEContinuousStyle + ([("short", "mode", "OutMode"), ("TextStyle", "aStyle", "OutMode")], + [("short", "mode", "InOutMode"), ("TextStyle", "aStyle", "InOutMode")]) + ] - def makerepairinstructions(self): - return [ - ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], - [("InBuffer", "*", "*")]), - - # TEContinuousStyle - ([("short", "mode", "OutMode"), ("TextStyle", "aStyle", "OutMode")], - [("short", "mode", "InOutMode"), ("TextStyle", "aStyle", "InOutMode")]) - ] - if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/te/tesupport.py b/Mac/Modules/te/tesupport.py index 13f1b97..ad6c053 100644 --- a/Mac/Modules/te/tesupport.py +++ b/Mac/Modules/te/tesupport.py @@ -6,17 +6,17 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'TextEdit.h' # The Apple header file -MODNAME = '_TE' # The name of the module -OBJECTNAME = 'TE' # The basic name of the objects used here -KIND = 'Handle' # Usually 'Ptr' or 'Handle' +MACHEADERFILE = 'TextEdit.h' # The Apple header file +MODNAME = '_TE' # The name of the module +OBJECTNAME = 'TE' # The basic name of the objects used here +KIND = 'Handle' # Usually 'Ptr' or 'Handle' # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'TE' # The prefix for module-wide routines -OBJECTTYPE = "TEHandle" # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'TE' # The prefix for module-wide routines +OBJECTTYPE = "TEHandle" # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -52,137 +52,137 @@ static PyObject * TextStyle_New(TextStylePtr itself) { - return Py_BuildValue("lllO&", (long)itself->tsFont, (long)itself->tsFace, (long)itself->tsSize, QdRGB_New, - &itself->tsColor); + return Py_BuildValue("lllO&", (long)itself->tsFont, (long)itself->tsFace, (long)itself->tsSize, QdRGB_New, + &itself->tsColor); } static int TextStyle_Convert(PyObject *v, TextStylePtr p_itself) { - long font, face, size; - - if( !PyArg_ParseTuple(v, "lllO&", &font, &face, &size, QdRGB_Convert, &p_itself->tsColor) ) - return 0; - p_itself->tsFont = (short)font; - p_itself->tsFace = (Style)face; - p_itself->tsSize = (short)size; - return 1; + long font, face, size; + + if( !PyArg_ParseTuple(v, "lllO&", &font, &face, &size, QdRGB_Convert, &p_itself->tsColor) ) + return 0; + p_itself->tsFont = (short)font; + p_itself->tsFace = (Style)face; + p_itself->tsSize = (short)size; + return 1; } """ initstuff = initstuff + """ - PyMac_INIT_TOOLBOX_OBJECT_NEW(TEHandle, TEObj_New); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(TEHandle, TEObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(TEHandle, TEObj_New); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(TEHandle, TEObj_Convert); """ class TEMethodGenerator(OSErrWeakLinkMethodGenerator): - """Similar to MethodGenerator, but has self as last argument""" + """Similar to MethodGenerator, but has self as last argument""" - def parseArgumentList(self, args): - args, a0 = args[:-1], args[-1] - t0, n0, m0 = a0 - if m0 != InMode: - raise ValueError, "method's 'self' must be 'InMode'" - self.itself = Variable(t0, "_self->ob_itself", SelfMode) - FunctionGenerator.parseArgumentList(self, args) - self.argumentList.append(self.itself) + def parseArgumentList(self, args): + args, a0 = args[:-1], args[-1] + t0, n0, m0 = a0 + if m0 != InMode: + raise ValueError, "method's 'self' must be 'InMode'" + self.itself = Variable(t0, "_self->ob_itself", SelfMode) + FunctionGenerator.parseArgumentList(self, args) + self.argumentList.append(self.itself) class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - # XXXX Could be subtype of Resource - # Attributes that can be set. - getsetlist = [ - ( - 'destRect', - 'return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->destRect);', - None, - 'Destination rectangle' - ), ( - 'viewRect', - 'return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->viewRect);', - None, - 'Viewing rectangle' - ), ( - 'selRect', - 'return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->selRect);', - None, - 'Selection rectangle' - ), ( - 'lineHeight', - 'return Py_BuildValue("h", (*self->ob_itself)->lineHeight);', - None, - 'Height of a line' - ), ( - 'fontAscent', - 'return Py_BuildValue("h", (*self->ob_itself)->fontAscent);', - None, - 'Ascent of a line' - ), ( - "selPoint", - 'return Py_BuildValue("O&", PyMac_BuildPoint, (*self->ob_itself)->selPoint);', - None, - 'Selection Point' - ), ( - 'selStart', - 'return Py_BuildValue("h", (*self->ob_itself)->selStart);', - None, - 'Start of selection' - ), ( - 'selEnd', - 'return Py_BuildValue("h", (*self->ob_itself)->selEnd);', - None, - 'End of selection' - ), ( - 'active', - 'return Py_BuildValue("h", (*self->ob_itself)->active);', - None, - 'TBD' - ), ( - 'just', - 'return Py_BuildValue("h", (*self->ob_itself)->just);', - None, - 'Justification' - ), ( - 'teLength', - 'return Py_BuildValue("h", (*self->ob_itself)->teLength);', - None, - 'TBD' - ), ( - 'txFont', - 'return Py_BuildValue("h", (*self->ob_itself)->txFont);', - None, - 'Current font' - ), ( - 'txFace', - 'return Py_BuildValue("h", (*self->ob_itself)->txFace);', - None, - 'Current font variant' - ), ( - 'txMode', - 'return Py_BuildValue("h", (*self->ob_itself)->txMode);', - None, - 'Current text-drawing mode' - ), ( - 'txSize', - 'return Py_BuildValue("h", (*self->ob_itself)->txSize);', - None, - 'Current font size' - ), ( - 'nLines', - 'return Py_BuildValue("h", (*self->ob_itself)->nLines);', - None, - 'TBD' - )] - - def outputCheckNewArg(self): - Output("""if (itself == NULL) { - PyErr_SetString(TE_Error,"Cannot create null TE"); - return NULL; - }""") - def outputFreeIt(self, itselfname): - Output("TEDispose(%s);", itselfname) - + # XXXX Could be subtype of Resource + # Attributes that can be set. + getsetlist = [ + ( + 'destRect', + 'return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->destRect);', + None, + 'Destination rectangle' + ), ( + 'viewRect', + 'return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->viewRect);', + None, + 'Viewing rectangle' + ), ( + 'selRect', + 'return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->selRect);', + None, + 'Selection rectangle' + ), ( + 'lineHeight', + 'return Py_BuildValue("h", (*self->ob_itself)->lineHeight);', + None, + 'Height of a line' + ), ( + 'fontAscent', + 'return Py_BuildValue("h", (*self->ob_itself)->fontAscent);', + None, + 'Ascent of a line' + ), ( + "selPoint", + 'return Py_BuildValue("O&", PyMac_BuildPoint, (*self->ob_itself)->selPoint);', + None, + 'Selection Point' + ), ( + 'selStart', + 'return Py_BuildValue("h", (*self->ob_itself)->selStart);', + None, + 'Start of selection' + ), ( + 'selEnd', + 'return Py_BuildValue("h", (*self->ob_itself)->selEnd);', + None, + 'End of selection' + ), ( + 'active', + 'return Py_BuildValue("h", (*self->ob_itself)->active);', + None, + 'TBD' + ), ( + 'just', + 'return Py_BuildValue("h", (*self->ob_itself)->just);', + None, + 'Justification' + ), ( + 'teLength', + 'return Py_BuildValue("h", (*self->ob_itself)->teLength);', + None, + 'TBD' + ), ( + 'txFont', + 'return Py_BuildValue("h", (*self->ob_itself)->txFont);', + None, + 'Current font' + ), ( + 'txFace', + 'return Py_BuildValue("h", (*self->ob_itself)->txFace);', + None, + 'Current font variant' + ), ( + 'txMode', + 'return Py_BuildValue("h", (*self->ob_itself)->txMode);', + None, + 'Current text-drawing mode' + ), ( + 'txSize', + 'return Py_BuildValue("h", (*self->ob_itself)->txSize);', + None, + 'Current font size' + ), ( + 'nLines', + 'return Py_BuildValue("h", (*self->ob_itself)->nLines);', + None, + 'TBD' + )] + + def outputCheckNewArg(self): + Output("""if (itself == NULL) { + PyErr_SetString(TE_Error,"Cannot create null TE"); + return NULL; + }""") + def outputFreeIt(self, itselfname): + Output("TEDispose(%s);", itselfname) + # From here on it's basically all boiler plate... @@ -214,4 +214,3 @@ for f in methods: object.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/waste/wastescan.py b/Mac/Modules/waste/wastescan.py index 8298f26..b5a2b43 100644 --- a/Mac/Modules/waste/wastescan.py +++ b/Mac/Modules/waste/wastescan.py @@ -7,9 +7,9 @@ sys.path.append(BGENDIR) from scantools import Scanner WASTEDIR='/Users/jack/src/waste/C_C++ Headers/' - + if not os.path.exists(WASTEDIR): - raise 'Error: not found: %s', WASTEDIR + raise 'Error: not found: %s', WASTEDIR OBJECT = "TEHandle" SHORT = "waste" @@ -17,136 +17,136 @@ OBJECT = "WEReference" OBJECT2 = "WEObjectReference" def main(): - input = WASTEDIR + "WASTE.h" - output = SHORT + "gen.py" - defsoutput = os.path.join(os.path.split(TOOLBOXDIR)[0], "WASTEconst.py") - scanner = MyScanner(input, output, defsoutput) - scanner.scan() -## scanner.gentypetest(SHORT+"typetest.py") - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - exec "import " + SHORT + "support" - print "=== Done. It's up to you to compile it now! ===" + input = WASTEDIR + "WASTE.h" + output = SHORT + "gen.py" + defsoutput = os.path.join(os.path.split(TOOLBOXDIR)[0], "WASTEconst.py") + scanner = MyScanner(input, output, defsoutput) + scanner.scan() +## scanner.gentypetest(SHORT+"typetest.py") + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + exec "import " + SHORT + "support" + print "=== Done. It's up to you to compile it now! ===" #class MyScanner(Scanner_PreUH3): class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[-1] - # This is non-functional today - if t == OBJECT and m == "InMode": - classname = "Method" - listname = "methods" - else: - t, n, m = arglist[0] - if t == OBJECT2 and m == "InMode": - classname = "Method2" - listname = "methods2" - return classname, listname - - def writeinitialdefs(self): - self.defsfile.write("kPascalStackBased = None # workaround for header parsing\n") - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - - def makeblacklistnames(self): - return [ - "WEDispose", - "WESetInfo", # Argument type unknown... - "WEGetInfo", - "WEVersion", # Unfortunately... - "WEPut", # XXXX TBD: needs array of flavortypes. - "WEGetOneAttribute", # XXXX TBD: output buffer - # Incompatible constant definitions - "weDoAutoScroll", - "weDoOutlineHilite", - "weDoReadOnly", - "weDoUndo", - "weDoIntCutAndPaste", - "weDoDragAndDrop", - "weDoInhibitRecal", - "weDoUseTempMem", - "weDoDrawOffscreen", - "weDoInhibitRedraw", - "weDoMonoStyled", - "weDoMultipleUndo", - "weDoNoKeyboardSync", - "weDoInhibitICSupport", - "weDoInhibitColor", - ] - - def makeblacklisttypes(self): - return [ - "DragReference", # For now... - "UniversalProcPtr", - "WEFontIDToNameUPP", - "WEFontNameToIDUPP", - "WEClickLoopUPP", - "WEScrollUPP", - "WETSMPreUpdateUPP", - "WETSMPostUpdateUPP", - "WEPreTrackDragUPP", - "WETranslateDragUPP", - "WEHiliteDropAreaUPP", - "WEDrawTextUPP", - "WEDrawTSMHiliteUPP", - "WEPixelToCharUPP", - "WECharToPixelUPP", - "WELineBreakUPP", - "WEWordBreakUPP", - "WECharByteUPP", - "WECharTypeUPP", - "WEEraseUPP", - "WEFluxUPP", - "WENewObjectUPP", - "WEDisposeObjectUPP", - "WEDrawObjectUPP", - "WEClickObjectUPP", - "WEStreamObjectUPP", - "WEHoverObjectUPP", - "WERuler", # XXXX To be done - "WERuler_ptr", # ditto - "WEParaInfo", # XXXX To be done - "WEPrintSession", # XXXX To be done - "WEPrintOptions_ptr", # XXXX To be done - ] - - def makerepairinstructions(self): - return [ - ([("void_ptr", "*", "InMode"), ("SInt32", "*", "InMode")], - [("InBuffer", "*", "*")]), - - # WEContinuousStyle - ([("WEStyleMode", "ioMode", "OutMode"), ("TextStyle", "outTextStyle", "OutMode")], - [("WEStyleMode", "*", "InOutMode"), ("TextStyle", "*", "*")]), - - # WECopyRange - ([('Handle', 'outText', 'InMode'), ('StScrpHandle', 'outStyles', 'InMode'), - ('WESoupHandle', 'outSoup', 'InMode')], - [('OptHandle', '*', '*'), ('OptStScrpHandle', '*', '*'), - ('OptSoupHandle', '*', '*')]), - - # WEInsert - ([('StScrpHandle', 'inStyles', 'InMode'), ('WESoupHandle', 'inSoup', 'InMode')], - [('OptStScrpHandle', '*', '*'), ('OptSoupHandle', '*', '*')]), - - # WEGetObjectOwner - ("WEGetObjectOwner", - [('WEReference', '*', 'ReturnMode')], - [('ExistingWEReference', '*', 'ReturnMode')]), - - # WEFindParagraph - ([("char_ptr", "inKey", "InMode")], - [("stringptr", "*", "*")]), - - # WESetOneAttribute - ([("void_ptr", "*", "InMode"), ("ByteCount", "*", "InMode")], - [("InBuffer", "*", "*")]), - ] - + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[-1] + # This is non-functional today + if t == OBJECT and m == "InMode": + classname = "Method" + listname = "methods" + else: + t, n, m = arglist[0] + if t == OBJECT2 and m == "InMode": + classname = "Method2" + listname = "methods2" + return classname, listname + + def writeinitialdefs(self): + self.defsfile.write("kPascalStackBased = None # workaround for header parsing\n") + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + + def makeblacklistnames(self): + return [ + "WEDispose", + "WESetInfo", # Argument type unknown... + "WEGetInfo", + "WEVersion", # Unfortunately... + "WEPut", # XXXX TBD: needs array of flavortypes. + "WEGetOneAttribute", # XXXX TBD: output buffer + # Incompatible constant definitions + "weDoAutoScroll", + "weDoOutlineHilite", + "weDoReadOnly", + "weDoUndo", + "weDoIntCutAndPaste", + "weDoDragAndDrop", + "weDoInhibitRecal", + "weDoUseTempMem", + "weDoDrawOffscreen", + "weDoInhibitRedraw", + "weDoMonoStyled", + "weDoMultipleUndo", + "weDoNoKeyboardSync", + "weDoInhibitICSupport", + "weDoInhibitColor", + ] + + def makeblacklisttypes(self): + return [ + "DragReference", # For now... + "UniversalProcPtr", + "WEFontIDToNameUPP", + "WEFontNameToIDUPP", + "WEClickLoopUPP", + "WEScrollUPP", + "WETSMPreUpdateUPP", + "WETSMPostUpdateUPP", + "WEPreTrackDragUPP", + "WETranslateDragUPP", + "WEHiliteDropAreaUPP", + "WEDrawTextUPP", + "WEDrawTSMHiliteUPP", + "WEPixelToCharUPP", + "WECharToPixelUPP", + "WELineBreakUPP", + "WEWordBreakUPP", + "WECharByteUPP", + "WECharTypeUPP", + "WEEraseUPP", + "WEFluxUPP", + "WENewObjectUPP", + "WEDisposeObjectUPP", + "WEDrawObjectUPP", + "WEClickObjectUPP", + "WEStreamObjectUPP", + "WEHoverObjectUPP", + "WERuler", # XXXX To be done + "WERuler_ptr", # ditto + "WEParaInfo", # XXXX To be done + "WEPrintSession", # XXXX To be done + "WEPrintOptions_ptr", # XXXX To be done + ] + + def makerepairinstructions(self): + return [ + ([("void_ptr", "*", "InMode"), ("SInt32", "*", "InMode")], + [("InBuffer", "*", "*")]), + + # WEContinuousStyle + ([("WEStyleMode", "ioMode", "OutMode"), ("TextStyle", "outTextStyle", "OutMode")], + [("WEStyleMode", "*", "InOutMode"), ("TextStyle", "*", "*")]), + + # WECopyRange + ([('Handle', 'outText', 'InMode'), ('StScrpHandle', 'outStyles', 'InMode'), + ('WESoupHandle', 'outSoup', 'InMode')], + [('OptHandle', '*', '*'), ('OptStScrpHandle', '*', '*'), + ('OptSoupHandle', '*', '*')]), + + # WEInsert + ([('StScrpHandle', 'inStyles', 'InMode'), ('WESoupHandle', 'inSoup', 'InMode')], + [('OptStScrpHandle', '*', '*'), ('OptSoupHandle', '*', '*')]), + + # WEGetObjectOwner + ("WEGetObjectOwner", + [('WEReference', '*', 'ReturnMode')], + [('ExistingWEReference', '*', 'ReturnMode')]), + + # WEFindParagraph + ([("char_ptr", "inKey", "InMode")], + [("stringptr", "*", "*")]), + + # WESetOneAttribute + ([("void_ptr", "*", "InMode"), ("ByteCount", "*", "InMode")], + [("InBuffer", "*", "*")]), + ] + if __name__ == "__main__": - main() + main() diff --git a/Mac/Modules/waste/wastesupport.py b/Mac/Modules/waste/wastesupport.py index c669fa1..13ddc40 100644 --- a/Mac/Modules/waste/wastesupport.py +++ b/Mac/Modules/waste/wastesupport.py @@ -6,18 +6,18 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'WASTE.h' # The Apple header file -MODNAME = 'waste' # The name of the module -OBJECTNAME = 'waste' # The basic name of the objects used here -KIND = 'Ptr' # Usually 'Ptr' or 'Handle' +MACHEADERFILE = 'WASTE.h' # The Apple header file +MODNAME = 'waste' # The name of the module +OBJECTNAME = 'waste' # The basic name of the objects used here +KIND = 'Ptr' # Usually 'Ptr' or 'Handle' # The following is *usually* unchanged but may still require tuning -MODPREFIX = MODNAME # The prefix for module-wide routines -OBJECTTYPE = "WEReference" # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = MODNAME # The prefix for module-wide routines +OBJECTTYPE = "WEReference" # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = 'wastegen.py' # The file generated by the scanner -TYPETESTFILE = 'wastetypetest.py' # Another file generated by the scanner -OUTPUTFILE = "wastemodule.c" # The file generated by this program +TYPETESTFILE = 'wastetypetest.py' # Another file generated by the scanner +OUTPUTFILE = "wastemodule.c" # The file generated by this program from macsupport import * @@ -83,21 +83,21 @@ static PyObject * TextStyle_New(TextStylePtr itself) { - return Py_BuildValue("lllO&", (long)itself->tsFont, (long)itself->tsFace, (long)itself->tsSize, QdRGB_New, - &itself->tsColor); + return Py_BuildValue("lllO&", (long)itself->tsFont, (long)itself->tsFace, (long)itself->tsSize, QdRGB_New, + &itself->tsColor); } static int TextStyle_Convert(PyObject *v, TextStylePtr p_itself) { - long font, face, size; - - if( !PyArg_ParseTuple(v, "lllO&", &font, &face, &size, QdRGB_Convert, &p_itself->tsColor) ) - return 0; - p_itself->tsFont = (short)font; - p_itself->tsFace = (Style)face; - p_itself->tsSize = (short)size; - return 1; + long font, face, size; + + if( !PyArg_ParseTuple(v, "lllO&", &font, &face, &size, QdRGB_Convert, &p_itself->tsColor) ) + return 0; + p_itself->tsFont = (short)font; + p_itself->tsFace = (Style)face; + p_itself->tsSize = (short)size; + return 1; } /* @@ -107,33 +107,33 @@ static PyObject * RunInfo_New(WERunInfo *itself) { - return Py_BuildValue("llhhO&O&", itself->runStart, itself->runEnd, itself->runHeight, - itself->runAscent, TextStyle_New, &itself->runStyle, WEOObj_New, itself->runObject); + return Py_BuildValue("llhhO&O&", itself->runStart, itself->runEnd, itself->runHeight, + itself->runAscent, TextStyle_New, &itself->runStyle, WEOObj_New, itself->runObject); } /* Conversion of long points and rects */ int LongRect_Convert(PyObject *v, LongRect *r) { - return PyArg_Parse(v, "(llll)", &r->left, &r->top, &r->right, &r->bottom); + return PyArg_Parse(v, "(llll)", &r->left, &r->top, &r->right, &r->bottom); } PyObject * LongRect_New(LongRect *r) { - return Py_BuildValue("(llll)", r->left, r->top, r->right, r->bottom); + return Py_BuildValue("(llll)", r->left, r->top, r->right, r->bottom); } int LongPt_Convert(PyObject *v, LongPt *p) { - return PyArg_Parse(v, "(ll)", &p->h, &p->v); + return PyArg_Parse(v, "(ll)", &p->h, &p->v); } PyObject * LongPt_New(LongPt *p) { - return Py_BuildValue("(ll)", p->h, p->v); + return Py_BuildValue("(ll)", p->h, p->v); } /* Stuff for the callbacks: */ @@ -146,110 +146,110 @@ WEClickObjectUPP upp_click_handler; static OSErr any_handler(WESelector what, WEObjectReference who, PyObject *args, PyObject **rv) { - FlavorType tp; - PyObject *key, *func; - - if ( args == NULL ) return errAECorruptData; - - tp = WEGetObjectType(who); - - if( (key=Py_BuildValue("O&O&", PyMac_BuildOSType, tp, PyMac_BuildOSType, what)) == NULL) - return errAECorruptData; - if( (func = PyDict_GetItem(callbackdict, key)) == NULL ) { - Py_DECREF(key); - return errAEHandlerNotFound; - } - Py_INCREF(func); - *rv = PyEval_CallObject(func, args); - Py_DECREF(func); - Py_DECREF(key); - if ( *rv == NULL ) { - PySys_WriteStderr("--Exception in callback: "); - PyErr_Print(); - return errAEReplyNotArrived; - } - return 0; + FlavorType tp; + PyObject *key, *func; + + if ( args == NULL ) return errAECorruptData; + + tp = WEGetObjectType(who); + + if( (key=Py_BuildValue("O&O&", PyMac_BuildOSType, tp, PyMac_BuildOSType, what)) == NULL) + return errAECorruptData; + if( (func = PyDict_GetItem(callbackdict, key)) == NULL ) { + Py_DECREF(key); + return errAEHandlerNotFound; + } + Py_INCREF(func); + *rv = PyEval_CallObject(func, args); + Py_DECREF(func); + Py_DECREF(key); + if ( *rv == NULL ) { + PySys_WriteStderr("--Exception in callback: "); + PyErr_Print(); + return errAEReplyNotArrived; + } + return 0; } static pascal OSErr my_new_handler(Point *objectSize, WEObjectReference objref) { - PyObject *args=NULL, *rv=NULL; - OSErr err; - - args=Py_BuildValue("(O&)", WEOObj_New, objref); - err = any_handler(weNewHandler, objref, args, &rv); - if (!err) { - if (!PyMac_GetPoint(rv, objectSize) ) - err = errAECoercionFail; - } - if ( args ) { - Py_DECREF(args); - } - if ( rv ) { - Py_DECREF(rv); - } - return err; + PyObject *args=NULL, *rv=NULL; + OSErr err; + + args=Py_BuildValue("(O&)", WEOObj_New, objref); + err = any_handler(weNewHandler, objref, args, &rv); + if (!err) { + if (!PyMac_GetPoint(rv, objectSize) ) + err = errAECoercionFail; + } + if ( args ) { + Py_DECREF(args); + } + if ( rv ) { + Py_DECREF(rv); + } + return err; } static pascal OSErr my_dispose_handler(WEObjectReference objref) { - PyObject *args=NULL, *rv=NULL; - OSErr err; - - args=Py_BuildValue("(O&)", WEOObj_New, objref); - err = any_handler(weDisposeHandler, objref, args, &rv); - if ( args ) { - Py_DECREF(args); - } - if ( rv ) { - Py_DECREF(rv); - } - return err; + PyObject *args=NULL, *rv=NULL; + OSErr err; + + args=Py_BuildValue("(O&)", WEOObj_New, objref); + err = any_handler(weDisposeHandler, objref, args, &rv); + if ( args ) { + Py_DECREF(args); + } + if ( rv ) { + Py_DECREF(rv); + } + return err; } static pascal OSErr my_draw_handler(const Rect *destRect, WEObjectReference objref) { - PyObject *args=NULL, *rv=NULL; - OSErr err; - - args=Py_BuildValue("O&O&", PyMac_BuildRect, destRect, WEOObj_New, objref); - err = any_handler(weDrawHandler, objref, args, &rv); - if ( args ) { - Py_DECREF(args); - } - if ( rv ) { - Py_DECREF(rv); - } - return err; + PyObject *args=NULL, *rv=NULL; + OSErr err; + + args=Py_BuildValue("O&O&", PyMac_BuildRect, destRect, WEOObj_New, objref); + err = any_handler(weDrawHandler, objref, args, &rv); + if ( args ) { + Py_DECREF(args); + } + if ( rv ) { + Py_DECREF(rv); + } + return err; } static pascal Boolean my_click_handler(Point hitPt, EventModifiers modifiers, - unsigned long clickTime, WEObjectReference objref) + unsigned long clickTime, WEObjectReference objref) { - PyObject *args=NULL, *rv=NULL; - int retvalue; - OSErr err; - - args=Py_BuildValue("O&llO&", PyMac_BuildPoint, hitPt, - (long)modifiers, (long)clickTime, WEOObj_New, objref); - err = any_handler(weClickHandler, objref, args, &rv); - if (!err) - retvalue = PyInt_AsLong(rv); - else - retvalue = 0; - if ( args ) { - Py_DECREF(args); - } - if ( rv ) { - Py_DECREF(rv); - } - return retvalue; + PyObject *args=NULL, *rv=NULL; + int retvalue; + OSErr err; + + args=Py_BuildValue("O&llO&", PyMac_BuildPoint, hitPt, + (long)modifiers, (long)clickTime, WEOObj_New, objref); + err = any_handler(weClickHandler, objref, args, &rv); + if (!err) + retvalue = PyInt_AsLong(rv); + else + retvalue = 0; + if ( args ) { + Py_DECREF(args); + } + if ( rv ) { + Py_DECREF(rv); + } + return retvalue; } - + """ finalstuff = finalstuff + """ @@ -257,62 +257,62 @@ finalstuff = finalstuff + """ PyObject * ExistingwasteObj_New(w) - WEReference w; + WEReference w; { - PyObject *it = NULL; - - if (w == NULL) - it = NULL; - else - WEGetInfo(weRefCon, (void *)&it, w); - if (it == NULL || ((wasteObject *)it)->ob_itself != w) - it = Py_None; - Py_INCREF(it); - return it; + PyObject *it = NULL; + + if (w == NULL) + it = NULL; + else + WEGetInfo(weRefCon, (void *)&it, w); + if (it == NULL || ((wasteObject *)it)->ob_itself != w) + it = Py_None; + Py_INCREF(it); + return it; } """ class WEMethodGenerator(OSErrMethodGenerator): - """Similar to MethodGenerator, but has self as last argument""" + """Similar to MethodGenerator, but has self as last argument""" - def parseArgumentList(self, args): - args, a0 = args[:-1], args[-1] - t0, n0, m0 = a0 - if m0 != InMode: - raise ValueError, "method's 'self' must be 'InMode'" - self.itself = Variable(t0, "_self->ob_itself", SelfMode) - FunctionGenerator.parseArgumentList(self, args) - self.argumentList.append(self.itself) + def parseArgumentList(self, args): + args, a0 = args[:-1], args[-1] + t0, n0, m0 = a0 + if m0 != InMode: + raise ValueError, "method's 'self' must be 'InMode'" + self.itself = Variable(t0, "_self->ob_itself", SelfMode) + FunctionGenerator.parseArgumentList(self, args) + self.argumentList.append(self.itself) class WEObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("""if (itself == NULL) { - PyErr_SetString(waste_Error,"Cannot create null WE"); - return NULL; - }""") - def outputInitStructMembers(self): - GlobalObjectDefinition.outputInitStructMembers(self) - Output("WESetInfo(weRefCon, (void *)&it, itself);") - def outputFreeIt(self, itselfname): - Output("WEDispose(%s);", itselfname) - + def outputCheckNewArg(self): + Output("""if (itself == NULL) { + PyErr_SetString(waste_Error,"Cannot create null WE"); + return NULL; + }""") + def outputInitStructMembers(self): + GlobalObjectDefinition.outputInitStructMembers(self) + Output("WESetInfo(weRefCon, (void *)&it, itself);") + def outputFreeIt(self, itselfname): + Output("WEDispose(%s);", itselfname) + class WEOObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("""if (itself == NULL) { - Py_INCREF(Py_None); - return Py_None; - }""") - + def outputCheckNewArg(self): + Output("""if (itself == NULL) { + Py_INCREF(Py_None); + return Py_None; + }""") + variablestuff = """ - callbackdict = PyDict_New(); - if (callbackdict == NULL || PyDict_SetItemString(d, "callbacks", callbackdict) != 0) - return; - upp_new_handler = NewWENewObjectProc(my_new_handler); - upp_dispose_handler = NewWEDisposeObjectProc(my_dispose_handler); - upp_draw_handler = NewWEDrawObjectProc(my_draw_handler); - upp_click_handler = NewWEClickObjectProc(my_click_handler); + callbackdict = PyDict_New(); + if (callbackdict == NULL || PyDict_SetItemString(d, "callbacks", callbackdict) != 0) + return; + upp_new_handler = NewWENewObjectProc(my_new_handler); + upp_dispose_handler = NewWEDisposeObjectProc(my_dispose_handler); + upp_draw_handler = NewWEDrawObjectProc(my_draw_handler); + upp_click_handler = NewWEClickObjectProc(my_click_handler); """ @@ -341,78 +341,78 @@ execfile(INPUTFILE) # A function written by hand: stdhandlers_body = """ - OSErr err; - // install the sample object handlers for pictures and sounds -#define kTypePicture 'PICT' -#define kTypeSound 'snd ' - - if ( !PyArg_ParseTuple(_args, "") ) return NULL; - - if ((err = WEInstallObjectHandler(kTypePicture, weNewHandler, - (UniversalProcPtr) NewWENewObjectProc(HandleNewPicture), NULL)) != noErr) - goto cleanup; - - if ((err = WEInstallObjectHandler(kTypePicture, weDisposeHandler, - (UniversalProcPtr) NewWEDisposeObjectProc(HandleDisposePicture), NULL)) != noErr) - goto cleanup; - - if ((err = WEInstallObjectHandler(kTypePicture, weDrawHandler, - (UniversalProcPtr) NewWEDrawObjectProc(HandleDrawPicture), NULL)) != noErr) - goto cleanup; - - if ((err = WEInstallObjectHandler(kTypeSound, weNewHandler, - (UniversalProcPtr) NewWENewObjectProc(HandleNewSound), NULL)) != noErr) - goto cleanup; - - if ((err = WEInstallObjectHandler(kTypeSound, weDrawHandler, - (UniversalProcPtr) NewWEDrawObjectProc(HandleDrawSound), NULL)) != noErr) - goto cleanup; - - if ((err = WEInstallObjectHandler(kTypeSound, weClickHandler, - (UniversalProcPtr) NewWEClickObjectProc(HandleClickSound), NULL)) != noErr) - goto cleanup; - Py_INCREF(Py_None); - _res = Py_None; - return _res; - + OSErr err; + // install the sample object handlers for pictures and sounds +#define kTypePicture 'PICT' +#define kTypeSound 'snd ' + + if ( !PyArg_ParseTuple(_args, "") ) return NULL; + + if ((err = WEInstallObjectHandler(kTypePicture, weNewHandler, + (UniversalProcPtr) NewWENewObjectProc(HandleNewPicture), NULL)) != noErr) + goto cleanup; + + if ((err = WEInstallObjectHandler(kTypePicture, weDisposeHandler, + (UniversalProcPtr) NewWEDisposeObjectProc(HandleDisposePicture), NULL)) != noErr) + goto cleanup; + + if ((err = WEInstallObjectHandler(kTypePicture, weDrawHandler, + (UniversalProcPtr) NewWEDrawObjectProc(HandleDrawPicture), NULL)) != noErr) + goto cleanup; + + if ((err = WEInstallObjectHandler(kTypeSound, weNewHandler, + (UniversalProcPtr) NewWENewObjectProc(HandleNewSound), NULL)) != noErr) + goto cleanup; + + if ((err = WEInstallObjectHandler(kTypeSound, weDrawHandler, + (UniversalProcPtr) NewWEDrawObjectProc(HandleDrawSound), NULL)) != noErr) + goto cleanup; + + if ((err = WEInstallObjectHandler(kTypeSound, weClickHandler, + (UniversalProcPtr) NewWEClickObjectProc(HandleClickSound), NULL)) != noErr) + goto cleanup; + Py_INCREF(Py_None); + _res = Py_None; + return _res; + cleanup: - return PyMac_Error(err); + return PyMac_Error(err); """ inshandler_body = """ - OSErr err; - FlavorType objectType; - WESelector selector; - PyObject *py_handler; - UniversalProcPtr handler; - WEReference we = NULL; - PyObject *key; - - - if ( !PyArg_ParseTuple(_args, "O&O&O|O&", - PyMac_GetOSType, &objectType, - PyMac_GetOSType, &selector, - &py_handler, - WEOObj_Convert, &we) ) return NULL; - - if ( selector == weNewHandler ) handler = (UniversalProcPtr)upp_new_handler; - else if ( selector == weDisposeHandler ) handler = (UniversalProcPtr)upp_dispose_handler; - else if ( selector == weDrawHandler ) handler = (UniversalProcPtr)upp_draw_handler; - else if ( selector == weClickHandler ) handler = (UniversalProcPtr)upp_click_handler; - else return PyMac_Error(weUndefinedSelectorErr); - - if ((key = Py_BuildValue("O&O&", - PyMac_BuildOSType, objectType, - PyMac_BuildOSType, selector)) == NULL ) - return NULL; - - PyDict_SetItem(callbackdict, key, py_handler); - - err = WEInstallObjectHandler(objectType, selector, handler, we); - if ( err ) return PyMac_Error(err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; + OSErr err; + FlavorType objectType; + WESelector selector; + PyObject *py_handler; + UniversalProcPtr handler; + WEReference we = NULL; + PyObject *key; + + + if ( !PyArg_ParseTuple(_args, "O&O&O|O&", + PyMac_GetOSType, &objectType, + PyMac_GetOSType, &selector, + &py_handler, + WEOObj_Convert, &we) ) return NULL; + + if ( selector == weNewHandler ) handler = (UniversalProcPtr)upp_new_handler; + else if ( selector == weDisposeHandler ) handler = (UniversalProcPtr)upp_dispose_handler; + else if ( selector == weDrawHandler ) handler = (UniversalProcPtr)upp_draw_handler; + else if ( selector == weClickHandler ) handler = (UniversalProcPtr)upp_click_handler; + else return PyMac_Error(weUndefinedSelectorErr); + + if ((key = Py_BuildValue("O&O&", + PyMac_BuildOSType, objectType, + PyMac_BuildOSType, selector)) == NULL ) + return NULL; + + PyDict_SetItem(callbackdict, key, py_handler); + + err = WEInstallObjectHandler(objectType, selector, handler, we); + if ( err ) return PyMac_Error(err); + Py_INCREF(Py_None); + _res = Py_None; + return _res; """ stdhand = ManualGenerator("STDObjectHandlers", stdhandlers_body) @@ -442,4 +442,3 @@ for f in methods2: object2.add(f) # generate output (open the output file as late as possible) SetOutputFileName(OUTPUTFILE) module.generate() - diff --git a/Mac/Modules/win/winedit.py b/Mac/Modules/win/winedit.py index d79356f..01cfe86 100644 --- a/Mac/Modules/win/winedit.py +++ b/Mac/Modules/win/winedit.py @@ -7,25 +7,25 @@ f = Method(Boolean, 'IsWindowVisible', methods.append(f) f = Method(void, 'GetWindowStructureRgn', - (WindowRef, 'theWindow', InMode), - (RgnHandle, 'r', InMode), + (WindowRef, 'theWindow', InMode), + (RgnHandle, 'r', InMode), ) methods.append(f) f = Method(void, 'GetWindowContentRgn', - (WindowRef, 'theWindow', InMode), - (RgnHandle, 'r', InMode), + (WindowRef, 'theWindow', InMode), + (RgnHandle, 'r', InMode), ) methods.append(f) f = Method(void, 'GetWindowUpdateRgn', - (WindowRef, 'theWindow', InMode), - (RgnHandle, 'r', InMode), + (WindowRef, 'theWindow', InMode), + (RgnHandle, 'r', InMode), ) methods.append(f) f = Method(ExistingWindowPtr, 'GetNextWindow', - (WindowRef, 'theWindow', InMode), + (WindowRef, 'theWindow', InMode), ) methods.append(f) @@ -54,18 +54,16 @@ methods.append(f) AutoDispose_body = """ int onoff, old = 0; if (!PyArg_ParseTuple(_args, "i", &onoff)) - return NULL; + return NULL; if ( _self->ob_freeit ) - old = 1; + old = 1; if ( onoff ) - _self->ob_freeit = PyMac_AutoDisposeWindow; + _self->ob_freeit = PyMac_AutoDisposeWindow; else - _self->ob_freeit = NULL; + _self->ob_freeit = NULL; _res = Py_BuildValue("i", old); return _res; """ f = ManualGenerator("AutoDispose", AutoDispose_body) f.docstring = lambda: "(int)->int. Automatically DisposeHandle the object on Python object cleanup" methods.append(f) - - diff --git a/Mac/Modules/win/winscan.py b/Mac/Modules/win/winscan.py index 6b08c00..f78935d 100644 --- a/Mac/Modules/win/winscan.py +++ b/Mac/Modules/win/winscan.py @@ -7,125 +7,124 @@ sys.path.append(BGENDIR) from scantools import Scanner def main(): - input = "MacWindows.h" - output = "wingen.py" - defsoutput = TOOLBOXDIR + "Windows.py" - scanner = MyScanner(input, output, defsoutput) - scanner.scan() - scanner.close() - print "=== Testing definitions output code ===" - execfile(defsoutput, {}, {}) - print "=== Done scanning and generating, now importing the generated code... ===" - import winsupport - print "=== Done. It's up to you to compile it now! ===" + input = "MacWindows.h" + output = "wingen.py" + defsoutput = TOOLBOXDIR + "Windows.py" + scanner = MyScanner(input, output, defsoutput) + scanner.scan() + scanner.close() + print "=== Testing definitions output code ===" + execfile(defsoutput, {}, {}) + print "=== Done scanning and generating, now importing the generated code... ===" + import winsupport + print "=== Done. It's up to you to compile it now! ===" class MyScanner(Scanner): - def destination(self, type, name, arglist): - classname = "Function" - listname = "functions" - if arglist: - t, n, m = arglist[0] - if t in ("WindowPtr", "WindowPeek", "WindowRef") and m == "InMode": - classname = "Method" - listname = "methods" - return classname, listname - - def writeinitialdefs(self): - self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") - self.defsfile.write("false = 0\n") - self.defsfile.write("true = 1\n") - self.defsfile.write("kWindowNoConstrainAttribute = 0x80000000\n") - - def makeblacklistnames(self): - return [ - 'DisposeWindow', # Implied when the object is deleted - 'CloseWindow', - 'SetWindowProperty', # For the moment - 'GetWindowProperty', - 'GetWindowPropertySize', - 'RemoveWindowProperty', - 'MacCloseWindow', - 'GetWindowList', # Don't know whether this is safe... - # Constants with funny definitions - 'kMouseUpOutOfSlop', - 'kAllWindowClasses', - 'kWindowNoConstrainAttribute', - # OS8 only: - 'GetAuxWin', - 'GetWindowDataHandle', - 'SaveOld', - 'DrawNew', - 'SetWinColor', - 'SetDeskCPat', - 'InitWindows', - 'InitFloatingWindows', - 'GetWMgrPort', - 'GetCWMgrPort', - 'ValidRgn', # Use versions with Window in their name - 'ValidRect', - 'InvalRgn', - 'InvalRect', - 'IsValidWindowPtr', # I think this is useless for Python, but not sure... - 'GetWindowZoomFlag', # Not available in Carbon - 'GetWindowTitleWidth', # Ditto - 'GetWindowGoAwayFlag', - 'GetWindowSpareFlag', - ] - - def makeblacklisttypes(self): - return [ - 'ProcPtr', - 'DragGrayRgnUPP', - 'WindowPaintUPP', - 'Collection', # For now, to be done later - 'WindowDefSpec', # Too difficult for now - 'WindowDefSpec_ptr', - 'EventRef', #TBD - ] - - def makerepairinstructions(self): - return [ - - # GetWTitle - ([("Str255", "*", "InMode")], - [("*", "*", "OutMode")]), - - ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], - [("InBuffer", "*", "*")]), - - ([("void", "*", "OutMode"), ("long", "*", "InMode"), - ("long", "*", "OutMode")], - [("VarVarOutBuffer", "*", "InOutMode")]), - - ([("void", "wStorage", "OutMode")], - [("NullStorage", "*", "InMode")]), - - # match FindWindowOfClass - ([("WindowRef", "outWindow", "OutMode"), ("WindowPartCode", "outWindowPart", "OutMode")], - [("ExistingWindowPtr", "*", "OutMode"), ("WindowPartCode", "outWindowPart", "OutMode")]), - # then match CreateNewWindow and CreateWindowFromResource - ([("WindowRef", "outWindow", "OutMode")], - [("WindowRef", "*", "*")]), - - ([("WindowPtr", "*", "OutMode")], - [("ExistingWindowPtr", "*", "*")]), - ([("WindowRef", "*", "OutMode")], # Same, but other style headerfiles - [("ExistingWindowPtr", "*", "*")]), - - ([("WindowPtr", "FrontWindow", "ReturnMode")], - [("ExistingWindowPtr", "*", "*")]), - ([("WindowRef", "FrontWindow", "ReturnMode")], # Ditto - [("ExistingWindowPtr", "*", "*")]), - ([("WindowPtr", "FrontNonFloatingWindow", "ReturnMode")], - [("ExistingWindowPtr", "*", "*")]), - ([("WindowRef", "FrontNonFloatingWindow", "ReturnMode")], # Ditto - [("ExistingWindowPtr", "*", "*")]), - - ([("Rect_ptr", "*", "ReturnMode")], # GetWindowXXXState accessors - [("void", "*", "ReturnMode")]), - ] + def destination(self, type, name, arglist): + classname = "Function" + listname = "functions" + if arglist: + t, n, m = arglist[0] + if t in ("WindowPtr", "WindowPeek", "WindowRef") and m == "InMode": + classname = "Method" + listname = "methods" + return classname, listname -if __name__ == "__main__": - main() + def writeinitialdefs(self): + self.defsfile.write("def FOUR_CHAR_CODE(x): return x\n") + self.defsfile.write("false = 0\n") + self.defsfile.write("true = 1\n") + self.defsfile.write("kWindowNoConstrainAttribute = 0x80000000\n") + + def makeblacklistnames(self): + return [ + 'DisposeWindow', # Implied when the object is deleted + 'CloseWindow', + 'SetWindowProperty', # For the moment + 'GetWindowProperty', + 'GetWindowPropertySize', + 'RemoveWindowProperty', + 'MacCloseWindow', + 'GetWindowList', # Don't know whether this is safe... + # Constants with funny definitions + 'kMouseUpOutOfSlop', + 'kAllWindowClasses', + 'kWindowNoConstrainAttribute', + # OS8 only: + 'GetAuxWin', + 'GetWindowDataHandle', + 'SaveOld', + 'DrawNew', + 'SetWinColor', + 'SetDeskCPat', + 'InitWindows', + 'InitFloatingWindows', + 'GetWMgrPort', + 'GetCWMgrPort', + 'ValidRgn', # Use versions with Window in their name + 'ValidRect', + 'InvalRgn', + 'InvalRect', + 'IsValidWindowPtr', # I think this is useless for Python, but not sure... + 'GetWindowZoomFlag', # Not available in Carbon + 'GetWindowTitleWidth', # Ditto + 'GetWindowGoAwayFlag', + 'GetWindowSpareFlag', + ] + + def makeblacklisttypes(self): + return [ + 'ProcPtr', + 'DragGrayRgnUPP', + 'WindowPaintUPP', + 'Collection', # For now, to be done later + 'WindowDefSpec', # Too difficult for now + 'WindowDefSpec_ptr', + 'EventRef', #TBD + ] + + def makerepairinstructions(self): + return [ + + # GetWTitle + ([("Str255", "*", "InMode")], + [("*", "*", "OutMode")]), + + ([("void_ptr", "*", "InMode"), ("long", "*", "InMode")], + [("InBuffer", "*", "*")]), + + ([("void", "*", "OutMode"), ("long", "*", "InMode"), + ("long", "*", "OutMode")], + [("VarVarOutBuffer", "*", "InOutMode")]), + ([("void", "wStorage", "OutMode")], + [("NullStorage", "*", "InMode")]), + + # match FindWindowOfClass + ([("WindowRef", "outWindow", "OutMode"), ("WindowPartCode", "outWindowPart", "OutMode")], + [("ExistingWindowPtr", "*", "OutMode"), ("WindowPartCode", "outWindowPart", "OutMode")]), + # then match CreateNewWindow and CreateWindowFromResource + ([("WindowRef", "outWindow", "OutMode")], + [("WindowRef", "*", "*")]), + + ([("WindowPtr", "*", "OutMode")], + [("ExistingWindowPtr", "*", "*")]), + ([("WindowRef", "*", "OutMode")], # Same, but other style headerfiles + [("ExistingWindowPtr", "*", "*")]), + + ([("WindowPtr", "FrontWindow", "ReturnMode")], + [("ExistingWindowPtr", "*", "*")]), + ([("WindowRef", "FrontWindow", "ReturnMode")], # Ditto + [("ExistingWindowPtr", "*", "*")]), + ([("WindowPtr", "FrontNonFloatingWindow", "ReturnMode")], + [("ExistingWindowPtr", "*", "*")]), + ([("WindowRef", "FrontNonFloatingWindow", "ReturnMode")], # Ditto + [("ExistingWindowPtr", "*", "*")]), + + ([("Rect_ptr", "*", "ReturnMode")], # GetWindowXXXState accessors + [("void", "*", "ReturnMode")]), + ] + +if __name__ == "__main__": + main() diff --git a/Mac/Modules/win/winsupport.py b/Mac/Modules/win/winsupport.py index 640e33a..08a0379 100644 --- a/Mac/Modules/win/winsupport.py +++ b/Mac/Modules/win/winsupport.py @@ -6,17 +6,17 @@ import string # Declarations that change for each manager -MACHEADERFILE = 'Windows.h' # The Apple header file -MODNAME = '_Win' # The name of the module -OBJECTNAME = 'Window' # The basic name of the objects used here +MACHEADERFILE = 'Windows.h' # The Apple header file +MODNAME = '_Win' # The name of the module +OBJECTNAME = 'Window' # The basic name of the objects used here # The following is *usually* unchanged but may still require tuning -MODPREFIX = 'Win' # The prefix for module-wide routines -OBJECTTYPE = OBJECTNAME + 'Ptr' # The C type used to represent them -OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods +MODPREFIX = 'Win' # The prefix for module-wide routines +OBJECTTYPE = OBJECTNAME + 'Ptr' # The C type used to represent them +OBJECTPREFIX = MODPREFIX + 'Obj' # The prefix for object methods INPUTFILE = string.lower(MODPREFIX) + 'gen.py' # The file generated by the scanner EDITFILE = string.lower(MODPREFIX) + 'edit.py' # The manual definitions -OUTPUTFILE = MODNAME + "module.c" # The file generated by this program +OUTPUTFILE = MODNAME + "module.c" # The file generated by this program from macsupport import * @@ -79,7 +79,7 @@ extern int _WinObj_Convert(PyObject *, WindowRef *); static void PyMac_AutoDisposeWindow(WindowPtr w) { - DisposeWindow(w); + DisposeWindow(w); } """ @@ -89,94 +89,94 @@ finalstuff = finalstuff + """ PyObject * WinObj_WhichWindow(WindowPtr w) { - PyObject *it; - - if (w == NULL) { - it = Py_None; - Py_INCREF(it); - } else { - it = (PyObject *) GetWRefCon(w); - if (it == NULL || !IsPointerValid((Ptr)it) || ((WindowObject *)it)->ob_itself != w || !WinObj_Check(it)) { - it = WinObj_New(w); - ((WindowObject *)it)->ob_freeit = NULL; - } else { - Py_INCREF(it); - } - } - return it; + PyObject *it; + + if (w == NULL) { + it = Py_None; + Py_INCREF(it); + } else { + it = (PyObject *) GetWRefCon(w); + if (it == NULL || !IsPointerValid((Ptr)it) || ((WindowObject *)it)->ob_itself != w || !WinObj_Check(it)) { + it = WinObj_New(w); + ((WindowObject *)it)->ob_freeit = NULL; + } else { + Py_INCREF(it); + } + } + return it; } """ initstuff = initstuff + """ - PyMac_INIT_TOOLBOX_OBJECT_NEW(WindowPtr, WinObj_New); - PyMac_INIT_TOOLBOX_OBJECT_NEW(WindowPtr, WinObj_WhichWindow); - PyMac_INIT_TOOLBOX_OBJECT_CONVERT(WindowPtr, WinObj_Convert); + PyMac_INIT_TOOLBOX_OBJECT_NEW(WindowPtr, WinObj_New); + PyMac_INIT_TOOLBOX_OBJECT_NEW(WindowPtr, WinObj_WhichWindow); + PyMac_INIT_TOOLBOX_OBJECT_CONVERT(WindowPtr, WinObj_Convert); """ class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): - def outputCheckNewArg(self): - Output("if (itself == NULL) return PyMac_Error(resNotFound);") - Output("/* XXXX Or should we use WhichWindow code here? */") - def outputStructMembers(self): - GlobalObjectDefinition.outputStructMembers(self) - Output("void (*ob_freeit)(%s ptr);", self.itselftype) - def outputInitStructMembers(self): - GlobalObjectDefinition.outputInitStructMembers(self) - Output("it->ob_freeit = NULL;") - Output("if (GetWRefCon(itself) == 0)") - OutLbrace() - Output("SetWRefCon(itself, (long)it);") - Output("it->ob_freeit = PyMac_AutoDisposeWindow;") - OutRbrace() - def outputCheckConvertArg(self): - Out(""" - if (v == Py_None) { *p_itself = NULL; return 1; } - if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; } - """) - OutLbrace() - Output("DialogRef dlg;") - OutLbrace("if (DlgObj_Convert(v, &dlg) && dlg)") - Output("*p_itself = GetDialogWindow(dlg);") - Output("return 1;") - OutRbrace() - Output("PyErr_Clear();") - OutRbrace() - def outputCleanupStructMembers(self): - Output("if (self->ob_freeit && self->ob_itself)") - OutLbrace() - Output("SetWRefCon(self->ob_itself, 0);") - Output("self->ob_freeit(self->ob_itself);") - OutRbrace() - Output("self->ob_itself = NULL;") - Output("self->ob_freeit = NULL;") - - def outputCompare(self): - Output() - Output("static int %s_compare(%s *self, %s *other)", self.prefix, self.objecttype, self.objecttype) - OutLbrace() - Output("if ( self->ob_itself > other->ob_itself ) return 1;") - Output("if ( self->ob_itself < other->ob_itself ) return -1;") - Output("return 0;") - OutRbrace() - - def outputHash(self): - Output() - Output("static int %s_hash(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("return (int)self->ob_itself;") - OutRbrace() - - def outputRepr(self): - Output() - Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) - OutLbrace() - Output("char buf[100];") - Output("""sprintf(buf, "<Window object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") - Output("return PyString_FromString(buf);") - OutRbrace() - -## def outputFreeIt(self, itselfname): -## Output("DisposeWindow(%s);", itselfname) + def outputCheckNewArg(self): + Output("if (itself == NULL) return PyMac_Error(resNotFound);") + Output("/* XXXX Or should we use WhichWindow code here? */") + def outputStructMembers(self): + GlobalObjectDefinition.outputStructMembers(self) + Output("void (*ob_freeit)(%s ptr);", self.itselftype) + def outputInitStructMembers(self): + GlobalObjectDefinition.outputInitStructMembers(self) + Output("it->ob_freeit = NULL;") + Output("if (GetWRefCon(itself) == 0)") + OutLbrace() + Output("SetWRefCon(itself, (long)it);") + Output("it->ob_freeit = PyMac_AutoDisposeWindow;") + OutRbrace() + def outputCheckConvertArg(self): + Out(""" + if (v == Py_None) { *p_itself = NULL; return 1; } + if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; } + """) + OutLbrace() + Output("DialogRef dlg;") + OutLbrace("if (DlgObj_Convert(v, &dlg) && dlg)") + Output("*p_itself = GetDialogWindow(dlg);") + Output("return 1;") + OutRbrace() + Output("PyErr_Clear();") + OutRbrace() + def outputCleanupStructMembers(self): + Output("if (self->ob_freeit && self->ob_itself)") + OutLbrace() + Output("SetWRefCon(self->ob_itself, 0);") + Output("self->ob_freeit(self->ob_itself);") + OutRbrace() + Output("self->ob_itself = NULL;") + Output("self->ob_freeit = NULL;") + + def outputCompare(self): + Output() + Output("static int %s_compare(%s *self, %s *other)", self.prefix, self.objecttype, self.objecttype) + OutLbrace() + Output("if ( self->ob_itself > other->ob_itself ) return 1;") + Output("if ( self->ob_itself < other->ob_itself ) return -1;") + Output("return 0;") + OutRbrace() + + def outputHash(self): + Output() + Output("static int %s_hash(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("return (int)self->ob_itself;") + OutRbrace() + + def outputRepr(self): + Output() + Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) + OutLbrace() + Output("char buf[100];") + Output("""sprintf(buf, "<Window object at 0x%%8.8x for 0x%%8.8x>", (unsigned)self, (unsigned)self->ob_itself);""") + Output("return PyString_FromString(buf);") + OutRbrace() + +## def outputFreeIt(self, itselfname): +## Output("DisposeWindow(%s);", itselfname) # From here on it's basically all boiler plate... # Create the generator groups and link them @@ -199,7 +199,7 @@ whichwin_body = """ long ptr; if ( !PyArg_ParseTuple(_args, "i", &ptr) ) - return NULL; + return NULL; _res = WinObj_WhichWindow((WindowPtr)ptr); return _res; """ diff --git a/Mac/OSX/Doc/HelpIndexingTool/Standard_Suite.py b/Mac/OSX/Doc/HelpIndexingTool/Standard_Suite.py index e986d75..4f6604c 100644 --- a/Mac/OSX/Doc/HelpIndexingTool/Standard_Suite.py +++ b/Mac/OSX/Doc/HelpIndexingTool/Standard_Suite.py @@ -304,9 +304,9 @@ document._privpropdict = { document._privelemdict = { } _Enum_savo = { - 'yes' : 'yes ', # Save objects now - 'no' : 'no ', # Do not save objects - 'ask' : 'ask ', # Ask the user whether to save + 'yes' : 'yes ', # Save objects now + 'no' : 'no ', # Do not save objects + 'ask' : 'ask ', # Ask the user whether to save } diff --git a/Mac/OSX/Doc/HelpIndexingTool/__init__.py b/Mac/OSX/Doc/HelpIndexingTool/__init__.py index 2745086..5359df5 100644 --- a/Mac/OSX/Doc/HelpIndexingTool/__init__.py +++ b/Mac/OSX/Doc/HelpIndexingTool/__init__.py @@ -76,4 +76,3 @@ class HelpIndexingTool(Standard_Suite_Events, _signature = 'hiti' _moduleName = 'HelpIndexingTool' - diff --git a/Mac/OSX/Doc/setup.py b/Mac/OSX/Doc/setup.py index 58d8df6..ae86b80 100644 --- a/Mac/OSX/Doc/setup.py +++ b/Mac/OSX/Doc/setup.py @@ -29,180 +29,180 @@ import Carbon.File import time class DocBuild(build): - def initialize_options(self): - build.initialize_options(self) - self.build_html = None - self.build_dest = None - self.download = 0 - self.doc_version = '2.3b1' # Only needed if download is true - - def finalize_options(self): - build.finalize_options(self) - if self.build_html is None: - self.build_html = os.path.join(self.build_base, 'html') - if self.build_dest is None: - self.build_dest = os.path.join(self.build_base, 'PythonDocumentation') - - def spawn(self, *args): - spawn(args, 1, self.verbose, self.dry_run) - - def downloadDocs(self): - workdir = os.getcwd() - url = 'http://www.python.org/ftp/python/doc/%s/html-%s.tgz' % \ - (self.doc_version,self.doc_version) - os.chdir(self.build_base) - self.spawn('curl','-O', url) - os.chdir(workdir) - tarfile = 'html-%s.tgz' % self.doc_version + def initialize_options(self): + build.initialize_options(self) + self.build_html = None + self.build_dest = None + self.download = 0 + self.doc_version = '2.3b1' # Only needed if download is true + + def finalize_options(self): + build.finalize_options(self) + if self.build_html is None: + self.build_html = os.path.join(self.build_base, 'html') + if self.build_dest is None: + self.build_dest = os.path.join(self.build_base, 'PythonDocumentation') + + def spawn(self, *args): + spawn(args, 1, self.verbose, self.dry_run) + + def downloadDocs(self): + workdir = os.getcwd() + url = 'http://www.python.org/ftp/python/doc/%s/html-%s.tgz' % \ + (self.doc_version,self.doc_version) + os.chdir(self.build_base) + self.spawn('curl','-O', url) + os.chdir(workdir) + tarfile = 'html-%s.tgz' % self.doc_version ## This no longer works due to name changes -## self.mkpath(self.build_html) -## os.chdir(self.build_html) -## self.spawn('tar', '-xzf', '../' + tarfile) -## os.chdir(workdir) - print "** Please unpack %s" % os.path.join(self.build_base, tarfile) - print "** Unpack the files into %s" % self.build_html - raise RuntimeError, "You need to unpack the docs manually" - - def buildDocsFromSource(self): - srcdir = '../../..' - docdir = os.path.join(srcdir, 'Doc') - htmldir = os.path.join(docdir, 'html') - spawn(('make','--directory', docdir, 'html'), 1, self.verbose, self.dry_run) - self.mkpath(self.build_html) - copy_tree(htmldir, self.build_html) - - def ensureHtml(self): - if not os.path.exists(self.build_html): - if self.download: - self.downloadDocs() - else: - self.buildDocsFromSource() - - def hackIndex(self): - ind_html = 'index.html' - #print 'self.build_dest =', self.build_dest - hackedIndex = file(os.path.join(self.build_dest, ind_html),'w') - origIndex = file(os.path.join(self.build_html,ind_html)) - r = re.compile('<style type="text/css">.*</style>', re.DOTALL) - hackedIndex.write(r.sub('<META NAME="AppleTitle" CONTENT="Python Documentation">',origIndex.read())) - - def hackFile(self,d,f): - origPath = os.path.join(d,f) - assert(origPath[:len(self.build_html)] == self.build_html) - outPath = os.path.join(self.build_dest, d[len(self.build_html)+1:], f) - (name, ext) = os.path.splitext(f) - if os.path.isdir(origPath): - self.mkpath(outPath) - elif ext == '.html': - if self.verbose: print 'hacking %s to %s' % (origPath,outPath) - hackedFile = file(outPath, 'w') - origFile = file(origPath,'r') - hackedFile.write(self.r.sub('<dl><dt><dd>', origFile.read())) - else: - copy_file(origPath, outPath) - - def hackHtml(self): - self.r = re.compile('<dl><dd>') - os.path.walk(self.build_html, self.visit, None) - - def visit(self, dummy, dirname, filenames): - for f in filenames: - self.hackFile(dirname, f) - - def makeHelpIndex(self): - app = '/Developer/Applications/Apple Help Indexing Tool.app' - self.spawn('open', '-a', app , self.build_dest) - print "Please wait until Apple Help Indexing Tool finishes before installing" - - def makeHelpIndex(self): - app = HelpIndexingTool.HelpIndexingTool(start=1) - app.open(Carbon.File.FSSpec(self.build_dest)) - sys.stderr.write("Waiting for Help Indexing Tool to start...") - while 1: - # This is bad design in the suite generation code! - idle = app._get(HelpIndexingTool.Help_Indexing_Tool_Suite._Prop_idleStatus()) - time.sleep(10) - if not idle: break - sys.stderr.write(".") - sys.stderr.write("\n") - sys.stderr.write("Waiting for Help Indexing Tool to finish...") - while 1: - # This is bad design in the suite generation code! - idle = app._get(HelpIndexingTool.Help_Indexing_Tool_Suite._Prop_idleStatus()) - time.sleep(10) - if idle: break - sys.stderr.write(".") - sys.stderr.write("\n") - - - def run(self): - self.ensure_finalized() - self.mkpath(self.build_base) - self.ensureHtml() - if not os.path.isdir(self.build_html): - raise RuntimeError, \ - "Can't find source folder for documentation." - self.mkpath(self.build_dest) - if dep_util.newer(os.path.join(self.build_html,'index.html'), os.path.join(self.build_dest,'index.html')): - self.mkpath(self.build_dest) - self.hackHtml() - self.hackIndex() - self.makeHelpIndex() +## self.mkpath(self.build_html) +## os.chdir(self.build_html) +## self.spawn('tar', '-xzf', '../' + tarfile) +## os.chdir(workdir) + print "** Please unpack %s" % os.path.join(self.build_base, tarfile) + print "** Unpack the files into %s" % self.build_html + raise RuntimeError, "You need to unpack the docs manually" + + def buildDocsFromSource(self): + srcdir = '../../..' + docdir = os.path.join(srcdir, 'Doc') + htmldir = os.path.join(docdir, 'html') + spawn(('make','--directory', docdir, 'html'), 1, self.verbose, self.dry_run) + self.mkpath(self.build_html) + copy_tree(htmldir, self.build_html) + + def ensureHtml(self): + if not os.path.exists(self.build_html): + if self.download: + self.downloadDocs() + else: + self.buildDocsFromSource() + + def hackIndex(self): + ind_html = 'index.html' + #print 'self.build_dest =', self.build_dest + hackedIndex = file(os.path.join(self.build_dest, ind_html),'w') + origIndex = file(os.path.join(self.build_html,ind_html)) + r = re.compile('<style type="text/css">.*</style>', re.DOTALL) + hackedIndex.write(r.sub('<META NAME="AppleTitle" CONTENT="Python Documentation">',origIndex.read())) + + def hackFile(self,d,f): + origPath = os.path.join(d,f) + assert(origPath[:len(self.build_html)] == self.build_html) + outPath = os.path.join(self.build_dest, d[len(self.build_html)+1:], f) + (name, ext) = os.path.splitext(f) + if os.path.isdir(origPath): + self.mkpath(outPath) + elif ext == '.html': + if self.verbose: print 'hacking %s to %s' % (origPath,outPath) + hackedFile = file(outPath, 'w') + origFile = file(origPath,'r') + hackedFile.write(self.r.sub('<dl><dt><dd>', origFile.read())) + else: + copy_file(origPath, outPath) + + def hackHtml(self): + self.r = re.compile('<dl><dd>') + os.path.walk(self.build_html, self.visit, None) + + def visit(self, dummy, dirname, filenames): + for f in filenames: + self.hackFile(dirname, f) + + def makeHelpIndex(self): + app = '/Developer/Applications/Apple Help Indexing Tool.app' + self.spawn('open', '-a', app , self.build_dest) + print "Please wait until Apple Help Indexing Tool finishes before installing" + + def makeHelpIndex(self): + app = HelpIndexingTool.HelpIndexingTool(start=1) + app.open(Carbon.File.FSSpec(self.build_dest)) + sys.stderr.write("Waiting for Help Indexing Tool to start...") + while 1: + # This is bad design in the suite generation code! + idle = app._get(HelpIndexingTool.Help_Indexing_Tool_Suite._Prop_idleStatus()) + time.sleep(10) + if not idle: break + sys.stderr.write(".") + sys.stderr.write("\n") + sys.stderr.write("Waiting for Help Indexing Tool to finish...") + while 1: + # This is bad design in the suite generation code! + idle = app._get(HelpIndexingTool.Help_Indexing_Tool_Suite._Prop_idleStatus()) + time.sleep(10) + if idle: break + sys.stderr.write(".") + sys.stderr.write("\n") + + + def run(self): + self.ensure_finalized() + self.mkpath(self.build_base) + self.ensureHtml() + if not os.path.isdir(self.build_html): + raise RuntimeError, \ + "Can't find source folder for documentation." + self.mkpath(self.build_dest) + if dep_util.newer(os.path.join(self.build_html,'index.html'), os.path.join(self.build_dest,'index.html')): + self.mkpath(self.build_dest) + self.hackHtml() + self.hackIndex() + self.makeHelpIndex() class AHVDocInstall(Command): - description = "install Apple Help Viewer html files" - user_options = [('install-doc=', 'd', - 'directory to install HTML tree'), - ('root=', None, - "install everything relative to this alternate root directory"), - ] - - def initialize_options(self): - self.build_dest = None - self.install_doc = None - self.prefix = None - self.root = None - - def finalize_options(self): - self.set_undefined_options('install', - ('prefix', 'prefix'), - ('root', 'root')) -# import pdb ; pdb.set_trace() - build_cmd = self.get_finalized_command('build') - if self.build_dest == None: - build_cmd = self.get_finalized_command('build') - self.build_dest = build_cmd.build_dest - if self.install_doc == None: - self.install_doc = os.path.join(self.prefix, 'Resources/Python.app/Contents/Resources/English.lproj/PythonDocumentation') - print 'INSTALL', self.build_dest, '->', self.install_doc - - def run(self): - self.finalize_options() - self.ensure_finalized() - print "Running Installer" - instloc = self.install_doc - if self.root: - instloc = change_root(self.root, instloc) - self.mkpath(instloc) - copy_tree(self.build_dest, instloc) - print "Installation complete" - + description = "install Apple Help Viewer html files" + user_options = [('install-doc=', 'd', + 'directory to install HTML tree'), + ('root=', None, + "install everything relative to this alternate root directory"), + ] + + def initialize_options(self): + self.build_dest = None + self.install_doc = None + self.prefix = None + self.root = None + + def finalize_options(self): + self.set_undefined_options('install', + ('prefix', 'prefix'), + ('root', 'root')) +# import pdb ; pdb.set_trace() + build_cmd = self.get_finalized_command('build') + if self.build_dest == None: + build_cmd = self.get_finalized_command('build') + self.build_dest = build_cmd.build_dest + if self.install_doc == None: + self.install_doc = os.path.join(self.prefix, 'Resources/Python.app/Contents/Resources/English.lproj/PythonDocumentation') + print 'INSTALL', self.build_dest, '->', self.install_doc + + def run(self): + self.finalize_options() + self.ensure_finalized() + print "Running Installer" + instloc = self.install_doc + if self.root: + instloc = change_root(self.root, instloc) + self.mkpath(instloc) + copy_tree(self.build_dest, instloc) + print "Installation complete" + def mungeVersion(infile, outfile): - i = file(infile,'r') - o = file(outfile,'w') - o.write(re.sub('\$\(VERSION\)',sysconfig.get_config_var('VERSION'),i.read())) - i.close() - o.close() - + i = file(infile,'r') + o = file(outfile,'w') + o.write(re.sub('\$\(VERSION\)',sysconfig.get_config_var('VERSION'),i.read())) + i.close() + o.close() + def main(): - # turn off warnings when deprecated modules are imported -## import warnings -## warnings.filterwarnings("ignore",category=DeprecationWarning) - setup(name = 'Documentation', - version = '%d.%d' % sys.version_info[:2], - cmdclass = {'install_data':AHVDocInstall, 'build':DocBuild}, - data_files = ['dummy'], - ) + # turn off warnings when deprecated modules are imported +## import warnings +## warnings.filterwarnings("ignore",category=DeprecationWarning) + setup(name = 'Documentation', + version = '%d.%d' % sys.version_info[:2], + cmdclass = {'install_data':AHVDocInstall, 'build':DocBuild}, + data_files = ['dummy'], + ) if __name__ == '__main__': - main() + main() diff --git a/Mac/OSX/Extras.install.py b/Mac/OSX/Extras.install.py index 1939904..2521f06 100644 --- a/Mac/OSX/Extras.install.py +++ b/Mac/OSX/Extras.install.py @@ -9,45 +9,45 @@ verbose = 1 debug = 0 def isclean(name): - if name == 'CVS': return 0 - if name == '.cvsignore': return 0 - if name == '.DS_store': return 0 - if name.endswith('~'): return 0 - if name.endswith('.BAK'): return 0 - if name.endswith('.pyc'): return 0 - if name.endswith('.pyo'): return 0 - if name.endswith('.orig'): return 0 - return 1 - + if name == 'CVS': return 0 + if name == '.cvsignore': return 0 + if name == '.DS_store': return 0 + if name.endswith('~'): return 0 + if name.endswith('.BAK'): return 0 + if name.endswith('.pyc'): return 0 + if name.endswith('.pyo'): return 0 + if name.endswith('.orig'): return 0 + return 1 + def copycleandir(src, dst): - for cursrc, dirs, files in os.walk(src): - assert cursrc.startswith(src) - curdst = dst + cursrc[len(src):] - if verbose: - print "mkdir", curdst - if not debug: - if not os.path.exists(curdst): - os.makedirs(curdst) - for fn in files: - if isclean(fn): - if verbose: - print "copy", os.path.join(cursrc, fn), os.path.join(curdst, fn) - if not debug: - shutil.copy2(os.path.join(cursrc, fn), os.path.join(curdst, fn)) - else: - if verbose: - print "skipfile", os.path.join(cursrc, fn) - for i in range(len(dirs)-1, -1, -1): - if not isclean(dirs[i]): - if verbose: - print "skipdir", os.path.join(cursrc, dirs[i]) - del dirs[i] - + for cursrc, dirs, files in os.walk(src): + assert cursrc.startswith(src) + curdst = dst + cursrc[len(src):] + if verbose: + print "mkdir", curdst + if not debug: + if not os.path.exists(curdst): + os.makedirs(curdst) + for fn in files: + if isclean(fn): + if verbose: + print "copy", os.path.join(cursrc, fn), os.path.join(curdst, fn) + if not debug: + shutil.copy2(os.path.join(cursrc, fn), os.path.join(curdst, fn)) + else: + if verbose: + print "skipfile", os.path.join(cursrc, fn) + for i in range(len(dirs)-1, -1, -1): + if not isclean(dirs[i]): + if verbose: + print "skipdir", os.path.join(cursrc, dirs[i]) + del dirs[i] + def main(): - if len(sys.argv) != 3: - sys.stderr.write("Usage: %s srcdir dstdir\n" % sys.argv[0]) - sys.exit(1) - copycleandir(sys.argv[1], sys.argv[2]) - + if len(sys.argv) != 3: + sys.stderr.write("Usage: %s srcdir dstdir\n" % sys.argv[0]) + sys.exit(1) + copycleandir(sys.argv[1], sys.argv[2]) + if __name__ == '__main__': - main()
\ No newline at end of file + main() diff --git a/Mac/OSX/fixversions.py b/Mac/OSX/fixversions.py index e782e8c..0277c79 100644 --- a/Mac/OSX/fixversions.py +++ b/Mac/OSX/fixversions.py @@ -8,63 +8,62 @@ import plistlib SHORTVERSION = "%d.%d" % (sys.version_info[0], sys.version_info[1]) if sys.version_info[2]: - SHORTVERSION = SHORTVERSION + ".%d" % sys.version_info[2] + SHORTVERSION = SHORTVERSION + ".%d" % sys.version_info[2] if sys.version_info[3] != 'final': - SHORTVERSION = SHORTVERSION + "%s%d" % (sys.version_info[3], sys.version_info[4]) + SHORTVERSION = SHORTVERSION + "%s%d" % (sys.version_info[3], sys.version_info[4]) COPYRIGHT = "(c) %d Python Software Foundation." % time.gmtime()[0] LONGVERSION = SHORTVERSION + ", " + COPYRIGHT def fix(file): - plist = plistlib.Plist.fromFile(file) - changed = False - if plist.has_key("CFBundleGetInfoString") and \ - plist["CFBundleGetInfoString"] != LONGVERSION: - plist["CFBundleGetInfoString"] = LONGVERSION - changed = True - if plist.has_key("CFBundleLongVersionString") and \ - plist["CFBundleLongVersionString"] != LONGVERSION: - plist["CFBundleLongVersionString"] = LONGVERSION - changed = True - if plist.has_key("NSHumanReadableCopyright") and \ - plist["NSHumanReadableCopyright"] != COPYRIGHT: - plist["NSHumanReadableCopyright"] = COPYRIGHT - changed = True - if plist.has_key("CFBundleVersion") and \ - plist["CFBundleVersion"] != SHORTVERSION: - plist["CFBundleVersion"] = SHORTVERSION - changed = True - if plist.has_key("CFBundleShortVersionString") and \ - plist["CFBundleShortVersionString"] != SHORTVERSION: - plist["CFBundleShortVersionString"] = SHORTVERSION - changed = True - if changed: - os.rename(file, file + '~') - plist.write(file) - + plist = plistlib.Plist.fromFile(file) + changed = False + if plist.has_key("CFBundleGetInfoString") and \ + plist["CFBundleGetInfoString"] != LONGVERSION: + plist["CFBundleGetInfoString"] = LONGVERSION + changed = True + if plist.has_key("CFBundleLongVersionString") and \ + plist["CFBundleLongVersionString"] != LONGVERSION: + plist["CFBundleLongVersionString"] = LONGVERSION + changed = True + if plist.has_key("NSHumanReadableCopyright") and \ + plist["NSHumanReadableCopyright"] != COPYRIGHT: + plist["NSHumanReadableCopyright"] = COPYRIGHT + changed = True + if plist.has_key("CFBundleVersion") and \ + plist["CFBundleVersion"] != SHORTVERSION: + plist["CFBundleVersion"] = SHORTVERSION + changed = True + if plist.has_key("CFBundleShortVersionString") and \ + plist["CFBundleShortVersionString"] != SHORTVERSION: + plist["CFBundleShortVersionString"] = SHORTVERSION + changed = True + if changed: + os.rename(file, file + '~') + plist.write(file) + def main(): - if len(sys.argv) < 2: - print "Usage: %s plistfile ..." % sys.argv[0] - print "or: %s -a fix standard Python plist files" - sys.exit(1) - if sys.argv[1] == "-a": - files = [ - "../OSXResources/app/Info.plist", - "../OSXResources/framework/version.plist", - "../Tools/IDE/PackageManager.plist", - "../Tools/IDE/PythonIDE.plist", - "../scripts/BuildApplet.plist" - ] - if not os.path.exists(files[0]): - print "%s -a must be run from Mac/OSX directory" - sys.exit(1) - else: - files = sys.argv[1:] - for file in files: - fix(file) - sys.exit(0) - + if len(sys.argv) < 2: + print "Usage: %s plistfile ..." % sys.argv[0] + print "or: %s -a fix standard Python plist files" + sys.exit(1) + if sys.argv[1] == "-a": + files = [ + "../OSXResources/app/Info.plist", + "../OSXResources/framework/version.plist", + "../Tools/IDE/PackageManager.plist", + "../Tools/IDE/PythonIDE.plist", + "../scripts/BuildApplet.plist" + ] + if not os.path.exists(files[0]): + print "%s -a must be run from Mac/OSX directory" + sys.exit(1) + else: + files = sys.argv[1:] + for file in files: + fix(file) + sys.exit(0) + if __name__ == "__main__": - main() -
\ No newline at end of file + main() diff --git a/Mac/Tools/IDE/BuildIDE.py b/Mac/Tools/IDE/BuildIDE.py index 7e65869..914028c 100644 --- a/Mac/Tools/IDE/BuildIDE.py +++ b/Mac/Tools/IDE/BuildIDE.py @@ -1,4 +1,4 @@ -"""Build a "big" applet for the IDE, and put it in the Python home +"""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).""" @@ -25,17 +25,16 @@ 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) +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) + 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) - diff --git a/Mac/Tools/IDE/FontSettings.py b/Mac/Tools/IDE/FontSettings.py index af2bd80..d713438 100644 --- a/Mac/Tools/IDE/FontSettings.py +++ b/Mac/Tools/IDE/FontSettings.py @@ -1,9 +1,9 @@ -"""usage: -newsettings = FontDialog(('Chicago', 0, 12, (0, 0, 0))) # font name or id, style flags, size, color (color is ignored) +"""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 + fontsettings, tabsettings = newsettings + font, style, size, color = fontsettings # 'font' is always the font name, not the id number + # do something """ import W @@ -15,209 +15,209 @@ import types import sys import MacOS if hasattr(MacOS, "SysBeep"): - SysBeep = MacOS.SysBeep + SysBeep = MacOS.SysBeep else: - def SysBeep(*args): - pass + 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 __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 + fd = _FontDialog(fontsettings, tabsettings) + return fd._rv def test(): - print FontDialog(('Zapata-Light', 0, 25, (0, 0, 0))) + print FontDialog(('Zapata-Light', 0, 25, (0, 0, 0))) diff --git a/Mac/Tools/IDE/MacPrefs.py b/Mac/Tools/IDE/MacPrefs.py index 25dda4f..3cf9153 100644 --- a/Mac/Tools/IDE/MacPrefs.py +++ b/Mac/Tools/IDE/MacPrefs.py @@ -4,105 +4,105 @@ 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 + + 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 + + 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 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 diff --git a/Mac/Tools/IDE/ModuleBrowser.py b/Mac/Tools/IDE/ModuleBrowser.py index 0e8850f..9fe1064 100644 --- a/Mac/Tools/IDE/ModuleBrowser.py +++ b/Mac/Tools/IDE/ModuleBrowser.py @@ -6,172 +6,172 @@ __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 __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 - - + 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() + global _browser + if _browser is not None: + _browser.window.select() + else: + _browser = _modulebrowser() diff --git a/Mac/Tools/IDE/PackageManager.py b/Mac/Tools/IDE/PackageManager.py index ee6355b..0041a17 100755 --- a/Mac/Tools/IDE/PackageManager.py +++ b/Mac/Tools/IDE/PackageManager.py @@ -1,37 +1,37 @@ # Prelude to allow running this as a main program def _init(): - 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(0, ide_path) - + 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(0, ide_path) + if __name__ == '__main__': - _init() - + _init() + import W import Wapplication from Carbon import Evt @@ -48,424 +48,424 @@ import pimp PACKMAN_HOMEPAGE="http://www.python.org/packman" ELIPSES = '...' - + USER_INSTALL_DIR = os.path.join(os.environ.get('HOME', ''), - 'Library', - 'Python', - sys.version[:3], - 'site-packages') - + 'Library', + 'Python', + sys.version[:3], + 'site-packages') + class PackageManagerMain(Wapplication.Application): - - def __init__(self): - self.preffilepath = os.path.join("Python", "Package Install Manager Prefs") - Wapplication.Application.__init__(self, 'Pimp') - from Carbon import AE - from Carbon import AppleEvents - self.defaulturl = "" - - AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenApplication, - self.ignoreevent) - AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEReopenApplication, - self.ignoreevent) - AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEPrintDocuments, - self.ignoreevent) - AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEQuitApplication, - self.quitevent) - if 1: - import PyConsole - # With -D option (OSX command line only) keep stderr, for debugging the IDE - # itself. - debug_stderr = None - if len(sys.argv) >= 2 and sys.argv[1] == '-D': - debug_stderr = sys.stderr - del sys.argv[1] - PyConsole.installoutput() - if debug_stderr: - sys.stderr = debug_stderr - self.domenu_openstandard() - self.mainloop() - - def makeusermenus(self): - m = Wapplication.Menu(self.menubar, "File") - newitem = FrameWork.MenuItem(m, "Open Standard Database", "N", 'openstandard') - newexpitem = FrameWork.MenuItem(m, "Open Experimental Database", None, 'openexperimental') - newexpitem.enable(pimp.PIMP_VERSION >= "0.4") - openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') - openURLitem = FrameWork.MenuItem(m, "Open URL"+ELIPSES, "D", 'openURL') - FrameWork.Separator(m) - moreinfoitem = FrameWork.MenuItem(m, "More Databases", None, 'opendatabasepage') - FrameWork.Separator(m) - closeitem = FrameWork.MenuItem(m, "Close", "W", 'close') -## saveitem = FrameWork.MenuItem(m, "Save", "S", 'save') -## saveasitem = FrameWork.MenuItem(m, "Save as"+ELIPSES, None, 'save_as') -## FrameWork.Separator(m) - - m = Wapplication.Menu(self.menubar, "Edit") - undoitem = FrameWork.MenuItem(m, "Undo", 'Z', "undo") - FrameWork.Separator(m) - cutitem = FrameWork.MenuItem(m, "Cut", 'X', "cut") - copyitem = FrameWork.MenuItem(m, "Copy", "C", "copy") - pasteitem = FrameWork.MenuItem(m, "Paste", "V", "paste") - FrameWork.MenuItem(m, "Clear", None, "clear") - FrameWork.Separator(m) - selallitem = FrameWork.MenuItem(m, "Select all", "A", "selectall") - - m = Wapplication.Menu(self.menubar, "Package") - runitem = FrameWork.MenuItem(m, "Install", "I", 'install') - homepageitem = FrameWork.MenuItem(m, "Visit Homepage", None, 'homepage') - - self.openwindowsmenu = Wapplication.Menu(self.menubar, 'Windows') - self.makeopenwindowsmenu() - self.makehelpmenu() - self._menustocheck = [closeitem, - undoitem, cutitem, copyitem, pasteitem, - selallitem, - runitem, homepageitem] - - def makehelpmenu(self): - python_app = os.path.join(sys.prefix, 'Resources/Python.app') - help_source = os.path.join(python_app, 'Contents/Resources/English.lproj/Documentation') - hashelp = os.path.isdir(help_source) - - self.helpmenu = m = self.gethelpmenu() - helpitem1 = FrameWork.MenuItem(m, "PackageManager Help", None, self.domenu_packmanhelp) - helpitem1.enable(hashelp) - helpitem2 = FrameWork.MenuItem(m, "MacPython Help", None, self.domenu_pythonhelp) - helpitem2.enable(hashelp) - - def quitevent(self, theAppleEvent, theReply): - self._quit() - - 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: - fsr, a = doc.FSResolveAlias(None) - path = fsr.as_pathname() - path = urllib.pathname2url(path) - self.opendoc(path) - - def opendoc(self, url): - if url: - self.defaulturl = url - PackageBrowser(url) - - def getabouttext(self): - return "About Package Manager"+ELIPSES - - def do_about(self, id, item, window, event): - EasyDialogs.Message("Package Install Manager for Python\nPackMan engine (pimp) version: %s" % - pimp.PIMP_VERSION) - - def domenu_openstandard(self, *args): - if pimp.PIMP_VERSION >= "0.4": - url = pimp.getDefaultDatabase() - else: - # 0.3 compatibility - url = None - self.opendoc(url) - - def domenu_openexperimental(self, *args): - database = pimp.getDefaultDatabase(experimental=True) - self.opendoc(database) - - def domenu_open(self, *args): - filename = EasyDialogs.AskFileForOpen(typeList=("TEXT",)) - if filename: - filename = urllib.pathname2url(filename) - self.opendoc(filename) - - def domenu_openURL(self, *args): - ok = EasyDialogs.AskYesNoCancel( - "Warning: by opening a non-standard database " - "you are trusting the maintainer of it " - "to run arbitrary code on your machine.", - yes="OK", no="") - if ok <= 0: return - url = EasyDialogs.AskString("URL of database to open:", - default=self.defaulturl, ok="Open") - if url: - self.opendoc(url) - - def domenu_opendatabasepage(self): - import ic - - icr = ic.IC() - icr.launchurl(PACKMAN_HOMEPAGE) - 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: - shortcut = None - item = FrameWork.MenuItem(self.openwindowsmenu, title, shortcut, callback = self.domenu_openwindows) - self._openwindows[item.item] = window - self._openwindowscheckmark = 0 - self.checkopenwindowsmenu() - - def domenu_openwindows(self, id, item, window, event): - w = self._openwindows[item] - w.ShowWindow() - w.SelectWindow() - - def domenu_quit(self): - self._quit() - - def domenu_save(self, *args): - print "Save" - - def domenu_pythonhelp(self, *args): - from Carbon import AH - AH.AHGotoPage("MacPython Help", None, None) - - def domenu_packmanhelp(self, *args): - from Carbon import AH - AH.AHGotoPage("MacPython Help", "packman.html", None) - - def _quit(self): -## import PyConsole, PyEdit - for window in self._windows.values(): - try: - rv = window.close() # ignore any errors while quitting - except: - rv = 0 # (otherwise, we can get stuck!) - if rv and rv > 0: - return -## try: -## PyConsole.console.writeprefs() -## PyConsole.output.writeprefs() -## PyEdit.searchengine.writeprefs() -## except: -## # Write to __stderr__ so the msg end up in Console.app and has -## # at least _some_ chance of getting read... -## # But: this is a workaround for way more serious problems with -## # the Python 2.2 Jaguar addon. -## sys.__stderr__.write("*** PythonIDE: Can't write preferences ***\n") - self.quitting = 1 - + + def __init__(self): + self.preffilepath = os.path.join("Python", "Package Install Manager Prefs") + Wapplication.Application.__init__(self, 'Pimp') + from Carbon import AE + from Carbon import AppleEvents + self.defaulturl = "" + + AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenApplication, + self.ignoreevent) + AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEReopenApplication, + self.ignoreevent) + AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEPrintDocuments, + self.ignoreevent) + AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEQuitApplication, + self.quitevent) + if 1: + import PyConsole + # With -D option (OSX command line only) keep stderr, for debugging the IDE + # itself. + debug_stderr = None + if len(sys.argv) >= 2 and sys.argv[1] == '-D': + debug_stderr = sys.stderr + del sys.argv[1] + PyConsole.installoutput() + if debug_stderr: + sys.stderr = debug_stderr + self.domenu_openstandard() + self.mainloop() + + def makeusermenus(self): + m = Wapplication.Menu(self.menubar, "File") + newitem = FrameWork.MenuItem(m, "Open Standard Database", "N", 'openstandard') + newexpitem = FrameWork.MenuItem(m, "Open Experimental Database", None, 'openexperimental') + newexpitem.enable(pimp.PIMP_VERSION >= "0.4") + openitem = FrameWork.MenuItem(m, "Open"+ELIPSES, "O", 'open') + openURLitem = FrameWork.MenuItem(m, "Open URL"+ELIPSES, "D", 'openURL') + FrameWork.Separator(m) + moreinfoitem = FrameWork.MenuItem(m, "More Databases", None, 'opendatabasepage') + FrameWork.Separator(m) + closeitem = FrameWork.MenuItem(m, "Close", "W", 'close') +## saveitem = FrameWork.MenuItem(m, "Save", "S", 'save') +## saveasitem = FrameWork.MenuItem(m, "Save as"+ELIPSES, None, 'save_as') +## FrameWork.Separator(m) + + m = Wapplication.Menu(self.menubar, "Edit") + undoitem = FrameWork.MenuItem(m, "Undo", 'Z', "undo") + FrameWork.Separator(m) + cutitem = FrameWork.MenuItem(m, "Cut", 'X', "cut") + copyitem = FrameWork.MenuItem(m, "Copy", "C", "copy") + pasteitem = FrameWork.MenuItem(m, "Paste", "V", "paste") + FrameWork.MenuItem(m, "Clear", None, "clear") + FrameWork.Separator(m) + selallitem = FrameWork.MenuItem(m, "Select all", "A", "selectall") + + m = Wapplication.Menu(self.menubar, "Package") + runitem = FrameWork.MenuItem(m, "Install", "I", 'install') + homepageitem = FrameWork.MenuItem(m, "Visit Homepage", None, 'homepage') + + self.openwindowsmenu = Wapplication.Menu(self.menubar, 'Windows') + self.makeopenwindowsmenu() + self.makehelpmenu() + self._menustocheck = [closeitem, + undoitem, cutitem, copyitem, pasteitem, + selallitem, + runitem, homepageitem] + + def makehelpmenu(self): + python_app = os.path.join(sys.prefix, 'Resources/Python.app') + help_source = os.path.join(python_app, 'Contents/Resources/English.lproj/Documentation') + hashelp = os.path.isdir(help_source) + + self.helpmenu = m = self.gethelpmenu() + helpitem1 = FrameWork.MenuItem(m, "PackageManager Help", None, self.domenu_packmanhelp) + helpitem1.enable(hashelp) + helpitem2 = FrameWork.MenuItem(m, "MacPython Help", None, self.domenu_pythonhelp) + helpitem2.enable(hashelp) + + def quitevent(self, theAppleEvent, theReply): + self._quit() + + 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: + fsr, a = doc.FSResolveAlias(None) + path = fsr.as_pathname() + path = urllib.pathname2url(path) + self.opendoc(path) + + def opendoc(self, url): + if url: + self.defaulturl = url + PackageBrowser(url) + + def getabouttext(self): + return "About Package Manager"+ELIPSES + + def do_about(self, id, item, window, event): + EasyDialogs.Message("Package Install Manager for Python\nPackMan engine (pimp) version: %s" % + pimp.PIMP_VERSION) + + def domenu_openstandard(self, *args): + if pimp.PIMP_VERSION >= "0.4": + url = pimp.getDefaultDatabase() + else: + # 0.3 compatibility + url = None + self.opendoc(url) + + def domenu_openexperimental(self, *args): + database = pimp.getDefaultDatabase(experimental=True) + self.opendoc(database) + + def domenu_open(self, *args): + filename = EasyDialogs.AskFileForOpen(typeList=("TEXT",)) + if filename: + filename = urllib.pathname2url(filename) + self.opendoc(filename) + + def domenu_openURL(self, *args): + ok = EasyDialogs.AskYesNoCancel( + "Warning: by opening a non-standard database " + "you are trusting the maintainer of it " + "to run arbitrary code on your machine.", + yes="OK", no="") + if ok <= 0: return + url = EasyDialogs.AskString("URL of database to open:", + default=self.defaulturl, ok="Open") + if url: + self.opendoc(url) + + def domenu_opendatabasepage(self): + import ic + + icr = ic.IC() + icr.launchurl(PACKMAN_HOMEPAGE) + 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: + shortcut = None + item = FrameWork.MenuItem(self.openwindowsmenu, title, shortcut, callback = self.domenu_openwindows) + self._openwindows[item.item] = window + self._openwindowscheckmark = 0 + self.checkopenwindowsmenu() + + def domenu_openwindows(self, id, item, window, event): + w = self._openwindows[item] + w.ShowWindow() + w.SelectWindow() + + def domenu_quit(self): + self._quit() + + def domenu_save(self, *args): + print "Save" + + def domenu_pythonhelp(self, *args): + from Carbon import AH + AH.AHGotoPage("MacPython Help", None, None) + + def domenu_packmanhelp(self, *args): + from Carbon import AH + AH.AHGotoPage("MacPython Help", "packman.html", None) + + def _quit(self): +## import PyConsole, PyEdit + for window in self._windows.values(): + try: + rv = window.close() # ignore any errors while quitting + except: + rv = 0 # (otherwise, we can get stuck!) + if rv and rv > 0: + return +## try: +## PyConsole.console.writeprefs() +## PyConsole.output.writeprefs() +## PyEdit.searchengine.writeprefs() +## except: +## # Write to __stderr__ so the msg end up in Console.app and has +## # at least _some_ chance of getting read... +## # But: this is a workaround for way more serious problems with +## # the Python 2.2 Jaguar addon. +## sys.__stderr__.write("*** PythonIDE: Can't write preferences ***\n") + self.quitting = 1 + class PimpInterface: - def setuppimp(self, url): - self.pimpprefs = pimp.PimpPreferences() - self.pimpdb = pimp.PimpDatabase(self.pimpprefs) - if not url: - url = self.pimpprefs.pimpDatabase - try: - self.pimpdb.appendURL(url) - except IOError, arg: - rv = "Cannot open %s: %s\n" % (url, arg) - rv += "\nSee MacPython Package Manager help page." - return rv - except: - rv = "Unspecified error while parsing database: %s\n" % url - rv += "Usually, this means the database is not correctly formatted.\n" - rv += "\nSee MacPython Package Manager help page." - return rv - # Check whether we can write the installation directory. - # If not, set to the per-user directory, possibly - # creating it, if needed. - installDir = self.pimpprefs.installDir - if not os.access(installDir, os.R_OK|os.W_OK|os.X_OK): - rv = self.setuserinstall(1) - if rv: return rv - return self.pimpprefs.check() - - def closepimp(self): - self.pimpdb.close() - self.pimpprefs = None - self.pimpdb = None - self.packages = [] - - def setuserinstall(self, onoff): - rv = "" - if onoff: - if not os.path.exists(USER_INSTALL_DIR): - try: - os.makedirs(USER_INSTALL_DIR) - except OSError, arg: - rv = rv + arg + "\n" - if not USER_INSTALL_DIR in sys.path: - import site - reload(site) - self.pimpprefs.setInstallDir(USER_INSTALL_DIR) - else: - self.pimpprefs.setInstallDir(None) - rv = rv + self.pimpprefs.check() - return rv - - def getuserinstall(self): - return self.pimpprefs.installDir == USER_INSTALL_DIR - - def getbrowserdata(self, show_hidden=1): - packages = self.pimpdb.list() - if show_hidden: - self.packages = packages - else: - self.packages = [] - for pkg in packages: - name = pkg.fullname() - if name[0] == '(' and name[-1] == ')' and not show_hidden: - continue - self.packages.append(pkg) - rv = [] - for pkg in self.packages: - name = pkg.fullname() - status, _ = pkg.installed() - description = pkg.description() - description_line1 = description.split('\n')[0] - rv.append((status, name, description_line1)) - return rv - - def getstatus(self, number): - pkg = self.packages[number] - return pkg.installed() - - def installpackage(self, sel, output, recursive, force): - pkg = self.packages[sel] - pimpinstaller = pimp.PimpInstaller(self.pimpdb) - list, messages = pimpinstaller.prepareInstall(pkg, force, recursive) - if messages: - return messages - messages = pimpinstaller.install(list, output) - return messages - + def setuppimp(self, url): + self.pimpprefs = pimp.PimpPreferences() + self.pimpdb = pimp.PimpDatabase(self.pimpprefs) + if not url: + url = self.pimpprefs.pimpDatabase + try: + self.pimpdb.appendURL(url) + except IOError, arg: + rv = "Cannot open %s: %s\n" % (url, arg) + rv += "\nSee MacPython Package Manager help page." + return rv + except: + rv = "Unspecified error while parsing database: %s\n" % url + rv += "Usually, this means the database is not correctly formatted.\n" + rv += "\nSee MacPython Package Manager help page." + return rv + # Check whether we can write the installation directory. + # If not, set to the per-user directory, possibly + # creating it, if needed. + installDir = self.pimpprefs.installDir + if not os.access(installDir, os.R_OK|os.W_OK|os.X_OK): + rv = self.setuserinstall(1) + if rv: return rv + return self.pimpprefs.check() + + def closepimp(self): + self.pimpdb.close() + self.pimpprefs = None + self.pimpdb = None + self.packages = [] + + def setuserinstall(self, onoff): + rv = "" + if onoff: + if not os.path.exists(USER_INSTALL_DIR): + try: + os.makedirs(USER_INSTALL_DIR) + except OSError, arg: + rv = rv + arg + "\n" + if not USER_INSTALL_DIR in sys.path: + import site + reload(site) + self.pimpprefs.setInstallDir(USER_INSTALL_DIR) + else: + self.pimpprefs.setInstallDir(None) + rv = rv + self.pimpprefs.check() + return rv + + def getuserinstall(self): + return self.pimpprefs.installDir == USER_INSTALL_DIR + + def getbrowserdata(self, show_hidden=1): + packages = self.pimpdb.list() + if show_hidden: + self.packages = packages + else: + self.packages = [] + for pkg in packages: + name = pkg.fullname() + if name[0] == '(' and name[-1] == ')' and not show_hidden: + continue + self.packages.append(pkg) + rv = [] + for pkg in self.packages: + name = pkg.fullname() + status, _ = pkg.installed() + description = pkg.description() + description_line1 = description.split('\n')[0] + rv.append((status, name, description_line1)) + return rv + + def getstatus(self, number): + pkg = self.packages[number] + return pkg.installed() + + def installpackage(self, sel, output, recursive, force): + pkg = self.packages[sel] + pimpinstaller = pimp.PimpInstaller(self.pimpdb) + list, messages = pimpinstaller.prepareInstall(pkg, force, recursive) + if messages: + return messages + messages = pimpinstaller.install(list, output) + return messages + class PackageBrowser(PimpInterface): - - def __init__(self, url = None): - self.ic = None - messages = self.setuppimp(url) - self.setupwidgets() - self.updatestatus() - self.showmessages(messages) - - def close(self): - self.closepimp() - - def setupwidgets(self): - DESCRIPTION_HEIGHT = 140 - INSTALL_POS = -30 - STATUS_POS = INSTALL_POS - (70 + DESCRIPTION_HEIGHT) - self.w = W.Window((580, 600), "Python Install Manager", minsize = (400, 400), tabbable = 0) - self.w.titlebar = W.TextBox((4, 8, 60, 18), 'Packages:') - self.w.hidden_button = W.CheckBox((-100, 4, 0, 18), 'Show Hidden', self.updatestatus) - data = self.getbrowserdata() - self.w.packagebrowser = W.MultiList((4, 24, 0, STATUS_POS-2), data, self.listhit, cols=3) - - self.w.installed_l = W.TextBox((4, STATUS_POS, 70, 12), 'Installed:') - self.w.installed = W.TextBox((74, STATUS_POS, 0, 12), '') - self.w.message_l = W.TextBox((4, STATUS_POS+20, 70, 12), 'Status:') - self.w.message = W.TextBox((74, STATUS_POS+20, 0, 12), '') - self.w.homepage_button = W.Button((4, STATUS_POS+40, 96, 18), 'View homepage', self.do_homepage) - self.w.description_l = W.TextBox((4, STATUS_POS+70, 70, 12), 'Description:') - self.w.description = W.EditText((74, STATUS_POS+70, 0, DESCRIPTION_HEIGHT-4)) - - self.w.divline = W.HorizontalLine((0, INSTALL_POS-4, 0, 0)) - self.w.verbose_button = W.CheckBox((84, INSTALL_POS+4, 60, 18), 'Verbose') - self.w.recursive_button = W.CheckBox((146, INSTALL_POS+4, 120, 18), 'Install dependencies', self.updatestatus) - self.w.recursive_button.set(1) - self.w.force_button = W.CheckBox((268, INSTALL_POS+4, 70, 18), 'Overwrite', self.updatestatus) - self.w.user_button = W.CheckBox((340, INSTALL_POS+4, 140, 18), 'For Current User Only', self.do_user) - self.w.install_button = W.Button((4, INSTALL_POS+4, 56, 18), 'Install:', self.do_install) - self.w.open() - self.w.description.enable(0) - - def updatestatus(self): - topcell = self.w.packagebrowser.gettopcell() - sel = self.w.packagebrowser.getselection() - data = self.getbrowserdata(self.w.hidden_button.get()) - self.w.packagebrowser.setitems(data) - self.w.user_button.set(self.getuserinstall()) - if len(sel) != 1: - self.w.installed.set('') - self.w.message.set('') - self.w.install_button.enable(0) - self.w.homepage_button.enable(0) - self.w.description.set('') - self.w.verbose_button.enable(0) - self.w.recursive_button.enable(0) - self.w.force_button.enable(0) - self.w.user_button.enable(0) - else: - sel = sel[0] - if sel >= len(self.packages): - sel = 0 - self.w.packagebrowser.setselection([sel]) - installed, message = self.getstatus(sel) - self.w.installed.set(installed) - self.w.message.set(message) - self.w.install_button.enable(installed != "yes" or self.w.force_button.get()) - self.w.homepage_button.enable(not not self.packages[sel].homepage()) - description = self.packages[sel].description() - description = description.splitlines() - description = '\r'.join(description) - self.w.description.set(description) - self.w.verbose_button.enable(1) - self.w.recursive_button.enable(1) - self.w.force_button.enable(1) - self.w.user_button.enable(1) - self.w.packagebrowser.settopcell(topcell) - - def listhit(self, *args, **kwargs): - self.updatestatus() - - def do_install(self): - sel = self.w.packagebrowser.getselection()[0] - if self.w.verbose_button.get(): - output = sys.stdout - else: - output = None - recursive = self.w.recursive_button.get() - force = self.w.force_button.get() - messages = self.installpackage(sel, output, recursive, force) - - # Re-read .pth files - import site - reload(site) - - self.updatestatus() - self.showmessages(messages) - - def showmessages(self, messages): - if messages: - # To be on the safe side we always show the hidden packages, - # they may be referred to in the error messages. - if not self.w.hidden_button.get(): - self.w.hidden_button.set(1) - self.updatestatus() - if type(messages) == list: - messages = '\n'.join(messages) - if self.w.verbose_button.get(): - sys.stdout.write(messages + '\n') - EasyDialogs.Message(messages) - - def do_homepage(self): - sel = self.w.packagebrowser.getselection()[0] - if not self.ic: - import ic - - self.ic = ic.IC() - self.ic.launchurl(self.packages[sel].homepage()) - - def do_user(self): - messages = self.setuserinstall(self.w.user_button.get()) - self.updatestatus() - self.showmessages(messages) - + + def __init__(self, url = None): + self.ic = None + messages = self.setuppimp(url) + self.setupwidgets() + self.updatestatus() + self.showmessages(messages) + + def close(self): + self.closepimp() + + def setupwidgets(self): + DESCRIPTION_HEIGHT = 140 + INSTALL_POS = -30 + STATUS_POS = INSTALL_POS - (70 + DESCRIPTION_HEIGHT) + self.w = W.Window((580, 600), "Python Install Manager", minsize = (400, 400), tabbable = 0) + self.w.titlebar = W.TextBox((4, 8, 60, 18), 'Packages:') + self.w.hidden_button = W.CheckBox((-100, 4, 0, 18), 'Show Hidden', self.updatestatus) + data = self.getbrowserdata() + self.w.packagebrowser = W.MultiList((4, 24, 0, STATUS_POS-2), data, self.listhit, cols=3) + + self.w.installed_l = W.TextBox((4, STATUS_POS, 70, 12), 'Installed:') + self.w.installed = W.TextBox((74, STATUS_POS, 0, 12), '') + self.w.message_l = W.TextBox((4, STATUS_POS+20, 70, 12), 'Status:') + self.w.message = W.TextBox((74, STATUS_POS+20, 0, 12), '') + self.w.homepage_button = W.Button((4, STATUS_POS+40, 96, 18), 'View homepage', self.do_homepage) + self.w.description_l = W.TextBox((4, STATUS_POS+70, 70, 12), 'Description:') + self.w.description = W.EditText((74, STATUS_POS+70, 0, DESCRIPTION_HEIGHT-4)) + + self.w.divline = W.HorizontalLine((0, INSTALL_POS-4, 0, 0)) + self.w.verbose_button = W.CheckBox((84, INSTALL_POS+4, 60, 18), 'Verbose') + self.w.recursive_button = W.CheckBox((146, INSTALL_POS+4, 120, 18), 'Install dependencies', self.updatestatus) + self.w.recursive_button.set(1) + self.w.force_button = W.CheckBox((268, INSTALL_POS+4, 70, 18), 'Overwrite', self.updatestatus) + self.w.user_button = W.CheckBox((340, INSTALL_POS+4, 140, 18), 'For Current User Only', self.do_user) + self.w.install_button = W.Button((4, INSTALL_POS+4, 56, 18), 'Install:', self.do_install) + self.w.open() + self.w.description.enable(0) + + def updatestatus(self): + topcell = self.w.packagebrowser.gettopcell() + sel = self.w.packagebrowser.getselection() + data = self.getbrowserdata(self.w.hidden_button.get()) + self.w.packagebrowser.setitems(data) + self.w.user_button.set(self.getuserinstall()) + if len(sel) != 1: + self.w.installed.set('') + self.w.message.set('') + self.w.install_button.enable(0) + self.w.homepage_button.enable(0) + self.w.description.set('') + self.w.verbose_button.enable(0) + self.w.recursive_button.enable(0) + self.w.force_button.enable(0) + self.w.user_button.enable(0) + else: + sel = sel[0] + if sel >= len(self.packages): + sel = 0 + self.w.packagebrowser.setselection([sel]) + installed, message = self.getstatus(sel) + self.w.installed.set(installed) + self.w.message.set(message) + self.w.install_button.enable(installed != "yes" or self.w.force_button.get()) + self.w.homepage_button.enable(not not self.packages[sel].homepage()) + description = self.packages[sel].description() + description = description.splitlines() + description = '\r'.join(description) + self.w.description.set(description) + self.w.verbose_button.enable(1) + self.w.recursive_button.enable(1) + self.w.force_button.enable(1) + self.w.user_button.enable(1) + self.w.packagebrowser.settopcell(topcell) + + def listhit(self, *args, **kwargs): + self.updatestatus() + + def do_install(self): + sel = self.w.packagebrowser.getselection()[0] + if self.w.verbose_button.get(): + output = sys.stdout + else: + output = None + recursive = self.w.recursive_button.get() + force = self.w.force_button.get() + messages = self.installpackage(sel, output, recursive, force) + + # Re-read .pth files + import site + reload(site) + + self.updatestatus() + self.showmessages(messages) + + def showmessages(self, messages): + if messages: + # To be on the safe side we always show the hidden packages, + # they may be referred to in the error messages. + if not self.w.hidden_button.get(): + self.w.hidden_button.set(1) + self.updatestatus() + if type(messages) == list: + messages = '\n'.join(messages) + if self.w.verbose_button.get(): + sys.stdout.write(messages + '\n') + EasyDialogs.Message(messages) + + def do_homepage(self): + sel = self.w.packagebrowser.getselection()[0] + if not self.ic: + import ic + + self.ic = ic.IC() + self.ic.launchurl(self.packages[sel].homepage()) + + def do_user(self): + messages = self.setuserinstall(self.w.user_button.get()) + self.updatestatus() + self.showmessages(messages) + if __name__ == '__main__': - PackageManagerMain() + PackageManagerMain() diff --git a/Mac/Tools/IDE/ProfileBrowser.py b/Mac/Tools/IDE/ProfileBrowser.py index a19641c..a2dafdd 100644 --- a/Mac/Tools/IDE/ProfileBrowser.py +++ b/Mac/Tools/IDE/ProfileBrowser.py @@ -9,84 +9,84 @@ import pstats, fpformat # increase precision def f8(x): - return string.rjust(fpformat.fix(x, 4), 8) + return string.rjust(fpformat.fix(x, 4), 8) pstats.f8 = f8 # hacking around a hack if sys.version[:3] > '1.4': - timer = Evt.TickCount + timer = Evt.TickCount else: - def timer(TickCount = Evt.TickCount): - return TickCount() / 60.0 + 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 __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) + 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() + main() diff --git a/Mac/Tools/IDE/PyBrowser.py b/Mac/Tools/IDE/PyBrowser.py index 397347e..0ad3a9a 100644 --- a/Mac/Tools/IDE/PyBrowser.py +++ b/Mac/Tools/IDE/PyBrowser.py @@ -18,600 +18,599 @@ arrows = (nullid, closedid, openid, closedsolidid, opensolidid) has_ctlcharsRE = re.compile(r'[\000-\037\177-\377]') def ctlcharsREsearch(str): - if has_ctlcharsRE.search(str) is None: - return -1 - return 1 - -def double_repr(key, value, truncvalue = 0, - type = type, StringType = types.StringType, - has_ctlchars = ctlcharsREsearch, _repr = repr, str = str): - if type(key) == StringType and has_ctlchars(key) < 0: - key = str(key) - else: - key = _repr(key) - if key == '__builtins__': - value = "<" + type(value).__name__ + " '__builtin__'>" - elif key == '__return__': - # bleh, when returning from a class codeblock we get infinite recursion in repr. - # Use safe repr instead. - import repr - value = repr.repr(value) - else: - try: - value = _repr(value) - '' + value # test to see if it is a string, in case a __repr__ method is buggy - except: - value = '\xa5\xa5\xa5 exception in repr()' - if truncvalue: - return key + '\t' + value[:255] - return key + '\t' + value + if has_ctlcharsRE.search(str) is None: + return -1 + return 1 + +def double_repr(key, value, truncvalue = 0, + type = type, StringType = types.StringType, + has_ctlchars = ctlcharsREsearch, _repr = repr, str = str): + if type(key) == StringType and has_ctlchars(key) < 0: + key = str(key) + else: + key = _repr(key) + if key == '__builtins__': + value = "<" + type(value).__name__ + " '__builtin__'>" + elif key == '__return__': + # bleh, when returning from a class codeblock we get infinite recursion in repr. + # Use safe repr instead. + import repr + value = repr.repr(value) + else: + try: + value = _repr(value) + '' + value # test to see if it is a string, in case a __repr__ method is buggy + except: + value = '\xa5\xa5\xa5 exception in repr()' + if truncvalue: + return key + '\t' + value[:255] + return key + '\t' + value def truncString(s, maxwid): - if maxwid < 1: - return 1, "" - strlen = len(s) - strwid = Qd.TextWidth(s, 0, strlen); - if strwid <= maxwid: - return 0, s - - Qd.TextFace(QuickDraw.condense) - strwid = Qd.TextWidth(s, 0, strlen) - ellipsis = Qd.StringWidth('\xc9') - - if strwid <= maxwid: - Qd.TextFace(0) - return 1, s - if strwid < 1: - Qd.TextFace(0) - return 1, "" - - mid = int(strlen * maxwid / strwid) - while 1: - if mid <= 0: - mid = 0 - break - strwid = Qd.TextWidth(s, 0, mid) + ellipsis - strwid2 = Qd.TextWidth(s, 0, mid + 1) + ellipsis - if strwid <= maxwid and maxwid <= strwid2: - if maxwid == strwid2: - mid += 1 - break - if strwid > maxwid: - mid -= 1 - if mid <= 0: - mid = 0 - break - elif strwid2 < maxwid: - mid += 1 - Qd.TextFace(0) - return 1, s[:mid] + '\xc9' + if maxwid < 1: + return 1, "" + strlen = len(s) + strwid = Qd.TextWidth(s, 0, strlen); + if strwid <= maxwid: + return 0, s + + Qd.TextFace(QuickDraw.condense) + strwid = Qd.TextWidth(s, 0, strlen) + ellipsis = Qd.StringWidth('\xc9') + + if strwid <= maxwid: + Qd.TextFace(0) + return 1, s + if strwid < 1: + Qd.TextFace(0) + return 1, "" + + mid = int(strlen * maxwid / strwid) + while 1: + if mid <= 0: + mid = 0 + break + strwid = Qd.TextWidth(s, 0, mid) + ellipsis + strwid2 = Qd.TextWidth(s, 0, mid + 1) + ellipsis + if strwid <= maxwid and maxwid <= strwid2: + if maxwid == strwid2: + mid += 1 + break + if strwid > maxwid: + mid -= 1 + if mid <= 0: + mid = 0 + break + elif strwid2 < maxwid: + mid += 1 + Qd.TextFace(0) + return 1, s[:mid] + '\xc9' def drawTextCell(text, cellRect, ascent, theList): - l, t, r, b = cellRect - cellwidth = r - l - Qd.MoveTo(int(l + 2), int(t + ascent)) - condense, text = truncString(text, cellwidth - 3) - if condense: - Qd.TextFace(QuickDraw.condense) - Qd.DrawText(text, 0, len(text)) - Qd.TextFace(0) + l, t, r, b = cellRect + cellwidth = r - l + Qd.MoveTo(int(l + 2), int(t + ascent)) + condense, text = truncString(text, cellwidth - 3) + if condense: + Qd.TextFace(QuickDraw.condense) + Qd.DrawText(text, 0, len(text)) + Qd.TextFace(0) PICTWIDTH = 16 class BrowserWidget(W.CustomList): - - def __init__(self, possize, object = None, col = 100, closechildren = 0): - W.List.__init__(self, possize, callback = self.listhit) - self.object = (None,) - self.indent = 16 - self.lastmaxindent = 0 - self.closechildren = closechildren - self.children = [] - self.mincol = 64 - self.setcolumn(col) - self.bind('return', self.openselection) - self.bind('enter', self.openselection) - if object is not None: - self.set(object) - - def set(self, object): - if self.object[0] is not object: - self.object = object, - self[:] = self.unpack(object, 0) - elif self._parentwindow is not None and self._parentwindow.wid: - self.update() - - def unpack(self, object, indent): - return unpack_object(object, indent) - - def update(self): - # for now... - W.SetCursor('watch') - self.setdrawingmode(0) - sel = self.getselectedobjects() - fold = self.getunfoldedobjects() - topcell = self.gettopcell() - self[:] = self.unpack(self.object[0], 0) - self.unfoldobjects(fold) - self.setselectedobjects(sel) - self.settopcell(topcell) - self.setdrawingmode(1) - - def setcolumn(self, col): - self.col = col - self.colstr = struct.pack('h', col) - if self._list: - sel = self.getselection() - self.setitems(self.items) - self.setselection(sel) - - def key(self, char, event): - if char in (Wkeys.leftarrowkey, Wkeys.rightarrowkey): - sel = self.getselection() - sel.reverse() - self.setdrawingmode(0) - for index in sel: - self.fold(index, char == Wkeys.rightarrowkey) - self.setdrawingmode(1) - else: - W.List.key(self, char, event) - - def rollover(self, (x, y), onoff): - if onoff: - if self.incolumn((x, y)): - W.SetCursor('hmover') - else: - W.SetCursor('arrow') - - def inarrow(self, (x, y)): - cl, ct, cr, cb = self._list.LRect((0, 0)) - l, t, r, b = self._bounds - if (x - cl) < 16: - cellheight = cb - ct - index = (y - ct) / cellheight - if index < len(self.items): - return 1, index - return None, None - - def incolumn(self, (x, y)): - l, t, r, b = self._list.LRect((0, 0)) - abscol = l + self.col - return abs(abscol - x) < 3 - - def trackcolumn(self, (x, y)): - from Carbon import Qd, QuickDraw, Evt - self.SetPort() - l, t, r, b = self._bounds - bounds = l, t, r, b = l + 1, t + 1, r - 16, b - 1 - abscol = l + self.col - mincol = l + self.mincol - maxcol = r - 10 - diff = abscol - x - Qd.PenPat('\000\377\000\377\000\377\000\377') - Qd.PenMode(QuickDraw.srcXor) - rect = abscol - 1, t, abscol, b - Qd.PaintRect(rect) - lastpoint = (x, y) - newcol = -1 - #W.SetCursor('fist') - while Evt.Button(): - Evt.WaitNextEvent(0, 1, None) # needed for OSX - (x, y) = Evt.GetMouse() - if (x, y) <> lastpoint: - newcol = x + diff - newcol = max(newcol, mincol) - newcol = min(newcol, maxcol) - Qd.PaintRect(rect) - rect = newcol - 1, t, newcol, b - Qd.PaintRect(rect) - lastpoint = (x, y) - Qd.PaintRect(rect) - Qd.PenPat(Qd.GetQDGlobalsBlack()) - Qd.PenNormal() - if newcol > 0 and newcol <> abscol: - self.setcolumn(newcol - l) - - def click(self, point, modifiers): - if point == (-1, -1): # gross. - W.List.click(self, point ,modifiers) - return - hit, index = self.inarrow(point) - if hit: - (key, value, arrow, indent) = self.items[index] - self.fold(index, arrow == 1) - elif self.incolumn(point): - self.trackcolumn(point) - else: - W.List.click(self, point, modifiers) - - # for W.List.key - def findmatch(self, tag): - lower = string.lower - items = self.items - taglen = len(tag) - match = '\377' * 100 - match_i = -1 - for i in range(len(items)): - item = lower(str(items[i][0])) - if tag <= item < match: - match = item - match_i = i - if match_i >= 0: - return match_i - else: - return len(items) - 1 - - def close(self): - if self.closechildren: - for window in self.children: - window.close() - self.children = [] - W.List.close(self) - - def fold(self, index, onoff): - (key, value, arrow, indent) = self.items[index] - if arrow == 0 or (onoff and arrow == 2) or (not onoff and arrow == 1): - return - W.SetCursor('watch') - topcell = self.gettopcell() - if onoff: - self[index] = (key, value, 4, indent) - self.setdrawingmode(0) - self[index+1:index+1] = self.unpack(value, indent + 1) - self[index] = (key, value, 2, indent) - else: - self[index] = (key, value, 3, indent) - self.setdrawingmode(0) - count = 0 - for i in range(index + 1, len(self.items)): - (dummy, dummy, dummy, subindent) = self.items[i] - if subindent <= indent: - break - count = count + 1 - self[index+1:index+1+count] = [] - self[index] = (key, value, 1, indent) - maxindent = self.getmaxindent() - if maxindent <> self.lastmaxindent: - newabsindent = self.col + (maxindent - self.lastmaxindent) * self.indent - if newabsindent >= self.mincol: - self.setcolumn(newabsindent) - self.lastmaxindent = maxindent - self.settopcell(topcell) - self.setdrawingmode(1) - - def unfoldobjects(self, objects): - for obj in objects: - try: - index = self.items.index(obj) - except ValueError: - pass - else: - self.fold(index, 1) - - def getunfoldedobjects(self): - curindent = 0 - objects = [] - for index in range(len(self.items)): - (key, value, arrow, indent) = self.items[index] - if indent > curindent: - (k, v, a, i) = self.items[index - 1] - objects.append((k, v, 1, i)) - curindent = indent - elif indent < curindent: - curindent = indent - return objects - - def listhit(self, isdbl): - if isdbl: - self.openselection() - - def openselection(self): - import os - sel = self.getselection() - for index in sel: - (key, value, arrow, indent) = self[index] - if arrow: - self.children.append(Browser(value)) - elif type(value) == types.StringType and '\0' not in value: - editor = self._parentwindow.parent.getscript(value) - if editor: - editor.select() - return - elif os.path.exists(value) and os.path.isfile(value): - if MacOS.GetCreatorAndType(value)[1] in ('TEXT', '\0\0\0\0'): - W.getapplication().openscript(value) - - def itemrepr(self, (key, value, arrow, indent), str = str, double_repr = double_repr, - arrows = arrows, pack = struct.pack): - arrow = arrows[arrow] - return arrow + pack('h', self.indent * indent) + self.colstr + \ - double_repr(key, value, 1) - - def getmaxindent(self, max = max): - maxindent = 0 - for item in self.items: - maxindent = max(maxindent, item[3]) - return maxindent - - def domenu_copy(self, *args): - sel = self.getselectedobjects() - selitems = [] - for key, value, dummy, dummy in sel: - selitems.append(double_repr(key, value)) - text = string.join(selitems, '\r') - if text: - from Carbon import Scrap - if hasattr(Scrap, 'PutScrap'): - Scrap.ZeroScrap() - Scrap.PutScrap('TEXT', text) - else: - Scrap.ClearCurrentScrap() - sc = Scrap.GetCurrentScrap() - sc.PutScrapFlavor('TEXT', 0, text) - - def listDefDraw(self, selected, cellRect, theCell, - dataOffset, dataLen, theList): - self.myDrawCell(0, selected, cellRect, theCell, - dataOffset, dataLen, theList) - - def listDefHighlight(self, selected, cellRect, theCell, - dataOffset, dataLen, theList): - self.myDrawCell(1, selected, cellRect, theCell, - dataOffset, dataLen, theList) - - def myDrawCell(self, onlyHilite, selected, cellRect, theCell, - dataOffset, dataLen, theList): - savedPort = Qd.GetPort() - Qd.SetPort(theList.GetListPort()) - savedClip = Qd.NewRgn() - Qd.GetClip(savedClip) - Qd.ClipRect(cellRect) - savedPenState = Qd.GetPenState() - Qd.PenNormal() - - l, t, r, b = cellRect - - if not onlyHilite: - Qd.EraseRect(cellRect) - - ascent, descent, leading, size, hm = Fm.FontMetrics() - linefeed = ascent + descent + leading - - if dataLen >= 6: - data = theList.LGetCell(dataLen, theCell) - iconId, indent, tab = struct.unpack("hhh", data[:6]) - try: - key, value = data[6:].split("\t", 1) - except ValueError: - # bogus data, at least don't crash. - indent = 0 - tab = 0 - iconId = 0 - key = "" - value = data[6:] - - if iconId: - try: - theIcon = Icn.GetCIcon(iconId) - except Icn.Error: - pass - else: - rect = (0, 0, 16, 16) - rect = Qd.OffsetRect(rect, l, t) - rect = Qd.OffsetRect(rect, 0, (theList.cellSize[1] - (rect[3] - rect[1])) / 2) - Icn.PlotCIcon(rect, theIcon) - - if len(key) >= 0: - cl, ct, cr, cb = cellRect - vl, vt, vr, vb = self._viewbounds - cl = vl + PICTWIDTH + indent - cr = vl + tab - if cr > vr: - cr = vr - if cl < cr: - drawTextCell(key, (cl, ct, cr, cb), ascent, theList) - cl = vl + tab - cr = vr - if cl < cr: - drawTextCell(value, (cl, ct, cr, cb), ascent, theList) - #elif dataLen != 0: - # drawTextCell("???", 3, cellRect, ascent, theList) - else: - return # we have bogus data - - # draw nice dotted line - l, t, r, b = cellRect - l = self._viewbounds[0] + tab - r = l + 1; - if not (theList.cellSize[1] & 0x01) or (t & 0x01): - myPat = "\xff\x00\xff\x00\xff\x00\xff\x00" - else: - myPat = "\x00\xff\x00\xff\x00\xff\x00\xff" - Qd.PenPat(myPat) - Qd.PenMode(QuickDraw.srcCopy) - Qd.PaintRect((l, t, r, b)) - Qd.PenNormal() - - if selected or onlyHilite: - l, t, r, b = cellRect - l = self._viewbounds[0] + PICTWIDTH - r = self._viewbounds[2] - Qd.PenMode(hilitetransfermode) - Qd.PaintRect((l, t, r, b)) - - # restore graphics environment - Qd.SetPort(savedPort) - Qd.SetClip(savedClip) - Qd.DisposeRgn(savedClip) - Qd.SetPenState(savedPenState) + + def __init__(self, possize, object = None, col = 100, closechildren = 0): + W.List.__init__(self, possize, callback = self.listhit) + self.object = (None,) + self.indent = 16 + self.lastmaxindent = 0 + self.closechildren = closechildren + self.children = [] + self.mincol = 64 + self.setcolumn(col) + self.bind('return', self.openselection) + self.bind('enter', self.openselection) + if object is not None: + self.set(object) + + def set(self, object): + if self.object[0] is not object: + self.object = object, + self[:] = self.unpack(object, 0) + elif self._parentwindow is not None and self._parentwindow.wid: + self.update() + + def unpack(self, object, indent): + return unpack_object(object, indent) + + def update(self): + # for now... + W.SetCursor('watch') + self.setdrawingmode(0) + sel = self.getselectedobjects() + fold = self.getunfoldedobjects() + topcell = self.gettopcell() + self[:] = self.unpack(self.object[0], 0) + self.unfoldobjects(fold) + self.setselectedobjects(sel) + self.settopcell(topcell) + self.setdrawingmode(1) + + def setcolumn(self, col): + self.col = col + self.colstr = struct.pack('h', col) + if self._list: + sel = self.getselection() + self.setitems(self.items) + self.setselection(sel) + + def key(self, char, event): + if char in (Wkeys.leftarrowkey, Wkeys.rightarrowkey): + sel = self.getselection() + sel.reverse() + self.setdrawingmode(0) + for index in sel: + self.fold(index, char == Wkeys.rightarrowkey) + self.setdrawingmode(1) + else: + W.List.key(self, char, event) + + def rollover(self, (x, y), onoff): + if onoff: + if self.incolumn((x, y)): + W.SetCursor('hmover') + else: + W.SetCursor('arrow') + + def inarrow(self, (x, y)): + cl, ct, cr, cb = self._list.LRect((0, 0)) + l, t, r, b = self._bounds + if (x - cl) < 16: + cellheight = cb - ct + index = (y - ct) / cellheight + if index < len(self.items): + return 1, index + return None, None + + def incolumn(self, (x, y)): + l, t, r, b = self._list.LRect((0, 0)) + abscol = l + self.col + return abs(abscol - x) < 3 + + def trackcolumn(self, (x, y)): + from Carbon import Qd, QuickDraw, Evt + self.SetPort() + l, t, r, b = self._bounds + bounds = l, t, r, b = l + 1, t + 1, r - 16, b - 1 + abscol = l + self.col + mincol = l + self.mincol + maxcol = r - 10 + diff = abscol - x + Qd.PenPat('\000\377\000\377\000\377\000\377') + Qd.PenMode(QuickDraw.srcXor) + rect = abscol - 1, t, abscol, b + Qd.PaintRect(rect) + lastpoint = (x, y) + newcol = -1 + #W.SetCursor('fist') + while Evt.Button(): + Evt.WaitNextEvent(0, 1, None) # needed for OSX + (x, y) = Evt.GetMouse() + if (x, y) <> lastpoint: + newcol = x + diff + newcol = max(newcol, mincol) + newcol = min(newcol, maxcol) + Qd.PaintRect(rect) + rect = newcol - 1, t, newcol, b + Qd.PaintRect(rect) + lastpoint = (x, y) + Qd.PaintRect(rect) + Qd.PenPat(Qd.GetQDGlobalsBlack()) + Qd.PenNormal() + if newcol > 0 and newcol <> abscol: + self.setcolumn(newcol - l) + + def click(self, point, modifiers): + if point == (-1, -1): # gross. + W.List.click(self, point ,modifiers) + return + hit, index = self.inarrow(point) + if hit: + (key, value, arrow, indent) = self.items[index] + self.fold(index, arrow == 1) + elif self.incolumn(point): + self.trackcolumn(point) + else: + W.List.click(self, point, modifiers) + + # for W.List.key + def findmatch(self, tag): + lower = string.lower + items = self.items + taglen = len(tag) + match = '\377' * 100 + match_i = -1 + for i in range(len(items)): + item = lower(str(items[i][0])) + if tag <= item < match: + match = item + match_i = i + if match_i >= 0: + return match_i + else: + return len(items) - 1 + + def close(self): + if self.closechildren: + for window in self.children: + window.close() + self.children = [] + W.List.close(self) + + def fold(self, index, onoff): + (key, value, arrow, indent) = self.items[index] + if arrow == 0 or (onoff and arrow == 2) or (not onoff and arrow == 1): + return + W.SetCursor('watch') + topcell = self.gettopcell() + if onoff: + self[index] = (key, value, 4, indent) + self.setdrawingmode(0) + self[index+1:index+1] = self.unpack(value, indent + 1) + self[index] = (key, value, 2, indent) + else: + self[index] = (key, value, 3, indent) + self.setdrawingmode(0) + count = 0 + for i in range(index + 1, len(self.items)): + (dummy, dummy, dummy, subindent) = self.items[i] + if subindent <= indent: + break + count = count + 1 + self[index+1:index+1+count] = [] + self[index] = (key, value, 1, indent) + maxindent = self.getmaxindent() + if maxindent <> self.lastmaxindent: + newabsindent = self.col + (maxindent - self.lastmaxindent) * self.indent + if newabsindent >= self.mincol: + self.setcolumn(newabsindent) + self.lastmaxindent = maxindent + self.settopcell(topcell) + self.setdrawingmode(1) + + def unfoldobjects(self, objects): + for obj in objects: + try: + index = self.items.index(obj) + except ValueError: + pass + else: + self.fold(index, 1) + + def getunfoldedobjects(self): + curindent = 0 + objects = [] + for index in range(len(self.items)): + (key, value, arrow, indent) = self.items[index] + if indent > curindent: + (k, v, a, i) = self.items[index - 1] + objects.append((k, v, 1, i)) + curindent = indent + elif indent < curindent: + curindent = indent + return objects + + def listhit(self, isdbl): + if isdbl: + self.openselection() + + def openselection(self): + import os + sel = self.getselection() + for index in sel: + (key, value, arrow, indent) = self[index] + if arrow: + self.children.append(Browser(value)) + elif type(value) == types.StringType and '\0' not in value: + editor = self._parentwindow.parent.getscript(value) + if editor: + editor.select() + return + elif os.path.exists(value) and os.path.isfile(value): + if MacOS.GetCreatorAndType(value)[1] in ('TEXT', '\0\0\0\0'): + W.getapplication().openscript(value) + + def itemrepr(self, (key, value, arrow, indent), str = str, double_repr = double_repr, + arrows = arrows, pack = struct.pack): + arrow = arrows[arrow] + return arrow + pack('h', self.indent * indent) + self.colstr + \ + double_repr(key, value, 1) + + def getmaxindent(self, max = max): + maxindent = 0 + for item in self.items: + maxindent = max(maxindent, item[3]) + return maxindent + + def domenu_copy(self, *args): + sel = self.getselectedobjects() + selitems = [] + for key, value, dummy, dummy in sel: + selitems.append(double_repr(key, value)) + text = string.join(selitems, '\r') + if text: + from Carbon import Scrap + if hasattr(Scrap, 'PutScrap'): + Scrap.ZeroScrap() + Scrap.PutScrap('TEXT', text) + else: + Scrap.ClearCurrentScrap() + sc = Scrap.GetCurrentScrap() + sc.PutScrapFlavor('TEXT', 0, text) + + def listDefDraw(self, selected, cellRect, theCell, + dataOffset, dataLen, theList): + self.myDrawCell(0, selected, cellRect, theCell, + dataOffset, dataLen, theList) + + def listDefHighlight(self, selected, cellRect, theCell, + dataOffset, dataLen, theList): + self.myDrawCell(1, selected, cellRect, theCell, + dataOffset, dataLen, theList) + + def myDrawCell(self, onlyHilite, selected, cellRect, theCell, + dataOffset, dataLen, theList): + savedPort = Qd.GetPort() + Qd.SetPort(theList.GetListPort()) + savedClip = Qd.NewRgn() + Qd.GetClip(savedClip) + Qd.ClipRect(cellRect) + savedPenState = Qd.GetPenState() + Qd.PenNormal() + + l, t, r, b = cellRect + + if not onlyHilite: + Qd.EraseRect(cellRect) + + ascent, descent, leading, size, hm = Fm.FontMetrics() + linefeed = ascent + descent + leading + + if dataLen >= 6: + data = theList.LGetCell(dataLen, theCell) + iconId, indent, tab = struct.unpack("hhh", data[:6]) + try: + key, value = data[6:].split("\t", 1) + except ValueError: + # bogus data, at least don't crash. + indent = 0 + tab = 0 + iconId = 0 + key = "" + value = data[6:] + + if iconId: + try: + theIcon = Icn.GetCIcon(iconId) + except Icn.Error: + pass + else: + rect = (0, 0, 16, 16) + rect = Qd.OffsetRect(rect, l, t) + rect = Qd.OffsetRect(rect, 0, (theList.cellSize[1] - (rect[3] - rect[1])) / 2) + Icn.PlotCIcon(rect, theIcon) + + if len(key) >= 0: + cl, ct, cr, cb = cellRect + vl, vt, vr, vb = self._viewbounds + cl = vl + PICTWIDTH + indent + cr = vl + tab + if cr > vr: + cr = vr + if cl < cr: + drawTextCell(key, (cl, ct, cr, cb), ascent, theList) + cl = vl + tab + cr = vr + if cl < cr: + drawTextCell(value, (cl, ct, cr, cb), ascent, theList) + #elif dataLen != 0: + # drawTextCell("???", 3, cellRect, ascent, theList) + else: + return # we have bogus data + + # draw nice dotted line + l, t, r, b = cellRect + l = self._viewbounds[0] + tab + r = l + 1; + if not (theList.cellSize[1] & 0x01) or (t & 0x01): + myPat = "\xff\x00\xff\x00\xff\x00\xff\x00" + else: + myPat = "\x00\xff\x00\xff\x00\xff\x00\xff" + Qd.PenPat(myPat) + Qd.PenMode(QuickDraw.srcCopy) + Qd.PaintRect((l, t, r, b)) + Qd.PenNormal() + + if selected or onlyHilite: + l, t, r, b = cellRect + l = self._viewbounds[0] + PICTWIDTH + r = self._viewbounds[2] + Qd.PenMode(hilitetransfermode) + Qd.PaintRect((l, t, r, b)) + + # restore graphics environment + Qd.SetPort(savedPort) + Qd.SetClip(savedClip) + Qd.DisposeRgn(savedClip) + Qd.SetPenState(savedPenState) class Browser: - - def __init__(self, object = None, title = None, closechildren = 0): - if hasattr(object, '__name__'): - name = object.__name__ - else: - name = '' - if title is None: - title = 'Object browser' - if name: - title = title + ': ' + name - self.w = w = W.Window((300, 400), title, minsize = (100, 100)) - w.info = W.TextBox((18, 8, -70, 15)) - w.updatebutton = W.BevelButton((-64, 4, 50, 16), 'Update', self.update) - w.browser = BrowserWidget((-1, 24, 1, -14), None) - w.bind('cmdu', w.updatebutton.push) - w.open() - self.set(object, name) - - def close(self): - if self.w.wid: - self.w.close() - - def set(self, object, name = ''): - W.SetCursor('watch') - tp = type(object).__name__ - try: - length = len(object) - except: - length = -1 - if not name and hasattr(object, '__name__'): - name = object.__name__ - if name: - info = name + ': ' + tp - else: - info = tp - if length >= 0: - if length == 1: - info = info + ' (%d element)' % length - else: - info = info + ' (%d elements)' % length - self.w.info.set(info) - self.w.browser.set(object) - - def update(self): - self.w.browser.update() + + def __init__(self, object = None, title = None, closechildren = 0): + if hasattr(object, '__name__'): + name = object.__name__ + else: + name = '' + if title is None: + title = 'Object browser' + if name: + title = title + ': ' + name + self.w = w = W.Window((300, 400), title, minsize = (100, 100)) + w.info = W.TextBox((18, 8, -70, 15)) + w.updatebutton = W.BevelButton((-64, 4, 50, 16), 'Update', self.update) + w.browser = BrowserWidget((-1, 24, 1, -14), None) + w.bind('cmdu', w.updatebutton.push) + w.open() + self.set(object, name) + + def close(self): + if self.w.wid: + self.w.close() + + def set(self, object, name = ''): + W.SetCursor('watch') + tp = type(object).__name__ + try: + length = len(object) + except: + length = -1 + if not name and hasattr(object, '__name__'): + name = object.__name__ + if name: + info = name + ': ' + tp + else: + info = tp + if length >= 0: + if length == 1: + info = info + ' (%d element)' % length + else: + info = info + ' (%d elements)' % length + self.w.info.set(info) + self.w.browser.set(object) + + def update(self): + self.w.browser.update() SIMPLE_TYPES = ( - type(None), - int, - long, - float, - complex, - str, - unicode, + type(None), + int, + long, + float, + complex, + str, + unicode, ) def get_ivars(obj): - """Return a list the names of all (potential) instance variables.""" - # __mro__ recipe from Guido - slots = {} - # old-style C objects - if hasattr(obj, "__members__"): - for name in obj.__members__: - slots[name] = None - if hasattr(obj, "__methods__"): - for name in obj.__methods__: - slots[name] = None - # generic type - if hasattr(obj, "__dict__"): - slots.update(obj.__dict__) - cls = type(obj) - if hasattr(cls, "__mro__"): - # new-style class, use descriptors - for base in cls.__mro__: - for name, value in base.__dict__.items(): - # XXX using callable() is a heuristic which isn't 100% - # foolproof. - if hasattr(value, "__get__") and not callable(value): - slots[name] = None - if "__dict__" in slots: - del slots["__dict__"] - slots = slots.keys() - slots.sort() - return slots + """Return a list the names of all (potential) instance variables.""" + # __mro__ recipe from Guido + slots = {} + # old-style C objects + if hasattr(obj, "__members__"): + for name in obj.__members__: + slots[name] = None + if hasattr(obj, "__methods__"): + for name in obj.__methods__: + slots[name] = None + # generic type + if hasattr(obj, "__dict__"): + slots.update(obj.__dict__) + cls = type(obj) + if hasattr(cls, "__mro__"): + # new-style class, use descriptors + for base in cls.__mro__: + for name, value in base.__dict__.items(): + # XXX using callable() is a heuristic which isn't 100% + # foolproof. + if hasattr(value, "__get__") and not callable(value): + slots[name] = None + if "__dict__" in slots: + del slots["__dict__"] + slots = slots.keys() + slots.sort() + return slots def unpack_object(object, indent = 0): - tp = type(object) - if isinstance(object, SIMPLE_TYPES) and object is not None: - raise TypeError, "can't browse simple type: %s" % tp.__name__ - elif isinstance(object, dict): - return unpack_dict(object, indent) - elif isinstance(object, (tuple, list)): - return unpack_sequence(object, indent) - elif isinstance(object, types.ModuleType): - return unpack_dict(object.__dict__, indent) - else: - return unpack_other(object, indent) + tp = type(object) + if isinstance(object, SIMPLE_TYPES) and object is not None: + raise TypeError, "can't browse simple type: %s" % tp.__name__ + elif isinstance(object, dict): + return unpack_dict(object, indent) + elif isinstance(object, (tuple, list)): + return unpack_sequence(object, indent) + elif isinstance(object, types.ModuleType): + return unpack_dict(object.__dict__, indent) + else: + return unpack_other(object, indent) def unpack_sequence(seq, indent = 0): - return [(i, v, not isinstance(v, SIMPLE_TYPES), indent) - for i, v in enumerate(seq)] + return [(i, v, not isinstance(v, SIMPLE_TYPES), indent) + for i, v in enumerate(seq)] def unpack_dict(dict, indent = 0): - items = dict.items() - return pack_items(items, indent) + items = dict.items() + return pack_items(items, indent) def unpack_instance(inst, indent = 0): - if hasattr(inst, '__pybrowse_unpack__'): - return unpack_object(inst.__pybrowse_unpack__(), indent) - else: - items = [('__class__', inst.__class__)] + inst.__dict__.items() - return pack_items(items, indent) + if hasattr(inst, '__pybrowse_unpack__'): + return unpack_object(inst.__pybrowse_unpack__(), indent) + else: + items = [('__class__', inst.__class__)] + inst.__dict__.items() + return pack_items(items, indent) def unpack_class(clss, indent = 0): - items = [('__bases__', clss.__bases__), ('__name__', clss.__name__)] + clss.__dict__.items() - return pack_items(items, indent) + items = [('__bases__', clss.__bases__), ('__name__', clss.__name__)] + clss.__dict__.items() + return pack_items(items, indent) def unpack_other(object, indent = 0): - attrs = get_ivars(object) - items = [] - for attr in attrs: - try: - value = getattr(object, attr) - except: - pass - else: - items.append((attr, value)) - return pack_items(items, indent) + attrs = get_ivars(object) + items = [] + for attr in attrs: + try: + value = getattr(object, attr) + except: + pass + else: + items.append((attr, value)) + return pack_items(items, indent) def pack_items(items, indent = 0): - items = [(k, v, not isinstance(v, SIMPLE_TYPES), indent) - for k, v in items] - return tuple_caselesssort(items) + items = [(k, v, not isinstance(v, SIMPLE_TYPES), indent) + for k, v in items] + return tuple_caselesssort(items) def caselesssort(alist): - """Return a sorted copy of a list. If there are only strings in the list, - it will not consider case""" - - try: - # turn ['FOO', 'aaBc', 'ABcD'] into [('foo', 'FOO'), ('aabc', 'aaBc'), ('abcd', 'ABcD')], if possible - tupledlist = map(lambda item, lower = string.lower: (lower(item), item), alist) - except TypeError: - # at least one element in alist is not a string, proceed the normal way... - alist = alist[:] - alist.sort() - return alist - else: - tupledlist.sort() - # turn [('aabc', 'aaBc'), ('abcd', 'ABcD'), ('foo', 'FOO')] into ['aaBc', 'ABcD', 'FOO'] - return map(lambda x: x[1], tupledlist) + """Return a sorted copy of a list. If there are only strings in the list, + it will not consider case""" -def tuple_caselesssort(items): - try: - tupledlist = map(lambda tuple, lower = string.lower: (lower(tuple[0]), tuple), items) - except (AttributeError, TypeError): - items = items[:] - items.sort() - return items - else: - tupledlist.sort() - return map(lambda (low, tuple): tuple, tupledlist) + try: + # turn ['FOO', 'aaBc', 'ABcD'] into [('foo', 'FOO'), ('aabc', 'aaBc'), ('abcd', 'ABcD')], if possible + tupledlist = map(lambda item, lower = string.lower: (lower(item), item), alist) + except TypeError: + # at least one element in alist is not a string, proceed the normal way... + alist = alist[:] + alist.sort() + return alist + else: + tupledlist.sort() + # turn [('aabc', 'aaBc'), ('abcd', 'ABcD'), ('foo', 'FOO')] into ['aaBc', 'ABcD', 'FOO'] + return map(lambda x: x[1], tupledlist) +def tuple_caselesssort(items): + try: + tupledlist = map(lambda tuple, lower = string.lower: (lower(tuple[0]), tuple), items) + except (AttributeError, TypeError): + items = items[:] + items.sort() + return items + else: + tupledlist.sort() + return map(lambda (low, tuple): tuple, tupledlist) diff --git a/Mac/Tools/IDE/PyConsole.py b/Mac/Tools/IDE/PyConsole.py index 6f398d1..b8d6489 100644 --- a/Mac/Tools/IDE/PyConsole.py +++ b/Mac/Tools/IDE/PyConsole.py @@ -14,424 +14,424 @@ import EasyDialogs import PyInteractive if not hasattr(sys, 'ps1'): - sys.ps1 = '>>> ' + sys.ps1 = '>>> ' if not hasattr(sys, 'ps2'): - sys.ps2 = '... ' + sys.ps2 = '... ' -def inspect(foo): # JJS 1/25/99 - "Launch the browser on the given object. This is a general built-in function." - import PyBrowser - PyBrowser.Browser(foo) +def inspect(foo): # JJS 1/25/99 + "Launch the browser on the given object. This is a general built-in function." + import PyBrowser + PyBrowser.Browser(foo) 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__ - self._namespace['inspect'] = inspect # JJS 1/25/99 - - 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" - if 'inspect' not in dict.keys(): dict['inspect'] = inspect # JJS 1/25/99 - self._namespace = dict - - def open(self): - import __main__ - W.EditText.open(self) - self.write('Python %s\n' % sys.version) - self.write('Type "copyright", "credits" or "license" for more information.\n') - self.write('MacPython IDE %s\n' % __main__.__version__) - 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 Wkeys.arrowkeys: - if char not in Wkeys.navigationkeys: - self.checkselection() - if char == Wkeys.enterkey: - char = Wkeys.returnkey - selstart, selend = self.getselection() - if char == Wkeys.backspacekey: - if selstart <= (self._inputstart - (selstart <> selend)): - return - self.ted.WEKey(ord(char), modifiers) - if char not in Wkeys.navigationkeys: - self.changed = 1 - if char not in Wkeys.scrollkeys: - self.selchanged = 1 - self.updatescrollbars() - if char == Wkeys.returnkey: - text = self.get()[self._inputstart:selstart] - text = string.join(string.split(text, "\r"), "\n") - if hasattr(MacOS, 'EnableAppswitch'): - saveyield = MacOS.EnableAppswitch(0) - self._scriptDone = False - if sys.platform == "darwin": - # see identical construct in PyEdit.py - from threading import Thread - t = Thread(target=self._userCancelledMonitor, - name="UserCancelledMonitor") - t.start() - try: - self.pyinteractive.executeline(text, self, self._namespace) - finally: - self._scriptDone = True - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(saveyield) - selstart, selend = self.getselection() - self._inputstart = selstart - - def _userCancelledMonitor(self): - # XXX duplicate code from PyEdit.py - import time, os - from signal import SIGINT - from Carbon import Evt - while not self._scriptDone: - if Evt.CheckEventQueueForUserCancel(): - # Send a SIGINT signal to ourselves. - # This gets delivered to the main thread, - # cancelling the running script. - os.kill(os.getpid(), SIGINT) - break - time.sleep(0.25) - - def domenu_save_as(self, *args): - filename = EasyDialogs.AskFileForSave(message='Save console text as:', - savedFileName='console.txt') - if not filename: - return - f = open(filename, 'wb') - f.write(self.get()) - f.close() - MacOS.SetCreatorAndType(filename, 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() - try: - self.ted.WEInsert(stuff, None, None) - finally: - self._buf = "" - selstart, selend = self.getselection() - self._inputstart = selstart - self.ted.WEClearUndo() - self.updatescrollbars() - if self._parentwindow.wid.GetWindowPort().QDIsPortBuffered(): - self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None) - - 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) + + 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__ + self._namespace['inspect'] = inspect # JJS 1/25/99 + + 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" + if 'inspect' not in dict.keys(): dict['inspect'] = inspect # JJS 1/25/99 + self._namespace = dict + + def open(self): + import __main__ + W.EditText.open(self) + self.write('Python %s\n' % sys.version) + self.write('Type "copyright", "credits" or "license" for more information.\n') + self.write('MacPython IDE %s\n' % __main__.__version__) + 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 Wkeys.arrowkeys: + if char not in Wkeys.navigationkeys: + self.checkselection() + if char == Wkeys.enterkey: + char = Wkeys.returnkey + selstart, selend = self.getselection() + if char == Wkeys.backspacekey: + if selstart <= (self._inputstart - (selstart <> selend)): + return + self.ted.WEKey(ord(char), modifiers) + if char not in Wkeys.navigationkeys: + self.changed = 1 + if char not in Wkeys.scrollkeys: + self.selchanged = 1 + self.updatescrollbars() + if char == Wkeys.returnkey: + text = self.get()[self._inputstart:selstart] + text = string.join(string.split(text, "\r"), "\n") + if hasattr(MacOS, 'EnableAppswitch'): + saveyield = MacOS.EnableAppswitch(0) + self._scriptDone = False + if sys.platform == "darwin": + # see identical construct in PyEdit.py + from threading import Thread + t = Thread(target=self._userCancelledMonitor, + name="UserCancelledMonitor") + t.start() + try: + self.pyinteractive.executeline(text, self, self._namespace) + finally: + self._scriptDone = True + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(saveyield) + selstart, selend = self.getselection() + self._inputstart = selstart + + def _userCancelledMonitor(self): + # XXX duplicate code from PyEdit.py + import time, os + from signal import SIGINT + from Carbon import Evt + while not self._scriptDone: + if Evt.CheckEventQueueForUserCancel(): + # Send a SIGINT signal to ourselves. + # This gets delivered to the main thread, + # cancelling the running script. + os.kill(os.getpid(), SIGINT) + break + time.sleep(0.25) + + def domenu_save_as(self, *args): + filename = EasyDialogs.AskFileForSave(message='Save console text as:', + savedFileName='console.txt') + if not filename: + return + f = open(filename, 'wb') + f.write(self.get()) + f.close() + MacOS.SetCreatorAndType(filename, 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() + try: + self.ted.WEInsert(stuff, None, None) + finally: + self._buf = "" + selstart, selend = self.getselection() + self._inputstart = selstart + self.ted.WEClearUndo() + self.updatescrollbars() + if self._parentwindow.wid.GetWindowPort().QDIsPortBuffered(): + self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None) + + 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)), - tabsettings = (32, 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, tabsettings = tabsettings) - 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([("Clear window", self.clearbuffer), ("Font settings\xc9", self.dofontsettings), - ["Namespace"] + namespacelist, ("Browse namespace\xc9", 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(3) - menu = self.namespacemenu.menu.bar.menus[submenuid] - menu.menu.CheckMenuItem(i + 1, 1) - - def browsenamespace(self): - import PyBrowser, W - W.SetCursor('watch') - PyBrowser.Browser(self.consoletext._namespace, self.consoletext._namespace["__name__"]) - - def clearbuffer(self): - from Carbon import Res - self.consoletext.ted.WEUseText(Res.Resource('')) - self.consoletext.write(sys.ps1) - self.consoletext.flush() - - def getnamespacelist(self): - import os - 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 - settings = FontSettings.FontDialog(self.consoletext.getfontsettings(), - self.consoletext.gettabsettings()) - if settings: - fontsettings, tabsettings = settings - self.consoletext.setfontsettings(fontsettings) - self.consoletext.settabsettings(tabsettings) - - 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.console.tabsettings = self.consoletext.gettabsettings() - prefs.save() - - def getselectedtext(self): - return self.consoletext.getselectedtext() - + + def __init__(self, bounds, show = 1, fontsettings = ("Monaco", 0, 9, (0, 0, 0)), + tabsettings = (32, 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, tabsettings = tabsettings) + 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([("Clear window", self.clearbuffer), ("Font settings\xc9", self.dofontsettings), + ["Namespace"] + namespacelist, ("Browse namespace\xc9", 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(3) + menu = self.namespacemenu.menu.bar.menus[submenuid] + menu.menu.CheckMenuItem(i + 1, 1) + + def browsenamespace(self): + import PyBrowser, W + W.SetCursor('watch') + PyBrowser.Browser(self.consoletext._namespace, self.consoletext._namespace["__name__"]) + + def clearbuffer(self): + from Carbon import Res + self.consoletext.ted.WEUseText(Res.Resource('')) + self.consoletext.write(sys.ps1) + self.consoletext.flush() + + def getnamespacelist(self): + import os + 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 + settings = FontSettings.FontDialog(self.consoletext.getfontsettings(), + self.consoletext.gettabsettings()) + if settings: + fontsettings, tabsettings = settings + self.consoletext.setfontsettings(fontsettings) + self.consoletext.settabsettings(tabsettings) + + 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.console.tabsettings = self.consoletext.gettabsettings() + prefs.save() + + def getselectedtext(self): + return self.consoletext.getselectedtext() + class OutputTextWidget(W.EditText): - - def domenu_save_as(self, *args): - title = self._parentwindow.gettitle() - filename = EasyDialogs.AskFileForSave(message='Save %s text as:' % title, - savedFileName=title + '.txt') - if not filename: - return - f = open(filename, 'wb') - f.write(self.get()) - f.close() - MacOS.SetCreatorAndType(filename, W._signature, 'TEXT') - - def domenu_cut(self, *args): - self.domenu_copy(*args) - - def domenu_clear(self, *args): - self.set('') + + def domenu_save_as(self, *args): + title = self._parentwindow.gettitle() + filename = EasyDialogs.AskFileForSave(message='Save %s text as:' % title, + savedFileName=title + '.txt') + if not filename: + return + f = open(filename, 'wb') + f.write(self.get()) + f.close() + MacOS.SetCreatorAndType(filename, W._signature, 'TEXT') + + def domenu_cut(self, *args): + self.domenu_copy(*args) + + def domenu_clear(self, *args): + self.set('') class PyOutput: - - def __init__(self, bounds, show = 1, fontsettings = ("Monaco", 0, 9, (0, 0, 0)), tabsettings = (32, 0)): - self.bounds = bounds - self.fontsettings = fontsettings - self.tabsettings = tabsettings - 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 - if show: - self.show() - - def setupwidgets(self): - self.w = W.Window(self.bounds, "Output", - minsize = (200, 100), - tabbable = 0) - self.w.outputtext = OutputTextWidget((-1, -1, -14, 1), inset = (6, 5), - fontsettings = self.fontsettings, tabsettings = self.tabsettings, readonly = 1) - menuitems = [("Clear window", self.clearbuffer), ("Font settings\xc9", self.dofontsettings)] - self.w.popupmenu = W.PopupMenu((-15, -1, 16, 16), menuitems) - - self.w._bary = W.Scrollbar((-15, 14, 16, -14), self.w.outputtext.vscroll, max = 32767) - self.w.bind("<close>", self.close) - self.w.bind("<activate>", self.activate) - - def write(self, text): - if hasattr(MacOS, 'EnableAppswitch'): - oldyield = MacOS.EnableAppswitch(-1) - try: - self._buf = self._buf + text - if '\n' in self._buf: - self.flush() - finally: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(oldyield) - - 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.WEFeatureFlag(WASTEconst.weFReadOnly, 0) - try: - self.w.outputtext.ted.WEInsert(stuff, None, None) - finally: - self._buf = "" - self.w.outputtext.updatescrollbars() - self.w.outputtext.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 1) - if self.w.wid.GetWindowPort().QDIsPortBuffered(): - self.w.wid.GetWindowPort().QDFlushPortBuffer(None) - - def show(self): - if self.closed: - if not self.w: - self.setupwidgets() - self.w.open() - self.w.outputtext.updatescrollbars() - self.closed = 0 - else: - self.w.show(1) - self.closed = 0 - self.w.select() - - def writeprefs(self): - if self.w is not None: - prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) - prefs.output.show = self.w.isvisible() - prefs.output.windowbounds = self.w.getbounds() - prefs.output.fontsettings = self.w.outputtext.getfontsettings() - prefs.output.tabsettings = self.w.outputtext.gettabsettings() - prefs.save() - - def dofontsettings(self): - import FontSettings - settings = FontSettings.FontDialog(self.w.outputtext.getfontsettings(), - self.w.outputtext.gettabsettings()) - if settings: - fontsettings, tabsettings = settings - self.w.outputtext.setfontsettings(fontsettings) - self.w.outputtext.settabsettings(tabsettings) - - def clearbuffer(self): - from Carbon import Res - self.w.outputtext.set('') - - def activate(self, onoff): - if onoff: - self.closed = 0 - - def close(self): - self.w.show(0) - self.closed = 1 - return -1 + + def __init__(self, bounds, show = 1, fontsettings = ("Monaco", 0, 9, (0, 0, 0)), tabsettings = (32, 0)): + self.bounds = bounds + self.fontsettings = fontsettings + self.tabsettings = tabsettings + 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 + if show: + self.show() + + def setupwidgets(self): + self.w = W.Window(self.bounds, "Output", + minsize = (200, 100), + tabbable = 0) + self.w.outputtext = OutputTextWidget((-1, -1, -14, 1), inset = (6, 5), + fontsettings = self.fontsettings, tabsettings = self.tabsettings, readonly = 1) + menuitems = [("Clear window", self.clearbuffer), ("Font settings\xc9", self.dofontsettings)] + self.w.popupmenu = W.PopupMenu((-15, -1, 16, 16), menuitems) + + self.w._bary = W.Scrollbar((-15, 14, 16, -14), self.w.outputtext.vscroll, max = 32767) + self.w.bind("<close>", self.close) + self.w.bind("<activate>", self.activate) + + def write(self, text): + if hasattr(MacOS, 'EnableAppswitch'): + oldyield = MacOS.EnableAppswitch(-1) + try: + self._buf = self._buf + text + if '\n' in self._buf: + self.flush() + finally: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(oldyield) + + 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.WEFeatureFlag(WASTEconst.weFReadOnly, 0) + try: + self.w.outputtext.ted.WEInsert(stuff, None, None) + finally: + self._buf = "" + self.w.outputtext.updatescrollbars() + self.w.outputtext.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 1) + if self.w.wid.GetWindowPort().QDIsPortBuffered(): + self.w.wid.GetWindowPort().QDFlushPortBuffer(None) + + def show(self): + if self.closed: + if not self.w: + self.setupwidgets() + self.w.open() + self.w.outputtext.updatescrollbars() + self.closed = 0 + else: + self.w.show(1) + self.closed = 0 + self.w.select() + + def writeprefs(self): + if self.w is not None: + prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) + prefs.output.show = self.w.isvisible() + prefs.output.windowbounds = self.w.getbounds() + prefs.output.fontsettings = self.w.outputtext.getfontsettings() + prefs.output.tabsettings = self.w.outputtext.gettabsettings() + prefs.save() + + def dofontsettings(self): + import FontSettings + settings = FontSettings.FontDialog(self.w.outputtext.getfontsettings(), + self.w.outputtext.gettabsettings()) + if settings: + fontsettings, tabsettings = settings + self.w.outputtext.setfontsettings(fontsettings) + self.w.outputtext.settabsettings(tabsettings) + + def clearbuffer(self): + from Carbon import Res + self.w.outputtext.set('') + + def activate(self, onoff): + if onoff: + self.closed = 0 + + def close(self): + self.w.show(0) + self.closed = 1 + return -1 class SimpleStdin: - - def readline(self): - import EasyDialogs - # A trick to make the input dialog box a bit more palatable - if hasattr(sys.stdout, '_buf'): - prompt = sys.stdout._buf - else: - prompt = "" - if not prompt: - prompt = "Stdin input:" - sys.stdout.flush() - rv = EasyDialogs.AskString(prompt) - if rv is None: - return "" - rv = rv + "\n" # readline should include line terminator - sys.stdout.write(rv) # echo user's reply - return rv + + def readline(self): + import EasyDialogs + # A trick to make the input dialog box a bit more palatable + if hasattr(sys.stdout, '_buf'): + prompt = sys.stdout._buf + else: + prompt = "" + if not prompt: + prompt = "Stdin input:" + sys.stdout.flush() + rv = EasyDialogs.AskString(prompt) + if rv is None: + return "" + rv = rv + "\n" # readline should include line terminator + sys.stdout.write(rv) # echo user's reply + return rv 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)) - if not hasattr(prefs.console, "tabsettings"): - prefs.console.tabsettings = (32, 0) - console = PyConsole(prefs.console.windowbounds, prefs.console.show, - prefs.console.fontsettings, prefs.console.tabsettings, 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)) + if not hasattr(prefs.console, "tabsettings"): + prefs.console.tabsettings = (32, 0) + console = PyConsole(prefs.console.windowbounds, prefs.console.show, + prefs.console.fontsettings, prefs.console.tabsettings, 1) def installoutput(defaultshow = 0, OutPutWindow = PyOutput): - global output - - # quick 'n' dirty std in emulation - sys.stdin = SimpleStdin() - - prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) - if not prefs.output or not hasattr(prefs.output, 'show'): - prefs.output.show = defaultshow - if not hasattr(prefs.output, "windowbounds"): - prefs.output.windowbounds = (450, 250) - if not hasattr(prefs.output, "fontsettings"): - prefs.output.fontsettings = ("Monaco", 0, 9, (0, 0, 0)) - if not hasattr(prefs.output, "tabsettings"): - prefs.output.tabsettings = (32, 0) - output = OutPutWindow(prefs.output.windowbounds, prefs.output.show, - prefs.output.fontsettings, prefs.output.tabsettings) + global output + + # quick 'n' dirty std in emulation + sys.stdin = SimpleStdin() + + prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) + if not prefs.output or not hasattr(prefs.output, 'show'): + prefs.output.show = defaultshow + if not hasattr(prefs.output, "windowbounds"): + prefs.output.windowbounds = (450, 250) + if not hasattr(prefs.output, "fontsettings"): + prefs.output.fontsettings = ("Monaco", 0, 9, (0, 0, 0)) + if not hasattr(prefs.output, "tabsettings"): + prefs.output.tabsettings = (32, 0) + output = OutPutWindow(prefs.output.windowbounds, prefs.output.show, + prefs.output.fontsettings, prefs.output.tabsettings) diff --git a/Mac/Tools/IDE/PyDebugger.py b/Mac/Tools/IDE/PyDebugger.py index 51ba753..5ee92d5 100644 --- a/Mac/Tools/IDE/PyDebugger.py +++ b/Mac/Tools/IDE/PyDebugger.py @@ -13,882 +13,882 @@ import MacOS _filenames = {} SIMPLE_TYPES = ( - types.NoneType, - types.IntType, - types.LongType, - types.FloatType, - types.ComplexType, - types.StringType + types.NoneType, + types.IntType, + types.LongType, + types.FloatType, + types.ComplexType, + types.StringType ) class Debugger(bdb.Bdb): - - def __init__(self, title = 'Debugger'): - bdb.Bdb.__init__(self) - self.closed = 1 - self.title = title - self.breaksviewer = None - self.reset() - self.tracing = 0 - self.tracingmonitortime = Evt.TickCount() - self.editors = {} - - prefs = W.getapplication().getprefs() - if prefs.debugger: - for file, breaks in prefs.debugger.breaks.items(): - for b in breaks: - self.set_break(file, b) - self.bounds, self.horpanes, self.verpanes = prefs.debugger.windowsettings - self.tracemagic = prefs.debugger.tracemagic - else: - self.breaks = {} - self.horpanes = (0.4, 0.6) - self.verpanes = (0.3, 0.35, 0.35) - self.bounds = (600, 400) - self.tracemagic = 0 - self.laststacksel = None - - def canonic(self, filename): - # override: the provided canonic() method breaks our - # file-less Untitled windows - return filename - - def reset(self): - self.currentframe = None - self.file = None - self.laststack = None - self.reason = 'Not running' - self.continuewithoutdebugger = 0 - bdb.Bdb.reset(self) - self.forget() - - def start(self, bottomframe = None, running = 0): - W.getapplication().DebuggerQuit = bdb.BdbQuit - from Carbon import Menu - Menu.HiliteMenu(0) - if self.closed: - self.setupwidgets(self.title) - self.closed = 0 - if not self.w.parent.debugger_quitting: - self.w.select() - raise W.AlertError, 'There is another debugger session busy.' - self.reset() - self.botframe = bottomframe - if running: - self.set_continue() - self.reason = 'Running\xc9' - self.setstate('running') - else: - self.set_step() - self.reason = 'stopped' - self.setstate('stopped') - sys.settrace(self.trace_dispatch) - - def stop(self): - self.set_quit() - if self.w.parent: - self.exit_mainloop() - self.resetwidgets() - - def set_continue_without_debugger(self): - sys.settrace(None) - self.set_quit() - self.clear_tracefuncs() - self.continuewithoutdebugger = 1 - if hasattr(self, "w") and self.w.parent: - self.exit_mainloop() - self.resetwidgets() - - def clear_tracefuncs(self): - try: - raise 'spam' - except: - pass - frame = sys.exc_traceback.tb_frame - while frame is not None: - del frame.f_trace - frame = frame.f_back - - def postmortem(self, exc_type, exc_value, traceback): - if self.closed: - self.setupwidgets(self.title) - self.closed = 0 - if not self.w.parent.debugger_quitting: - raise W.AlertError, 'There is another debugger session busy.' - self.reset() - if traceback: - self.botframe = traceback.tb_frame - while traceback.tb_next <> None: - traceback = traceback.tb_next - frame = traceback.tb_frame - else: - self.botframe = None - frame = None - self.w.panes.bottom.buttons.killbutton.enable(1) - self.reason = '(dead) ' + self.formatexception(exc_type, exc_value) - self.w.select() - self.setup(frame, traceback) - self.setstate('dead') - self.showstack(self.curindex) - self.showframe(self.curindex) - - def setupwidgets(self, title): - self.w = w = W.Window(self.bounds, title, minsize = (500, 300)) - - w.panes = W.HorizontalPanes((8, 4, -8, -8), self.horpanes) - - w.panes.browserpanes = browserpanes = W.VerticalPanes(None, self.verpanes) - - browserpanes.stacklist = W.Group(None) - browserpanes.stacklist.title = W.TextBox((4, 0, 0, 12), 'Stack') - browserpanes.stacklist.stack = W.List((0, 16, 0, 0), callback = self.do_stack, flags = Lists.lOnlyOne) - - browserpanes.locals = W.Group(None) - browserpanes.locals.title = W.TextBox((4, 0, 0, 12), 'Local variables') - browserpanes.locals.browser = PyBrowser.BrowserWidget((0, 16, 0, 0)) - - browserpanes.globals = W.Group(None) - browserpanes.globals.title = W.TextBox((4, 0, 0, 12), 'Global variables') - browserpanes.globals.browser = PyBrowser.BrowserWidget((0, 16, 0, 0)) - - w.panes.bottom = bottom = W.Group(None) - bottom.src = src = W.Group((0, 64, 0, 0)) - source = SourceViewer((1, 1, -15, -15), readonly = 1, debugger = self) - src.optionsmenu = W.PopupMenu((-16, 0, 16, 16), []) - src.optionsmenu.bind('<click>', self.makeoptionsmenu) - - src._barx = W.Scrollbar((0, -16, -15, 16), source.hscroll, max = 32767) - src._bary = W.Scrollbar((-16, 15, 16, -15), source.vscroll, max = 32767) - src.source = source - src.frame = W.Frame((0, 0, -15, -15)) - - bottom.tracingmonitor = TracingMonitor((0, 23, 6, 6)) - bottom.state = W.TextBox((12, 24, 0, 16), self.reason) - - bottom.srctitle = W.TextBox((12, 44, 0, 16)) - bottom.buttons = buttons = W.Group((12, 0, 0, 20)) - - buttons.runbutton = W.Button((0, 0, 50, 16), "Run", self.do_run) - buttons.stopbutton = W.Button((58, 0, 50, 16), "Stop", self.do_stop) - buttons.killbutton = W.Button((116, 0, 50, 16), "Kill", self.do_kill) - buttons.line = W.VerticalLine((173, 0, 0, 0)) - buttons.stepbutton = W.Button((181, 0, 60, 16), "Step", self.do_step) - buttons.stepinbutton = W.Button((249, 0, 60, 16), "Step in", self.do_stepin) - buttons.stepoutbutton = W.Button((317, 0, 60, 16), "Step out", self.do_stepout) - - w.bind('cmdr', buttons.runbutton.push) - w.bind('cmd.', buttons.stopbutton.push) - w.bind('cmdk', buttons.killbutton.push) - w.bind('cmds', buttons.stepbutton.push) - w.bind('cmdt', buttons.stepinbutton.push) - w.bind('cmdu', buttons.stepoutbutton.push) - - w.bind('<close>', self.close) - - w.open() - w.xxx___select(w.panes.bottom.src.source) - - def makeoptionsmenu(self): - options = [('Clear breakpoints', self.w.panes.bottom.src.source.clearbreakpoints), - ('Clear all breakpoints', self.clear_all_breaks), - ('Edit breakpoints\xc9', self.edit_breaks), '-', - (self.tracemagic and - 'Disable __magic__ tracing' or 'Enable __magic__ tracing', self.togglemagic)] - self.w.panes.bottom.src.optionsmenu.set(options) - - def edit_breaks(self): - if self.breaksviewer: - self.breaksviewer.select() - else: - self.breaksviewer = BreakpointsViewer(self) - - def togglemagic(self): - self.tracemagic = not self.tracemagic - - def setstate(self, state): - self.w.panes.bottom.tracingmonitor.reset() - self.w.panes.bottom.state.set(self.reason) - buttons = self.w.panes.bottom.buttons - if state == 'stopped': - buttons.runbutton.enable(1) - buttons.stopbutton.enable(0) - buttons.killbutton.enable(1) - buttons.stepbutton.enable(1) - buttons.stepinbutton.enable(1) - buttons.stepoutbutton.enable(1) - elif state == 'running': - buttons.runbutton.enable(0) - buttons.stopbutton.enable(1) - buttons.killbutton.enable(1) - buttons.stepbutton.enable(0) - buttons.stepinbutton.enable(0) - buttons.stepoutbutton.enable(0) - elif state == 'idle': - buttons.runbutton.enable(0) - buttons.stopbutton.enable(0) - buttons.killbutton.enable(0) - buttons.stepbutton.enable(0) - buttons.stepinbutton.enable(0) - buttons.stepoutbutton.enable(0) - elif state == 'dead': - buttons.runbutton.enable(0) - buttons.stopbutton.enable(0) - buttons.killbutton.enable(1) - buttons.stepbutton.enable(0) - buttons.stepinbutton.enable(0) - buttons.stepoutbutton.enable(0) - else: - print 'unknown state:', state - - def resetwidgets(self): - self.reason = '' - self.w.panes.bottom.srctitle.set('') - self.w.panes.bottom.src.source.set('') - self.w.panes.browserpanes.stacklist.stack.set([]) - self.w.panes.browserpanes.locals.browser.set({}) - self.w.panes.browserpanes.globals.browser.set({}) - self.setstate('idle') - - # W callbacks - - def close(self): - self.set_quit() - self.exit_mainloop() - self.closed = 1 - - self.unregister_editor(self.w.panes.bottom.src.source, - self.w.panes.bottom.src.source.file) - self.horpanes = self.w.panes.getpanesizes() - self.verpanes = self.w.panes.browserpanes.getpanesizes() - self.bounds = self.w.getbounds() - prefs = W.getapplication().getprefs() - prefs.debugger.breaks = self.breaks - prefs.debugger.windowsettings = self.bounds, self.horpanes, self.verpanes - prefs.debugger.tracemagic = self.tracemagic - prefs.save() - - # stack list callback - - def do_stack(self, isdbl): - sel = self.w.panes.browserpanes.stacklist.stack.getselection() - if isdbl: - if sel: - frame, lineno = self.stack[sel[0] + 1] - filename = frame.f_code.co_filename - editor = self.w._parentwindow.parent.openscript(filename, lineno) - if self.breaks.has_key(filename): - editor.showbreakpoints(1) - else: - if sel and sel <> self.laststacksel: - self.showframe(sel[0] + 1) - self.laststacksel = sel - - def geteditor(self, filename): - if filename[:1] == '<' and filename[-1:] == '>': - editor = W.getapplication().getscript(filename[1:-1]) - else: - editor = W.getapplication().getscript(filename) - return editor - - # button callbacks - - def do_run(self): - self.running() - self.set_continue() - self.exit_mainloop() - - def do_stop(self): - self.set_step() - - def do_kill(self): - self.set_quit() - self.exit_mainloop() - self.resetwidgets() - - def do_step(self): - self.running() - self.set_next(self.curframe) - self.exit_mainloop() - - def do_stepin(self): - self.running() - self.set_step() - self.exit_mainloop() - - def do_stepout(self): - self.running() - self.set_return(self.curframe) - self.exit_mainloop() - - def running(self): - W.SetCursor('watch') - self.reason = 'Running\xc9' - self.setstate('running') - #self.w.panes.bottom.src.source.set('') - #self.w.panes.browserpanes.stacklist.stack.set([]) - #self.w.panes.browserpanes.locals.browser.set({}) - #self.w.panes.browserpanes.globals.browser.set({}) - - def exit_mainloop(self): - self.w.parent.debugger_quitting = 1 - - # - - def showframe(self, stackindex): - (frame, lineno) = self.stack[stackindex] - W.SetCursor('watch') - filename = frame.f_code.co_filename - if filename <> self.file: - editor = self.geteditor(filename) - if editor: - self.w.panes.bottom.src.source.set(editor.get(), filename) - else: - try: - f = open(filename, 'rU') - data = f.read() - f.close() - except IOError: - if filename[-3:] == '.py': - import imp - modname = os.path.basename(filename)[:-3] - try: - f, filename, (suff, mode, dummy) = imp.find_module(modname) - except ImportError: - self.w.panes.bottom.src.source.set("can't find file") - else: - if f: - f.close() - if f and suff == '.py': - f = open(filename, 'rU') - data = f.read() - f.close() - self.w.panes.bottom.src.source.set(data, filename) - else: - self.w.panes.bottom.src.source.set("can't find file") - else: - self.w.panes.bottom.src.source.set("can't find file") - else: - data = data.replace('\n', '\r') - self.w.panes.bottom.src.source.set(data, filename) - self.file = filename - self.w.panes.bottom.srctitle.set('Source: ' + filename + ((lineno > 0) and (' (line %d)' % lineno) or ' ')) - self.goto_line(lineno) - self.lineno = lineno - self.showvars((frame, lineno)) - - def showvars(self, (frame, lineno)): - if frame.f_locals is not frame.f_globals: - locals = frame.f_locals - else: - locals = {'Same as Globals':''} - filteredlocals = {} - for key, value in locals.items(): - # empty key is magic for Python 1.4; '.' is magic for 1.5... - if not key or key[0] <> '.': - filteredlocals[key] = value - self.w.panes.browserpanes.locals.browser.set(filteredlocals) - self.w.panes.browserpanes.globals.browser.set(frame.f_globals) - - def showstack(self, stackindex): - stack = [] - for frame, lineno in self.stack[1:]: - filename = frame.f_code.co_filename - try: - filename = _filenames[filename] - except KeyError: - if filename[:1] + filename[-1:] <> '<>': - filename = os.path.basename(filename) - _filenames[frame.f_code.co_filename] = filename - funcname = frame.f_code.co_name - if funcname == '?': - funcname = '<toplevel>' - stack.append(filename + ': ' + funcname) - if stack <> self.laststack: - self.w.panes.browserpanes.stacklist.stack.set(stack) - self.laststack = stack - sel = [stackindex - 1] - self.w.panes.browserpanes.stacklist.stack.setselection(sel) - self.laststacksel = sel - - def goto_line(self, lineno): - if lineno > 0: - self.w.panes.bottom.src.source.selectline(lineno - 1) - else: - self.w.panes.bottom.src.source.setselection(0, 0) - - # bdb entry points - -# def user_call(self, frame, argument_list): -# self.reason = 'Calling' -# self.interaction(frame, None) - - def user_line(self, frame): - # This function is called when we stop or break at this line - self.reason = 'Stopped' - self.interaction(frame, None) - - def user_return(self, frame, return_value): - # This function is called when a return trap is set here - fname = frame.f_code.co_name - if fname <> '?': - self.reason = 'Returning from %s()' % frame.f_code.co_name - frame.f_locals['__return__'] = return_value - elif frame.f_back is self.botframe: - self.reason = 'Done' - else: - self.reason = 'Returning' - self.interaction(frame, None, 1) - - def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): - # This function is called when we stop or break at this line - self.reason = self.formatexception(exc_type, exc_value) - self.interaction(frame, exc_traceback) - - def formatexception(self, exc_type, exc_value): - if exc_type == SyntaxError: - try: - value, (filename, lineno, charno, line) = exc_value - except: - pass - else: - return str(exc_type) + ': ' + str(value) - if type(exc_type) == types.ClassType: - nice = exc_type.__name__ - else: - nice = str(exc_type) - value = str(exc_value) - if exc_value and value: - nice = nice + ": " + value - return nice - - def forget(self): - self.stack = [] - self.curindex = 0 - self.curframe = None - - def setup(self, f, t, isreturning = 0): - self.forget() - self.stack, self.curindex = self.get_stack(f, t) - self.curframe = self.stack[self.curindex - isreturning][0] - - def interaction(self, frame, traceback, isreturning = 0): - saveport = Qd.GetPort() - self.w.select() - try: - self.setup(frame, traceback, isreturning) - self.setstate('stopped') - stackindex = self.curindex - if isreturning: - if frame.f_back is not self.botframe: - stackindex = stackindex - 1 - self.showstack(stackindex) - self.showframe(stackindex) - self.w.parent.debugger_mainloop() - self.forget() - finally: - Qd.SetPort(saveport) - - # bdb customization - - def trace_dispatch(self, frame, event, arg, TickCount = Evt.TickCount): - if TickCount() - self.tracingmonitortime > 15: - self.tracingmonitortime = TickCount() - self.w.panes.bottom.tracingmonitor.toggle() - try: - try: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(0) - if self.quitting: - # returning None is not enough, a former BdbQuit exception - # might have been eaten by the print statement - raise bdb.BdbQuit - if event == 'line': - return self.dispatch_line(frame) - if event == 'call': - return self.dispatch_call(frame, arg) - if event == 'return': - return self.dispatch_return(frame, arg) - if event == 'exception': - return self.dispatch_exception(frame, arg) - print 'bdb.Bdb.dispatch: unknown debugging event:', repr(event) - return self.trace_dispatch - finally: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(-1) - except KeyboardInterrupt: - self.set_step() - return self.trace_dispatch - except bdb.BdbQuit: - if self.continuewithoutdebugger: - self.clear_tracefuncs() - return - else: - raise bdb.BdbQuit - except: - print 'XXX Exception during debugger interaction.', \ - self.formatexception(sys.exc_type, sys.exc_value) - import traceback - traceback.print_exc() - return self.trace_dispatch - - def dispatch_call(self, frame, arg): - if not self.tracemagic and \ - frame.f_code.co_name[:2] == '__' == frame.f_code.co_name[-2:] and \ - frame.f_code.co_name <> '__init__': - return - if self.botframe is None: - # First call of dispatch since reset() - self.botframe = frame.f_back # xxx !!! added f_back - return self.trace_dispatch - if not (self.stop_here(frame) or self.break_anywhere(frame)): - # No need to trace this function - return # None - self.user_call(frame, arg) - if self.quitting: - raise bdb.BdbQuit - return self.trace_dispatch - - def set_continue(self): - # Don't stop except at breakpoints or when finished - self.stopframe = self.botframe - self.returnframe = None - self.quitting = 0 - # unlike in bdb/pdb, there's a chance that breakpoints change - # *while* a program (this program ;-) is running. It's actually quite likely. - # So we don't delete frame.f_trace until the bottom frame if there are no breakpoints. - - def set_break(self, filename, lineno): - if not self.breaks.has_key(filename): - self.breaks[filename] = [] - list = self.breaks[filename] - if lineno in list: - return 'There is already a breakpoint there!' - list.append(lineno) - list.sort() # I want to keep them neatly sorted; easier for drawing - if hasattr(bdb, "Breakpoint"): - # 1.5.2b1 specific - bp = bdb.Breakpoint(filename, lineno, 0, None) - self.update_breaks(filename) - - def clear_break(self, filename, lineno): - bdb.Bdb.clear_break(self, filename, lineno) - self.update_breaks(filename) - - def clear_all_file_breaks(self, filename): - bdb.Bdb.clear_all_file_breaks(self, filename) - self.update_breaks(filename) - - def clear_all_breaks(self): - bdb.Bdb.clear_all_breaks(self) - for editors in self.editors.values(): - for editor in editors: - editor.drawbreakpoints() - - # special - - def toggle_break(self, filename, lineno): - if self.get_break(filename, lineno): - self.clear_break(filename, lineno) - else: - self.set_break(filename, lineno) - - def clear_breaks_above(self, filename, above): - if not self.breaks.has_key(filename): - return 'There are no breakpoints in that file!' - for lineno in self.breaks[filename][:]: - if lineno > above: - self.breaks[filename].remove(lineno) - if not self.breaks[filename]: - del self.breaks[filename] - - # editor stuff - - def update_breaks(self, filename): - if self.breaksviewer: - self.breaksviewer.update() - if self.editors.has_key(filename): - for editor in self.editors[filename]: - if editor._debugger: # XXX - editor.drawbreakpoints() - else: - print 'xxx dead editor!' - - def update_allbreaks(self): - if self.breaksviewer: - self.breaksviewer.update() - for filename in self.breaks.keys(): - if self.editors.has_key(filename): - for editor in self.editors[filename]: - if editor._debugger: # XXX - editor.drawbreakpoints() - else: - print 'xxx dead editor!' - - def register_editor(self, editor, filename): - if not filename: - return - if not self.editors.has_key(filename): - self.editors[filename] = [editor] - elif editor not in self.editors[filename]: - self.editors[filename].append(editor) - - def unregister_editor(self, editor, filename): - if not filename: - return - try: - self.editors[filename].remove(editor) - if not self.editors[filename]: - del self.editors[filename] - # if this was an untitled window, clear the breaks. - if filename[:1] == '<' and filename[-1:] == '>' and \ - self.breaks.has_key(filename): - self.clear_all_file_breaks(filename) - except (KeyError, ValueError): - pass - + + def __init__(self, title = 'Debugger'): + bdb.Bdb.__init__(self) + self.closed = 1 + self.title = title + self.breaksviewer = None + self.reset() + self.tracing = 0 + self.tracingmonitortime = Evt.TickCount() + self.editors = {} + + prefs = W.getapplication().getprefs() + if prefs.debugger: + for file, breaks in prefs.debugger.breaks.items(): + for b in breaks: + self.set_break(file, b) + self.bounds, self.horpanes, self.verpanes = prefs.debugger.windowsettings + self.tracemagic = prefs.debugger.tracemagic + else: + self.breaks = {} + self.horpanes = (0.4, 0.6) + self.verpanes = (0.3, 0.35, 0.35) + self.bounds = (600, 400) + self.tracemagic = 0 + self.laststacksel = None + + def canonic(self, filename): + # override: the provided canonic() method breaks our + # file-less Untitled windows + return filename + + def reset(self): + self.currentframe = None + self.file = None + self.laststack = None + self.reason = 'Not running' + self.continuewithoutdebugger = 0 + bdb.Bdb.reset(self) + self.forget() + + def start(self, bottomframe = None, running = 0): + W.getapplication().DebuggerQuit = bdb.BdbQuit + from Carbon import Menu + Menu.HiliteMenu(0) + if self.closed: + self.setupwidgets(self.title) + self.closed = 0 + if not self.w.parent.debugger_quitting: + self.w.select() + raise W.AlertError, 'There is another debugger session busy.' + self.reset() + self.botframe = bottomframe + if running: + self.set_continue() + self.reason = 'Running\xc9' + self.setstate('running') + else: + self.set_step() + self.reason = 'stopped' + self.setstate('stopped') + sys.settrace(self.trace_dispatch) + + def stop(self): + self.set_quit() + if self.w.parent: + self.exit_mainloop() + self.resetwidgets() + + def set_continue_without_debugger(self): + sys.settrace(None) + self.set_quit() + self.clear_tracefuncs() + self.continuewithoutdebugger = 1 + if hasattr(self, "w") and self.w.parent: + self.exit_mainloop() + self.resetwidgets() + + def clear_tracefuncs(self): + try: + raise 'spam' + except: + pass + frame = sys.exc_traceback.tb_frame + while frame is not None: + del frame.f_trace + frame = frame.f_back + + def postmortem(self, exc_type, exc_value, traceback): + if self.closed: + self.setupwidgets(self.title) + self.closed = 0 + if not self.w.parent.debugger_quitting: + raise W.AlertError, 'There is another debugger session busy.' + self.reset() + if traceback: + self.botframe = traceback.tb_frame + while traceback.tb_next <> None: + traceback = traceback.tb_next + frame = traceback.tb_frame + else: + self.botframe = None + frame = None + self.w.panes.bottom.buttons.killbutton.enable(1) + self.reason = '(dead) ' + self.formatexception(exc_type, exc_value) + self.w.select() + self.setup(frame, traceback) + self.setstate('dead') + self.showstack(self.curindex) + self.showframe(self.curindex) + + def setupwidgets(self, title): + self.w = w = W.Window(self.bounds, title, minsize = (500, 300)) + + w.panes = W.HorizontalPanes((8, 4, -8, -8), self.horpanes) + + w.panes.browserpanes = browserpanes = W.VerticalPanes(None, self.verpanes) + + browserpanes.stacklist = W.Group(None) + browserpanes.stacklist.title = W.TextBox((4, 0, 0, 12), 'Stack') + browserpanes.stacklist.stack = W.List((0, 16, 0, 0), callback = self.do_stack, flags = Lists.lOnlyOne) + + browserpanes.locals = W.Group(None) + browserpanes.locals.title = W.TextBox((4, 0, 0, 12), 'Local variables') + browserpanes.locals.browser = PyBrowser.BrowserWidget((0, 16, 0, 0)) + + browserpanes.globals = W.Group(None) + browserpanes.globals.title = W.TextBox((4, 0, 0, 12), 'Global variables') + browserpanes.globals.browser = PyBrowser.BrowserWidget((0, 16, 0, 0)) + + w.panes.bottom = bottom = W.Group(None) + bottom.src = src = W.Group((0, 64, 0, 0)) + source = SourceViewer((1, 1, -15, -15), readonly = 1, debugger = self) + src.optionsmenu = W.PopupMenu((-16, 0, 16, 16), []) + src.optionsmenu.bind('<click>', self.makeoptionsmenu) + + src._barx = W.Scrollbar((0, -16, -15, 16), source.hscroll, max = 32767) + src._bary = W.Scrollbar((-16, 15, 16, -15), source.vscroll, max = 32767) + src.source = source + src.frame = W.Frame((0, 0, -15, -15)) + + bottom.tracingmonitor = TracingMonitor((0, 23, 6, 6)) + bottom.state = W.TextBox((12, 24, 0, 16), self.reason) + + bottom.srctitle = W.TextBox((12, 44, 0, 16)) + bottom.buttons = buttons = W.Group((12, 0, 0, 20)) + + buttons.runbutton = W.Button((0, 0, 50, 16), "Run", self.do_run) + buttons.stopbutton = W.Button((58, 0, 50, 16), "Stop", self.do_stop) + buttons.killbutton = W.Button((116, 0, 50, 16), "Kill", self.do_kill) + buttons.line = W.VerticalLine((173, 0, 0, 0)) + buttons.stepbutton = W.Button((181, 0, 60, 16), "Step", self.do_step) + buttons.stepinbutton = W.Button((249, 0, 60, 16), "Step in", self.do_stepin) + buttons.stepoutbutton = W.Button((317, 0, 60, 16), "Step out", self.do_stepout) + + w.bind('cmdr', buttons.runbutton.push) + w.bind('cmd.', buttons.stopbutton.push) + w.bind('cmdk', buttons.killbutton.push) + w.bind('cmds', buttons.stepbutton.push) + w.bind('cmdt', buttons.stepinbutton.push) + w.bind('cmdu', buttons.stepoutbutton.push) + + w.bind('<close>', self.close) + + w.open() + w.xxx___select(w.panes.bottom.src.source) + + def makeoptionsmenu(self): + options = [('Clear breakpoints', self.w.panes.bottom.src.source.clearbreakpoints), + ('Clear all breakpoints', self.clear_all_breaks), + ('Edit breakpoints\xc9', self.edit_breaks), '-', + (self.tracemagic and + 'Disable __magic__ tracing' or 'Enable __magic__ tracing', self.togglemagic)] + self.w.panes.bottom.src.optionsmenu.set(options) + + def edit_breaks(self): + if self.breaksviewer: + self.breaksviewer.select() + else: + self.breaksviewer = BreakpointsViewer(self) + + def togglemagic(self): + self.tracemagic = not self.tracemagic + + def setstate(self, state): + self.w.panes.bottom.tracingmonitor.reset() + self.w.panes.bottom.state.set(self.reason) + buttons = self.w.panes.bottom.buttons + if state == 'stopped': + buttons.runbutton.enable(1) + buttons.stopbutton.enable(0) + buttons.killbutton.enable(1) + buttons.stepbutton.enable(1) + buttons.stepinbutton.enable(1) + buttons.stepoutbutton.enable(1) + elif state == 'running': + buttons.runbutton.enable(0) + buttons.stopbutton.enable(1) + buttons.killbutton.enable(1) + buttons.stepbutton.enable(0) + buttons.stepinbutton.enable(0) + buttons.stepoutbutton.enable(0) + elif state == 'idle': + buttons.runbutton.enable(0) + buttons.stopbutton.enable(0) + buttons.killbutton.enable(0) + buttons.stepbutton.enable(0) + buttons.stepinbutton.enable(0) + buttons.stepoutbutton.enable(0) + elif state == 'dead': + buttons.runbutton.enable(0) + buttons.stopbutton.enable(0) + buttons.killbutton.enable(1) + buttons.stepbutton.enable(0) + buttons.stepinbutton.enable(0) + buttons.stepoutbutton.enable(0) + else: + print 'unknown state:', state + + def resetwidgets(self): + self.reason = '' + self.w.panes.bottom.srctitle.set('') + self.w.panes.bottom.src.source.set('') + self.w.panes.browserpanes.stacklist.stack.set([]) + self.w.panes.browserpanes.locals.browser.set({}) + self.w.panes.browserpanes.globals.browser.set({}) + self.setstate('idle') + + # W callbacks + + def close(self): + self.set_quit() + self.exit_mainloop() + self.closed = 1 + + self.unregister_editor(self.w.panes.bottom.src.source, + self.w.panes.bottom.src.source.file) + self.horpanes = self.w.panes.getpanesizes() + self.verpanes = self.w.panes.browserpanes.getpanesizes() + self.bounds = self.w.getbounds() + prefs = W.getapplication().getprefs() + prefs.debugger.breaks = self.breaks + prefs.debugger.windowsettings = self.bounds, self.horpanes, self.verpanes + prefs.debugger.tracemagic = self.tracemagic + prefs.save() + + # stack list callback + + def do_stack(self, isdbl): + sel = self.w.panes.browserpanes.stacklist.stack.getselection() + if isdbl: + if sel: + frame, lineno = self.stack[sel[0] + 1] + filename = frame.f_code.co_filename + editor = self.w._parentwindow.parent.openscript(filename, lineno) + if self.breaks.has_key(filename): + editor.showbreakpoints(1) + else: + if sel and sel <> self.laststacksel: + self.showframe(sel[0] + 1) + self.laststacksel = sel + + def geteditor(self, filename): + if filename[:1] == '<' and filename[-1:] == '>': + editor = W.getapplication().getscript(filename[1:-1]) + else: + editor = W.getapplication().getscript(filename) + return editor + + # button callbacks + + def do_run(self): + self.running() + self.set_continue() + self.exit_mainloop() + + def do_stop(self): + self.set_step() + + def do_kill(self): + self.set_quit() + self.exit_mainloop() + self.resetwidgets() + + def do_step(self): + self.running() + self.set_next(self.curframe) + self.exit_mainloop() + + def do_stepin(self): + self.running() + self.set_step() + self.exit_mainloop() + + def do_stepout(self): + self.running() + self.set_return(self.curframe) + self.exit_mainloop() + + def running(self): + W.SetCursor('watch') + self.reason = 'Running\xc9' + self.setstate('running') + #self.w.panes.bottom.src.source.set('') + #self.w.panes.browserpanes.stacklist.stack.set([]) + #self.w.panes.browserpanes.locals.browser.set({}) + #self.w.panes.browserpanes.globals.browser.set({}) + + def exit_mainloop(self): + self.w.parent.debugger_quitting = 1 + + # + + def showframe(self, stackindex): + (frame, lineno) = self.stack[stackindex] + W.SetCursor('watch') + filename = frame.f_code.co_filename + if filename <> self.file: + editor = self.geteditor(filename) + if editor: + self.w.panes.bottom.src.source.set(editor.get(), filename) + else: + try: + f = open(filename, 'rU') + data = f.read() + f.close() + except IOError: + if filename[-3:] == '.py': + import imp + modname = os.path.basename(filename)[:-3] + try: + f, filename, (suff, mode, dummy) = imp.find_module(modname) + except ImportError: + self.w.panes.bottom.src.source.set("can't find file") + else: + if f: + f.close() + if f and suff == '.py': + f = open(filename, 'rU') + data = f.read() + f.close() + self.w.panes.bottom.src.source.set(data, filename) + else: + self.w.panes.bottom.src.source.set("can't find file") + else: + self.w.panes.bottom.src.source.set("can't find file") + else: + data = data.replace('\n', '\r') + self.w.panes.bottom.src.source.set(data, filename) + self.file = filename + self.w.panes.bottom.srctitle.set('Source: ' + filename + ((lineno > 0) and (' (line %d)' % lineno) or ' ')) + self.goto_line(lineno) + self.lineno = lineno + self.showvars((frame, lineno)) + + def showvars(self, (frame, lineno)): + if frame.f_locals is not frame.f_globals: + locals = frame.f_locals + else: + locals = {'Same as Globals':''} + filteredlocals = {} + for key, value in locals.items(): + # empty key is magic for Python 1.4; '.' is magic for 1.5... + if not key or key[0] <> '.': + filteredlocals[key] = value + self.w.panes.browserpanes.locals.browser.set(filteredlocals) + self.w.panes.browserpanes.globals.browser.set(frame.f_globals) + + def showstack(self, stackindex): + stack = [] + for frame, lineno in self.stack[1:]: + filename = frame.f_code.co_filename + try: + filename = _filenames[filename] + except KeyError: + if filename[:1] + filename[-1:] <> '<>': + filename = os.path.basename(filename) + _filenames[frame.f_code.co_filename] = filename + funcname = frame.f_code.co_name + if funcname == '?': + funcname = '<toplevel>' + stack.append(filename + ': ' + funcname) + if stack <> self.laststack: + self.w.panes.browserpanes.stacklist.stack.set(stack) + self.laststack = stack + sel = [stackindex - 1] + self.w.panes.browserpanes.stacklist.stack.setselection(sel) + self.laststacksel = sel + + def goto_line(self, lineno): + if lineno > 0: + self.w.panes.bottom.src.source.selectline(lineno - 1) + else: + self.w.panes.bottom.src.source.setselection(0, 0) + + # bdb entry points + +# def user_call(self, frame, argument_list): +# self.reason = 'Calling' +# self.interaction(frame, None) + + def user_line(self, frame): + # This function is called when we stop or break at this line + self.reason = 'Stopped' + self.interaction(frame, None) + + def user_return(self, frame, return_value): + # This function is called when a return trap is set here + fname = frame.f_code.co_name + if fname <> '?': + self.reason = 'Returning from %s()' % frame.f_code.co_name + frame.f_locals['__return__'] = return_value + elif frame.f_back is self.botframe: + self.reason = 'Done' + else: + self.reason = 'Returning' + self.interaction(frame, None, 1) + + def user_exception(self, frame, (exc_type, exc_value, exc_traceback)): + # This function is called when we stop or break at this line + self.reason = self.formatexception(exc_type, exc_value) + self.interaction(frame, exc_traceback) + + def formatexception(self, exc_type, exc_value): + if exc_type == SyntaxError: + try: + value, (filename, lineno, charno, line) = exc_value + except: + pass + else: + return str(exc_type) + ': ' + str(value) + if type(exc_type) == types.ClassType: + nice = exc_type.__name__ + else: + nice = str(exc_type) + value = str(exc_value) + if exc_value and value: + nice = nice + ": " + value + return nice + + def forget(self): + self.stack = [] + self.curindex = 0 + self.curframe = None + + def setup(self, f, t, isreturning = 0): + self.forget() + self.stack, self.curindex = self.get_stack(f, t) + self.curframe = self.stack[self.curindex - isreturning][0] + + def interaction(self, frame, traceback, isreturning = 0): + saveport = Qd.GetPort() + self.w.select() + try: + self.setup(frame, traceback, isreturning) + self.setstate('stopped') + stackindex = self.curindex + if isreturning: + if frame.f_back is not self.botframe: + stackindex = stackindex - 1 + self.showstack(stackindex) + self.showframe(stackindex) + self.w.parent.debugger_mainloop() + self.forget() + finally: + Qd.SetPort(saveport) + + # bdb customization + + def trace_dispatch(self, frame, event, arg, TickCount = Evt.TickCount): + if TickCount() - self.tracingmonitortime > 15: + self.tracingmonitortime = TickCount() + self.w.panes.bottom.tracingmonitor.toggle() + try: + try: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(0) + if self.quitting: + # returning None is not enough, a former BdbQuit exception + # might have been eaten by the print statement + raise bdb.BdbQuit + if event == 'line': + return self.dispatch_line(frame) + if event == 'call': + return self.dispatch_call(frame, arg) + if event == 'return': + return self.dispatch_return(frame, arg) + if event == 'exception': + return self.dispatch_exception(frame, arg) + print 'bdb.Bdb.dispatch: unknown debugging event:', repr(event) + return self.trace_dispatch + finally: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(-1) + except KeyboardInterrupt: + self.set_step() + return self.trace_dispatch + except bdb.BdbQuit: + if self.continuewithoutdebugger: + self.clear_tracefuncs() + return + else: + raise bdb.BdbQuit + except: + print 'XXX Exception during debugger interaction.', \ + self.formatexception(sys.exc_type, sys.exc_value) + import traceback + traceback.print_exc() + return self.trace_dispatch + + def dispatch_call(self, frame, arg): + if not self.tracemagic and \ + frame.f_code.co_name[:2] == '__' == frame.f_code.co_name[-2:] and \ + frame.f_code.co_name <> '__init__': + return + if self.botframe is None: + # First call of dispatch since reset() + self.botframe = frame.f_back # xxx !!! added f_back + return self.trace_dispatch + if not (self.stop_here(frame) or self.break_anywhere(frame)): + # No need to trace this function + return # None + self.user_call(frame, arg) + if self.quitting: + raise bdb.BdbQuit + return self.trace_dispatch + + def set_continue(self): + # Don't stop except at breakpoints or when finished + self.stopframe = self.botframe + self.returnframe = None + self.quitting = 0 + # unlike in bdb/pdb, there's a chance that breakpoints change + # *while* a program (this program ;-) is running. It's actually quite likely. + # So we don't delete frame.f_trace until the bottom frame if there are no breakpoints. + + def set_break(self, filename, lineno): + if not self.breaks.has_key(filename): + self.breaks[filename] = [] + list = self.breaks[filename] + if lineno in list: + return 'There is already a breakpoint there!' + list.append(lineno) + list.sort() # I want to keep them neatly sorted; easier for drawing + if hasattr(bdb, "Breakpoint"): + # 1.5.2b1 specific + bp = bdb.Breakpoint(filename, lineno, 0, None) + self.update_breaks(filename) + + def clear_break(self, filename, lineno): + bdb.Bdb.clear_break(self, filename, lineno) + self.update_breaks(filename) + + def clear_all_file_breaks(self, filename): + bdb.Bdb.clear_all_file_breaks(self, filename) + self.update_breaks(filename) + + def clear_all_breaks(self): + bdb.Bdb.clear_all_breaks(self) + for editors in self.editors.values(): + for editor in editors: + editor.drawbreakpoints() + + # special + + def toggle_break(self, filename, lineno): + if self.get_break(filename, lineno): + self.clear_break(filename, lineno) + else: + self.set_break(filename, lineno) + + def clear_breaks_above(self, filename, above): + if not self.breaks.has_key(filename): + return 'There are no breakpoints in that file!' + for lineno in self.breaks[filename][:]: + if lineno > above: + self.breaks[filename].remove(lineno) + if not self.breaks[filename]: + del self.breaks[filename] + + # editor stuff + + def update_breaks(self, filename): + if self.breaksviewer: + self.breaksviewer.update() + if self.editors.has_key(filename): + for editor in self.editors[filename]: + if editor._debugger: # XXX + editor.drawbreakpoints() + else: + print 'xxx dead editor!' + + def update_allbreaks(self): + if self.breaksviewer: + self.breaksviewer.update() + for filename in self.breaks.keys(): + if self.editors.has_key(filename): + for editor in self.editors[filename]: + if editor._debugger: # XXX + editor.drawbreakpoints() + else: + print 'xxx dead editor!' + + def register_editor(self, editor, filename): + if not filename: + return + if not self.editors.has_key(filename): + self.editors[filename] = [editor] + elif editor not in self.editors[filename]: + self.editors[filename].append(editor) + + def unregister_editor(self, editor, filename): + if not filename: + return + try: + self.editors[filename].remove(editor) + if not self.editors[filename]: + del self.editors[filename] + # if this was an untitled window, clear the breaks. + if filename[:1] == '<' and filename[-1:] == '>' and \ + self.breaks.has_key(filename): + self.clear_all_file_breaks(filename) + except (KeyError, ValueError): + pass + class SourceViewer(W.PyEditor): - - def __init__(self, *args, **kwargs): - apply(W.PyEditor.__init__, (self,) + args, kwargs) - self.bind('<click>', self.clickintercept) - - def clickintercept(self, point, modifiers): - if self._parentwindow._currentwidget <> self and not self.pt_in_breaks(point): - self._parentwindow.xxx___select(self) - return 1 - - def _getviewrect(self): - l, t, r, b = self._bounds - if self._debugger: - return (l + 12, t + 2, r - 1, b - 2) - else: - return (l + 5, t + 2, r - 1, b - 2) - - def select(self, onoff, isclick = 0): - if W.SelectableWidget.select(self, onoff): - return - self.SetPort() - #if onoff: - # self.ted.WEActivate() - #else: - # self.ted.WEDeactivate() - self.drawselframe(onoff) - - def drawselframe(self, onoff): - pass + + def __init__(self, *args, **kwargs): + apply(W.PyEditor.__init__, (self,) + args, kwargs) + self.bind('<click>', self.clickintercept) + + def clickintercept(self, point, modifiers): + if self._parentwindow._currentwidget <> self and not self.pt_in_breaks(point): + self._parentwindow.xxx___select(self) + return 1 + + def _getviewrect(self): + l, t, r, b = self._bounds + if self._debugger: + return (l + 12, t + 2, r - 1, b - 2) + else: + return (l + 5, t + 2, r - 1, b - 2) + + def select(self, onoff, isclick = 0): + if W.SelectableWidget.select(self, onoff): + return + self.SetPort() + #if onoff: + # self.ted.WEActivate() + #else: + # self.ted.WEDeactivate() + self.drawselframe(onoff) + + def drawselframe(self, onoff): + pass class BreakpointsViewer: - - def __init__(self, debugger): - self.debugger = debugger - self.w = W.Window((300, 250), 'Breakpoints', minsize = (200, 200)) - self.w.panes = W.HorizontalPanes((8, 8, -8, -32), (0.3, 0.7)) - self.w.panes.files = W.List(None, callback = self.filehit) #, flags = Lists.lOnlyOne) - self.w.panes.gr = W.Group(None) - self.w.panes.gr.breaks = W.List((0, 0, -130, 0), callback = self.linehit) #, flags = Lists.lOnlyOne) - self.w.panes.gr.openbutton = W.Button((-80, 4, 0, 16), 'View\xc9', self.openbuttonhit) - self.w.panes.gr.deletebutton = W.Button((-80, 28, 0, 16), 'Delete', self.deletebuttonhit) - - self.w.bind('<close>', self.close) - self.w.bind('backspace', self.w.panes.gr.deletebutton.push) - - self.setup() - self.w.open() - self.w.panes.gr.openbutton.enable(0) - self.w.panes.gr.deletebutton.enable(0) - self.curfile = None - - def deletebuttonhit(self): - if self.w._currentwidget == self.w.panes.files: - self.del_filename() - else: - self.del_number() - self.checkbuttons() - - def del_number(self): - if self.curfile is None: - return - sel = self.w.panes.gr.breaks.getselectedobjects() - for lineno in sel: - self.debugger.clear_break(self.curfile, lineno) - - def del_filename(self): - sel = self.w.panes.files.getselectedobjects() - for filename in sel: - self.debugger.clear_all_file_breaks(filename) - self.debugger.update_allbreaks() - - def setup(self): - files = self.debugger.breaks.keys() - files.sort() - self.w.panes.files.set(files) - - def close(self): - self.debugger.breaksviewer = None - self.debugger = None - - def update(self): - sel = self.w.panes.files.getselectedobjects() - self.setup() - self.w.panes.files.setselectedobjects(sel) - sel = self.w.panes.files.getselection() - if len(sel) == 0 and self.curfile: - self.w.panes.files.setselectedobjects([self.curfile]) - self.filehit(0) - - def select(self): - self.w.select() - - def selectfile(self, file): - self.w.panes.files.setselectedobjects([file]) - self.filehit(0) - - def openbuttonhit(self): - self.filehit(1) - - def filehit(self, isdbl): - sel = self.w.panes.files.getselectedobjects() - if isdbl: - for filename in sel: - lineno = None - if filename == self.curfile: - linesel = self.w.panes.gr.breaks.getselectedobjects() - if linesel: - lineno = linesel[-1] - elif self.w.panes.gr.breaks: - lineno = self.w.panes.gr.breaks[0] - editor = self.w._parentwindow.parent.openscript(filename, lineno) - editor.showbreakpoints(1) - return - if len(sel) == 1: - file = sel[0] - filebreaks = self.debugger.breaks[file][:] - if self.curfile == file: - linesel = self.w.panes.gr.breaks.getselectedobjects() - self.w.panes.gr.breaks.set(filebreaks) - if self.curfile == file: - self.w.panes.gr.breaks.setselectedobjects(linesel) - self.curfile = file - else: - if len(sel) <> 0: - self.curfile = None - self.w.panes.gr.breaks.set([]) - self.checkbuttons() - - def linehit(self, isdbl): - if isdbl: - files = self.w.panes.files.getselectedobjects() - if len(files) <> 1: - return - filename = files[0] - linenos = self.w.panes.gr.breaks.getselectedobjects() - if not linenos: - return - lineno = linenos[-1] - editor = self.w._parentwindow.parent.openscript(filename, lineno) - editor.showbreakpoints(1) - self.checkbuttons() - - def checkbuttons(self): - if self.w.panes.files.getselection(): - self.w.panes.gr.openbutton.enable(1) - self.w._parentwindow.setdefaultbutton(self.w.panes.gr.openbutton) - if self.w._currentwidget == self.w.panes.files: - if self.w.panes.files.getselection(): - self.w.panes.gr.deletebutton.enable(1) - else: - self.w.panes.gr.deletebutton.enable(0) - else: - if self.w.panes.gr.breaks.getselection(): - self.w.panes.gr.deletebutton.enable(1) - else: - self.w.panes.gr.deletebutton.enable(0) - else: - self.w.panes.gr.openbutton.enable(0) - self.w.panes.gr.deletebutton.enable(0) + + def __init__(self, debugger): + self.debugger = debugger + self.w = W.Window((300, 250), 'Breakpoints', minsize = (200, 200)) + self.w.panes = W.HorizontalPanes((8, 8, -8, -32), (0.3, 0.7)) + self.w.panes.files = W.List(None, callback = self.filehit) #, flags = Lists.lOnlyOne) + self.w.panes.gr = W.Group(None) + self.w.panes.gr.breaks = W.List((0, 0, -130, 0), callback = self.linehit) #, flags = Lists.lOnlyOne) + self.w.panes.gr.openbutton = W.Button((-80, 4, 0, 16), 'View\xc9', self.openbuttonhit) + self.w.panes.gr.deletebutton = W.Button((-80, 28, 0, 16), 'Delete', self.deletebuttonhit) + + self.w.bind('<close>', self.close) + self.w.bind('backspace', self.w.panes.gr.deletebutton.push) + + self.setup() + self.w.open() + self.w.panes.gr.openbutton.enable(0) + self.w.panes.gr.deletebutton.enable(0) + self.curfile = None + + def deletebuttonhit(self): + if self.w._currentwidget == self.w.panes.files: + self.del_filename() + else: + self.del_number() + self.checkbuttons() + + def del_number(self): + if self.curfile is None: + return + sel = self.w.panes.gr.breaks.getselectedobjects() + for lineno in sel: + self.debugger.clear_break(self.curfile, lineno) + + def del_filename(self): + sel = self.w.panes.files.getselectedobjects() + for filename in sel: + self.debugger.clear_all_file_breaks(filename) + self.debugger.update_allbreaks() + + def setup(self): + files = self.debugger.breaks.keys() + files.sort() + self.w.panes.files.set(files) + + def close(self): + self.debugger.breaksviewer = None + self.debugger = None + + def update(self): + sel = self.w.panes.files.getselectedobjects() + self.setup() + self.w.panes.files.setselectedobjects(sel) + sel = self.w.panes.files.getselection() + if len(sel) == 0 and self.curfile: + self.w.panes.files.setselectedobjects([self.curfile]) + self.filehit(0) + + def select(self): + self.w.select() + + def selectfile(self, file): + self.w.panes.files.setselectedobjects([file]) + self.filehit(0) + + def openbuttonhit(self): + self.filehit(1) + + def filehit(self, isdbl): + sel = self.w.panes.files.getselectedobjects() + if isdbl: + for filename in sel: + lineno = None + if filename == self.curfile: + linesel = self.w.panes.gr.breaks.getselectedobjects() + if linesel: + lineno = linesel[-1] + elif self.w.panes.gr.breaks: + lineno = self.w.panes.gr.breaks[0] + editor = self.w._parentwindow.parent.openscript(filename, lineno) + editor.showbreakpoints(1) + return + if len(sel) == 1: + file = sel[0] + filebreaks = self.debugger.breaks[file][:] + if self.curfile == file: + linesel = self.w.panes.gr.breaks.getselectedobjects() + self.w.panes.gr.breaks.set(filebreaks) + if self.curfile == file: + self.w.panes.gr.breaks.setselectedobjects(linesel) + self.curfile = file + else: + if len(sel) <> 0: + self.curfile = None + self.w.panes.gr.breaks.set([]) + self.checkbuttons() + + def linehit(self, isdbl): + if isdbl: + files = self.w.panes.files.getselectedobjects() + if len(files) <> 1: + return + filename = files[0] + linenos = self.w.panes.gr.breaks.getselectedobjects() + if not linenos: + return + lineno = linenos[-1] + editor = self.w._parentwindow.parent.openscript(filename, lineno) + editor.showbreakpoints(1) + self.checkbuttons() + + def checkbuttons(self): + if self.w.panes.files.getselection(): + self.w.panes.gr.openbutton.enable(1) + self.w._parentwindow.setdefaultbutton(self.w.panes.gr.openbutton) + if self.w._currentwidget == self.w.panes.files: + if self.w.panes.files.getselection(): + self.w.panes.gr.deletebutton.enable(1) + else: + self.w.panes.gr.deletebutton.enable(0) + else: + if self.w.panes.gr.breaks.getselection(): + self.w.panes.gr.deletebutton.enable(1) + else: + self.w.panes.gr.deletebutton.enable(0) + else: + self.w.panes.gr.openbutton.enable(0) + self.w.panes.gr.deletebutton.enable(0) class TracingMonitor(W.Widget): - - def __init__(self, *args, **kwargs): - apply(W.Widget.__init__, (self,) + args, kwargs) - self.state = 0 - - def toggle(self): - if hasattr(self, "_parentwindow") and self._parentwindow is not None: - self.state = self.state % 2 + 1 - port = Qd.GetPort() - self.SetPort() - self.draw() - Qd.SetPort(port) - - def reset(self): - if self._parentwindow: - self.state = 0 - port = Qd.GetPort() - self.SetPort() - self.draw() - Qd.SetPort(port) - - def draw(self, visRgn = None): - if self.state == 2: - Qd.PaintOval(self._bounds) - else: - Qd.EraseOval(self._bounds) + + def __init__(self, *args, **kwargs): + apply(W.Widget.__init__, (self,) + args, kwargs) + self.state = 0 + + def toggle(self): + if hasattr(self, "_parentwindow") and self._parentwindow is not None: + self.state = self.state % 2 + 1 + port = Qd.GetPort() + self.SetPort() + self.draw() + Qd.SetPort(port) + + def reset(self): + if self._parentwindow: + self.state = 0 + port = Qd.GetPort() + self.SetPort() + self.draw() + Qd.SetPort(port) + + def draw(self, visRgn = None): + if self.state == 2: + Qd.PaintOval(self._bounds) + else: + Qd.EraseOval(self._bounds) # convenience funcs def postmortem(exc_type, exc_value, tb): - d = getdebugger() - d.postmortem(exc_type, exc_value, tb) + d = getdebugger() + d.postmortem(exc_type, exc_value, tb) def start(bottomframe = None): - d = getdebugger() - d.start(bottomframe) + d = getdebugger() + d.start(bottomframe) def startfromhere(): - d = getdebugger() - try: - raise 'spam' - except: - frame = sys.exc_traceback.tb_frame.f_back - d.start(frame) + d = getdebugger() + try: + raise 'spam' + except: + frame = sys.exc_traceback.tb_frame.f_back + d.start(frame) def startfrombottom(): - d = getdebugger() - d.start(_getbottomframe(), 1) + d = getdebugger() + d.start(_getbottomframe(), 1) def stop(): - d = getdebugger() - d.stop() + d = getdebugger() + d.stop() def cont(): - sys.settrace(None) - d = getdebugger() - d.set_continue_without_debugger() + sys.settrace(None) + d = getdebugger() + d.set_continue_without_debugger() def _getbottomframe(): - try: - raise 'spam' - except: - pass - frame = sys.exc_traceback.tb_frame - while 1: - if frame.f_code.co_name == 'mainloop' or frame.f_back is None: - break - frame = frame.f_back - return frame + try: + raise 'spam' + except: + pass + frame = sys.exc_traceback.tb_frame + while 1: + if frame.f_code.co_name == 'mainloop' or frame.f_back is None: + break + frame = frame.f_back + return frame _debugger = None def getdebugger(): - if not __debug__: - raise W.AlertError, "Can't debug in \"Optimize bytecode\" mode.\r(see \"Default startup options\" in EditPythonPreferences)" - global _debugger - if _debugger is None: - _debugger = Debugger() - return _debugger + if not __debug__: + raise W.AlertError, "Can't debug in \"Optimize bytecode\" mode.\r(see \"Default startup options\" in EditPythonPreferences)" + global _debugger + if _debugger is None: + _debugger = Debugger() + return _debugger diff --git a/Mac/Tools/IDE/PyDocSearch.py b/Mac/Tools/IDE/PyDocSearch.py index 1abd4cd..ec666b6 100644 --- a/Mac/Tools/IDE/PyDocSearch.py +++ b/Mac/Tools/IDE/PyDocSearch.py @@ -13,244 +13,244 @@ 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 + 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 + 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) + + 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 __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 + 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 + (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()) + + 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()) diff --git a/Mac/Tools/IDE/PyEdit.py b/Mac/Tools/IDE/PyEdit.py index ce228ff..88c72ac 100644 --- a/Mac/Tools/IDE/PyEdit.py +++ b/Mac/Tools/IDE/PyEdit.py @@ -21,9 +21,9 @@ import re smAllScripts = -3 if hasattr(Win, "FrontNonFloatingWindow"): - MyFrontWindow = Win.FrontNonFloatingWindow + MyFrontWindow = Win.FrontNonFloatingWindow else: - MyFrontWindow = Win.FrontWindow + MyFrontWindow = Win.FrontWindow _scriptuntitledcounter = 1 @@ -35,1328 +35,1328 @@ runSelButtonLabels = ["Run selection", "Pause!", "Resume"] class Editor(W.Window): - - def __init__(self, path = "", title = ""): - defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs() - global _scriptuntitledcounter - if not path: - if title: - self.title = title - else: - self.title = "Untitled Script %r" % (_scriptuntitledcounter,) - _scriptuntitledcounter = _scriptuntitledcounter + 1 - text = "" - self._creator = W._signature - self._eoln = os.linesep - elif os.path.exists(path): - path = resolvealiases(path) - dir, name = os.path.split(path) - self.title = name - f = open(path, "rb") - text = f.read() - f.close() - self._creator, filetype = MacOS.GetCreatorAndType(path) - self.addrecentfile(path) - if '\n' in text: - if string.find(text, '\r\n') >= 0: - self._eoln = '\r\n' - else: - self._eoln = '\n' - text = string.replace(text, self._eoln, '\r') - else: - self._eoln = '\r' - else: - raise IOError, "file '%s' does not exist" % path - self.path = path - - self.settings = {} - if self.path: - self.readwindowsettings() - if self.settings.has_key("windowbounds"): - bounds = self.settings["windowbounds"] - else: - bounds = defaultwindowsize - if self.settings.has_key("fontsettings"): - self.fontsettings = self.settings["fontsettings"] - else: - self.fontsettings = defaultfontsettings - if self.settings.has_key("tabsize"): - try: - self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"] - except: - self.tabsettings = defaulttabsettings - else: - self.tabsettings = defaulttabsettings - - W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0) - self.setupwidgets(text) - - if self.settings.has_key("selection"): - selstart, selend = self.settings["selection"] - self.setselection(selstart, selend) - self.open() - self.setinfotext() - self.globals = {} - self._buf = "" # for write method - self.debugging = 0 - self.profiling = 0 - self.run_as_main = self.settings.get("run_as_main", 0) - self.run_with_interpreter = self.settings.get("run_with_interpreter", 0) - self.run_with_cl_interpreter = self.settings.get("run_with_cl_interpreter", 0) - - def readwindowsettings(self): - try: - resref = Res.FSpOpenResFile(self.path, 1) - except Res.Error: - return - try: - Res.UseResFile(resref) - data = Res.Get1Resource('PyWS', 128) - self.settings = marshal.loads(data.data) - except: - pass - Res.CloseResFile(resref) - - def writewindowsettings(self): - try: - resref = Res.FSpOpenResFile(self.path, 3) - except Res.Error: - Res.FSpCreateResFile(self.path, self._creator, 'TEXT', smAllScripts) - resref = Res.FSpOpenResFile(self.path, 3) - try: - data = Res.Resource(marshal.dumps(self.settings)) - Res.UseResFile(resref) - try: - temp = Res.Get1Resource('PyWS', 128) - temp.RemoveResource() - except Res.Error: - pass - data.AddResource('PyWS', 128, "window settings") - finally: - Res.UpdateResFile(resref) - Res.CloseResFile(resref) - - def getsettings(self): - self.settings = {} - self.settings["windowbounds"] = self.getbounds() - self.settings["selection"] = self.getselection() - self.settings["fontsettings"] = self.editgroup.editor.getfontsettings() - self.settings["tabsize"] = self.editgroup.editor.gettabsettings() - self.settings["run_as_main"] = self.run_as_main - self.settings["run_with_interpreter"] = self.run_with_interpreter - self.settings["run_with_cl_interpreter"] = self.run_with_cl_interpreter - - def get(self): - return self.editgroup.editor.get() - - def getselection(self): - return self.editgroup.editor.ted.WEGetSelection() - - def setselection(self, selstart, selend): - self.editgroup.editor.setselection(selstart, selend) - - def getselectedtext(self): - return self.editgroup.editor.getselectedtext() - - def getfilename(self): - if self.path: - return self.path - return '<%s>' % self.title - - def setupwidgets(self, text): - topbarheight = 24 - popfieldwidth = 80 - self.lastlineno = None - - # make an editor - self.editgroup = W.Group((0, topbarheight + 1, 0, 0)) - editor = W.PyEditor((0, 0, -15,-15), text, - fontsettings = self.fontsettings, - tabsettings = self.tabsettings, - file = self.getfilename()) - - # make the widgets - self.popfield = ClassFinder((popfieldwidth - 17, -15, 16, 16), [], self.popselectline) - self.linefield = W.EditText((-1, -15, popfieldwidth - 15, 16), inset = (6, 1)) - self.editgroup._barx = W.Scrollbar((popfieldwidth - 2, -15, -14, 16), editor.hscroll, max = 32767) - self.editgroup._bary = W.Scrollbar((-15, 14, 16, -14), editor.vscroll, max = 32767) - self.editgroup.editor = editor # add editor *after* scrollbars - - self.editgroup.optionsmenu = W.PopupMenu((-15, -1, 16, 16), []) - self.editgroup.optionsmenu.bind('<click>', self.makeoptionsmenu) - - self.bevelbox = W.BevelBox((0, 0, 0, topbarheight)) - self.hline = W.HorizontalLine((0, topbarheight, 0, 0)) - self.infotext = W.TextBox((175, 6, -4, 14), backgroundcolor = (0xe000, 0xe000, 0xe000)) - self.runbutton = W.BevelButton((6, 4, 80, 16), runButtonLabels[0], self.run) - self.runselbutton = W.BevelButton((90, 4, 80, 16), runSelButtonLabels[0], self.runselection) - - # bind some keys - editor.bind("cmdr", self.runbutton.push) - editor.bind("enter", self.runselbutton.push) - editor.bind("cmdj", self.domenu_gotoline) - editor.bind("cmdd", self.domenu_toggledebugger) - editor.bind("<idle>", self.updateselection) - - editor.bind("cmde", searchengine.setfindstring) - editor.bind("cmdf", searchengine.show) - editor.bind("cmdg", searchengine.findnext) - editor.bind("cmdshiftr", searchengine.replace) - editor.bind("cmdt", searchengine.replacefind) - - self.linefield.bind("return", self.dolinefield) - self.linefield.bind("enter", self.dolinefield) - self.linefield.bind("tab", self.dolinefield) - - # intercept clicks - editor.bind("<click>", self.clickeditor) - self.linefield.bind("<click>", self.clicklinefield) - - def makeoptionsmenu(self): - menuitems = [('Font settings\xc9', self.domenu_fontsettings), - ("Save options\xc9", self.domenu_options), - '-', - ('\0' + chr(self.run_as_main) + 'Run as __main__', self.domenu_toggle_run_as_main), - #('\0' + chr(self.run_with_interpreter) + 'Run with Interpreter', self.domenu_dtoggle_run_with_interpreter), - ('\0' + chr(self.run_with_cl_interpreter) + 'Run with commandline Python', self.domenu_toggle_run_with_cl_interpreter), - '-', - ('Modularize', self.domenu_modularize), - ('Browse namespace\xc9', self.domenu_browsenamespace), - '-'] - if self.profiling: - menuitems = menuitems + [('Disable profiler', self.domenu_toggleprofiler)] - else: - menuitems = menuitems + [('Enable profiler', self.domenu_toggleprofiler)] - if self.editgroup.editor._debugger: - menuitems = menuitems + [('Disable debugger', self.domenu_toggledebugger), - ('Clear breakpoints', self.domenu_clearbreakpoints), - ('Edit breakpoints\xc9', self.domenu_editbreakpoints)] - else: - menuitems = menuitems + [('Enable debugger', self.domenu_toggledebugger)] - self.editgroup.optionsmenu.set(menuitems) - - def domenu_toggle_run_as_main(self): - self.run_as_main = not self.run_as_main - self.run_with_interpreter = 0 - self.run_with_cl_interpreter = 0 - self.editgroup.editor.selectionchanged() - - def XXdomenu_toggle_run_with_interpreter(self): - self.run_with_interpreter = not self.run_with_interpreter - self.run_as_main = 0 - self.run_with_cl_interpreter = 0 - self.editgroup.editor.selectionchanged() - - def domenu_toggle_run_with_cl_interpreter(self): - self.run_with_cl_interpreter = not self.run_with_cl_interpreter - self.run_as_main = 0 - self.run_with_interpreter = 0 - self.editgroup.editor.selectionchanged() - - def showbreakpoints(self, onoff): - self.editgroup.editor.showbreakpoints(onoff) - self.debugging = onoff - - def domenu_clearbreakpoints(self, *args): - self.editgroup.editor.clearbreakpoints() - - def domenu_editbreakpoints(self, *args): - self.editgroup.editor.editbreakpoints() - - def domenu_toggledebugger(self, *args): - if not self.debugging: - W.SetCursor('watch') - self.debugging = not self.debugging - self.editgroup.editor.togglebreakpoints() - - def domenu_toggleprofiler(self, *args): - self.profiling = not self.profiling - - def domenu_browsenamespace(self, *args): - import PyBrowser, W - W.SetCursor('watch') - globals, file, modname = self.getenvironment() - if not modname: - modname = self.title - PyBrowser.Browser(globals, "Object browser: " + modname) - - def domenu_modularize(self, *args): - modname = _filename_as_modname(self.title) - if not modname: - raise W.AlertError, "Can't modularize \"%s\"" % self.title - run_as_main = self.run_as_main - self.run_as_main = 0 - self.run() - self.run_as_main = run_as_main - if self.path: - file = self.path - else: - file = self.title - - if self.globals and not sys.modules.has_key(modname): - module = imp.new_module(modname) - for attr in self.globals.keys(): - setattr(module,attr,self.globals[attr]) - sys.modules[modname] = module - self.globals = {} - - def domenu_fontsettings(self, *args): - import FontSettings - fontsettings = self.editgroup.editor.getfontsettings() - tabsettings = self.editgroup.editor.gettabsettings() - settings = FontSettings.FontDialog(fontsettings, tabsettings) - if settings: - fontsettings, tabsettings = settings - self.editgroup.editor.setfontsettings(fontsettings) - self.editgroup.editor.settabsettings(tabsettings) - - def domenu_options(self, *args): - rv = SaveOptions(self._creator, self._eoln) - if rv: - self.editgroup.editor.selectionchanged() # ouch... - self._creator, self._eoln = rv - - def clicklinefield(self): - if self._currentwidget <> self.linefield: - self.linefield.select(1) - self.linefield.selectall() - return 1 - - def clickeditor(self): - if self._currentwidget <> self.editgroup.editor: - self.dolinefield() - return 1 - - def updateselection(self, force = 0): - sel = min(self.editgroup.editor.getselection()) - lineno = self.editgroup.editor.offsettoline(sel) - if lineno <> self.lastlineno or force: - self.lastlineno = lineno - self.linefield.set(str(lineno + 1)) - self.linefield.selview() - - def dolinefield(self): - try: - lineno = string.atoi(self.linefield.get()) - 1 - if lineno <> self.lastlineno: - self.editgroup.editor.selectline(lineno) - self.updateselection(1) - except: - self.updateselection(1) - self.editgroup.editor.select(1) - - def setinfotext(self): - if not hasattr(self, 'infotext'): - return - if self.path: - self.infotext.set(self.path) - else: - self.infotext.set("") - - def close(self): - if self.editgroup.editor.changed: - Qd.InitCursor() - save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?' % self.title, - default=1, no="Don\xd5t save") - if save > 0: - if self.domenu_save(): - return 1 - elif save < 0: - return 1 - self.globals = None - W.Window.close(self) - - def domenu_close(self, *args): - return self.close() - - def domenu_save(self, *args): - if not self.path: - # Will call us recursively - return self.domenu_save_as() - data = self.editgroup.editor.get() - if self._eoln != '\r': - data = string.replace(data, '\r', self._eoln) - fp = open(self.path, 'wb') # open file in binary mode, data has '\r' line-endings - fp.write(data) - fp.close() - MacOS.SetCreatorAndType(self.path, self._creator, 'TEXT') - self.getsettings() - self.writewindowsettings() - self.editgroup.editor.changed = 0 - self.editgroup.editor.selchanged = 0 - import linecache - if linecache.cache.has_key(self.path): - del linecache.cache[self.path] - import macostools - macostools.touched(self.path) - self.addrecentfile(self.path) - - def can_save(self, menuitem): - return self.editgroup.editor.changed or self.editgroup.editor.selchanged - - def domenu_save_as(self, *args): - path = EasyDialogs.AskFileForSave(message='Save as:', savedFileName=self.title) - if not path: - return 1 - self.showbreakpoints(0) - self.path = path - self.setinfotext() - self.title = os.path.split(self.path)[-1] - self.wid.SetWTitle(self.title) - self.domenu_save() - self.editgroup.editor.setfile(self.getfilename()) - app = W.getapplication() - app.makeopenwindowsmenu() - if hasattr(app, 'makescriptsmenu'): - app = W.getapplication() - fsr, changed = app.scriptsfolder.FSResolveAlias(None) - path = fsr.as_pathname() - if path == self.path[:len(path)]: - W.getapplication().makescriptsmenu() - - def domenu_save_as_applet(self, *args): - import buildtools - - buildtools.DEBUG = 0 # ouch. - - if self.title[-3:] == ".py": - destname = self.title[:-3] - else: - destname = self.title + ".applet" - destname = EasyDialogs.AskFileForSave(message='Save as Applet:', - savedFileName=destname) - if not destname: - return 1 - W.SetCursor("watch") - if self.path: - filename = self.path - if filename[-3:] == ".py": - rsrcname = filename[:-3] + '.rsrc' - else: - rsrcname = filename + '.rsrc' - else: - filename = self.title - rsrcname = "" - - pytext = self.editgroup.editor.get() - pytext = string.split(pytext, '\r') - pytext = string.join(pytext, '\n') + '\n' - try: - code = compile(pytext, filename, "exec") - except (SyntaxError, EOFError): - raise buildtools.BuildError, "Syntax error in script %r" % (filename,) - - import tempfile - tmpdir = tempfile.mkdtemp() - - if filename[-3:] != ".py": - filename = filename + ".py" - filename = os.path.join(tmpdir, os.path.split(filename)[1]) - fp = open(filename, "w") - fp.write(pytext) - fp.close() - - # Try removing the output file - try: - os.remove(destname) - except os.error: - pass - template = buildtools.findtemplate() - buildtools.process(template, filename, destname, 1, rsrcname=rsrcname, progress=None) - try: - os.remove(filename) - os.rmdir(tmpdir) - except os.error: - pass - - def domenu_gotoline(self, *args): - self.linefield.selectall() - self.linefield.select(1) - self.linefield.selectall() - - def domenu_selectline(self, *args): - self.editgroup.editor.expandselection() - - def domenu_find(self, *args): - searchengine.show() - - def domenu_entersearchstring(self, *args): - searchengine.setfindstring() - - def domenu_replace(self, *args): - searchengine.replace() - - def domenu_findnext(self, *args): - searchengine.findnext() - - def domenu_replacefind(self, *args): - searchengine.replacefind() - - def domenu_run(self, *args): - self.runbutton.push() - - def domenu_runselection(self, *args): - self.runselbutton.push() - - def run(self): - self._run() - - def _run(self): - if self.run_with_interpreter: - if self.editgroup.editor.changed: - Qd.InitCursor() - save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1) - if save > 0: - if self.domenu_save(): - return - elif save < 0: - return - if not self.path: - raise W.AlertError, "Can't run unsaved file" - self._run_with_interpreter() - elif self.run_with_cl_interpreter: - if self.editgroup.editor.changed: - Qd.InitCursor() - save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1) - if save > 0: - if self.domenu_save(): - return - elif save < 0: - return - if not self.path: - raise W.AlertError, "Can't run unsaved file" - self._run_with_cl_interpreter() - else: - pytext = self.editgroup.editor.get() - globals, file, modname = self.getenvironment() - self.execstring(pytext, globals, globals, file, modname) - - def _run_with_interpreter(self): - interp_path = os.path.join(sys.exec_prefix, "PythonInterpreter") - if not os.path.exists(interp_path): - raise W.AlertError, "Can't find interpreter" - import findertools - XXX - - def _run_with_cl_interpreter(self): - import Terminal - interp_path = os.path.join(sys.exec_prefix, - "Resources", "Python.app", "Contents", "MacOS", "Python") - if not os.path.exists(interp_path): - interp_path = os.path.join(sys.exec_prefix, "bin", "python") - file_path = self.path - if not os.path.exists(interp_path): - # This "can happen" if we are running IDE under MacPython-OS9. - raise W.AlertError, "Can't find command-line Python" - cmd = '"%s" "%s" ; exit' % (interp_path, file_path) - t = Terminal.Terminal() - t.do_script(cmd) - - def runselection(self): - self._runselection() - - def _runselection(self): - if self.run_with_interpreter or self.run_with_cl_interpreter: - raise W.AlertError, "Can't run selection with Interpreter" - globals, file, modname = self.getenvironment() - locals = globals - # select whole lines - self.editgroup.editor.expandselection() - - # get lineno of first selected line - selstart, selend = self.editgroup.editor.getselection() - selstart, selend = min(selstart, selend), max(selstart, selend) - selfirstline = self.editgroup.editor.offsettoline(selstart) - alltext = self.editgroup.editor.get() - pytext = alltext[selstart:selend] - lines = string.split(pytext, '\r') - indent = getminindent(lines) - if indent == 1: - classname = '' - alllines = string.split(alltext, '\r') - for i in range(selfirstline - 1, -1, -1): - line = alllines[i] - if line[:6] == 'class ': - classname = string.split(string.strip(line[6:]))[0] - classend = identifieRE_match(classname) - if classend < 1: - raise W.AlertError, "Can't find a class." - classname = classname[:classend] - break - elif line and line[0] not in '\t#': - raise W.AlertError, "Can't find a class." - else: - raise W.AlertError, "Can't find a class." - if globals.has_key(classname): - klass = globals[classname] - else: - raise W.AlertError, "Can't find class \"%s\"." % classname - # add class def - pytext = ("class %s:\n" % classname) + pytext - selfirstline = selfirstline - 1 - elif indent > 0: - raise W.AlertError, "Can't run indented code." - - # add "newlines" to fool compile/exec: - # now a traceback will give the right line number - pytext = selfirstline * '\r' + pytext - self.execstring(pytext, globals, locals, file, modname) - if indent == 1 and globals[classname] is not klass: - # update the class in place - klass.__dict__.update(globals[classname].__dict__) - globals[classname] = klass - - def execstring(self, pytext, globals, locals, file, modname): - tracebackwindow.hide() - # update windows - W.getapplication().refreshwindows() - if self.run_as_main: - modname = "__main__" - if self.path: - dir = os.path.dirname(self.path) - savedir = os.getcwd() - os.chdir(dir) - sys.path.insert(0, dir) - self._scriptDone = False - if sys.platform == "darwin": - # On MacOSX, MacPython doesn't poll for command-period - # (cancel), so to enable the user to cancel a running - # script, we have to spawn a thread which does the - # polling. It will send a SIGINT to the main thread - # (in which the script is running) when the user types - # command-period. - from threading import Thread - t = Thread(target=self._userCancelledMonitor, - name="UserCancelledMonitor") - t.start() - try: - execstring(pytext, globals, locals, file, self.debugging, - modname, self.profiling) - finally: - self._scriptDone = True - if self.path: - os.chdir(savedir) - del sys.path[0] - - def _userCancelledMonitor(self): - import time - from signal import SIGINT - while not self._scriptDone: - if Evt.CheckEventQueueForUserCancel(): - # Send a SIGINT signal to ourselves. - # This gets delivered to the main thread, - # cancelling the running script. - os.kill(os.getpid(), SIGINT) - break - time.sleep(0.25) - - def getenvironment(self): - if self.path: - file = self.path - dir = os.path.dirname(file) - # check if we're part of a package - modname = "" - while os.path.exists(os.path.join(dir, "__init__.py")): - dir, dirname = os.path.split(dir) - modname = dirname + '.' + modname - subname = _filename_as_modname(self.title) - if subname is None: - return self.globals, file, None - if modname: - if subname == "__init__": - # strip trailing period - modname = modname[:-1] - else: - modname = modname + subname - else: - modname = subname - if sys.modules.has_key(modname): - globals = sys.modules[modname].__dict__ - self.globals = {} - else: - globals = self.globals - modname = subname - else: - file = '<%s>' % self.title - globals = self.globals - modname = file - return globals, file, modname - - def write(self, stuff): - """for use as stdout""" - self._buf = self._buf + stuff - if '\n' in self._buf: - self.flush() - - def flush(self): - stuff = string.split(self._buf, '\n') - stuff = string.join(stuff, '\r') - end = self.editgroup.editor.ted.WEGetTextLength() - self.editgroup.editor.ted.WESetSelection(end, end) - self.editgroup.editor.ted.WEInsert(stuff, None, None) - self.editgroup.editor.updatescrollbars() - self._buf = "" - # ? optional: - #self.wid.SelectWindow() - - def getclasslist(self): - from string import find, strip - methodRE = re.compile(r"\r[ \t]+def ") - findMethod = methodRE.search - editor = self.editgroup.editor - text = editor.get() - list = [] - append = list.append - functag = "func" - classtag = "class" - methodtag = "method" - pos = -1 - if text[:4] == 'def ': - append((pos + 4, functag)) - pos = 4 - while 1: - pos = find(text, '\rdef ', pos + 1) - if pos < 0: - break - append((pos + 5, functag)) - pos = -1 - if text[:6] == 'class ': - append((pos + 6, classtag)) - pos = 6 - while 1: - pos = find(text, '\rclass ', pos + 1) - if pos < 0: - break - append((pos + 7, classtag)) - pos = 0 - while 1: - m = findMethod(text, pos + 1) - if m is None: - break - pos = m.regs[0][0] - #pos = find(text, '\r\tdef ', pos + 1) - append((m.regs[0][1], methodtag)) - list.sort() - classlist = [] - methodlistappend = None - offsetToLine = editor.ted.WEOffsetToLine - getLineRange = editor.ted.WEGetLineRange - append = classlist.append - for pos, tag in list: - lineno = offsetToLine(pos) - lineStart, lineEnd = getLineRange(lineno) - line = strip(text[pos:lineEnd]) - line = line[:identifieRE_match(line)] - if tag is functag: - append(("def " + line, lineno + 1)) - methodlistappend = None - elif tag is classtag: - append(["class " + line]) - methodlistappend = classlist[-1].append - elif methodlistappend and tag is methodtag: - methodlistappend(("def " + line, lineno + 1)) - return classlist - - def popselectline(self, lineno): - self.editgroup.editor.selectline(lineno - 1) - - def selectline(self, lineno, charoffset = 0): - self.editgroup.editor.selectline(lineno - 1, charoffset) - - def addrecentfile(self, filename): - app = W.getapplication() - app.addrecentfile(filename) + + def __init__(self, path = "", title = ""): + defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs() + global _scriptuntitledcounter + if not path: + if title: + self.title = title + else: + self.title = "Untitled Script %r" % (_scriptuntitledcounter,) + _scriptuntitledcounter = _scriptuntitledcounter + 1 + text = "" + self._creator = W._signature + self._eoln = os.linesep + elif os.path.exists(path): + path = resolvealiases(path) + dir, name = os.path.split(path) + self.title = name + f = open(path, "rb") + text = f.read() + f.close() + self._creator, filetype = MacOS.GetCreatorAndType(path) + self.addrecentfile(path) + if '\n' in text: + if string.find(text, '\r\n') >= 0: + self._eoln = '\r\n' + else: + self._eoln = '\n' + text = string.replace(text, self._eoln, '\r') + else: + self._eoln = '\r' + else: + raise IOError, "file '%s' does not exist" % path + self.path = path + + self.settings = {} + if self.path: + self.readwindowsettings() + if self.settings.has_key("windowbounds"): + bounds = self.settings["windowbounds"] + else: + bounds = defaultwindowsize + if self.settings.has_key("fontsettings"): + self.fontsettings = self.settings["fontsettings"] + else: + self.fontsettings = defaultfontsettings + if self.settings.has_key("tabsize"): + try: + self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"] + except: + self.tabsettings = defaulttabsettings + else: + self.tabsettings = defaulttabsettings + + W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0) + self.setupwidgets(text) + + if self.settings.has_key("selection"): + selstart, selend = self.settings["selection"] + self.setselection(selstart, selend) + self.open() + self.setinfotext() + self.globals = {} + self._buf = "" # for write method + self.debugging = 0 + self.profiling = 0 + self.run_as_main = self.settings.get("run_as_main", 0) + self.run_with_interpreter = self.settings.get("run_with_interpreter", 0) + self.run_with_cl_interpreter = self.settings.get("run_with_cl_interpreter", 0) + + def readwindowsettings(self): + try: + resref = Res.FSpOpenResFile(self.path, 1) + except Res.Error: + return + try: + Res.UseResFile(resref) + data = Res.Get1Resource('PyWS', 128) + self.settings = marshal.loads(data.data) + except: + pass + Res.CloseResFile(resref) + + def writewindowsettings(self): + try: + resref = Res.FSpOpenResFile(self.path, 3) + except Res.Error: + Res.FSpCreateResFile(self.path, self._creator, 'TEXT', smAllScripts) + resref = Res.FSpOpenResFile(self.path, 3) + try: + data = Res.Resource(marshal.dumps(self.settings)) + Res.UseResFile(resref) + try: + temp = Res.Get1Resource('PyWS', 128) + temp.RemoveResource() + except Res.Error: + pass + data.AddResource('PyWS', 128, "window settings") + finally: + Res.UpdateResFile(resref) + Res.CloseResFile(resref) + + def getsettings(self): + self.settings = {} + self.settings["windowbounds"] = self.getbounds() + self.settings["selection"] = self.getselection() + self.settings["fontsettings"] = self.editgroup.editor.getfontsettings() + self.settings["tabsize"] = self.editgroup.editor.gettabsettings() + self.settings["run_as_main"] = self.run_as_main + self.settings["run_with_interpreter"] = self.run_with_interpreter + self.settings["run_with_cl_interpreter"] = self.run_with_cl_interpreter + + def get(self): + return self.editgroup.editor.get() + + def getselection(self): + return self.editgroup.editor.ted.WEGetSelection() + + def setselection(self, selstart, selend): + self.editgroup.editor.setselection(selstart, selend) + + def getselectedtext(self): + return self.editgroup.editor.getselectedtext() + + def getfilename(self): + if self.path: + return self.path + return '<%s>' % self.title + + def setupwidgets(self, text): + topbarheight = 24 + popfieldwidth = 80 + self.lastlineno = None + + # make an editor + self.editgroup = W.Group((0, topbarheight + 1, 0, 0)) + editor = W.PyEditor((0, 0, -15,-15), text, + fontsettings = self.fontsettings, + tabsettings = self.tabsettings, + file = self.getfilename()) + + # make the widgets + self.popfield = ClassFinder((popfieldwidth - 17, -15, 16, 16), [], self.popselectline) + self.linefield = W.EditText((-1, -15, popfieldwidth - 15, 16), inset = (6, 1)) + self.editgroup._barx = W.Scrollbar((popfieldwidth - 2, -15, -14, 16), editor.hscroll, max = 32767) + self.editgroup._bary = W.Scrollbar((-15, 14, 16, -14), editor.vscroll, max = 32767) + self.editgroup.editor = editor # add editor *after* scrollbars + + self.editgroup.optionsmenu = W.PopupMenu((-15, -1, 16, 16), []) + self.editgroup.optionsmenu.bind('<click>', self.makeoptionsmenu) + + self.bevelbox = W.BevelBox((0, 0, 0, topbarheight)) + self.hline = W.HorizontalLine((0, topbarheight, 0, 0)) + self.infotext = W.TextBox((175, 6, -4, 14), backgroundcolor = (0xe000, 0xe000, 0xe000)) + self.runbutton = W.BevelButton((6, 4, 80, 16), runButtonLabels[0], self.run) + self.runselbutton = W.BevelButton((90, 4, 80, 16), runSelButtonLabels[0], self.runselection) + + # bind some keys + editor.bind("cmdr", self.runbutton.push) + editor.bind("enter", self.runselbutton.push) + editor.bind("cmdj", self.domenu_gotoline) + editor.bind("cmdd", self.domenu_toggledebugger) + editor.bind("<idle>", self.updateselection) + + editor.bind("cmde", searchengine.setfindstring) + editor.bind("cmdf", searchengine.show) + editor.bind("cmdg", searchengine.findnext) + editor.bind("cmdshiftr", searchengine.replace) + editor.bind("cmdt", searchengine.replacefind) + + self.linefield.bind("return", self.dolinefield) + self.linefield.bind("enter", self.dolinefield) + self.linefield.bind("tab", self.dolinefield) + + # intercept clicks + editor.bind("<click>", self.clickeditor) + self.linefield.bind("<click>", self.clicklinefield) + + def makeoptionsmenu(self): + menuitems = [('Font settings\xc9', self.domenu_fontsettings), + ("Save options\xc9", self.domenu_options), + '-', + ('\0' + chr(self.run_as_main) + 'Run as __main__', self.domenu_toggle_run_as_main), + #('\0' + chr(self.run_with_interpreter) + 'Run with Interpreter', self.domenu_dtoggle_run_with_interpreter), + ('\0' + chr(self.run_with_cl_interpreter) + 'Run with commandline Python', self.domenu_toggle_run_with_cl_interpreter), + '-', + ('Modularize', self.domenu_modularize), + ('Browse namespace\xc9', self.domenu_browsenamespace), + '-'] + if self.profiling: + menuitems = menuitems + [('Disable profiler', self.domenu_toggleprofiler)] + else: + menuitems = menuitems + [('Enable profiler', self.domenu_toggleprofiler)] + if self.editgroup.editor._debugger: + menuitems = menuitems + [('Disable debugger', self.domenu_toggledebugger), + ('Clear breakpoints', self.domenu_clearbreakpoints), + ('Edit breakpoints\xc9', self.domenu_editbreakpoints)] + else: + menuitems = menuitems + [('Enable debugger', self.domenu_toggledebugger)] + self.editgroup.optionsmenu.set(menuitems) + + def domenu_toggle_run_as_main(self): + self.run_as_main = not self.run_as_main + self.run_with_interpreter = 0 + self.run_with_cl_interpreter = 0 + self.editgroup.editor.selectionchanged() + + def XXdomenu_toggle_run_with_interpreter(self): + self.run_with_interpreter = not self.run_with_interpreter + self.run_as_main = 0 + self.run_with_cl_interpreter = 0 + self.editgroup.editor.selectionchanged() + + def domenu_toggle_run_with_cl_interpreter(self): + self.run_with_cl_interpreter = not self.run_with_cl_interpreter + self.run_as_main = 0 + self.run_with_interpreter = 0 + self.editgroup.editor.selectionchanged() + + def showbreakpoints(self, onoff): + self.editgroup.editor.showbreakpoints(onoff) + self.debugging = onoff + + def domenu_clearbreakpoints(self, *args): + self.editgroup.editor.clearbreakpoints() + + def domenu_editbreakpoints(self, *args): + self.editgroup.editor.editbreakpoints() + + def domenu_toggledebugger(self, *args): + if not self.debugging: + W.SetCursor('watch') + self.debugging = not self.debugging + self.editgroup.editor.togglebreakpoints() + + def domenu_toggleprofiler(self, *args): + self.profiling = not self.profiling + + def domenu_browsenamespace(self, *args): + import PyBrowser, W + W.SetCursor('watch') + globals, file, modname = self.getenvironment() + if not modname: + modname = self.title + PyBrowser.Browser(globals, "Object browser: " + modname) + + def domenu_modularize(self, *args): + modname = _filename_as_modname(self.title) + if not modname: + raise W.AlertError, "Can't modularize \"%s\"" % self.title + run_as_main = self.run_as_main + self.run_as_main = 0 + self.run() + self.run_as_main = run_as_main + if self.path: + file = self.path + else: + file = self.title + + if self.globals and not sys.modules.has_key(modname): + module = imp.new_module(modname) + for attr in self.globals.keys(): + setattr(module,attr,self.globals[attr]) + sys.modules[modname] = module + self.globals = {} + + def domenu_fontsettings(self, *args): + import FontSettings + fontsettings = self.editgroup.editor.getfontsettings() + tabsettings = self.editgroup.editor.gettabsettings() + settings = FontSettings.FontDialog(fontsettings, tabsettings) + if settings: + fontsettings, tabsettings = settings + self.editgroup.editor.setfontsettings(fontsettings) + self.editgroup.editor.settabsettings(tabsettings) + + def domenu_options(self, *args): + rv = SaveOptions(self._creator, self._eoln) + if rv: + self.editgroup.editor.selectionchanged() # ouch... + self._creator, self._eoln = rv + + def clicklinefield(self): + if self._currentwidget <> self.linefield: + self.linefield.select(1) + self.linefield.selectall() + return 1 + + def clickeditor(self): + if self._currentwidget <> self.editgroup.editor: + self.dolinefield() + return 1 + + def updateselection(self, force = 0): + sel = min(self.editgroup.editor.getselection()) + lineno = self.editgroup.editor.offsettoline(sel) + if lineno <> self.lastlineno or force: + self.lastlineno = lineno + self.linefield.set(str(lineno + 1)) + self.linefield.selview() + + def dolinefield(self): + try: + lineno = string.atoi(self.linefield.get()) - 1 + if lineno <> self.lastlineno: + self.editgroup.editor.selectline(lineno) + self.updateselection(1) + except: + self.updateselection(1) + self.editgroup.editor.select(1) + + def setinfotext(self): + if not hasattr(self, 'infotext'): + return + if self.path: + self.infotext.set(self.path) + else: + self.infotext.set("") + + def close(self): + if self.editgroup.editor.changed: + Qd.InitCursor() + save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?' % self.title, + default=1, no="Don\xd5t save") + if save > 0: + if self.domenu_save(): + return 1 + elif save < 0: + return 1 + self.globals = None + W.Window.close(self) + + def domenu_close(self, *args): + return self.close() + + def domenu_save(self, *args): + if not self.path: + # Will call us recursively + return self.domenu_save_as() + data = self.editgroup.editor.get() + if self._eoln != '\r': + data = string.replace(data, '\r', self._eoln) + fp = open(self.path, 'wb') # open file in binary mode, data has '\r' line-endings + fp.write(data) + fp.close() + MacOS.SetCreatorAndType(self.path, self._creator, 'TEXT') + self.getsettings() + self.writewindowsettings() + self.editgroup.editor.changed = 0 + self.editgroup.editor.selchanged = 0 + import linecache + if linecache.cache.has_key(self.path): + del linecache.cache[self.path] + import macostools + macostools.touched(self.path) + self.addrecentfile(self.path) + + def can_save(self, menuitem): + return self.editgroup.editor.changed or self.editgroup.editor.selchanged + + def domenu_save_as(self, *args): + path = EasyDialogs.AskFileForSave(message='Save as:', savedFileName=self.title) + if not path: + return 1 + self.showbreakpoints(0) + self.path = path + self.setinfotext() + self.title = os.path.split(self.path)[-1] + self.wid.SetWTitle(self.title) + self.domenu_save() + self.editgroup.editor.setfile(self.getfilename()) + app = W.getapplication() + app.makeopenwindowsmenu() + if hasattr(app, 'makescriptsmenu'): + app = W.getapplication() + fsr, changed = app.scriptsfolder.FSResolveAlias(None) + path = fsr.as_pathname() + if path == self.path[:len(path)]: + W.getapplication().makescriptsmenu() + + def domenu_save_as_applet(self, *args): + import buildtools + + buildtools.DEBUG = 0 # ouch. + + if self.title[-3:] == ".py": + destname = self.title[:-3] + else: + destname = self.title + ".applet" + destname = EasyDialogs.AskFileForSave(message='Save as Applet:', + savedFileName=destname) + if not destname: + return 1 + W.SetCursor("watch") + if self.path: + filename = self.path + if filename[-3:] == ".py": + rsrcname = filename[:-3] + '.rsrc' + else: + rsrcname = filename + '.rsrc' + else: + filename = self.title + rsrcname = "" + + pytext = self.editgroup.editor.get() + pytext = string.split(pytext, '\r') + pytext = string.join(pytext, '\n') + '\n' + try: + code = compile(pytext, filename, "exec") + except (SyntaxError, EOFError): + raise buildtools.BuildError, "Syntax error in script %r" % (filename,) + + import tempfile + tmpdir = tempfile.mkdtemp() + + if filename[-3:] != ".py": + filename = filename + ".py" + filename = os.path.join(tmpdir, os.path.split(filename)[1]) + fp = open(filename, "w") + fp.write(pytext) + fp.close() + + # Try removing the output file + try: + os.remove(destname) + except os.error: + pass + template = buildtools.findtemplate() + buildtools.process(template, filename, destname, 1, rsrcname=rsrcname, progress=None) + try: + os.remove(filename) + os.rmdir(tmpdir) + except os.error: + pass + + def domenu_gotoline(self, *args): + self.linefield.selectall() + self.linefield.select(1) + self.linefield.selectall() + + def domenu_selectline(self, *args): + self.editgroup.editor.expandselection() + + def domenu_find(self, *args): + searchengine.show() + + def domenu_entersearchstring(self, *args): + searchengine.setfindstring() + + def domenu_replace(self, *args): + searchengine.replace() + + def domenu_findnext(self, *args): + searchengine.findnext() + + def domenu_replacefind(self, *args): + searchengine.replacefind() + + def domenu_run(self, *args): + self.runbutton.push() + + def domenu_runselection(self, *args): + self.runselbutton.push() + + def run(self): + self._run() + + def _run(self): + if self.run_with_interpreter: + if self.editgroup.editor.changed: + Qd.InitCursor() + save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1) + if save > 0: + if self.domenu_save(): + return + elif save < 0: + return + if not self.path: + raise W.AlertError, "Can't run unsaved file" + self._run_with_interpreter() + elif self.run_with_cl_interpreter: + if self.editgroup.editor.changed: + Qd.InitCursor() + save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1) + if save > 0: + if self.domenu_save(): + return + elif save < 0: + return + if not self.path: + raise W.AlertError, "Can't run unsaved file" + self._run_with_cl_interpreter() + else: + pytext = self.editgroup.editor.get() + globals, file, modname = self.getenvironment() + self.execstring(pytext, globals, globals, file, modname) + + def _run_with_interpreter(self): + interp_path = os.path.join(sys.exec_prefix, "PythonInterpreter") + if not os.path.exists(interp_path): + raise W.AlertError, "Can't find interpreter" + import findertools + XXX + + def _run_with_cl_interpreter(self): + import Terminal + interp_path = os.path.join(sys.exec_prefix, + "Resources", "Python.app", "Contents", "MacOS", "Python") + if not os.path.exists(interp_path): + interp_path = os.path.join(sys.exec_prefix, "bin", "python") + file_path = self.path + if not os.path.exists(interp_path): + # This "can happen" if we are running IDE under MacPython-OS9. + raise W.AlertError, "Can't find command-line Python" + cmd = '"%s" "%s" ; exit' % (interp_path, file_path) + t = Terminal.Terminal() + t.do_script(cmd) + + def runselection(self): + self._runselection() + + def _runselection(self): + if self.run_with_interpreter or self.run_with_cl_interpreter: + raise W.AlertError, "Can't run selection with Interpreter" + globals, file, modname = self.getenvironment() + locals = globals + # select whole lines + self.editgroup.editor.expandselection() + + # get lineno of first selected line + selstart, selend = self.editgroup.editor.getselection() + selstart, selend = min(selstart, selend), max(selstart, selend) + selfirstline = self.editgroup.editor.offsettoline(selstart) + alltext = self.editgroup.editor.get() + pytext = alltext[selstart:selend] + lines = string.split(pytext, '\r') + indent = getminindent(lines) + if indent == 1: + classname = '' + alllines = string.split(alltext, '\r') + for i in range(selfirstline - 1, -1, -1): + line = alllines[i] + if line[:6] == 'class ': + classname = string.split(string.strip(line[6:]))[0] + classend = identifieRE_match(classname) + if classend < 1: + raise W.AlertError, "Can't find a class." + classname = classname[:classend] + break + elif line and line[0] not in '\t#': + raise W.AlertError, "Can't find a class." + else: + raise W.AlertError, "Can't find a class." + if globals.has_key(classname): + klass = globals[classname] + else: + raise W.AlertError, "Can't find class \"%s\"." % classname + # add class def + pytext = ("class %s:\n" % classname) + pytext + selfirstline = selfirstline - 1 + elif indent > 0: + raise W.AlertError, "Can't run indented code." + + # add "newlines" to fool compile/exec: + # now a traceback will give the right line number + pytext = selfirstline * '\r' + pytext + self.execstring(pytext, globals, locals, file, modname) + if indent == 1 and globals[classname] is not klass: + # update the class in place + klass.__dict__.update(globals[classname].__dict__) + globals[classname] = klass + + def execstring(self, pytext, globals, locals, file, modname): + tracebackwindow.hide() + # update windows + W.getapplication().refreshwindows() + if self.run_as_main: + modname = "__main__" + if self.path: + dir = os.path.dirname(self.path) + savedir = os.getcwd() + os.chdir(dir) + sys.path.insert(0, dir) + self._scriptDone = False + if sys.platform == "darwin": + # On MacOSX, MacPython doesn't poll for command-period + # (cancel), so to enable the user to cancel a running + # script, we have to spawn a thread which does the + # polling. It will send a SIGINT to the main thread + # (in which the script is running) when the user types + # command-period. + from threading import Thread + t = Thread(target=self._userCancelledMonitor, + name="UserCancelledMonitor") + t.start() + try: + execstring(pytext, globals, locals, file, self.debugging, + modname, self.profiling) + finally: + self._scriptDone = True + if self.path: + os.chdir(savedir) + del sys.path[0] + + def _userCancelledMonitor(self): + import time + from signal import SIGINT + while not self._scriptDone: + if Evt.CheckEventQueueForUserCancel(): + # Send a SIGINT signal to ourselves. + # This gets delivered to the main thread, + # cancelling the running script. + os.kill(os.getpid(), SIGINT) + break + time.sleep(0.25) + + def getenvironment(self): + if self.path: + file = self.path + dir = os.path.dirname(file) + # check if we're part of a package + modname = "" + while os.path.exists(os.path.join(dir, "__init__.py")): + dir, dirname = os.path.split(dir) + modname = dirname + '.' + modname + subname = _filename_as_modname(self.title) + if subname is None: + return self.globals, file, None + if modname: + if subname == "__init__": + # strip trailing period + modname = modname[:-1] + else: + modname = modname + subname + else: + modname = subname + if sys.modules.has_key(modname): + globals = sys.modules[modname].__dict__ + self.globals = {} + else: + globals = self.globals + modname = subname + else: + file = '<%s>' % self.title + globals = self.globals + modname = file + return globals, file, modname + + def write(self, stuff): + """for use as stdout""" + self._buf = self._buf + stuff + if '\n' in self._buf: + self.flush() + + def flush(self): + stuff = string.split(self._buf, '\n') + stuff = string.join(stuff, '\r') + end = self.editgroup.editor.ted.WEGetTextLength() + self.editgroup.editor.ted.WESetSelection(end, end) + self.editgroup.editor.ted.WEInsert(stuff, None, None) + self.editgroup.editor.updatescrollbars() + self._buf = "" + # ? optional: + #self.wid.SelectWindow() + + def getclasslist(self): + from string import find, strip + methodRE = re.compile(r"\r[ \t]+def ") + findMethod = methodRE.search + editor = self.editgroup.editor + text = editor.get() + list = [] + append = list.append + functag = "func" + classtag = "class" + methodtag = "method" + pos = -1 + if text[:4] == 'def ': + append((pos + 4, functag)) + pos = 4 + while 1: + pos = find(text, '\rdef ', pos + 1) + if pos < 0: + break + append((pos + 5, functag)) + pos = -1 + if text[:6] == 'class ': + append((pos + 6, classtag)) + pos = 6 + while 1: + pos = find(text, '\rclass ', pos + 1) + if pos < 0: + break + append((pos + 7, classtag)) + pos = 0 + while 1: + m = findMethod(text, pos + 1) + if m is None: + break + pos = m.regs[0][0] + #pos = find(text, '\r\tdef ', pos + 1) + append((m.regs[0][1], methodtag)) + list.sort() + classlist = [] + methodlistappend = None + offsetToLine = editor.ted.WEOffsetToLine + getLineRange = editor.ted.WEGetLineRange + append = classlist.append + for pos, tag in list: + lineno = offsetToLine(pos) + lineStart, lineEnd = getLineRange(lineno) + line = strip(text[pos:lineEnd]) + line = line[:identifieRE_match(line)] + if tag is functag: + append(("def " + line, lineno + 1)) + methodlistappend = None + elif tag is classtag: + append(["class " + line]) + methodlistappend = classlist[-1].append + elif methodlistappend and tag is methodtag: + methodlistappend(("def " + line, lineno + 1)) + return classlist + + def popselectline(self, lineno): + self.editgroup.editor.selectline(lineno - 1) + + def selectline(self, lineno, charoffset = 0): + self.editgroup.editor.selectline(lineno - 1, charoffset) + + def addrecentfile(self, filename): + app = W.getapplication() + app.addrecentfile(filename) class _saveoptions: - - def __init__(self, creator, eoln): - self.rv = None - self.eoln = eoln - self.w = w = W.ModalDialog((260, 160), 'Save options') - radiobuttons = [] - w.label = W.TextBox((8, 8, 80, 18), "File creator:") - w.ide_radio = W.RadioButton((8, 22, 160, 18), "PythonIDE", radiobuttons, self.ide_hit) - w.interp_radio = W.RadioButton((8, 42, 160, 18), "MacPython-OS9 Interpreter", radiobuttons, self.interp_hit) - w.interpx_radio = W.RadioButton((8, 62, 160, 18), "PythonLauncher", radiobuttons, self.interpx_hit) - w.other_radio = W.RadioButton((8, 82, 50, 18), "Other:", radiobuttons) - w.other_creator = W.EditText((62, 82, 40, 20), creator, self.otherselect) - w.none_radio = W.RadioButton((8, 102, 160, 18), "None", radiobuttons, self.none_hit) - w.cancelbutton = W.Button((-180, -30, 80, 16), "Cancel", self.cancelbuttonhit) - w.okbutton = W.Button((-90, -30, 80, 16), "Done", self.okbuttonhit) - w.setdefaultbutton(w.okbutton) - if creator == 'Pyth': - w.interp_radio.set(1) - elif creator == W._signature: - w.ide_radio.set(1) - elif creator == 'PytX': - w.interpx_radio.set(1) - elif creator == '\0\0\0\0': - w.none_radio.set(1) - else: - w.other_radio.set(1) - - w.eolnlabel = W.TextBox((168, 8, 80, 18), "Newline style:") - radiobuttons = [] - w.unix_radio = W.RadioButton((168, 22, 80, 18), "Unix", radiobuttons, self.unix_hit) - w.mac_radio = W.RadioButton((168, 42, 80, 18), "Macintosh", radiobuttons, self.mac_hit) - w.win_radio = W.RadioButton((168, 62, 80, 18), "Windows", radiobuttons, self.win_hit) - if self.eoln == '\n': - w.unix_radio.set(1) - elif self.eoln == '\r\n': - w.win_radio.set(1) - else: - w.mac_radio.set(1) - - w.bind("cmd.", w.cancelbutton.push) - w.open() - - def ide_hit(self): - self.w.other_creator.set(W._signature) - - def interp_hit(self): - self.w.other_creator.set("Pyth") - - def interpx_hit(self): - self.w.other_creator.set("PytX") - - def none_hit(self): - self.w.other_creator.set("\0\0\0\0") - - def otherselect(self, *args): - sel_from, sel_to = self.w.other_creator.getselection() - creator = self.w.other_creator.get()[:4] - creator = creator + " " * (4 - len(creator)) - self.w.other_creator.set(creator) - self.w.other_creator.setselection(sel_from, sel_to) - self.w.other_radio.set(1) - - def mac_hit(self): - self.eoln = '\r' - - def unix_hit(self): - self.eoln = '\n' - - def win_hit(self): - self.eoln = '\r\n' - - def cancelbuttonhit(self): - self.w.close() - - def okbuttonhit(self): - self.rv = (self.w.other_creator.get()[:4], self.eoln) - self.w.close() + + def __init__(self, creator, eoln): + self.rv = None + self.eoln = eoln + self.w = w = W.ModalDialog((260, 160), 'Save options') + radiobuttons = [] + w.label = W.TextBox((8, 8, 80, 18), "File creator:") + w.ide_radio = W.RadioButton((8, 22, 160, 18), "PythonIDE", radiobuttons, self.ide_hit) + w.interp_radio = W.RadioButton((8, 42, 160, 18), "MacPython-OS9 Interpreter", radiobuttons, self.interp_hit) + w.interpx_radio = W.RadioButton((8, 62, 160, 18), "PythonLauncher", radiobuttons, self.interpx_hit) + w.other_radio = W.RadioButton((8, 82, 50, 18), "Other:", radiobuttons) + w.other_creator = W.EditText((62, 82, 40, 20), creator, self.otherselect) + w.none_radio = W.RadioButton((8, 102, 160, 18), "None", radiobuttons, self.none_hit) + w.cancelbutton = W.Button((-180, -30, 80, 16), "Cancel", self.cancelbuttonhit) + w.okbutton = W.Button((-90, -30, 80, 16), "Done", self.okbuttonhit) + w.setdefaultbutton(w.okbutton) + if creator == 'Pyth': + w.interp_radio.set(1) + elif creator == W._signature: + w.ide_radio.set(1) + elif creator == 'PytX': + w.interpx_radio.set(1) + elif creator == '\0\0\0\0': + w.none_radio.set(1) + else: + w.other_radio.set(1) + + w.eolnlabel = W.TextBox((168, 8, 80, 18), "Newline style:") + radiobuttons = [] + w.unix_radio = W.RadioButton((168, 22, 80, 18), "Unix", radiobuttons, self.unix_hit) + w.mac_radio = W.RadioButton((168, 42, 80, 18), "Macintosh", radiobuttons, self.mac_hit) + w.win_radio = W.RadioButton((168, 62, 80, 18), "Windows", radiobuttons, self.win_hit) + if self.eoln == '\n': + w.unix_radio.set(1) + elif self.eoln == '\r\n': + w.win_radio.set(1) + else: + w.mac_radio.set(1) + + w.bind("cmd.", w.cancelbutton.push) + w.open() + + def ide_hit(self): + self.w.other_creator.set(W._signature) + + def interp_hit(self): + self.w.other_creator.set("Pyth") + + def interpx_hit(self): + self.w.other_creator.set("PytX") + + def none_hit(self): + self.w.other_creator.set("\0\0\0\0") + + def otherselect(self, *args): + sel_from, sel_to = self.w.other_creator.getselection() + creator = self.w.other_creator.get()[:4] + creator = creator + " " * (4 - len(creator)) + self.w.other_creator.set(creator) + self.w.other_creator.setselection(sel_from, sel_to) + self.w.other_radio.set(1) + + def mac_hit(self): + self.eoln = '\r' + + def unix_hit(self): + self.eoln = '\n' + + def win_hit(self): + self.eoln = '\r\n' + + def cancelbuttonhit(self): + self.w.close() + + def okbuttonhit(self): + self.rv = (self.w.other_creator.get()[:4], self.eoln) + self.w.close() def SaveOptions(creator, eoln): - s = _saveoptions(creator, eoln) - return s.rv + s = _saveoptions(creator, eoln) + return s.rv -def _escape(where, what) : - return string.join(string.split(where, what), '\\' + what) +def _escape(where, what) : + return string.join(string.split(where, what), '\\' + what) def _makewholewordpattern(word): - # first, escape special regex chars - for esc in "\\[]()|.*^+$?": - word = _escape(word, esc) - notwordcharspat = '[^' + _wordchars + ']' - pattern = '(' + word + ')' - if word[0] in _wordchars: - pattern = notwordcharspat + pattern - if word[-1] in _wordchars: - pattern = pattern + notwordcharspat - return re.compile(pattern) + # first, escape special regex chars + for esc in "\\[]()|.*^+$?": + word = _escape(word, esc) + notwordcharspat = '[^' + _wordchars + ']' + pattern = '(' + word + ')' + if word[0] in _wordchars: + pattern = notwordcharspat + pattern + if word[-1] in _wordchars: + pattern = pattern + notwordcharspat + return re.compile(pattern) class SearchEngine: - - def __init__(self): - self.visible = 0 - self.w = None - self.parms = { "find": "", - "replace": "", - "wrap": 1, - "casesens": 1, - "wholeword": 1 - } - import MacPrefs - prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) - if prefs.searchengine: - self.parms["casesens"] = prefs.searchengine.casesens - self.parms["wrap"] = prefs.searchengine.wrap - self.parms["wholeword"] = prefs.searchengine.wholeword - - def show(self): - self.visible = 1 - if self.w: - self.w.wid.ShowWindow() - self.w.wid.SelectWindow() - self.w.find.edit.select(1) - self.w.find.edit.selectall() - return - self.w = W.Dialog((420, 150), "Find") - - self.w.find = TitledEditText((10, 4, 300, 36), "Search for:") - self.w.replace = TitledEditText((10, 100, 300, 36), "Replace with:") - - self.w.boxes = W.Group((10, 50, 300, 40)) - self.w.boxes.casesens = W.CheckBox((0, 0, 100, 16), "Case sensitive") - self.w.boxes.wholeword = W.CheckBox((0, 20, 100, 16), "Whole word") - self.w.boxes.wrap = W.CheckBox((110, 0, 100, 16), "Wrap around") - - self.buttons = [ ("Find", "cmdf", self.find), - ("Replace", "cmdr", self.replace), - ("Replace all", None, self.replaceall), - ("Don't find", "cmdd", self.dont), - ("Cancel", "cmd.", self.cancel) - ] - for i in range(len(self.buttons)): - bounds = -90, 22 + i * 24, 80, 16 - title, shortcut, callback = self.buttons[i] - self.w[title] = W.Button(bounds, title, callback) - if shortcut: - self.w.bind(shortcut, self.w[title].push) - self.w.setdefaultbutton(self.w["Don't find"]) - self.w.find.edit.bind("<key>", self.key) - self.w.bind("<activate>", self.activate) - self.w.bind("<close>", self.close) - self.w.open() - self.setparms() - self.w.find.edit.select(1) - self.w.find.edit.selectall() - self.checkbuttons() - - def close(self): - self.hide() - return -1 - - def key(self, char, modifiers): - self.w.find.edit.key(char, modifiers) - self.checkbuttons() - return 1 - - def activate(self, onoff): - if onoff: - self.checkbuttons() - - def checkbuttons(self): - editor = findeditor(self) - if editor: - if self.w.find.get(): - for title, cmd, call in self.buttons[:-2]: - self.w[title].enable(1) - self.w.setdefaultbutton(self.w["Find"]) - else: - for title, cmd, call in self.buttons[:-2]: - self.w[title].enable(0) - self.w.setdefaultbutton(self.w["Don't find"]) - else: - for title, cmd, call in self.buttons[:-2]: - self.w[title].enable(0) - self.w.setdefaultbutton(self.w["Don't find"]) - - def find(self): - self.getparmsfromwindow() - if self.findnext(): - self.hide() - - def replace(self): - editor = findeditor(self) - if not editor: - return - if self.visible: - self.getparmsfromwindow() - text = editor.getselectedtext() - find = self.parms["find"] - if not self.parms["casesens"]: - find = string.lower(find) - text = string.lower(text) - if text == find: - self.hide() - editor.insert(self.parms["replace"]) - - def replaceall(self): - editor = findeditor(self) - if not editor: - return - if self.visible: - self.getparmsfromwindow() - W.SetCursor("watch") - find = self.parms["find"] - if not find: - return - findlen = len(find) - replace = self.parms["replace"] - replacelen = len(replace) - Text = editor.get() - if not self.parms["casesens"]: - find = string.lower(find) - text = string.lower(Text) - else: - text = Text - newtext = "" - pos = 0 - counter = 0 - while 1: - if self.parms["wholeword"]: - wholewordRE = _makewholewordpattern(find) - match = wholewordRE.search(text, pos) - if match: - pos = match.start(1) - else: - pos = -1 - else: - pos = string.find(text, find, pos) - if pos < 0: - break - counter = counter + 1 - text = text[:pos] + replace + text[pos + findlen:] - Text = Text[:pos] + replace + Text[pos + findlen:] - pos = pos + replacelen - W.SetCursor("arrow") - if counter: - self.hide() - from Carbon import Res - editor.textchanged() - editor.selectionchanged() - editor.set(Text) - EasyDialogs.Message("Replaced %d occurrences" % counter) - - def dont(self): - self.getparmsfromwindow() - self.hide() - - def replacefind(self): - self.replace() - self.findnext() - - def setfindstring(self): - editor = findeditor(self) - if not editor: - return - find = editor.getselectedtext() - if not find: - return - self.parms["find"] = find - if self.w: - self.w.find.edit.set(self.parms["find"]) - self.w.find.edit.selectall() - - def findnext(self): - editor = findeditor(self) - if not editor: - return - find = self.parms["find"] - if not find: - return - text = editor.get() - if not self.parms["casesens"]: - find = string.lower(find) - text = string.lower(text) - selstart, selend = editor.getselection() - selstart, selend = min(selstart, selend), max(selstart, selend) - if self.parms["wholeword"]: - wholewordRE = _makewholewordpattern(find) - match = wholewordRE.search(text, selend) - if match: - pos = match.start(1) - else: - pos = -1 - else: - pos = string.find(text, find, selend) - if pos >= 0: - editor.setselection(pos, pos + len(find)) - return 1 - elif self.parms["wrap"]: - if self.parms["wholeword"]: - match = wholewordRE.search(text, 0) - if match: - pos = match.start(1) - else: - pos = -1 - else: - pos = string.find(text, find) - if selstart > pos >= 0: - editor.setselection(pos, pos + len(find)) - return 1 - - def setparms(self): - for key, value in self.parms.items(): - try: - self.w[key].set(value) - except KeyError: - self.w.boxes[key].set(value) - - def getparmsfromwindow(self): - if not self.w: - return - for key, value in self.parms.items(): - try: - value = self.w[key].get() - except KeyError: - value = self.w.boxes[key].get() - self.parms[key] = value - - def cancel(self): - self.hide() - self.setparms() - - def hide(self): - if self.w: - self.w.wid.HideWindow() - self.visible = 0 - - def writeprefs(self): - import MacPrefs - self.getparmsfromwindow() - prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) - prefs.searchengine.casesens = self.parms["casesens"] - prefs.searchengine.wrap = self.parms["wrap"] - prefs.searchengine.wholeword = self.parms["wholeword"] - prefs.save() - + + def __init__(self): + self.visible = 0 + self.w = None + self.parms = { "find": "", + "replace": "", + "wrap": 1, + "casesens": 1, + "wholeword": 1 + } + import MacPrefs + prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) + if prefs.searchengine: + self.parms["casesens"] = prefs.searchengine.casesens + self.parms["wrap"] = prefs.searchengine.wrap + self.parms["wholeword"] = prefs.searchengine.wholeword + + def show(self): + self.visible = 1 + if self.w: + self.w.wid.ShowWindow() + self.w.wid.SelectWindow() + self.w.find.edit.select(1) + self.w.find.edit.selectall() + return + self.w = W.Dialog((420, 150), "Find") + + self.w.find = TitledEditText((10, 4, 300, 36), "Search for:") + self.w.replace = TitledEditText((10, 100, 300, 36), "Replace with:") + + self.w.boxes = W.Group((10, 50, 300, 40)) + self.w.boxes.casesens = W.CheckBox((0, 0, 100, 16), "Case sensitive") + self.w.boxes.wholeword = W.CheckBox((0, 20, 100, 16), "Whole word") + self.w.boxes.wrap = W.CheckBox((110, 0, 100, 16), "Wrap around") + + self.buttons = [ ("Find", "cmdf", self.find), + ("Replace", "cmdr", self.replace), + ("Replace all", None, self.replaceall), + ("Don't find", "cmdd", self.dont), + ("Cancel", "cmd.", self.cancel) + ] + for i in range(len(self.buttons)): + bounds = -90, 22 + i * 24, 80, 16 + title, shortcut, callback = self.buttons[i] + self.w[title] = W.Button(bounds, title, callback) + if shortcut: + self.w.bind(shortcut, self.w[title].push) + self.w.setdefaultbutton(self.w["Don't find"]) + self.w.find.edit.bind("<key>", self.key) + self.w.bind("<activate>", self.activate) + self.w.bind("<close>", self.close) + self.w.open() + self.setparms() + self.w.find.edit.select(1) + self.w.find.edit.selectall() + self.checkbuttons() + + def close(self): + self.hide() + return -1 + + def key(self, char, modifiers): + self.w.find.edit.key(char, modifiers) + self.checkbuttons() + return 1 + + def activate(self, onoff): + if onoff: + self.checkbuttons() + + def checkbuttons(self): + editor = findeditor(self) + if editor: + if self.w.find.get(): + for title, cmd, call in self.buttons[:-2]: + self.w[title].enable(1) + self.w.setdefaultbutton(self.w["Find"]) + else: + for title, cmd, call in self.buttons[:-2]: + self.w[title].enable(0) + self.w.setdefaultbutton(self.w["Don't find"]) + else: + for title, cmd, call in self.buttons[:-2]: + self.w[title].enable(0) + self.w.setdefaultbutton(self.w["Don't find"]) + + def find(self): + self.getparmsfromwindow() + if self.findnext(): + self.hide() + + def replace(self): + editor = findeditor(self) + if not editor: + return + if self.visible: + self.getparmsfromwindow() + text = editor.getselectedtext() + find = self.parms["find"] + if not self.parms["casesens"]: + find = string.lower(find) + text = string.lower(text) + if text == find: + self.hide() + editor.insert(self.parms["replace"]) + + def replaceall(self): + editor = findeditor(self) + if not editor: + return + if self.visible: + self.getparmsfromwindow() + W.SetCursor("watch") + find = self.parms["find"] + if not find: + return + findlen = len(find) + replace = self.parms["replace"] + replacelen = len(replace) + Text = editor.get() + if not self.parms["casesens"]: + find = string.lower(find) + text = string.lower(Text) + else: + text = Text + newtext = "" + pos = 0 + counter = 0 + while 1: + if self.parms["wholeword"]: + wholewordRE = _makewholewordpattern(find) + match = wholewordRE.search(text, pos) + if match: + pos = match.start(1) + else: + pos = -1 + else: + pos = string.find(text, find, pos) + if pos < 0: + break + counter = counter + 1 + text = text[:pos] + replace + text[pos + findlen:] + Text = Text[:pos] + replace + Text[pos + findlen:] + pos = pos + replacelen + W.SetCursor("arrow") + if counter: + self.hide() + from Carbon import Res + editor.textchanged() + editor.selectionchanged() + editor.set(Text) + EasyDialogs.Message("Replaced %d occurrences" % counter) + + def dont(self): + self.getparmsfromwindow() + self.hide() + + def replacefind(self): + self.replace() + self.findnext() + + def setfindstring(self): + editor = findeditor(self) + if not editor: + return + find = editor.getselectedtext() + if not find: + return + self.parms["find"] = find + if self.w: + self.w.find.edit.set(self.parms["find"]) + self.w.find.edit.selectall() + + def findnext(self): + editor = findeditor(self) + if not editor: + return + find = self.parms["find"] + if not find: + return + text = editor.get() + if not self.parms["casesens"]: + find = string.lower(find) + text = string.lower(text) + selstart, selend = editor.getselection() + selstart, selend = min(selstart, selend), max(selstart, selend) + if self.parms["wholeword"]: + wholewordRE = _makewholewordpattern(find) + match = wholewordRE.search(text, selend) + if match: + pos = match.start(1) + else: + pos = -1 + else: + pos = string.find(text, find, selend) + if pos >= 0: + editor.setselection(pos, pos + len(find)) + return 1 + elif self.parms["wrap"]: + if self.parms["wholeword"]: + match = wholewordRE.search(text, 0) + if match: + pos = match.start(1) + else: + pos = -1 + else: + pos = string.find(text, find) + if selstart > pos >= 0: + editor.setselection(pos, pos + len(find)) + return 1 + + def setparms(self): + for key, value in self.parms.items(): + try: + self.w[key].set(value) + except KeyError: + self.w.boxes[key].set(value) + + def getparmsfromwindow(self): + if not self.w: + return + for key, value in self.parms.items(): + try: + value = self.w[key].get() + except KeyError: + value = self.w.boxes[key].get() + self.parms[key] = value + + def cancel(self): + self.hide() + self.setparms() + + def hide(self): + if self.w: + self.w.wid.HideWindow() + self.visible = 0 + + def writeprefs(self): + import MacPrefs + self.getparmsfromwindow() + prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) + prefs.searchengine.casesens = self.parms["casesens"] + prefs.searchengine.wrap = self.parms["wrap"] + prefs.searchengine.wholeword = self.parms["wholeword"] + prefs.save() + class TitledEditText(W.Group): - - def __init__(self, possize, title, text = ""): - W.Group.__init__(self, possize) - self.title = W.TextBox((0, 0, 0, 16), title) - self.edit = W.EditText((0, 16, 0, 0), text) - - def set(self, value): - self.edit.set(value) - - def get(self): - return self.edit.get() + + def __init__(self, possize, title, text = ""): + W.Group.__init__(self, possize) + self.title = W.TextBox((0, 0, 0, 16), title) + self.edit = W.EditText((0, 16, 0, 0), text) + + def set(self, value): + self.edit.set(value) + + def get(self): + return self.edit.get() class ClassFinder(W.PopupWidget): - - def click(self, point, modifiers): - W.SetCursor("watch") - self.set(self._parentwindow.getclasslist()) - W.PopupWidget.click(self, point, modifiers) + + def click(self, point, modifiers): + W.SetCursor("watch") + self.set(self._parentwindow.getclasslist()) + W.PopupWidget.click(self, point, modifiers) def getminindent(lines): - indent = -1 - for line in lines: - stripped = string.strip(line) - if not stripped or stripped[0] == '#': - continue - if indent < 0 or line[:indent] <> indent * '\t': - indent = 0 - for c in line: - if c <> '\t': - break - indent = indent + 1 - return indent + indent = -1 + for line in lines: + stripped = string.strip(line) + if not stripped or stripped[0] == '#': + continue + if indent < 0 or line[:indent] <> indent * '\t': + indent = 0 + for c in line: + if c <> '\t': + break + indent = indent + 1 + return indent def getoptionkey(): - return not not ord(Evt.GetKeys()[7]) & 0x04 - - -def execstring(pytext, globals, locals, filename="<string>", debugging=0, - modname="__main__", profiling=0): - if debugging: - import PyDebugger, bdb - BdbQuit = bdb.BdbQuit - else: - BdbQuit = 'BdbQuitDummyException' - pytext = string.split(pytext, '\r') - pytext = string.join(pytext, '\n') + '\n' - W.SetCursor("watch") - globals['__name__'] = modname - globals['__file__'] = filename - sys.argv = [filename] - try: - code = compile(pytext, filename, "exec") - except: - # XXXX BAAAADDD.... We let tracebackwindow decide to treat SyntaxError - # special. That's wrong because THIS case is special (could be literal - # overflow!) and SyntaxError could mean we need a traceback (syntax error - # in imported module!!! - tracebackwindow.traceback(1, filename) - return - try: - if debugging: - PyDebugger.startfromhere() - else: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(0) - try: - if profiling: - import profile, ProfileBrowser - p = profile.Profile() - p.set_cmd(filename) - try: - p.runctx(code, globals, locals) - finally: - import pstats - - stats = pstats.Stats(p) - ProfileBrowser.ProfileBrowser(stats) - else: - exec code in globals, locals - finally: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(-1) - except W.AlertError, detail: - raise W.AlertError, detail - except (KeyboardInterrupt, BdbQuit): - pass - except SystemExit, arg: - if arg.code: - sys.stderr.write("Script exited with status code: %s\n" % repr(arg.code)) - except: - if debugging: - sys.settrace(None) - PyDebugger.postmortem(sys.exc_type, sys.exc_value, sys.exc_traceback) - return - else: - tracebackwindow.traceback(1, filename) - if debugging: - sys.settrace(None) - PyDebugger.stop() + return not not ord(Evt.GetKeys()[7]) & 0x04 + + +def execstring(pytext, globals, locals, filename="<string>", debugging=0, + modname="__main__", profiling=0): + if debugging: + import PyDebugger, bdb + BdbQuit = bdb.BdbQuit + else: + BdbQuit = 'BdbQuitDummyException' + pytext = string.split(pytext, '\r') + pytext = string.join(pytext, '\n') + '\n' + W.SetCursor("watch") + globals['__name__'] = modname + globals['__file__'] = filename + sys.argv = [filename] + try: + code = compile(pytext, filename, "exec") + except: + # XXXX BAAAADDD.... We let tracebackwindow decide to treat SyntaxError + # special. That's wrong because THIS case is special (could be literal + # overflow!) and SyntaxError could mean we need a traceback (syntax error + # in imported module!!! + tracebackwindow.traceback(1, filename) + return + try: + if debugging: + PyDebugger.startfromhere() + else: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(0) + try: + if profiling: + import profile, ProfileBrowser + p = profile.Profile() + p.set_cmd(filename) + try: + p.runctx(code, globals, locals) + finally: + import pstats + + stats = pstats.Stats(p) + ProfileBrowser.ProfileBrowser(stats) + else: + exec code in globals, locals + finally: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(-1) + except W.AlertError, detail: + raise W.AlertError, detail + except (KeyboardInterrupt, BdbQuit): + pass + except SystemExit, arg: + if arg.code: + sys.stderr.write("Script exited with status code: %s\n" % repr(arg.code)) + except: + if debugging: + sys.settrace(None) + PyDebugger.postmortem(sys.exc_type, sys.exc_value, sys.exc_traceback) + return + else: + tracebackwindow.traceback(1, filename) + if debugging: + sys.settrace(None) + PyDebugger.stop() _identifieRE = re.compile(r"[A-Za-z_][A-Za-z_0-9]*") def identifieRE_match(str): - match = _identifieRE.match(str) - if not match: - return -1 - return match.end() + match = _identifieRE.match(str) + if not match: + return -1 + return match.end() def _filename_as_modname(fname): - if fname[-3:] == '.py': - modname = fname[:-3] - match = _identifieRE.match(modname) - if match and match.start() == 0 and match.end() == len(modname): - return string.join(string.split(modname, '.'), '_') + if fname[-3:] == '.py': + modname = fname[:-3] + match = _identifieRE.match(modname) + if match and match.start() == 0 and match.end() == len(modname): + return string.join(string.split(modname, '.'), '_') def findeditor(topwindow, fromtop = 0): - wid = MyFrontWindow() - if not fromtop: - if topwindow.w and wid == topwindow.w.wid: - wid = topwindow.w.wid.GetNextWindow() - if not wid: - return - app = W.getapplication() - if app._windows.has_key(wid): # KeyError otherwise can happen in RoboFog :-( - window = W.getapplication()._windows[wid] - else: - return - if not isinstance(window, Editor): - return - return window.editgroup.editor + wid = MyFrontWindow() + if not fromtop: + if topwindow.w and wid == topwindow.w.wid: + wid = topwindow.w.wid.GetNextWindow() + if not wid: + return + app = W.getapplication() + if app._windows.has_key(wid): # KeyError otherwise can happen in RoboFog :-( + window = W.getapplication()._windows[wid] + else: + return + if not isinstance(window, Editor): + return + return window.editgroup.editor class _EditorDefaultSettings: - - def __init__(self): - self.template = "%s, %d point" - self.fontsettings, self.tabsettings, self.windowsize = geteditorprefs() - self.w = W.Dialog((328, 120), "Editor default settings") - self.w.setfontbutton = W.Button((8, 8, 80, 16), "Set font\xc9", self.dofont) - self.w.fonttext = W.TextBox((98, 10, -8, 14), self.template % (self.fontsettings[0], self.fontsettings[2])) - - self.w.picksizebutton = W.Button((8, 50, 80, 16), "Front window", self.picksize) - self.w.xsizelabel = W.TextBox((98, 32, 40, 14), "Width:") - self.w.ysizelabel = W.TextBox((148, 32, 40, 14), "Height:") - self.w.xsize = W.EditText((98, 48, 40, 20), repr(self.windowsize[0])) - self.w.ysize = W.EditText((148, 48, 40, 20), repr(self.windowsize[1])) - - self.w.cancelbutton = W.Button((-180, -26, 80, 16), "Cancel", self.cancel) - self.w.okbutton = W.Button((-90, -26, 80, 16), "Done", self.ok) - self.w.setdefaultbutton(self.w.okbutton) - self.w.bind('cmd.', self.w.cancelbutton.push) - self.w.open() - - def picksize(self): - app = W.getapplication() - editor = findeditor(self) - if editor is not None: - width, height = editor._parentwindow._bounds[2:] - self.w.xsize.set(repr(width)) - self.w.ysize.set(repr(height)) - else: - raise W.AlertError, "No edit window found" - - def dofont(self): - import FontSettings - settings = FontSettings.FontDialog(self.fontsettings, self.tabsettings) - if settings: - self.fontsettings, self.tabsettings = settings - sys.exc_traceback = None - self.w.fonttext.set(self.template % (self.fontsettings[0], self.fontsettings[2])) - - def close(self): - self.w.close() - del self.w - - def cancel(self): - self.close() - - def ok(self): - try: - width = string.atoi(self.w.xsize.get()) - except: - self.w.xsize.select(1) - self.w.xsize.selectall() - raise W.AlertError, "Bad number for window width" - try: - height = string.atoi(self.w.ysize.get()) - except: - self.w.ysize.select(1) - self.w.ysize.selectall() - raise W.AlertError, "Bad number for window height" - self.windowsize = width, height - seteditorprefs(self.fontsettings, self.tabsettings, self.windowsize) - self.close() + + def __init__(self): + self.template = "%s, %d point" + self.fontsettings, self.tabsettings, self.windowsize = geteditorprefs() + self.w = W.Dialog((328, 120), "Editor default settings") + self.w.setfontbutton = W.Button((8, 8, 80, 16), "Set font\xc9", self.dofont) + self.w.fonttext = W.TextBox((98, 10, -8, 14), self.template % (self.fontsettings[0], self.fontsettings[2])) + + self.w.picksizebutton = W.Button((8, 50, 80, 16), "Front window", self.picksize) + self.w.xsizelabel = W.TextBox((98, 32, 40, 14), "Width:") + self.w.ysizelabel = W.TextBox((148, 32, 40, 14), "Height:") + self.w.xsize = W.EditText((98, 48, 40, 20), repr(self.windowsize[0])) + self.w.ysize = W.EditText((148, 48, 40, 20), repr(self.windowsize[1])) + + self.w.cancelbutton = W.Button((-180, -26, 80, 16), "Cancel", self.cancel) + self.w.okbutton = W.Button((-90, -26, 80, 16), "Done", self.ok) + self.w.setdefaultbutton(self.w.okbutton) + self.w.bind('cmd.', self.w.cancelbutton.push) + self.w.open() + + def picksize(self): + app = W.getapplication() + editor = findeditor(self) + if editor is not None: + width, height = editor._parentwindow._bounds[2:] + self.w.xsize.set(repr(width)) + self.w.ysize.set(repr(height)) + else: + raise W.AlertError, "No edit window found" + + def dofont(self): + import FontSettings + settings = FontSettings.FontDialog(self.fontsettings, self.tabsettings) + if settings: + self.fontsettings, self.tabsettings = settings + sys.exc_traceback = None + self.w.fonttext.set(self.template % (self.fontsettings[0], self.fontsettings[2])) + + def close(self): + self.w.close() + del self.w + + def cancel(self): + self.close() + + def ok(self): + try: + width = string.atoi(self.w.xsize.get()) + except: + self.w.xsize.select(1) + self.w.xsize.selectall() + raise W.AlertError, "Bad number for window width" + try: + height = string.atoi(self.w.ysize.get()) + except: + self.w.ysize.select(1) + self.w.ysize.selectall() + raise W.AlertError, "Bad number for window height" + self.windowsize = width, height + seteditorprefs(self.fontsettings, self.tabsettings, self.windowsize) + self.close() def geteditorprefs(): - import MacPrefs - prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) - try: - fontsettings = prefs.pyedit.fontsettings - tabsettings = prefs.pyedit.tabsettings - windowsize = prefs.pyedit.windowsize - except: - fontsettings = prefs.pyedit.fontsettings = ("Geneva", 0, 10, (0, 0, 0)) - tabsettings = prefs.pyedit.tabsettings = (8, 1) - windowsize = prefs.pyedit.windowsize = (500, 250) - sys.exc_traceback = None - return fontsettings, tabsettings, windowsize + import MacPrefs + prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) + try: + fontsettings = prefs.pyedit.fontsettings + tabsettings = prefs.pyedit.tabsettings + windowsize = prefs.pyedit.windowsize + except: + fontsettings = prefs.pyedit.fontsettings = ("Geneva", 0, 10, (0, 0, 0)) + tabsettings = prefs.pyedit.tabsettings = (8, 1) + windowsize = prefs.pyedit.windowsize = (500, 250) + sys.exc_traceback = None + return fontsettings, tabsettings, windowsize def seteditorprefs(fontsettings, tabsettings, windowsize): - import MacPrefs - prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) - prefs.pyedit.fontsettings = fontsettings - prefs.pyedit.tabsettings = tabsettings - prefs.pyedit.windowsize = windowsize - prefs.save() + import MacPrefs + prefs = MacPrefs.GetPrefs(W.getapplication().preffilepath) + prefs.pyedit.fontsettings = fontsettings + prefs.pyedit.tabsettings = tabsettings + prefs.pyedit.windowsize = windowsize + prefs.save() _defaultSettingsEditor = None def EditorDefaultSettings(): - global _defaultSettingsEditor - if _defaultSettingsEditor is None or not hasattr(_defaultSettingsEditor, "w"): - _defaultSettingsEditor = _EditorDefaultSettings() - else: - _defaultSettingsEditor.w.select() + global _defaultSettingsEditor + if _defaultSettingsEditor is None or not hasattr(_defaultSettingsEditor, "w"): + _defaultSettingsEditor = _EditorDefaultSettings() + else: + _defaultSettingsEditor.w.select() def resolvealiases(path): - try: - fsr, d1, d2 = File.FSResolveAliasFile(path, 1) - path = fsr.as_pathname() - return path - except (File.Error, ValueError), (error, str): - if error <> -120: - raise - dir, file = os.path.split(path) - return os.path.join(resolvealiases(dir), file) + try: + fsr, d1, d2 = File.FSResolveAliasFile(path, 1) + path = fsr.as_pathname() + return path + except (File.Error, ValueError), (error, str): + if error <> -120: + raise + dir, file = os.path.split(path) + return os.path.join(resolvealiases(dir), file) searchengine = SearchEngine() tracebackwindow = Wtraceback.TraceBack() diff --git a/Mac/Tools/IDE/PyFontify.py b/Mac/Tools/IDE/PyFontify.py index eb37ad3..41f1942 100644 --- a/Mac/Tools/IDE/PyFontify.py +++ b/Mac/Tools/IDE/PyFontify.py @@ -1,29 +1,29 @@ """Module to analyze Python source code; for syntax coloring tools. Interface: - tags = fontify(pytext, searchfrom, searchto) + 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 (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. ] + [('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, startindex, endindex, sublist) tag is one of 'keyword', 'string', 'comment' or 'identifier' -sublist is not used, hence always None. +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 +# 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 +# Copyright 1996-2001: +# Mitchell S. Chapman, +# Zachary Roadhouse, +# Tim Peters, +# Just van Rossum __version__ = "0.4" @@ -33,18 +33,18 @@ 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) + 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"] + "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. @@ -55,24 +55,24 @@ 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 + qqq + [^\\q]* + ( + ( \\[\000-\377] + | q + ( \\[\000-\377] + | [^\q] + | q + ( \\[\000-\377] + | [^\\q] + ) + ) + ) + [^\\q]* + )* + qqq """ -pat = string.join(string.split(pat), '') # get rid of whitespace +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 @@ -87,69 +87,69 @@ 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. +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 + 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]) + f = open(path) + text = f.read() + f.close() + tags = fontify(text) + for tag, start, end, sublist in tags: + print tag, repr(text[start:end]) diff --git a/Mac/Tools/IDE/PyInteractive.py b/Mac/Tools/IDE/PyInteractive.py index 3ad02c5..987eec5 100644 --- a/Mac/Tools/IDE/PyInteractive.py +++ b/Mac/Tools/IDE/PyInteractive.py @@ -4,114 +4,114 @@ import traceback try: - sys.ps1 + sys.ps1 except AttributeError: - sys.ps1 = ">>> " + sys.ps1 = ">>> " try: - sys.ps2 + sys.ps2 except AttributeError: - sys.ps2 = "... " + 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) + 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 + + 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 diff --git a/Mac/Tools/IDE/PythonIDE.py b/Mac/Tools/IDE/PythonIDE.py index 1ea7711..b8f54a9 100644 --- a/Mac/Tools/IDE/PythonIDE.py +++ b/Mac/Tools/IDE/PythonIDE.py @@ -1,6 +1,6 @@ # copyright 1996-2001 Just van Rossum, Letterror. just@letterror.com -# keep this (__main__) as clean as possible, since we are using +# keep this (__main__) as clean as possible, since we are using # it like the "normal" interpreter. __version__ = '1.0.2' @@ -8,48 +8,48 @@ 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) + 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() diff --git a/Mac/Tools/IDE/PythonIDEMain.py b/Mac/Tools/IDE/PythonIDEMain.py index 111a0b0..4dbe92a 100644 --- a/Mac/Tools/IDE/PythonIDEMain.py +++ b/Mac/Tools/IDE/PythonIDEMain.py @@ -13,476 +13,476 @@ from Carbon import File from Carbon import Files if MacOS.runtimemodel == 'macho': - ELLIPSIS = '...' + ELLIPSIS = '...' else: - ELLIPSIS = '\xc9' + ELLIPSIS = '\xc9' def runningOnOSX(): - from gestalt import gestalt - gestaltMenuMgrAquaLayoutBit = 1 # menus have the Aqua 1.0 layout - gestaltMenuMgrAquaLayoutMask = (1L << gestaltMenuMgrAquaLayoutBit) - value = gestalt("menu") & gestaltMenuMgrAquaLayoutMask - return not not value + from gestalt import gestalt + gestaltMenuMgrAquaLayoutBit = 1 # menus have the Aqua 1.0 layout + gestaltMenuMgrAquaLayoutMask = (1L << gestaltMenuMgrAquaLayoutBit) + value = gestalt("menu") & gestaltMenuMgrAquaLayoutMask + return not not value def getmodtime(file): - file = File.FSRef(file) - catinfo, d1, d2, d3 = file.FSGetCatalogInfo(Files.kFSCatInfoContentMod) - return catinfo.contentModDate + file = File.FSRef(file) + catinfo, d1, d2, d3 = file.FSGetCatalogInfo(Files.kFSCatInfoContentMod) + return catinfo.contentModDate class PythonIDE(Wapplication.Application): - - def __init__(self): - if sys.platform == "darwin": - if len(sys.argv) > 1 and sys.argv[1].startswith("-psn"): - home = os.getenv("HOME") - if home: - os.chdir(home) - self.preffilepath = os.path.join("Python", "PythonIDE preferences") - Wapplication.Application.__init__(self, 'Pide') - from Carbon import AE - from Carbon import AppleEvents - - AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenApplication, - self.ignoreevent) - AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEReopenApplication, - 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() - # With -D option (OSX command line only) keep stderr, for debugging the IDE - # itself. - debug_stderr = None - if len(sys.argv) >= 2 and sys.argv[1] == '-D': - debug_stderr = sys.stderr - del sys.argv[1] - PyConsole.installoutput() - PyConsole.installconsole() - if debug_stderr: - sys.stderr = debug_stderr - for path in sys.argv[1:]: - if path.startswith("-p"): - # process number added by the OS - continue - self.opendoc(path) - self.mainloop() - - def makeusermenus(self): - m = Wapplication.Menu(self.menubar, "File") - newitem = FrameWork.MenuItem(m, "New", "N", 'new') - openitem = FrameWork.MenuItem(m, "Open"+ELLIPSIS, "O", 'open') - openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELLIPSIS, "D", 'openbyname') - self.openrecentmenu = FrameWork.SubMenu(m, "Open Recent") - self.makeopenrecentmenu() - FrameWork.Separator(m) - closeitem = FrameWork.MenuItem(m, "Close", "W", 'close') - saveitem = FrameWork.MenuItem(m, "Save", "S", 'save') - saveasitem = FrameWork.MenuItem(m, "Save as"+ELLIPSIS, None, 'save_as') - FrameWork.Separator(m) - saveasappletitem = FrameWork.MenuItem(m, "Save as Applet"+ELLIPSIS, None, 'save_as_applet') - FrameWork.Separator(m) - instmgritem = FrameWork.MenuItem(m, "Package Manager", None, 'openpackagemanager') - gensuiteitem = FrameWork.MenuItem(m, "Generate OSA Suite...", None, 'gensuite') - if not runningOnOSX(): - # On OSX there's a special "magic" quit menu, so we shouldn't add - # it to the File menu. - FrameWork.Separator(m) - quititem = FrameWork.MenuItem(m, "Quit", "Q", 'quit') - - m = Wapplication.Menu(self.menubar, "Edit") - undoitem = FrameWork.MenuItem(m, "Undo", 'Z', "undo") - FrameWork.Separator(m) - cutitem = FrameWork.MenuItem(m, "Cut", 'X', "cut") - copyitem = FrameWork.MenuItem(m, "Copy", "C", "copy") - pasteitem = FrameWork.MenuItem(m, "Paste", "V", "paste") - FrameWork.MenuItem(m, "Clear", None, "clear") - FrameWork.Separator(m) - selallitem = FrameWork.MenuItem(m, "Select all", "A", "selectall") - sellineitem = FrameWork.MenuItem(m, "Select line", "L", "selectline") - FrameWork.Separator(m) - finditem = FrameWork.MenuItem(m, "Find"+ELLIPSIS, "F", "find") - findagainitem = FrameWork.MenuItem(m, "Find again", 'G', "findnext") - enterselitem = FrameWork.MenuItem(m, "Enter search string", "E", "entersearchstring") - replaceitem = FrameWork.MenuItem(m, "Replace", None, "replace") - replacefinditem = FrameWork.MenuItem(m, "Replace & find again", 'T', "replacefind") - FrameWork.Separator(m) - shiftleftitem = FrameWork.MenuItem(m, "Shift left", "[", "shiftleft") - shiftrightitem = FrameWork.MenuItem(m, "Shift right", "]", "shiftright") - - m = Wapplication.Menu(self.menubar, "Python") - runitem = FrameWork.MenuItem(m, "Run window", "R", 'run') - runselitem = FrameWork.MenuItem(m, "Run selection", None, 'runselection') - FrameWork.Separator(m) - moditem = FrameWork.MenuItem(m, "Module browser"+ELLIPSIS, "M", self.domenu_modulebrowser) - FrameWork.Separator(m) - mm = FrameWork.SubMenu(m, "Preferences") - FrameWork.MenuItem(mm, "Set Scripts folder"+ELLIPSIS, None, self.do_setscriptsfolder) - FrameWork.MenuItem(mm, "Editor default settings"+ELLIPSIS, None, self.do_editorprefs) - FrameWork.MenuItem(mm, "Set default window font"+ELLIPSIS, None, self.do_setwindowfont) - - self.openwindowsmenu = Wapplication.Menu(self.menubar, 'Windows') - self.makeopenwindowsmenu() - self._menustocheck = [closeitem, saveitem, saveasitem, saveasappletitem, - undoitem, cutitem, copyitem, pasteitem, - selallitem, sellineitem, - finditem, findagainitem, enterselitem, replaceitem, replacefinditem, - shiftleftitem, shiftrightitem, - runitem, runselitem] - - prefs = self.getprefs() - try: - fsr, d = File.Alias(rawdata=prefs.scriptsfolder).FSResolveAlias(None) - self.scriptsfolder = fsr.FSNewAliasMinimal() - except: - path = os.path.join(os.getcwd(), "Mac", "IDE scripts") - if not os.path.exists(path): - if sys.platform == "darwin": - path = os.path.join(os.getenv("HOME"), "Library", "Python", "IDE-Scripts") - else: - path = os.path.join(os.getcwd(), "Scripts") - if not os.path.exists(path): - os.makedirs(path) - f = open(os.path.join(path, "Place your scripts here"+ELLIPSIS), "w") - f.close() - fsr = File.FSRef(path) - self.scriptsfolder = fsr.FSNewAliasMinimal() - self.scriptsfoldermodtime = getmodtime(fsr) - else: - self.scriptsfoldermodtime = getmodtime(fsr) - prefs.scriptsfolder = self.scriptsfolder.data - self._scripts = {} - self.scriptsmenu = None - self.makescriptsmenu() - self.makehelpmenu() - - def quitevent(self, theAppleEvent, theReply): - self._quit() - - def suspendresume(self, onoff): - if onoff: - fsr, changed = self.scriptsfolder.FSResolveAlias(None) - modtime = getmodtime(fsr) - if self.scriptsfoldermodtime <> modtime or 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: - fsr, a = doc.FSResolveAlias(None) - path = fsr.as_pathname() - self.opendoc(path) - - def opendoc(self, path): - fcreator, ftype = MacOS.GetCreatorAndType(path) - if ftype == 'TEXT': - self.openscript(path) - elif ftype == '\0\0\0\0' and path[-3:] == '.py': - self.openscript(path) - else: - W.Message("Can't open file of type '%s'." % ftype) - - def getabouttext(self): - return "About Python IDE"+ELLIPSIS - - def do_about(self, id, item, window, event): - Splash.about() - - def do_setscriptsfolder(self, *args): - fsr = EasyDialogs.AskFolder(message="Select Scripts Folder", - wanted=File.FSRef) - if fsr: - prefs = self.getprefs() - alis = fsr.FSNewAliasMinimal() - 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): - filename = EasyDialogs.AskFileForOpen(typeList=("TEXT",)) - if filename: - self.openscript(filename) - - def domenu_openbyname(self, *args): - # Open a file by name. If the clipboard contains a filename - # use that as the default. - from Carbon import Scrap - try: - sc = Scrap.GetCurrentScrap() - dft = sc.GetScrapFlavorData("TEXT") - except Scrap.Error: - dft = "" - else: - if not os.path.exists(dft): - dft = "" - filename = EasyDialogs.AskString("Open File Named:", default=dft, ok="Open") - if filename: - self.openscript(filename) - - 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() - fsr, d1 = self.scriptsfolder.FSResolveAlias(None) - self.scriptswalk(fsr.as_pathname(), self.scriptsmenu) - - def makeopenwindowsmenu(self): - for i in range(len(self.openwindowsmenu.items)): - self.openwindowsmenu.menu.DeleteMenuItem(1) - self.openwindowsmenu.items = [] - windows = [] - self._openwindows = {} - for window in self._windows.keys(): - title = window.GetWTitle() - if not title: - title = "<no title>" - windows.append((title, window)) - windows.sort() - for title, window in windows: - if title == "Python Interactive": # ugly but useful hack by Joe Strout - shortcut = '0' - else: - shortcut = None - item = FrameWork.MenuItem(self.openwindowsmenu, title, shortcut, callback = self.domenu_openwindows) - self._openwindows[item.item] = window - self._openwindowscheckmark = 0 - self.checkopenwindowsmenu() - - def makeopenrecentmenu(self): - for i in range(len(self.openrecentmenu.items)): - self.openrecentmenu.menu.DeleteMenuItem(1) - self.openrecentmenu.items = [] - prefs = self.getprefs() - filelist = prefs.recentfiles - if not filelist: - self.openrecentmenu.enable(0) - return - self.openrecentmenu.enable(1) - for filename in filelist: - item = FrameWork.MenuItem(self.openrecentmenu, filename, None, callback = self.domenu_openrecent) - - def addrecentfile(self, file): - prefs = self.getprefs() - filelist = prefs.recentfiles - if not filelist: - filelist = [] - - if file in filelist: - if file == filelist[0]: - return - filelist.remove(file) - filelist.insert(0, file) - filelist = filelist[:10] - prefs.recentfiles = filelist - prefs.save() - self.makeopenrecentmenu() - - def domenu_openwindows(self, id, item, window, event): - w = self._openwindows[item] - w.ShowWindow() - w.SelectWindow() - - def domenu_openrecent(self, id, item, window, event): - prefs = self.getprefs() - filelist = prefs.recentfiles - if not filelist: - filelist = [] - item = item - 1 - filename = filelist[item] - self.openscript(filename) - - def domenu_quit(self): - self._quit() - - def domenu_save(self, *args): - print "Save" - - def _quit(self): - import PyConsole, PyEdit - for window in self._windows.values(): - try: - rv = window.close() # ignore any errors while quitting - except: - rv = 0 # (otherwise, we can get stuck!) - if rv and rv > 0: - return - try: - PyConsole.console.writeprefs() - PyConsole.output.writeprefs() - PyEdit.searchengine.writeprefs() - except: - # Write to __stderr__ so the msg end up in Console.app and has - # at least _some_ chance of getting read... - # But: this is a workaround for way more serious problems with - # the Python 2.2 Jaguar addon. - sys.__stderr__.write("*** PythonIDE: Can't write preferences ***\n") - self.quitting = 1 - - def domenu_openpackagemanager(self): - import PackageManager - PackageManager.PackageBrowser() - - def domenu_gensuite(self): - import gensuitemodule - gensuitemodule.main_interactive() - - def makehelpmenu(self): - hashelp, hasdocs = self.installdocumentation() - self.helpmenu = m = self.gethelpmenu() - helpitem = FrameWork.MenuItem(m, "MacPython Help", None, self.domenu_localhelp) - helpitem.enable(hashelp) - docitem = FrameWork.MenuItem(m, "Python Documentation", None, self.domenu_localdocs) - docitem.enable(hasdocs) - finditem = FrameWork.MenuItem(m, "Lookup in Python Documentation", None, 'lookuppython') - finditem.enable(hasdocs) - if runningOnOSX(): - FrameWork.Separator(m) - doc2item = FrameWork.MenuItem(m, "Apple Developer Documentation", None, self.domenu_appledocs) - find2item = FrameWork.MenuItem(m, "Lookup in Carbon Documentation", None, 'lookupcarbon') - FrameWork.Separator(m) - webitem = FrameWork.MenuItem(m, "Python Documentation on the Web", None, self.domenu_webdocs) - web2item = FrameWork.MenuItem(m, "Python on the Web", None, self.domenu_webpython) - web3item = FrameWork.MenuItem(m, "MacPython on the Web", None, self.domenu_webmacpython) - - def domenu_localdocs(self, *args): - from Carbon import AH - AH.AHGotoPage("Python Documentation", None, None) - - def domenu_localhelp(self, *args): - from Carbon import AH - AH.AHGotoPage("MacPython Help", None, None) - - def domenu_appledocs(self, *args): - from Carbon import AH, AppleHelp - try: - AH.AHGotoMainTOC(AppleHelp.kAHTOCTypeDeveloper) - except AH.Error, arg: - if arg[0] == -50: - W.Message("Developer documentation not installed") - else: - W.Message("AppleHelp Error: %r" % (arg,)) - - def domenu_lookuppython(self, *args): - from Carbon import AH - searchstring = self._getsearchstring() - if not searchstring: - return - try: - AH.AHSearch("Python Documentation", searchstring) - except AH.Error, arg: - W.Message("AppleHelp Error: %r" % (arg,)) - - def domenu_lookupcarbon(self, *args): - from Carbon import AH - searchstring = self._getsearchstring() - if not searchstring: - return - try: - AH.AHSearch("Carbon", searchstring) - except AH.Error, arg: - W.Message("AppleHelp Error: %r" % (arg,)) - - def _getsearchstring(self): - # First we get the frontmost window - front = self.getfrontwindow() - if front and hasattr(front, 'getselectedtext'): - text = front.getselectedtext() - if text: - return text - # This is a cop-out. We should have disabled the menus - # if there is no selection, but the can_ methods only seem - # to work for Windows. Or not for the Help menu, maybe? - text = EasyDialogs.AskString("Search documentation for", ok="Search") - return text - - def domenu_webdocs(self, *args): - import webbrowser - major, minor, micro, state, nano = sys.version_info - if state in ('alpha', 'beta'): - docversion = 'dev/doc/devel' - elif micro == 0: - docversion = 'doc/%d.%d' % (major, minor) - else: - docversion = 'doc/%d.%d.%d' % (major, minor, micro) - webbrowser.open("http://www.python.org/%s" % docversion) - - def domenu_webpython(self, *args): - import webbrowser - webbrowser.open("http://www.python.org/") - - def domenu_webmacpython(self, *args): - import webbrowser - webbrowser.open("http://www.cwi.nl/~jack/macpython.html") - - def installdocumentation(self): - # This is rather much of a hack. Someone has to tell the Help Viewer - # about the Python documentation, so why not us. The documentation - # is located in the framework, but there's a symlink in Python.app. - # And as AHRegisterHelpBook wants a bundle (with the right bits in - # the plist file) we refer it to Python.app - # - # To make matters worse we have to look in two places: first in the IDE - # itself, then in the Python application inside the framework. - has_help = False - has_doc = False - ide_path_components = sys.argv[0].split("/") - if ide_path_components[-3:] == ["Contents", "Resources", "PythonIDE.py"]: - ide_app = "/".join(ide_path_components[:-3]) - help_source = os.path.join(ide_app, 'Contents/Resources/English.lproj/Documentation') - doc_source = os.path.join(ide_app, 'Contents/Resources/English.lproj/PythonDocumentation') - has_help = os.path.isdir(help_source) - has_doc = os.path.isdir(doc_source) - if has_help or has_doc: - try: - from Carbon import AH - AH.AHRegisterHelpBook(ide_app) - except (ImportError, MacOS.Error), arg: - pass # W.Message("Cannot register Python Documentation: %s" % str(arg)) - python_app = os.path.join(sys.prefix, 'Resources/Python.app') - if not has_help: - help_source = os.path.join(python_app, 'Contents/Resources/English.lproj/Documentation') - has_help = os.path.isdir(help_source) - if not has_doc: - doc_source = os.path.join(python_app, 'Contents/Resources/English.lproj/PythonDocumentation') - has_doc = os.path.isdir(doc_source) - if has_help or has_doc: - try: - from Carbon import AH - AH.AHRegisterHelpBook(python_app) - except (ImportError, MacOS.Error), arg: - pass # W.Message("Cannot register Python Documentation: %s" % str(arg)) - return has_help, has_doc + + def __init__(self): + if sys.platform == "darwin": + if len(sys.argv) > 1 and sys.argv[1].startswith("-psn"): + home = os.getenv("HOME") + if home: + os.chdir(home) + self.preffilepath = os.path.join("Python", "PythonIDE preferences") + Wapplication.Application.__init__(self, 'Pide') + from Carbon import AE + from Carbon import AppleEvents + + AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEOpenApplication, + self.ignoreevent) + AE.AEInstallEventHandler(AppleEvents.kCoreEventClass, AppleEvents.kAEReopenApplication, + 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() + # With -D option (OSX command line only) keep stderr, for debugging the IDE + # itself. + debug_stderr = None + if len(sys.argv) >= 2 and sys.argv[1] == '-D': + debug_stderr = sys.stderr + del sys.argv[1] + PyConsole.installoutput() + PyConsole.installconsole() + if debug_stderr: + sys.stderr = debug_stderr + for path in sys.argv[1:]: + if path.startswith("-p"): + # process number added by the OS + continue + self.opendoc(path) + self.mainloop() + + def makeusermenus(self): + m = Wapplication.Menu(self.menubar, "File") + newitem = FrameWork.MenuItem(m, "New", "N", 'new') + openitem = FrameWork.MenuItem(m, "Open"+ELLIPSIS, "O", 'open') + openbynameitem = FrameWork.MenuItem(m, "Open File by Name"+ELLIPSIS, "D", 'openbyname') + self.openrecentmenu = FrameWork.SubMenu(m, "Open Recent") + self.makeopenrecentmenu() + FrameWork.Separator(m) + closeitem = FrameWork.MenuItem(m, "Close", "W", 'close') + saveitem = FrameWork.MenuItem(m, "Save", "S", 'save') + saveasitem = FrameWork.MenuItem(m, "Save as"+ELLIPSIS, None, 'save_as') + FrameWork.Separator(m) + saveasappletitem = FrameWork.MenuItem(m, "Save as Applet"+ELLIPSIS, None, 'save_as_applet') + FrameWork.Separator(m) + instmgritem = FrameWork.MenuItem(m, "Package Manager", None, 'openpackagemanager') + gensuiteitem = FrameWork.MenuItem(m, "Generate OSA Suite...", None, 'gensuite') + if not runningOnOSX(): + # On OSX there's a special "magic" quit menu, so we shouldn't add + # it to the File menu. + FrameWork.Separator(m) + quititem = FrameWork.MenuItem(m, "Quit", "Q", 'quit') + + m = Wapplication.Menu(self.menubar, "Edit") + undoitem = FrameWork.MenuItem(m, "Undo", 'Z', "undo") + FrameWork.Separator(m) + cutitem = FrameWork.MenuItem(m, "Cut", 'X', "cut") + copyitem = FrameWork.MenuItem(m, "Copy", "C", "copy") + pasteitem = FrameWork.MenuItem(m, "Paste", "V", "paste") + FrameWork.MenuItem(m, "Clear", None, "clear") + FrameWork.Separator(m) + selallitem = FrameWork.MenuItem(m, "Select all", "A", "selectall") + sellineitem = FrameWork.MenuItem(m, "Select line", "L", "selectline") + FrameWork.Separator(m) + finditem = FrameWork.MenuItem(m, "Find"+ELLIPSIS, "F", "find") + findagainitem = FrameWork.MenuItem(m, "Find again", 'G', "findnext") + enterselitem = FrameWork.MenuItem(m, "Enter search string", "E", "entersearchstring") + replaceitem = FrameWork.MenuItem(m, "Replace", None, "replace") + replacefinditem = FrameWork.MenuItem(m, "Replace & find again", 'T', "replacefind") + FrameWork.Separator(m) + shiftleftitem = FrameWork.MenuItem(m, "Shift left", "[", "shiftleft") + shiftrightitem = FrameWork.MenuItem(m, "Shift right", "]", "shiftright") + + m = Wapplication.Menu(self.menubar, "Python") + runitem = FrameWork.MenuItem(m, "Run window", "R", 'run') + runselitem = FrameWork.MenuItem(m, "Run selection", None, 'runselection') + FrameWork.Separator(m) + moditem = FrameWork.MenuItem(m, "Module browser"+ELLIPSIS, "M", self.domenu_modulebrowser) + FrameWork.Separator(m) + mm = FrameWork.SubMenu(m, "Preferences") + FrameWork.MenuItem(mm, "Set Scripts folder"+ELLIPSIS, None, self.do_setscriptsfolder) + FrameWork.MenuItem(mm, "Editor default settings"+ELLIPSIS, None, self.do_editorprefs) + FrameWork.MenuItem(mm, "Set default window font"+ELLIPSIS, None, self.do_setwindowfont) + + self.openwindowsmenu = Wapplication.Menu(self.menubar, 'Windows') + self.makeopenwindowsmenu() + self._menustocheck = [closeitem, saveitem, saveasitem, saveasappletitem, + undoitem, cutitem, copyitem, pasteitem, + selallitem, sellineitem, + finditem, findagainitem, enterselitem, replaceitem, replacefinditem, + shiftleftitem, shiftrightitem, + runitem, runselitem] + + prefs = self.getprefs() + try: + fsr, d = File.Alias(rawdata=prefs.scriptsfolder).FSResolveAlias(None) + self.scriptsfolder = fsr.FSNewAliasMinimal() + except: + path = os.path.join(os.getcwd(), "Mac", "IDE scripts") + if not os.path.exists(path): + if sys.platform == "darwin": + path = os.path.join(os.getenv("HOME"), "Library", "Python", "IDE-Scripts") + else: + path = os.path.join(os.getcwd(), "Scripts") + if not os.path.exists(path): + os.makedirs(path) + f = open(os.path.join(path, "Place your scripts here"+ELLIPSIS), "w") + f.close() + fsr = File.FSRef(path) + self.scriptsfolder = fsr.FSNewAliasMinimal() + self.scriptsfoldermodtime = getmodtime(fsr) + else: + self.scriptsfoldermodtime = getmodtime(fsr) + prefs.scriptsfolder = self.scriptsfolder.data + self._scripts = {} + self.scriptsmenu = None + self.makescriptsmenu() + self.makehelpmenu() + + def quitevent(self, theAppleEvent, theReply): + self._quit() + + def suspendresume(self, onoff): + if onoff: + fsr, changed = self.scriptsfolder.FSResolveAlias(None) + modtime = getmodtime(fsr) + if self.scriptsfoldermodtime <> modtime or 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: + fsr, a = doc.FSResolveAlias(None) + path = fsr.as_pathname() + self.opendoc(path) + + def opendoc(self, path): + fcreator, ftype = MacOS.GetCreatorAndType(path) + if ftype == 'TEXT': + self.openscript(path) + elif ftype == '\0\0\0\0' and path[-3:] == '.py': + self.openscript(path) + else: + W.Message("Can't open file of type '%s'." % ftype) + + def getabouttext(self): + return "About Python IDE"+ELLIPSIS + + def do_about(self, id, item, window, event): + Splash.about() + + def do_setscriptsfolder(self, *args): + fsr = EasyDialogs.AskFolder(message="Select Scripts Folder", + wanted=File.FSRef) + if fsr: + prefs = self.getprefs() + alis = fsr.FSNewAliasMinimal() + 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): + filename = EasyDialogs.AskFileForOpen(typeList=("TEXT",)) + if filename: + self.openscript(filename) + + def domenu_openbyname(self, *args): + # Open a file by name. If the clipboard contains a filename + # use that as the default. + from Carbon import Scrap + try: + sc = Scrap.GetCurrentScrap() + dft = sc.GetScrapFlavorData("TEXT") + except Scrap.Error: + dft = "" + else: + if not os.path.exists(dft): + dft = "" + filename = EasyDialogs.AskString("Open File Named:", default=dft, ok="Open") + if filename: + self.openscript(filename) + + 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() + fsr, d1 = self.scriptsfolder.FSResolveAlias(None) + self.scriptswalk(fsr.as_pathname(), self.scriptsmenu) + + def makeopenwindowsmenu(self): + for i in range(len(self.openwindowsmenu.items)): + self.openwindowsmenu.menu.DeleteMenuItem(1) + self.openwindowsmenu.items = [] + windows = [] + self._openwindows = {} + for window in self._windows.keys(): + title = window.GetWTitle() + if not title: + title = "<no title>" + windows.append((title, window)) + windows.sort() + for title, window in windows: + if title == "Python Interactive": # ugly but useful hack by Joe Strout + shortcut = '0' + else: + shortcut = None + item = FrameWork.MenuItem(self.openwindowsmenu, title, shortcut, callback = self.domenu_openwindows) + self._openwindows[item.item] = window + self._openwindowscheckmark = 0 + self.checkopenwindowsmenu() + + def makeopenrecentmenu(self): + for i in range(len(self.openrecentmenu.items)): + self.openrecentmenu.menu.DeleteMenuItem(1) + self.openrecentmenu.items = [] + prefs = self.getprefs() + filelist = prefs.recentfiles + if not filelist: + self.openrecentmenu.enable(0) + return + self.openrecentmenu.enable(1) + for filename in filelist: + item = FrameWork.MenuItem(self.openrecentmenu, filename, None, callback = self.domenu_openrecent) + + def addrecentfile(self, file): + prefs = self.getprefs() + filelist = prefs.recentfiles + if not filelist: + filelist = [] + + if file in filelist: + if file == filelist[0]: + return + filelist.remove(file) + filelist.insert(0, file) + filelist = filelist[:10] + prefs.recentfiles = filelist + prefs.save() + self.makeopenrecentmenu() + + def domenu_openwindows(self, id, item, window, event): + w = self._openwindows[item] + w.ShowWindow() + w.SelectWindow() + + def domenu_openrecent(self, id, item, window, event): + prefs = self.getprefs() + filelist = prefs.recentfiles + if not filelist: + filelist = [] + item = item - 1 + filename = filelist[item] + self.openscript(filename) + + def domenu_quit(self): + self._quit() + + def domenu_save(self, *args): + print "Save" + + def _quit(self): + import PyConsole, PyEdit + for window in self._windows.values(): + try: + rv = window.close() # ignore any errors while quitting + except: + rv = 0 # (otherwise, we can get stuck!) + if rv and rv > 0: + return + try: + PyConsole.console.writeprefs() + PyConsole.output.writeprefs() + PyEdit.searchengine.writeprefs() + except: + # Write to __stderr__ so the msg end up in Console.app and has + # at least _some_ chance of getting read... + # But: this is a workaround for way more serious problems with + # the Python 2.2 Jaguar addon. + sys.__stderr__.write("*** PythonIDE: Can't write preferences ***\n") + self.quitting = 1 + + def domenu_openpackagemanager(self): + import PackageManager + PackageManager.PackageBrowser() + + def domenu_gensuite(self): + import gensuitemodule + gensuitemodule.main_interactive() + + def makehelpmenu(self): + hashelp, hasdocs = self.installdocumentation() + self.helpmenu = m = self.gethelpmenu() + helpitem = FrameWork.MenuItem(m, "MacPython Help", None, self.domenu_localhelp) + helpitem.enable(hashelp) + docitem = FrameWork.MenuItem(m, "Python Documentation", None, self.domenu_localdocs) + docitem.enable(hasdocs) + finditem = FrameWork.MenuItem(m, "Lookup in Python Documentation", None, 'lookuppython') + finditem.enable(hasdocs) + if runningOnOSX(): + FrameWork.Separator(m) + doc2item = FrameWork.MenuItem(m, "Apple Developer Documentation", None, self.domenu_appledocs) + find2item = FrameWork.MenuItem(m, "Lookup in Carbon Documentation", None, 'lookupcarbon') + FrameWork.Separator(m) + webitem = FrameWork.MenuItem(m, "Python Documentation on the Web", None, self.domenu_webdocs) + web2item = FrameWork.MenuItem(m, "Python on the Web", None, self.domenu_webpython) + web3item = FrameWork.MenuItem(m, "MacPython on the Web", None, self.domenu_webmacpython) + + def domenu_localdocs(self, *args): + from Carbon import AH + AH.AHGotoPage("Python Documentation", None, None) + + def domenu_localhelp(self, *args): + from Carbon import AH + AH.AHGotoPage("MacPython Help", None, None) + + def domenu_appledocs(self, *args): + from Carbon import AH, AppleHelp + try: + AH.AHGotoMainTOC(AppleHelp.kAHTOCTypeDeveloper) + except AH.Error, arg: + if arg[0] == -50: + W.Message("Developer documentation not installed") + else: + W.Message("AppleHelp Error: %r" % (arg,)) + + def domenu_lookuppython(self, *args): + from Carbon import AH + searchstring = self._getsearchstring() + if not searchstring: + return + try: + AH.AHSearch("Python Documentation", searchstring) + except AH.Error, arg: + W.Message("AppleHelp Error: %r" % (arg,)) + + def domenu_lookupcarbon(self, *args): + from Carbon import AH + searchstring = self._getsearchstring() + if not searchstring: + return + try: + AH.AHSearch("Carbon", searchstring) + except AH.Error, arg: + W.Message("AppleHelp Error: %r" % (arg,)) + + def _getsearchstring(self): + # First we get the frontmost window + front = self.getfrontwindow() + if front and hasattr(front, 'getselectedtext'): + text = front.getselectedtext() + if text: + return text + # This is a cop-out. We should have disabled the menus + # if there is no selection, but the can_ methods only seem + # to work for Windows. Or not for the Help menu, maybe? + text = EasyDialogs.AskString("Search documentation for", ok="Search") + return text + + def domenu_webdocs(self, *args): + import webbrowser + major, minor, micro, state, nano = sys.version_info + if state in ('alpha', 'beta'): + docversion = 'dev/doc/devel' + elif micro == 0: + docversion = 'doc/%d.%d' % (major, minor) + else: + docversion = 'doc/%d.%d.%d' % (major, minor, micro) + webbrowser.open("http://www.python.org/%s" % docversion) + + def domenu_webpython(self, *args): + import webbrowser + webbrowser.open("http://www.python.org/") + + def domenu_webmacpython(self, *args): + import webbrowser + webbrowser.open("http://www.cwi.nl/~jack/macpython.html") + + def installdocumentation(self): + # This is rather much of a hack. Someone has to tell the Help Viewer + # about the Python documentation, so why not us. The documentation + # is located in the framework, but there's a symlink in Python.app. + # And as AHRegisterHelpBook wants a bundle (with the right bits in + # the plist file) we refer it to Python.app + # + # To make matters worse we have to look in two places: first in the IDE + # itself, then in the Python application inside the framework. + has_help = False + has_doc = False + ide_path_components = sys.argv[0].split("/") + if ide_path_components[-3:] == ["Contents", "Resources", "PythonIDE.py"]: + ide_app = "/".join(ide_path_components[:-3]) + help_source = os.path.join(ide_app, 'Contents/Resources/English.lproj/Documentation') + doc_source = os.path.join(ide_app, 'Contents/Resources/English.lproj/PythonDocumentation') + has_help = os.path.isdir(help_source) + has_doc = os.path.isdir(doc_source) + if has_help or has_doc: + try: + from Carbon import AH + AH.AHRegisterHelpBook(ide_app) + except (ImportError, MacOS.Error), arg: + pass # W.Message("Cannot register Python Documentation: %s" % str(arg)) + python_app = os.path.join(sys.prefix, 'Resources/Python.app') + if not has_help: + help_source = os.path.join(python_app, 'Contents/Resources/English.lproj/Documentation') + has_help = os.path.isdir(help_source) + if not has_doc: + doc_source = os.path.join(python_app, 'Contents/Resources/English.lproj/PythonDocumentation') + has_doc = os.path.isdir(doc_source) + if has_help or has_doc: + try: + from Carbon import AH + AH.AHRegisterHelpBook(python_app) + except (ImportError, MacOS.Error), arg: + pass # W.Message("Cannot register Python Documentation: %s" % str(arg)) + return has_help, has_doc diff --git a/Mac/Tools/IDE/Splash.py b/Mac/Tools/IDE/Splash.py index 86009d2..ab36fa4 100644 --- a/Mac/Tools/IDE/Splash.py +++ b/Mac/Tools/IDE/Splash.py @@ -25,88 +25,88 @@ 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 . . . +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') + return string.replace(text, '\n\n', '\n') def nl2return(text): - return string.replace(text, '\n', '\r') + 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) + 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) + 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 + 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() + global splash, splashresfile, _keepsplashscreenopen + _keepsplashscreenopen = 1 + splash = Dlg.GetNewDialog(468, -1) + splash.DrawDialog() + wait() diff --git a/Mac/Tools/IDE/W.py b/Mac/Tools/IDE/W.py index 397b211..3ddeb76 100644 --- a/Mac/Tools/IDE/W.py +++ b/Mac/Tools/IDE/W.py @@ -15,27 +15,26 @@ _signature = None AlertError = 'AlertError' def setapplication(app, sig): - global _application, _signature - _application = app - _signature = sig + global _application, _signature + _application = app + _signature = sig def getapplication(): - if _application is None: - raise WidgetsError, 'W not properly initialized: unknown Application' - return _application + 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 + 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) - + 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) diff --git a/Mac/Tools/IDE/Wapplication.py b/Mac/Tools/IDE/Wapplication.py index 553391e..4cfc77b 100644 --- a/Mac/Tools/IDE/Wapplication.py +++ b/Mac/Tools/IDE/Wapplication.py @@ -11,472 +11,471 @@ import macresource from Carbon import File if hasattr(Win, "FrontNonFloatingWindow"): - MyFrontWindow = Win.FrontNonFloatingWindow + MyFrontWindow = Win.FrontNonFloatingWindow else: - MyFrontWindow = Win.FrontWindow + MyFrontWindow = Win.FrontWindow KILLUNKNOWNWINDOWS = 0 # Set to 0 for debugging. class Application(FrameWork.Application): - - def __init__(self, signature='Pyth'): - # Open our resource file, if it is not open yet - macresource.need('CURS', 468, "Widgets.rsrc") - import W - W.setapplication(self, signature) - FrameWork.Application.__init__(self) - self._suspended = 0 - self.quitting = 0 - self.debugger_quitting = 1 - self.DebuggerQuit = 'DebuggerQuitDummyException' - self._idlefuncs = [] - # map certain F key codes to equivalent command-letter combos (JJS) - self.fkeymaps = {122:"z", 120:"x", 99:"c", 118:"v"} - - def mainloop(self, mask=FrameWork.everyEvent, wait=None): - import W - self.quitting = 0 - if hasattr(MacOS, 'EnableAppswitch'): - saveyield = MacOS.EnableAppswitch(-1) - try: - while not self.quitting: - try: - self.do1event(mask, wait) - except W.AlertError, detail: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(-1) - W.Message(detail) - except self.DebuggerQuit: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(-1) - except: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(-1) - import PyEdit - PyEdit.tracebackwindow.traceback() - finally: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(1) - - def debugger_mainloop(self, mask=FrameWork.everyEvent, wait=None): - import W - self.debugger_quitting = 0 - if hasattr(MacOS, 'EnableAppswitch'): - 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: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(saveyield) - - def breathe(self, wait=1): - import W - ok, event = Evt.WaitNextEvent(FrameWork.updateMask | - FrameWork.mDownMask | FrameWork.osMask | - FrameWork.activMask, - wait) - if ok: - (what, message, when, where, modifiers) = event - #print FrameWork.eventname[what] - if FrameWork.eventname[what] == 'mouseDown': - partcode, wid = Win.FindWindow(where) - if FrameWork.partname[partcode] <> 'inDesk': - return - else: - W.SetCursor('watch') - self.dispatch(event) - - def refreshwindows(self, wait=1): - import W - while 1: - ok, event = Evt.WaitNextEvent(FrameWork.updateMask, wait) - if not ok: - break - self.dispatch(event) - - def addidlefunc(self, func): - self._idlefuncs.append(func) - - def removeidlefunc(self, func): - self._idlefuncs.remove(func) - - def idle(self, event): - if not self._suspended: - if not self.do_frontWindowMethod("idle", event): - Qd.InitCursor() - if self._idlefuncs: - for func in self._idlefuncs: - try: - func() - except: - import sys - sys.stderr.write("exception in idle function %r; killed:\n" % (func,)) - traceback.print_exc() - self._idlefuncs.remove(func) - break - - def do_frontWindowMethod(self, attr, *args): - wid = MyFrontWindow() - 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 getfrontwindow(self): - wid = MyFrontWindow() - if wid and self._windows.has_key(wid): - return self._windows[wid] - return None - - def appendwindow(self, wid, window): - self._windows[wid] = window - self.makeopenwindowsmenu() - - def removewindow(self, wid): - del self._windows[wid] - self.makeopenwindowsmenu() - - def makeopenwindowsmenu(self): - # dummy; could be the full version from PythonIDEMain.py - self._openwindows = {} - self._openwindowscheckmark = 0 - if not hasattr(self, "_menustocheck"): - self._menustocheck = [] - - def do_key(self, event): - (what, message, when, where, modifiers) = event - ch = chr(message & FrameWork.charCodeMask) - rest = message & ~FrameWork.charCodeMask - keycode = (message & FrameWork.keyCodeMask) >> 8 - if keycode in self.fkeymaps.keys(): # JJS - ch = self.fkeymaps[keycode] - modifiers = modifiers | FrameWork.cmdKey - wid = MyFrontWindow() - if modifiers & FrameWork.cmdKey and not modifiers & FrameWork.shiftKey: - 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-%r" % 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 = MyFrontWindow() - 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 - if id >= 0x8000: - id = -0x10000 + id - 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 KILLUNKNOWNWINDOWS and wid: - wid.HideWindow() - import sys - sys.stderr.write("XXX killed unknown (crashed?) Python window.\n") - else: - if hasattr(MacOS, 'HandleEvent'): - MacOS.HandleEvent(event) - else: - print 'Unexpected updateEvent:', event - - def suspendresume(self, onoff): - pass - - def do_suspendresume(self, event): - self._suspended = not event[1] & 1 - FrameWork.Application.do_suspendresume(self, event) - - def checkopenwindowsmenu(self): - if self._openwindowscheckmark: - self.openwindowsmenu.menu.CheckMenuItem(self._openwindowscheckmark, 0) - window = MyFrontWindow() - if window: - for item, wid in self._openwindows.items(): - if wid == window: - #self.pythonwindowsmenuitem.check(1) - self.openwindowsmenu.menu.CheckMenuItem(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 enablemenubar(self, onoff): - for m in self.menubar.menus.values(): - if onoff: - m.menu.EnableMenuItem(0) - elif m.menu.GetMenuItemText(3) <> 'Cut': # ew... - m.menu.DisableMenuItem(0) - MenuToolbox.DrawMenuBar() - - def makemenubar(self): - self.menubar = MenuBar(self) - FrameWork.AppleMenu(self.menubar, self.getabouttext(), self.do_about) - self.makeusermenus() - - def scriptswalk(self, top, menu, done=None): - if menu.id > 200: - import W - W.Message("Scripts folder not completely traversed: running out of menus") - return False - if done is None: - done = {} - if done.has_key(top): - return True - done[top] = 1 - import os, string - try: - names = os.listdir(top) - except os.error: - FrameWork.MenuItem(menu, '(Scripts Folder not found)', None, None) - return True - savedir = os.getcwd() - os.chdir(top) - for name in names: - if name == "CVS": - continue - try: - fsr, isdir, isalias = File.FSResolveAliasFile(name, 1) - except: - # maybe a broken alias - continue - path = fsr.as_pathname() - if done.has_key(path): - continue - name = string.strip(name) - if os.name == "posix": - name = unicode(name, "utf-8") - if name[-3:] == '---': - menu.addseparator() - elif isdir: - submenu = FrameWork.SubMenu(menu, name) - if not self.scriptswalk(path, submenu, done): - return False - else: - creator, type = MacOS.GetCreatorAndType(path) - 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 - done[path] = 1 - os.chdir(savedir) - return True - - 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 ord(Evt.GetKeys()[7]) & 4: - 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? - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(0) - execfile(path, {'__name__': '__main__', '__file__': path}) - except W.AlertError, detail: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(-1) - raise W.AlertError, detail - except KeyboardInterrupt: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(-1) - except: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(-1) - import PyEdit - PyEdit.tracebackwindow.traceback(1) - else: - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(-1) - #os.chdir(cwd) - - def openscript(self, filename, lineno=None, charoffset=0, modname=""): - 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' or filename[-4:] == '.pyc': - import imp - if not modname: - if filename[-1] == 'c': - modname = os.path.basename(filename)[:-4] - else: - modname = os.path.basename(filename)[:-3] - try: - # XXX This does not work correctly with packages! - # XXX The docs say we should do it manually, pack, then sub, then sub2 etc. - # XXX It says we should use imp.load_module(), but that *reloads* a package, - # XXX and that's the last thing we want here. - f, filename, (suff, mode, dummy) = imp.find_module(modname) - except ImportError: - raise W.AlertError, "Can't find file for \"%s\"" % modname - else: - if not f: - raise W.AlertError, "Can't find file for \"%s\"" % modname - f.close() - if suff == '.py': - self.openscript(filename, lineno, charoffset) - return - else: - raise W.AlertError, "Can't find file for \"%s\"" % modname - else: - raise W.AlertError, "Can't 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 type(window.path) == StringType 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) - - def do_editorprefs(self, *args): - import PyEdit - PyEdit.EditorDefaultSettings() - - def do_setwindowfont(self, *args): - import FontSettings, W - prefs = self.getprefs() - settings = FontSettings.FontDialog(prefs.defaultfont) - if settings: - prefs.defaultfont, tabsettings = settings - raise W.AlertError, "Note that changes will only affect new windows!" + + def __init__(self, signature='Pyth'): + # Open our resource file, if it is not open yet + macresource.need('CURS', 468, "Widgets.rsrc") + import W + W.setapplication(self, signature) + FrameWork.Application.__init__(self) + self._suspended = 0 + self.quitting = 0 + self.debugger_quitting = 1 + self.DebuggerQuit = 'DebuggerQuitDummyException' + self._idlefuncs = [] + # map certain F key codes to equivalent command-letter combos (JJS) + self.fkeymaps = {122:"z", 120:"x", 99:"c", 118:"v"} + + def mainloop(self, mask=FrameWork.everyEvent, wait=None): + import W + self.quitting = 0 + if hasattr(MacOS, 'EnableAppswitch'): + saveyield = MacOS.EnableAppswitch(-1) + try: + while not self.quitting: + try: + self.do1event(mask, wait) + except W.AlertError, detail: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(-1) + W.Message(detail) + except self.DebuggerQuit: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(-1) + except: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(-1) + import PyEdit + PyEdit.tracebackwindow.traceback() + finally: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(1) + + def debugger_mainloop(self, mask=FrameWork.everyEvent, wait=None): + import W + self.debugger_quitting = 0 + if hasattr(MacOS, 'EnableAppswitch'): + 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: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(saveyield) + + def breathe(self, wait=1): + import W + ok, event = Evt.WaitNextEvent(FrameWork.updateMask | + FrameWork.mDownMask | FrameWork.osMask | + FrameWork.activMask, + wait) + if ok: + (what, message, when, where, modifiers) = event + #print FrameWork.eventname[what] + if FrameWork.eventname[what] == 'mouseDown': + partcode, wid = Win.FindWindow(where) + if FrameWork.partname[partcode] <> 'inDesk': + return + else: + W.SetCursor('watch') + self.dispatch(event) + + def refreshwindows(self, wait=1): + import W + while 1: + ok, event = Evt.WaitNextEvent(FrameWork.updateMask, wait) + if not ok: + break + self.dispatch(event) + + def addidlefunc(self, func): + self._idlefuncs.append(func) + + def removeidlefunc(self, func): + self._idlefuncs.remove(func) + + def idle(self, event): + if not self._suspended: + if not self.do_frontWindowMethod("idle", event): + Qd.InitCursor() + if self._idlefuncs: + for func in self._idlefuncs: + try: + func() + except: + import sys + sys.stderr.write("exception in idle function %r; killed:\n" % (func,)) + traceback.print_exc() + self._idlefuncs.remove(func) + break + + def do_frontWindowMethod(self, attr, *args): + wid = MyFrontWindow() + 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 getfrontwindow(self): + wid = MyFrontWindow() + if wid and self._windows.has_key(wid): + return self._windows[wid] + return None + + def appendwindow(self, wid, window): + self._windows[wid] = window + self.makeopenwindowsmenu() + + def removewindow(self, wid): + del self._windows[wid] + self.makeopenwindowsmenu() + + def makeopenwindowsmenu(self): + # dummy; could be the full version from PythonIDEMain.py + self._openwindows = {} + self._openwindowscheckmark = 0 + if not hasattr(self, "_menustocheck"): + self._menustocheck = [] + + def do_key(self, event): + (what, message, when, where, modifiers) = event + ch = chr(message & FrameWork.charCodeMask) + rest = message & ~FrameWork.charCodeMask + keycode = (message & FrameWork.keyCodeMask) >> 8 + if keycode in self.fkeymaps.keys(): # JJS + ch = self.fkeymaps[keycode] + modifiers = modifiers | FrameWork.cmdKey + wid = MyFrontWindow() + if modifiers & FrameWork.cmdKey and not modifiers & FrameWork.shiftKey: + 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-%r" % 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 = MyFrontWindow() + 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 + if id >= 0x8000: + id = -0x10000 + id + 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 KILLUNKNOWNWINDOWS and wid: + wid.HideWindow() + import sys + sys.stderr.write("XXX killed unknown (crashed?) Python window.\n") + else: + if hasattr(MacOS, 'HandleEvent'): + MacOS.HandleEvent(event) + else: + print 'Unexpected updateEvent:', event + + def suspendresume(self, onoff): + pass + + def do_suspendresume(self, event): + self._suspended = not event[1] & 1 + FrameWork.Application.do_suspendresume(self, event) + + def checkopenwindowsmenu(self): + if self._openwindowscheckmark: + self.openwindowsmenu.menu.CheckMenuItem(self._openwindowscheckmark, 0) + window = MyFrontWindow() + if window: + for item, wid in self._openwindows.items(): + if wid == window: + #self.pythonwindowsmenuitem.check(1) + self.openwindowsmenu.menu.CheckMenuItem(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 enablemenubar(self, onoff): + for m in self.menubar.menus.values(): + if onoff: + m.menu.EnableMenuItem(0) + elif m.menu.GetMenuItemText(3) <> 'Cut': # ew... + m.menu.DisableMenuItem(0) + MenuToolbox.DrawMenuBar() + + def makemenubar(self): + self.menubar = MenuBar(self) + FrameWork.AppleMenu(self.menubar, self.getabouttext(), self.do_about) + self.makeusermenus() + + def scriptswalk(self, top, menu, done=None): + if menu.id > 200: + import W + W.Message("Scripts folder not completely traversed: running out of menus") + return False + if done is None: + done = {} + if done.has_key(top): + return True + done[top] = 1 + import os, string + try: + names = os.listdir(top) + except os.error: + FrameWork.MenuItem(menu, '(Scripts Folder not found)', None, None) + return True + savedir = os.getcwd() + os.chdir(top) + for name in names: + if name == "CVS": + continue + try: + fsr, isdir, isalias = File.FSResolveAliasFile(name, 1) + except: + # maybe a broken alias + continue + path = fsr.as_pathname() + if done.has_key(path): + continue + name = string.strip(name) + if os.name == "posix": + name = unicode(name, "utf-8") + if name[-3:] == '---': + menu.addseparator() + elif isdir: + submenu = FrameWork.SubMenu(menu, name) + if not self.scriptswalk(path, submenu, done): + return False + else: + creator, type = MacOS.GetCreatorAndType(path) + 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 + done[path] = 1 + os.chdir(savedir) + return True + + 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 ord(Evt.GetKeys()[7]) & 4: + 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? + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(0) + execfile(path, {'__name__': '__main__', '__file__': path}) + except W.AlertError, detail: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(-1) + raise W.AlertError, detail + except KeyboardInterrupt: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(-1) + except: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(-1) + import PyEdit + PyEdit.tracebackwindow.traceback(1) + else: + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(-1) + #os.chdir(cwd) + + def openscript(self, filename, lineno=None, charoffset=0, modname=""): + 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' or filename[-4:] == '.pyc': + import imp + if not modname: + if filename[-1] == 'c': + modname = os.path.basename(filename)[:-4] + else: + modname = os.path.basename(filename)[:-3] + try: + # XXX This does not work correctly with packages! + # XXX The docs say we should do it manually, pack, then sub, then sub2 etc. + # XXX It says we should use imp.load_module(), but that *reloads* a package, + # XXX and that's the last thing we want here. + f, filename, (suff, mode, dummy) = imp.find_module(modname) + except ImportError: + raise W.AlertError, "Can't find file for \"%s\"" % modname + else: + if not f: + raise W.AlertError, "Can't find file for \"%s\"" % modname + f.close() + if suff == '.py': + self.openscript(filename, lineno, charoffset) + return + else: + raise W.AlertError, "Can't find file for \"%s\"" % modname + else: + raise W.AlertError, "Can't 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 type(window.path) == StringType 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) + + def do_editorprefs(self, *args): + import PyEdit + PyEdit.EditorDefaultSettings() + + def do_setwindowfont(self, *args): + import FontSettings, W + prefs = self.getprefs() + settings = FontSettings.FontDialog(prefs.defaultfont) + if settings: + prefs.defaultfont, tabsettings = settings + raise W.AlertError, "Note that changes will only affect new windows!" 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) - + + 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 = MyFrontWindow() - 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 + 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 = MyFrontWindow() + 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 diff --git a/Mac/Tools/IDE/Wbase.py b/Mac/Tools/IDE/Wbase.py index a5d556b..4eef120 100644 --- a/Mac/Tools/IDE/Wbase.py +++ b/Mac/Tools/IDE/Wbase.py @@ -9,790 +9,790 @@ DEBUG = 0 def _intRect((l, t, r, b)): - return (int(l), int(t), int(r), int(b)) + return (int(l), int(t), int(r), int(b)) class Widget: - - """Base class for all widgets.""" - - _selectable = 0 - - def __init__(self, possize): - self._widgets = [] - self._widgetsdict = {} - self._possize = possize - self._bounds = None - self._visible = 1 - self._enabled = 0 - self._selected = 0 - self._activated = 0 - self._callback = None - self._parent = None - self._parentwindow = None - self._bindings = {} - self._backcolor = None - - def show(self, onoff): - self._visible = onoff - for w in self._widgets: - w.show(onoff) - if self._parentwindow is not None and self._parentwindow.wid is not None: - self.SetPort() - if onoff: - self.draw() - else: - Qd.EraseRect(self._bounds) - - def draw(self, visRgn = None): - if self._visible: - # draw your stuff here - pass - - def getpossize(self): - return self._possize - - def getbounds(self): - return self._bounds - - def move(self, x, y = None): - """absolute move""" - if y == None: - x, y = x - if type(self._possize) <> TupleType: - raise WidgetsError, "can't move widget with bounds function" - l, t, r, b = self._possize - self.resize(x, y, r, b) - - def rmove(self, x, y = None): - """relative move""" - if y == None: - x, y = x - if type(self._possize) <> TupleType: - raise WidgetsError, "can't move widget with bounds function" - l, t, r, b = self._possize - self.resize(l + x, t + y, r, b) - - def resize(self, *args): - if len(args) == 1: - if type(args[0]) == FunctionType or type(args[0]) == MethodType: - self._possize = args[0] - else: - apply(self.resize, args[0]) - elif len(args) == 2: - self._possize = (0, 0) + args - elif len(args) == 4: - self._possize = args - else: - raise TypeError, "wrong number of arguments" - self._calcbounds() - - def open(self): - self._calcbounds() - - def close(self): - del self._callback - del self._possize - del self._bindings - del self._parent - del self._parentwindow - - def bind(self, key, callback): - """bind a key or an 'event' to a callback""" - if callback: - self._bindings[key] = callback - elif self._bindings.has_key(key): - del self._bindings[key] - - def adjust(self, oldbounds): - self.SetPort() - self.GetWindow().InvalWindowRect(oldbounds) - self.GetWindow().InvalWindowRect(self._bounds) - - def _calcbounds(self): - # calculate absolute bounds relative to the window origin from our - # abstract _possize attribute, which is either a 4-tuple or a callable object - oldbounds = self._bounds - pl, pt, pr, pb = self._parent._bounds - if callable(self._possize): - # _possize is callable, let it figure it out by itself: it should return - # the bounds relative to our parent widget. - width = pr - pl - height = pb - pt - self._bounds = Qd.OffsetRect(_intRect(self._possize(width, height)), pl, pt) - else: - # _possize must be a 4-tuple. This is where the algorithm by Peter Kriens and - # Petr van Blokland kicks in. (*** Parts of this algorithm are applied for - # patents by Ericsson, Sweden ***) - l, t, r, b = self._possize - # depending on the values of l(eft), t(op), r(right) and b(ottom), - # they mean different things: - if l < -1: - # l is less than -1, this mean it measures from the *right* of it's parent - l = pr + l - else: - # l is -1 or greater, this mean it measures from the *left* of it's parent - l = pl + l - if t < -1: - # t is less than -1, this mean it measures from the *bottom* of it's parent - t = pb + t - else: - # t is -1 or greater, this mean it measures from the *top* of it's parent - t = pt + t - if r > 1: - # r is greater than 1, this means r is the *width* of the widget - r = l + r - else: - # r is less than 1, this means it measures from the *right* of it's parent - r = pr + r - if b > 1: - # b is greater than 1, this means b is the *height* of the widget - b = t + b - else: - # b is less than 1, this means it measures from the *bottom* of it's parent - b = pb + b - self._bounds = (l, t, r, b) - if oldbounds and oldbounds <> self._bounds: - self.adjust(oldbounds) - for w in self._widgets: - w._calcbounds() - - def test(self, point): - if Qd.PtInRect(point, self._bounds): - return 1 - - def click(self, point, modifiers): - pass - - def findwidget(self, point, onlyenabled = 1): - if self.test(point): - for w in self._widgets: - widget = w.findwidget(point) - if widget is not None: - return widget - if self._enabled or not onlyenabled: - return self - - def forall(self, methodname, *args): - for w in self._widgets: - rv = apply(w.forall, (methodname,) + args) - if rv: - return rv - if self._bindings.has_key("<" + methodname + ">"): - callback = self._bindings["<" + methodname + ">"] - rv = apply(callback, args) - if rv: - return rv - if hasattr(self, methodname): - method = getattr(self, methodname) - return apply(method, args) - - def forall_butself(self, methodname, *args): - for w in self._widgets: - rv = apply(w.forall, (methodname,) + args) - if rv: - return rv - - def forall_frombottom(self, methodname, *args): - if self._bindings.has_key("<" + methodname + ">"): - callback = self._bindings["<" + methodname + ">"] - rv = apply(callback, args) - if rv: - return rv - if hasattr(self, methodname): - method = getattr(self, methodname) - rv = apply(method, args) - if rv: - return rv - for w in self._widgets: - rv = apply(w.forall_frombottom, (methodname,) + args) - if rv: - return rv - - def _addwidget(self, key, widget): - if widget in self._widgets: - raise ValueError, "duplicate widget" - if self._widgetsdict.has_key(key): - self._removewidget(key) - self._widgets.append(widget) - self._widgetsdict[key] = widget - widget._parent = self - self._setparentwindow(widget) - if self._parentwindow and self._parentwindow.wid: - widget.forall_frombottom("open") - self.GetWindow().InvalWindowRect(widget._bounds) - - def _setparentwindow(self, widget): - widget._parentwindow = self._parentwindow - for w in widget._widgets: - self._setparentwindow(w) - - def _removewidget(self, key): - if not self._widgetsdict.has_key(key): - raise KeyError, "no widget with key %r" % (key,) - widget = self._widgetsdict[key] - for k in widget._widgetsdict.keys(): - widget._removewidget(k) - if self._parentwindow._currentwidget == widget: - widget.select(0) - self._parentwindow._currentwidget = None - self.SetPort() - self.GetWindow().InvalWindowRect(widget._bounds) - widget.close() - del self._widgetsdict[key] - self._widgets.remove(widget) - - def __setattr__(self, attr, value): - if type(value) == InstanceType and isinstance(value, Widget) and \ - attr not in ("_currentwidget", "_lastrollover", - "_parent", "_parentwindow", "_defaultbutton"): - if hasattr(self, attr): - raise ValueError, "Can't replace existing attribute: " + attr - self._addwidget(attr, value) - self.__dict__[attr] = value - - def __delattr__(self, attr): - if attr == "_widgetsdict": - raise AttributeError, "cannot delete attribute _widgetsdict" - if self._widgetsdict.has_key(attr): - self._removewidget(attr) - if self.__dict__.has_key(attr): - del self.__dict__[attr] - elif self.__dict__.has_key(attr): - del self.__dict__[attr] - else: - raise AttributeError, attr - - def __setitem__(self, key, value): - self._addwidget(key, value) - - def __getitem__(self, key): - if not self._widgetsdict.has_key(key): - raise KeyError, key - return self._widgetsdict[key] - - def __delitem__(self, key): - self._removewidget(key) - - def SetPort(self): - self._parentwindow.SetPort() - - - def GetWindow(self): - return self._parentwindow.GetWindow() - - def __del__(self): - if DEBUG: - print "%s instance deleted" % self.__class__.__name__ - - def _drawbounds(self): - Qd.FrameRect(self._bounds) + + """Base class for all widgets.""" + + _selectable = 0 + + def __init__(self, possize): + self._widgets = [] + self._widgetsdict = {} + self._possize = possize + self._bounds = None + self._visible = 1 + self._enabled = 0 + self._selected = 0 + self._activated = 0 + self._callback = None + self._parent = None + self._parentwindow = None + self._bindings = {} + self._backcolor = None + + def show(self, onoff): + self._visible = onoff + for w in self._widgets: + w.show(onoff) + if self._parentwindow is not None and self._parentwindow.wid is not None: + self.SetPort() + if onoff: + self.draw() + else: + Qd.EraseRect(self._bounds) + + def draw(self, visRgn = None): + if self._visible: + # draw your stuff here + pass + + def getpossize(self): + return self._possize + + def getbounds(self): + return self._bounds + + def move(self, x, y = None): + """absolute move""" + if y == None: + x, y = x + if type(self._possize) <> TupleType: + raise WidgetsError, "can't move widget with bounds function" + l, t, r, b = self._possize + self.resize(x, y, r, b) + + def rmove(self, x, y = None): + """relative move""" + if y == None: + x, y = x + if type(self._possize) <> TupleType: + raise WidgetsError, "can't move widget with bounds function" + l, t, r, b = self._possize + self.resize(l + x, t + y, r, b) + + def resize(self, *args): + if len(args) == 1: + if type(args[0]) == FunctionType or type(args[0]) == MethodType: + self._possize = args[0] + else: + apply(self.resize, args[0]) + elif len(args) == 2: + self._possize = (0, 0) + args + elif len(args) == 4: + self._possize = args + else: + raise TypeError, "wrong number of arguments" + self._calcbounds() + + def open(self): + self._calcbounds() + + def close(self): + del self._callback + del self._possize + del self._bindings + del self._parent + del self._parentwindow + + def bind(self, key, callback): + """bind a key or an 'event' to a callback""" + if callback: + self._bindings[key] = callback + elif self._bindings.has_key(key): + del self._bindings[key] + + def adjust(self, oldbounds): + self.SetPort() + self.GetWindow().InvalWindowRect(oldbounds) + self.GetWindow().InvalWindowRect(self._bounds) + + def _calcbounds(self): + # calculate absolute bounds relative to the window origin from our + # abstract _possize attribute, which is either a 4-tuple or a callable object + oldbounds = self._bounds + pl, pt, pr, pb = self._parent._bounds + if callable(self._possize): + # _possize is callable, let it figure it out by itself: it should return + # the bounds relative to our parent widget. + width = pr - pl + height = pb - pt + self._bounds = Qd.OffsetRect(_intRect(self._possize(width, height)), pl, pt) + else: + # _possize must be a 4-tuple. This is where the algorithm by Peter Kriens and + # Petr van Blokland kicks in. (*** Parts of this algorithm are applied for + # patents by Ericsson, Sweden ***) + l, t, r, b = self._possize + # depending on the values of l(eft), t(op), r(right) and b(ottom), + # they mean different things: + if l < -1: + # l is less than -1, this mean it measures from the *right* of it's parent + l = pr + l + else: + # l is -1 or greater, this mean it measures from the *left* of it's parent + l = pl + l + if t < -1: + # t is less than -1, this mean it measures from the *bottom* of it's parent + t = pb + t + else: + # t is -1 or greater, this mean it measures from the *top* of it's parent + t = pt + t + if r > 1: + # r is greater than 1, this means r is the *width* of the widget + r = l + r + else: + # r is less than 1, this means it measures from the *right* of it's parent + r = pr + r + if b > 1: + # b is greater than 1, this means b is the *height* of the widget + b = t + b + else: + # b is less than 1, this means it measures from the *bottom* of it's parent + b = pb + b + self._bounds = (l, t, r, b) + if oldbounds and oldbounds <> self._bounds: + self.adjust(oldbounds) + for w in self._widgets: + w._calcbounds() + + def test(self, point): + if Qd.PtInRect(point, self._bounds): + return 1 + + def click(self, point, modifiers): + pass + + def findwidget(self, point, onlyenabled = 1): + if self.test(point): + for w in self._widgets: + widget = w.findwidget(point) + if widget is not None: + return widget + if self._enabled or not onlyenabled: + return self + + def forall(self, methodname, *args): + for w in self._widgets: + rv = apply(w.forall, (methodname,) + args) + if rv: + return rv + if self._bindings.has_key("<" + methodname + ">"): + callback = self._bindings["<" + methodname + ">"] + rv = apply(callback, args) + if rv: + return rv + if hasattr(self, methodname): + method = getattr(self, methodname) + return apply(method, args) + + def forall_butself(self, methodname, *args): + for w in self._widgets: + rv = apply(w.forall, (methodname,) + args) + if rv: + return rv + + def forall_frombottom(self, methodname, *args): + if self._bindings.has_key("<" + methodname + ">"): + callback = self._bindings["<" + methodname + ">"] + rv = apply(callback, args) + if rv: + return rv + if hasattr(self, methodname): + method = getattr(self, methodname) + rv = apply(method, args) + if rv: + return rv + for w in self._widgets: + rv = apply(w.forall_frombottom, (methodname,) + args) + if rv: + return rv + + def _addwidget(self, key, widget): + if widget in self._widgets: + raise ValueError, "duplicate widget" + if self._widgetsdict.has_key(key): + self._removewidget(key) + self._widgets.append(widget) + self._widgetsdict[key] = widget + widget._parent = self + self._setparentwindow(widget) + if self._parentwindow and self._parentwindow.wid: + widget.forall_frombottom("open") + self.GetWindow().InvalWindowRect(widget._bounds) + + def _setparentwindow(self, widget): + widget._parentwindow = self._parentwindow + for w in widget._widgets: + self._setparentwindow(w) + + def _removewidget(self, key): + if not self._widgetsdict.has_key(key): + raise KeyError, "no widget with key %r" % (key,) + widget = self._widgetsdict[key] + for k in widget._widgetsdict.keys(): + widget._removewidget(k) + if self._parentwindow._currentwidget == widget: + widget.select(0) + self._parentwindow._currentwidget = None + self.SetPort() + self.GetWindow().InvalWindowRect(widget._bounds) + widget.close() + del self._widgetsdict[key] + self._widgets.remove(widget) + + def __setattr__(self, attr, value): + if type(value) == InstanceType and isinstance(value, Widget) and \ + attr not in ("_currentwidget", "_lastrollover", + "_parent", "_parentwindow", "_defaultbutton"): + if hasattr(self, attr): + raise ValueError, "Can't replace existing attribute: " + attr + self._addwidget(attr, value) + self.__dict__[attr] = value + + def __delattr__(self, attr): + if attr == "_widgetsdict": + raise AttributeError, "cannot delete attribute _widgetsdict" + if self._widgetsdict.has_key(attr): + self._removewidget(attr) + if self.__dict__.has_key(attr): + del self.__dict__[attr] + elif self.__dict__.has_key(attr): + del self.__dict__[attr] + else: + raise AttributeError, attr + + def __setitem__(self, key, value): + self._addwidget(key, value) + + def __getitem__(self, key): + if not self._widgetsdict.has_key(key): + raise KeyError, key + return self._widgetsdict[key] + + def __delitem__(self, key): + self._removewidget(key) + + def SetPort(self): + self._parentwindow.SetPort() + + + def GetWindow(self): + return self._parentwindow.GetWindow() + + def __del__(self): + if DEBUG: + print "%s instance deleted" % self.__class__.__name__ + + def _drawbounds(self): + Qd.FrameRect(self._bounds) class ClickableWidget(Widget): - - """Base class for clickable widgets. (note: self._enabled must be true to receive click events.)""" - - def click(self, point, modifiers): - pass - - def enable(self, onoff): - self._enabled = onoff - self.SetPort() - self.draw() - - def callback(self): - if self._callback: - return CallbackCall(self._callback, 1) - + + """Base class for clickable widgets. (note: self._enabled must be true to receive click events.)""" + + def click(self, point, modifiers): + pass + + def enable(self, onoff): + self._enabled = onoff + self.SetPort() + self.draw() + + def callback(self): + if self._callback: + return CallbackCall(self._callback, 1) + class SelectableWidget(ClickableWidget): - """Base class for selectable widgets.""" - - _selectable = 1 - - def select(self, onoff, isclick = 0): - if onoff == self._selected: - return 1 - if self._bindings.has_key("<select>"): - callback = self._bindings["<select>"] - if callback(onoff): - return 1 - self._selected = onoff - if onoff: - if self._parentwindow._currentwidget is not None: - self._parentwindow._currentwidget.select(0) - self._parentwindow._currentwidget = self - else: - self._parentwindow._currentwidget = None - - def key(self, char, event): - pass - - def drawselframe(self, onoff): - if not self._parentwindow._hasselframes: - return - App.DrawThemeFocusRect(self._bounds, onoff) - - def adjust(self, oldbounds): - self.SetPort() - if self._selected: - self.GetWindow().InvalWindowRect(Qd.InsetRect(oldbounds, -3, -3)) - self.GetWindow().InvalWindowRect(Qd.InsetRect(self._bounds, -3, -3)) - else: - self.GetWindow().InvalWindowRect(oldbounds) - self.GetWindow().InvalWindowRect(self._bounds) + """Base class for selectable widgets.""" + + _selectable = 1 + + def select(self, onoff, isclick = 0): + if onoff == self._selected: + return 1 + if self._bindings.has_key("<select>"): + callback = self._bindings["<select>"] + if callback(onoff): + return 1 + self._selected = onoff + if onoff: + if self._parentwindow._currentwidget is not None: + self._parentwindow._currentwidget.select(0) + self._parentwindow._currentwidget = self + else: + self._parentwindow._currentwidget = None + + def key(self, char, event): + pass + + def drawselframe(self, onoff): + if not self._parentwindow._hasselframes: + return + App.DrawThemeFocusRect(self._bounds, onoff) + + def adjust(self, oldbounds): + self.SetPort() + if self._selected: + self.GetWindow().InvalWindowRect(Qd.InsetRect(oldbounds, -3, -3)) + self.GetWindow().InvalWindowRect(Qd.InsetRect(self._bounds, -3, -3)) + else: + self.GetWindow().InvalWindowRect(oldbounds) + self.GetWindow().InvalWindowRect(self._bounds) class _Line(Widget): - - def __init__(self, possize, thickness = 1): - Widget.__init__(self, possize) - self._thickness = thickness - - def open(self): - self._calcbounds() - self.SetPort() - self.draw() - - def draw(self, visRgn = None): - if self._visible: - Qd.PaintRect(self._bounds) - - def _drawbounds(self): - pass + + def __init__(self, possize, thickness = 1): + Widget.__init__(self, possize) + self._thickness = thickness + + def open(self): + self._calcbounds() + self.SetPort() + self.draw() + + def draw(self, visRgn = None): + if self._visible: + Qd.PaintRect(self._bounds) + + def _drawbounds(self): + pass class HorizontalLine(_Line): - - def _calcbounds(self): - Widget._calcbounds(self) - l, t, r, b = self._bounds - self._bounds = l, t, r, t + self._thickness + + def _calcbounds(self): + Widget._calcbounds(self) + l, t, r, b = self._bounds + self._bounds = l, t, r, t + self._thickness class VerticalLine(_Line): - - def _calcbounds(self): - Widget._calcbounds(self) - l, t, r, b = self._bounds - self._bounds = l, t, l + self._thickness, b + + def _calcbounds(self): + Widget._calcbounds(self) + l, t, r, b = self._bounds + self._bounds = l, t, l + self._thickness, b class Frame(Widget): - - def __init__(self, possize, pattern = Qd.GetQDGlobalsBlack(), color = (0, 0, 0)): - Widget.__init__(self, possize) - self._framepattern = pattern - self._framecolor = color - - def setcolor(self, color): - self._framecolor = color - self.SetPort() - self.draw() - - def setpattern(self, pattern): - self._framepattern = pattern - self.SetPort() - self.draw() - - def draw(self, visRgn = None): - if self._visible: - penstate = Qd.GetPenState() - Qd.PenPat(self._framepattern) - Qd.RGBForeColor(self._framecolor) - Qd.FrameRect(self._bounds) - Qd.RGBForeColor((0, 0, 0)) - Qd.SetPenState(penstate) + + def __init__(self, possize, pattern = Qd.GetQDGlobalsBlack(), color = (0, 0, 0)): + Widget.__init__(self, possize) + self._framepattern = pattern + self._framecolor = color + + def setcolor(self, color): + self._framecolor = color + self.SetPort() + self.draw() + + def setpattern(self, pattern): + self._framepattern = pattern + self.SetPort() + self.draw() + + def draw(self, visRgn = None): + if self._visible: + penstate = Qd.GetPenState() + Qd.PenPat(self._framepattern) + Qd.RGBForeColor(self._framecolor) + Qd.FrameRect(self._bounds) + Qd.RGBForeColor((0, 0, 0)) + Qd.SetPenState(penstate) def _darkencolor((r, g, b)): - return int(0.75 * r), int(0.75 * g), int(0.75 * b) + return int(0.75 * r), int(0.75 * g), int(0.75 * b) class BevelBox(Widget): - - """'Platinum' beveled rectangle.""" - - def __init__(self, possize, color = (0xe000, 0xe000, 0xe000)): - Widget.__init__(self, possize) - self._color = color - self._darkercolor = _darkencolor(color) - - def setcolor(self, color): - self._color = color - self.SetPort() - self.draw() - - def draw(self, visRgn = None): - if self._visible: - l, t, r, b = Qd.InsetRect(self._bounds, 1, 1) - Qd.RGBForeColor(self._color) - Qd.PaintRect((l, t, r, b)) - Qd.RGBForeColor(self._darkercolor) - Qd.MoveTo(l, b) - Qd.LineTo(r, b) - Qd.LineTo(r, t) - Qd.RGBForeColor((0, 0, 0)) + + """'Platinum' beveled rectangle.""" + + def __init__(self, possize, color = (0xe000, 0xe000, 0xe000)): + Widget.__init__(self, possize) + self._color = color + self._darkercolor = _darkencolor(color) + + def setcolor(self, color): + self._color = color + self.SetPort() + self.draw() + + def draw(self, visRgn = None): + if self._visible: + l, t, r, b = Qd.InsetRect(self._bounds, 1, 1) + Qd.RGBForeColor(self._color) + Qd.PaintRect((l, t, r, b)) + Qd.RGBForeColor(self._darkercolor) + Qd.MoveTo(l, b) + Qd.LineTo(r, b) + Qd.LineTo(r, t) + Qd.RGBForeColor((0, 0, 0)) class Group(Widget): - - """A container for subwidgets""" + + """A container for subwidgets""" class HorizontalPanes(Widget): - - """Panes, a.k.a. frames. Works a bit like a group. Devides the widget area into "panes", - which can be resized by the user by clicking and dragging between the subwidgets.""" - - _direction = 1 - - def __init__(self, possize, panesizes = None, gutter = 8): - """panesizes should be a tuple of numbers. The length of the tuple is the number of panes, - the items in the tuple are the relative sizes of these panes; these numbers should add up - to 1 (the total size of all panes).""" - Widget.__init__(self, possize) - self._panesizes = panesizes - self._gutter = gutter - self._enabled = 1 - self.setuppanes() - - #def open(self): - # self.installbounds() - # ClickableWidget.open(self) - - def _calcbounds(self): - # hmmm. It should not neccesary be override _calcbounds :-( - self.installbounds() - Widget._calcbounds(self) - - def setuppanes(self): - panesizes = self._panesizes - total = 0 - if panesizes is not None: - #if len(self._widgets) <> len(panesizes): - # raise TypeError, 'number of widgets does not match number of panes' - for panesize in panesizes: - if not 0 < panesize < 1: - raise TypeError, 'pane sizes must be between 0 and 1, not including.' - total = total + panesize - if round(total, 4) <> 1.0: - raise TypeError, 'pane sizes must add up to 1' - else: - # XXX does not work! - step = 1.0 / len(self._widgets) - panesizes = [] - for i in range(len(self._widgets)): - panesizes.append(step) - current = 0 - self._panesizes = [] - self._gutters = [] - for panesize in panesizes: - if current: - self._gutters.append(current) - self._panesizes.append((current, current + panesize)) - current = current + panesize - self.makepanebounds() - - def getpanesizes(self): - return map(lambda (fr, to): to-fr, self._panesizes) - - boundstemplate = "lambda width, height: (0, height * %s + %d, width, height * %s + %d)" - - def makepanebounds(self): - halfgutter = self._gutter / 2 - self._panebounds = [] - for i in range(len(self._panesizes)): - panestart, paneend = self._panesizes[i] - boundsstring = self.boundstemplate % (repr(panestart), panestart and halfgutter, - repr(paneend), (paneend <> 1.0) and -halfgutter) - self._panebounds.append(eval(boundsstring)) - - def installbounds(self): - #self.setuppanes() - for i in range(len(self._widgets)): - w = self._widgets[i] - w._possize = self._panebounds[i] - #if hasattr(w, "setuppanes"): - # w.setuppanes() - if hasattr(w, "installbounds"): - w.installbounds() - - def rollover(self, point, onoff): - if onoff: - orgmouse = point[self._direction] - halfgutter = self._gutter / 2 - l, t, r, b = self._bounds - if self._direction: - begin, end = t, b - else: - begin, end = l, r - - i = self.findgutter(orgmouse, begin, end) - if i is None: - SetCursor("arrow") - else: - SetCursor(self._direction and 'vmover' or 'hmover') - - def findgutter(self, orgmouse, begin, end): - tolerance = max(4, self._gutter) / 2 - for i in range(len(self._gutters)): - pos = begin + (end - begin) * self._gutters[i] - if abs(orgmouse - pos) <= tolerance: - break - else: - return - return i - - def click(self, point, modifiers): - # what a mess... - orgmouse = point[self._direction] - halfgutter = self._gutter / 2 - l, t, r, b = self._bounds - if self._direction: - begin, end = t, b - else: - begin, end = l, r - - i = self.findgutter(orgmouse, begin, end) - if i is None: - return - - pos = orgpos = begin + (end - begin) * self._gutters[i] # init pos too, for fast click on border, bug done by Petr - - minpos = self._panesizes[i][0] - maxpos = self._panesizes[i+1][1] - minpos = begin + (end - begin) * minpos + 64 - maxpos = begin + (end - begin) * maxpos - 64 - if minpos > orgpos and maxpos < orgpos: - return - - #SetCursor("fist") - self.SetPort() - if self._direction: - rect = l, orgpos - 1, r, orgpos - else: - rect = orgpos - 1, t, orgpos, b - - # track mouse --- XXX move to separate method? - Qd.PenMode(QuickDraw.srcXor) - Qd.PenPat(Qd.GetQDGlobalsGray()) - Qd.PaintRect(_intRect(rect)) - lastpos = None - while Evt.Button(): - pos = orgpos - orgmouse + Evt.GetMouse()[self._direction] - pos = max(pos, minpos) - pos = min(pos, maxpos) - if pos == lastpos: - continue - Qd.PenPat(Qd.GetQDGlobalsGray()) - Qd.PaintRect(_intRect(rect)) - if self._direction: - rect = l, pos - 1, r, pos - else: - rect = pos - 1, t, pos, b - Qd.PenPat(Qd.GetQDGlobalsGray()) - Qd.PaintRect(_intRect(rect)) - lastpos = pos - self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None) - Evt.WaitNextEvent(0, 3) - Qd.PaintRect(_intRect(rect)) - Qd.PenNormal() - SetCursor("watch") - - newpos = (pos - begin) / float(end - begin) - self._gutters[i] = newpos - self._panesizes[i] = self._panesizes[i][0], newpos - self._panesizes[i+1] = newpos, self._panesizes[i+1][1] - self.makepanebounds() - self.installbounds() - self._calcbounds() + + """Panes, a.k.a. frames. Works a bit like a group. Devides the widget area into "panes", + which can be resized by the user by clicking and dragging between the subwidgets.""" + + _direction = 1 + + def __init__(self, possize, panesizes = None, gutter = 8): + """panesizes should be a tuple of numbers. The length of the tuple is the number of panes, + the items in the tuple are the relative sizes of these panes; these numbers should add up + to 1 (the total size of all panes).""" + Widget.__init__(self, possize) + self._panesizes = panesizes + self._gutter = gutter + self._enabled = 1 + self.setuppanes() + + #def open(self): + # self.installbounds() + # ClickableWidget.open(self) + + def _calcbounds(self): + # hmmm. It should not neccesary be override _calcbounds :-( + self.installbounds() + Widget._calcbounds(self) + + def setuppanes(self): + panesizes = self._panesizes + total = 0 + if panesizes is not None: + #if len(self._widgets) <> len(panesizes): + # raise TypeError, 'number of widgets does not match number of panes' + for panesize in panesizes: + if not 0 < panesize < 1: + raise TypeError, 'pane sizes must be between 0 and 1, not including.' + total = total + panesize + if round(total, 4) <> 1.0: + raise TypeError, 'pane sizes must add up to 1' + else: + # XXX does not work! + step = 1.0 / len(self._widgets) + panesizes = [] + for i in range(len(self._widgets)): + panesizes.append(step) + current = 0 + self._panesizes = [] + self._gutters = [] + for panesize in panesizes: + if current: + self._gutters.append(current) + self._panesizes.append((current, current + panesize)) + current = current + panesize + self.makepanebounds() + + def getpanesizes(self): + return map(lambda (fr, to): to-fr, self._panesizes) + + boundstemplate = "lambda width, height: (0, height * %s + %d, width, height * %s + %d)" + + def makepanebounds(self): + halfgutter = self._gutter / 2 + self._panebounds = [] + for i in range(len(self._panesizes)): + panestart, paneend = self._panesizes[i] + boundsstring = self.boundstemplate % (repr(panestart), panestart and halfgutter, + repr(paneend), (paneend <> 1.0) and -halfgutter) + self._panebounds.append(eval(boundsstring)) + + def installbounds(self): + #self.setuppanes() + for i in range(len(self._widgets)): + w = self._widgets[i] + w._possize = self._panebounds[i] + #if hasattr(w, "setuppanes"): + # w.setuppanes() + if hasattr(w, "installbounds"): + w.installbounds() + + def rollover(self, point, onoff): + if onoff: + orgmouse = point[self._direction] + halfgutter = self._gutter / 2 + l, t, r, b = self._bounds + if self._direction: + begin, end = t, b + else: + begin, end = l, r + + i = self.findgutter(orgmouse, begin, end) + if i is None: + SetCursor("arrow") + else: + SetCursor(self._direction and 'vmover' or 'hmover') + + def findgutter(self, orgmouse, begin, end): + tolerance = max(4, self._gutter) / 2 + for i in range(len(self._gutters)): + pos = begin + (end - begin) * self._gutters[i] + if abs(orgmouse - pos) <= tolerance: + break + else: + return + return i + + def click(self, point, modifiers): + # what a mess... + orgmouse = point[self._direction] + halfgutter = self._gutter / 2 + l, t, r, b = self._bounds + if self._direction: + begin, end = t, b + else: + begin, end = l, r + + i = self.findgutter(orgmouse, begin, end) + if i is None: + return + + pos = orgpos = begin + (end - begin) * self._gutters[i] # init pos too, for fast click on border, bug done by Petr + + minpos = self._panesizes[i][0] + maxpos = self._panesizes[i+1][1] + minpos = begin + (end - begin) * minpos + 64 + maxpos = begin + (end - begin) * maxpos - 64 + if minpos > orgpos and maxpos < orgpos: + return + + #SetCursor("fist") + self.SetPort() + if self._direction: + rect = l, orgpos - 1, r, orgpos + else: + rect = orgpos - 1, t, orgpos, b + + # track mouse --- XXX move to separate method? + Qd.PenMode(QuickDraw.srcXor) + Qd.PenPat(Qd.GetQDGlobalsGray()) + Qd.PaintRect(_intRect(rect)) + lastpos = None + while Evt.Button(): + pos = orgpos - orgmouse + Evt.GetMouse()[self._direction] + pos = max(pos, minpos) + pos = min(pos, maxpos) + if pos == lastpos: + continue + Qd.PenPat(Qd.GetQDGlobalsGray()) + Qd.PaintRect(_intRect(rect)) + if self._direction: + rect = l, pos - 1, r, pos + else: + rect = pos - 1, t, pos, b + Qd.PenPat(Qd.GetQDGlobalsGray()) + Qd.PaintRect(_intRect(rect)) + lastpos = pos + self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None) + Evt.WaitNextEvent(0, 3) + Qd.PaintRect(_intRect(rect)) + Qd.PenNormal() + SetCursor("watch") + + newpos = (pos - begin) / float(end - begin) + self._gutters[i] = newpos + self._panesizes[i] = self._panesizes[i][0], newpos + self._panesizes[i+1] = newpos, self._panesizes[i+1][1] + self.makepanebounds() + self.installbounds() + self._calcbounds() class VerticalPanes(HorizontalPanes): - """see HorizontalPanes""" - _direction = 0 - boundstemplate = "lambda width, height: (width * %s + %d, 0, width * %s + %d, height)" + """see HorizontalPanes""" + _direction = 0 + boundstemplate = "lambda width, height: (width * %s + %d, 0, width * %s + %d, height)" class ColorPicker(ClickableWidget): - - """Color picker widget. Allows the user to choose a color.""" - - def __init__(self, possize, color = (0, 0, 0), callback = None): - ClickableWidget.__init__(self, possize) - self._color = color - self._callback = callback - self._enabled = 1 - - def click(self, point, modifiers): - if not self._enabled: - return - import ColorPicker - newcolor, ok = ColorPicker.GetColor("", self._color) - if ok: - self._color = newcolor - self.SetPort() - self.draw() - if self._callback: - return CallbackCall(self._callback, 0, self._color) - - def set(self, color): - self._color = color - self.SetPort() - self.draw() - - def get(self): - return self._color - - def draw(self, visRgn=None): - if self._visible: - if not visRgn: - visRgn = self._parentwindow.wid.GetWindowPort().visRgn - Qd.PenPat(Qd.GetQDGlobalsGray()) - rect = self._bounds - Qd.FrameRect(rect) - rect = Qd.InsetRect(rect, 3, 3) - Qd.PenNormal() - Qd.RGBForeColor(self._color) - Qd.PaintRect(rect) - Qd.RGBForeColor((0, 0, 0)) - + + """Color picker widget. Allows the user to choose a color.""" + + def __init__(self, possize, color = (0, 0, 0), callback = None): + ClickableWidget.__init__(self, possize) + self._color = color + self._callback = callback + self._enabled = 1 + + def click(self, point, modifiers): + if not self._enabled: + return + import ColorPicker + newcolor, ok = ColorPicker.GetColor("", self._color) + if ok: + self._color = newcolor + self.SetPort() + self.draw() + if self._callback: + return CallbackCall(self._callback, 0, self._color) + + def set(self, color): + self._color = color + self.SetPort() + self.draw() + + def get(self): + return self._color + + def draw(self, visRgn=None): + if self._visible: + if not visRgn: + visRgn = self._parentwindow.wid.GetWindowPort().visRgn + Qd.PenPat(Qd.GetQDGlobalsGray()) + rect = self._bounds + Qd.FrameRect(rect) + rect = Qd.InsetRect(rect, 3, 3) + Qd.PenNormal() + Qd.RGBForeColor(self._color) + Qd.PaintRect(rect) + Qd.RGBForeColor((0, 0, 0)) + # misc utils def CallbackCall(callback, mustfit, *args): - """internal helper routine for W""" - # XXX this function should die. - if type(callback) == FunctionType: - func = callback - maxargs = func.func_code.co_argcount - elif type(callback) == MethodType: - func = callback.im_func - maxargs = func.func_code.co_argcount - 1 - else: - if callable(callback): - return apply(callback, args) - else: - raise TypeError, "uncallable callback object" - - if func.func_defaults: - minargs = maxargs - len(func.func_defaults) - else: - minargs = maxargs - if minargs <= len(args) <= maxargs: - return apply(callback, args) - elif not mustfit and minargs == 0: - return callback() - else: - if mustfit: - raise TypeError, "callback accepts wrong number of arguments: %r" % len(args) - else: - raise TypeError, "callback accepts wrong number of arguments: 0 or %r" % len(args) + """internal helper routine for W""" + # XXX this function should die. + if type(callback) == FunctionType: + func = callback + maxargs = func.func_code.co_argcount + elif type(callback) == MethodType: + func = callback.im_func + maxargs = func.func_code.co_argcount - 1 + else: + if callable(callback): + return apply(callback, args) + else: + raise TypeError, "uncallable callback object" + + if func.func_defaults: + minargs = maxargs - len(func.func_defaults) + else: + minargs = maxargs + if minargs <= len(args) <= maxargs: + return apply(callback, args) + elif not mustfit and minargs == 0: + return callback() + else: + if mustfit: + raise TypeError, "callback accepts wrong number of arguments: %r" % len(args) + else: + raise TypeError, "callback accepts wrong number of arguments: 0 or %r" % len(args) def HasBaseClass(obj, class_): - try: - raise obj - except class_: - return 1 - except: - pass - return 0 + try: + raise obj + except class_: + return 1 + except: + pass + return 0 # # To remove the dependence of Widgets.rsrc we hardcode the cursor # data below. #_cursors = { -# "watch" : Qd.GetCursor(QuickDraw.watchCursor).data, -# "arrow" : Qd.GetQDGlobalsArrow(), -# "iBeam" : Qd.GetCursor(QuickDraw.iBeamCursor).data, -# "cross" : Qd.GetCursor(QuickDraw.crossCursor).data, -# "plus" : Qd.GetCursor(QuickDraw.plusCursor).data, -# "hand" : Qd.GetCursor(468).data, -# "fist" : Qd.GetCursor(469).data, -# "hmover" : Qd.GetCursor(470).data, -# "vmover" : Qd.GetCursor(471).data, -# "zoomin" : Qd.GetCursor(472).data, -# "zoomout" : Qd.GetCursor(473).data, -# "zoom" : Qd.GetCursor(474).data, +# "watch" : Qd.GetCursor(QuickDraw.watchCursor).data, +# "arrow" : Qd.GetQDGlobalsArrow(), +# "iBeam" : Qd.GetCursor(QuickDraw.iBeamCursor).data, +# "cross" : Qd.GetCursor(QuickDraw.crossCursor).data, +# "plus" : Qd.GetCursor(QuickDraw.plusCursor).data, +# "hand" : Qd.GetCursor(468).data, +# "fist" : Qd.GetCursor(469).data, +# "hmover" : Qd.GetCursor(470).data, +# "vmover" : Qd.GetCursor(471).data, +# "zoomin" : Qd.GetCursor(472).data, +# "zoomout" : Qd.GetCursor(473).data, +# "zoom" : Qd.GetCursor(474).data, #} _cursors = { - 'arrow': - '\x00\x00\x40\x00\x60\x00\x70\x00\x78\x00\x7c\x00\x7e\x00\x7f\x00' - '\x7f\x80\x7c\x00\x6c\x00\x46\x00\x06\x00\x03\x00\x03\x00\x00\x00' - '\xc0\x00\xe0\x00\xf0\x00\xf8\x00\xfc\x00\xfe\x00\xff\x00\xff\x80' - '\xff\xc0\xff\xe0\xfe\x00\xef\x00\xcf\x00\x87\x80\x07\x80\x03\x80' - '\x00\x01\x00\x01', - 'cross': - '\x04\x00\x04\x00\x04\x00\x04\x00\x04\x00\xff\xe0\x04\x00\x04\x00' - '\x04\x00\x04\x00\x04\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x05\x00\x05', - 'fist': - '\x00\x00\x00\x00\x0d\x80\x12\x70\x12\x4c\x12\x4a\x28\x0a\x28\x02' - '\x48\x02\x40\x02\x20\x02\x20\x04\x10\x04\x08\x08\x04\x08\x04\x08' - '\x00\x00\x00\x00\x0d\x80\x1f\xf0\x1f\xfc\x1f\xfe\x3f\xfe\x3f\xfe' - '\x7f\xfe\x7f\xfe\x3f\xfe\x3f\xfc\x1f\xfc\x0f\xf8\x07\xf8\x07\xf8' - '\x00\x09\x00\x08', - 'hand': - '\x01\x80\x1a\x70\x26\x48\x26\x4a\x12\x4d\x12\x49\x68\x09\x98\x01' - '\x88\x02\x40\x02\x20\x02\x20\x04\x10\x04\x08\x08\x04\x08\x04\x08' - '\x01\x80\x1b\xf0\x3f\xf8\x3f\xfa\x1f\xff\x1f\xff\x6f\xff\xff\xff' - '\xff\xfe\x7f\xfe\x3f\xfe\x3f\xfc\x1f\xfc\x0f\xf8\x07\xf8\x07\xf8' - '\x00\x09\x00\x08', - 'hmover': - '\x00\x00\x01\x80\x01\x80\x01\x80\x01\x80\x11\x88\x31\x8c\x7f\xfe' - '\x31\x8c\x11\x88\x01\x80\x01\x80\x01\x80\x01\x80\x00\x00\x00\x00' - '\x03\xc0\x03\xc0\x03\xc0\x03\xc0\x1b\xd8\x3b\xdc\x7f\xfe\xff\xff' - '\x7f\xfe\x3b\xdc\x1b\xd8\x03\xc0\x03\xc0\x03\xc0\x03\xc0\x00\x00' - '\x00\x07\x00\x07', - 'iBeam': - '\x0c\x60\x02\x80\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00' - '\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x02\x80\x0c\x60' - '\x0c\x60\x02\x80\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00' - '\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x02\x80\x0c\x60' - '\x00\x04\x00\x07', - 'plus': - '\x00\x00\x07\xc0\x04\x60\x04\x60\x04\x60\x7c\x7c\x43\x86\x42\x86' - '\x43\x86\x7c\x7e\x3c\x7e\x04\x60\x04\x60\x07\xe0\x03\xe0\x00\x00' - '\x0f\xc0\x0f\xe0\x0f\xf0\x0f\xf0\xff\xff\xff\xfe\xfc\x7f\xfc\x7f' - '\xfc\x7f\xff\xff\x7f\xff\x7f\xff\x0f\xf0\x0f\xf0\x07\xf0\x03\xe0' - '\x00\x08\x00\x08', - 'vmover': - '\x00\x00\x01\x00\x03\x80\x07\xc0\x01\x00\x01\x00\x01\x00\x7f\xfc' - '\x7f\xfc\x01\x00\x01\x00\x01\x00\x07\xc0\x03\x80\x01\x00\x00\x00' - '\x01\x00\x03\x80\x07\xc0\x0f\xe0\x0f\xe0\x03\x80\xff\xfe\xff\xfe' - '\xff\xfe\xff\xfe\x03\x80\x0f\xe0\x0f\xe0\x07\xc0\x03\x80\x01\x00' - '\x00\x07\x00\x07', - 'watch': - '\x3f\x00\x3f\x00\x3f\x00\x3f\x00\x40\x80\x84\x40\x84\x40\x84\x60' - '\x9c\x60\x80\x40\x80\x40\x40\x80\x3f\x00\x3f\x00\x3f\x00\x3f\x00' - '\x3f\x00\x3f\x00\x3f\x00\x3f\x00\x7f\x80\xff\xc0\xff\xc0\xff\xc0' - '\xff\xc0\xff\xc0\xff\xc0\x7f\x80\x3f\x00\x3f\x00\x3f\x00\x3f\x00' - '\x00\x08\x00\x08', - 'zoom': - '\x0f\x00\x30\xc0\x40\x20\x40\x20\x80\x10\x80\x10\x80\x10\x80\x10' - '\x40\x20\x40\x20\x30\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' - '\x0f\x00\x3f\xc0\x7f\xe0\x7f\xe0\xff\xf0\xff\xf0\xff\xf0\xff\xf0' - '\x7f\xe0\x7f\xe0\x3f\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' - '\x00\x06\x00\x06', - 'zoomin': - '\x0f\x00\x30\xc0\x40\x20\x46\x20\x86\x10\x9f\x90\x9f\x90\x86\x10' - '\x46\x20\x40\x20\x30\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' - '\x0f\x00\x3f\xc0\x7f\xe0\x7f\xe0\xff\xf0\xff\xf0\xff\xf0\xff\xf0' - '\x7f\xe0\x7f\xe0\x3f\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' - '\x00\x06\x00\x06', - 'zoomout': - '\x0f\x00\x30\xc0\x40\x20\x40\x20\x80\x10\x9f\x90\x9f\x90\x80\x10' - '\x40\x20\x40\x20\x30\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' - '\x0f\x00\x3f\xc0\x7f\xe0\x7f\xe0\xff\xf0\xff\xf0\xff\xf0\xff\xf0' - '\x7f\xe0\x7f\xe0\x3f\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' - '\x00\x06\x00\x06', + 'arrow': + '\x00\x00\x40\x00\x60\x00\x70\x00\x78\x00\x7c\x00\x7e\x00\x7f\x00' + '\x7f\x80\x7c\x00\x6c\x00\x46\x00\x06\x00\x03\x00\x03\x00\x00\x00' + '\xc0\x00\xe0\x00\xf0\x00\xf8\x00\xfc\x00\xfe\x00\xff\x00\xff\x80' + '\xff\xc0\xff\xe0\xfe\x00\xef\x00\xcf\x00\x87\x80\x07\x80\x03\x80' + '\x00\x01\x00\x01', + 'cross': + '\x04\x00\x04\x00\x04\x00\x04\x00\x04\x00\xff\xe0\x04\x00\x04\x00' + '\x04\x00\x04\x00\x04\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + '\x00\x05\x00\x05', + 'fist': + '\x00\x00\x00\x00\x0d\x80\x12\x70\x12\x4c\x12\x4a\x28\x0a\x28\x02' + '\x48\x02\x40\x02\x20\x02\x20\x04\x10\x04\x08\x08\x04\x08\x04\x08' + '\x00\x00\x00\x00\x0d\x80\x1f\xf0\x1f\xfc\x1f\xfe\x3f\xfe\x3f\xfe' + '\x7f\xfe\x7f\xfe\x3f\xfe\x3f\xfc\x1f\xfc\x0f\xf8\x07\xf8\x07\xf8' + '\x00\x09\x00\x08', + 'hand': + '\x01\x80\x1a\x70\x26\x48\x26\x4a\x12\x4d\x12\x49\x68\x09\x98\x01' + '\x88\x02\x40\x02\x20\x02\x20\x04\x10\x04\x08\x08\x04\x08\x04\x08' + '\x01\x80\x1b\xf0\x3f\xf8\x3f\xfa\x1f\xff\x1f\xff\x6f\xff\xff\xff' + '\xff\xfe\x7f\xfe\x3f\xfe\x3f\xfc\x1f\xfc\x0f\xf8\x07\xf8\x07\xf8' + '\x00\x09\x00\x08', + 'hmover': + '\x00\x00\x01\x80\x01\x80\x01\x80\x01\x80\x11\x88\x31\x8c\x7f\xfe' + '\x31\x8c\x11\x88\x01\x80\x01\x80\x01\x80\x01\x80\x00\x00\x00\x00' + '\x03\xc0\x03\xc0\x03\xc0\x03\xc0\x1b\xd8\x3b\xdc\x7f\xfe\xff\xff' + '\x7f\xfe\x3b\xdc\x1b\xd8\x03\xc0\x03\xc0\x03\xc0\x03\xc0\x00\x00' + '\x00\x07\x00\x07', + 'iBeam': + '\x0c\x60\x02\x80\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00' + '\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x02\x80\x0c\x60' + '\x0c\x60\x02\x80\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00' + '\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x02\x80\x0c\x60' + '\x00\x04\x00\x07', + 'plus': + '\x00\x00\x07\xc0\x04\x60\x04\x60\x04\x60\x7c\x7c\x43\x86\x42\x86' + '\x43\x86\x7c\x7e\x3c\x7e\x04\x60\x04\x60\x07\xe0\x03\xe0\x00\x00' + '\x0f\xc0\x0f\xe0\x0f\xf0\x0f\xf0\xff\xff\xff\xfe\xfc\x7f\xfc\x7f' + '\xfc\x7f\xff\xff\x7f\xff\x7f\xff\x0f\xf0\x0f\xf0\x07\xf0\x03\xe0' + '\x00\x08\x00\x08', + 'vmover': + '\x00\x00\x01\x00\x03\x80\x07\xc0\x01\x00\x01\x00\x01\x00\x7f\xfc' + '\x7f\xfc\x01\x00\x01\x00\x01\x00\x07\xc0\x03\x80\x01\x00\x00\x00' + '\x01\x00\x03\x80\x07\xc0\x0f\xe0\x0f\xe0\x03\x80\xff\xfe\xff\xfe' + '\xff\xfe\xff\xfe\x03\x80\x0f\xe0\x0f\xe0\x07\xc0\x03\x80\x01\x00' + '\x00\x07\x00\x07', + 'watch': + '\x3f\x00\x3f\x00\x3f\x00\x3f\x00\x40\x80\x84\x40\x84\x40\x84\x60' + '\x9c\x60\x80\x40\x80\x40\x40\x80\x3f\x00\x3f\x00\x3f\x00\x3f\x00' + '\x3f\x00\x3f\x00\x3f\x00\x3f\x00\x7f\x80\xff\xc0\xff\xc0\xff\xc0' + '\xff\xc0\xff\xc0\xff\xc0\x7f\x80\x3f\x00\x3f\x00\x3f\x00\x3f\x00' + '\x00\x08\x00\x08', + 'zoom': + '\x0f\x00\x30\xc0\x40\x20\x40\x20\x80\x10\x80\x10\x80\x10\x80\x10' + '\x40\x20\x40\x20\x30\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' + '\x0f\x00\x3f\xc0\x7f\xe0\x7f\xe0\xff\xf0\xff\xf0\xff\xf0\xff\xf0' + '\x7f\xe0\x7f\xe0\x3f\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' + '\x00\x06\x00\x06', + 'zoomin': + '\x0f\x00\x30\xc0\x40\x20\x46\x20\x86\x10\x9f\x90\x9f\x90\x86\x10' + '\x46\x20\x40\x20\x30\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' + '\x0f\x00\x3f\xc0\x7f\xe0\x7f\xe0\xff\xf0\xff\xf0\xff\xf0\xff\xf0' + '\x7f\xe0\x7f\xe0\x3f\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' + '\x00\x06\x00\x06', + 'zoomout': + '\x0f\x00\x30\xc0\x40\x20\x40\x20\x80\x10\x9f\x90\x9f\x90\x80\x10' + '\x40\x20\x40\x20\x30\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' + '\x0f\x00\x3f\xc0\x7f\xe0\x7f\xe0\xff\xf0\xff\xf0\xff\xf0\xff\xf0' + '\x7f\xe0\x7f\xe0\x3f\xf0\x0f\x38\x00\x1c\x00\x0e\x00\x07\x00\x02' + '\x00\x06\x00\x06', } def SetCursor(what): - """Set the cursorshape to any of these: 'arrow', 'cross', 'fist', 'hand', 'hmover', 'iBeam', - 'plus', 'vmover', 'watch', 'zoom', 'zoomin', 'zoomout'.""" - Qd.SetCursor(_cursors[what]) + """Set the cursorshape to any of these: 'arrow', 'cross', 'fist', 'hand', 'hmover', 'iBeam', + 'plus', 'vmover', 'watch', 'zoom', 'zoomin', 'zoomout'.""" + Qd.SetCursor(_cursors[what]) diff --git a/Mac/Tools/IDE/Wcontrols.py b/Mac/Tools/IDE/Wcontrols.py index 58fc31bf..00b06ac 100644 --- a/Mac/Tools/IDE/Wcontrols.py +++ b/Mac/Tools/IDE/Wcontrols.py @@ -4,430 +4,429 @@ import Wbase class ControlWidget(Wbase.ClickableWidget): - - """Baseclass for all native controls.""" - - def __init__(self, possize, title = "Control", procID = 0, callback = None, value = 0, min = 0, max = 1, viewsize = 0): - Wbase.ClickableWidget.__init__(self, possize) - self._control = None - self._title = title - self._callback = callback - self._procID = procID - self._value = value - self._min = min - self._max = max - self._enabled = 1 - self._viewsize = viewsize - - def open(self): - self._calcbounds() - - # NewControl doesn't accept 32-bit value, min, or max, so for consistency - # with the new 32-bit set/get methods, out-of-range values are initially - # set as zero, followed by a 32-bit set of the actual value. - # Values not representable in 16 bits will fail on MacOS 8.1, however - # the vast majority of control usage should still be compatible. - _value, _min, _max = self._value, self._min, self._max - if -32768 <= _value <= 32767: - bigvalue = None - else: - bigvalue = _value - _value = 0 - if -32768 <= _min <= 32767: - bigmin = None - else: - bigmin = _min - _min = 0 - if -32768 <= _max <= 32767: - bigmax = None - else: - bigmax = _max - _max = 0 - self._control = Ctl.NewControl(self._parentwindow.wid, - self._bounds, - self._title, - 1, - _value, - _min, - _max, - self._procID, - 0) - if bigvalue: - self._control.SetControl32BitValue(bigvalue) - if bigmin: - self._control.SetControl32BitMinimum(bigmin) - if bigmax: - self._control.SetControl32BitMaximum(bigmax) - if self._viewsize: - try: - self._control.SetControlViewSize(self._viewsize) - # Not available in MacOS 8.1, but that's OK since it only affects - # proportional scrollbars which weren't available in 8.1 either. - except NotImplementedError: - pass - self.enable(self._enabled) - - def adjust(self, oldbounds): - self.SetPort() - self._control.HideControl() - self._control.MoveControl(self._bounds[0], self._bounds[1]) - self._control.SizeControl(self._bounds[2] - self._bounds[0], self._bounds[3] - self._bounds[1]) - if self._visible: - Qd.EraseRect(self._bounds) - self._control.ShowControl() - self.GetWindow().ValidWindowRect(self._bounds) - - def close(self): - self._control.HideControl() - self._control = None - Wbase.ClickableWidget.close(self) - - def enable(self, onoff): - if self._control and self._enabled <> onoff: - self._control.HiliteControl((not onoff) and 255) - self._enabled = onoff - - def show(self, onoff): - self._visible = onoff - for w in self._widgets: - w.show(onoff) - if onoff: - self._control.ShowControl() - else: - self._control.HideControl() - - def activate(self, onoff): - self._activated = onoff - if self._enabled: - if onoff: - self._control.ActivateControl() - else: - self._control.DeactivateControl() - - def draw(self, visRgn = None): - if self._visible: - self._control.Draw1Control() - - def test(self, point): - if Qd.PtInRect(point, self._bounds) and self._enabled: - return 1 - #ctltype, control = Ctl.FindControl(point, self._parentwindow.wid) - #if self._enabled and control == self._control: - # return 1 - - def click(self, point, modifiers): - if not self._enabled: - return - part = self._control.TrackControl(point) - if part: - if self._callback: - Wbase.CallbackCall(self._callback, 0) - - def settitle(self, title): - if self._control: - self._control.SetControlTitle(title) - self._title = title - - def gettitle(self): - return self._title - - def set(self, value): - if self._control: - if -32768 <= value <= 32767: - # No 32-bit control support in MacOS 8.1, so use - # the 16-bit interface when possible. - self._control.SetControlValue(value) - else: - self._control.SetControl32BitValue(value) - else: - self._value = value - - def get(self): - if self._control: - try: - return self._control.GetControl32BitValue() - # No 32-bit control support in MacOS 8.1, so fall - # back to the 16-bit interface when needed. - except NotImplementedError: - return self._control.GetControlValue() - else: - return self._value + + """Baseclass for all native controls.""" + + def __init__(self, possize, title = "Control", procID = 0, callback = None, value = 0, min = 0, max = 1, viewsize = 0): + Wbase.ClickableWidget.__init__(self, possize) + self._control = None + self._title = title + self._callback = callback + self._procID = procID + self._value = value + self._min = min + self._max = max + self._enabled = 1 + self._viewsize = viewsize + + def open(self): + self._calcbounds() + + # NewControl doesn't accept 32-bit value, min, or max, so for consistency + # with the new 32-bit set/get methods, out-of-range values are initially + # set as zero, followed by a 32-bit set of the actual value. + # Values not representable in 16 bits will fail on MacOS 8.1, however + # the vast majority of control usage should still be compatible. + _value, _min, _max = self._value, self._min, self._max + if -32768 <= _value <= 32767: + bigvalue = None + else: + bigvalue = _value + _value = 0 + if -32768 <= _min <= 32767: + bigmin = None + else: + bigmin = _min + _min = 0 + if -32768 <= _max <= 32767: + bigmax = None + else: + bigmax = _max + _max = 0 + self._control = Ctl.NewControl(self._parentwindow.wid, + self._bounds, + self._title, + 1, + _value, + _min, + _max, + self._procID, + 0) + if bigvalue: + self._control.SetControl32BitValue(bigvalue) + if bigmin: + self._control.SetControl32BitMinimum(bigmin) + if bigmax: + self._control.SetControl32BitMaximum(bigmax) + if self._viewsize: + try: + self._control.SetControlViewSize(self._viewsize) + # Not available in MacOS 8.1, but that's OK since it only affects + # proportional scrollbars which weren't available in 8.1 either. + except NotImplementedError: + pass + self.enable(self._enabled) + + def adjust(self, oldbounds): + self.SetPort() + self._control.HideControl() + self._control.MoveControl(self._bounds[0], self._bounds[1]) + self._control.SizeControl(self._bounds[2] - self._bounds[0], self._bounds[3] - self._bounds[1]) + if self._visible: + Qd.EraseRect(self._bounds) + self._control.ShowControl() + self.GetWindow().ValidWindowRect(self._bounds) + + def close(self): + self._control.HideControl() + self._control = None + Wbase.ClickableWidget.close(self) + + def enable(self, onoff): + if self._control and self._enabled <> onoff: + self._control.HiliteControl((not onoff) and 255) + self._enabled = onoff + + def show(self, onoff): + self._visible = onoff + for w in self._widgets: + w.show(onoff) + if onoff: + self._control.ShowControl() + else: + self._control.HideControl() + + def activate(self, onoff): + self._activated = onoff + if self._enabled: + if onoff: + self._control.ActivateControl() + else: + self._control.DeactivateControl() + + def draw(self, visRgn = None): + if self._visible: + self._control.Draw1Control() + + def test(self, point): + if Qd.PtInRect(point, self._bounds) and self._enabled: + return 1 + #ctltype, control = Ctl.FindControl(point, self._parentwindow.wid) + #if self._enabled and control == self._control: + # return 1 + + def click(self, point, modifiers): + if not self._enabled: + return + part = self._control.TrackControl(point) + if part: + if self._callback: + Wbase.CallbackCall(self._callback, 0) + + def settitle(self, title): + if self._control: + self._control.SetControlTitle(title) + self._title = title + + def gettitle(self): + return self._title + + def set(self, value): + if self._control: + if -32768 <= value <= 32767: + # No 32-bit control support in MacOS 8.1, so use + # the 16-bit interface when possible. + self._control.SetControlValue(value) + else: + self._control.SetControl32BitValue(value) + else: + self._value = value + + def get(self): + if self._control: + try: + return self._control.GetControl32BitValue() + # No 32-bit control support in MacOS 8.1, so fall + # back to the 16-bit interface when needed. + except NotImplementedError: + return self._control.GetControlValue() + else: + return self._value class Button(ControlWidget): - - """Standard push button.""" - - procID = Controls.pushButProc | Controls.useWFont - - def __init__(self, possize, title = "Button", callback = None): - ControlWidget.__init__(self, possize, title, self.procID, callback, 0, 0, 1) - self._isdefault = 0 - - def push(self): - if not self._enabled: - return - # emulate the pushing of the button - import time - self._control.HiliteControl(Controls.kControlButtonPart) - self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None) # needed under OSX - time.sleep(0.1) - self._control.HiliteControl(0) - if self._callback: - Wbase.CallbackCall(self._callback, 0) - - def enable(self, onoff): - if self._control and self._enabled <> onoff: - self._control.HiliteControl((not onoff) and 255) - self._enabled = onoff - - def show(self, onoff): - ControlWidget.show(self, onoff) - - def draw(self, visRgn = None): - if self._visible: - self._control.Draw1Control() - - def open(self): - ControlWidget.open(self) - if self._isdefault: - self._setdefault(self._isdefault) - - def _setdefault(self, onoff): - c = self._control - if c is not None: - if onoff: - data = "\xFF" - else: - data = "\0" - # hide before changing state, otherwise the button isn't always - # redrawn correctly, although it's quite different under Aqua - # and Classic... - c.HideControl() - c.SetControlData(Controls.kControlNoPart, - Controls.kControlPushButtonDefaultTag, data) - c.ShowControl() - self._isdefault = onoff - - def adjust(self, oldbounds): - if self._isdefault: - old = Qd.InsetRect(oldbounds, -4, -4) - new = Qd.InsetRect(self._bounds, -4, -4) - Qd.EraseRect(old) - self.GetWindow().InvalWindowRect(old) - self.GetWindow().InvalWindowRect(new) - ControlWidget.adjust(self, oldbounds) + + """Standard push button.""" + + procID = Controls.pushButProc | Controls.useWFont + + def __init__(self, possize, title = "Button", callback = None): + ControlWidget.__init__(self, possize, title, self.procID, callback, 0, 0, 1) + self._isdefault = 0 + + def push(self): + if not self._enabled: + return + # emulate the pushing of the button + import time + self._control.HiliteControl(Controls.kControlButtonPart) + self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None) # needed under OSX + time.sleep(0.1) + self._control.HiliteControl(0) + if self._callback: + Wbase.CallbackCall(self._callback, 0) + + def enable(self, onoff): + if self._control and self._enabled <> onoff: + self._control.HiliteControl((not onoff) and 255) + self._enabled = onoff + + def show(self, onoff): + ControlWidget.show(self, onoff) + + def draw(self, visRgn = None): + if self._visible: + self._control.Draw1Control() + + def open(self): + ControlWidget.open(self) + if self._isdefault: + self._setdefault(self._isdefault) + + def _setdefault(self, onoff): + c = self._control + if c is not None: + if onoff: + data = "\xFF" + else: + data = "\0" + # hide before changing state, otherwise the button isn't always + # redrawn correctly, although it's quite different under Aqua + # and Classic... + c.HideControl() + c.SetControlData(Controls.kControlNoPart, + Controls.kControlPushButtonDefaultTag, data) + c.ShowControl() + self._isdefault = onoff + + def adjust(self, oldbounds): + if self._isdefault: + old = Qd.InsetRect(oldbounds, -4, -4) + new = Qd.InsetRect(self._bounds, -4, -4) + Qd.EraseRect(old) + self.GetWindow().InvalWindowRect(old) + self.GetWindow().InvalWindowRect(new) + ControlWidget.adjust(self, oldbounds) class BevelButton(Button): - procID = Controls.kControlBevelButtonNormalBevelProc | Controls.useWFont + procID = Controls.kControlBevelButtonNormalBevelProc | Controls.useWFont class CheckBox(ControlWidget): - - """Standard checkbox.""" - - def __init__(self, possize, title = "Checkbox", callback = None, value = 0): - procID = Controls.checkBoxProc | Controls.useWFont - ControlWidget.__init__(self, possize, title, procID, callback, value, 0, 1) - - def click(self, point, modifiers): - if not self._enabled: - return - part = self._control.TrackControl(point) - if part: - self.toggle() - if self._callback: - Wbase.CallbackCall(self._callback, 0, self.get()) - - def push(self): - if not self._enabled: - return - self.toggle() - if self._callback: - Wbase.CallbackCall(self._callback, 0, self.get()) - - def toggle(self): - self.set(not self.get()) + + """Standard checkbox.""" + + def __init__(self, possize, title = "Checkbox", callback = None, value = 0): + procID = Controls.checkBoxProc | Controls.useWFont + ControlWidget.__init__(self, possize, title, procID, callback, value, 0, 1) + + def click(self, point, modifiers): + if not self._enabled: + return + part = self._control.TrackControl(point) + if part: + self.toggle() + if self._callback: + Wbase.CallbackCall(self._callback, 0, self.get()) + + def push(self): + if not self._enabled: + return + self.toggle() + if self._callback: + Wbase.CallbackCall(self._callback, 0, self.get()) + + def toggle(self): + self.set(not self.get()) class RadioButton(ControlWidget): - - """Standard radiobutton.""" - - # XXX We need a radiogroup widget; this is too kludgy. - - def __init__(self, possize, title, thebuttons, callback = None, value = 0): - procID = Controls.radioButProc | Controls.useWFont - ControlWidget.__init__(self, possize, title, procID, callback, value, 0, 1) - self.thebuttons = thebuttons - thebuttons.append(self) - - def close(self): - self.thebuttons = None - ControlWidget.close(self) - - def click(self, point, modifiers): - if not self._enabled: - return - part = self._control.TrackControl(point) - if part: - self.set(1) - if self._callback: - Wbase.CallbackCall(self._callback, 0, 1) - - def push(self): - if not self._enabled: - return - self.set(1) - if self._callback: - Wbase.CallbackCall(self._callback, 0, 1) - - def set(self, value): - for button in self.thebuttons: - if button._control: - button._control.SetControlValue(button == self) - else: - button._value = (button == self) + + """Standard radiobutton.""" + + # XXX We need a radiogroup widget; this is too kludgy. + + def __init__(self, possize, title, thebuttons, callback = None, value = 0): + procID = Controls.radioButProc | Controls.useWFont + ControlWidget.__init__(self, possize, title, procID, callback, value, 0, 1) + self.thebuttons = thebuttons + thebuttons.append(self) + + def close(self): + self.thebuttons = None + ControlWidget.close(self) + + def click(self, point, modifiers): + if not self._enabled: + return + part = self._control.TrackControl(point) + if part: + self.set(1) + if self._callback: + Wbase.CallbackCall(self._callback, 0, 1) + + def push(self): + if not self._enabled: + return + self.set(1) + if self._callback: + Wbase.CallbackCall(self._callback, 0, 1) + + def set(self, value): + for button in self.thebuttons: + if button._control: + button._control.SetControlValue(button == self) + else: + button._value = (button == self) class Scrollbar(ControlWidget): - - """Standard scrollbar.""" - - def __init__(self, possize, callback=None, value=0, min=0, max=0, livefeedback=1): - if livefeedback: - procID = Controls.kControlScrollBarLiveProc - else: - procID = Controls.scrollBarProc - ControlWidget.__init__(self, possize, "", procID, callback, value, min, max) - - # interface -# def set(self, value): -# if self._callback: -# Wbase.CallbackCall(self._callback, 1, value) - - def up(self): - if self._callback: - Wbase.CallbackCall(self._callback, 1, '+') - - def down(self): - if self._callback: - Wbase.CallbackCall(self._callback, 1, '-') - - def pageup(self): - if self._callback: - Wbase.CallbackCall(self._callback, 1, '++') - - def pagedown(self): - if self._callback: - Wbase.CallbackCall(self._callback, 1, '--') - - def setmin(self, min): - if self._control is not None: - if -32768 <= min <= 32767: - # No 32-bit control support in MacOS 8.1, so use - # the 16-bit interface when possible. - self._control.SetControlMinimum(min) - else: - self._control.SetControl32BitMinimum(min) - else: - self._min = min - - def setmax(self, max): - if self._control is not None: - if -32768 <= max <= 32767: - # No 32-bit control support in MacOS 8.1, so use - # the 16-bit interface when possible. - self._control.SetControlMaximum(max) - else: - self._control.SetControl32BitMaximum(max) - else: - self._max = max - - def setviewsize(self, viewsize): - if self._control is not None: - try: - self._control.SetControlViewSize(viewsize) - # Not available in MacOS 8.1, but that's OK since it only affects - # proportional scrollbars which weren't available in 8.1 either. - except NotImplementedError: - pass - else: - self._viewsize = viewsize - - def getmin(self): - try: - return self._control.GetControl32BitMinimum() - # No 32-bit control support in MacOS 8.1, so fall - # back to the 16-bit interface when needed. - except NotImplementedError: - return self._control.GetControlMinimum() - - def getmax(self): - try: - return self._control.GetControl32BitMaximum() - # No 32-bit control support in MacOS 8.1, so fall - # back to the 16-bit interface when needed. - except NotImplementedError: - return self._control.GetControlMaximum() - - # internals - def click(self, point, modifiers): - if not self._enabled: - return - def hitter(ctl, part, self=self): - if part: - self._hit(part) - part = self._control.TrackControl(point, hitter) - - def _hit(self, part): - value = None - if part == Controls.inThumb: - try: - value = self._control.GetControl32BitValue() - # No 32-bit control support in MacOS 8.1, so fall - # back to the 16-bit interface when needed. - except NotImplementedError: - value = self._control.GetControlValue() - elif part == Controls.inUpButton: - value = "+" - elif part == Controls.inDownButton: - value = "-" - elif part == Controls.inPageUp: - value = "++" - elif part == Controls.inPageDown: - value = "--" - if value is not None and self._callback: - Wbase.CallbackCall(self._callback, 1, value) - - def draw(self, visRgn = None): - if self._visible: - self._control.Draw1Control() - #Qd.FrameRect(self._bounds) - - def adjust(self, oldbounds): - self.SetPort() - self.GetWindow().InvalWindowRect(oldbounds) - self._control.HideControl() - self._control.MoveControl(self._bounds[0], self._bounds[1]) - self._control.SizeControl(self._bounds[2] - self._bounds[0], self._bounds[3] - self._bounds[1]) - if self._visible: - Qd.EraseRect(self._bounds) - if self._activated: - self._control.ShowControl() - else: - Qd.FrameRect(self._bounds) - self.GetWindow().ValidWindowRect(self._bounds) + """Standard scrollbar.""" -def _scalebarvalue(absmin, absmax, curmin, curmax): - if curmin <= absmin and curmax >= absmax: - return None - if curmin <= absmin: - return 0 - if curmax >= absmax: - return 32767 - perc = float(curmin-absmin) / float((absmax - absmin) - (curmax - curmin)) - return int(perc*32767) + def __init__(self, possize, callback=None, value=0, min=0, max=0, livefeedback=1): + if livefeedback: + procID = Controls.kControlScrollBarLiveProc + else: + procID = Controls.scrollBarProc + ControlWidget.__init__(self, possize, "", procID, callback, value, min, max) + + # interface +# def set(self, value): +# if self._callback: +# Wbase.CallbackCall(self._callback, 1, value) + + def up(self): + if self._callback: + Wbase.CallbackCall(self._callback, 1, '+') + + def down(self): + if self._callback: + Wbase.CallbackCall(self._callback, 1, '-') + def pageup(self): + if self._callback: + Wbase.CallbackCall(self._callback, 1, '++') + + def pagedown(self): + if self._callback: + Wbase.CallbackCall(self._callback, 1, '--') + + def setmin(self, min): + if self._control is not None: + if -32768 <= min <= 32767: + # No 32-bit control support in MacOS 8.1, so use + # the 16-bit interface when possible. + self._control.SetControlMinimum(min) + else: + self._control.SetControl32BitMinimum(min) + else: + self._min = min + + def setmax(self, max): + if self._control is not None: + if -32768 <= max <= 32767: + # No 32-bit control support in MacOS 8.1, so use + # the 16-bit interface when possible. + self._control.SetControlMaximum(max) + else: + self._control.SetControl32BitMaximum(max) + else: + self._max = max + + def setviewsize(self, viewsize): + if self._control is not None: + try: + self._control.SetControlViewSize(viewsize) + # Not available in MacOS 8.1, but that's OK since it only affects + # proportional scrollbars which weren't available in 8.1 either. + except NotImplementedError: + pass + else: + self._viewsize = viewsize + + def getmin(self): + try: + return self._control.GetControl32BitMinimum() + # No 32-bit control support in MacOS 8.1, so fall + # back to the 16-bit interface when needed. + except NotImplementedError: + return self._control.GetControlMinimum() + + def getmax(self): + try: + return self._control.GetControl32BitMaximum() + # No 32-bit control support in MacOS 8.1, so fall + # back to the 16-bit interface when needed. + except NotImplementedError: + return self._control.GetControlMaximum() + + # internals + def click(self, point, modifiers): + if not self._enabled: + return + def hitter(ctl, part, self=self): + if part: + self._hit(part) + part = self._control.TrackControl(point, hitter) + + def _hit(self, part): + value = None + if part == Controls.inThumb: + try: + value = self._control.GetControl32BitValue() + # No 32-bit control support in MacOS 8.1, so fall + # back to the 16-bit interface when needed. + except NotImplementedError: + value = self._control.GetControlValue() + elif part == Controls.inUpButton: + value = "+" + elif part == Controls.inDownButton: + value = "-" + elif part == Controls.inPageUp: + value = "++" + elif part == Controls.inPageDown: + value = "--" + if value is not None and self._callback: + Wbase.CallbackCall(self._callback, 1, value) + + def draw(self, visRgn = None): + if self._visible: + self._control.Draw1Control() + #Qd.FrameRect(self._bounds) + + def adjust(self, oldbounds): + self.SetPort() + self.GetWindow().InvalWindowRect(oldbounds) + self._control.HideControl() + self._control.MoveControl(self._bounds[0], self._bounds[1]) + self._control.SizeControl(self._bounds[2] - self._bounds[0], self._bounds[3] - self._bounds[1]) + if self._visible: + Qd.EraseRect(self._bounds) + if self._activated: + self._control.ShowControl() + else: + Qd.FrameRect(self._bounds) + self.GetWindow().ValidWindowRect(self._bounds) + + +def _scalebarvalue(absmin, absmax, curmin, curmax): + if curmin <= absmin and curmax >= absmax: + return None + if curmin <= absmin: + return 0 + if curmax >= absmax: + return 32767 + perc = float(curmin-absmin) / float((absmax - absmin) - (curmax - curmin)) + return int(perc*32767) diff --git a/Mac/Tools/IDE/Wkeys.py b/Mac/Tools/IDE/Wkeys.py index 876f02f..9bc4522 100644 --- a/Mac/Tools/IDE/Wkeys.py +++ b/Mac/Tools/IDE/Wkeys.py @@ -1,45 +1,45 @@ -spacekey = ' ' -returnkey = '\r' -tabkey = '\t' -enterkey = '\003' -backspacekey = '\010' -deletekey = '\177' -clearkey = '\033' -helpkey = '\005' +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] +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] +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' + "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 + keynames[v] = k del k, v diff --git a/Mac/Tools/IDE/Wlists.py b/Mac/Tools/IDE/Wlists.py index 1b66a8b..9aeb7c4 100644 --- a/Mac/Tools/IDE/Wlists.py +++ b/Mac/Tools/IDE/Wlists.py @@ -10,573 +10,572 @@ from Carbon.Appearance import kThemeStateActive, kThemeStateInactive, kThemeStat class List(Wbase.SelectableWidget): - - """Standard list widget.""" - - LDEF_ID = 0 - - def __init__(self, possize, items = None, callback = None, flags = 0, cols = 1, typingcasesens=0): - if items is None: - items = [] - self.items = items - Wbase.SelectableWidget.__init__(self, possize) - self._selected = 0 - self._enabled = 1 - self._list = None - self._cols = cols - self._callback = callback - self._flags = flags - self.typingcasesens = typingcasesens - self.lasttyping = "" - self.lasttime = Evt.TickCount() - self.timelimit = 30 - self.setitems(items) - self.drawingmode = 0 - - def open(self): - self.setdrawingmode(0) - self.createlist() - self.setdrawingmode(1) - - def createlist(self): - self._calcbounds() - self.SetPort() - rect = self._bounds - rect = rect[0]+1, rect[1]+1, rect[2]-16, rect[3]-1 - self._viewbounds = rect - self._list = LNew(rect, (0, 0, self._cols, 0), (0, 0), self.LDEF_ID, self._parentwindow.wid, - 0, 1, 0, 1) - if self.drawingmode: - self._list.LSetDrawingMode(0) - self._list.selFlags = self._flags - self.setitems(self.items) - if hasattr(self, "_sel"): - self.setselection(self._sel) - del self._sel - - def adjust(self, oldbounds): - self.SetPort() - # Appearance frames are drawn outside the specified bounds, - # so we always need to outset the invalidated area. - self.GetWindow().InvalWindowRect(Qd.InsetRect(oldbounds, -3, -3)) - self.GetWindow().InvalWindowRect(Qd.InsetRect(self._bounds, -3, -3)) - - if oldbounds[:2] == self._bounds[:2]: - # set visRgn to empty, to prevent nasty drawing side effect of LSize() - Qd.RectRgn(self._parentwindow.wid.GetWindowPort().visRgn, (0, 0, 0, 0)) - # list still has the same upper/left coordinates, use LSize - l, t, r, b = self._bounds - width = r - l - 17 - height = b - t - 2 - vl, vt, vr, vb = self._viewbounds - self._viewbounds = vl, vt, vl + width, vt + height - self._list.LSize(width, height) - # now *why* doesn't the list manager recalc the cellrect??? - l, t, r, b = self._list.LRect((0,0)) - cellheight = b - t - self._list.LCellSize((width/self._cols, cellheight)) - # reset visRgn - self._parentwindow.wid.CalcVis() - else: - # oh well, since the list manager doesn't have a LMove call, - # we have to make the list all over again... - sel = self.getselection() - topcell = self.gettopcell() - self._list = None - self.setdrawingmode(0) - self.createlist() - self.setselection(sel) - self.settopcell(topcell) - self.setdrawingmode(1) - - def close(self): - self._list = None - self._callback = None - self.items = [] - Wbase.SelectableWidget.close(self) - - def set(self, items): - self.setitems(items) - - def setitems(self, items): - self.items = items - the_list = self._list - if not self._parent or not self._list: - return - self.setdrawingmode(0) - topcell = self.gettopcell() - the_list.LDelRow(0, 1) - the_list.LAddRow(len(self.items), 0) - self_itemrepr = self.itemrepr - set_cell = the_list.LSetCell - for i in range(len(items)): - set_cell(self_itemrepr(items[i]), (0, i)) - self.settopcell(topcell) - self.setdrawingmode(1) - - def click(self, point, modifiers): - if not self._enabled: - return - isdoubleclick = self._list.LClick(point, modifiers) - if self._callback: - Wbase.CallbackCall(self._callback, 0, isdoubleclick) - return 1 - - def key(self, char, event): - (what, message, when, where, modifiers) = event - sel = self.getselection() - newselection = [] - if char == Wkeys.uparrowkey: - if len(sel) >= 1 and min(sel) > 0: - newselection = [min(sel) - 1] - else: - newselection = [0] - elif char == Wkeys.downarrowkey: - if len(sel) >= 1 and max(sel) < (len(self.items) - 1): - newselection = [max(sel) + 1] - else: - newselection = [len(self.items) - 1] - else: - modifiers = 0 - if (self.lasttime + self.timelimit) < Evt.TickCount(): - self.lasttyping = "" - if self.typingcasesens: - self.lasttyping = self.lasttyping + char - else: - self.lasttyping = self.lasttyping + string.lower(char) - self.lasttime = Evt.TickCount() - i = self.findmatch(self.lasttyping) - newselection = [i] - if modifiers & Events.shiftKey and not self._list.selFlags & Lists.lOnlyOne: - newselection = newselection + sel - self.setselection(newselection) - self._list.LAutoScroll() - self.click((-1, -1), 0) - - def findmatch(self, tag): - lower = string.lower - items = self.items - typingcasesens = self.typingcasesens - taglen = len(tag) - match = '\377' * 100 - match_i = -1 - for i in range(len(items)): - item = str(items[i]) - if not typingcasesens: - item = lower(item) - if tag <= item < match: - match = item - match_i = i - if match_i >= 0: - return match_i - else: - return len(items) - 1 - - def domenu_copy(self, *args): - sel = self.getselection() - selitems = [] - for i in sel: - selitems.append(str(self.items[i])) - text = string.join(selitems, '\r') - if text: - if hasattr(Scrap, 'PutScrap'): - Scrap.ZeroScrap() - Scrap.PutScrap('TEXT', text) - else: - Scrap.ClearCurrentScrap() - sc = Scrap.GetCurrentScrap() - sc.PutScrapFlavor('TEXT', 0, text) - - def can_copy(self, *args): - return len(self.getselection()) <> 0 - - def domenu_selectall(self, *args): - self.selectall() - - def can_selectall(self, *args): - return not self._list.selFlags & Lists.lOnlyOne - - def selectall(self): - if not self._list.selFlags & Lists.lOnlyOne: - self.setselection(range(len(self.items))) - self._list.LAutoScroll() - self.click((-1, -1), 0) - - def getselection(self): - if not self._parent or not self._list: - if hasattr(self, "_sel"): - return self._sel - return [] - items = [] - point = (0,0) - while 1: - ok, point = self._list.LGetSelect(1, point) - if not ok: - break - items.append(point[1]) - point = point[0], point[1]+1 - return items - - def setselection(self, selection): - if not self._parent or not self._list: - self._sel = selection - return - set_sel = self._list.LSetSelect - for i in range(len(self.items)): - if i in selection: - set_sel(1, (0, i)) - else: - set_sel(0, (0, i)) - self._list.LAutoScroll() - - def getselectedobjects(self): - sel = self.getselection() - objects = [] - for i in sel: - objects.append(self.items[i]) - return objects - - def setselectedobjects(self, objects): - sel = [] - for o in objects: - try: - sel.append(self.items.index(o)) - except: - pass - self.setselection(sel) - - def gettopcell(self): - l, t, r, b = self._bounds - t = t + 1 - cl, ct, cr, cb = self._list.LRect((0, 0)) - cellheight = cb - ct - return (t - ct) / cellheight - - def settopcell(self, topcell): - top = self.gettopcell() - diff = topcell - top - self._list.LScroll(0, diff) - - def draw(self, visRgn = None): - if self._visible: - if not visRgn: - visRgn = self._parentwindow.wid.GetWindowPort().visRgn - self._list.LUpdate(visRgn) - state = [kThemeStateActive, kThemeStateInactive][not self._activated] - App.DrawThemeListBoxFrame(Qd.InsetRect(self._bounds, 1, 1), state) - if self._selected and self._activated: - self.drawselframe(1) - - def select(self, onoff, isclick = 0): - if Wbase.SelectableWidget.select(self, onoff): - return - self.SetPort() - self.drawselframe(onoff) - - def activate(self, onoff): - self._activated = onoff - if self._visible: - self._list.LActivate(onoff) - #state = [kThemeStateActive, kThemeStateInactive][not onoff] - #App.DrawThemeListBoxFrame(Qd.InsetRect(self._bounds, 1, 1), state) - if self._selected: - self.drawselframe(onoff) - - def get(self): - return self.items - - def itemrepr(self, item): - return str(item)[:255] - - def __getitem__(self, index): - return self.items[index] - - def __setitem__(self, index, item): - if self._parent and self._list: - self._list.LSetCell(self.itemrepr(item), (0, index)) - self.items[index] = item - - def __delitem__(self, index): - if self._parent and self._list: - self._list.LDelRow(1, index) - del self.items[index] - - def __getslice__(self, a, b): - return self.items[a:b] - - def __delslice__(self, a, b): - if b-a: - if self._parent and self._list: - self._list.LDelRow(b-a, a) - del self.items[a:b] - - def __setslice__(self, a, b, items): - if self._parent and self._list: - l = len(items) - the_list = self._list - self.setdrawingmode(0) - if b-a: - if b > len(self.items): - # fix for new 1.5 "feature" where b is sys.maxint instead of len(self)... - # LDelRow doesn't like maxint. - b = len(self.items) - the_list.LDelRow(b-a, a) - the_list.LAddRow(l, a) - self_itemrepr = self.itemrepr - set_cell = the_list.LSetCell - for i in range(len(items)): - set_cell(self_itemrepr(items[i]), (0, i + a)) - self.items[a:b] = items - self.setdrawingmode(1) - else: - self.items[a:b] = items - - def __len__(self): - return len(self.items) - - def append(self, item): - if self._parent and self._list: - index = len(self.items) - self._list.LAddRow(1, index) - self._list.LSetCell(self.itemrepr(item), (0, index)) - self.items.append(item) - - def remove(self, item): - index = self.items.index(item) - self.__delitem__(index) - - def index(self, item): - return self.items.index(item) - - def insert(self, index, item): - if index < 0: - index = 0 - if self._parent and self._list: - self._list.LAddRow(1, index) - self._list.LSetCell(self.itemrepr(item), (0, index)) - self.items.insert(index, item) - - def setdrawingmode(self, onoff): - if onoff: - self.drawingmode = self.drawingmode - 1 - if self.drawingmode == 0 and self._list is not None: - self._list.LSetDrawingMode(1) - if self._visible: - bounds = l, t, r, b = Qd.InsetRect(self._bounds, 1, 1) - cl, ct, cr, cb = self._list.LRect((0, len(self.items)-1)) - if cb < b: - self.SetPort() - Qd.EraseRect((l, cb, cr, b)) - self._list.LUpdate(self._parentwindow.wid.GetWindowPort().visRgn) - self.GetWindow().ValidWindowRect(bounds) - else: - if self.drawingmode == 0 and self._list is not None: - self._list.LSetDrawingMode(0) - self.drawingmode = self.drawingmode + 1 + + """Standard list widget.""" + + LDEF_ID = 0 + + def __init__(self, possize, items = None, callback = None, flags = 0, cols = 1, typingcasesens=0): + if items is None: + items = [] + self.items = items + Wbase.SelectableWidget.__init__(self, possize) + self._selected = 0 + self._enabled = 1 + self._list = None + self._cols = cols + self._callback = callback + self._flags = flags + self.typingcasesens = typingcasesens + self.lasttyping = "" + self.lasttime = Evt.TickCount() + self.timelimit = 30 + self.setitems(items) + self.drawingmode = 0 + + def open(self): + self.setdrawingmode(0) + self.createlist() + self.setdrawingmode(1) + + def createlist(self): + self._calcbounds() + self.SetPort() + rect = self._bounds + rect = rect[0]+1, rect[1]+1, rect[2]-16, rect[3]-1 + self._viewbounds = rect + self._list = LNew(rect, (0, 0, self._cols, 0), (0, 0), self.LDEF_ID, self._parentwindow.wid, + 0, 1, 0, 1) + if self.drawingmode: + self._list.LSetDrawingMode(0) + self._list.selFlags = self._flags + self.setitems(self.items) + if hasattr(self, "_sel"): + self.setselection(self._sel) + del self._sel + + def adjust(self, oldbounds): + self.SetPort() + # Appearance frames are drawn outside the specified bounds, + # so we always need to outset the invalidated area. + self.GetWindow().InvalWindowRect(Qd.InsetRect(oldbounds, -3, -3)) + self.GetWindow().InvalWindowRect(Qd.InsetRect(self._bounds, -3, -3)) + + if oldbounds[:2] == self._bounds[:2]: + # set visRgn to empty, to prevent nasty drawing side effect of LSize() + Qd.RectRgn(self._parentwindow.wid.GetWindowPort().visRgn, (0, 0, 0, 0)) + # list still has the same upper/left coordinates, use LSize + l, t, r, b = self._bounds + width = r - l - 17 + height = b - t - 2 + vl, vt, vr, vb = self._viewbounds + self._viewbounds = vl, vt, vl + width, vt + height + self._list.LSize(width, height) + # now *why* doesn't the list manager recalc the cellrect??? + l, t, r, b = self._list.LRect((0,0)) + cellheight = b - t + self._list.LCellSize((width/self._cols, cellheight)) + # reset visRgn + self._parentwindow.wid.CalcVis() + else: + # oh well, since the list manager doesn't have a LMove call, + # we have to make the list all over again... + sel = self.getselection() + topcell = self.gettopcell() + self._list = None + self.setdrawingmode(0) + self.createlist() + self.setselection(sel) + self.settopcell(topcell) + self.setdrawingmode(1) + + def close(self): + self._list = None + self._callback = None + self.items = [] + Wbase.SelectableWidget.close(self) + + def set(self, items): + self.setitems(items) + + def setitems(self, items): + self.items = items + the_list = self._list + if not self._parent or not self._list: + return + self.setdrawingmode(0) + topcell = self.gettopcell() + the_list.LDelRow(0, 1) + the_list.LAddRow(len(self.items), 0) + self_itemrepr = self.itemrepr + set_cell = the_list.LSetCell + for i in range(len(items)): + set_cell(self_itemrepr(items[i]), (0, i)) + self.settopcell(topcell) + self.setdrawingmode(1) + + def click(self, point, modifiers): + if not self._enabled: + return + isdoubleclick = self._list.LClick(point, modifiers) + if self._callback: + Wbase.CallbackCall(self._callback, 0, isdoubleclick) + return 1 + + def key(self, char, event): + (what, message, when, where, modifiers) = event + sel = self.getselection() + newselection = [] + if char == Wkeys.uparrowkey: + if len(sel) >= 1 and min(sel) > 0: + newselection = [min(sel) - 1] + else: + newselection = [0] + elif char == Wkeys.downarrowkey: + if len(sel) >= 1 and max(sel) < (len(self.items) - 1): + newselection = [max(sel) + 1] + else: + newselection = [len(self.items) - 1] + else: + modifiers = 0 + if (self.lasttime + self.timelimit) < Evt.TickCount(): + self.lasttyping = "" + if self.typingcasesens: + self.lasttyping = self.lasttyping + char + else: + self.lasttyping = self.lasttyping + string.lower(char) + self.lasttime = Evt.TickCount() + i = self.findmatch(self.lasttyping) + newselection = [i] + if modifiers & Events.shiftKey and not self._list.selFlags & Lists.lOnlyOne: + newselection = newselection + sel + self.setselection(newselection) + self._list.LAutoScroll() + self.click((-1, -1), 0) + + def findmatch(self, tag): + lower = string.lower + items = self.items + typingcasesens = self.typingcasesens + taglen = len(tag) + match = '\377' * 100 + match_i = -1 + for i in range(len(items)): + item = str(items[i]) + if not typingcasesens: + item = lower(item) + if tag <= item < match: + match = item + match_i = i + if match_i >= 0: + return match_i + else: + return len(items) - 1 + + def domenu_copy(self, *args): + sel = self.getselection() + selitems = [] + for i in sel: + selitems.append(str(self.items[i])) + text = string.join(selitems, '\r') + if text: + if hasattr(Scrap, 'PutScrap'): + Scrap.ZeroScrap() + Scrap.PutScrap('TEXT', text) + else: + Scrap.ClearCurrentScrap() + sc = Scrap.GetCurrentScrap() + sc.PutScrapFlavor('TEXT', 0, text) + + def can_copy(self, *args): + return len(self.getselection()) <> 0 + + def domenu_selectall(self, *args): + self.selectall() + + def can_selectall(self, *args): + return not self._list.selFlags & Lists.lOnlyOne + + def selectall(self): + if not self._list.selFlags & Lists.lOnlyOne: + self.setselection(range(len(self.items))) + self._list.LAutoScroll() + self.click((-1, -1), 0) + + def getselection(self): + if not self._parent or not self._list: + if hasattr(self, "_sel"): + return self._sel + return [] + items = [] + point = (0,0) + while 1: + ok, point = self._list.LGetSelect(1, point) + if not ok: + break + items.append(point[1]) + point = point[0], point[1]+1 + return items + + def setselection(self, selection): + if not self._parent or not self._list: + self._sel = selection + return + set_sel = self._list.LSetSelect + for i in range(len(self.items)): + if i in selection: + set_sel(1, (0, i)) + else: + set_sel(0, (0, i)) + self._list.LAutoScroll() + + def getselectedobjects(self): + sel = self.getselection() + objects = [] + for i in sel: + objects.append(self.items[i]) + return objects + + def setselectedobjects(self, objects): + sel = [] + for o in objects: + try: + sel.append(self.items.index(o)) + except: + pass + self.setselection(sel) + + def gettopcell(self): + l, t, r, b = self._bounds + t = t + 1 + cl, ct, cr, cb = self._list.LRect((0, 0)) + cellheight = cb - ct + return (t - ct) / cellheight + + def settopcell(self, topcell): + top = self.gettopcell() + diff = topcell - top + self._list.LScroll(0, diff) + + def draw(self, visRgn = None): + if self._visible: + if not visRgn: + visRgn = self._parentwindow.wid.GetWindowPort().visRgn + self._list.LUpdate(visRgn) + state = [kThemeStateActive, kThemeStateInactive][not self._activated] + App.DrawThemeListBoxFrame(Qd.InsetRect(self._bounds, 1, 1), state) + if self._selected and self._activated: + self.drawselframe(1) + + def select(self, onoff, isclick = 0): + if Wbase.SelectableWidget.select(self, onoff): + return + self.SetPort() + self.drawselframe(onoff) + + def activate(self, onoff): + self._activated = onoff + if self._visible: + self._list.LActivate(onoff) + #state = [kThemeStateActive, kThemeStateInactive][not onoff] + #App.DrawThemeListBoxFrame(Qd.InsetRect(self._bounds, 1, 1), state) + if self._selected: + self.drawselframe(onoff) + + def get(self): + return self.items + + def itemrepr(self, item): + return str(item)[:255] + + def __getitem__(self, index): + return self.items[index] + + def __setitem__(self, index, item): + if self._parent and self._list: + self._list.LSetCell(self.itemrepr(item), (0, index)) + self.items[index] = item + + def __delitem__(self, index): + if self._parent and self._list: + self._list.LDelRow(1, index) + del self.items[index] + + def __getslice__(self, a, b): + return self.items[a:b] + + def __delslice__(self, a, b): + if b-a: + if self._parent and self._list: + self._list.LDelRow(b-a, a) + del self.items[a:b] + + def __setslice__(self, a, b, items): + if self._parent and self._list: + l = len(items) + the_list = self._list + self.setdrawingmode(0) + if b-a: + if b > len(self.items): + # fix for new 1.5 "feature" where b is sys.maxint instead of len(self)... + # LDelRow doesn't like maxint. + b = len(self.items) + the_list.LDelRow(b-a, a) + the_list.LAddRow(l, a) + self_itemrepr = self.itemrepr + set_cell = the_list.LSetCell + for i in range(len(items)): + set_cell(self_itemrepr(items[i]), (0, i + a)) + self.items[a:b] = items + self.setdrawingmode(1) + else: + self.items[a:b] = items + + def __len__(self): + return len(self.items) + + def append(self, item): + if self._parent and self._list: + index = len(self.items) + self._list.LAddRow(1, index) + self._list.LSetCell(self.itemrepr(item), (0, index)) + self.items.append(item) + + def remove(self, item): + index = self.items.index(item) + self.__delitem__(index) + + def index(self, item): + return self.items.index(item) + + def insert(self, index, item): + if index < 0: + index = 0 + if self._parent and self._list: + self._list.LAddRow(1, index) + self._list.LSetCell(self.itemrepr(item), (0, index)) + self.items.insert(index, item) + + def setdrawingmode(self, onoff): + if onoff: + self.drawingmode = self.drawingmode - 1 + if self.drawingmode == 0 and self._list is not None: + self._list.LSetDrawingMode(1) + if self._visible: + bounds = l, t, r, b = Qd.InsetRect(self._bounds, 1, 1) + cl, ct, cr, cb = self._list.LRect((0, len(self.items)-1)) + if cb < b: + self.SetPort() + Qd.EraseRect((l, cb, cr, b)) + self._list.LUpdate(self._parentwindow.wid.GetWindowPort().visRgn) + self.GetWindow().ValidWindowRect(bounds) + else: + if self.drawingmode == 0 and self._list is not None: + self._list.LSetDrawingMode(0) + self.drawingmode = self.drawingmode + 1 class CustomList(List): - - """Base class for writing custom list definitions.""" - - _cellHeight = 0 - - def createlist(self): - self._calcbounds() - self.SetPort() - rect = self._bounds - rect = rect[0]+1, rect[1]+1, rect[2]-16, rect[3]-1 - self._viewbounds = rect - self._list = CreateCustomList( - rect, - (0, 0, 1, 0), - (0, self._cellHeight), - (kListDefUserProcType, self.listDefinitionFunc), - self._parentwindow.wid, - 0, 1, 0, 1) - if self.drawingmode: - self._list.LSetDrawingMode(0) - self._list.selFlags = self._flags - self.setitems(self.items) - if hasattr(self, "_sel"): - self.setselection(self._sel) - del self._sel - - def listDefinitionFunc(self, message, selected, cellRect, theCell, - dataOffset, dataLen, theList): - """The LDEF message dispatcher routine, no need to override.""" - if message == lInitMsg: - self.listDefInit(theList) - elif message == lDrawMsg: - self.listDefDraw(selected, cellRect, theCell, - dataOffset, dataLen, theList) - elif message == lHiliteMsg: - self.listDefHighlight(selected, cellRect, theCell, - dataOffset, dataLen, theList) - elif message == lCloseMsg: - self.listDefClose(theList) - - def listDefInit(self, theList): - pass - def listDefClose(self, theList): - pass - def listDefDraw(self, selected, cellRect, theCell, - dataOffset, dataLen, theList): - pass - def listDefHighlight(self, selected, cellRect, theCell, - dataOffset, dataLen, theList): - pass + + """Base class for writing custom list definitions.""" + + _cellHeight = 0 + + def createlist(self): + self._calcbounds() + self.SetPort() + rect = self._bounds + rect = rect[0]+1, rect[1]+1, rect[2]-16, rect[3]-1 + self._viewbounds = rect + self._list = CreateCustomList( + rect, + (0, 0, 1, 0), + (0, self._cellHeight), + (kListDefUserProcType, self.listDefinitionFunc), + self._parentwindow.wid, + 0, 1, 0, 1) + if self.drawingmode: + self._list.LSetDrawingMode(0) + self._list.selFlags = self._flags + self.setitems(self.items) + if hasattr(self, "_sel"): + self.setselection(self._sel) + del self._sel + + def listDefinitionFunc(self, message, selected, cellRect, theCell, + dataOffset, dataLen, theList): + """The LDEF message dispatcher routine, no need to override.""" + if message == lInitMsg: + self.listDefInit(theList) + elif message == lDrawMsg: + self.listDefDraw(selected, cellRect, theCell, + dataOffset, dataLen, theList) + elif message == lHiliteMsg: + self.listDefHighlight(selected, cellRect, theCell, + dataOffset, dataLen, theList) + elif message == lCloseMsg: + self.listDefClose(theList) + + def listDefInit(self, theList): + pass + def listDefClose(self, theList): + pass + def listDefDraw(self, selected, cellRect, theCell, + dataOffset, dataLen, theList): + pass + def listDefHighlight(self, selected, cellRect, theCell, + dataOffset, dataLen, theList): + pass class TwoLineList(CustomList): - - _cellHeight = 28 - - def listDefDraw(self, selected, cellRect, theCell, - dataOffset, dataLen, theList): - savedPort = Qd.GetPort() - Qd.SetPort(theList.GetListPort()) - savedClip = Qd.NewRgn() - Qd.GetClip(savedClip) - Qd.ClipRect(cellRect) - savedPenState = Qd.GetPenState() - Qd.PenNormal() - Qd.EraseRect(cellRect) - - #draw the cell if it contains data - ascent, descent, leading, size, hm = Fm.FontMetrics() - linefeed = ascent + descent + leading - - if dataLen: - left, top, right, bottom = cellRect - data = theList.LGetCell(dataLen, theCell) - lines = data.split("\r") - line1 = lines[0] - if len(lines) > 1: - line2 = lines[1] - else: - line2 = "" - Qd.MoveTo(int(left + 4), int(top + ascent)) - Qd.DrawText(line1, 0, len(line1)) - if line2: - Qd.MoveTo(int(left + 4), int(top + ascent + linefeed)) - Qd.DrawText(line2, 0, len(line2)) - Qd.PenPat("\x11\x11\x11\x11\x11\x11\x11\x11") - bottom = top + theList.cellSize[1] - Qd.MoveTo(left, bottom - 1) - Qd.LineTo(right, bottom - 1) - if selected: - self.listDefHighlight(selected, cellRect, theCell, - dataOffset, dataLen, theList) - #restore graphics environment - Qd.SetPort(savedPort) - Qd.SetClip(savedClip) - Qd.DisposeRgn(savedClip) - Qd.SetPenState(savedPenState) - - def listDefHighlight(self, selected, cellRect, theCell, - dataOffset, dataLen, theList): - savedPort = Qd.GetPort() - Qd.SetPort(theList.GetListPort()) - savedClip = Qd.NewRgn() - Qd.GetClip(savedClip) - Qd.ClipRect(cellRect) - savedPenState = Qd.GetPenState() - Qd.PenNormal() - Qd.PenMode(hilitetransfermode) - Qd.PaintRect(cellRect) - - #restore graphics environment - Qd.SetPort(savedPort) - Qd.SetClip(savedClip) - Qd.DisposeRgn(savedClip) - Qd.SetPenState(savedPenState) - + + _cellHeight = 28 + + def listDefDraw(self, selected, cellRect, theCell, + dataOffset, dataLen, theList): + savedPort = Qd.GetPort() + Qd.SetPort(theList.GetListPort()) + savedClip = Qd.NewRgn() + Qd.GetClip(savedClip) + Qd.ClipRect(cellRect) + savedPenState = Qd.GetPenState() + Qd.PenNormal() + Qd.EraseRect(cellRect) + + #draw the cell if it contains data + ascent, descent, leading, size, hm = Fm.FontMetrics() + linefeed = ascent + descent + leading + + if dataLen: + left, top, right, bottom = cellRect + data = theList.LGetCell(dataLen, theCell) + lines = data.split("\r") + line1 = lines[0] + if len(lines) > 1: + line2 = lines[1] + else: + line2 = "" + Qd.MoveTo(int(left + 4), int(top + ascent)) + Qd.DrawText(line1, 0, len(line1)) + if line2: + Qd.MoveTo(int(left + 4), int(top + ascent + linefeed)) + Qd.DrawText(line2, 0, len(line2)) + Qd.PenPat("\x11\x11\x11\x11\x11\x11\x11\x11") + bottom = top + theList.cellSize[1] + Qd.MoveTo(left, bottom - 1) + Qd.LineTo(right, bottom - 1) + if selected: + self.listDefHighlight(selected, cellRect, theCell, + dataOffset, dataLen, theList) + #restore graphics environment + Qd.SetPort(savedPort) + Qd.SetClip(savedClip) + Qd.DisposeRgn(savedClip) + Qd.SetPenState(savedPenState) + + def listDefHighlight(self, selected, cellRect, theCell, + dataOffset, dataLen, theList): + savedPort = Qd.GetPort() + Qd.SetPort(theList.GetListPort()) + savedClip = Qd.NewRgn() + Qd.GetClip(savedClip) + Qd.ClipRect(cellRect) + savedPenState = Qd.GetPenState() + Qd.PenNormal() + Qd.PenMode(hilitetransfermode) + Qd.PaintRect(cellRect) + + #restore graphics environment + Qd.SetPort(savedPort) + Qd.SetClip(savedClip) + Qd.DisposeRgn(savedClip) + Qd.SetPenState(savedPenState) + class ResultsWindow: - - """Simple results window. The user cannot make this window go away completely: - closing it will just hide it. It will remain in the windows list. The owner of this window - should call the done() method to indicate it's done with it. - """ - - def __init__(self, possize=None, title="Results", callback=None): - import W - if possize is None: - possize = (500, 200) - self.w = W.Window(possize, title, minsize=(200, 100)) - self.w.results = W.TwoLineList((-1, -1, 1, -14), callback=None) - self.w.bind("<close>", self.hide) - self.w.open() - self._done = 0 - - def done(self): - self._done = 1 - if not self.w.isvisible(): - self.w.close() - - def hide(self): - if not self._done: - self.w.show(0) - return -1 - - def append(self, msg): - if not self.w.isvisible(): - self.w.show(1) - self.w.select() - msg = string.replace(msg, '\n', '\r') - self.w.results.append(msg) - self.w.results.setselection([len(self.w.results)-1]) - - def __getattr__(self, attr): - return getattr(self.w.results, attr) + + """Simple results window. The user cannot make this window go away completely: + closing it will just hide it. It will remain in the windows list. The owner of this window + should call the done() method to indicate it's done with it. + """ + + def __init__(self, possize=None, title="Results", callback=None): + import W + if possize is None: + possize = (500, 200) + self.w = W.Window(possize, title, minsize=(200, 100)) + self.w.results = W.TwoLineList((-1, -1, 1, -14), callback=None) + self.w.bind("<close>", self.hide) + self.w.open() + self._done = 0 + + def done(self): + self._done = 1 + if not self.w.isvisible(): + self.w.close() + + def hide(self): + if not self._done: + self.w.show(0) + return -1 + + def append(self, msg): + if not self.w.isvisible(): + self.w.show(1) + self.w.select() + msg = string.replace(msg, '\n', '\r') + self.w.results.append(msg) + self.w.results.setselection([len(self.w.results)-1]) + + def __getattr__(self, attr): + return getattr(self.w.results, attr) class MultiList(List): - - """XXX Experimantal!!!""" - - def setitems(self, items): - self.items = items - if not self._parent or not self._list: - return - self._list.LDelRow(0, 1) - self.setdrawingmode(0) - self._list.LAddRow(len(self.items), 0) - self_itemrepr = self.itemrepr - set_cell = self._list.LSetCell - for i in range(len(items)): - row = items[i] - for j in range(len(row)): - item = row[j] - set_cell(self_itemrepr(item), (j, i)) - self.setdrawingmode(1) - - def getselection(self): - if not self._parent or not self._list: - if hasattr(self, "_sel"): - return self._sel - return [] - items = [] - point = (0,0) - while 1: - ok, point = self._list.LGetSelect(1, point) - if not ok: - break - items.append(point[1]) - point = point[0], point[1]+1 - return items - - def setselection(self, selection): - if not self._parent or not self._list: - self._sel = selection - return - set_sel = self._list.LSetSelect - for i in range(len(self.items)): - for j in range(len(self.items[i])): - if i in selection: - set_sel(1, (j, i)) - else: - set_sel(0, (j, i)) - #self._list.LAutoScroll() + """XXX Experimantal!!!""" + + def setitems(self, items): + self.items = items + if not self._parent or not self._list: + return + self._list.LDelRow(0, 1) + self.setdrawingmode(0) + self._list.LAddRow(len(self.items), 0) + self_itemrepr = self.itemrepr + set_cell = self._list.LSetCell + for i in range(len(items)): + row = items[i] + for j in range(len(row)): + item = row[j] + set_cell(self_itemrepr(item), (j, i)) + self.setdrawingmode(1) + + def getselection(self): + if not self._parent or not self._list: + if hasattr(self, "_sel"): + return self._sel + return [] + items = [] + point = (0,0) + while 1: + ok, point = self._list.LGetSelect(1, point) + if not ok: + break + items.append(point[1]) + point = point[0], point[1]+1 + return items + + def setselection(self, selection): + if not self._parent or not self._list: + self._sel = selection + return + set_sel = self._list.LSetSelect + for i in range(len(self.items)): + for j in range(len(self.items[i])): + if i in selection: + set_sel(1, (j, i)) + else: + set_sel(0, (j, i)) + #self._list.LAutoScroll() diff --git a/Mac/Tools/IDE/Wmenus.py b/Mac/Tools/IDE/Wmenus.py index bd119a5..01a8e1c 100644 --- a/Mac/Tools/IDE/Wmenus.py +++ b/Mac/Tools/IDE/Wmenus.py @@ -8,252 +8,252 @@ import Wapplication #_arrowdown = Qd.GetPicture(473) _arrowright = Res.Resource( - '\x00I\x00\x00\x00\x00\x00\n\x00\n\x11\x01\x01\x00\n\x00\x00\x00' - '\x00\x00\n\x00\n\x90\x00\x02\x00\x00\x00\x00\x00\n\x00\n\x00\x00' - '\x00\x00\x00\n\x00\n\x00\x00\x00\x00\x00\n\x00\n\x00\x00\x10\x00' - '\x18\x00\x1c\x00\x1e\x00\x1f\x00\x1f\x00\x1e\x00\x1c\x00\x18\x00' - '\x10\x00\xff') + '\x00I\x00\x00\x00\x00\x00\n\x00\n\x11\x01\x01\x00\n\x00\x00\x00' + '\x00\x00\n\x00\n\x90\x00\x02\x00\x00\x00\x00\x00\n\x00\n\x00\x00' + '\x00\x00\x00\n\x00\n\x00\x00\x00\x00\x00\n\x00\n\x00\x00\x10\x00' + '\x18\x00\x1c\x00\x1e\x00\x1f\x00\x1f\x00\x1e\x00\x1c\x00\x18\x00' + '\x10\x00\xff') class PopupControl(Wcontrols.ControlWidget): - - def __init__(self, possize, items=None, callback=None): - if items is None: - items = [] - procID = Controls.popupMenuProc|Controls.popupFixedWidth|Controls.useWFont - Wcontrols.ControlWidget.__init__(self, possize, "", procID, callback, 0, 0, 0) - self._items = items[:] - - def set(self, value): - self._control.SetControlValue(value+1) - - def get(self): - return self._control.GetControlValue() - 1 - - def open(self): - self.menu = menu = FrameWork.Menu(self._parentwindow.parent.menubar, 'Foo', -1) - - for i in range(len(self._items)): - item = self._items[i] - if type(item) == StringType: - menuitemtext = object = item - elif type(item) == TupleType and len(item) == 2: - menuitemtext, object = item - self._items[i] = object - else: - raise Wbase.WidgetsError, "illegal itemlist for popup menu" - menuitem = FrameWork.MenuItem(menu, menuitemtext, None, None) - - self._calcbounds() - self._control = Ctl.NewControl(self._parentwindow.wid, - self._bounds, - self._title, - 1, - self._value, - self.menu.id, - self._max, - self._procID, - 0) - self.SetPort() - self.enable(self._enabled) - - def close(self): - self.menu.delete() - return Wcontrols.ControlWidget.close(self) - - def click(self, point, modifiers): - if not self._enabled: - return - part = self._control.TrackControl(point, -1) - if part: - if self._callback: - Wbase.CallbackCall(self._callback, 0, self._items[self.get()]) + + def __init__(self, possize, items=None, callback=None): + if items is None: + items = [] + procID = Controls.popupMenuProc|Controls.popupFixedWidth|Controls.useWFont + Wcontrols.ControlWidget.__init__(self, possize, "", procID, callback, 0, 0, 0) + self._items = items[:] + + def set(self, value): + self._control.SetControlValue(value+1) + + def get(self): + return self._control.GetControlValue() - 1 + + def open(self): + self.menu = menu = FrameWork.Menu(self._parentwindow.parent.menubar, 'Foo', -1) + + for i in range(len(self._items)): + item = self._items[i] + if type(item) == StringType: + menuitemtext = object = item + elif type(item) == TupleType and len(item) == 2: + menuitemtext, object = item + self._items[i] = object + else: + raise Wbase.WidgetsError, "illegal itemlist for popup menu" + menuitem = FrameWork.MenuItem(menu, menuitemtext, None, None) + + self._calcbounds() + self._control = Ctl.NewControl(self._parentwindow.wid, + self._bounds, + self._title, + 1, + self._value, + self.menu.id, + self._max, + self._procID, + 0) + self.SetPort() + self.enable(self._enabled) + + def close(self): + self.menu.delete() + return Wcontrols.ControlWidget.close(self) + + def click(self, point, modifiers): + if not self._enabled: + return + part = self._control.TrackControl(point, -1) + if part: + if self._callback: + Wbase.CallbackCall(self._callback, 0, self._items[self.get()]) class PopupWidget(Wbase.ClickableWidget): - - """Simple title-less popup widget. Should be 16x16 pixels. - Builds the menu items on the fly, good for dynamic popup menus.""" - - def __init__(self, possize, items=None, callback=None): - Wbase.ClickableWidget.__init__(self, possize) - if items is None: - items = [] - self._items = items - self._itemsdict = {} - self._callback = callback - self._enabled = 1 - - def close(self): - Wbase.ClickableWidget.close(self) - self._items = None - self._itemsdict = {} - - def draw(self, visRgn = None): - if self._visible: - Qd.FrameRect(self._bounds) - Qd.EraseRect(Qd.InsetRect(self._bounds, 1, 1)) - l, t, r, b = self._bounds - l = l + 2 - t = t + 3 - pictframe = (l, t, l + 10, t + 10) - Qd.DrawPicture(_arrowright, pictframe) - - def click(self, point, modifiers): - if not self._enabled: - return - self.menu = FrameWork.Menu(self._parentwindow.parent.menubar, 'Foo', -1) - self._additems(self._items, self.menu) - self.SetPort() - l, t, r, b = self._bounds - l, t = Qd.LocalToGlobal((l+1, t+1)) - Wbase.SetCursor("arrow") - self.menu.menu.EnableMenuItem(0) - reply = self.menu.menu.PopUpMenuSelect(t, l, 1) - if reply: - id = reply >> 16 - item = reply & 0xffff - self._menu_callback(id, item) - self._emptymenu() - - def set(self, items): - self._items = items - - def get(self): - return self._items - - def _additems(self, items, menu): - from FrameWork import SubMenu, MenuItem - menu_id = menu.id - for item in items: - if item == "-": - menu.addseparator() - continue - elif type(item) == ListType: - submenu = SubMenu(menu, item[0]) - self._additems(item[1:], submenu) - continue - elif type(item) == StringType: - menuitemtext = object = item - elif type(item) == TupleType and len(item) == 2: - menuitemtext, object = item - else: - raise Wbase.WidgetsError, "illegal itemlist for popup menu" - - if menuitemtext[:1] == '\0': - check = ord(menuitemtext[1]) - menuitemtext = menuitemtext[2:] - else: - check = 0 - menuitem = MenuItem(menu, menuitemtext, None, None) - if check: - menuitem.check(1) - self._itemsdict[(menu_id, menuitem.item)] = object - - def _emptymenu(self): - menus = self._parentwindow.parent.menubar.menus - for id, item in self._itemsdict.keys(): - if menus.has_key(id): - self.menu = menus[id] - self.menu.delete() - self._itemsdict = {} - - def _menu_callback(self, id, item): - thing = self._itemsdict[(id, item)] - if callable(thing): - thing() - elif self._callback: - Wbase.CallbackCall(self._callback, 0, thing) + + """Simple title-less popup widget. Should be 16x16 pixels. + Builds the menu items on the fly, good for dynamic popup menus.""" + + def __init__(self, possize, items=None, callback=None): + Wbase.ClickableWidget.__init__(self, possize) + if items is None: + items = [] + self._items = items + self._itemsdict = {} + self._callback = callback + self._enabled = 1 + + def close(self): + Wbase.ClickableWidget.close(self) + self._items = None + self._itemsdict = {} + + def draw(self, visRgn = None): + if self._visible: + Qd.FrameRect(self._bounds) + Qd.EraseRect(Qd.InsetRect(self._bounds, 1, 1)) + l, t, r, b = self._bounds + l = l + 2 + t = t + 3 + pictframe = (l, t, l + 10, t + 10) + Qd.DrawPicture(_arrowright, pictframe) + + def click(self, point, modifiers): + if not self._enabled: + return + self.menu = FrameWork.Menu(self._parentwindow.parent.menubar, 'Foo', -1) + self._additems(self._items, self.menu) + self.SetPort() + l, t, r, b = self._bounds + l, t = Qd.LocalToGlobal((l+1, t+1)) + Wbase.SetCursor("arrow") + self.menu.menu.EnableMenuItem(0) + reply = self.menu.menu.PopUpMenuSelect(t, l, 1) + if reply: + id = reply >> 16 + item = reply & 0xffff + self._menu_callback(id, item) + self._emptymenu() + + def set(self, items): + self._items = items + + def get(self): + return self._items + + def _additems(self, items, menu): + from FrameWork import SubMenu, MenuItem + menu_id = menu.id + for item in items: + if item == "-": + menu.addseparator() + continue + elif type(item) == ListType: + submenu = SubMenu(menu, item[0]) + self._additems(item[1:], submenu) + continue + elif type(item) == StringType: + menuitemtext = object = item + elif type(item) == TupleType and len(item) == 2: + menuitemtext, object = item + else: + raise Wbase.WidgetsError, "illegal itemlist for popup menu" + + if menuitemtext[:1] == '\0': + check = ord(menuitemtext[1]) + menuitemtext = menuitemtext[2:] + else: + check = 0 + menuitem = MenuItem(menu, menuitemtext, None, None) + if check: + menuitem.check(1) + self._itemsdict[(menu_id, menuitem.item)] = object + + def _emptymenu(self): + menus = self._parentwindow.parent.menubar.menus + for id, item in self._itemsdict.keys(): + if menus.has_key(id): + self.menu = menus[id] + self.menu.delete() + self._itemsdict = {} + + def _menu_callback(self, id, item): + thing = self._itemsdict[(id, item)] + if callable(thing): + thing() + elif self._callback: + Wbase.CallbackCall(self._callback, 0, thing) class PopupMenu(PopupWidget): - - """Simple title-less popup widget. Should be 16x16 pixels. - Prebuilds the menu items, good for static (non changing) popup menus.""" - - def open(self): - self._calcbounds() - self.menu = Wapplication.Menu(self._parentwindow.parent.menubar, 'Foo', -1) - self._additems(self._items, self.menu) - - def close(self): - self._emptymenu() - Wbase.Widget.close(self) - self._items = None - self._itemsdict = {} - self.menu = None - - def set(self, items): - if self._itemsdict: - self._emptymenu() - self.menu = Wapplication.Menu(self._parentwindow.parent.menubar, 'Foo', -1) - self._items = items - self._additems(self._items, self.menu) - - def click(self, point, modifiers): - if not self._enabled: - return - self.SetPort() - l, t, r, b = self._bounds - l, t = Qd.LocalToGlobal((l+1, t+1)) - Wbase.SetCursor("arrow") - self.menu.menu.EnableMenuItem(0) - reply = self.menu.menu.PopUpMenuSelect(t, l, 1) - if reply: - id = reply >> 16 - item = reply & 0xffff - self._menu_callback(id, item) + + """Simple title-less popup widget. Should be 16x16 pixels. + Prebuilds the menu items, good for static (non changing) popup menus.""" + + def open(self): + self._calcbounds() + self.menu = Wapplication.Menu(self._parentwindow.parent.menubar, 'Foo', -1) + self._additems(self._items, self.menu) + + def close(self): + self._emptymenu() + Wbase.Widget.close(self) + self._items = None + self._itemsdict = {} + self.menu = None + + def set(self, items): + if self._itemsdict: + self._emptymenu() + self.menu = Wapplication.Menu(self._parentwindow.parent.menubar, 'Foo', -1) + self._items = items + self._additems(self._items, self.menu) + + def click(self, point, modifiers): + if not self._enabled: + return + self.SetPort() + l, t, r, b = self._bounds + l, t = Qd.LocalToGlobal((l+1, t+1)) + Wbase.SetCursor("arrow") + self.menu.menu.EnableMenuItem(0) + reply = self.menu.menu.PopUpMenuSelect(t, l, 1) + if reply: + id = reply >> 16 + item = reply & 0xffff + self._menu_callback(id, item) class FontMenu(PopupMenu): - - """A font popup menu.""" - - menu = None - - def __init__(self, possize, callback): - PopupMenu.__init__(self, possize) - _makefontmenu() - self._callback = callback - self._enabled = 1 - - def open(self): - self._calcbounds() - - def close(self): - del self._callback - - def set(self): - raise Wbase.WidgetsError, "can't change font menu widget" - - def _menu_callback(self, id, item): - fontname = self.menu.menu.GetMenuItemText(item) - if self._callback: - Wbase.CallbackCall(self._callback, 0, fontname) - - def click(self, point, modifiers): - if not self._enabled: - return - _makefontmenu() - return PopupMenu.click(self, point, modifiers) - + + """A font popup menu.""" + + menu = None + + def __init__(self, possize, callback): + PopupMenu.__init__(self, possize) + _makefontmenu() + self._callback = callback + self._enabled = 1 + + def open(self): + self._calcbounds() + + def close(self): + del self._callback + + def set(self): + raise Wbase.WidgetsError, "can't change font menu widget" + + def _menu_callback(self, id, item): + fontname = self.menu.menu.GetMenuItemText(item) + if self._callback: + Wbase.CallbackCall(self._callback, 0, fontname) + + def click(self, point, modifiers): + if not self._enabled: + return + _makefontmenu() + return PopupMenu.click(self, point, modifiers) + def _makefontmenu(): - """helper for font menu""" - if FontMenu.menu is not None: - return - import W - FontMenu.menu = Wapplication.Menu(W.getapplication().menubar, 'Foo', -1) - W.SetCursor('watch') - for i in range(FontMenu.menu.menu.CountMenuItems(), 0, -1): - FontMenu.menu.menu.DeleteMenuItem(i) - FontMenu.menu.menu.AppendResMenu('FOND') + """helper for font menu""" + if FontMenu.menu is not None: + return + import W + FontMenu.menu = Wapplication.Menu(W.getapplication().menubar, 'Foo', -1) + W.SetCursor('watch') + for i in range(FontMenu.menu.menu.CountMenuItems(), 0, -1): + FontMenu.menu.menu.DeleteMenuItem(i) + FontMenu.menu.menu.AppendResMenu('FOND') def _getfontlist(): - from Carbon import Res - fontnames = [] - for i in range(1, Res.CountResources('FOND') + 1): - r = Res.GetIndResource('FOND', i) - fontnames.append(r.GetResInfo()[2]) - return fontnames + from Carbon import Res + fontnames = [] + for i in range(1, Res.CountResources('FOND') + 1): + r = Res.GetIndResource('FOND', i) + fontnames.append(r.GetResInfo()[2]) + return fontnames diff --git a/Mac/Tools/IDE/Wminiapp.py b/Mac/Tools/IDE/Wminiapp.py index e09e334..0c51583 100644 --- a/Mac/Tools/IDE/Wminiapp.py +++ b/Mac/Tools/IDE/Wminiapp.py @@ -5,18 +5,18 @@ 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() - + + 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() diff --git a/Mac/Tools/IDE/Wquicktime.py b/Mac/Tools/IDE/Wquicktime.py index 421d558..671aa09 100644 --- a/Mac/Tools/IDE/Wquicktime.py +++ b/Mac/Tools/IDE/Wquicktime.py @@ -9,106 +9,105 @@ from Carbon import Evt, Events _moviesinitialized = 0 def EnterMovies(): - global _moviesinitialized - if not _moviesinitialized: - Qt.EnterMovies() - _moviesinitialized = 1 + 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) + 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) diff --git a/Mac/Tools/IDE/Wsocket.py b/Mac/Tools/IDE/Wsocket.py index 913797c..eb5936d 100644 --- a/Mac/Tools/IDE/Wsocket.py +++ b/Mac/Tools/IDE/Wsocket.py @@ -17,375 +17,375 @@ BUFSIZE = 512 VERBOSE = 1 class Server(asyncore.dispatcher): - - """Generic asynchronous server class""" - - def __init__(self, port, handler_class, backlog=1, host=""): - """arguments: - - port: the port to listen to - - handler_class: class to handle requests - - backlog: backlog queue size (optional) (don't fully understand, see socket docs) - - host: host name (optional: can be empty to use default host name) - """ - if VERBOSE: - print "Starting", self.__class__.__name__ - self.handler_class = handler_class - asyncore.dispatcher.__init__(self) - self.create_socket(socket.AF_INET, socket.SOCK_STREAM) - self.bind((host, port)) - self.listen(backlog) - - def handle_accept(self): - conn, addr = self.accept() - if VERBOSE: - print 'Incoming Connection from %s:%d' % addr - self.handler_class(conn) + + """Generic asynchronous server class""" + + def __init__(self, port, handler_class, backlog=1, host=""): + """arguments: + - port: the port to listen to + - handler_class: class to handle requests + - backlog: backlog queue size (optional) (don't fully understand, see socket docs) + - host: host name (optional: can be empty to use default host name) + """ + if VERBOSE: + print "Starting", self.__class__.__name__ + self.handler_class = handler_class + asyncore.dispatcher.__init__(self) + self.create_socket(socket.AF_INET, socket.SOCK_STREAM) + self.bind((host, port)) + self.listen(backlog) + + def handle_accept(self): + conn, addr = self.accept() + if VERBOSE: + print 'Incoming Connection from %s:%d' % addr + self.handler_class(conn) class ProxyServer(Server): - - """Generic proxy server class""" - - def __init__(self, port, handler_class, proxyaddr=None, closepartners=0): - """arguments: - - port: the port to listen to - - handler_class: proxy class to handle requests - - proxyaddr: a tuple containing the address and - port of a remote host to connect to (optional) - - closepartners: boolean, specifies whether we should close - all proxy connections or not (optional). http seems to *not* - want this, but telnet does... - """ - Server.__init__(self, port, handler_class, 1, "") - self.proxyaddr = proxyaddr - self.closepartners = closepartners - - def handle_accept(self): - conn, addr = self.accept() - if VERBOSE: - print 'Incoming Connection from %s:%d' % addr - self.handler_class(conn, self.proxyaddr, closepartner=self.closepartners) + + """Generic proxy server class""" + + def __init__(self, port, handler_class, proxyaddr=None, closepartners=0): + """arguments: + - port: the port to listen to + - handler_class: proxy class to handle requests + - proxyaddr: a tuple containing the address and + port of a remote host to connect to (optional) + - closepartners: boolean, specifies whether we should close + all proxy connections or not (optional). http seems to *not* + want this, but telnet does... + """ + Server.__init__(self, port, handler_class, 1, "") + self.proxyaddr = proxyaddr + self.closepartners = closepartners + + def handle_accept(self): + conn, addr = self.accept() + if VERBOSE: + print 'Incoming Connection from %s:%d' % addr + self.handler_class(conn, self.proxyaddr, closepartner=self.closepartners) class Connection(asyncore.dispatcher): - - """Generic connection class""" - - def __init__(self, sock_or_address=None, readfunc=None, terminator=None): - """arguments: - - sock_or_address: either a socket, or a tuple containing the name - and port number of a remote host - - readfunc: callback function (optional). Will be called whenever - there is some data available, or when an appropraite terminator - is found. - - terminator: string which specifies when a read is complete (optional)""" - self._out_buffer = "" - self._in_buffer = "" - self.readfunc = readfunc - self.terminator = terminator - asyncore.dispatcher.__init__(self) - if hasattr(sock_or_address, "fileno"): - self.set_socket(sock_or_address) - else: - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.setblocking(0) - self.set_socket(sock) - if sock_or_address: - self.connect(sock_or_address) - - # public methods - def send(self, data): - self._out_buffer = self._out_buffer + data - - def recv(self, bytes=-1): - if bytes == -1: - bytes = len(self._in_buffer) - data = self._in_buffer[:bytes] - self._in_buffer = self._in_buffer[bytes:] - return data - - def set_terminator(self, terminator): - self.terminator = terminator - - # override this if you want to control the incoming data stream - def handle_incoming_data(self, data): - if self.readfunc: - if self.terminator: - self._in_buffer = self._in_buffer + data - pos = string.find(self._in_buffer, self.terminator) - if pos < 0: - return - data = self._in_buffer[:pos] - self._in_buffer = self._in_buffer[pos + len(self.terminator):] - self.readfunc(data) - else: - self.readfunc(self._in_buffer + data) - self._in_buffer = "" - else: - self._in_buffer = self._in_buffer + data - - # internal muck - def handle_read(self): - data = asyncore.dispatcher.recv(self, BUFSIZE) - if data: - if VERBOSE > 2: - print "incoming -> %x %r" % (id(self), data) - self.handle_incoming_data(data) - - def handle_write(self): - if self._out_buffer: - sent = self.socket.send(self._out_buffer[:BUFSIZE]) - if VERBOSE > 2: - print "outgoing -> %x %r" % (id(self), self._out_buffer[:sent]) - self._out_buffer = self._out_buffer[sent:] - - def close(self): - if self.readfunc and self._in_buffer: - self.readfunc(self._in_buffer) - self._in_buffer = "" - #elif VERBOSE > 1 and self._in_buffer: - # print "--- there is unread data: %r", (self._in_buffer,) - asyncore.dispatcher.close(self) - - def handle_close(self): - self.close() - - def handle_connect(self): - pass + + """Generic connection class""" + + def __init__(self, sock_or_address=None, readfunc=None, terminator=None): + """arguments: + - sock_or_address: either a socket, or a tuple containing the name + and port number of a remote host + - readfunc: callback function (optional). Will be called whenever + there is some data available, or when an appropraite terminator + is found. + - terminator: string which specifies when a read is complete (optional)""" + self._out_buffer = "" + self._in_buffer = "" + self.readfunc = readfunc + self.terminator = terminator + asyncore.dispatcher.__init__(self) + if hasattr(sock_or_address, "fileno"): + self.set_socket(sock_or_address) + else: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setblocking(0) + self.set_socket(sock) + if sock_or_address: + self.connect(sock_or_address) + + # public methods + def send(self, data): + self._out_buffer = self._out_buffer + data + + def recv(self, bytes=-1): + if bytes == -1: + bytes = len(self._in_buffer) + data = self._in_buffer[:bytes] + self._in_buffer = self._in_buffer[bytes:] + return data + + def set_terminator(self, terminator): + self.terminator = terminator + + # override this if you want to control the incoming data stream + def handle_incoming_data(self, data): + if self.readfunc: + if self.terminator: + self._in_buffer = self._in_buffer + data + pos = string.find(self._in_buffer, self.terminator) + if pos < 0: + return + data = self._in_buffer[:pos] + self._in_buffer = self._in_buffer[pos + len(self.terminator):] + self.readfunc(data) + else: + self.readfunc(self._in_buffer + data) + self._in_buffer = "" + else: + self._in_buffer = self._in_buffer + data + + # internal muck + def handle_read(self): + data = asyncore.dispatcher.recv(self, BUFSIZE) + if data: + if VERBOSE > 2: + print "incoming -> %x %r" % (id(self), data) + self.handle_incoming_data(data) + + def handle_write(self): + if self._out_buffer: + sent = self.socket.send(self._out_buffer[:BUFSIZE]) + if VERBOSE > 2: + print "outgoing -> %x %r" % (id(self), self._out_buffer[:sent]) + self._out_buffer = self._out_buffer[sent:] + + def close(self): + if self.readfunc and self._in_buffer: + self.readfunc(self._in_buffer) + self._in_buffer = "" + #elif VERBOSE > 1 and self._in_buffer: + # print "--- there is unread data: %r", (self._in_buffer,) + asyncore.dispatcher.close(self) + + def handle_close(self): + self.close() + + def handle_connect(self): + pass class ConnectionUI: - - """Glue to let a connection tell things to the UI in a standardized way. - - The protocoll defines four functions, which the connection will call: - - def settotal(int total): gets called when the connection knows the data size - def setcurrent(int current): gets called when some new data has arrived - def done(): gets called when the transaction is complete - def error(type, value, tb): gets called wheneven an error occured - """ - - def __init__(self, settotal_func, setcurrent_func, done_func, error_func): - self.settotal = settotal_func - self.setcurrent = setcurrent_func - self.done = done_func - self.error = error_func + + """Glue to let a connection tell things to the UI in a standardized way. + + The protocoll defines four functions, which the connection will call: + + def settotal(int total): gets called when the connection knows the data size + def setcurrent(int current): gets called when some new data has arrived + def done(): gets called when the transaction is complete + def error(type, value, tb): gets called wheneven an error occured + """ + + def __init__(self, settotal_func, setcurrent_func, done_func, error_func): + self.settotal = settotal_func + self.setcurrent = setcurrent_func + self.done = done_func + self.error = error_func class HTTPError(socket.error): pass class HTTPClient(Connection, httplib.HTTP): - - """Asynchronous HTTP connection""" - - def __init__(self, (host, port), datahandler, ui=None): - Connection.__init__(self, (host, port)) - self.datahandler = datahandler - self.ui = ui - self.buf = "" - self.doneheaders = 0 - self.done = 0 - self.headers = None - self.length = None - self.pos = 0 - - def getreply(self): - raise TypeError, "getreply() is not supported in async HTTP connection" - - def handle_incoming_data(self, data): - assert not self.done - if not self.doneheaders: - self.buf = self.buf + data - pos = string.find(self.buf, "\r\n\r\n") - if pos >= 0: - self.handle_reply(self.buf[:pos+4]) - length = self.headers.getheader("Content-Length") - if length is not None: - self.length = int(length) - if self.ui is not None: - self.ui.settotal(self.length) - else: - self.length = -1 - self.doneheaders = 1 - self.handle_data(self.buf[pos+4:]) - self.buf = "" - else: - self.handle_data(data) - - def handle_reply(self, data): - f = cStringIO.StringIO(data) - ver, code, msg = string.split(f.readline(), None, 2) - code = int(code) - msg = string.strip(msg) - if code <> 200: - # Hm, this is what *I* need, but probably not correct... - raise HTTPError, (code, msg) - self.headers = mimetools.Message(f) - - def handle_data(self, data): - self.pos = self.pos + len(data) - if self.ui is not None: - self.ui.setcurrent(self.pos) - self.datahandler(data) - if self.pos >= self.length: - self.datahandler("") - self.done = 1 - if self.ui is not None: - self.ui.done() - - def handle_error(self, type, value, tb): - if self.ui is not None: - self.ui.error(type, value, tb) - else: - Connection.handle_error(self, type, value, tb) - - def log(self, message): - if VERBOSE: - print 'LOG:', message + + """Asynchronous HTTP connection""" + + def __init__(self, (host, port), datahandler, ui=None): + Connection.__init__(self, (host, port)) + self.datahandler = datahandler + self.ui = ui + self.buf = "" + self.doneheaders = 0 + self.done = 0 + self.headers = None + self.length = None + self.pos = 0 + + def getreply(self): + raise TypeError, "getreply() is not supported in async HTTP connection" + + def handle_incoming_data(self, data): + assert not self.done + if not self.doneheaders: + self.buf = self.buf + data + pos = string.find(self.buf, "\r\n\r\n") + if pos >= 0: + self.handle_reply(self.buf[:pos+4]) + length = self.headers.getheader("Content-Length") + if length is not None: + self.length = int(length) + if self.ui is not None: + self.ui.settotal(self.length) + else: + self.length = -1 + self.doneheaders = 1 + self.handle_data(self.buf[pos+4:]) + self.buf = "" + else: + self.handle_data(data) + + def handle_reply(self, data): + f = cStringIO.StringIO(data) + ver, code, msg = string.split(f.readline(), None, 2) + code = int(code) + msg = string.strip(msg) + if code <> 200: + # Hm, this is what *I* need, but probably not correct... + raise HTTPError, (code, msg) + self.headers = mimetools.Message(f) + + def handle_data(self, data): + self.pos = self.pos + len(data) + if self.ui is not None: + self.ui.setcurrent(self.pos) + self.datahandler(data) + if self.pos >= self.length: + self.datahandler("") + self.done = 1 + if self.ui is not None: + self.ui.done() + + def handle_error(self, type, value, tb): + if self.ui is not None: + self.ui.error(type, value, tb) + else: + Connection.handle_error(self, type, value, tb) + + def log(self, message): + if VERBOSE: + print 'LOG:', message class PyMessage: - - def __init__(self): - self._buf = "" - self._len = None - self._checksum = None - - def feed(self, data): - self._buf = self._buf + data - if self._len is None: - if len(self._buf) >= 8: - import struct - self._len, self._checksum = struct.unpack("ll", self._buf[:8]) - self._buf = self._buf[8:] - if self._len is not None: - if len(self._buf) >= self._len: - import zlib - data = self._buf[:self._len] - leftover = self._buf[self._len:] - self._buf = None - assert self._checksum == zlib.adler32(data), "corrupt data" - self.data = data - return 1, leftover - else: - return 0, None - else: - return 0, None + + def __init__(self): + self._buf = "" + self._len = None + self._checksum = None + + def feed(self, data): + self._buf = self._buf + data + if self._len is None: + if len(self._buf) >= 8: + import struct + self._len, self._checksum = struct.unpack("ll", self._buf[:8]) + self._buf = self._buf[8:] + if self._len is not None: + if len(self._buf) >= self._len: + import zlib + data = self._buf[:self._len] + leftover = self._buf[self._len:] + self._buf = None + assert self._checksum == zlib.adler32(data), "corrupt data" + self.data = data + return 1, leftover + else: + return 0, None + else: + return 0, None class PyConnection(Connection): - - def __init__(self, sock_or_address): - Connection.__init__(self, sock_or_address) - self.currentmessage = PyMessage() - - def handle_incoming_data(self, data): - while data: - done, data = self.currentmessage.feed(data) - if done: - import cPickle - self.handle_object(cPickle.loads(self.currentmessage.data)) - self.currentmessage = PyMessage() - - def handle_object(self, object): - print 'unhandled object:', repr(object) - - def send(self, object): - import cPickle, zlib, struct - data = cPickle.dumps(object, 1) - length = len(data) - checksum = zlib.adler32(data) - data = struct.pack("ll", length, checksum) + data - Connection.send(self, data) + + def __init__(self, sock_or_address): + Connection.__init__(self, sock_or_address) + self.currentmessage = PyMessage() + + def handle_incoming_data(self, data): + while data: + done, data = self.currentmessage.feed(data) + if done: + import cPickle + self.handle_object(cPickle.loads(self.currentmessage.data)) + self.currentmessage = PyMessage() + + def handle_object(self, object): + print 'unhandled object:', repr(object) + + def send(self, object): + import cPickle, zlib, struct + data = cPickle.dumps(object, 1) + length = len(data) + checksum = zlib.adler32(data) + data = struct.pack("ll", length, checksum) + data + Connection.send(self, data) class Echo(Connection): - - """Simple echoing connection: it sends everything back it receives.""" - - def handle_incoming_data(self, data): - self.send(data) + + """Simple echoing connection: it sends everything back it receives.""" + + def handle_incoming_data(self, data): + self.send(data) class Proxy(Connection): - - """Generic proxy connection""" - - def __init__(self, sock_or_address=None, proxyaddr=None, closepartner=0): - """arguments: - - sock_or_address is either a socket or a tuple containing the - name and port number of a remote host - - proxyaddr: a tuple containing a name and a port number of a - remote host (optional). - - closepartner: boolean, specifies whether we should close - the proxy connection (optional)""" - - Connection.__init__(self, sock_or_address) - self.other = None - self.proxyaddr = proxyaddr - self.closepartner = closepartner - - def close(self): - if self.other: - other = self.other - self.other = None - other.other = None - if self.closepartner: - other.close() - Connection.close(self) - - def handle_incoming_data(self, data): - if not self.other: - # pass data for possible automatic remote host detection - # (see HTTPProxy) - data = self.connectproxy(data) - self.other.send(data) - - def connectproxy(self, data): - other = self.__class__(self.proxyaddr, closepartner=self.closepartner) - self.other = other - other.other = self - return data + + """Generic proxy connection""" + + def __init__(self, sock_or_address=None, proxyaddr=None, closepartner=0): + """arguments: + - sock_or_address is either a socket or a tuple containing the + name and port number of a remote host + - proxyaddr: a tuple containing a name and a port number of a + remote host (optional). + - closepartner: boolean, specifies whether we should close + the proxy connection (optional)""" + + Connection.__init__(self, sock_or_address) + self.other = None + self.proxyaddr = proxyaddr + self.closepartner = closepartner + + def close(self): + if self.other: + other = self.other + self.other = None + other.other = None + if self.closepartner: + other.close() + Connection.close(self) + + def handle_incoming_data(self, data): + if not self.other: + # pass data for possible automatic remote host detection + # (see HTTPProxy) + data = self.connectproxy(data) + self.other.send(data) + + def connectproxy(self, data): + other = self.__class__(self.proxyaddr, closepartner=self.closepartner) + self.other = other + other.other = self + return data class HTTPProxy(Proxy): - - """Simple, useless, http proxy. It figures out itself where to connect to.""" - - def connectproxy(self, data): - if VERBOSE: - print "--- proxy request", repr(data) - addr, data = de_proxify(data) - other = Proxy(addr) - self.other = other - other.other = self - return data + + """Simple, useless, http proxy. It figures out itself where to connect to.""" + + def connectproxy(self, data): + if VERBOSE: + print "--- proxy request", repr(data) + addr, data = de_proxify(data) + other = Proxy(addr) + self.other = other + other.other = self + return data # helper for HTTPProxy def de_proxify(data): - import re - req_pattern = "GET http://([a-zA-Z0-9-_.]+)(:([0-9]+))?" - m = re.match(req_pattern, data) - host, dummy, port = m.groups() - if not port: - port = 80 - else: - port = int(port) - # change "GET http://xx.xx.xx/yy" into "GET /yy" - data = re.sub(req_pattern, "GET ", data) - return (host, port), data + import re + req_pattern = "GET http://([a-zA-Z0-9-_.]+)(:([0-9]+))?" + m = re.match(req_pattern, data) + host, dummy, port = m.groups() + if not port: + port = 80 + else: + port = int(port) + # change "GET http://xx.xx.xx/yy" into "GET /yy" + data = re.sub(req_pattern, "GET ", data) + return (host, port), data # if we're running "under W", let's register the socket poller to the event loop try: - import W + import W except: - pass + pass else: - W.getapplication().addidlefunc(asyncore.poll) + W.getapplication().addidlefunc(asyncore.poll) ## testing muck diff --git a/Mac/Tools/IDE/Wtext.py b/Mac/Tools/IDE/Wtext.py index 3894e16..b3d2f8e 100644 --- a/Mac/Tools/IDE/Wtext.py +++ b/Mac/Tools/IDE/Wtext.py @@ -14,640 +14,640 @@ from types import TupleType, StringType class TextBox(Wbase.Widget): - - """A static text widget""" - - def __init__(self, possize, text="", align=TextEdit.teJustLeft, - fontsettings=None, - backgroundcolor=(0xffff, 0xffff, 0xffff) - ): - if fontsettings is None: - import W - fontsettings = W.getdefaultfont() - Wbase.Widget.__init__(self, possize) - self.fontsettings = fontsettings - self.text = text - self.align = align - self._backgroundcolor = backgroundcolor - - def draw(self, visRgn = None): - if self._visible: - (font, style, size, color) = self.fontsettings - fontid = GetFNum(font) - savestate = Qd.GetPenState() - Qd.TextFont(fontid) - Qd.TextFace(style) - Qd.TextSize(size) - Qd.RGBForeColor(color) - Qd.RGBBackColor(self._backgroundcolor) - TE.TETextBox(self.text, self._bounds, self.align) - Qd.RGBBackColor((0xffff, 0xffff, 0xffff)) - Qd.SetPenState(savestate) - - def get(self): - return self.text - - def set(self, text): - self.text = text - if self._parentwindow and self._parentwindow.wid: - self.SetPort() - self.draw() + + """A static text widget""" + + def __init__(self, possize, text="", align=TextEdit.teJustLeft, + fontsettings=None, + backgroundcolor=(0xffff, 0xffff, 0xffff) + ): + if fontsettings is None: + import W + fontsettings = W.getdefaultfont() + Wbase.Widget.__init__(self, possize) + self.fontsettings = fontsettings + self.text = text + self.align = align + self._backgroundcolor = backgroundcolor + + def draw(self, visRgn = None): + if self._visible: + (font, style, size, color) = self.fontsettings + fontid = GetFNum(font) + savestate = Qd.GetPenState() + Qd.TextFont(fontid) + Qd.TextFace(style) + Qd.TextSize(size) + Qd.RGBForeColor(color) + Qd.RGBBackColor(self._backgroundcolor) + TE.TETextBox(self.text, self._bounds, self.align) + Qd.RGBBackColor((0xffff, 0xffff, 0xffff)) + Qd.SetPenState(savestate) + + def get(self): + return self.text + + def set(self, text): + self.text = text + if self._parentwindow and self._parentwindow.wid: + self.SetPort() + self.draw() class _ScrollWidget: - - # to be overridden - def getscrollrects(self): - """Return (destrect, viewrect).""" - return None, None - - # internal method - - def updatescrollbars(self): - (dl, dt, dr, db), (vl, vt, vr, vb) = self.getscrollrects() - if self._parent._barx: - viewwidth = vr - vl - destwidth = dr - dl - bar = self._parent._barx - bar.setmax(destwidth - viewwidth) - - # MacOS 8.1 doesn't automatically disable - # scrollbars whose max <= min - bar.enable(destwidth > viewwidth) - - bar.setviewsize(viewwidth) - bar.set(vl - dl) - if self._parent._bary: - viewheight = vb - vt - destheight = db - dt - bar = self._parent._bary - bar.setmax(destheight - viewheight) - - # MacOS 8.1 doesn't automatically disable - # scrollbars whose max <= min - bar.enable(destheight > viewheight) - - bar.setviewsize(viewheight) - bar.set(vt - dt) - - -UNDOLABELS = [ # Indexed by WEGetUndoInfo() value - None, "", "typing", "Cut", "Paste", "Clear", "Drag", "Style", - "Ruler", "backspace", "delete", "transform", "resize"] + + # to be overridden + def getscrollrects(self): + """Return (destrect, viewrect).""" + return None, None + + # internal method + + def updatescrollbars(self): + (dl, dt, dr, db), (vl, vt, vr, vb) = self.getscrollrects() + if self._parent._barx: + viewwidth = vr - vl + destwidth = dr - dl + bar = self._parent._barx + bar.setmax(destwidth - viewwidth) + + # MacOS 8.1 doesn't automatically disable + # scrollbars whose max <= min + bar.enable(destwidth > viewwidth) + + bar.setviewsize(viewwidth) + bar.set(vl - dl) + if self._parent._bary: + viewheight = vb - vt + destheight = db - dt + bar = self._parent._bary + bar.setmax(destheight - viewheight) + + # MacOS 8.1 doesn't automatically disable + # scrollbars whose max <= min + bar.enable(destheight > viewheight) + + bar.setviewsize(viewheight) + bar.set(vt - dt) + + +UNDOLABELS = [ # Indexed by WEGetUndoInfo() value + None, "", "typing", "Cut", "Paste", "Clear", "Drag", "Style", + "Ruler", "backspace", "delete", "transform", "resize"] class EditText(Wbase.SelectableWidget, _ScrollWidget): - - """A text edit widget, mainly for simple entry fields.""" - - def __init__(self, possize, text="", - callback=None, inset=(3, 3), - fontsettings=None, - tabsettings = (32, 0), - readonly = 0): - if fontsettings is None: - import W - fontsettings = W.getdefaultfont() - Wbase.SelectableWidget.__init__(self, possize) - self.temptext = text - self.ted = None - self.selection = None - self.oldselection = None - self._callback = callback - self.changed = 0 - self.selchanged = 0 - self._selected = 0 - self._enabled = 1 - self.wrap = 1 - self.readonly = readonly - self.fontsettings = fontsettings - self.tabsettings = tabsettings - if type(inset) <> TupleType: - self.inset = (inset, inset) - else: - self.inset = inset - - def open(self): - if not hasattr(self._parent, "_barx"): - self._parent._barx = None - if not hasattr(self._parent, "_bary"): - self._parent._bary = None - self._calcbounds() - self.SetPort() - viewrect, destrect = self._calctextbounds() - flags = self._getflags() - self.ted = waste.WENew(destrect, viewrect, flags) - self.ted.WEInstallTabHooks() - self.ted.WESetAlignment(WASTEconst.weFlushLeft) - self.setfontsettings(self.fontsettings) - self.settabsettings(self.tabsettings) - self.ted.WEUseText(Res.Resource(self.temptext)) - self.ted.WECalText() - if self.selection: - self.setselection(self.selection[0], self.selection[1]) - self.selection = None - else: - self.selview() - self.temptext = None - self.updatescrollbars() - self.bind("pageup", self.scrollpageup) - self.bind("pagedown", self.scrollpagedown) - self.bind("top", self.scrolltop) - self.bind("bottom", self.scrollbottom) - self.selchanged = 0 - - def close(self): - self._parent._barx = None - self._parent._bary = None - self.ted = None - self.temptext = None - Wbase.SelectableWidget.close(self) - - def textchanged(self, all=0): - self.changed = 1 - - def selectionchanged(self): - self.selchanged = 1 - self.oldselection = self.getselection() - - def gettabsettings(self): - return self.tabsettings - - def settabsettings(self, (tabsize, tabmode)): - self.tabsettings = (tabsize, tabmode) - if hasattr(self.ted, "WESetTabSize"): - port = self._parentwindow.wid.GetWindowPort() - if tabmode: - (font, style, size, color) = self.getfontsettings() - savesettings = GetPortFontSettings(port) - SetPortFontSettings(port, (font, style, size)) - tabsize = Qd.StringWidth(' ' * tabsize) - SetPortFontSettings(port, savesettings) - tabsize = max(tabsize, 1) - self.ted.WESetTabSize(tabsize) - self.SetPort() - Qd.EraseRect(self.ted.WEGetViewRect()) - self.ted.WEUpdate(port.visRgn) - - def getfontsettings(self): - from Carbon import Res - (font, style, size, color) = self.ted.WEGetRunInfo(0)[4] - font = Fm.GetFontName(font) - return (font, style, size, color) - - def setfontsettings(self, (font, style, size, color)): - self.SetPort() - if type(font) <> StringType: - font = Fm.GetFontName(font) - self.fontsettings = (font, style, size, color) - fontid = GetFNum(font) - readonly = self.ted.WEFeatureFlag(WASTEconst.weFReadOnly, -1) - if readonly: - self.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 0) - try: - self.ted.WEFeatureFlag(WASTEconst.weFInhibitRecal, 1) - selstart, selend = self.ted.WEGetSelection() - self.ted.WESetSelection(0, self.ted.WEGetTextLength()) - self.ted.WESetStyle(WASTEconst.weDoFace, (0, 0, 0, (0, 0, 0))) - self.ted.WESetStyle(WASTEconst.weDoFace | - WASTEconst.weDoColor | - WASTEconst.weDoFont | - WASTEconst.weDoSize, - (fontid, style, size, color)) - self.ted.WEFeatureFlag(WASTEconst.weFInhibitRecal, 0) - self.ted.WECalText() - self.ted.WESetSelection(selstart, selend) - finally: - if readonly: - self.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 1) - viewrect = self.ted.WEGetViewRect() - Qd.EraseRect(viewrect) - self.ted.WEUpdate(self._parentwindow.wid.GetWindowPort().visRgn) - self.selectionchanged() - self.updatescrollbars() - - def adjust(self, oldbounds): - self.SetPort() - # Note: if App.DrawThemeEditTextFrame is ever used, it will be necessary - # to unconditionally outset the invalidated rectangles, since Appearance - # frames are drawn outside the bounds. - if self._selected and self._parentwindow._hasselframes: - self.GetWindow().InvalWindowRect(Qd.InsetRect(oldbounds, -3, -3)) - self.GetWindow().InvalWindowRect(Qd.InsetRect(self._bounds, -3, -3)) - else: - self.GetWindow().InvalWindowRect(oldbounds) - self.GetWindow().InvalWindowRect(self._bounds) - viewrect, destrect = self._calctextbounds() - self.ted.WESetViewRect(viewrect) - self.ted.WESetDestRect(destrect) - if self.wrap: - self.ted.WECalText() - if self.ted.WEGetDestRect()[3] < viewrect[1]: - self.selview() - self.updatescrollbars() - - # interface ----------------------- - # selection stuff - def selview(self): - self.ted.WESelView() - - def selectall(self): - self.ted.WESetSelection(0, self.ted.WEGetTextLength()) - self.selectionchanged() - self.updatescrollbars() - - def selectline(self, lineno, charoffset = 0): - newselstart, newselend = self.ted.WEGetLineRange(lineno) - # Autoscroll makes the *end* of the selection visible, which, - # in the case of a whole line, is the beginning of the *next* line. - # So sometimes it leaves our line just above the view rect. - # Let's fool Waste by initially selecting one char less: - self.ted.WESetSelection(newselstart + charoffset, newselend-1) - self.ted.WESetSelection(newselstart + charoffset, newselend) - self.selectionchanged() - self.updatescrollbars() - - def getselection(self): - if self.ted: - return self.ted.WEGetSelection() - else: - return self.selection - - def setselection(self, selstart, selend): - self.selectionchanged() - if self.ted: - self.ted.WESetSelection(selstart, selend) - self.ted.WESelView() - self.updatescrollbars() - else: - self.selection = selstart, selend - - def offsettoline(self, offset): - return self.ted.WEOffsetToLine(offset) - - def countlines(self): - return self.ted.WECountLines() - - def getselectedtext(self): - selstart, selend = self.ted.WEGetSelection() - return self.ted.WEGetText().data[selstart:selend] - - def expandselection(self): - oldselstart, oldselend = self.ted.WEGetSelection() - selstart, selend = min(oldselstart, oldselend), max(oldselstart, oldselend) - if selstart <> selend and chr(self.ted.WEGetChar(selend-1)) == '\r': - selend = selend - 1 - newselstart, dummy = self.ted.WEFindLine(selstart, 1) - dummy, newselend = self.ted.WEFindLine(selend, 1) - if oldselstart <> newselstart or oldselend <> newselend: - self.ted.WESetSelection(newselstart, newselend) - self.updatescrollbars() - self.selectionchanged() - - def insert(self, text): - self.ted.WEInsert(text, None, None) - self.textchanged() - self.selectionchanged() - - # text - def set(self, text): - if not self.ted: - self.temptext = text - else: - self.ted.WEUseText(Res.Resource(text)) - self.ted.WECalText() - self.SetPort() - viewrect, destrect = self._calctextbounds() - self.ted.WESetViewRect(viewrect) - self.ted.WESetDestRect(destrect) - rgn = Qd.NewRgn() - Qd.RectRgn(rgn, viewrect) - Qd.EraseRect(viewrect) - self.draw(rgn) - self.updatescrollbars() - self.textchanged(1) - - def get(self): - if not self._parent: - return self.temptext - else: - return self.ted.WEGetText().data - - # events - def key(self, char, event): - (what, message, when, where, modifiers) = event - if self._enabled and not modifiers & Events.cmdKey or char in Wkeys.arrowkeys: - self.ted.WEKey(ord(char), modifiers) - if char not in Wkeys.navigationkeys: - self.textchanged() - if char not in Wkeys.scrollkeys: - self.selectionchanged() - self.updatescrollbars() - if self._callback: - Wbase.CallbackCall(self._callback, 0, char, modifiers) - - def click(self, point, modifiers): - if not self._enabled: - return - self.ted.WEClick(point, modifiers, Evt.TickCount()) - self.selectionchanged() - self.updatescrollbars() - return 1 - - def idle(self): - self.SetPort() - self.ted.WEIdle() - - def rollover(self, point, onoff): - if onoff: - Wbase.SetCursor("iBeam") - - def activate(self, onoff): - self._activated = onoff - if self._visible: - self.SetPort() - - # DISABLED! There are too many places where it is assumed that - # the frame of an EditText item is 1 pixel, inside the bounds. - #state = [kThemeStateActive, kThemeStateInactive][not onoff] - #App.DrawThemeEditTextFrame(Qd.InsetRect(self._bounds, 1, 1), state) - - if self._selected: - if onoff: - self.ted.WEActivate() - else: - self.ted.WEDeactivate() - self.drawselframe(onoff) - - def select(self, onoff, isclick = 0): - if Wbase.SelectableWidget.select(self, onoff): - return - self.SetPort() - if onoff: - self.ted.WEActivate() - if self._parentwindow._tabbable and not isclick: - self.selectall() - else: - self.ted.WEDeactivate() - self.drawselframe(onoff) - - def draw(self, visRgn = None): - if self._visible: - if not visRgn: - visRgn = self._parentwindow.wid.GetWindowPort().visRgn - self.ted.WEUpdate(visRgn) - - # DISABLED! There are too many places where it is assumed that - # the frame of an EditText item is 1 pixel, inside the bounds. - #state = [kThemeStateActive, kThemeStateInactive][not self._activated] - #App.DrawThemeEditTextFrame(Qd.InsetRect(self._bounds, 1, 1), state) - Qd.FrameRect(self._bounds) - - if self._selected and self._activated: - self.drawselframe(1) - - # scrolling - def scrollpageup(self): - if self._parent._bary and self._parent._bary._enabled: - self.vscroll("++") - - def scrollpagedown(self): - if self._parent._bary and self._parent._bary._enabled: - self.vscroll("--") - - def scrolltop(self): - if self._parent._bary and self._parent._bary._enabled: - self.vscroll(self._parent._bary.getmin()) - if self._parent._barx and self._parent._barx._enabled: - self.hscroll(self._parent._barx.getmin()) - - def scrollbottom(self): - if self._parent._bary and self._parent._bary._enabled: - self.vscroll(self._parent._bary.getmax()) - - # menu handlers - def domenu_copy(self, *args): - selbegin, selend = self.ted.WEGetSelection() - if selbegin == selend: - return - if hasattr(Scrap, 'ZeroScrap'): - Scrap.ZeroScrap() - else: - Scrap.ClearCurrentScrap() - self.ted.WECopy() - self.updatescrollbars() - - def domenu_cut(self, *args): - selbegin, selend = self.ted.WEGetSelection() - if selbegin == selend: - return - if hasattr(Scrap, 'ZeroScrap'): - Scrap.ZeroScrap() - else: - Scrap.ClearCurrentScrap() - self.ted.WECut() - self.updatescrollbars() - self.selview() - self.textchanged() - self.selectionchanged() - if self._callback: - Wbase.CallbackCall(self._callback, 0, "", None) - - def domenu_paste(self, *args): - if not self.ted.WECanPaste(): - return - self.selview() - self.ted.WEPaste() - self.updatescrollbars() - self.textchanged() - self.selectionchanged() - if self._callback: - Wbase.CallbackCall(self._callback, 0, "", None) - - def domenu_clear(self, *args): - self.ted.WEDelete() - self.selview() - self.updatescrollbars() - self.textchanged() - self.selectionchanged() - if self._callback: - Wbase.CallbackCall(self._callback, 0, "", None) - - def domenu_undo(self, *args): - which, redo = self.ted.WEGetUndoInfo() - if not which: - return - self.ted.WEUndo() - self.updatescrollbars() - self.textchanged() - self.selectionchanged() - if self._callback: - Wbase.CallbackCall(self._callback, 0, "", None) - - def can_undo(self, menuitem): - #doundo = self.ted.WEFeatureFlag(WASTEconst.weFUndo, -1) - #print doundo - #if not doundo: - # return 0 - which, redo = self.ted.WEGetUndoInfo() - if which < len(UNDOLABELS): - which = UNDOLABELS[which] - else: - which = "" - if which == None: - return None - if redo: - which = "Redo "+which - else: - which = "Undo "+which - menuitem.settext(which) - return 1 - - def domenu_selectall(self, *args): - self.selectall() - - # private - def getscrollrects(self): - return self.ted.WEGetDestRect(), self.ted.WEGetViewRect() - - def vscroll(self, value): - lineheight = self.ted.WEGetHeight(0, 1) - dr = self.ted.WEGetDestRect() - vr = self.ted.WEGetViewRect() - viewheight = vr[3] - vr[1] - maxdelta = vr[1] - dr[1] - mindelta = vr[3] - dr[3] - if value == "+": - delta = lineheight - elif value == "-": - delta = - lineheight - elif value == "++": - delta = viewheight - lineheight - elif value == "--": - delta = lineheight - viewheight - else: # in thumb - delta = vr[1] - dr[1] - value - delta = min(maxdelta, delta) - delta = max(mindelta, delta) - delta = int(delta) - self.ted.WEScroll(0, delta) - self.updatescrollbars() - - def hscroll(self, value): - dr = self.ted.WEGetDestRect() - vr = self.ted.WEGetViewRect() - destwidth = dr[2] - dr[0] - viewwidth = vr[2] - vr[0] - viewoffset = maxdelta = vr[0] - dr[0] - mindelta = vr[2] - dr[2] - if value == "+": - delta = 32 - elif value == "-": - delta = - 32 - elif value == "++": - delta = 0.5 * (vr[2] - vr[0]) - elif value == "--": - delta = 0.5 * (vr[0] - vr[2]) - else: # in thumb - delta = vr[0] - dr[0] - value - #cur = (32767 * viewoffset) / (destwidth - viewwidth) - #delta = (cur-value)*(destwidth - viewwidth)/32767 - #if abs(delta - viewoffset) <=2: - # # compensate for irritating rounding error - # delta = viewoffset - delta = min(maxdelta, delta) - delta = max(mindelta, delta) - delta = int(delta) - self.ted.WEScroll(delta, 0) - self.updatescrollbars() - - # some internals - def _getflags(self): - flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoMonoStyled - if self.readonly: - flags = flags | WASTEconst.weDoReadOnly - else: - flags = flags | WASTEconst.weDoUndo - return flags - - def _getviewrect(self): - return Qd.InsetRect(self._bounds, self.inset[0], self.inset[1]) - - def _calctextbounds(self): - viewrect = l, t, r, b = self._getviewrect() - if self.ted: - dl, dt, dr, db = self.ted.WEGetDestRect() - vl, vt, vr, vb = self.ted.WEGetViewRect() - yshift = t - vt - if (db - dt) < (b - t): - destrect = viewrect - else: - destrect = l, dt + yshift, r, db + yshift - else: - destrect = viewrect - return viewrect, destrect - + + """A text edit widget, mainly for simple entry fields.""" + + def __init__(self, possize, text="", + callback=None, inset=(3, 3), + fontsettings=None, + tabsettings = (32, 0), + readonly = 0): + if fontsettings is None: + import W + fontsettings = W.getdefaultfont() + Wbase.SelectableWidget.__init__(self, possize) + self.temptext = text + self.ted = None + self.selection = None + self.oldselection = None + self._callback = callback + self.changed = 0 + self.selchanged = 0 + self._selected = 0 + self._enabled = 1 + self.wrap = 1 + self.readonly = readonly + self.fontsettings = fontsettings + self.tabsettings = tabsettings + if type(inset) <> TupleType: + self.inset = (inset, inset) + else: + self.inset = inset + + def open(self): + if not hasattr(self._parent, "_barx"): + self._parent._barx = None + if not hasattr(self._parent, "_bary"): + self._parent._bary = None + self._calcbounds() + self.SetPort() + viewrect, destrect = self._calctextbounds() + flags = self._getflags() + self.ted = waste.WENew(destrect, viewrect, flags) + self.ted.WEInstallTabHooks() + self.ted.WESetAlignment(WASTEconst.weFlushLeft) + self.setfontsettings(self.fontsettings) + self.settabsettings(self.tabsettings) + self.ted.WEUseText(Res.Resource(self.temptext)) + self.ted.WECalText() + if self.selection: + self.setselection(self.selection[0], self.selection[1]) + self.selection = None + else: + self.selview() + self.temptext = None + self.updatescrollbars() + self.bind("pageup", self.scrollpageup) + self.bind("pagedown", self.scrollpagedown) + self.bind("top", self.scrolltop) + self.bind("bottom", self.scrollbottom) + self.selchanged = 0 + + def close(self): + self._parent._barx = None + self._parent._bary = None + self.ted = None + self.temptext = None + Wbase.SelectableWidget.close(self) + + def textchanged(self, all=0): + self.changed = 1 + + def selectionchanged(self): + self.selchanged = 1 + self.oldselection = self.getselection() + + def gettabsettings(self): + return self.tabsettings + + def settabsettings(self, (tabsize, tabmode)): + self.tabsettings = (tabsize, tabmode) + if hasattr(self.ted, "WESetTabSize"): + port = self._parentwindow.wid.GetWindowPort() + if tabmode: + (font, style, size, color) = self.getfontsettings() + savesettings = GetPortFontSettings(port) + SetPortFontSettings(port, (font, style, size)) + tabsize = Qd.StringWidth(' ' * tabsize) + SetPortFontSettings(port, savesettings) + tabsize = max(tabsize, 1) + self.ted.WESetTabSize(tabsize) + self.SetPort() + Qd.EraseRect(self.ted.WEGetViewRect()) + self.ted.WEUpdate(port.visRgn) + + def getfontsettings(self): + from Carbon import Res + (font, style, size, color) = self.ted.WEGetRunInfo(0)[4] + font = Fm.GetFontName(font) + return (font, style, size, color) + + def setfontsettings(self, (font, style, size, color)): + self.SetPort() + if type(font) <> StringType: + font = Fm.GetFontName(font) + self.fontsettings = (font, style, size, color) + fontid = GetFNum(font) + readonly = self.ted.WEFeatureFlag(WASTEconst.weFReadOnly, -1) + if readonly: + self.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 0) + try: + self.ted.WEFeatureFlag(WASTEconst.weFInhibitRecal, 1) + selstart, selend = self.ted.WEGetSelection() + self.ted.WESetSelection(0, self.ted.WEGetTextLength()) + self.ted.WESetStyle(WASTEconst.weDoFace, (0, 0, 0, (0, 0, 0))) + self.ted.WESetStyle(WASTEconst.weDoFace | + WASTEconst.weDoColor | + WASTEconst.weDoFont | + WASTEconst.weDoSize, + (fontid, style, size, color)) + self.ted.WEFeatureFlag(WASTEconst.weFInhibitRecal, 0) + self.ted.WECalText() + self.ted.WESetSelection(selstart, selend) + finally: + if readonly: + self.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 1) + viewrect = self.ted.WEGetViewRect() + Qd.EraseRect(viewrect) + self.ted.WEUpdate(self._parentwindow.wid.GetWindowPort().visRgn) + self.selectionchanged() + self.updatescrollbars() + + def adjust(self, oldbounds): + self.SetPort() + # Note: if App.DrawThemeEditTextFrame is ever used, it will be necessary + # to unconditionally outset the invalidated rectangles, since Appearance + # frames are drawn outside the bounds. + if self._selected and self._parentwindow._hasselframes: + self.GetWindow().InvalWindowRect(Qd.InsetRect(oldbounds, -3, -3)) + self.GetWindow().InvalWindowRect(Qd.InsetRect(self._bounds, -3, -3)) + else: + self.GetWindow().InvalWindowRect(oldbounds) + self.GetWindow().InvalWindowRect(self._bounds) + viewrect, destrect = self._calctextbounds() + self.ted.WESetViewRect(viewrect) + self.ted.WESetDestRect(destrect) + if self.wrap: + self.ted.WECalText() + if self.ted.WEGetDestRect()[3] < viewrect[1]: + self.selview() + self.updatescrollbars() + + # interface ----------------------- + # selection stuff + def selview(self): + self.ted.WESelView() + + def selectall(self): + self.ted.WESetSelection(0, self.ted.WEGetTextLength()) + self.selectionchanged() + self.updatescrollbars() + + def selectline(self, lineno, charoffset = 0): + newselstart, newselend = self.ted.WEGetLineRange(lineno) + # Autoscroll makes the *end* of the selection visible, which, + # in the case of a whole line, is the beginning of the *next* line. + # So sometimes it leaves our line just above the view rect. + # Let's fool Waste by initially selecting one char less: + self.ted.WESetSelection(newselstart + charoffset, newselend-1) + self.ted.WESetSelection(newselstart + charoffset, newselend) + self.selectionchanged() + self.updatescrollbars() + + def getselection(self): + if self.ted: + return self.ted.WEGetSelection() + else: + return self.selection + + def setselection(self, selstart, selend): + self.selectionchanged() + if self.ted: + self.ted.WESetSelection(selstart, selend) + self.ted.WESelView() + self.updatescrollbars() + else: + self.selection = selstart, selend + + def offsettoline(self, offset): + return self.ted.WEOffsetToLine(offset) + + def countlines(self): + return self.ted.WECountLines() + + def getselectedtext(self): + selstart, selend = self.ted.WEGetSelection() + return self.ted.WEGetText().data[selstart:selend] + + def expandselection(self): + oldselstart, oldselend = self.ted.WEGetSelection() + selstart, selend = min(oldselstart, oldselend), max(oldselstart, oldselend) + if selstart <> selend and chr(self.ted.WEGetChar(selend-1)) == '\r': + selend = selend - 1 + newselstart, dummy = self.ted.WEFindLine(selstart, 1) + dummy, newselend = self.ted.WEFindLine(selend, 1) + if oldselstart <> newselstart or oldselend <> newselend: + self.ted.WESetSelection(newselstart, newselend) + self.updatescrollbars() + self.selectionchanged() + + def insert(self, text): + self.ted.WEInsert(text, None, None) + self.textchanged() + self.selectionchanged() + + # text + def set(self, text): + if not self.ted: + self.temptext = text + else: + self.ted.WEUseText(Res.Resource(text)) + self.ted.WECalText() + self.SetPort() + viewrect, destrect = self._calctextbounds() + self.ted.WESetViewRect(viewrect) + self.ted.WESetDestRect(destrect) + rgn = Qd.NewRgn() + Qd.RectRgn(rgn, viewrect) + Qd.EraseRect(viewrect) + self.draw(rgn) + self.updatescrollbars() + self.textchanged(1) + + def get(self): + if not self._parent: + return self.temptext + else: + return self.ted.WEGetText().data + + # events + def key(self, char, event): + (what, message, when, where, modifiers) = event + if self._enabled and not modifiers & Events.cmdKey or char in Wkeys.arrowkeys: + self.ted.WEKey(ord(char), modifiers) + if char not in Wkeys.navigationkeys: + self.textchanged() + if char not in Wkeys.scrollkeys: + self.selectionchanged() + self.updatescrollbars() + if self._callback: + Wbase.CallbackCall(self._callback, 0, char, modifiers) + + def click(self, point, modifiers): + if not self._enabled: + return + self.ted.WEClick(point, modifiers, Evt.TickCount()) + self.selectionchanged() + self.updatescrollbars() + return 1 + + def idle(self): + self.SetPort() + self.ted.WEIdle() + + def rollover(self, point, onoff): + if onoff: + Wbase.SetCursor("iBeam") + + def activate(self, onoff): + self._activated = onoff + if self._visible: + self.SetPort() + + # DISABLED! There are too many places where it is assumed that + # the frame of an EditText item is 1 pixel, inside the bounds. + #state = [kThemeStateActive, kThemeStateInactive][not onoff] + #App.DrawThemeEditTextFrame(Qd.InsetRect(self._bounds, 1, 1), state) + + if self._selected: + if onoff: + self.ted.WEActivate() + else: + self.ted.WEDeactivate() + self.drawselframe(onoff) + + def select(self, onoff, isclick = 0): + if Wbase.SelectableWidget.select(self, onoff): + return + self.SetPort() + if onoff: + self.ted.WEActivate() + if self._parentwindow._tabbable and not isclick: + self.selectall() + else: + self.ted.WEDeactivate() + self.drawselframe(onoff) + + def draw(self, visRgn = None): + if self._visible: + if not visRgn: + visRgn = self._parentwindow.wid.GetWindowPort().visRgn + self.ted.WEUpdate(visRgn) + + # DISABLED! There are too many places where it is assumed that + # the frame of an EditText item is 1 pixel, inside the bounds. + #state = [kThemeStateActive, kThemeStateInactive][not self._activated] + #App.DrawThemeEditTextFrame(Qd.InsetRect(self._bounds, 1, 1), state) + Qd.FrameRect(self._bounds) + + if self._selected and self._activated: + self.drawselframe(1) + + # scrolling + def scrollpageup(self): + if self._parent._bary and self._parent._bary._enabled: + self.vscroll("++") + + def scrollpagedown(self): + if self._parent._bary and self._parent._bary._enabled: + self.vscroll("--") + + def scrolltop(self): + if self._parent._bary and self._parent._bary._enabled: + self.vscroll(self._parent._bary.getmin()) + if self._parent._barx and self._parent._barx._enabled: + self.hscroll(self._parent._barx.getmin()) + + def scrollbottom(self): + if self._parent._bary and self._parent._bary._enabled: + self.vscroll(self._parent._bary.getmax()) + + # menu handlers + def domenu_copy(self, *args): + selbegin, selend = self.ted.WEGetSelection() + if selbegin == selend: + return + if hasattr(Scrap, 'ZeroScrap'): + Scrap.ZeroScrap() + else: + Scrap.ClearCurrentScrap() + self.ted.WECopy() + self.updatescrollbars() + + def domenu_cut(self, *args): + selbegin, selend = self.ted.WEGetSelection() + if selbegin == selend: + return + if hasattr(Scrap, 'ZeroScrap'): + Scrap.ZeroScrap() + else: + Scrap.ClearCurrentScrap() + self.ted.WECut() + self.updatescrollbars() + self.selview() + self.textchanged() + self.selectionchanged() + if self._callback: + Wbase.CallbackCall(self._callback, 0, "", None) + + def domenu_paste(self, *args): + if not self.ted.WECanPaste(): + return + self.selview() + self.ted.WEPaste() + self.updatescrollbars() + self.textchanged() + self.selectionchanged() + if self._callback: + Wbase.CallbackCall(self._callback, 0, "", None) + + def domenu_clear(self, *args): + self.ted.WEDelete() + self.selview() + self.updatescrollbars() + self.textchanged() + self.selectionchanged() + if self._callback: + Wbase.CallbackCall(self._callback, 0, "", None) + + def domenu_undo(self, *args): + which, redo = self.ted.WEGetUndoInfo() + if not which: + return + self.ted.WEUndo() + self.updatescrollbars() + self.textchanged() + self.selectionchanged() + if self._callback: + Wbase.CallbackCall(self._callback, 0, "", None) + + def can_undo(self, menuitem): + #doundo = self.ted.WEFeatureFlag(WASTEconst.weFUndo, -1) + #print doundo + #if not doundo: + # return 0 + which, redo = self.ted.WEGetUndoInfo() + if which < len(UNDOLABELS): + which = UNDOLABELS[which] + else: + which = "" + if which == None: + return None + if redo: + which = "Redo "+which + else: + which = "Undo "+which + menuitem.settext(which) + return 1 + + def domenu_selectall(self, *args): + self.selectall() + + # private + def getscrollrects(self): + return self.ted.WEGetDestRect(), self.ted.WEGetViewRect() + + def vscroll(self, value): + lineheight = self.ted.WEGetHeight(0, 1) + dr = self.ted.WEGetDestRect() + vr = self.ted.WEGetViewRect() + viewheight = vr[3] - vr[1] + maxdelta = vr[1] - dr[1] + mindelta = vr[3] - dr[3] + if value == "+": + delta = lineheight + elif value == "-": + delta = - lineheight + elif value == "++": + delta = viewheight - lineheight + elif value == "--": + delta = lineheight - viewheight + else: # in thumb + delta = vr[1] - dr[1] - value + delta = min(maxdelta, delta) + delta = max(mindelta, delta) + delta = int(delta) + self.ted.WEScroll(0, delta) + self.updatescrollbars() + + def hscroll(self, value): + dr = self.ted.WEGetDestRect() + vr = self.ted.WEGetViewRect() + destwidth = dr[2] - dr[0] + viewwidth = vr[2] - vr[0] + viewoffset = maxdelta = vr[0] - dr[0] + mindelta = vr[2] - dr[2] + if value == "+": + delta = 32 + elif value == "-": + delta = - 32 + elif value == "++": + delta = 0.5 * (vr[2] - vr[0]) + elif value == "--": + delta = 0.5 * (vr[0] - vr[2]) + else: # in thumb + delta = vr[0] - dr[0] - value + #cur = (32767 * viewoffset) / (destwidth - viewwidth) + #delta = (cur-value)*(destwidth - viewwidth)/32767 + #if abs(delta - viewoffset) <=2: + # # compensate for irritating rounding error + # delta = viewoffset + delta = min(maxdelta, delta) + delta = max(mindelta, delta) + delta = int(delta) + self.ted.WEScroll(delta, 0) + self.updatescrollbars() + + # some internals + def _getflags(self): + flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoMonoStyled + if self.readonly: + flags = flags | WASTEconst.weDoReadOnly + else: + flags = flags | WASTEconst.weDoUndo + return flags + + def _getviewrect(self): + return Qd.InsetRect(self._bounds, self.inset[0], self.inset[1]) + + def _calctextbounds(self): + viewrect = l, t, r, b = self._getviewrect() + if self.ted: + dl, dt, dr, db = self.ted.WEGetDestRect() + vl, vt, vr, vb = self.ted.WEGetViewRect() + yshift = t - vt + if (db - dt) < (b - t): + destrect = viewrect + else: + destrect = l, dt + yshift, r, db + yshift + else: + destrect = viewrect + return viewrect, destrect + class TextEditor(EditText): - - """A text edit widget.""" - - def __init__(self, possize, text="", callback=None, wrap=1, inset=(4, 4), - fontsettings=None, - tabsettings=(32, 0), - readonly=0): - EditText.__init__(self, possize, text, callback, inset, fontsettings, tabsettings, readonly) - self.wrap = wrap - - def _getflags(self): - flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoMonoStyled | \ - WASTEconst.weDoOutlineHilite - if self.readonly: - flags = flags | WASTEconst.weDoReadOnly - else: - flags = flags | WASTEconst.weDoUndo - return flags - - def _getviewrect(self): - l, t, r, b = self._bounds - return (l + 5, t + 2, r, b - 2) - - def _calctextbounds(self): - if self.wrap: - return EditText._calctextbounds(self) - else: - viewrect = l, t, r, b = self._getviewrect() - if self.ted: - dl, dt, dr, db = self.ted.WEGetDestRect() - vl, vt, vr, vb = self.ted.WEGetViewRect() - xshift = l - vl - yshift = t - vt - if (db - dt) < (b - t): - yshift = t - dt - destrect = (dl + xshift, dt + yshift, dr + xshift, db + yshift) - else: - destrect = (l, t, r + 5000, b) - return viewrect, destrect - - def draw(self, visRgn = None): - if self._visible: - if not visRgn: - visRgn = self._parentwindow.wid.GetWindowPort().visRgn - self.ted.WEUpdate(visRgn) - if self._selected and self._activated: - self.drawselframe(1) - - def activate(self, onoff): - self._activated = onoff - if self._visible: - self.SetPort() - # doesn't draw frame, as EditText.activate does - if self._selected: - if onoff: - self.ted.WEActivate() - else: - self.ted.WEDeactivate() - self.drawselframe(onoff) + + """A text edit widget.""" + + def __init__(self, possize, text="", callback=None, wrap=1, inset=(4, 4), + fontsettings=None, + tabsettings=(32, 0), + readonly=0): + EditText.__init__(self, possize, text, callback, inset, fontsettings, tabsettings, readonly) + self.wrap = wrap + + def _getflags(self): + flags = WASTEconst.weDoAutoScroll | WASTEconst.weDoMonoStyled | \ + WASTEconst.weDoOutlineHilite + if self.readonly: + flags = flags | WASTEconst.weDoReadOnly + else: + flags = flags | WASTEconst.weDoUndo + return flags + + def _getviewrect(self): + l, t, r, b = self._bounds + return (l + 5, t + 2, r, b - 2) + + def _calctextbounds(self): + if self.wrap: + return EditText._calctextbounds(self) + else: + viewrect = l, t, r, b = self._getviewrect() + if self.ted: + dl, dt, dr, db = self.ted.WEGetDestRect() + vl, vt, vr, vb = self.ted.WEGetViewRect() + xshift = l - vl + yshift = t - vt + if (db - dt) < (b - t): + yshift = t - dt + destrect = (dl + xshift, dt + yshift, dr + xshift, db + yshift) + else: + destrect = (l, t, r + 5000, b) + return viewrect, destrect + + def draw(self, visRgn = None): + if self._visible: + if not visRgn: + visRgn = self._parentwindow.wid.GetWindowPort().visRgn + self.ted.WEUpdate(visRgn) + if self._selected and self._activated: + self.drawselframe(1) + + def activate(self, onoff): + self._activated = onoff + if self._visible: + self.SetPort() + # doesn't draw frame, as EditText.activate does + if self._selected: + if onoff: + self.ted.WEActivate() + else: + self.ted.WEDeactivate() + self.drawselframe(onoff) import re @@ -658,479 +658,479 @@ kCommentColor = (0, 0, 0xb000) class PyEditor(TextEditor): - - """A specialized Python source edit widget""" - - def __init__(self, possize, text="", callback=None, inset=(4, 4), - fontsettings=None, - tabsettings=(32, 0), - readonly=0, - debugger=None, - file=''): - TextEditor.__init__(self, possize, text, callback, 0, inset, fontsettings, tabsettings, readonly) - self.bind("cmd[", self.domenu_shiftleft) - self.bind("cmd]", self.domenu_shiftright) - self.bind("cmdshift[", self.domenu_uncomment) - self.bind("cmdshift]", self.domenu_comment) - self.bind("cmdshiftd", self.alldirty) - self.file = file # only for debugger reference - self._debugger = debugger - if debugger: - debugger.register_editor(self, self.file) - self._dirty = (0, None) - self.do_fontify = 0 - - #def open(self): - # TextEditor.open(self) - # if self.do_fontify: - # self.fontify() - # self._dirty = (None, None) - - def _getflags(self): - flags = (WASTEconst.weDoDrawOffscreen | WASTEconst.weDoUseTempMem | - WASTEconst.weDoAutoScroll | WASTEconst.weDoOutlineHilite) - if self.readonly: - flags = flags | WASTEconst.weDoReadOnly - else: - flags = flags | WASTEconst.weDoUndo - return flags - - def textchanged(self, all=0): - self.changed = 1 - if all: - self._dirty = (0, None) - return - oldsel = self.oldselection - sel = self.getselection() - if not sel: - # XXX what to do? - return - selstart, selend = sel - selstart, selend = min(selstart, selend), max(selstart, selend) - if oldsel: - oldselstart, oldselend = min(oldsel), max(oldsel) - selstart, selend = min(selstart, oldselstart), max(selend, oldselend) - startline = self.offsettoline(selstart) - endline = self.offsettoline(selend) - selstart, _ = self.ted.WEGetLineRange(startline) - _, selend = self.ted.WEGetLineRange(endline) - if selstart > 0: - selstart = selstart - 1 - self._dirty = (selstart, selend) - - def idle(self): - self.SetPort() - self.ted.WEIdle() - if not self.do_fontify: - return - start, end = self._dirty - if start is None: - return - textLength = self.ted.WEGetTextLength() - if end is None: - end = textLength - if start >= end: - self._dirty = (None, None) - else: - self.fontify(start, end) - self._dirty = (None, None) - - def alldirty(self, *args): - self._dirty = (0, None) - - def fontify(self, start=0, end=None): - #W.SetCursor('watch') - if self.readonly: - self.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 0) - self.ted.WEFeatureFlag(WASTEconst.weFOutlineHilite, 0) - self.ted.WEDeactivate() - self.ted.WEFeatureFlag(WASTEconst.weFAutoScroll, 0) - self.ted.WEFeatureFlag(WASTEconst.weFUndo, 0) - pytext = self.get().replace("\r", "\n") - if end is None: - end = len(pytext) - else: - end = min(end, len(pytext)) - selstart, selend = self.ted.WEGetSelection() - self.ted.WESetSelection(start, end) - self.ted.WESetStyle(WASTEconst.weDoFace | WASTEconst.weDoColor, - (0, 0, 12, (0, 0, 0))) - - tags = PyFontify.fontify(pytext, start, end) - styles = { - 'string': (WASTEconst.weDoColor, (0, 0, 0, kStringColor)), - 'keyword': (WASTEconst.weDoFace, (0, 1, 0, (0, 0, 0))), - 'comment': (WASTEconst.weDoFace | WASTEconst.weDoColor, (0, 0, 0, kCommentColor)), - 'identifier': (WASTEconst.weDoColor, (0, 0, 0, (0xbfff, 0, 0))) - } - setselection = self.ted.WESetSelection - setstyle = self.ted.WESetStyle - for tag, start, end, sublist in tags: - setselection(start, end) - mode, style = styles[tag] - setstyle(mode, style) - self.ted.WESetSelection(selstart, selend) - self.SetPort() - self.ted.WEFeatureFlag(WASTEconst.weFAutoScroll, 1) - self.ted.WEFeatureFlag(WASTEconst.weFUndo, 1) - self.ted.WEActivate() - self.ted.WEFeatureFlag(WASTEconst.weFOutlineHilite, 1) - if self.readonly: - self.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 1) - - def domenu_shiftleft(self): - self.expandselection() - selstart, selend = self.ted.WEGetSelection() - selstart, selend = min(selstart, selend), max(selstart, selend) - snippet = self.getselectedtext() - lines = string.split(snippet, '\r') - for i in range(len(lines)): - if lines[i][:1] == '\t': - lines[i] = lines[i][1:] - snippet = string.join(lines, '\r') - self.insert(snippet) - self.ted.WESetSelection(selstart, selstart + len(snippet)) - - def domenu_shiftright(self): - self.expandselection() - selstart, selend = self.ted.WEGetSelection() - selstart, selend = min(selstart, selend), max(selstart, selend) - snippet = self.getselectedtext() - lines = string.split(snippet, '\r') - for i in range(len(lines) - (not lines[-1])): - lines[i] = '\t' + lines[i] - snippet = string.join(lines, '\r') - self.insert(snippet) - self.ted.WESetSelection(selstart, selstart + len(snippet)) - - def domenu_uncomment(self): - self.expandselection() - selstart, selend = self.ted.WEGetSelection() - selstart, selend = min(selstart, selend), max(selstart, selend) - snippet = self.getselectedtext() - lines = string.split(snippet, '\r') - for i in range(len(lines)): - m = commentPat.match(lines[i]) - if m: - pos = m.start(1) - lines[i] = lines[i][:pos] + lines[i][pos+1:] - snippet = string.join(lines, '\r') - self.insert(snippet) - self.ted.WESetSelection(selstart, selstart + len(snippet)) - - def domenu_comment(self): - self.expandselection() - selstart, selend = self.ted.WEGetSelection() - selstart, selend = min(selstart, selend), max(selstart, selend) - snippet = self.getselectedtext() - lines = string.split(snippet, '\r') - indent = 3000 # arbitrary large number... - for line in lines: - if string.strip(line): - m = indentPat.match(line) - if m: - indent = min(indent, m.regs[0][1]) - else: - indent = 0 - break - for i in range(len(lines) - (not lines[-1])): - lines[i] = lines[i][:indent] + "#" + lines[i][indent:] - snippet = string.join(lines, '\r') - self.insert(snippet) - self.ted.WESetSelection(selstart, selstart + len(snippet)) - - def setfile(self, file): - self.file = file - - def set(self, text, file = ''): - oldfile = self.file - self.file = file - if self._debugger: - self._debugger.unregister_editor(self, oldfile) - self._debugger.register_editor(self, file) - TextEditor.set(self, text) - - def close(self): - if self._debugger: - self._debugger.unregister_editor(self, self.file) - self._debugger = None - TextEditor.close(self) - - def click(self, point, modifiers): - if not self._enabled: - return - if self._debugger and self.pt_in_breaks(point): - self.breakhit(point, modifiers) - elif self._debugger: - bl, bt, br, bb = self._getbreakrect() - Qd.EraseRect((bl, bt, br-1, bb)) - TextEditor.click(self, point, modifiers) - self.drawbreakpoints() - else: - TextEditor.click(self, point, modifiers) - if self.ted.WEGetClickCount() >= 3: - # select block with our indent - lines = string.split(self.get(), '\r') - selstart, selend = self.ted.WEGetSelection() - lineno = self.ted.WEOffsetToLine(selstart) - tabs = 0 - line = lines[lineno] - while line[tabs:] and line[tabs] == '\t': - tabs = tabs + 1 - tabstag = '\t' * tabs - fromline = 0 - toline = len(lines) - if tabs: - for i in range(lineno - 1, -1, -1): - line = lines[i] - if line[:tabs] <> tabstag: - fromline = i + 1 - break - for i in range(lineno + 1, toline): - line = lines[i] - if line[:tabs] <> tabstag: - toline = i - 1 - break - selstart, dummy = self.ted.WEGetLineRange(fromline) - dummy, selend = self.ted.WEGetLineRange(toline) - self.ted.WESetSelection(selstart, selend) - - def breakhit(self, point, modifiers): - if not self.file: - return - destrect = self.ted.WEGetDestRect() - offset, edge = self.ted.WEGetOffset(point) - lineno = self.ted.WEOffsetToLine(offset) + 1 - if point[1] <= destrect[3]: - self._debugger.clear_breaks_above(self.file, self.countlines()) - self._debugger.toggle_break(self.file, lineno) - else: - self._debugger.clear_breaks_above(self.file, lineno) - - def key(self, char, event): - (what, message, when, where, modifiers) = event - if modifiers & Events.cmdKey and not char in Wkeys.arrowkeys: - return - if char == '\r': - selstart, selend = self.ted.WEGetSelection() - selstart, selend = min(selstart, selend), max(selstart, selend) - lastchar = chr(self.ted.WEGetChar(selstart-1)) - if lastchar <> '\r' and selstart: - pos, dummy = self.ted.WEFindLine(selstart, 0) - lineres = Res.Resource('') - self.ted.WECopyRange(pos, selstart, lineres, None, None) - line = lineres.data + '\n' - tabcount = self.extratabs(line) - self.ted.WEKey(ord('\r'), 0) - for i in range(tabcount): - self.ted.WEKey(ord('\t'), 0) - else: - self.ted.WEKey(ord('\r'), 0) - elif char in ')]}': - self.ted.WEKey(ord(char), modifiers) - self.balanceparens(char) - else: - self.ted.WEKey(ord(char), modifiers) - if char not in Wkeys.navigationkeys: - self.textchanged() - self.selectionchanged() - self.updatescrollbars() - - def balanceparens(self, char): - if char == ')': - target = '(' - elif char == ']': - target = '[' - elif char == '}': - target = '{' - recursionlevel = 1 - selstart, selend = self.ted.WEGetSelection() - count = min(selstart, selend) - 2 - mincount = max(0, count - 2048) - lastquote = None - while count > mincount: - testchar = chr(self.ted.WEGetChar(count)) - if testchar in "\"'" and chr(self.ted.WEGetChar(count - 1)) <> '\\': - if lastquote == testchar: - recursionlevel = recursionlevel - 1 - lastquote = None - elif not lastquote: - recursionlevel = recursionlevel + 1 - lastquote = testchar - elif not lastquote and testchar == char: - recursionlevel = recursionlevel + 1 - elif not lastquote and testchar == target: - recursionlevel = recursionlevel - 1 - if recursionlevel == 0: - import time - autoscroll = self.ted.WEFeatureFlag(WASTEconst.weFAutoScroll, -1) - if autoscroll: - self.ted.WEFeatureFlag(WASTEconst.weFAutoScroll, 0) - self.ted.WESetSelection(count, count + 1) - self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None) # needed under OSX - time.sleep(0.2) - self.ted.WESetSelection(selstart, selend) - if autoscroll: - self.ted.WEFeatureFlag(WASTEconst.weFAutoScroll, 1) - break - count = count - 1 - - def extratabs(self, line): - tabcount = 0 - for c in line: - if c <> '\t': - break - tabcount = tabcount + 1 - last = 0 - cleanline = '' - tags = PyFontify.fontify(line) - # strip comments and strings - for tag, start, end, sublist in tags: - if tag in ('string', 'comment'): - cleanline = cleanline + line[last:start] - last = end - cleanline = cleanline + line[last:] - cleanline = string.strip(cleanline) - if cleanline and cleanline[-1] == ':': - tabcount = tabcount + 1 - else: - # extra indent after unbalanced (, [ or { - for open, close in (('(', ')'), ('[', ']'), ('{', '}')): - count = string.count(cleanline, open) - if count and count > string.count(cleanline, close): - tabcount = tabcount + 2 - break - return tabcount - - def rollover(self, point, onoff): - if onoff: - if self._debugger and self.pt_in_breaks(point): - Wbase.SetCursor("arrow") - else: - Wbase.SetCursor("iBeam") - - def draw(self, visRgn = None): - TextEditor.draw(self, visRgn) - if self._debugger: - self.drawbreakpoints() - - def showbreakpoints(self, onoff): - if (not not self._debugger) <> onoff: - if onoff: - if not __debug__: - import W - raise W.AlertError, "Can't debug in \"Optimize bytecode\" mode.\r(see \"Default startup options\" in EditPythonPreferences)" - import PyDebugger - self._debugger = PyDebugger.getdebugger() - self._debugger.register_editor(self, self.file) - elif self._debugger: - self._debugger.unregister_editor(self, self.file) - self._debugger = None - self.adjust(self._bounds) - - def togglebreakpoints(self): - self.showbreakpoints(not self._debugger) - - def clearbreakpoints(self): - if self.file: - self._debugger.clear_all_file_breaks(self.file) - - def editbreakpoints(self): - if self._debugger: - self._debugger.edit_breaks() - self._debugger.breaksviewer.selectfile(self.file) - - def drawbreakpoints(self, eraseall = 0): - breakrect = bl, bt, br, bb = self._getbreakrect() - br = br - 1 - self.SetPort() - Qd.PenPat(Qd.GetQDGlobalsGray()) - Qd.PaintRect((br, bt, br + 1, bb)) - Qd.PenNormal() - self._parentwindow.tempcliprect(breakrect) - Qd.RGBForeColor((0xffff, 0, 0)) - try: - lasttop = bt - self_ted = self.ted - Qd_PaintOval = Qd.PaintOval - Qd_EraseRect = Qd.EraseRect - for lineno in self._debugger.get_file_breaks(self.file): - start, end = self_ted.WEGetLineRange(lineno - 1) - if lineno <> self_ted.WEOffsetToLine(start) + 1: - # breakpoints beyond our text: erase rest, and back out - Qd_EraseRect((bl, lasttop, br, bb)) - break - (x, y), h = self_ted.WEGetPoint(start, 0) - bottom = y + h - #print y, (lasttop, bottom) - if bottom > lasttop: - Qd_EraseRect((bl, lasttop, br, y + h * eraseall)) - lasttop = bottom - redbullet = bl + 2, y + 3, bl + 8, y + 9 - Qd_PaintOval(redbullet) - else: - Qd_EraseRect((bl, lasttop, br, bb)) - Qd.RGBForeColor((0, 0, 0)) - finally: - self._parentwindow.restoreclip() - - def updatescrollbars(self): - if self._debugger: - self.drawbreakpoints(1) - TextEditor.updatescrollbars(self) - - def pt_in_breaks(self, point): - return Qd.PtInRect(point, self._getbreakrect()) - - def _getbreakrect(self): - if self._debugger: - l, t, r, b = self._bounds - return (l+1, t+1, l + 12, b-1) - else: - return (0, 0, 0, 0) - - def _getviewrect(self): - l, t, r, b = self._bounds - if self._debugger: - return (l + 17, t + 2, r, b - 2) - else: - return (l + 5, t + 2, r, b - 2) - - def _calctextbounds(self): - viewrect = l, t, r, b = self._getviewrect() - if self.ted: - dl, dt, dr, db = self.ted.WEGetDestRect() - vl, vt, vr, vb = self.ted.WEGetViewRect() - xshift = l - vl - yshift = t - vt - if (db - dt) < (b - t): - yshift = t - dt - destrect = (dl + xshift, dt + yshift, dr + xshift, db + yshift) - else: - destrect = (l, t, r + 5000, b) - return viewrect, destrect + + """A specialized Python source edit widget""" + + def __init__(self, possize, text="", callback=None, inset=(4, 4), + fontsettings=None, + tabsettings=(32, 0), + readonly=0, + debugger=None, + file=''): + TextEditor.__init__(self, possize, text, callback, 0, inset, fontsettings, tabsettings, readonly) + self.bind("cmd[", self.domenu_shiftleft) + self.bind("cmd]", self.domenu_shiftright) + self.bind("cmdshift[", self.domenu_uncomment) + self.bind("cmdshift]", self.domenu_comment) + self.bind("cmdshiftd", self.alldirty) + self.file = file # only for debugger reference + self._debugger = debugger + if debugger: + debugger.register_editor(self, self.file) + self._dirty = (0, None) + self.do_fontify = 0 + + #def open(self): + # TextEditor.open(self) + # if self.do_fontify: + # self.fontify() + # self._dirty = (None, None) + + def _getflags(self): + flags = (WASTEconst.weDoDrawOffscreen | WASTEconst.weDoUseTempMem | + WASTEconst.weDoAutoScroll | WASTEconst.weDoOutlineHilite) + if self.readonly: + flags = flags | WASTEconst.weDoReadOnly + else: + flags = flags | WASTEconst.weDoUndo + return flags + + def textchanged(self, all=0): + self.changed = 1 + if all: + self._dirty = (0, None) + return + oldsel = self.oldselection + sel = self.getselection() + if not sel: + # XXX what to do? + return + selstart, selend = sel + selstart, selend = min(selstart, selend), max(selstart, selend) + if oldsel: + oldselstart, oldselend = min(oldsel), max(oldsel) + selstart, selend = min(selstart, oldselstart), max(selend, oldselend) + startline = self.offsettoline(selstart) + endline = self.offsettoline(selend) + selstart, _ = self.ted.WEGetLineRange(startline) + _, selend = self.ted.WEGetLineRange(endline) + if selstart > 0: + selstart = selstart - 1 + self._dirty = (selstart, selend) + + def idle(self): + self.SetPort() + self.ted.WEIdle() + if not self.do_fontify: + return + start, end = self._dirty + if start is None: + return + textLength = self.ted.WEGetTextLength() + if end is None: + end = textLength + if start >= end: + self._dirty = (None, None) + else: + self.fontify(start, end) + self._dirty = (None, None) + + def alldirty(self, *args): + self._dirty = (0, None) + + def fontify(self, start=0, end=None): + #W.SetCursor('watch') + if self.readonly: + self.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 0) + self.ted.WEFeatureFlag(WASTEconst.weFOutlineHilite, 0) + self.ted.WEDeactivate() + self.ted.WEFeatureFlag(WASTEconst.weFAutoScroll, 0) + self.ted.WEFeatureFlag(WASTEconst.weFUndo, 0) + pytext = self.get().replace("\r", "\n") + if end is None: + end = len(pytext) + else: + end = min(end, len(pytext)) + selstart, selend = self.ted.WEGetSelection() + self.ted.WESetSelection(start, end) + self.ted.WESetStyle(WASTEconst.weDoFace | WASTEconst.weDoColor, + (0, 0, 12, (0, 0, 0))) + + tags = PyFontify.fontify(pytext, start, end) + styles = { + 'string': (WASTEconst.weDoColor, (0, 0, 0, kStringColor)), + 'keyword': (WASTEconst.weDoFace, (0, 1, 0, (0, 0, 0))), + 'comment': (WASTEconst.weDoFace | WASTEconst.weDoColor, (0, 0, 0, kCommentColor)), + 'identifier': (WASTEconst.weDoColor, (0, 0, 0, (0xbfff, 0, 0))) + } + setselection = self.ted.WESetSelection + setstyle = self.ted.WESetStyle + for tag, start, end, sublist in tags: + setselection(start, end) + mode, style = styles[tag] + setstyle(mode, style) + self.ted.WESetSelection(selstart, selend) + self.SetPort() + self.ted.WEFeatureFlag(WASTEconst.weFAutoScroll, 1) + self.ted.WEFeatureFlag(WASTEconst.weFUndo, 1) + self.ted.WEActivate() + self.ted.WEFeatureFlag(WASTEconst.weFOutlineHilite, 1) + if self.readonly: + self.ted.WEFeatureFlag(WASTEconst.weFReadOnly, 1) + + def domenu_shiftleft(self): + self.expandselection() + selstart, selend = self.ted.WEGetSelection() + selstart, selend = min(selstart, selend), max(selstart, selend) + snippet = self.getselectedtext() + lines = string.split(snippet, '\r') + for i in range(len(lines)): + if lines[i][:1] == '\t': + lines[i] = lines[i][1:] + snippet = string.join(lines, '\r') + self.insert(snippet) + self.ted.WESetSelection(selstart, selstart + len(snippet)) + + def domenu_shiftright(self): + self.expandselection() + selstart, selend = self.ted.WEGetSelection() + selstart, selend = min(selstart, selend), max(selstart, selend) + snippet = self.getselectedtext() + lines = string.split(snippet, '\r') + for i in range(len(lines) - (not lines[-1])): + lines[i] = '\t' + lines[i] + snippet = string.join(lines, '\r') + self.insert(snippet) + self.ted.WESetSelection(selstart, selstart + len(snippet)) + + def domenu_uncomment(self): + self.expandselection() + selstart, selend = self.ted.WEGetSelection() + selstart, selend = min(selstart, selend), max(selstart, selend) + snippet = self.getselectedtext() + lines = string.split(snippet, '\r') + for i in range(len(lines)): + m = commentPat.match(lines[i]) + if m: + pos = m.start(1) + lines[i] = lines[i][:pos] + lines[i][pos+1:] + snippet = string.join(lines, '\r') + self.insert(snippet) + self.ted.WESetSelection(selstart, selstart + len(snippet)) + + def domenu_comment(self): + self.expandselection() + selstart, selend = self.ted.WEGetSelection() + selstart, selend = min(selstart, selend), max(selstart, selend) + snippet = self.getselectedtext() + lines = string.split(snippet, '\r') + indent = 3000 # arbitrary large number... + for line in lines: + if string.strip(line): + m = indentPat.match(line) + if m: + indent = min(indent, m.regs[0][1]) + else: + indent = 0 + break + for i in range(len(lines) - (not lines[-1])): + lines[i] = lines[i][:indent] + "#" + lines[i][indent:] + snippet = string.join(lines, '\r') + self.insert(snippet) + self.ted.WESetSelection(selstart, selstart + len(snippet)) + + def setfile(self, file): + self.file = file + + def set(self, text, file = ''): + oldfile = self.file + self.file = file + if self._debugger: + self._debugger.unregister_editor(self, oldfile) + self._debugger.register_editor(self, file) + TextEditor.set(self, text) + + def close(self): + if self._debugger: + self._debugger.unregister_editor(self, self.file) + self._debugger = None + TextEditor.close(self) + + def click(self, point, modifiers): + if not self._enabled: + return + if self._debugger and self.pt_in_breaks(point): + self.breakhit(point, modifiers) + elif self._debugger: + bl, bt, br, bb = self._getbreakrect() + Qd.EraseRect((bl, bt, br-1, bb)) + TextEditor.click(self, point, modifiers) + self.drawbreakpoints() + else: + TextEditor.click(self, point, modifiers) + if self.ted.WEGetClickCount() >= 3: + # select block with our indent + lines = string.split(self.get(), '\r') + selstart, selend = self.ted.WEGetSelection() + lineno = self.ted.WEOffsetToLine(selstart) + tabs = 0 + line = lines[lineno] + while line[tabs:] and line[tabs] == '\t': + tabs = tabs + 1 + tabstag = '\t' * tabs + fromline = 0 + toline = len(lines) + if tabs: + for i in range(lineno - 1, -1, -1): + line = lines[i] + if line[:tabs] <> tabstag: + fromline = i + 1 + break + for i in range(lineno + 1, toline): + line = lines[i] + if line[:tabs] <> tabstag: + toline = i - 1 + break + selstart, dummy = self.ted.WEGetLineRange(fromline) + dummy, selend = self.ted.WEGetLineRange(toline) + self.ted.WESetSelection(selstart, selend) + + def breakhit(self, point, modifiers): + if not self.file: + return + destrect = self.ted.WEGetDestRect() + offset, edge = self.ted.WEGetOffset(point) + lineno = self.ted.WEOffsetToLine(offset) + 1 + if point[1] <= destrect[3]: + self._debugger.clear_breaks_above(self.file, self.countlines()) + self._debugger.toggle_break(self.file, lineno) + else: + self._debugger.clear_breaks_above(self.file, lineno) + + def key(self, char, event): + (what, message, when, where, modifiers) = event + if modifiers & Events.cmdKey and not char in Wkeys.arrowkeys: + return + if char == '\r': + selstart, selend = self.ted.WEGetSelection() + selstart, selend = min(selstart, selend), max(selstart, selend) + lastchar = chr(self.ted.WEGetChar(selstart-1)) + if lastchar <> '\r' and selstart: + pos, dummy = self.ted.WEFindLine(selstart, 0) + lineres = Res.Resource('') + self.ted.WECopyRange(pos, selstart, lineres, None, None) + line = lineres.data + '\n' + tabcount = self.extratabs(line) + self.ted.WEKey(ord('\r'), 0) + for i in range(tabcount): + self.ted.WEKey(ord('\t'), 0) + else: + self.ted.WEKey(ord('\r'), 0) + elif char in ')]}': + self.ted.WEKey(ord(char), modifiers) + self.balanceparens(char) + else: + self.ted.WEKey(ord(char), modifiers) + if char not in Wkeys.navigationkeys: + self.textchanged() + self.selectionchanged() + self.updatescrollbars() + + def balanceparens(self, char): + if char == ')': + target = '(' + elif char == ']': + target = '[' + elif char == '}': + target = '{' + recursionlevel = 1 + selstart, selend = self.ted.WEGetSelection() + count = min(selstart, selend) - 2 + mincount = max(0, count - 2048) + lastquote = None + while count > mincount: + testchar = chr(self.ted.WEGetChar(count)) + if testchar in "\"'" and chr(self.ted.WEGetChar(count - 1)) <> '\\': + if lastquote == testchar: + recursionlevel = recursionlevel - 1 + lastquote = None + elif not lastquote: + recursionlevel = recursionlevel + 1 + lastquote = testchar + elif not lastquote and testchar == char: + recursionlevel = recursionlevel + 1 + elif not lastquote and testchar == target: + recursionlevel = recursionlevel - 1 + if recursionlevel == 0: + import time + autoscroll = self.ted.WEFeatureFlag(WASTEconst.weFAutoScroll, -1) + if autoscroll: + self.ted.WEFeatureFlag(WASTEconst.weFAutoScroll, 0) + self.ted.WESetSelection(count, count + 1) + self._parentwindow.wid.GetWindowPort().QDFlushPortBuffer(None) # needed under OSX + time.sleep(0.2) + self.ted.WESetSelection(selstart, selend) + if autoscroll: + self.ted.WEFeatureFlag(WASTEconst.weFAutoScroll, 1) + break + count = count - 1 + + def extratabs(self, line): + tabcount = 0 + for c in line: + if c <> '\t': + break + tabcount = tabcount + 1 + last = 0 + cleanline = '' + tags = PyFontify.fontify(line) + # strip comments and strings + for tag, start, end, sublist in tags: + if tag in ('string', 'comment'): + cleanline = cleanline + line[last:start] + last = end + cleanline = cleanline + line[last:] + cleanline = string.strip(cleanline) + if cleanline and cleanline[-1] == ':': + tabcount = tabcount + 1 + else: + # extra indent after unbalanced (, [ or { + for open, close in (('(', ')'), ('[', ']'), ('{', '}')): + count = string.count(cleanline, open) + if count and count > string.count(cleanline, close): + tabcount = tabcount + 2 + break + return tabcount + + def rollover(self, point, onoff): + if onoff: + if self._debugger and self.pt_in_breaks(point): + Wbase.SetCursor("arrow") + else: + Wbase.SetCursor("iBeam") + + def draw(self, visRgn = None): + TextEditor.draw(self, visRgn) + if self._debugger: + self.drawbreakpoints() + + def showbreakpoints(self, onoff): + if (not not self._debugger) <> onoff: + if onoff: + if not __debug__: + import W + raise W.AlertError, "Can't debug in \"Optimize bytecode\" mode.\r(see \"Default startup options\" in EditPythonPreferences)" + import PyDebugger + self._debugger = PyDebugger.getdebugger() + self._debugger.register_editor(self, self.file) + elif self._debugger: + self._debugger.unregister_editor(self, self.file) + self._debugger = None + self.adjust(self._bounds) + + def togglebreakpoints(self): + self.showbreakpoints(not self._debugger) + + def clearbreakpoints(self): + if self.file: + self._debugger.clear_all_file_breaks(self.file) + + def editbreakpoints(self): + if self._debugger: + self._debugger.edit_breaks() + self._debugger.breaksviewer.selectfile(self.file) + + def drawbreakpoints(self, eraseall = 0): + breakrect = bl, bt, br, bb = self._getbreakrect() + br = br - 1 + self.SetPort() + Qd.PenPat(Qd.GetQDGlobalsGray()) + Qd.PaintRect((br, bt, br + 1, bb)) + Qd.PenNormal() + self._parentwindow.tempcliprect(breakrect) + Qd.RGBForeColor((0xffff, 0, 0)) + try: + lasttop = bt + self_ted = self.ted + Qd_PaintOval = Qd.PaintOval + Qd_EraseRect = Qd.EraseRect + for lineno in self._debugger.get_file_breaks(self.file): + start, end = self_ted.WEGetLineRange(lineno - 1) + if lineno <> self_ted.WEOffsetToLine(start) + 1: + # breakpoints beyond our text: erase rest, and back out + Qd_EraseRect((bl, lasttop, br, bb)) + break + (x, y), h = self_ted.WEGetPoint(start, 0) + bottom = y + h + #print y, (lasttop, bottom) + if bottom > lasttop: + Qd_EraseRect((bl, lasttop, br, y + h * eraseall)) + lasttop = bottom + redbullet = bl + 2, y + 3, bl + 8, y + 9 + Qd_PaintOval(redbullet) + else: + Qd_EraseRect((bl, lasttop, br, bb)) + Qd.RGBForeColor((0, 0, 0)) + finally: + self._parentwindow.restoreclip() + + def updatescrollbars(self): + if self._debugger: + self.drawbreakpoints(1) + TextEditor.updatescrollbars(self) + + def pt_in_breaks(self, point): + return Qd.PtInRect(point, self._getbreakrect()) + + def _getbreakrect(self): + if self._debugger: + l, t, r, b = self._bounds + return (l+1, t+1, l + 12, b-1) + else: + return (0, 0, 0, 0) + + def _getviewrect(self): + l, t, r, b = self._bounds + if self._debugger: + return (l + 17, t + 2, r, b - 2) + else: + return (l + 5, t + 2, r, b - 2) + + def _calctextbounds(self): + viewrect = l, t, r, b = self._getviewrect() + if self.ted: + dl, dt, dr, db = self.ted.WEGetDestRect() + vl, vt, vr, vb = self.ted.WEGetViewRect() + xshift = l - vl + yshift = t - vt + if (db - dt) < (b - t): + yshift = t - dt + destrect = (dl + xshift, dt + yshift, dr + xshift, db + yshift) + else: + destrect = (l, t, r + 5000, b) + return viewrect, destrect def GetFNum(fontname): - """Same as Fm.GetFNum(), but maps a missing font to Monaco instead of the system font.""" - if fontname <> Fm.GetFontName(0): - fontid = Fm.GetFNum(fontname) - if fontid == 0: - fontid = Fonts.monaco - else: - fontid = 0 - return fontid + """Same as Fm.GetFNum(), but maps a missing font to Monaco instead of the system font.""" + if fontname <> Fm.GetFontName(0): + fontid = Fm.GetFNum(fontname) + if fontid == 0: + fontid = Fonts.monaco + else: + fontid = 0 + return fontid # b/w compat. Anyone using this? GetFName = Fm.GetFontName def GetPortFontSettings(port): - return Fm.GetFontName(port.GetPortTextFont()), port.GetPortTextFace(), port.GetPortTextSize() + return Fm.GetFontName(port.GetPortTextFont()), port.GetPortTextFace(), port.GetPortTextSize() def SetPortFontSettings(port, (font, face, size)): - saveport = Qd.GetPort() - Qd.SetPort(port) - Qd.TextFont(GetFNum(font)) - Qd.TextFace(face) - Qd.TextSize(size) - Qd.SetPort(saveport) + saveport = Qd.GetPort() + Qd.SetPort(port) + Qd.TextFont(GetFNum(font)) + Qd.TextFace(face) + Qd.TextSize(size) + Qd.SetPort(saveport) diff --git a/Mac/Tools/IDE/Wtraceback.py b/Mac/Tools/IDE/Wtraceback.py index 90a25fe..e84349d 100644 --- a/Mac/Tools/IDE/Wtraceback.py +++ b/Mac/Tools/IDE/Wtraceback.py @@ -7,182 +7,181 @@ from Carbon import List class TraceBack: - - def __init__(self, title = "Traceback"): - app = W.getapplication() # checks if W is properly initialized - self.title = title - self.w = None - self.closed = 1 - self.start = 0 - self.lastwindowtitle = "" - self.bounds = (360, 298) - - def traceback(self, start = 0, lastwindowtitle = ""): - try: - self.lastwindowtitle = lastwindowtitle - self.start = start - self.type, self.value, self.tb = sys.exc_info() - if self.type is not SyntaxError: - self.show() - if type(self.type) == types.ClassType: - errortext = self.type.__name__ - else: - errortext = str(self.type) - value = str(self.value) - if self.value and value: - errortext = errortext + ": " + value - self.w.text.set(errortext) - self.buildtblist() - self.w.list.set(self.textlist) - self.w.list.setselection([len(self.textlist) - 1]) - self.w.wid.SelectWindow() - self.closed = 0 - else: - self.syntaxerror() - except: - traceback.print_exc() - - def syntaxerror(self): - try: - value, (filename, lineno, charno, line) = self.value - except: - filename = "" - lineno = None - value = self.value - if not filename and self.lastwindowtitle: - filename = self.lastwindowtitle - elif not filename: - filename = "<unknown>" - if filename and os.path.exists(filename): - filename = os.path.split(filename)[1] - if lineno and charno is not None: - charno = charno - 1 - text = str(value) + '\rFile: "' + str(filename) + '", line ' + str(lineno) + '\r\r' + line[:charno] + "\xa5" + line[charno:-1] - else: - text = str(value) + '\rFile: "' + str(filename) + '"' - self.syntaxdialog = W.ModalDialog((360, 120), "Syntax Error") - self.syntaxdialog.text = W.TextBox((10, 10, -10, -40), text) - self.syntaxdialog.cancel = W.Button((-190, -32, 80, 16), "Cancel", self.syntaxclose) - self.syntaxdialog.edit = W.Button((-100, -32, 80, 16), "Edit", self.syntaxedit) - self.syntaxdialog.setdefaultbutton(self.syntaxdialog.edit) - self.syntaxdialog.bind("cmd.", self.syntaxdialog.cancel.push) - self.syntaxdialog.open() - - def syntaxclose(self): - self.syntaxdialog.close() - del self.syntaxdialog - - def syntaxedit(self): - try: - value, (filename, lineno, charno, line) = self.value - except: - filename = "" - lineno = None - if not filename and self.lastwindowtitle: - filename = self.lastwindowtitle - elif not filename: - filename = "<unknown>" - self.syntaxclose() - if lineno: - if charno is None: - charno = 1 - W.getapplication().openscript(filename, lineno, charno - 1) - else: - W.getapplication().openscript(filename) - - def show(self): - if self.closed: - self.setupwidgets() - self.w.open() - else: - self.w.wid.ShowWindow() - self.w.wid.SelectWindow() - - def hide(self): - if self.closed: - return - self.w.close() - - def close(self): - self.bounds = self.w.getbounds() - self.closed = 1 - self.type, self.value, self.tb = None, None, None - self.tblist = None - - def activate(self, onoff): - if onoff: - if self.closed: - self.traceback() - self.closed = 0 - self.checkbuttons() - - def setupwidgets(self): - self.w = W.Window(self.bounds, self.title, minsize = (316, 168)) - self.w.text = W.TextBox((10, 10, -10, 30)) - self.w.tbtitle = W.TextBox((10, 40, -10, 10), "Traceback (innermost last):") - self.w.list = W.TwoLineList((10, 60, -10, -40), callback = self.listhit) - - self.w.editbutton = W.Button((10, -30, 60, 16), "Edit", self.edit) - self.w.editbutton.enable(0) - - self.w.browselocalsbutton = W.Button((80, -30, 100, 16), "Browse locals\xc9", self.browselocals) - self.w.browselocalsbutton.enable(0) - - self.w.postmortembutton = W.Button((190, -30, 100, 16), "Post mortem\xc9", self.postmortem) - - self.w.setdefaultbutton(self.w.editbutton) - self.w.bind("cmdb", self.w.browselocalsbutton.push) - self.w.bind("<close>", self.close) - self.w.bind("<activate>", self.activate) - - def buildtblist(self): - tb = self.tb - for i in range(self.start): - if tb.tb_next is None: - break - tb = tb.tb_next - self.tblist = traceback.extract_tb(tb) - self.textlist = [] - for filename, lineno, func, line in self.tblist: - tbline = "" - if os.path.exists(filename): - filename = os.path.split(filename)[1] - tbline = 'File "%s", line %r, in %r' % (filename, lineno, func) - if line: - tbline = tbline + '\r ' + line - self.textlist.append(tbline[:255]) - - def edit(self): - sel = self.w.list.getselection() - for i in sel: - filename, lineno, func, line = self.tblist[i] - W.getapplication().openscript(filename, lineno) - - def browselocals(self): - sel = self.w.list.getselection() - for i in sel: - tb = self.tb - for j in range(i + self.start): - tb = tb.tb_next - self.browse(tb.tb_frame.f_locals) - - def browse(self, object): - import PyBrowser - PyBrowser.Browser(object) - - def postmortem(self): - import PyDebugger - PyDebugger.postmortem(self.type, self.value, self.tb) - - def listhit(self, isdbl): - if isdbl: - self.w.editbutton.push() - else: - self.checkbuttons() - - def checkbuttons(self): - havefile = len(self.w.list.getselection()) > 0 - self.w.editbutton.enable(havefile) - self.w.browselocalsbutton.enable(havefile) - self.w.setdefaultbutton(havefile and self.w.editbutton or self.w.postmortembutton) + def __init__(self, title = "Traceback"): + app = W.getapplication() # checks if W is properly initialized + self.title = title + self.w = None + self.closed = 1 + self.start = 0 + self.lastwindowtitle = "" + self.bounds = (360, 298) + + def traceback(self, start = 0, lastwindowtitle = ""): + try: + self.lastwindowtitle = lastwindowtitle + self.start = start + self.type, self.value, self.tb = sys.exc_info() + if self.type is not SyntaxError: + self.show() + if type(self.type) == types.ClassType: + errortext = self.type.__name__ + else: + errortext = str(self.type) + value = str(self.value) + if self.value and value: + errortext = errortext + ": " + value + self.w.text.set(errortext) + self.buildtblist() + self.w.list.set(self.textlist) + self.w.list.setselection([len(self.textlist) - 1]) + self.w.wid.SelectWindow() + self.closed = 0 + else: + self.syntaxerror() + except: + traceback.print_exc() + + def syntaxerror(self): + try: + value, (filename, lineno, charno, line) = self.value + except: + filename = "" + lineno = None + value = self.value + if not filename and self.lastwindowtitle: + filename = self.lastwindowtitle + elif not filename: + filename = "<unknown>" + if filename and os.path.exists(filename): + filename = os.path.split(filename)[1] + if lineno and charno is not None: + charno = charno - 1 + text = str(value) + '\rFile: "' + str(filename) + '", line ' + str(lineno) + '\r\r' + line[:charno] + "\xa5" + line[charno:-1] + else: + text = str(value) + '\rFile: "' + str(filename) + '"' + self.syntaxdialog = W.ModalDialog((360, 120), "Syntax Error") + self.syntaxdialog.text = W.TextBox((10, 10, -10, -40), text) + self.syntaxdialog.cancel = W.Button((-190, -32, 80, 16), "Cancel", self.syntaxclose) + self.syntaxdialog.edit = W.Button((-100, -32, 80, 16), "Edit", self.syntaxedit) + self.syntaxdialog.setdefaultbutton(self.syntaxdialog.edit) + self.syntaxdialog.bind("cmd.", self.syntaxdialog.cancel.push) + self.syntaxdialog.open() + + def syntaxclose(self): + self.syntaxdialog.close() + del self.syntaxdialog + + def syntaxedit(self): + try: + value, (filename, lineno, charno, line) = self.value + except: + filename = "" + lineno = None + if not filename and self.lastwindowtitle: + filename = self.lastwindowtitle + elif not filename: + filename = "<unknown>" + self.syntaxclose() + if lineno: + if charno is None: + charno = 1 + W.getapplication().openscript(filename, lineno, charno - 1) + else: + W.getapplication().openscript(filename) + + def show(self): + if self.closed: + self.setupwidgets() + self.w.open() + else: + self.w.wid.ShowWindow() + self.w.wid.SelectWindow() + + def hide(self): + if self.closed: + return + self.w.close() + + def close(self): + self.bounds = self.w.getbounds() + self.closed = 1 + self.type, self.value, self.tb = None, None, None + self.tblist = None + + def activate(self, onoff): + if onoff: + if self.closed: + self.traceback() + self.closed = 0 + self.checkbuttons() + + def setupwidgets(self): + self.w = W.Window(self.bounds, self.title, minsize = (316, 168)) + self.w.text = W.TextBox((10, 10, -10, 30)) + self.w.tbtitle = W.TextBox((10, 40, -10, 10), "Traceback (innermost last):") + self.w.list = W.TwoLineList((10, 60, -10, -40), callback = self.listhit) + + self.w.editbutton = W.Button((10, -30, 60, 16), "Edit", self.edit) + self.w.editbutton.enable(0) + + self.w.browselocalsbutton = W.Button((80, -30, 100, 16), "Browse locals\xc9", self.browselocals) + self.w.browselocalsbutton.enable(0) + + self.w.postmortembutton = W.Button((190, -30, 100, 16), "Post mortem\xc9", self.postmortem) + + self.w.setdefaultbutton(self.w.editbutton) + self.w.bind("cmdb", self.w.browselocalsbutton.push) + self.w.bind("<close>", self.close) + self.w.bind("<activate>", self.activate) + + def buildtblist(self): + tb = self.tb + for i in range(self.start): + if tb.tb_next is None: + break + tb = tb.tb_next + self.tblist = traceback.extract_tb(tb) + self.textlist = [] + for filename, lineno, func, line in self.tblist: + tbline = "" + if os.path.exists(filename): + filename = os.path.split(filename)[1] + tbline = 'File "%s", line %r, in %r' % (filename, lineno, func) + if line: + tbline = tbline + '\r ' + line + self.textlist.append(tbline[:255]) + + def edit(self): + sel = self.w.list.getselection() + for i in sel: + filename, lineno, func, line = self.tblist[i] + W.getapplication().openscript(filename, lineno) + + def browselocals(self): + sel = self.w.list.getselection() + for i in sel: + tb = self.tb + for j in range(i + self.start): + tb = tb.tb_next + self.browse(tb.tb_frame.f_locals) + + def browse(self, object): + import PyBrowser + PyBrowser.Browser(object) + + def postmortem(self): + import PyDebugger + PyDebugger.postmortem(self.type, self.value, self.tb) + + def listhit(self, isdbl): + if isdbl: + self.w.editbutton.push() + else: + self.checkbuttons() + + def checkbuttons(self): + havefile = len(self.w.list.getselection()) > 0 + self.w.editbutton.enable(havefile) + self.w.browselocalsbutton.enable(havefile) + self.w.setdefaultbutton(havefile and self.w.editbutton or self.w.postmortembutton) diff --git a/Mac/Tools/IDE/Wwindows.py b/Mac/Tools/IDE/Wwindows.py index d646bcf..cb8d855 100644 --- a/Mac/Tools/IDE/Wwindows.py +++ b/Mac/Tools/IDE/Wwindows.py @@ -8,629 +8,629 @@ import traceback from types import InstanceType, StringType if hasattr(Win, "FrontNonFloatingWindow"): - MyFrontWindow = Win.FrontNonFloatingWindow + MyFrontWindow = Win.FrontNonFloatingWindow else: - MyFrontWindow = Win.FrontWindow + MyFrontWindow = Win.FrontWindow class Window(FrameWork.Window, Wbase.SelectableWidget): - - windowkind = Windows.documentProc - - def __init__(self, possize, title="", minsize=None, maxsize=None, - tabbable=1, show=1, fontsettings=None): - import W - if fontsettings is None: - fontsettings = W.getdefaultfont() - self._fontsettings = fontsettings - W.SelectableWidget.__init__(self, possize) - self._globalbounds = l, t, r, b = self.getwindowbounds(possize, minsize) - self._bounds = (0, 0, r - l, b - t) - self._tabchain = [] - self._currentwidget = None - self.title = title - self._parentwindow = self - self._tabbable = tabbable - self._defaultbutton = None - self._drawwidgetbounds = 0 - self._show = show - self._lastrollover = None - self.hasclosebox = 1 - # XXX the following is not really compatible with the - # new (system >= 7.5) window procs. - if minsize: - self._hasgrowbox = 1 - self.windowkind = self.windowkind | 8 - l, t = minsize - if maxsize: - r, b = maxsize[0] + 1, maxsize[1] + 1 - else: - r, b = 32000, 32000 - self.growlimit = (l, t, r, b) - else: - self._hasgrowbox = 0 - if (self.windowkind == 0 or self.windowkind >= 8) and self.windowkind < 1000: - self.windowkind = self.windowkind | 4 - FrameWork.Window.__init__(self, W.getapplication()) - - def gettitle(self): - return self.title - - def settitle(self, title): - self.title = title - if self.wid: - self.wid.SetWTitle(title) - - def getwindowbounds(self, size, minsize = None): - return windowbounds(size, minsize) - - def getcurrentwidget(self): - return self._currentwidget - - def show(self, onoff): - if onoff: - self.wid.ShowWindow() - else: - self.wid.HideWindow() - - def isvisible(self): - return self.wid.IsWindowVisible() - - def select(self): - self.wid.SelectWindow() - # not sure if this is the best place, I need it when - # an editor gets selected, and immediately scrolled - # to a certain line, waste scroll assumes everything - # to be in tact. - self.do_rawupdate(self.wid, "DummyEvent") - - def open(self): - self.wid = Win.NewCWindow(self._globalbounds, self.title, self._show, - self.windowkind, -1, self.hasclosebox, 0) - self.SetPort() - fontname, fontstyle, fontsize, fontcolor = self._fontsettings - fnum = Fm.GetFNum(fontname) - if fnum == 0: - fnum = Fm.GetFNum("Geneva") - Qd.TextFont(fnum) - Qd.TextFace(fontstyle) - Qd.TextSize(fontsize) - if self._bindings.has_key("<open>"): - callback = self._bindings["<open>"] - callback() - for w in self._widgets: - w.forall_frombottom("open") - self._maketabchain() - if self._tabbable: - self.bind('tab', self.nextwidget) - self.bind('shifttab', self.previouswidget) - else: - self._hasselframes = 0 - if self._tabchain: - self._tabchain[0].select(1) - self.do_postopen() - - def close(self): - if not self.wid: - return # we are already closed - if self._bindings.has_key("<close>"): - callback = self._bindings["<close>"] - try: - rv = callback() - except: - print 'error in <close> callback' - traceback.print_exc() - else: - if rv: - return rv - #for key in self._widgetsdict.keys(): - # self._removewidget(key) - self.forall_butself("close") - Wbase.SelectableWidget.close(self) - self._tabchain = [] - self._currentwidget = None - self.wid.HideWindow() - self.do_postclose() - - def domenu_close(self, *args): - self.close() - - def getbounds(self): - return self._globalbounds - - def setbounds(self, bounds): - l, t, r, b = bounds - self.move(l, t) - self.resize(r-l, b-t) - - def move(self, x, y = None): - """absolute move""" - if y == None: - x, y = x - self.wid.MoveWindow(x, y, 0) - - def resize(self, x, y = None): - if not self._hasgrowbox: - return # hands off! - if y == None: - x, y = x - self.SetPort() - self.GetWindow().InvalWindowRect(self.getgrowrect()) - self.wid.SizeWindow(x, y, 1) - self._calcbounds() - - def test(self, point): - return 1 - - def draw(self, visRgn = None): - if self._hasgrowbox: - self.tempcliprect(self.getgrowrect()) - self.wid.DrawGrowIcon() - self.restoreclip() - - def idle(self, *args): - self.SetPort() - point = Evt.GetMouse() - widget = self.findwidget(point, 0) - if self._bindings.has_key("<idle>"): - callback = self._bindings["<idle>"] - if callback(): - return - if self._currentwidget is not None and hasattr(self._currentwidget, "idle"): - if self._currentwidget._bindings.has_key("<idle>"): - callback = self._currentwidget._bindings["<idle>"] - if callback(): - return - if self._currentwidget.idle(): - return - if widget is not None and hasattr(widget, "rollover"): - if 1: #self._lastrollover <> widget: - if self._lastrollover: - self._lastrollover.rollover(point, 0) - self._lastrollover = widget - self._lastrollover.rollover(point, 1) - else: - if self._lastrollover: - self._lastrollover.rollover(point, 0) - self._lastrollover = None - Wbase.SetCursor("arrow") - - def xxx___select(self, widget): - if self._currentwidget == widget: - return - if self._bindings.has_key("<select>"): - callback = self._bindings["<select>"] - if callback(widget): - return - if widget is None: - if self._currentwidget is not None: - self._currentwidget.select(0) - elif type(widget) == InstanceType and widget._selectable: - widget.select(1) - elif widget == -1 or widget == 1: - if len(self._tabchain) <= 1: - return - temp = self._tabchain[(self._tabchain.index(self._currentwidget) + widget) % len(self._tabchain)] - temp.select(1) - else: - raise TypeError, "Widget is not selectable" - - def setdefaultbutton(self, newdefaultbutton = None, *keys): - if newdefaultbutton == self._defaultbutton: - return - if self._defaultbutton: - self._defaultbutton._setdefault(0) - if not newdefaultbutton: - self.bind("return", None) - self.bind("enter", None) - return - import Wcontrols - if not isinstance(newdefaultbutton, Wcontrols.Button): - raise TypeError, "widget is not a button" - self._defaultbutton = newdefaultbutton - self._defaultbutton._setdefault(1) - if not keys: - self.bind("return", self._defaultbutton.push) - self.bind("enter", self._defaultbutton.push) - else: - for key in keys: - self.bind(key, self._defaultbutton.push) - - def nextwidget(self): - self.xxx___select(1) - - def previouswidget(self): - self.xxx___select(-1) - - def drawwidgetbounds(self, onoff): - self._drawwidgetbounds = onoff - self.SetPort() - self.GetWindow().InvalWindowRect(self._bounds) - - def _drawbounds(self): - pass - - def _maketabchain(self): - # XXX This has to change, it's no good when we are adding or deleting widgets. - # XXX Perhaps we shouldn't keep a "tabchain" at all. - self._hasselframes = 0 - self._collectselectablewidgets(self._widgets) - if self._hasselframes and len(self._tabchain) > 1: - self._hasselframes = 1 - else: - self._hasselframes = 0 - - def _collectselectablewidgets(self, widgets): - import W - for w in widgets: - if w._selectable: - self._tabchain.append(w) - if isinstance(w, W.List): - self._hasselframes = 1 - self._collectselectablewidgets(w._widgets) - - def _calcbounds(self): - self._possize = self.wid.GetWindowPort().GetPortBounds()[2:] - w, h = self._possize - self._bounds = (0, 0, w, h) - self.wid.GetWindowContentRgn(scratchRegion) - l, t, r, b = GetRgnBounds(scratchRegion) - self._globalbounds = l, t, l + w, t + h - for w in self._widgets: - w._calcbounds() - - # FrameWork override methods - def do_inDrag(self, partcode, window, event): - where = event[3] - self.wid.GetWindowContentRgn(scratchRegion) - was_l, was_t, r, b = GetRgnBounds(scratchRegion) - window.DragWindow(where, self.draglimit) - self.wid.GetWindowContentRgn(scratchRegion) - is_l, is_t, r, b = GetRgnBounds(scratchRegion) - self._globalbounds = Qd.OffsetRect(self._globalbounds, - is_l - was_l, is_t - was_t) - - def do_char(self, char, event): - import Wkeys - (what, message, when, where, modifiers) = event - key = char - if Wkeys.keynames.has_key(key): - key = Wkeys.keynames[key] - if modifiers & Events.shiftKey: - key = 'shift' + key - if modifiers & Events.cmdKey: - key = 'cmd' + key - if modifiers & Events.controlKey: - key = 'control' + key - if self._bindings.has_key("<key>"): - callback = self._bindings["<key>"] - if Wbase.CallbackCall(callback, 0, char, event): - return - if self._bindings.has_key(key): - callback = self._bindings[key] - Wbase.CallbackCall(callback, 0, char, event) - elif self._currentwidget is not None: - if self._currentwidget._bindings.has_key(key): - callback = self._currentwidget._bindings[key] - Wbase.CallbackCall(callback, 0, char, event) - else: - if self._currentwidget._bindings.has_key("<key>"): - callback = self._currentwidget._bindings["<key>"] - if Wbase.CallbackCall(callback, 0, char, event): - return - self._currentwidget.key(char, event) - - def do_contentclick(self, point, modifiers, event): - widget = self.findwidget(point) - if widget is not None: - if self._bindings.has_key("<click>"): - callback = self._bindings["<click>"] - if Wbase.CallbackCall(callback, 0, point, modifiers): - return - if widget._bindings.has_key("<click>"): - callback = widget._bindings["<click>"] - if Wbase.CallbackCall(callback, 0, point, modifiers): - return - if widget._selectable: - widget.select(1, 1) - widget.click(point, modifiers) - - def do_update(self, window, event): - Qd.EraseRgn(window.GetWindowPort().visRgn) - self.forall_frombottom("draw", window.GetWindowPort().visRgn) - if self._drawwidgetbounds: - self.forall_frombottom("_drawbounds") - - def do_activate(self, onoff, event): - if not onoff: - if self._lastrollover: - self._lastrollover.rollover((0, 0), 0) - self._lastrollover = None - self.SetPort() - self.forall("activate", onoff) - self.draw() - - def do_postresize(self, width, height, window): - self.GetWindow().InvalWindowRect(self.getgrowrect()) - self._calcbounds() - - def do_inGoAway(self, partcode, window, event): - where = event[3] - closeall = event[4] & Events.optionKey - if window.TrackGoAway(where): - if not closeall: - self.close() - else: - for window in self.parent._windows.values(): - rv = window.close() - if rv and rv > 0: - return - - # utilities - def tempcliprect(self, tempcliprect): - tempclip = Qd.NewRgn() - Qd.RectRgn(tempclip, tempcliprect) - self.tempclip(tempclip) - Qd.DisposeRgn(tempclip) - - def tempclip(self, tempclip): - if not hasattr(self, "saveclip"): - self.saveclip = [] - saveclip = Qd.NewRgn() - Qd.GetClip(saveclip) - self.saveclip.append(saveclip) - Qd.SetClip(tempclip) - - def restoreclip(self): - Qd.SetClip(self.saveclip[-1]) - Qd.DisposeRgn(self.saveclip[-1]) - del self.saveclip[-1] - - def getgrowrect(self): - l, t, r, b = self.wid.GetWindowPort().GetPortBounds() - return (r - 15, b - 15, r, b) - - def has_key(self, key): - return self._widgetsdict.has_key(key) - - def __getattr__(self, attr): - global _successcount, _failcount, _magiccount - if self._widgetsdict.has_key(attr): - _successcount = _successcount + 1 - return self._widgetsdict[attr] - if self._currentwidget is None or (attr[:7] <> 'domenu_' and - attr[:4] <> 'can_' and attr <> 'insert'): - _failcount = _failcount + 1 - raise AttributeError, attr - # special case: if a domenu_xxx, can_xxx or insert method is asked for, - # see if the active widget supports it - _magiccount = _magiccount + 1 - return getattr(self._currentwidget, attr) + + windowkind = Windows.documentProc + + def __init__(self, possize, title="", minsize=None, maxsize=None, + tabbable=1, show=1, fontsettings=None): + import W + if fontsettings is None: + fontsettings = W.getdefaultfont() + self._fontsettings = fontsettings + W.SelectableWidget.__init__(self, possize) + self._globalbounds = l, t, r, b = self.getwindowbounds(possize, minsize) + self._bounds = (0, 0, r - l, b - t) + self._tabchain = [] + self._currentwidget = None + self.title = title + self._parentwindow = self + self._tabbable = tabbable + self._defaultbutton = None + self._drawwidgetbounds = 0 + self._show = show + self._lastrollover = None + self.hasclosebox = 1 + # XXX the following is not really compatible with the + # new (system >= 7.5) window procs. + if minsize: + self._hasgrowbox = 1 + self.windowkind = self.windowkind | 8 + l, t = minsize + if maxsize: + r, b = maxsize[0] + 1, maxsize[1] + 1 + else: + r, b = 32000, 32000 + self.growlimit = (l, t, r, b) + else: + self._hasgrowbox = 0 + if (self.windowkind == 0 or self.windowkind >= 8) and self.windowkind < 1000: + self.windowkind = self.windowkind | 4 + FrameWork.Window.__init__(self, W.getapplication()) + + def gettitle(self): + return self.title + + def settitle(self, title): + self.title = title + if self.wid: + self.wid.SetWTitle(title) + + def getwindowbounds(self, size, minsize = None): + return windowbounds(size, minsize) + + def getcurrentwidget(self): + return self._currentwidget + + def show(self, onoff): + if onoff: + self.wid.ShowWindow() + else: + self.wid.HideWindow() + + def isvisible(self): + return self.wid.IsWindowVisible() + + def select(self): + self.wid.SelectWindow() + # not sure if this is the best place, I need it when + # an editor gets selected, and immediately scrolled + # to a certain line, waste scroll assumes everything + # to be in tact. + self.do_rawupdate(self.wid, "DummyEvent") + + def open(self): + self.wid = Win.NewCWindow(self._globalbounds, self.title, self._show, + self.windowkind, -1, self.hasclosebox, 0) + self.SetPort() + fontname, fontstyle, fontsize, fontcolor = self._fontsettings + fnum = Fm.GetFNum(fontname) + if fnum == 0: + fnum = Fm.GetFNum("Geneva") + Qd.TextFont(fnum) + Qd.TextFace(fontstyle) + Qd.TextSize(fontsize) + if self._bindings.has_key("<open>"): + callback = self._bindings["<open>"] + callback() + for w in self._widgets: + w.forall_frombottom("open") + self._maketabchain() + if self._tabbable: + self.bind('tab', self.nextwidget) + self.bind('shifttab', self.previouswidget) + else: + self._hasselframes = 0 + if self._tabchain: + self._tabchain[0].select(1) + self.do_postopen() + + def close(self): + if not self.wid: + return # we are already closed + if self._bindings.has_key("<close>"): + callback = self._bindings["<close>"] + try: + rv = callback() + except: + print 'error in <close> callback' + traceback.print_exc() + else: + if rv: + return rv + #for key in self._widgetsdict.keys(): + # self._removewidget(key) + self.forall_butself("close") + Wbase.SelectableWidget.close(self) + self._tabchain = [] + self._currentwidget = None + self.wid.HideWindow() + self.do_postclose() + + def domenu_close(self, *args): + self.close() + + def getbounds(self): + return self._globalbounds + + def setbounds(self, bounds): + l, t, r, b = bounds + self.move(l, t) + self.resize(r-l, b-t) + + def move(self, x, y = None): + """absolute move""" + if y == None: + x, y = x + self.wid.MoveWindow(x, y, 0) + + def resize(self, x, y = None): + if not self._hasgrowbox: + return # hands off! + if y == None: + x, y = x + self.SetPort() + self.GetWindow().InvalWindowRect(self.getgrowrect()) + self.wid.SizeWindow(x, y, 1) + self._calcbounds() + + def test(self, point): + return 1 + + def draw(self, visRgn = None): + if self._hasgrowbox: + self.tempcliprect(self.getgrowrect()) + self.wid.DrawGrowIcon() + self.restoreclip() + + def idle(self, *args): + self.SetPort() + point = Evt.GetMouse() + widget = self.findwidget(point, 0) + if self._bindings.has_key("<idle>"): + callback = self._bindings["<idle>"] + if callback(): + return + if self._currentwidget is not None and hasattr(self._currentwidget, "idle"): + if self._currentwidget._bindings.has_key("<idle>"): + callback = self._currentwidget._bindings["<idle>"] + if callback(): + return + if self._currentwidget.idle(): + return + if widget is not None and hasattr(widget, "rollover"): + if 1: #self._lastrollover <> widget: + if self._lastrollover: + self._lastrollover.rollover(point, 0) + self._lastrollover = widget + self._lastrollover.rollover(point, 1) + else: + if self._lastrollover: + self._lastrollover.rollover(point, 0) + self._lastrollover = None + Wbase.SetCursor("arrow") + + def xxx___select(self, widget): + if self._currentwidget == widget: + return + if self._bindings.has_key("<select>"): + callback = self._bindings["<select>"] + if callback(widget): + return + if widget is None: + if self._currentwidget is not None: + self._currentwidget.select(0) + elif type(widget) == InstanceType and widget._selectable: + widget.select(1) + elif widget == -1 or widget == 1: + if len(self._tabchain) <= 1: + return + temp = self._tabchain[(self._tabchain.index(self._currentwidget) + widget) % len(self._tabchain)] + temp.select(1) + else: + raise TypeError, "Widget is not selectable" + + def setdefaultbutton(self, newdefaultbutton = None, *keys): + if newdefaultbutton == self._defaultbutton: + return + if self._defaultbutton: + self._defaultbutton._setdefault(0) + if not newdefaultbutton: + self.bind("return", None) + self.bind("enter", None) + return + import Wcontrols + if not isinstance(newdefaultbutton, Wcontrols.Button): + raise TypeError, "widget is not a button" + self._defaultbutton = newdefaultbutton + self._defaultbutton._setdefault(1) + if not keys: + self.bind("return", self._defaultbutton.push) + self.bind("enter", self._defaultbutton.push) + else: + for key in keys: + self.bind(key, self._defaultbutton.push) + + def nextwidget(self): + self.xxx___select(1) + + def previouswidget(self): + self.xxx___select(-1) + + def drawwidgetbounds(self, onoff): + self._drawwidgetbounds = onoff + self.SetPort() + self.GetWindow().InvalWindowRect(self._bounds) + + def _drawbounds(self): + pass + + def _maketabchain(self): + # XXX This has to change, it's no good when we are adding or deleting widgets. + # XXX Perhaps we shouldn't keep a "tabchain" at all. + self._hasselframes = 0 + self._collectselectablewidgets(self._widgets) + if self._hasselframes and len(self._tabchain) > 1: + self._hasselframes = 1 + else: + self._hasselframes = 0 + + def _collectselectablewidgets(self, widgets): + import W + for w in widgets: + if w._selectable: + self._tabchain.append(w) + if isinstance(w, W.List): + self._hasselframes = 1 + self._collectselectablewidgets(w._widgets) + + def _calcbounds(self): + self._possize = self.wid.GetWindowPort().GetPortBounds()[2:] + w, h = self._possize + self._bounds = (0, 0, w, h) + self.wid.GetWindowContentRgn(scratchRegion) + l, t, r, b = GetRgnBounds(scratchRegion) + self._globalbounds = l, t, l + w, t + h + for w in self._widgets: + w._calcbounds() + + # FrameWork override methods + def do_inDrag(self, partcode, window, event): + where = event[3] + self.wid.GetWindowContentRgn(scratchRegion) + was_l, was_t, r, b = GetRgnBounds(scratchRegion) + window.DragWindow(where, self.draglimit) + self.wid.GetWindowContentRgn(scratchRegion) + is_l, is_t, r, b = GetRgnBounds(scratchRegion) + self._globalbounds = Qd.OffsetRect(self._globalbounds, + is_l - was_l, is_t - was_t) + + def do_char(self, char, event): + import Wkeys + (what, message, when, where, modifiers) = event + key = char + if Wkeys.keynames.has_key(key): + key = Wkeys.keynames[key] + if modifiers & Events.shiftKey: + key = 'shift' + key + if modifiers & Events.cmdKey: + key = 'cmd' + key + if modifiers & Events.controlKey: + key = 'control' + key + if self._bindings.has_key("<key>"): + callback = self._bindings["<key>"] + if Wbase.CallbackCall(callback, 0, char, event): + return + if self._bindings.has_key(key): + callback = self._bindings[key] + Wbase.CallbackCall(callback, 0, char, event) + elif self._currentwidget is not None: + if self._currentwidget._bindings.has_key(key): + callback = self._currentwidget._bindings[key] + Wbase.CallbackCall(callback, 0, char, event) + else: + if self._currentwidget._bindings.has_key("<key>"): + callback = self._currentwidget._bindings["<key>"] + if Wbase.CallbackCall(callback, 0, char, event): + return + self._currentwidget.key(char, event) + + def do_contentclick(self, point, modifiers, event): + widget = self.findwidget(point) + if widget is not None: + if self._bindings.has_key("<click>"): + callback = self._bindings["<click>"] + if Wbase.CallbackCall(callback, 0, point, modifiers): + return + if widget._bindings.has_key("<click>"): + callback = widget._bindings["<click>"] + if Wbase.CallbackCall(callback, 0, point, modifiers): + return + if widget._selectable: + widget.select(1, 1) + widget.click(point, modifiers) + + def do_update(self, window, event): + Qd.EraseRgn(window.GetWindowPort().visRgn) + self.forall_frombottom("draw", window.GetWindowPort().visRgn) + if self._drawwidgetbounds: + self.forall_frombottom("_drawbounds") + + def do_activate(self, onoff, event): + if not onoff: + if self._lastrollover: + self._lastrollover.rollover((0, 0), 0) + self._lastrollover = None + self.SetPort() + self.forall("activate", onoff) + self.draw() + + def do_postresize(self, width, height, window): + self.GetWindow().InvalWindowRect(self.getgrowrect()) + self._calcbounds() + + def do_inGoAway(self, partcode, window, event): + where = event[3] + closeall = event[4] & Events.optionKey + if window.TrackGoAway(where): + if not closeall: + self.close() + else: + for window in self.parent._windows.values(): + rv = window.close() + if rv and rv > 0: + return + + # utilities + def tempcliprect(self, tempcliprect): + tempclip = Qd.NewRgn() + Qd.RectRgn(tempclip, tempcliprect) + self.tempclip(tempclip) + Qd.DisposeRgn(tempclip) + + def tempclip(self, tempclip): + if not hasattr(self, "saveclip"): + self.saveclip = [] + saveclip = Qd.NewRgn() + Qd.GetClip(saveclip) + self.saveclip.append(saveclip) + Qd.SetClip(tempclip) + + def restoreclip(self): + Qd.SetClip(self.saveclip[-1]) + Qd.DisposeRgn(self.saveclip[-1]) + del self.saveclip[-1] + + def getgrowrect(self): + l, t, r, b = self.wid.GetWindowPort().GetPortBounds() + return (r - 15, b - 15, r, b) + + def has_key(self, key): + return self._widgetsdict.has_key(key) + + def __getattr__(self, attr): + global _successcount, _failcount, _magiccount + if self._widgetsdict.has_key(attr): + _successcount = _successcount + 1 + return self._widgetsdict[attr] + if self._currentwidget is None or (attr[:7] <> 'domenu_' and + attr[:4] <> 'can_' and attr <> 'insert'): + _failcount = _failcount + 1 + raise AttributeError, attr + # special case: if a domenu_xxx, can_xxx or insert method is asked for, + # see if the active widget supports it + _magiccount = _magiccount + 1 + return getattr(self._currentwidget, attr) _successcount = 0 _failcount = 0 _magiccount = 0 class Dialog(Window): - - windowkind = Windows.movableDBoxProc - - # this __init__ seems redundant, but it's not: it has less args - def __init__(self, possize, title = ""): - Window.__init__(self, possize, title) - - def can_close(self, *args): - return 0 - - def getwindowbounds(self, size, minsize = None): - screenbounds = sl, st, sr, sb = Qd.GetQDGlobalsScreenBits().bounds - w, h = size - l = sl + (sr - sl - w) / 2 - t = st + (sb - st - h) / 3 - return l, t, l + w, t + h + + windowkind = Windows.movableDBoxProc + + # this __init__ seems redundant, but it's not: it has less args + def __init__(self, possize, title = ""): + Window.__init__(self, possize, title) + + def can_close(self, *args): + return 0 + + def getwindowbounds(self, size, minsize = None): + screenbounds = sl, st, sr, sb = Qd.GetQDGlobalsScreenBits().bounds + w, h = size + l = sl + (sr - sl - w) / 2 + t = st + (sb - st - h) / 3 + return l, t, l + w, t + h class ModalDialog(Dialog): - - def __init__(self, possize, title = ""): - Dialog.__init__(self, possize, title) - if title: - self.windowkind = Windows.movableDBoxProc - else: - self.windowkind = Windows.dBoxProc - - def open(self): - import W - Dialog.open(self) - self.app = W.getapplication() - self.done = 0 - Menu.HiliteMenu(0) - app = self.parent - app.enablemenubar(0) - try: - self.mainloop() - finally: - app.enablemenubar(1) - - def close(self): - if not self.wid: - return # we are already closed - self.done = 1 - del self.app - Dialog.close(self) - - def mainloop(self): - if hasattr(MacOS, 'EnableAppswitch'): - saveyield = MacOS.EnableAppswitch(-1) - while not self.done: - #self.do1event() - self.do1event( Events.keyDownMask + - Events.autoKeyMask + - Events.activMask + - Events.updateMask + - Events.mDownMask + - Events.mUpMask, - 10) - if hasattr(MacOS, 'EnableAppswitch'): - MacOS.EnableAppswitch(saveyield) - - def do1event(self, mask = Events.everyEvent, wait = 0): - ok, event = self.app.getevent(mask, wait) - if Dlg.IsDialogEvent(event): - if self.app.do_dialogevent(event): - return - if ok: - self.dispatch(event) - else: - self.app.idle(event) - - def do_keyDown(self, event): - self.do_key(event) - - def do_autoKey(self, event): - if not event[-1] & Events.cmdKey: - self.do_key(event) - - def do_key(self, event): - (what, message, when, where, modifiers) = event - #w = Win.FrontWindow() - #if w <> self.wid: - # return - c = chr(message & Events.charCodeMask) - if modifiers & Events.cmdKey: - self.app.checkmenus(self) - result = Menu.MenuKey(ord(c)) - id = (result>>16) & 0xffff # Hi word - item = result & 0xffff # Lo word - if id: - self.app.do_rawmenu(id, item, None, event) - return - self.do_char(c, event) - - def do_mouseDown(self, event): - (what, message, when, where, modifiers) = event - partcode, wid = Win.FindWindow(where) - # - # Find the correct name. - # - if FrameWork.partname.has_key(partcode): - name = "do_" + FrameWork.partname[partcode] - else: - name = "do_%d" % partcode - - if name == "do_inDesk": - if hasattr(MacOS, "HandleEvent"): - MacOS.HandleEvent(event) - else: - print 'Unexpected inDesk event:', event - return - if wid == self.wid: - try: - handler = getattr(self, name) - except AttributeError: - handler = self.app.do_unknownpartcode - else: - #MacOS.HandleEvent(event) - if name == 'do_inMenuBar': - handler = getattr(self.parent, name) - else: - return - handler(partcode, wid, event) - - def dispatch(self, event): - (what, message, when, where, modifiers) = event - if FrameWork.eventname.has_key(what): - name = "do_" + FrameWork.eventname[what] - else: - name = "do_%d" % what - try: - handler = getattr(self, name) - except AttributeError: - try: - handler = getattr(self.app, name) - except AttributeError: - handler = self.app.do_unknownevent - handler(event) - + + def __init__(self, possize, title = ""): + Dialog.__init__(self, possize, title) + if title: + self.windowkind = Windows.movableDBoxProc + else: + self.windowkind = Windows.dBoxProc + + def open(self): + import W + Dialog.open(self) + self.app = W.getapplication() + self.done = 0 + Menu.HiliteMenu(0) + app = self.parent + app.enablemenubar(0) + try: + self.mainloop() + finally: + app.enablemenubar(1) + + def close(self): + if not self.wid: + return # we are already closed + self.done = 1 + del self.app + Dialog.close(self) + + def mainloop(self): + if hasattr(MacOS, 'EnableAppswitch'): + saveyield = MacOS.EnableAppswitch(-1) + while not self.done: + #self.do1event() + self.do1event( Events.keyDownMask + + Events.autoKeyMask + + Events.activMask + + Events.updateMask + + Events.mDownMask + + Events.mUpMask, + 10) + if hasattr(MacOS, 'EnableAppswitch'): + MacOS.EnableAppswitch(saveyield) + + def do1event(self, mask = Events.everyEvent, wait = 0): + ok, event = self.app.getevent(mask, wait) + if Dlg.IsDialogEvent(event): + if self.app.do_dialogevent(event): + return + if ok: + self.dispatch(event) + else: + self.app.idle(event) + + def do_keyDown(self, event): + self.do_key(event) + + def do_autoKey(self, event): + if not event[-1] & Events.cmdKey: + self.do_key(event) + + def do_key(self, event): + (what, message, when, where, modifiers) = event + #w = Win.FrontWindow() + #if w <> self.wid: + # return + c = chr(message & Events.charCodeMask) + if modifiers & Events.cmdKey: + self.app.checkmenus(self) + result = Menu.MenuKey(ord(c)) + id = (result>>16) & 0xffff # Hi word + item = result & 0xffff # Lo word + if id: + self.app.do_rawmenu(id, item, None, event) + return + self.do_char(c, event) + + def do_mouseDown(self, event): + (what, message, when, where, modifiers) = event + partcode, wid = Win.FindWindow(where) + # + # Find the correct name. + # + if FrameWork.partname.has_key(partcode): + name = "do_" + FrameWork.partname[partcode] + else: + name = "do_%d" % partcode + + if name == "do_inDesk": + if hasattr(MacOS, "HandleEvent"): + MacOS.HandleEvent(event) + else: + print 'Unexpected inDesk event:', event + return + if wid == self.wid: + try: + handler = getattr(self, name) + except AttributeError: + handler = self.app.do_unknownpartcode + else: + #MacOS.HandleEvent(event) + if name == 'do_inMenuBar': + handler = getattr(self.parent, name) + else: + return + handler(partcode, wid, event) + + def dispatch(self, event): + (what, message, when, where, modifiers) = event + if FrameWork.eventname.has_key(what): + name = "do_" + FrameWork.eventname[what] + else: + name = "do_%d" % what + try: + handler = getattr(self, name) + except AttributeError: + try: + handler = getattr(self.app, name) + except AttributeError: + handler = self.app.do_unknownevent + handler(event) + def FrontWindowInsert(stuff): - if not stuff: - return - if type(stuff) <> StringType: - raise TypeError, 'string expected' - import W - app = W.getapplication() - wid = MyFrontWindow() - if wid and app._windows.has_key(wid): - window = app._windows[wid] - if hasattr(window, "insert"): - try: - window.insert(stuff) - return - except: - pass - import EasyDialogs - if EasyDialogs.AskYesNoCancel( - "Can't find window or widget to insert text into; copy to clipboard instead?", - 1) == 1: - from Carbon import Scrap - if hasattr(Scrap, 'PutScrap'): - Scrap.ZeroScrap() - Scrap.PutScrap('TEXT', stuff) - else: - Scrap.ClearCurrentScrap() - sc = Scrap.GetCurrentScrap() - sc.PutScrapFlavor('TEXT', 0, stuff) - - -# not quite based on the same function in FrameWork + if not stuff: + return + if type(stuff) <> StringType: + raise TypeError, 'string expected' + import W + app = W.getapplication() + wid = MyFrontWindow() + if wid and app._windows.has_key(wid): + window = app._windows[wid] + if hasattr(window, "insert"): + try: + window.insert(stuff) + return + except: + pass + import EasyDialogs + if EasyDialogs.AskYesNoCancel( + "Can't find window or widget to insert text into; copy to clipboard instead?", + 1) == 1: + from Carbon import Scrap + if hasattr(Scrap, 'PutScrap'): + Scrap.ZeroScrap() + Scrap.PutScrap('TEXT', stuff) + else: + Scrap.ClearCurrentScrap() + sc = Scrap.GetCurrentScrap() + sc.PutScrapFlavor('TEXT', 0, stuff) + + +# not quite based on the same function in FrameWork _windowcounter = 0 def getnextwindowpos(): - global _windowcounter - rows = 8 - l = 4 * (rows + 1 - (_windowcounter % rows) + _windowcounter / rows) - t = 44 + 20 * (_windowcounter % rows) - _windowcounter = _windowcounter + 1 - return l, t + global _windowcounter + rows = 8 + l = 4 * (rows + 1 - (_windowcounter % rows) + _windowcounter / rows) + t = 44 + 20 * (_windowcounter % rows) + _windowcounter = _windowcounter + 1 + return l, t def windowbounds(preferredsize, minsize=None): - "Return sensible window bounds" - - global _windowcounter - if len(preferredsize) == 4: - bounds = l, t, r, b = preferredsize - desktopRgn = Win.GetGrayRgn() - tempRgn = Qd.NewRgn() - Qd.RectRgn(tempRgn, bounds) - union = Qd.UnionRgn(tempRgn, desktopRgn, tempRgn) - equal = Qd.EqualRgn(tempRgn, desktopRgn) - Qd.DisposeRgn(tempRgn) - if equal: - return bounds - else: - preferredsize = r - l, b - t - if not minsize: - minsize = preferredsize - minwidth, minheight = minsize - width, height = preferredsize - - sl, st, sr, sb = screenbounds = Qd.InsetRect(Qd.GetQDGlobalsScreenBits().bounds, 4, 4) - l, t = getnextwindowpos() - if (l + width) > sr: - _windowcounter = 0 - l, t = getnextwindowpos() - r = l + width - b = t + height - if (t + height) > sb: - b = sb - if (b - t) < minheight: - b = t + minheight - return l, t, r, b + "Return sensible window bounds" + + global _windowcounter + if len(preferredsize) == 4: + bounds = l, t, r, b = preferredsize + desktopRgn = Win.GetGrayRgn() + tempRgn = Qd.NewRgn() + Qd.RectRgn(tempRgn, bounds) + union = Qd.UnionRgn(tempRgn, desktopRgn, tempRgn) + equal = Qd.EqualRgn(tempRgn, desktopRgn) + Qd.DisposeRgn(tempRgn) + if equal: + return bounds + else: + preferredsize = r - l, b - t + if not minsize: + minsize = preferredsize + minwidth, minheight = minsize + width, height = preferredsize + + sl, st, sr, sb = screenbounds = Qd.InsetRect(Qd.GetQDGlobalsScreenBits().bounds, 4, 4) + l, t = getnextwindowpos() + if (l + width) > sr: + _windowcounter = 0 + l, t = getnextwindowpos() + r = l + width + b = t + height + if (t + height) > sb: + b = sb + if (b - t) < minheight: + b = t + minheight + return l, t, r, b scratchRegion = Qd.NewRgn() # util -- move somewhere convenient??? def GetRgnBounds(the_Rgn): - (t, l, b, r) = struct.unpack("hhhh", the_Rgn.data[2:10]) - return (l, t, r, b) + (t, l, b, r) = struct.unpack("hhhh", the_Rgn.data[2:10]) + return (l, t, r, b) diff --git a/Mac/Tools/macfreeze/directives.py b/Mac/Tools/macfreeze/directives.py index 3ef9661..7f6142e 100644 --- a/Mac/Tools/macfreeze/directives.py +++ b/Mac/Tools/macfreeze/directives.py @@ -17,27 +17,26 @@ 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 - + 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 diff --git a/Mac/Tools/macfreeze/macfreeze.py b/Mac/Tools/macfreeze/macfreeze.py index 8a2ca76..b2cf72e 100644 --- a/Mac/Tools/macfreeze/macfreeze.py +++ b/Mac/Tools/macfreeze/macfreeze.py @@ -26,50 +26,50 @@ import macmodulefinder # def main(): - if len(sys.argv) < 2: - gentype, program, output, debug = macfreezegui.dialog() - elif len(sys.argv) == 2: - gentype, program, output, debug = macfreezegui.dialog(sys.argv[1]) - else: - EasyDialog.Message( - "Please pass a single script. Additional modules can be specified with directives") - sys.exit(0) - mustwait = process(gentype, program, output, debug=debug) - if mustwait: - sys.exit(1) + if len(sys.argv) < 2: + gentype, program, output, debug = macfreezegui.dialog() + elif len(sys.argv) == 2: + gentype, program, output, debug = macfreezegui.dialog(sys.argv[1]) + else: + EasyDialog.Message( + "Please pass a single script. Additional modules can be specified with directives") + sys.exit(0) + mustwait = process(gentype, program, output, debug=debug) + if mustwait: + sys.exit(1) def process(gentype, program, output, modules=None, module_files=None, debug=0, with_ifdef=0): - if modules is None: - modules = [] - if module_files is None: - module_files = [] - module_dict, missing = macmodulefinder.process(program, modules, module_files, debug) - if missing: - missing.sort() - print '** Missing modules:', string.join(missing, ' ') - sys.exit(1) - # - # And generate - # - if gentype == 'info': - import macgen_info - macgen_info.generate(output, module_dict) - return 1 # So the user can inspect it - elif gentype == 'source': - import macgen_src - warnings = macgen_src.generate(output, module_dict, debug, with_ifdef) - return warnings - elif gentype == 'resource': - import macgen_rsrc - macgen_rsrc.generate(output, module_dict, debug) - warnings = macgen_rsrc.warnings(module_dict) - return warnings - elif gentype == 'applet': - import macgen_bin - architecture = 'fat' # user should choose - macgen_bin.generate(program, output, module_dict, architecture, debug) - else: - raise 'unknown gentype', gentype + if modules is None: + modules = [] + if module_files is None: + module_files = [] + module_dict, missing = macmodulefinder.process(program, modules, module_files, debug) + if missing: + missing.sort() + print '** Missing modules:', string.join(missing, ' ') + sys.exit(1) + # + # And generate + # + if gentype == 'info': + import macgen_info + macgen_info.generate(output, module_dict) + return 1 # So the user can inspect it + elif gentype == 'source': + import macgen_src + warnings = macgen_src.generate(output, module_dict, debug, with_ifdef) + return warnings + elif gentype == 'resource': + import macgen_rsrc + macgen_rsrc.generate(output, module_dict, debug) + warnings = macgen_rsrc.warnings(module_dict) + return warnings + elif gentype == 'applet': + import macgen_bin + architecture = 'fat' # user should choose + macgen_bin.generate(program, output, module_dict, architecture, debug) + else: + raise 'unknown gentype', gentype if __name__ == '__main__': - main() + main() diff --git a/Mac/Tools/macfreeze/macfreezegui.py b/Mac/Tools/macfreeze/macfreezegui.py index 5dd3435..41d0ec8 100644 --- a/Mac/Tools/macfreeze/macfreezegui.py +++ b/Mac/Tools/macfreeze/macfreezegui.py @@ -30,121 +30,121 @@ ITEM_DEBUG=19 ITEM_GENINFO=20 RADIO_GROUPING={ - ITEM_GENSOURCE: ITEM_GENSOURCE_ITEMS, - ITEM_GENRESOURCE: ITEM_GENRESOURCE_ITEMS, - ITEM_GENAPPLET: ITEM_GENAPPLET_ITEMS, - ITEM_GENINFO: () + ITEM_GENSOURCE: ITEM_GENSOURCE_ITEMS, + ITEM_GENRESOURCE: ITEM_GENRESOURCE_ITEMS, + ITEM_GENAPPLET: ITEM_GENAPPLET_ITEMS, + ITEM_GENINFO: () } def dialog(script=None): - # Invent the various names - if not script: - fss, ok = macfs.PromptGetFile("Script?", "TEXT") - if not ok: - sys.exit(0) - script = fss.as_pathname() - basename, ext = os.path.splitext(script) - if ext: - appletname = basename - rsrcname = basename + 'modules.rsrc' - else: - appletname = script + '.applet' - rsrcname = script + 'modules.rsrc' - dirname, basebase = os.path.split(basename) - dirname = os.path.join(dirname, 'build.'+basebase) - - # Get the dialog, possibly opening the resource file (if needed) - macresource.need('DLOG', ID_MAINDIALOG, 'macfreeze.rsrc') - d = Dlg.GetNewDialog(ID_MAINDIALOG, -1) - if d == None: - EasyDialogs.Message("Dialog resource not found or faulty") - sys.exit(1) - - # Fill the dialog - d.SetDialogDefaultItem(ITEM_OK) - d.SetDialogCancelItem(ITEM_CANCEL) - - _dialogsetfile(d, ITEM_SCRIPTNAME, script) - _dialogsetfile(d, ITEM_SOURCEDIRNAME, dirname) - _dialogsetfile(d, ITEM_RESOURCENAME, rsrcname) - _dialogsetfile(d, ITEM_APPLETNAME, appletname) + # Invent the various names + if not script: + fss, ok = macfs.PromptGetFile("Script?", "TEXT") + if not ok: + sys.exit(0) + script = fss.as_pathname() + basename, ext = os.path.splitext(script) + if ext: + appletname = basename + rsrcname = basename + 'modules.rsrc' + else: + appletname = script + '.applet' + rsrcname = script + 'modules.rsrc' + dirname, basebase = os.path.split(basename) + dirname = os.path.join(dirname, 'build.'+basebase) - gentype = ITEM_GENSOURCE - _dialogradiogroup(d, ITEM_GENSOURCE) + # Get the dialog, possibly opening the resource file (if needed) + macresource.need('DLOG', ID_MAINDIALOG, 'macfreeze.rsrc') + d = Dlg.GetNewDialog(ID_MAINDIALOG, -1) + if d == None: + EasyDialogs.Message("Dialog resource not found or faulty") + sys.exit(1) - # Interact - d.GetDialogWindow().SetWTitle("Standalone application creation options") - d.GetDialogWindow().ShowWindow() - d.DrawDialog() - while 1: - item = Dlg.ModalDialog(None) - if item == ITEM_OK: - break - elif item == ITEM_CANCEL: - sys.exit(0) - elif item in RADIO_GROUPING.keys(): - gentype = item - _dialogradiogroup(d, item) - elif item == ITEM_SCRIPTBROWSE: - fss, ok = macfs.PromptGetFile("Script?") - if ok: - script = fss.as_pathname() - _dialogsetfile(d, ITEM_SCRIPTNAME, script) - elif item == ITEM_SOURCEDIRBROWSE: - fss, ok = macfs.StandardPutFile("Output folder name", os.path.split(dirname)[1]) - if ok: - dirname = fss.as_pathname() - _dialogsetfile(d, ITEM_SOURCEDIRNAME, dirname) - elif item == ITEM_RESOURCEBROWSE: - fss, ok = macfs.StandardPutFile("Resource output file", os.path.split(rsrcname)[1]) - if ok: - rsrcname = fss.as_pathname() - _dialogsetfile(d, ITEM_RESOURCENAME, rsrcname) - elif item == ITEM_APPLETBROWSE: - fss, ok = macfs.StandardPutFile("Applet output file", os.path.split(appletname)[1]) - if ok: - appletname = fss.as_pathname() - _dialogsetfile(d, ITEM_APPLETNAME, appletname) - else: - pass - tp, h, rect = d.GetDialogItem(ITEM_DEBUG) - debug = Dlg.GetDialogItemText(h) - try: - debug = string.atoi(string.strip(debug)) - except ValueError: - EasyDialogs.Message("Illegal debug value %r, set to zero."%(debug,)) - debug = 0 - if gentype == ITEM_GENSOURCE: - return 'source', script, dirname, debug - elif gentype == ITEM_GENRESOURCE: - return 'resource', script, rsrcname, debug - elif gentype == ITEM_GENAPPLET: - return 'applet', script, appletname, debug - elif gentype == ITEM_GENINFO: - return 'info', script, '', debug - raise 'Error in gentype', gentype + # Fill the dialog + d.SetDialogDefaultItem(ITEM_OK) + d.SetDialogCancelItem(ITEM_CANCEL) + + _dialogsetfile(d, ITEM_SCRIPTNAME, script) + _dialogsetfile(d, ITEM_SOURCEDIRNAME, dirname) + _dialogsetfile(d, ITEM_RESOURCENAME, rsrcname) + _dialogsetfile(d, ITEM_APPLETNAME, appletname) + + gentype = ITEM_GENSOURCE + _dialogradiogroup(d, ITEM_GENSOURCE) + + # Interact + d.GetDialogWindow().SetWTitle("Standalone application creation options") + d.GetDialogWindow().ShowWindow() + d.DrawDialog() + while 1: + item = Dlg.ModalDialog(None) + if item == ITEM_OK: + break + elif item == ITEM_CANCEL: + sys.exit(0) + elif item in RADIO_GROUPING.keys(): + gentype = item + _dialogradiogroup(d, item) + elif item == ITEM_SCRIPTBROWSE: + fss, ok = macfs.PromptGetFile("Script?") + if ok: + script = fss.as_pathname() + _dialogsetfile(d, ITEM_SCRIPTNAME, script) + elif item == ITEM_SOURCEDIRBROWSE: + fss, ok = macfs.StandardPutFile("Output folder name", os.path.split(dirname)[1]) + if ok: + dirname = fss.as_pathname() + _dialogsetfile(d, ITEM_SOURCEDIRNAME, dirname) + elif item == ITEM_RESOURCEBROWSE: + fss, ok = macfs.StandardPutFile("Resource output file", os.path.split(rsrcname)[1]) + if ok: + rsrcname = fss.as_pathname() + _dialogsetfile(d, ITEM_RESOURCENAME, rsrcname) + elif item == ITEM_APPLETBROWSE: + fss, ok = macfs.StandardPutFile("Applet output file", os.path.split(appletname)[1]) + if ok: + appletname = fss.as_pathname() + _dialogsetfile(d, ITEM_APPLETNAME, appletname) + else: + pass + tp, h, rect = d.GetDialogItem(ITEM_DEBUG) + debug = Dlg.GetDialogItemText(h) + try: + debug = string.atoi(string.strip(debug)) + except ValueError: + EasyDialogs.Message("Illegal debug value %r, set to zero."%(debug,)) + debug = 0 + if gentype == ITEM_GENSOURCE: + return 'source', script, dirname, debug + elif gentype == ITEM_GENRESOURCE: + return 'resource', script, rsrcname, debug + elif gentype == ITEM_GENAPPLET: + return 'applet', script, appletname, debug + elif gentype == ITEM_GENINFO: + return 'info', script, '', debug + raise 'Error in gentype', gentype def _dialogradiogroup(d, item): - for k in RADIO_GROUPING.keys(): - subitems = RADIO_GROUPING[k] - tp, h, rect = d.GetDialogItem(k) - if k == item: - h.as_Control().SetControlValue(1) - for i2 in subitems: - d.ShowDialogItem(i2) - else: - h.as_Control().SetControlValue(0) - for i2 in subitems: - d.HideDialogItem(i2) + for k in RADIO_GROUPING.keys(): + subitems = RADIO_GROUPING[k] + tp, h, rect = d.GetDialogItem(k) + if k == item: + h.as_Control().SetControlValue(1) + for i2 in subitems: + d.ShowDialogItem(i2) + else: + h.as_Control().SetControlValue(0) + for i2 in subitems: + d.HideDialogItem(i2) def _dialogsetfile(d, item, file): - if len(file) > 32: - file = '\311:' + os.path.split(file)[1] - tp, h, rect = d.GetDialogItem(item) - Dlg.SetDialogItemText(h, file) - + if len(file) > 32: + file = '\311:' + os.path.split(file)[1] + tp, h, rect = d.GetDialogItem(item) + Dlg.SetDialogItemText(h, file) + if __name__ == '__main__': - type, script, file, debug = dialog() - print type, script, file, 'debug=%d'%debug - sys.exit(1) + type, script, file, debug = dialog() + print type, script, file, 'debug=%d'%debug + sys.exit(1) diff --git a/Mac/Tools/macfreeze/macgen_bin.py b/Mac/Tools/macfreeze/macgen_bin.py index 8735e171..bfcdc8b 100644 --- a/Mac/Tools/macfreeze/macgen_bin.py +++ b/Mac/Tools/macfreeze/macgen_bin.py @@ -14,208 +14,208 @@ import buildtools def generate(input, output, module_dict=None, architecture='fat', debug=0): - # try to remove old file - try: - os.remove(output) - except: - pass - - if module_dict is None: - import macmodulefinder - print "Searching for modules..." - module_dict, missing = macmodulefinder.process(input, [], [], 1) - if missing: - import EasyDialogs - missing.sort() - answer = EasyDialogs.AskYesNoCancel("Some modules could not be found; continue anyway?\n(%s)" - % string.join(missing, ", ")) - if answer <> 1: - sys.exit(0) - - applettemplatepath = buildtools.findtemplate() - corepath = findpythoncore() - - dynamicmodules, dynamicfiles, extraresfiles = findfragments(module_dict, architecture) - - print 'Adding "__main__"' - buildtools.process(applettemplatepath, input, output, 0) - - outputref = Res.FSpOpenResFile(output, 3) - try: - Res.UseResFile(outputref) - - print "Adding Python modules" - addpythonmodules(module_dict) - - print "Adding PythonCore resources" - copyres(corepath, outputref, ['cfrg', 'Popt', 'GU\267I'], 1) - - print "Adding resources from shared libraries" - for ppcpath, cfm68kpath in extraresfiles: - if os.path.exists(ppcpath): - copyres(ppcpath, outputref, ['cfrg'], 1) - elif os.path.exists(cfm68kpath): - copyres(cfm68kpath, outputref, ['cfrg'], 1) - - print "Fixing sys.path prefs" - Res.UseResFile(outputref) - try: - res = Res.Get1Resource('STR#', 228) # from PythonCore - except Res.Error: pass - else: - res.RemoveResource() - # setting pref file name to empty string - res = Res.Get1NamedResource('STR ', "PythonPreferenceFileName") - res.data = Pstring("") - res.ChangedResource() - syspathpref = "$(APPLICATION)" - res = Res.Resource("\000\001" + Pstring(syspathpref)) - res.AddResource("STR#", 229, "sys.path preference") - - print "Creating 'PYD ' resources" - for modname, (ppcfrag, cfm68kfrag) in dynamicmodules.items(): - res = Res.Resource(Pstring(ppcfrag) + Pstring(cfm68kfrag)) - id = 0 - while id < 128: - id = Res.Unique1ID('PYD ') - res.AddResource('PYD ', id, modname) - finally: - Res.CloseResFile(outputref) - print "Merging code fragments" - cfmfile.mergecfmfiles([applettemplatepath, corepath] + dynamicfiles.keys(), - output, architecture) - - print "done!" + # try to remove old file + try: + os.remove(output) + except: + pass + + if module_dict is None: + import macmodulefinder + print "Searching for modules..." + module_dict, missing = macmodulefinder.process(input, [], [], 1) + if missing: + import EasyDialogs + missing.sort() + answer = EasyDialogs.AskYesNoCancel("Some modules could not be found; continue anyway?\n(%s)" + % string.join(missing, ", ")) + if answer <> 1: + sys.exit(0) + + applettemplatepath = buildtools.findtemplate() + corepath = findpythoncore() + + dynamicmodules, dynamicfiles, extraresfiles = findfragments(module_dict, architecture) + + print 'Adding "__main__"' + buildtools.process(applettemplatepath, input, output, 0) + + outputref = Res.FSpOpenResFile(output, 3) + try: + Res.UseResFile(outputref) + + print "Adding Python modules" + addpythonmodules(module_dict) + + print "Adding PythonCore resources" + copyres(corepath, outputref, ['cfrg', 'Popt', 'GU\267I'], 1) + + print "Adding resources from shared libraries" + for ppcpath, cfm68kpath in extraresfiles: + if os.path.exists(ppcpath): + copyres(ppcpath, outputref, ['cfrg'], 1) + elif os.path.exists(cfm68kpath): + copyres(cfm68kpath, outputref, ['cfrg'], 1) + + print "Fixing sys.path prefs" + Res.UseResFile(outputref) + try: + res = Res.Get1Resource('STR#', 228) # from PythonCore + except Res.Error: pass + else: + res.RemoveResource() + # setting pref file name to empty string + res = Res.Get1NamedResource('STR ', "PythonPreferenceFileName") + res.data = Pstring("") + res.ChangedResource() + syspathpref = "$(APPLICATION)" + res = Res.Resource("\000\001" + Pstring(syspathpref)) + res.AddResource("STR#", 229, "sys.path preference") + + print "Creating 'PYD ' resources" + for modname, (ppcfrag, cfm68kfrag) in dynamicmodules.items(): + res = Res.Resource(Pstring(ppcfrag) + Pstring(cfm68kfrag)) + id = 0 + while id < 128: + id = Res.Unique1ID('PYD ') + res.AddResource('PYD ', id, modname) + finally: + Res.CloseResFile(outputref) + print "Merging code fragments" + cfmfile.mergecfmfiles([applettemplatepath, corepath] + dynamicfiles.keys(), + output, architecture) + + print "done!" def findfragments(module_dict, architecture): - dynamicmodules = {} - dynamicfiles = {} - extraresfiles = [] - for name, module in module_dict.items(): - if module.gettype() <> 'dynamic': - continue - path = resolvealiasfile(module.__file__) - dir, filename = os.path.split(path) -## ppcfile, cfm68kfile = makefilenames(filename) - ppcfile = filename - cfm68kfile = "dummy.cfm68k.slb" - - # ppc stuff - ppcpath = os.path.join(dir, ppcfile) - if architecture <> 'm68k': - ppcfrag, dynamicfiles = getfragname(ppcpath, dynamicfiles) - else: - ppcfrag = "_no_fragment_" - - # 68k stuff - cfm68kpath = os.path.join(dir, cfm68kfile) - if architecture <> 'pwpc': - cfm68kfrag, dynamicfiles = getfragname(cfm68kpath, dynamicfiles) - else: - cfm68kfrag = "_no_fragment_" - - dynamicmodules[name] = ppcfrag, cfm68kfrag - if (ppcpath, cfm68kpath) not in extraresfiles: - extraresfiles.append((ppcpath, cfm68kpath)) - return dynamicmodules, dynamicfiles, extraresfiles + dynamicmodules = {} + dynamicfiles = {} + extraresfiles = [] + for name, module in module_dict.items(): + if module.gettype() <> 'dynamic': + continue + path = resolvealiasfile(module.__file__) + dir, filename = os.path.split(path) +## ppcfile, cfm68kfile = makefilenames(filename) + ppcfile = filename + cfm68kfile = "dummy.cfm68k.slb" + + # ppc stuff + ppcpath = os.path.join(dir, ppcfile) + if architecture <> 'm68k': + ppcfrag, dynamicfiles = getfragname(ppcpath, dynamicfiles) + else: + ppcfrag = "_no_fragment_" + + # 68k stuff + cfm68kpath = os.path.join(dir, cfm68kfile) + if architecture <> 'pwpc': + cfm68kfrag, dynamicfiles = getfragname(cfm68kpath, dynamicfiles) + else: + cfm68kfrag = "_no_fragment_" + + dynamicmodules[name] = ppcfrag, cfm68kfrag + if (ppcpath, cfm68kpath) not in extraresfiles: + extraresfiles.append((ppcpath, cfm68kpath)) + return dynamicmodules, dynamicfiles, extraresfiles def getfragname(path, dynamicfiles): - if not dynamicfiles.has_key(path): - if os.path.exists(path): - lib = cfmfile.CfrgResource(path) - fragname = lib.fragments[0].name - else: - print "shared lib not found:", path - fragname = "_no_fragment_" - dynamicfiles[path] = fragname - else: - fragname = dynamicfiles[path] - return fragname, dynamicfiles + if not dynamicfiles.has_key(path): + if os.path.exists(path): + lib = cfmfile.CfrgResource(path) + fragname = lib.fragments[0].name + else: + print "shared lib not found:", path + fragname = "_no_fragment_" + dynamicfiles[path] = fragname + else: + fragname = dynamicfiles[path] + return fragname, dynamicfiles def addpythonmodules(module_dict): - # XXX should really use macgen_rsrc.generate(), this does the same, but skips __main__ - items = module_dict.items() - items.sort() - for name, module in items: - mtype = module.gettype() - if mtype not in ['module', 'package'] or name == "__main__": - continue - location = module.__file__ - - if location[-4:] == '.pyc': - # Attempt corresponding .py - location = location[:-1] - if location[-3:] != '.py': - print '*** skipping', location - continue - - print 'Adding module "%s"' % name - id, name = py_resource.frompyfile(location, name, preload=0, - ispackage=mtype=='package') + # XXX should really use macgen_rsrc.generate(), this does the same, but skips __main__ + items = module_dict.items() + items.sort() + for name, module in items: + mtype = module.gettype() + if mtype not in ['module', 'package'] or name == "__main__": + continue + location = module.__file__ + + if location[-4:] == '.pyc': + # Attempt corresponding .py + location = location[:-1] + if location[-3:] != '.py': + print '*** skipping', location + continue + + print 'Adding module "%s"' % name + id, name = py_resource.frompyfile(location, name, preload=0, + ispackage=mtype=='package') def Pstring(str): - if len(str) > 255: - raise TypeError, "Str255 must be at most 255 chars long" - return chr(len(str)) + str + if len(str) > 255: + raise TypeError, "Str255 must be at most 255 chars long" + return chr(len(str)) + str ##def makefilenames(name): -## lname = string.lower(name) -## pos = string.find(lname, ".ppc.") -## if pos > 0: -## return name, name[:pos] + '.CFM68K.' + name[pos+5:] -## pos = string.find(lname, ".cfm68k.") -## if pos > 0: -## return name[:pos] + '.ppc.' + name[pos+8:], name -## raise ValueError, "can't make ppc/cfm68k filenames" +## lname = string.lower(name) +## pos = string.find(lname, ".ppc.") +## if pos > 0: +## return name, name[:pos] + '.CFM68K.' + name[pos+5:] +## pos = string.find(lname, ".cfm68k.") +## if pos > 0: +## return name[:pos] + '.ppc.' + name[pos+8:], name +## raise ValueError, "can't make ppc/cfm68k filenames" def copyres(input, output, *args, **kwargs): - openedin = openedout = 0 - if type(input) == types.StringType: - input = Res.FSpOpenResFile(input, 1) - openedin = 1 - if type(output) == types.StringType: - output = Res.FSpOpenResFile(output, 3) - openedout = 1 - try: - apply(buildtools.copyres, (input, output) + args, kwargs) - finally: - if openedin: - Res.CloseResFile(input) - if openedout: - Res.CloseResFile(output) + openedin = openedout = 0 + if type(input) == types.StringType: + input = Res.FSpOpenResFile(input, 1) + openedin = 1 + if type(output) == types.StringType: + output = Res.FSpOpenResFile(output, 3) + openedout = 1 + try: + apply(buildtools.copyres, (input, output) + args, kwargs) + finally: + if openedin: + Res.CloseResFile(input) + if openedout: + Res.CloseResFile(output) def findpythoncore(): - """find the PythonCore shared library, possibly asking the user if we can't find it""" - - try: - vRefNum, dirID = macfs.FindFolder(kOnSystemDisk, kSharedLibrariesFolderType, 0) - except macfs.error: - extpath = ":" - else: - extpath = macfs.FSSpec((vRefNum, dirID, "")).as_pathname() - version = string.split(sys.version)[0] - if MacOS.runtimemodel == 'carbon': - corename = "PythonCoreCarbon " + version - elif MacOS.runtimemodel == 'ppc': - corename = "PythonCore " + version - else: - raise "Unknown MacOS.runtimemodel", MacOS.runtimemodel - corepath = os.path.join(extpath, corename) - if not os.path.exists(corepath): - corepath = EasyDialogs.AskFileForOpen(message="Please locate PythonCore:", - typeList=("shlb",)) - if not corepath: - raise KeyboardInterrupt, "cancelled" - return resolvealiasfile(corepath) + """find the PythonCore shared library, possibly asking the user if we can't find it""" + + try: + vRefNum, dirID = macfs.FindFolder(kOnSystemDisk, kSharedLibrariesFolderType, 0) + except macfs.error: + extpath = ":" + else: + extpath = macfs.FSSpec((vRefNum, dirID, "")).as_pathname() + version = string.split(sys.version)[0] + if MacOS.runtimemodel == 'carbon': + corename = "PythonCoreCarbon " + version + elif MacOS.runtimemodel == 'ppc': + corename = "PythonCore " + version + else: + raise "Unknown MacOS.runtimemodel", MacOS.runtimemodel + corepath = os.path.join(extpath, corename) + if not os.path.exists(corepath): + corepath = EasyDialogs.AskFileForOpen(message="Please locate PythonCore:", + typeList=("shlb",)) + if not corepath: + raise KeyboardInterrupt, "cancelled" + return resolvealiasfile(corepath) def resolvealiasfile(path): - try: - fss, dummy1, dummy2 = macfs.ResolveAliasFile(path) - except macfs.error: - pass - else: - path = fss.as_pathname() - return path + try: + fss, dummy1, dummy2 = macfs.ResolveAliasFile(path) + except macfs.error: + pass + else: + path = fss.as_pathname() + return path diff --git a/Mac/Tools/macfreeze/macgen_info.py b/Mac/Tools/macfreeze/macgen_info.py index 2d984c1..d2edb92 100644 --- a/Mac/Tools/macfreeze/macgen_info.py +++ b/Mac/Tools/macfreeze/macgen_info.py @@ -1,8 +1,8 @@ """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 + for name in module_dict.keys(): + print 'Include %-20s\t'%name, + module = module_dict[name] + print module.gettype(), '\t', repr(module) + return 0 diff --git a/Mac/Tools/macfreeze/macgen_rsrc.py b/Mac/Tools/macfreeze/macgen_rsrc.py index 03fc0af..34c17ff 100644 --- a/Mac/Tools/macfreeze/macgen_rsrc.py +++ b/Mac/Tools/macfreeze/macgen_rsrc.py @@ -5,33 +5,32 @@ from Carbon import Res import sys def generate(output, module_dict, debug=0, preload=1): - fsid = py_resource.create(output) - - for name, module in module_dict.items(): - mtype = module.gettype() - if mtype not in ['module', 'package']: - continue - location = module.__file__ - - if location[-4:] == '.pyc': - # Attempt corresponding .py - location = location[:-1] - if location[-3:] != '.py': - print '*** skipping', location - continue - - id, name = py_resource.frompyfile(location, name, preload=preload, - ispackage=mtype=='package') - if debug > 0: - print 'PYC resource %5d\t%s\t%s'%(id, name, location) - - Res.CloseResFile(fsid) - + fsid = py_resource.create(output) + + for name, module in module_dict.items(): + mtype = module.gettype() + if mtype not in ['module', 'package']: + continue + location = module.__file__ + + if location[-4:] == '.pyc': + # Attempt corresponding .py + location = location[:-1] + if location[-3:] != '.py': + print '*** skipping', location + continue + + id, name = py_resource.frompyfile(location, name, preload=preload, + ispackage=mtype=='package') + if debug > 0: + print 'PYC resource %5d\t%s\t%s'%(id, name, location) + + Res.CloseResFile(fsid) + def warnings(module_dict): - problems = 0 - for name, module in module_dict.items(): - if module.gettype() not in ('builtin', 'module', 'package'): - problems = problems + 1 - print 'Warning: %s not included: %s %s'%(name, module.gettype(), module) - return problems - + problems = 0 + for name, module in module_dict.items(): + if module.gettype() not in ('builtin', 'module', 'package'): + problems = problems + 1 + print 'Warning: %s not included: %s %s'%(name, module.gettype(), module) + return problems diff --git a/Mac/Tools/macfreeze/macgen_src.py b/Mac/Tools/macfreeze/macgen_src.py index 089727a..301e85e 100644 --- a/Mac/Tools/macfreeze/macgen_src.py +++ b/Mac/Tools/macfreeze/macgen_src.py @@ -16,98 +16,98 @@ CONFIG_TEMPLATE=os.path.join(TEMPLATEDIR, ':templatefrozenconfig.c') BUNDLE_TEMPLATE=os.path.join(TEMPLATEDIR, ':frozenbundle.rsrc') def generate(output, module_dict, debug=0, with_ifdef=0): - problems = 0 - output_created=0 - if not os.path.exists(output): - print 'Creating project folder', output - os.mkdir(output) - output_created = 1 - # Resolve aliases, if needed - try: - fss, dummy1, dummy2 = macfs.ResolveAliasFile(output) - except macfs.error: - pass - else: - newname = fss.as_pathname() - if newname != output: - if debug: - print 'Alias', output - print 'Resolved to', newname - output = newname - # Construct the filenames - dummy, outfile = os.path.split(output) - build, ext = os.path.splitext(outfile) - if build == 'build' and ext[0] == '.': - # This is probably a good name for the project - projname = ext[1:] - else: - projname = 'frozenapplet.prj' - config_name = os.path.join(output, ':macfrozenconfig.c') - project_name = os.path.join(output, ':' + projname + '.prj') - resource_name = os.path.join(output, ':frozenmodules.rsrc') - bundle_name = os.path.join(output, ':frozenbundle.rsrc') + problems = 0 + output_created=0 + if not os.path.exists(output): + print 'Creating project folder', output + os.mkdir(output) + output_created = 1 + # Resolve aliases, if needed + try: + fss, dummy1, dummy2 = macfs.ResolveAliasFile(output) + except macfs.error: + pass + else: + newname = fss.as_pathname() + if newname != output: + if debug: + print 'Alias', output + print 'Resolved to', newname + output = newname + # Construct the filenames + dummy, outfile = os.path.split(output) + build, ext = os.path.splitext(outfile) + if build == 'build' and ext[0] == '.': + # This is probably a good name for the project + projname = ext[1:] + else: + projname = 'frozenapplet.prj' + config_name = os.path.join(output, ':macfrozenconfig.c') + project_name = os.path.join(output, ':' + projname + '.prj') + resource_name = os.path.join(output, ':frozenmodules.rsrc') + bundle_name = os.path.join(output, ':frozenbundle.rsrc') - # Fill the output folder, if needed. - if output_created: - # Create the project, if needed - if not os.path.exists(project_name): - print 'Creating project', project_name - if not os.path.exists(PROJECT_TEMPLATE): - print '** No template CodeWarrior project found at', PROJECT_TEMPLATE - print ' To generate standalone Python applications from source you need' - print ' a full source distribution. Check http://www.cwi.nl/~jack/macpython.html' - print ' for details.' - problems = 1 - else: - macostools.copy(PROJECT_TEMPLATE, project_name) - print 'A template CodeWarrior project has been copied to', project_name - print 'It is up to you to make the following changes:' - print '- Change the output file name' - print '- Change the search path, unless the folder is in the python home' - print '- Add sourcefiles/libraries for any extension modules used' - print '- Remove unused sources, to speed up the build process' - print '- Remove unused resource files (like tcl/tk) for a smaller binary' - problems = 1 - macostools.copy(BUNDLE_TEMPLATE, bundle_name) - print 'A template bundle file has also been copied to', bundle_name - print 'You may want to adapt signature, size resource, etc' + # Fill the output folder, if needed. + if output_created: + # Create the project, if needed + if not os.path.exists(project_name): + print 'Creating project', project_name + if not os.path.exists(PROJECT_TEMPLATE): + print '** No template CodeWarrior project found at', PROJECT_TEMPLATE + print ' To generate standalone Python applications from source you need' + print ' a full source distribution. Check http://www.cwi.nl/~jack/macpython.html' + print ' for details.' + problems = 1 + else: + macostools.copy(PROJECT_TEMPLATE, project_name) + print 'A template CodeWarrior project has been copied to', project_name + print 'It is up to you to make the following changes:' + print '- Change the output file name' + print '- Change the search path, unless the folder is in the python home' + print '- Add sourcefiles/libraries for any extension modules used' + print '- Remove unused sources, to speed up the build process' + print '- Remove unused resource files (like tcl/tk) for a smaller binary' + problems = 1 + macostools.copy(BUNDLE_TEMPLATE, bundle_name) + print 'A template bundle file has also been copied to', bundle_name + print 'You may want to adapt signature, size resource, etc' + + + # Create the resource file + macgen_rsrc.generate(resource_name, module_dict, debug=debug) + + # Create the config.c file + if not os.path.exists(CONFIG_TEMPLATE): + print '** No template config.c found at', PROJECT_TEMPLATE + print ' To generate standalone Python applications from source you need' + print ' a full source distribution. Check http://www.cwi.nl/~jack/macpython.html' + print ' for details.' + problems = 1 + else: + # Find elegible modules (builtins and dynamically loaded modules) + c_modules = [] + for module in module_dict.keys(): + if module_dict[module].gettype() in ('builtin', 'dynamic'): + # if the module is in a package we have no choice but + # to put it at the toplevel in the frozen application. + if '.' in module: + module = module.split('.')[-1] + c_modules.append(module) + ifp = open(CONFIG_TEMPLATE) + ofp = open(config_name, 'w') + makeconfig.makeconfig(ifp, ofp, c_modules, with_ifdef) + ifp.close() + ofp.close() + MacOS.SetCreatorAndType(config_name, 'CWIE', 'TEXT') + + if warnings(module_dict): + problems = 1 + return problems - - # Create the resource file - macgen_rsrc.generate(resource_name, module_dict, debug=debug) - - # Create the config.c file - if not os.path.exists(CONFIG_TEMPLATE): - print '** No template config.c found at', PROJECT_TEMPLATE - print ' To generate standalone Python applications from source you need' - print ' a full source distribution. Check http://www.cwi.nl/~jack/macpython.html' - print ' for details.' - problems = 1 - else: - # Find elegible modules (builtins and dynamically loaded modules) - c_modules = [] - for module in module_dict.keys(): - if module_dict[module].gettype() in ('builtin', 'dynamic'): - # if the module is in a package we have no choice but - # to put it at the toplevel in the frozen application. - if '.' in module: - module = module.split('.')[-1] - c_modules.append(module) - ifp = open(CONFIG_TEMPLATE) - ofp = open(config_name, 'w') - makeconfig.makeconfig(ifp, ofp, c_modules, with_ifdef) - ifp.close() - ofp.close() - MacOS.SetCreatorAndType(config_name, 'CWIE', 'TEXT') - - if warnings(module_dict): - problems = 1 - return problems - def warnings(module_dict): - problems = 0 - for name, module in module_dict.items(): - if module.gettype() not in ('builtin', 'module', 'dynamic', 'package'): - problems = problems + 1 - print 'Warning: %s not included: %s %s'%(name, module.gettype(), module) - return problems + problems = 0 + for name, module in module_dict.items(): + if module.gettype() not in ('builtin', 'module', 'dynamic', 'package'): + problems = problems + 1 + print 'Warning: %s not included: %s %s'%(name, module.gettype(), module) + return problems diff --git a/Mac/Tools/macfreeze/macgenerate.py b/Mac/Tools/macfreeze/macgenerate.py index dfa2047..12343c3 100644 --- a/Mac/Tools/macfreeze/macgenerate.py +++ b/Mac/Tools/macfreeze/macgenerate.py @@ -1,8 +1,8 @@ """macgenerate - Generate the out for macfreeze""" def generate(program, 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 + for name in module_dict.keys(): + print 'Include %-20s\t'%name, + module = module_dict[name] + print module.gettype(), '\t', repr(module) + return 0 diff --git a/Mac/Tools/macfreeze/macmodulefinder.py b/Mac/Tools/macfreeze/macmodulefinder.py index 285f51f..3f4e0b7 100644 --- a/Mac/Tools/macfreeze/macmodulefinder.py +++ b/Mac/Tools/macfreeze/macmodulefinder.py @@ -7,40 +7,40 @@ import os import directives try: - # This will work if we are frozen ourselves - import modulefinder + # This will work if we are frozen ourselves + import modulefinder except ImportError: - # And this will work otherwise - _FREEZEDIR=os.path.join(sys.prefix, ':Tools:freeze') - sys.path.insert(0, _FREEZEDIR) - import modulefinder + # And this will work otherwise + _FREEZEDIR=os.path.join(sys.prefix, ':Tools:freeze') + sys.path.insert(0, _FREEZEDIR) + import modulefinder # # Modules that must be included, and modules that need not be included # (but are if they are found) # MAC_INCLUDE_MODULES=['site'] -MAC_MAYMISS_MODULES=['posix', 'os2', 'nt', 'ntpath', 'dos', 'dospath', - 'win32api', 'ce', '_winreg', - 'nturl2path', 'pwd', 'sitecustomize', - 'org.python.core', - 'riscos', 'riscosenviron', 'riscospath' - ] +MAC_MAYMISS_MODULES=['posix', 'os2', 'nt', 'ntpath', 'dos', 'dospath', + 'win32api', 'ce', '_winreg', + 'nturl2path', 'pwd', 'sitecustomize', + 'org.python.core', + 'riscos', 'riscosenviron', 'riscospath' + ] # An exception: Missing="macmodulefinder.Missing" class Module(modulefinder.Module): - - def gettype(self): - """Return type of module""" - if self.__path__: - return 'package' - if self.__code__: - return 'module' - if self.__file__: - return 'dynamic' - return 'builtin' + + def gettype(self): + """Return type of module""" + if self.__path__: + return 'package' + if self.__code__: + return 'module' + if self.__file__: + return 'dynamic' + return 'builtin' class ModuleFinder(modulefinder.ModuleFinder): @@ -49,64 +49,64 @@ class ModuleFinder(modulefinder.ModuleFinder): return self.modules[fqname] self.modules[fqname] = m = Module(fqname) return m - + def process(program, modules=None, module_files=None, debug=0): - if modules is None: - modules = [] - if module_files is None: - module_files = [] - missing = [] - # - # Add the standard modules needed for startup - # - modules = modules + MAC_INCLUDE_MODULES - # - # search the main source for directives - # - extra_modules, exclude_modules, optional_modules, extra_path = \ - directives.findfreezedirectives(program) - for m in extra_modules: - if os.sep in m: - # It is a file - module_files.append(m) - else: - modules.append(m) + if modules is None: + modules = [] + if module_files is None: + module_files = [] + missing = [] + # + # Add the standard modules needed for startup + # + modules = modules + MAC_INCLUDE_MODULES + # + # search the main source for directives + # + extra_modules, exclude_modules, optional_modules, extra_path = \ + directives.findfreezedirectives(program) + for m in extra_modules: + if os.sep in m: + # It is a file + module_files.append(m) + else: + modules.append(m) # collect all modules of the program - path = sys.path[:] - dir = os.path.dirname(program) - path[0] = dir # "current dir" - path = extra_path + path - # - # Create the module finder and let it do its work - # - modfinder = ModuleFinder(path, - excludes=exclude_modules, debug=debug) - for m in modules: - modfinder.import_hook(m) - for m in module_files: - modfinder.load_file(m) - modfinder.run_script(program) - module_dict = modfinder.modules - # - # Tell the user about missing modules - # - maymiss = exclude_modules + optional_modules + MAC_MAYMISS_MODULES - for m in modfinder.badmodules.keys(): - if not m in maymiss: - if debug > 0: - print 'Missing', m - missing.append(m) - # - # Warn the user about unused builtins - # - for m in sys.builtin_module_names: - if m in ('__main__', '__builtin__'): - pass - elif not module_dict.has_key(m): - if debug > 0: - print 'Unused', m - elif module_dict[m].gettype() != 'builtin': - # XXXX Can this happen? - if debug > 0: - print 'Conflict', m - return module_dict, missing + path = sys.path[:] + dir = os.path.dirname(program) + path[0] = dir # "current dir" + path = extra_path + path + # + # Create the module finder and let it do its work + # + modfinder = ModuleFinder(path, + excludes=exclude_modules, debug=debug) + for m in modules: + modfinder.import_hook(m) + for m in module_files: + modfinder.load_file(m) + modfinder.run_script(program) + module_dict = modfinder.modules + # + # Tell the user about missing modules + # + maymiss = exclude_modules + optional_modules + MAC_MAYMISS_MODULES + for m in modfinder.badmodules.keys(): + if not m in maymiss: + if debug > 0: + print 'Missing', m + missing.append(m) + # + # Warn the user about unused builtins + # + for m in sys.builtin_module_names: + if m in ('__main__', '__builtin__'): + pass + elif not module_dict.has_key(m): + if debug > 0: + print 'Unused', m + elif module_dict[m].gettype() != 'builtin': + # XXXX Can this happen? + if debug > 0: + print 'Conflict', m + return module_dict, missing diff --git a/Mac/scripts/BuildApplet.py b/Mac/scripts/BuildApplet.py index e954854..cb2aed8 100644 --- a/Mac/scripts/BuildApplet.py +++ b/Mac/scripts/BuildApplet.py @@ -17,117 +17,117 @@ import buildtools import getopt def main(): - try: - buildapplet() - except buildtools.BuildError, detail: - EasyDialogs.Message(detail) + try: + buildapplet() + except buildtools.BuildError, detail: + EasyDialogs.Message(detail) def buildapplet(): - buildtools.DEBUG=1 - - # Find the template - # (there's no point in proceeding if we can't find it) - - template = buildtools.findtemplate() - - # Ask for source text if not specified in sys.argv[1:] - - if not sys.argv[1:]: - filename = EasyDialogs.AskFileForOpen(message='Select Python source or applet:', - typeList=('TEXT', 'APPL')) - if not filename: - return - tp, tf = os.path.split(filename) - if tf[-3:] == '.py': - tf = tf[:-3] - else: - tf = tf + '.applet' - dstfilename = EasyDialogs.AskFileForSave(message='Save application as:', - savedFileName=tf) - if not dstfilename: return - cr, tp = MacOS.GetCreatorAndType(filename) - if tp == 'APPL': - buildtools.update(template, filename, dstfilename) - else: - buildtools.process(template, filename, dstfilename, 1) - else: - - SHORTOPTS = "o:r:ne:v?P" - LONGOPTS=("output=", "resource=", "noargv", "extra=", "verbose", "help", "python=") - try: - options, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS) - except getopt.error: - usage() - if options and len(args) > 1: - sys.stderr.write("Cannot use options when specifying multiple input files") - sys.exit(1) - dstfilename = None - rsrcfilename = None - raw = 0 - extras = [] - verbose = None - for opt, arg in options: - if opt in ('-o', '--output'): - dstfilename = arg - elif opt in ('-r', '--resource'): - rsrcfilename = arg - elif opt in ('-n', '--noargv'): - raw = 1 - elif opt in ('-e', '--extra'): - if ':' in arg: - arg = arg.split(':') - extras.append(arg) - elif opt in ('-P', '--python'): - # This is a very dirty trick. We set sys.executable - # so that bundlebuilder will use this in the #! line - # for the applet bootstrap. - sys.executable = arg - elif opt in ('-v', '--verbose'): - verbose = Verbose() - elif opt in ('-?', '--help'): - usage() - # On OS9 always be verbose - if sys.platform == 'mac' and not verbose: - verbose = 'default' - # Loop over all files to be processed - for filename in args: - cr, tp = MacOS.GetCreatorAndType(filename) - if tp == 'APPL': - buildtools.update(template, filename, dstfilename) - else: - buildtools.process(template, filename, dstfilename, 1, - rsrcname=rsrcfilename, others=extras, raw=raw, progress=verbose) + buildtools.DEBUG=1 + + # Find the template + # (there's no point in proceeding if we can't find it) + + template = buildtools.findtemplate() + + # Ask for source text if not specified in sys.argv[1:] + + if not sys.argv[1:]: + filename = EasyDialogs.AskFileForOpen(message='Select Python source or applet:', + typeList=('TEXT', 'APPL')) + if not filename: + return + tp, tf = os.path.split(filename) + if tf[-3:] == '.py': + tf = tf[:-3] + else: + tf = tf + '.applet' + dstfilename = EasyDialogs.AskFileForSave(message='Save application as:', + savedFileName=tf) + if not dstfilename: return + cr, tp = MacOS.GetCreatorAndType(filename) + if tp == 'APPL': + buildtools.update(template, filename, dstfilename) + else: + buildtools.process(template, filename, dstfilename, 1) + else: + + SHORTOPTS = "o:r:ne:v?P" + LONGOPTS=("output=", "resource=", "noargv", "extra=", "verbose", "help", "python=") + try: + options, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS) + except getopt.error: + usage() + if options and len(args) > 1: + sys.stderr.write("Cannot use options when specifying multiple input files") + sys.exit(1) + dstfilename = None + rsrcfilename = None + raw = 0 + extras = [] + verbose = None + for opt, arg in options: + if opt in ('-o', '--output'): + dstfilename = arg + elif opt in ('-r', '--resource'): + rsrcfilename = arg + elif opt in ('-n', '--noargv'): + raw = 1 + elif opt in ('-e', '--extra'): + if ':' in arg: + arg = arg.split(':') + extras.append(arg) + elif opt in ('-P', '--python'): + # This is a very dirty trick. We set sys.executable + # so that bundlebuilder will use this in the #! line + # for the applet bootstrap. + sys.executable = arg + elif opt in ('-v', '--verbose'): + verbose = Verbose() + elif opt in ('-?', '--help'): + usage() + # On OS9 always be verbose + if sys.platform == 'mac' and not verbose: + verbose = 'default' + # Loop over all files to be processed + for filename in args: + cr, tp = MacOS.GetCreatorAndType(filename) + if tp == 'APPL': + buildtools.update(template, filename, dstfilename) + else: + buildtools.process(template, filename, dstfilename, 1, + rsrcname=rsrcfilename, others=extras, raw=raw, progress=verbose) def usage(): - print "BuildApplet creates an application from a Python source file" - print "Usage:" - print " BuildApplet interactive, single file, no options" - print " BuildApplet src1.py src2.py ... non-interactive multiple file" - print " BuildApplet [options] src.py non-interactive single file" - print "Options:" - print " --output o Output file; default based on source filename, short -o" - print " --resource r Resource file; default based on source filename, short -r" - print " --noargv Build applet without drag-and-drop sys.argv emulation, short -n, OSX only" - print " --extra src[:dst] Extra file to put in .app bundle, short -e, OSX only" - print " --verbose Verbose, short -v" - print " --help This message, short -?" - sys.exit(1) + print "BuildApplet creates an application from a Python source file" + print "Usage:" + print " BuildApplet interactive, single file, no options" + print " BuildApplet src1.py src2.py ... non-interactive multiple file" + print " BuildApplet [options] src.py non-interactive single file" + print "Options:" + print " --output o Output file; default based on source filename, short -o" + print " --resource r Resource file; default based on source filename, short -r" + print " --noargv Build applet without drag-and-drop sys.argv emulation, short -n, OSX only" + print " --extra src[:dst] Extra file to put in .app bundle, short -e, OSX only" + print " --verbose Verbose, short -v" + print " --help This message, short -?" + sys.exit(1) class Verbose: - """This class mimics EasyDialogs.ProgressBar but prints to stderr""" - def __init__(self, *args): - if args and args[0]: - self.label(args[0]) - - def set(self, *args): - pass - - def inc(self, *args): - pass - - def label(self, str): - sys.stderr.write(str+'\n') + """This class mimics EasyDialogs.ProgressBar but prints to stderr""" + def __init__(self, *args): + if args and args[0]: + self.label(args[0]) + + def set(self, *args): + pass + + def inc(self, *args): + pass + + def label(self, str): + sys.stderr.write(str+'\n') if __name__ == '__main__': - main() + main() diff --git a/Mac/scripts/bgenall.py b/Mac/scripts/bgenall.py index 6490265..1fe5f34 100644 --- a/Mac/scripts/bgenall.py +++ b/Mac/scripts/bgenall.py @@ -5,52 +5,52 @@ import os import string def bgenone(dirname, shortname): - os.chdir(dirname) - print '%s:'%shortname - # Sigh, we don't want to lose CVS history, so two - # modules have funny names: - if shortname == 'carbonevt': - modulename = 'CarbonEvtscan' - elif shortname == 'ibcarbon': - modulename = 'IBCarbonscan' - else: - modulename = shortname + 'scan' - try: - m = __import__(modulename) - except: - print "Error:", shortname, sys.exc_info()[1] - return 0 - try: - m.main() - except: - print "Error:", shortname, sys.exc_info()[1] - return 0 - return 1 - + os.chdir(dirname) + print '%s:'%shortname + # Sigh, we don't want to lose CVS history, so two + # modules have funny names: + if shortname == 'carbonevt': + modulename = 'CarbonEvtscan' + elif shortname == 'ibcarbon': + modulename = 'IBCarbonscan' + else: + modulename = shortname + 'scan' + try: + m = __import__(modulename) + except: + print "Error:", shortname, sys.exc_info()[1] + return 0 + try: + m.main() + except: + print "Error:", shortname, sys.exc_info()[1] + return 0 + return 1 + def main(): - success = [] - failure = [] - sys.path.insert(0, os.curdir) - if len(sys.argv) > 1: - srcdir = sys.argv[1] - else: - srcdir = os.path.join(os.path.join(sys.prefix, 'Mac'), 'Modules') - srcdir = os.path.abspath(srcdir) - contents = os.listdir(srcdir) - for name in contents: - moduledir = os.path.join(srcdir, name) - scanmodule = os.path.join(moduledir, name +'scan.py') - if os.path.exists(scanmodule): - if bgenone(moduledir, name): - success.append(name) - else: - failure.append(name) - print 'Done:', string.join(success, ' ') - if failure: - print 'Failed:', string.join(failure, ' ') - return 0 - return 1 - + success = [] + failure = [] + sys.path.insert(0, os.curdir) + if len(sys.argv) > 1: + srcdir = sys.argv[1] + else: + srcdir = os.path.join(os.path.join(sys.prefix, 'Mac'), 'Modules') + srcdir = os.path.abspath(srcdir) + contents = os.listdir(srcdir) + for name in contents: + moduledir = os.path.join(srcdir, name) + scanmodule = os.path.join(moduledir, name +'scan.py') + if os.path.exists(scanmodule): + if bgenone(moduledir, name): + success.append(name) + else: + failure.append(name) + print 'Done:', string.join(success, ' ') + if failure: + print 'Failed:', string.join(failure, ' ') + return 0 + return 1 + if __name__ == '__main__': - rv = main() - sys.exit(not rv)
\ No newline at end of file + rv = main() + sys.exit(not rv) diff --git a/Mac/scripts/buildpkg.py b/Mac/scripts/buildpkg.py index a9c70c1..7f635a0 100644 --- a/Mac/scripts/buildpkg.py +++ b/Mac/scripts/buildpkg.py @@ -3,34 +3,34 @@ """buildpkg.py -- Build OS X packages for Apple's Installer.app. This is an experimental command-line tool for building packages to be -installed with the Mac OS X Installer.app application. +installed with the Mac OS X Installer.app application. -It is much inspired by Apple's GUI tool called PackageMaker.app, that -seems to be part of the OS X developer tools installed in the folder -/Developer/Applications. But apparently there are other free tools to -do the same thing which are also named PackageMaker like Brian Hill's -one: +It is much inspired by Apple's GUI tool called PackageMaker.app, that +seems to be part of the OS X developer tools installed in the folder +/Developer/Applications. But apparently there are other free tools to +do the same thing which are also named PackageMaker like Brian Hill's +one: http://personalpages.tds.net/~brian_hill/packagemaker.html -Beware of the multi-package features of Installer.app (which are not -yet supported here) that can potentially screw-up your installation +Beware of the multi-package features of Installer.app (which are not +yet supported here) that can potentially screw-up your installation and are discussed in these articles on Stepwise: http://www.stepwise.com/Articles/Technical/Packages/InstallerWoes.html http://www.stepwise.com/Articles/Technical/Packages/InstallerOnX.html -Beside using the PackageMaker class directly, by importing it inside +Beside using the PackageMaker class directly, by importing it inside another module, say, there are additional ways of using this module: -the top-level buildPackage() function provides a shortcut to the same +the top-level buildPackage() function provides a shortcut to the same feature and is also called when using this module from the command- line. **************************************************************** - NOTE: For now you should be able to run this even on a non-OS X + NOTE: For now you should be able to run this even on a non-OS X system and get something similar to a package, but without - the real archive (needs pax) and bom files (needs mkbom) - inside! This is only for providing a chance for testing to + the real archive (needs pax) and bom files (needs mkbom) + inside! This is only for providing a chance for testing to folks without OS X. **************************************************************** @@ -39,7 +39,7 @@ TODO: - handle multi-volume packages (?) - integrate into distutils (?) -Dinu C. Gherman, +Dinu C. Gherman, gherman@europemail.com November 2001 @@ -120,14 +120,14 @@ class PackageMaker: """A class to generate packages for Mac OS X. This is intended to create OS X packages (with extension .pkg) - containing archives of arbitrary files that the Installer.app + containing archives of arbitrary files that the Installer.app will be able to handle. - As of now, PackageMaker instances need to be created with the - title, version and description of the package to be built. - The package is built after calling the instance method - build(root, **options). It has the same name as the constructor's - title argument plus a '.pkg' extension and is located in the same + As of now, PackageMaker instances need to be created with the + title, version and description of the package to be built. + The package is built after calling the instance method + build(root, **options). It has the same name as the constructor's + title argument plus a '.pkg' extension and is located in the same parent folder that contains the root folder. E.g. this will create a package folder /my/space/distutils.pkg/: @@ -165,7 +165,7 @@ class PackageMaker: info = {"Title": title, "Version": version, "Description": desc} self.packageInfo = copy.deepcopy(self.packageInfoDefaults) self.packageInfo.update(info) - + # variables set later self.packageRootFolder = None self.packageResourceFolder = None @@ -176,8 +176,8 @@ class PackageMaker: def build(self, root, resources=None, **options): """Create a package for some given root folder. - With no 'resources' argument set it is assumed to be the same - as the root directory. Option items replace the default ones + With no 'resources' argument set it is assumed to be the same + as the root directory. Option items replace the default ones in the package info. """ @@ -195,12 +195,12 @@ class PackageMaker: self.packageInfo[k] = v elif not k in ["OutputDir"]: raise Error, "Unknown package option: %s" % k - + # Check where we should leave the output. Default is current directory outputdir = options.get("OutputDir", os.getcwd()) packageName = self.packageInfo["Title"] self.PackageRootFolder = os.path.join(outputdir, packageName + ".pkg") - + # do what needs to be done self._makeFolders() self._addInfo() @@ -215,7 +215,7 @@ class PackageMaker: "Create package folder structure." # Not sure if the package name should contain the version or not... - # packageName = "%s-%s" % (self.packageInfo["Title"], + # packageName = "%s-%s" % (self.packageInfo["Title"], # self.packageInfo["Version"]) # ?? contFolder = join(self.PackageRootFolder, "Contents") @@ -267,7 +267,7 @@ class PackageMaker: self.archPath = join(self.packageResourceFolder, base) cmd = "pax -w -f %s %s" % (self.archPath, ".") res = os.system(cmd) - + # compress archive cmd = "gzip %s" % self.archPath res = os.system(cmd) @@ -277,8 +277,8 @@ class PackageMaker: def _addResources(self): "Add Welcome/ReadMe/License files, .lproj folders and scripts." - # Currently we just copy everything that matches the allowed - # filenames. So, it's left to Installer.app to deal with the + # Currently we just copy everything that matches the allowed + # filenames. So, it's left to Installer.app to deal with the # same file available in multiple formats... if not self.resourceFolder: @@ -337,9 +337,9 @@ class PackageMaker: def _addSizes(self): "Write .sizes file with info about number and size of files." - # Not sure if this is correct, but 'installedSize' and - # 'zippedSize' are now in Bytes. Maybe blocks are needed? - # Well, Installer.app doesn't seem to care anyway, saying + # Not sure if this is correct, but 'installedSize' and + # 'zippedSize' are now in Bytes. Maybe blocks are needed? + # Well, Installer.app doesn't seem to care anyway, saying # the installation needs 100+ MB... numFiles = 0 @@ -353,7 +353,7 @@ class PackageMaker: try: zippedSize = os.stat(self.archPath+ ".gz")[6] - except OSError: # ignore error + except OSError: # ignore error pass base = self.packageInfo["Title"] + ".sizes" f = open(join(self.packageResourceFolder, base), "w") @@ -370,7 +370,7 @@ class PackageMaker: def buildPackage(*args, **options): "A Shortcut function for building a package." - + o = options title, version, desc = o["Title"], o["Version"], o["Description"] pm = PackageMaker(title, version, desc) @@ -391,9 +391,9 @@ def test0(): def test1(): "Test for the reportlab distribution with modified options." - pm = PackageMaker("reportlab", "1.10", + pm = PackageMaker("reportlab", "1.10", "ReportLab's Open Source PDF toolkit.") - pm.build(root="/Users/dinu/Desktop/reportlab", + pm.build(root="/Users/dinu/Desktop/reportlab", DefaultLocation="/Applications/ReportLab", Relocatable="YES") @@ -401,9 +401,9 @@ def test2(): "Shortcut test for the reportlab distribution with modified options." buildPackage( - "/Users/dinu/Desktop/reportlab", - Title="reportlab", - Version="1.10", + "/Users/dinu/Desktop/reportlab", + Title="reportlab", + Version="1.10", Description="ReportLab's Open Source PDF toolkit.", DefaultLocation="/Applications/ReportLab", Relocatable="YES") diff --git a/Mac/scripts/cachersrc.py b/Mac/scripts/cachersrc.py index e6524c9..e2eed8b 100644 --- a/Mac/scripts/cachersrc.py +++ b/Mac/scripts/cachersrc.py @@ -10,36 +10,35 @@ import sys import getopt class NoArgsError(Exception): - pass - + pass + def handler((verbose, force), dirname, fnames): - for fn in fnames: - if fn[-5:] == '.rsrc' and fn[-13:] != '.rsrc.df.rsrc': - if force: - try: - os.unlink(os.path.join(dirname, fn + '.df.rsrc')) - except IOError: - pass - macresource.open_pathname(os.path.join(dirname, fn), verbose=verbose) - + for fn in fnames: + if fn[-5:] == '.rsrc' and fn[-13:] != '.rsrc.df.rsrc': + if force: + try: + os.unlink(os.path.join(dirname, fn + '.df.rsrc')) + except IOError: + pass + macresource.open_pathname(os.path.join(dirname, fn), verbose=verbose) + def main(): - try: - opts, args = getopt.getopt(sys.argv[1:], 'vf') - if not args: - raise NoArgsError - except (getopt.GetoptError, NoArgsError): - sys.stderr.write('Usage: cachersrc.py dirname ...\n') - sys.exit(1) - verbose = 0 - force = 0 - for o, v in opts: - if o == '-v': - verbose = 1 - if o == '-f': - force = 1 - for dir in sys.argv[1:]: - os.path.walk(dir, handler, (verbose, force)) - + try: + opts, args = getopt.getopt(sys.argv[1:], 'vf') + if not args: + raise NoArgsError + except (getopt.GetoptError, NoArgsError): + sys.stderr.write('Usage: cachersrc.py dirname ...\n') + sys.exit(1) + verbose = 0 + force = 0 + for o, v in opts: + if o == '-v': + verbose = 1 + if o == '-f': + force = 1 + for dir in sys.argv[1:]: + os.path.walk(dir, handler, (verbose, force)) + if __name__ == '__main__': - main() -
\ No newline at end of file + main() diff --git a/Mac/scripts/genallsuites.py b/Mac/scripts/genallsuites.py index 884d4a4..a556847 100644 --- a/Mac/scripts/genallsuites.py +++ b/Mac/scripts/genallsuites.py @@ -22,32 +22,31 @@ NETSCAPE=OS9DISK + "/Applications (Mac OS 9)/Netscape Communicator\xe2\x84\xa2 F TERMINAL="/Applications/Utilities/Terminal.app" gensuitemodule.processfile_fromresource(APPLESCRIPT, - output=os.path.join(DSTDIR, 'StdSuites'), - basepkgname='_builtinSuites', - edit_modnames=[], verbose=verbose) + output=os.path.join(DSTDIR, 'StdSuites'), + basepkgname='_builtinSuites', + edit_modnames=[], verbose=verbose) gensuitemodule.processfile(SYSTEMEVENTS, - output=os.path.join(DSTDIR, 'SystemEvents'), - basepkgname='StdSuites', - edit_modnames=[('Disk_2d_Folder_2d_File_Suite', 'Disk_Folder_File_Suite')], - verbose=verbose) + output=os.path.join(DSTDIR, 'SystemEvents'), + basepkgname='StdSuites', + edit_modnames=[('Disk_2d_Folder_2d_File_Suite', 'Disk_Folder_File_Suite')], + verbose=verbose) gensuitemodule.processfile(CODEWARRIOR, - output=os.path.join(DSTDIR, 'CodeWarrior'), - basepkgname='StdSuites', - edit_modnames=[], verbose=verbose) + output=os.path.join(DSTDIR, 'CodeWarrior'), + basepkgname='StdSuites', + edit_modnames=[], verbose=verbose) gensuitemodule.processfile(EXPLORER, - output=os.path.join(DSTDIR, 'Explorer'), - basepkgname='StdSuites', - edit_modnames=[], verbose=verbose) + output=os.path.join(DSTDIR, 'Explorer'), + basepkgname='StdSuites', + edit_modnames=[], verbose=verbose) gensuitemodule.processfile(FINDER, - output=os.path.join(DSTDIR, 'Finder'), - basepkgname='StdSuites', - edit_modnames=[], verbose=verbose) + output=os.path.join(DSTDIR, 'Finder'), + basepkgname='StdSuites', + edit_modnames=[], verbose=verbose) gensuitemodule.processfile(NETSCAPE, - output=os.path.join(DSTDIR, 'Netscape'), - basepkgname='StdSuites', - edit_modnames=[('WorldWideWeb_suite_2c__as_d', 'WorldWideWeb_suite')], verbose=verbose) + output=os.path.join(DSTDIR, 'Netscape'), + basepkgname='StdSuites', + edit_modnames=[('WorldWideWeb_suite_2c__as_d', 'WorldWideWeb_suite')], verbose=verbose) gensuitemodule.processfile(TERMINAL, - output=os.path.join(DSTDIR, 'Terminal'), - basepkgname='StdSuites', - edit_modnames=[], verbose=verbose) -
\ No newline at end of file + output=os.path.join(DSTDIR, 'Terminal'), + basepkgname='StdSuites', + edit_modnames=[], verbose=verbose) diff --git a/Mac/scripts/mkestrres.py b/Mac/scripts/mkestrres.py index faa203b..715b8c6 100644 --- a/Mac/scripts/mkestrres.py +++ b/Mac/scripts/mkestrres.py @@ -10,149 +10,148 @@ WRITE = 2 smAllScripts = -3 ERRNO_PROG="#define[ \t]+" \ - "([A-Z0-9a-z_]+)" \ - "[ \t]+" \ - "([0-9]+)" \ - "[ \t]*/\*[ \t]*" \ - "(.*)" \ - "[ \t]*\*/" - + "([A-Z0-9a-z_]+)" \ + "[ \t]+" \ + "([0-9]+)" \ + "[ \t]*/\*[ \t]*" \ + "(.*)" \ + "[ \t]*\*/" + ERRORS_PROG="[ \t]*" \ - "([A-Z0-9a-z_]+)" \ - "[ \t]*=[ \t]*" \ - "([-0-9]+)" \ - "[, \t]*/\*[ \t]*" \ - "(.*)" \ - "[ \t]*\*/" - + "([A-Z0-9a-z_]+)" \ + "[ \t]*=[ \t]*" \ + "([-0-9]+)" \ + "[, \t]*/\*[ \t]*" \ + "(.*)" \ + "[ \t]*\*/" + ERRORS_PROG_2="[ \t]*" \ - "([A-Z0-9a-z_]+)" \ - "[ \t]*=[ \t]*" \ - "([-0-9]+)" \ - "[, \t]*" + "([A-Z0-9a-z_]+)" \ + "[ \t]*=[ \t]*" \ + "([-0-9]+)" \ + "[, \t]*" def Pstring(str): - if len(str) > 255: - raise ValueError, 'String too large' - return chr(len(str))+str - + if len(str) > 255: + raise ValueError, 'String too large' + return chr(len(str))+str + def writeestr(dst, edict): - """Create Estr resource file given a dictionary of errors.""" - - os.unlink(dst.as_pathname()) - Res.FSpCreateResFile(dst, 'RSED', 'rsrc', smAllScripts) - output = Res.FSpOpenResFile(dst, WRITE) - Res.UseResFile(output) - for num in edict.keys(): - res = Res.Resource(Pstring(edict[num][0])) - res.AddResource('Estr', num, '') - res.WriteResource() - Res.CloseResFile(output) - + """Create Estr resource file given a dictionary of errors.""" + + os.unlink(dst.as_pathname()) + Res.FSpCreateResFile(dst, 'RSED', 'rsrc', smAllScripts) + output = Res.FSpOpenResFile(dst, WRITE) + Res.UseResFile(output) + for num in edict.keys(): + res = Res.Resource(Pstring(edict[num][0])) + res.AddResource('Estr', num, '') + res.WriteResource() + Res.CloseResFile(output) + def writepython(fp, dict): - k = dict.keys() - k.sort() - for i in k: - fp.write("%s\t=\t%d\t#%s\n"%(dict[i][1], i, dict[i][0])) - + k = dict.keys() + k.sort() + for i in k: + fp.write("%s\t=\t%d\t#%s\n"%(dict[i][1], i, dict[i][0])) + def parse_errno_h(fp, dict): - errno_prog = re.compile(ERRNO_PROG) - for line in fp.readlines(): - m = errno_prog.match(line) - if m: - number = string.atoi(m.group(2)) - name = m.group(1) - desc = string.strip(m.group(3)) - - if not dict.has_key(number): - dict[number] = desc, name - else: - print 'DUPLICATE', number - print '\t', dict[number] - print '\t', (desc, name) - + errno_prog = re.compile(ERRNO_PROG) + for line in fp.readlines(): + m = errno_prog.match(line) + if m: + number = string.atoi(m.group(2)) + name = m.group(1) + desc = string.strip(m.group(3)) + + if not dict.has_key(number): + dict[number] = desc, name + else: + print 'DUPLICATE', number + print '\t', dict[number] + print '\t', (desc, name) + def parse_errors_h(fp, dict): - errno_prog = re.compile(ERRORS_PROG) - errno_prog_2 = re.compile(ERRORS_PROG_2) - for line in fp.readlines(): - match = 0 - m = errno_prog.match(line) - m2 = errno_prog_2.match(line) - if m: - number = string.atoi(m.group(2)) - name = m.group(1) - desc = string.strip(m.group(3)) - match=1 - elif m2: - number = string.atoi(m2.group(2)) - name = m2.group(1) - desc = name - match=1 - if match: - if number > 0: continue - - if not dict.has_key(number): - dict[number] = desc, name - else: - print 'DUPLICATE', number - print '\t', dict[number] - print '\t', (desc, name) - if len(desc) > len(dict[number][0]): - print 'Pick second one' - dict[number] = desc, name - + errno_prog = re.compile(ERRORS_PROG) + errno_prog_2 = re.compile(ERRORS_PROG_2) + for line in fp.readlines(): + match = 0 + m = errno_prog.match(line) + m2 = errno_prog_2.match(line) + if m: + number = string.atoi(m.group(2)) + name = m.group(1) + desc = string.strip(m.group(3)) + match=1 + elif m2: + number = string.atoi(m2.group(2)) + name = m2.group(1) + desc = name + match=1 + if match: + if number > 0: continue + + if not dict.has_key(number): + dict[number] = desc, name + else: + print 'DUPLICATE', number + print '\t', dict[number] + print '\t', (desc, name) + if len(desc) > len(dict[number][0]): + print 'Pick second one' + dict[number] = desc, name + def main(): - dict = {} - pathname = EasyDialogs.AskFileForOpen(message="Where is GUSI sys/errno.h?") - if pathname: - fp = open(pathname) - parse_errno_h(fp, dict) - fp.close() - - pathname = EasyDialogs.AskFileForOpen(message="Select cerrno (MSL) or cancel") - if pathname: - fp = open(pathname) - parse_errno_h(fp, dict) - fp.close() - - pathname = EasyDialogs.AskFileForOpen(message="Where is MacErrors.h?") - if pathname: - fp = open(pathname) - parse_errors_h(fp, dict) - fp.close() - - pathname = EasyDialogs.AskFileForOpen(message="Where is mkestrres-MacErrors.h?") - if pathname: - fp = open(pathname) - parse_errors_h(fp, dict) - fp.close() - - if not dict: - return - - pathname = EasyDialogs.AskFileForSave(message="Resource output file?", savedFileName="errors.rsrc") - if pathname: - writeestr(fss, dict) - - pathname = EasyDialogs.AskFileForSave(message="Python output file?", savedFileName="macerrors.py") - if pathname: - fp = open(pathname, "w") - writepython(fp, dict) - fp.close() - fss.SetCreatorType('Pyth', 'TEXT') - - pathname = EasyDialogs.AskFileForSave(message="Text output file?", savedFileName="errors.txt") - if pathname: - fp = open(pathname, "w") - - k = dict.keys() - k.sort() - for i in k: - fp.write("%d\t%s\t%s\n"%(i, dict[i][1], dict[i][0])) - fp.close() - - + dict = {} + pathname = EasyDialogs.AskFileForOpen(message="Where is GUSI sys/errno.h?") + if pathname: + fp = open(pathname) + parse_errno_h(fp, dict) + fp.close() + + pathname = EasyDialogs.AskFileForOpen(message="Select cerrno (MSL) or cancel") + if pathname: + fp = open(pathname) + parse_errno_h(fp, dict) + fp.close() + + pathname = EasyDialogs.AskFileForOpen(message="Where is MacErrors.h?") + if pathname: + fp = open(pathname) + parse_errors_h(fp, dict) + fp.close() + + pathname = EasyDialogs.AskFileForOpen(message="Where is mkestrres-MacErrors.h?") + if pathname: + fp = open(pathname) + parse_errors_h(fp, dict) + fp.close() + + if not dict: + return + + pathname = EasyDialogs.AskFileForSave(message="Resource output file?", savedFileName="errors.rsrc") + if pathname: + writeestr(fss, dict) + + pathname = EasyDialogs.AskFileForSave(message="Python output file?", savedFileName="macerrors.py") + if pathname: + fp = open(pathname, "w") + writepython(fp, dict) + fp.close() + fss.SetCreatorType('Pyth', 'TEXT') + + pathname = EasyDialogs.AskFileForSave(message="Text output file?", savedFileName="errors.txt") + if pathname: + fp = open(pathname, "w") + + k = dict.keys() + k.sort() + for i in k: + fp.write("%d\t%s\t%s\n"%(i, dict[i][1], dict[i][0])) + fp.close() + + if __name__ == '__main__': - main() - + main() diff --git a/Mac/scripts/zappycfiles.py b/Mac/scripts/zappycfiles.py index 0349220..a8193c1 100644 --- a/Mac/scripts/zappycfiles.py +++ b/Mac/scripts/zappycfiles.py @@ -8,30 +8,29 @@ import sys doit = 1 def main(): - if not sys.argv[1:]: - if os.name == 'mac': - import EasyDialogs - dir = EasyDialogs.AskFolder(message='Directory to zap pyc files in') - if not dir: - sys.exit(0) - zappyc(dir) - else: - print 'Usage: zappyc dir ...' - sys.exit(1) - for dir in sys.argv[1:]: - zappyc(dir) + if not sys.argv[1:]: + if os.name == 'mac': + import EasyDialogs + dir = EasyDialogs.AskFolder(message='Directory to zap pyc files in') + if not dir: + sys.exit(0) + zappyc(dir) + else: + print 'Usage: zappyc dir ...' + sys.exit(1) + for dir in sys.argv[1:]: + zappyc(dir) def zappyc(dir): - os.path.walk(dir, walker, None) - + os.path.walk(dir, walker, None) + def walker(dummy, top, names): - for name in names: - if name[-4:] in ('.pyc', '.pyo'): - path = os.path.join(top, name) - print 'Zapping', path - if doit: - os.unlink(path) - + for name in names: + if name[-4:] in ('.pyc', '.pyo'): + path = os.path.join(top, name) + print 'Zapping', path + if doit: + os.unlink(path) + if __name__ == '__main__': - main() - + main() |