summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rwxr-xr-xDemo/tix/samples/Balloon.py2
-rwxr-xr-xDemo/tix/samples/BtnBox.py8
-rwxr-xr-xDemo/tix/samples/CmpImg.py37
-rwxr-xr-xDemo/tix/samples/ComboBox.py20
-rwxr-xr-xDemo/tix/samples/Control.py16
-rwxr-xr-xDemo/tix/samples/DirList.py17
-rwxr-xr-xDemo/tix/samples/DirTree.py11
-rwxr-xr-xDemo/tix/samples/NoteBook.py50
-rwxr-xr-xDemo/tix/samples/OptMenu.py24
-rwxr-xr-xDemo/tix/samples/PanedWin.py2
-rwxr-xr-xDemo/tix/samples/PopMenu.py10
-rwxr-xr-xDemo/tix/samples/SHList1.py21
-rwxr-xr-xDemo/tix/samples/SHList2.py41
-rwxr-xr-xDemo/tix/samples/Tree.py44
-rw-r--r--Demo/tix/tixwidgets.py391
-rwxr-xr-xDemo/tkinter/guido/AttrDialog.py796
-rwxr-xr-xDemo/tkinter/guido/ManPage.py370
-rwxr-xr-xDemo/tkinter/guido/MimeViewer.py242
-rwxr-xr-xDemo/tkinter/guido/ShellWindow.py266
-rw-r--r--Demo/tkinter/guido/canvasevents.py230
-rwxr-xr-xDemo/tkinter/guido/dialog.py68
-rwxr-xr-xDemo/tkinter/guido/electrons.py120
-rwxr-xr-xDemo/tkinter/guido/hanoi.py238
-rwxr-xr-xDemo/tkinter/guido/hello.py14
-rwxr-xr-xDemo/tkinter/guido/kill.py169
-rwxr-xr-xDemo/tkinter/guido/listtree.py46
-rwxr-xr-xDemo/tkinter/guido/mbox.py410
-rw-r--r--Demo/tkinter/guido/newmenubardemo.py36
-rw-r--r--Demo/tkinter/guido/paint.py52
-rwxr-xr-xDemo/tkinter/guido/rmt.py114
-rwxr-xr-xDemo/tkinter/guido/solitaire.py578
-rw-r--r--Demo/tkinter/guido/sortvisu.py834
-rw-r--r--Demo/tkinter/guido/ss1.py2
-rwxr-xr-xDemo/tkinter/guido/svkill.py216
-rwxr-xr-xDemo/tkinter/guido/tkman.py408
-rwxr-xr-xDemo/tkinter/guido/wish.py32
-rw-r--r--Demo/tkinter/matt/00-HELLO-WORLD.py28
-rw-r--r--Demo/tkinter/matt/animation-simple.py30
-rw-r--r--Demo/tkinter/matt/animation-w-velocity-ctrl.py46
-rw-r--r--Demo/tkinter/matt/bind-w-mult-calls-p-type.py40
-rw-r--r--Demo/tkinter/matt/canvas-demo-simple.py22
-rw-r--r--Demo/tkinter/matt/canvas-gridding.py80
-rw-r--r--Demo/tkinter/matt/canvas-moving-or-creating.py73
-rw-r--r--Demo/tkinter/matt/canvas-moving-w-mouse.py54
-rw-r--r--Demo/tkinter/matt/canvas-mult-item-sel.py119
-rw-r--r--Demo/tkinter/matt/canvas-reading-tag-info.py72
-rw-r--r--Demo/tkinter/matt/canvas-w-widget-draw-el.py36
-rw-r--r--Demo/tkinter/matt/canvas-with-scrollbars.py70
-rw-r--r--Demo/tkinter/matt/dialog-box.py86
-rw-r--r--Demo/tkinter/matt/entry-simple.py21
-rw-r--r--Demo/tkinter/matt/entry-with-shared-variable.py63
-rw-r--r--Demo/tkinter/matt/killing-window-w-wm.py38
-rw-r--r--Demo/tkinter/matt/menu-all-types-of-entries.py104
-rw-r--r--Demo/tkinter/matt/menu-simple.py44
-rw-r--r--Demo/tkinter/matt/not-what-you-might-think-1.py22
-rw-r--r--Demo/tkinter/matt/not-what-you-might-think-2.py24
-rw-r--r--Demo/tkinter/matt/packer-and-placer-together.py11
-rw-r--r--Demo/tkinter/matt/packer-simple.py32
-rw-r--r--Demo/tkinter/matt/placer-simple.py5
-rw-r--r--Demo/tkinter/matt/pong-demo-1.py62
-rw-r--r--Demo/tkinter/matt/printing-coords-of-items.py73
-rw-r--r--Demo/tkinter/matt/radiobutton-simple.py86
-rw-r--r--Demo/tkinter/matt/rubber-band-box-demo-1.py78
-rw-r--r--Demo/tkinter/matt/rubber-line-demo-1.py68
-rw-r--r--Demo/tkinter/matt/slider-demo-1.py36
-rw-r--r--Demo/tkinter/matt/subclass-existing-widgets.py7
-rw-r--r--Demo/tkinter/matt/two-radio-groups.py72
-rw-r--r--Demo/tkinter/matt/window-creation-more.py36
-rw-r--r--Demo/tkinter/matt/window-creation-simple.py30
-rw-r--r--Demo/tkinter/matt/window-creation-w-location.py30
-rw-r--r--Demo/xml/elem_count.py2
-rw-r--r--Demo/xml/roundtrip.py4
-rw-r--r--Demo/xml/rss2html.py2
-rwxr-xr-xDemo/zlib/minigzip.py15
-rwxr-xr-xDemo/zlib/zlibdemo.py5
-rw-r--r--Lib/_threading_local.py6
-rw-r--r--Lib/asyncore.py4
-rw-r--r--Lib/bsddb/test/test_basics.py6
-rw-r--r--Lib/cgitb.py4
-rw-r--r--Lib/curses/__init__.py9
-rw-r--r--Lib/curses/has_key.py298
-rw-r--r--Lib/curses/panel.py1
-rw-r--r--Lib/distutils/archive_util.py4
-rw-r--r--Lib/distutils/bcppcompiler.py2
-rw-r--r--Lib/distutils/ccompiler.py4
-rw-r--r--Lib/distutils/cmd.py4
-rw-r--r--Lib/distutils/command/bdist.py2
-rw-r--r--Lib/distutils/command/bdist_dumb.py2
-rw-r--r--Lib/distutils/command/bdist_wininst.py2
-rw-r--r--Lib/distutils/command/build_ext.py4
-rw-r--r--Lib/distutils/command/build_scripts.py2
-rw-r--r--Lib/distutils/command/install.py2
-rw-r--r--Lib/distutils/command/register.py1
-rw-r--r--Lib/distutils/core.py1
-rw-r--r--Lib/distutils/cygwinccompiler.py2
-rw-r--r--Lib/distutils/debug.py1
-rw-r--r--Lib/distutils/dir_util.py1
-rw-r--r--Lib/distutils/dist.py4
-rw-r--r--Lib/distutils/file_util.py2
-rw-r--r--Lib/distutils/filelist.py2
-rw-r--r--Lib/distutils/log.py8
-rw-r--r--Lib/distutils/msvccompiler.py7
-rw-r--r--Lib/distutils/spawn.py2
-rw-r--r--Lib/distutils/sysconfig.py2
-rw-r--r--Lib/distutils/unixccompiler.py6
-rw-r--r--Lib/distutils/util.py2
-rw-r--r--Lib/dummy_threading.py2
-rw-r--r--Lib/lib-old/Para.py656
-rw-r--r--Lib/lib-old/addpack.py56
-rw-r--r--Lib/lib-old/codehack.py70
-rw-r--r--Lib/lib-old/dump.py60
-rw-r--r--Lib/lib-old/find.py36
-rw-r--r--Lib/lib-old/fmt.py1038
-rw-r--r--Lib/lib-old/grep.py118
-rw-r--r--Lib/lib-old/lockfile.py12
-rw-r--r--Lib/lib-old/newdir.py110
-rw-r--r--Lib/lib-old/packmail.py168
-rw-r--r--Lib/lib-old/poly.py60
-rw-r--r--Lib/lib-old/rand.py6
-rw-r--r--Lib/lib-old/tb.py286
-rw-r--r--Lib/lib-old/util.py6
-rw-r--r--Lib/lib-old/zmod.py86
-rwxr-xr-xLib/lib-tk/Tix.py16
-rw-r--r--Lib/lib-tk/Tkinter.py2
-rw-r--r--Lib/lib-tk/tkFileDialog.py11
-rw-r--r--Lib/plat-atheos/IN.py5
-rw-r--r--Lib/plat-atheos/TYPES.py5
-rw-r--r--Lib/plat-beos5/IN.py2
-rwxr-xr-xLib/plat-irix5/AL.py102
-rwxr-xr-xLib/plat-irix5/CD.py58
-rwxr-xr-xLib/plat-irix5/CL.py38
-rwxr-xr-xLib/plat-irix5/CL_old.py182
-rwxr-xr-xLib/plat-irix5/FL.py58
-rwxr-xr-xLib/plat-irix5/SV.py22
-rwxr-xr-xLib/plat-irix5/cddb.py350
-rwxr-xr-xLib/plat-irix5/cdplayer.py136
-rwxr-xr-xLib/plat-irix5/flp.py30
-rwxr-xr-xLib/plat-irix5/jpeg.py176
-rwxr-xr-xLib/plat-irix5/panel.py344
-rwxr-xr-xLib/plat-irix5/panelparser.py122
-rwxr-xr-xLib/plat-irix5/readcd.py464
-rwxr-xr-xLib/plat-irix5/torgb.py84
-rw-r--r--Lib/plat-irix6/AL.py102
-rw-r--r--Lib/plat-irix6/CD.py58
-rw-r--r--Lib/plat-irix6/CL.py38
-rw-r--r--Lib/plat-irix6/FILE.py6
-rw-r--r--Lib/plat-irix6/FL.py58
-rw-r--r--Lib/plat-irix6/SV.py22
-rw-r--r--Lib/plat-irix6/cddb.py350
-rw-r--r--Lib/plat-irix6/cdplayer.py136
-rw-r--r--Lib/plat-irix6/flp.py30
-rw-r--r--Lib/plat-irix6/jpeg.py176
-rw-r--r--Lib/plat-irix6/panel.py344
-rw-r--r--Lib/plat-irix6/panelparser.py122
-rw-r--r--Lib/plat-irix6/readcd.py464
-rw-r--r--Lib/plat-irix6/torgb.py84
-rw-r--r--Lib/plat-linux2/DLFCN.py4
-rw-r--r--Lib/plat-linux2/IN.py5
-rw-r--r--Lib/plat-linux2/TYPES.py5
-rw-r--r--Lib/plat-mac/Audio_mac.py2
-rw-r--r--Lib/plat-mac/Carbon/Aliases.py8
-rw-r--r--Lib/plat-mac/Carbon/Appearance.py32
-rw-r--r--Lib/plat-mac/Carbon/AppleEvents.py86
-rwxr-xr-xLib/plat-mac/Carbon/CarbonEvents.py38
-rw-r--r--Lib/plat-mac/Carbon/Components.py4
-rw-r--r--Lib/plat-mac/Carbon/ControlAccessor.py13
-rw-r--r--Lib/plat-mac/Carbon/Controls.py142
-rw-r--r--Lib/plat-mac/Carbon/CoreFoundation.py4
-rwxr-xr-xLib/plat-mac/Carbon/CoreGraphics.py2
-rw-r--r--Lib/plat-mac/Carbon/Dialogs.py6
-rw-r--r--Lib/plat-mac/Carbon/Dragconst.py50
-rw-r--r--Lib/plat-mac/Carbon/Events.py10
-rw-r--r--Lib/plat-mac/Carbon/Files.py44
-rw-r--r--Lib/plat-mac/Carbon/Folders.py20
-rw-r--r--Lib/plat-mac/Carbon/Icons.py2
-rw-r--r--Lib/plat-mac/Carbon/LaunchServices.py16
-rw-r--r--Lib/plat-mac/Carbon/Lists.py2
-rw-r--r--Lib/plat-mac/Carbon/MacHelp.py4
-rw-r--r--Lib/plat-mac/Carbon/MacTextEditor.py6
-rw-r--r--Lib/plat-mac/Carbon/MediaDescr.py82
-rw-r--r--Lib/plat-mac/Carbon/Menus.py18
-rw-r--r--Lib/plat-mac/Carbon/OSAconst.py6
-rw-r--r--Lib/plat-mac/Carbon/Qt.py1
-rw-r--r--Lib/plat-mac/Carbon/QuickDraw.py54
-rw-r--r--Lib/plat-mac/Carbon/QuickTime.py218
-rw-r--r--Lib/plat-mac/Carbon/Resources.py8
-rw-r--r--Lib/plat-mac/Carbon/Sound.py56
-rw-r--r--Lib/plat-mac/Carbon/TextEdit.py22
-rw-r--r--Lib/plat-mac/Carbon/Windows.py24
-rw-r--r--Lib/plat-mac/Carbon/__init__.py2
-rw-r--r--Lib/plat-mac/EasyDialogs.py27
-rw-r--r--Lib/plat-mac/FrameWork.py2
-rw-r--r--Lib/plat-mac/MiniAEFrame.py6
-rw-r--r--Lib/plat-mac/PixMapWrapper.py19
-rw-r--r--Lib/plat-mac/aepack.py18
-rw-r--r--Lib/plat-mac/aetools.py42
-rw-r--r--Lib/plat-mac/aetypes.py191
-rw-r--r--Lib/plat-mac/applesingle.py12
-rw-r--r--Lib/plat-mac/appletrawmain.py2
-rw-r--r--Lib/plat-mac/bgenlocations.py11
-rw-r--r--Lib/plat-mac/buildtools.py77
-rw-r--r--Lib/plat-mac/cfmfile.py59
-rw-r--r--Lib/plat-mac/findertools.py99
-rw-r--r--Lib/plat-mac/gensuitemodule.py168
-rw-r--r--Lib/plat-mac/ic.py69
-rw-r--r--Lib/plat-mac/icopen.py24
-rw-r--r--Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py58
-rw-r--r--Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py118
-rw-r--r--Lib/plat-mac/lib-scriptpackages/CodeWarrior/Required.py4
-rw-r--r--Lib/plat-mac/lib-scriptpackages/CodeWarrior/__init__.py1
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py2
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Explorer/Standard_Suite.py2
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py2
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Finder/Enumerations.py146
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py34
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py10
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Netscape/Required_suite.py2
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Netscape/Standard_URL_suite.py4
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Netscape/Text.py2
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py4
-rw-r--r--Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py92
-rw-r--r--Lib/plat-mac/lib-scriptpackages/StdSuites/Macintosh_Connectivity_Clas.py124
-rw-r--r--Lib/plat-mac/lib-scriptpackages/StdSuites/QuickDraw_Graphics_Suite.py38
-rw-r--r--Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py42
-rw-r--r--Lib/plat-mac/lib-scriptpackages/StdSuites/Table_Suite.py6
-rw-r--r--Lib/plat-mac/lib-scriptpackages/StdSuites/Text_Suite.py38
-rw-r--r--Lib/plat-mac/lib-scriptpackages/StdSuites/__init__.py1
-rw-r--r--Lib/plat-mac/lib-scriptpackages/SystemEvents/Disk_Folder_File_Suite.py30
-rw-r--r--Lib/plat-mac/lib-scriptpackages/SystemEvents/Folder_Actions_Suite.py10
-rw-r--r--Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py6
-rw-r--r--Lib/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py6
-rw-r--r--Lib/plat-mac/lib-scriptpackages/_builtinSuites/__init__.py13
-rw-r--r--Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py222
-rw-r--r--Lib/plat-mac/macfs.py52
-rw-r--r--Lib/plat-mac/macostools.py22
-rw-r--r--Lib/plat-mac/macresource.py22
-rw-r--r--Lib/plat-mac/pimp.py260
-rw-r--r--Lib/plat-mac/videoreader.py55
-rw-r--r--Lib/plat-netbsd1/IN.py1
-rw-r--r--Lib/plat-os2emx/_emx_link.py2
-rw-r--r--Lib/plat-os2emx/grp.py14
-rw-r--r--Lib/plat-os2emx/pwd.py20
-rw-r--r--Lib/plat-riscos/rourl2path.py2
-rwxr-xr-xLib/plat-sunos5/IN.py10
-rw-r--r--Lib/plat-sunos5/STROPTS.py28
-rwxr-xr-xLib/plat-sunos5/SUNAUDIODEV.py28
-rw-r--r--Lib/plat-sunos5/TYPES.py1
-rw-r--r--Lib/plat-unixware7/IN.py26
-rw-r--r--Lib/posixpath.py2
-rw-r--r--Lib/test/test_codecencodings_cn.py4
-rw-r--r--Lib/test/test_site.py4
-rw-r--r--Lib/test/test_transformer.py44
-rw-r--r--Lib/urllib.py2
-rw-r--r--Lib/xml/sax/_exceptions.py4
-rw-r--r--Mac/Demo/PICTbrowse/ICONbrowse.py256
-rw-r--r--Mac/Demo/PICTbrowse/PICTbrowse.py222
-rw-r--r--Mac/Demo/PICTbrowse/PICTbrowse2.py258
-rw-r--r--Mac/Demo/PICTbrowse/cicnbrowse.py256
-rw-r--r--Mac/Demo/PICTbrowse/oldPICTbrowse.py260
-rw-r--r--Mac/Demo/applescript/Disk_Copy/Special_Events.py732
-rw-r--r--Mac/Demo/applescript/Disk_Copy/Standard_Suite.py664
-rw-r--r--Mac/Demo/applescript/Disk_Copy/Utility_Events.py362
-rw-r--r--Mac/Demo/applescript/Disk_Copy/__init__.py23
-rw-r--r--Mac/Demo/applescript/makedisk.py6
-rw-r--r--Mac/Demo/calldll/testcalldll.py102
-rw-r--r--Mac/Demo/example0/checktext.py56
-rw-r--r--Mac/Demo/example1/dnslookup-1.py3
-rw-r--r--Mac/Demo/example2/dnslookup-2.py16
-rw-r--r--Mac/Demo/imgbrowse/imgbrowse.py170
-rw-r--r--Mac/Demo/imgbrowse/mac_image.py86
-rw-r--r--Mac/Demo/mlte/mlted.py703
-rw-r--r--Mac/Demo/quicktime/MovieInWindow.py95
-rw-r--r--Mac/Demo/quicktime/VerySimplePlayer.py141
-rw-r--r--Mac/Demo/resources/copyres.py92
-rw-r--r--Mac/Demo/resources/listres.py82
-rw-r--r--Mac/Demo/sound/morse.py288
-rw-r--r--Mac/Demo/sound/morselib.py316
-rw-r--r--Mac/Demo/textedit/ped.py675
-rw-r--r--Mac/Demo/waste/htmled.py1567
-rw-r--r--Mac/Demo/waste/swed.py1205
-rw-r--r--Mac/Demo/waste/wed.py801
-rw-r--r--Mac/IDE scripts/Widget demos/ActivateWindowDemo.py26
-rw-r--r--Mac/IDE scripts/Widget demos/KeyTester.py6
-rw-r--r--Mac/IDE scripts/Widget demos/ListWindow.py8
-rw-r--r--Mac/IDE scripts/Widget demos/TwoLists.py8
-rw-r--r--Mac/IDE scripts/Widget demos/WidgetTest.py48
-rw-r--r--Mac/Modules/ae/aescan.py158
-rw-r--r--Mac/Modules/ae/aesupport.py206
-rw-r--r--Mac/Modules/ah/ahscan.py70
-rw-r--r--Mac/Modules/ah/ahsupport.py9
-rw-r--r--Mac/Modules/app/appscan.py120
-rw-r--r--Mac/Modules/app/appsupport.py43
-rw-r--r--Mac/Modules/carbonevt/CarbonEvtscan.py186
-rw-r--r--Mac/Modules/carbonevt/CarbonEvtsupport.py176
-rw-r--r--Mac/Modules/cf/cfscan.py238
-rw-r--r--Mac/Modules/cf/cfsupport.py577
-rwxr-xr-xMac/Modules/cg/cgscan.py124
-rwxr-xr-xMac/Modules/cg/cgsupport.py99
-rw-r--r--Mac/Modules/cm/cmscan.py138
-rw-r--r--Mac/Modules/cm/cmsupport.py75
-rw-r--r--Mac/Modules/ctl/ctledit.py30
-rw-r--r--Mac/Modules/ctl/ctlscan.py316
-rw-r--r--Mac/Modules/ctl/ctlsupport.py584
-rw-r--r--Mac/Modules/dlg/dlgscan.py192
-rw-r--r--Mac/Modules/dlg/dlgsupport.py288
-rw-r--r--Mac/Modules/drag/dragscan.py114
-rw-r--r--Mac/Modules/drag/dragsupport.py246
-rw-r--r--Mac/Modules/evt/evtedit.py1
-rw-r--r--Mac/Modules/evt/evtscan.py122
-rw-r--r--Mac/Modules/evt/evtsupport.py19
-rw-r--r--Mac/Modules/file/filescan.py366
-rw-r--r--Mac/Modules/file/filesupport.py1151
-rw-r--r--Mac/Modules/fm/fmscan.py104
-rw-r--r--Mac/Modules/fm/fmsupport.py37
-rw-r--r--Mac/Modules/folder/folderscan.py96
-rw-r--r--Mac/Modules/folder/foldersupport.py9
-rw-r--r--Mac/Modules/help/helpscan.py92
-rw-r--r--Mac/Modules/help/helpsupport.py37
-rw-r--r--Mac/Modules/ibcarbon/IBCarbonscan.py62
-rw-r--r--Mac/Modules/ibcarbon/IBCarbonsupport.py8
-rw-r--r--Mac/Modules/icn/icnscan.py102
-rw-r--r--Mac/Modules/icn/icnsupport.py39
-rw-r--r--Mac/Modules/launch/launchscan.py128
-rw-r--r--Mac/Modules/launch/launchsupport.py49
-rw-r--r--Mac/Modules/launch/setup.py14
-rw-r--r--Mac/Modules/list/listscan.py142
-rw-r--r--Mac/Modules/list/listsupport.py183
-rw-r--r--Mac/Modules/menu/menuedit.py1
-rw-r--r--Mac/Modules/menu/menuscan.py158
-rw-r--r--Mac/Modules/menu/menusupport.py42
-rw-r--r--Mac/Modules/mlte/mltescan.py218
-rw-r--r--Mac/Modules/mlte/mltesupport.py67
-rw-r--r--Mac/Modules/osa/osascan.py92
-rw-r--r--Mac/Modules/osa/osasupport.py43
-rw-r--r--Mac/Modules/osa/setup.py14
-rw-r--r--Mac/Modules/qd/qdedit.py3
-rw-r--r--Mac/Modules/qd/qdscan.py434
-rw-r--r--Mac/Modules/qd/qdsupport.py284
-rw-r--r--Mac/Modules/qdoffs/qdoffsscan.py97
-rw-r--r--Mac/Modules/qdoffs/qdoffssupport.py56
-rw-r--r--Mac/Modules/qt/qtscan.py604
-rw-r--r--Mac/Modules/qt/qtsupport.py177
-rwxr-xr-xMac/Modules/qt/setup.py14
-rw-r--r--Mac/Modules/res/resedit.py28
-rw-r--r--Mac/Modules/res/resscan.py130
-rw-r--r--Mac/Modules/res/ressupport.py296
-rw-r--r--Mac/Modules/scrap/scrapscan.py84
-rw-r--r--Mac/Modules/scrap/scrapsupport.py25
-rw-r--r--Mac/Modules/snd/sndscan.py222
-rw-r--r--Mac/Modules/snd/sndsupport.py356
-rw-r--r--Mac/Modules/te/tescan.py94
-rw-r--r--Mac/Modules/te/tesupport.py245
-rw-r--r--Mac/Modules/waste/wastescan.py260
-rw-r--r--Mac/Modules/waste/wastesupport.py441
-rw-r--r--Mac/Modules/win/winedit.py24
-rw-r--r--Mac/Modules/win/winscan.py233
-rw-r--r--Mac/Modules/win/winsupport.py180
-rw-r--r--Mac/OSX/Doc/HelpIndexingTool/Standard_Suite.py6
-rw-r--r--Mac/OSX/Doc/HelpIndexingTool/__init__.py1
-rw-r--r--Mac/OSX/Doc/setup.py340
-rw-r--r--Mac/OSX/Extras.install.py78
-rw-r--r--Mac/OSX/fixversions.py101
-rw-r--r--Mac/Tools/IDE/BuildIDE.py15
-rw-r--r--Mac/Tools/IDE/FontSettings.py402
-rw-r--r--Mac/Tools/IDE/MacPrefs.py188
-rw-r--r--Mac/Tools/IDE/ModuleBrowser.py324
-rwxr-xr-xMac/Tools/IDE/PackageManager.py892
-rw-r--r--Mac/Tools/IDE/ProfileBrowser.py138
-rw-r--r--Mac/Tools/IDE/PyBrowser.py1113
-rw-r--r--Mac/Tools/IDE/PyConsole.py804
-rw-r--r--Mac/Tools/IDE/PyDebugger.py1692
-rw-r--r--Mac/Tools/IDE/PyDocSearch.py444
-rw-r--r--Mac/Tools/IDE/PyEdit.py2558
-rw-r--r--Mac/Tools/IDE/PyFontify.py190
-rw-r--r--Mac/Tools/IDE/PyInteractive.py204
-rw-r--r--Mac/Tools/IDE/PythonIDE.py86
-rw-r--r--Mac/Tools/IDE/PythonIDEMain.py932
-rw-r--r--Mac/Tools/IDE/Splash.py138
-rw-r--r--Mac/Tools/IDE/W.py35
-rw-r--r--Mac/Tools/IDE/Wapplication.py911
-rw-r--r--Mac/Tools/IDE/Wbase.py1466
-rw-r--r--Mac/Tools/IDE/Wcontrols.py817
-rw-r--r--Mac/Tools/IDE/Wkeys.py68
-rw-r--r--Mac/Tools/IDE/Wlists.py1115
-rw-r--r--Mac/Tools/IDE/Wmenus.py464
-rw-r--r--Mac/Tools/IDE/Wminiapp.py26
-rw-r--r--Mac/Tools/IDE/Wquicktime.py199
-rw-r--r--Mac/Tools/IDE/Wsocket.py658
-rw-r--r--Mac/Tools/IDE/Wtext.py2184
-rw-r--r--Mac/Tools/IDE/Wtraceback.py355
-rw-r--r--Mac/Tools/IDE/Wwindows.py1202
-rw-r--r--Mac/Tools/macfreeze/directives.py47
-rw-r--r--Mac/Tools/macfreeze/macfreeze.py86
-rw-r--r--Mac/Tools/macfreeze/macfreezegui.py214
-rw-r--r--Mac/Tools/macfreeze/macgen_bin.py372
-rw-r--r--Mac/Tools/macfreeze/macgen_info.py10
-rw-r--r--Mac/Tools/macfreeze/macgen_rsrc.py57
-rw-r--r--Mac/Tools/macfreeze/macgen_src.py184
-rw-r--r--Mac/Tools/macfreeze/macgenerate.py10
-rw-r--r--Mac/Tools/macfreeze/macmodulefinder.py162
-rw-r--r--Mac/scripts/BuildApplet.py210
-rw-r--r--Mac/scripts/bgenall.py94
-rw-r--r--Mac/scripts/buildpkg.py78
-rw-r--r--Mac/scripts/cachersrc.py59
-rw-r--r--Mac/scripts/genallsuites.py45
-rw-r--r--Mac/scripts/mkestrres.py269
-rw-r--r--Mac/scripts/zappycfiles.py45
-rw-r--r--Misc/BeOS-setup.py48
-rw-r--r--Misc/find_recursionlimit.py3
-rw-r--r--Modules/cgen.py782
-rw-r--r--Tools/bgen/bgen/bgenBuffer.py66
-rw-r--r--Tools/bgen/bgen/bgenGenerator.py14
-rw-r--r--Tools/bgen/bgen/bgenHeapBuffer.py14
-rw-r--r--Tools/bgen/bgen/bgenModule.py2
-rw-r--r--Tools/bgen/bgen/bgenObjectDefinition.py98
-rw-r--r--Tools/bgen/bgen/bgenOutput.py18
-rw-r--r--Tools/bgen/bgen/bgenStringBuffer.py6
-rw-r--r--Tools/bgen/bgen/bgenType.py6
-rw-r--r--Tools/bgen/bgen/macsupport.py6
-rw-r--r--Tools/bgen/bgen/scantools.py25
-rw-r--r--Tools/compiler/astgen.py4
-rw-r--r--Tools/compiler/compile.py2
-rwxr-xr-xTools/compiler/demo.py6
-rw-r--r--Tools/faqwiz/faqconf.py4
-rw-r--r--Tools/faqwiz/faqwiz.py6
-rw-r--r--Tools/framer/example.py9
-rw-r--r--Tools/framer/framer/__init__.py2
-rw-r--r--Tools/framer/framer/bases.py11
-rw-r--r--Tools/framer/framer/function.py10
-rw-r--r--Tools/framer/framer/struct.py2
-rw-r--r--Tools/framer/framer/structparse.py2
-rw-r--r--Tools/framer/framer/template.py6
-rw-r--r--Tools/freeze/bkfile.py82
-rw-r--r--Tools/freeze/checkextensions.py146
-rw-r--r--Tools/freeze/checkextensions_win32.py250
-rwxr-xr-xTools/freeze/freeze.py12
-rw-r--r--Tools/freeze/makeconfig.py92
-rw-r--r--Tools/freeze/makefreeze.py2
-rw-r--r--Tools/freeze/makemakefile.py2
-rw-r--r--Tools/freeze/parsesetup.py162
-rwxr-xr-xTools/i18n/msgfmt.py4
-rwxr-xr-xTools/modulator/Tkextra.py4
-rwxr-xr-xTools/modulator/genmodule.py4
-rwxr-xr-xTools/modulator/modulator.py26
-rw-r--r--Tools/modulator/varsubst.py2
-rw-r--r--Tools/pynche/ChipViewer.py2
-rw-r--r--Tools/pynche/DetailsViewer.py4
-rw-r--r--Tools/pynche/StripViewer.py6
-rw-r--r--Tools/unicode/mkstringprep.py1
-rw-r--r--Tools/versioncheck/checkversions.py6
-rw-r--r--Tools/versioncheck/pyversioncheck.py1
-rwxr-xr-xTools/webchecker/wcgui.py10
-rwxr-xr-xTools/webchecker/webchecker.py8
453 files changed, 31802 insertions, 31936 deletions
diff --git a/Demo/tix/samples/Balloon.py b/Demo/tix/samples/Balloon.py
index 825ae6aa7f..229590570b 100755
--- a/Demo/tix/samples/Balloon.py
+++ b/Demo/tix/samples/Balloon.py
@@ -17,7 +17,7 @@
import Tix
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
balloon = DemoBalloon(root)
diff --git a/Demo/tix/samples/BtnBox.py b/Demo/tix/samples/BtnBox.py
index 57d02dfefc..af2a2a8753 100755
--- a/Demo/tix/samples/BtnBox.py
+++ b/Demo/tix/samples/BtnBox.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -21,7 +21,7 @@ def RunSample(w):
# Create the label on the top of the dialog box
#
top = Tix.Label(w, padx=20, pady=10, bd=1, relief=Tix.RAISED,
- anchor=Tix.CENTER, text='This dialog box is\n a demonstration of the\n tixButtonBox widget')
+ anchor=Tix.CENTER, text='This dialog box is\n a demonstration of the\n tixButtonBox widget')
# Create the button box and add a few buttons in it. Set the
# -width of all the buttons to the same value so that they
@@ -32,9 +32,9 @@ def RunSample(w):
#
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='OK', underline=0, width=5,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.add('close', text='Cancel', underline=0, width=5,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
diff --git a/Demo/tix/samples/CmpImg.py b/Demo/tix/samples/CmpImg.py
index 4e08df799b..4720a10ccf 100755
--- a/Demo/tix/samples/CmpImg.py
+++ b/Demo/tix/samples/CmpImg.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -22,13 +22,13 @@ static char * netw_xpm[] = {
/* width height ncolors chars_per_pixel */
"32 32 7 1",
/* colors */
-" s None c None",
-". c #000000000000",
-"X c white",
-"o c #c000c000c000",
-"O c #404040",
-"+ c blue",
-"@ c red",
+" s None c None",
+". c #000000000000",
+"X c white",
+"o c #c000c000c000",
+"O c #404040",
+"+ c blue",
+"@ c red",
/* pixels */
" ",
" .............. ",
@@ -69,11 +69,11 @@ static char * drivea_xpm[] = {
/* width height ncolors chars_per_pixel */
"32 32 5 1",
/* colors */
-" s None c None",
-". c #000000000000",
-"X c white",
-"o c #c000c000c000",
-"O c #800080008000",
+" s None c None",
+". c #000000000000",
+"X c white",
+"o c #c000c000c000",
+"O c #800080008000",
/* pixels */
" ",
" ",
@@ -146,10 +146,10 @@ static unsigned char drivea_bits[] = {
def RunSample(w):
w.img0 = Tix.Image('pixmap', data=network_pixmap)
if not w.img0:
- w.img0 = Tix.Image('bitmap', data=network_bitmap)
+ w.img0 = Tix.Image('bitmap', data=network_bitmap)
w.img1 = Tix.Image('pixmap', data=hard_disk_pixmap)
if not w.img0:
- w.img1 = Tix.Image('bitmap', data=hard_disk_bitmap)
+ w.img1 = Tix.Image('bitmap', data=hard_disk_bitmap)
hdd = Tix.Button(w, padx=4, pady=1, width=120)
net = Tix.Button(w, padx=4, pady=1, width=120)
@@ -163,7 +163,7 @@ def RunSample(w):
w.hdd_img = Tix.Image('compound', window=hdd)
w.hdd_img.tk.call(str(w.hdd_img), 'add', 'line')
w.hdd_img.tk.call(str(w.hdd_img), 'add', 'text', '-text', 'Hard Disk',
- '-underline', '0')
+ '-underline', '0')
w.hdd_img.tk.call(str(w.hdd_img), 'add', 'space', '-width', '7')
w.hdd_img.tk.call(str(w.hdd_img), 'add', 'image', '-image', w.img1)
@@ -175,7 +175,7 @@ def RunSample(w):
w.net_img = Tix.Image('compound', window=net)
w.net_img.tk.call(str(w.net_img), 'add', 'line')
w.net_img.tk.call(str(w.net_img), 'add', 'text', '-text', 'Network',
- '-underline', '0')
+ '-underline', '0')
w.net_img.tk.call(str(w.net_img), 'add', 'space', '-width', '7')
w.net_img.tk.call(str(w.net_img), 'add', 'image', '-image', w.img0)
@@ -184,7 +184,7 @@ def RunSample(w):
net['image'] = w.net_img
close = Tix.Button(w, pady=1, text='Close',
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
hdd.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1)
net.pack(side=Tix.LEFT, padx=10, pady=10, fill=Tix.Y, expand=1)
@@ -194,4 +194,3 @@ if __name__ == '__main__':
root = Tix.Tk()
RunSample(root)
root.mainloop()
-
diff --git a/Demo/tix/samples/ComboBox.py b/Demo/tix/samples/ComboBox.py
index afecea4c7d..9140987153 100755
--- a/Demo/tix/samples/ComboBox.py
+++ b/Demo/tix/samples/ComboBox.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -27,25 +27,25 @@ def RunSample(w):
# to invent new months?
#
# [Hint] The -options switch sets the options of the subwidgets.
- # [Hint] We set the label.width subwidget option of both comboboxes to
+ # [Hint] We set the label.width subwidget option of both comboboxes to
# be 10 so that their labels appear to be aligned.
#
a = Tix.ComboBox(top, label="Month: ", dropdown=1,
- command=select_month, editable=0, variable=demo_month,
- options='listbox.height 6 label.width 10 label.anchor e')
+ command=select_month, editable=0, variable=demo_month,
+ options='listbox.height 6 label.width 10 label.anchor e')
# $w.top.b is a non-drop-down combo box. It is not editable: we provide
# four choices for the user, but he can enter an alternative year if he
# wants to.
#
# [Hint] Use the padY and anchor options of the label subwidget to
- # align the label with the entry subwidget.
+ # align the label with the entry subwidget.
# [Hint] Notice that you should use padY (the NAME of the option) and not
# pady (the SWITCH of the option).
#
b = Tix.ComboBox(top, label="Year: ", dropdown=0,
- command=select_year, editable=1, variable=demo_year,
- options='listbox.height 4 label.padY 5 label.width 10 label.anchor ne')
+ command=select_year, editable=1, variable=demo_year,
+ options='listbox.height 4 label.padY 5 label.width 10 label.anchor ne')
a.pack(side=Tix.TOP, anchor=Tix.W)
b.pack(side=Tix.TOP, anchor=Tix.W)
@@ -70,7 +70,7 @@ def RunSample(w):
b.insert(Tix.END, '1996')
# Use "tixSetSilent" to set the values of the combo box if you
- # don't want your -command procedures (cbx:select_month and
+ # don't want your -command procedures (cbx:select_month and
# cbx:select_year) to be called.
#
a.set_silent('January')
@@ -78,9 +78,9 @@ def RunSample(w):
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='Ok', underline=0, width=6,
- command=lambda w=w: ok_command(w))
+ command=lambda w=w: ok_command(w))
box.add('cancel', text='Cancel', underline=0, width=6,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
diff --git a/Demo/tix/samples/Control.py b/Demo/tix/samples/Control.py
index e85ee845df..3a344c1e27 100755
--- a/Demo/tix/samples/Control.py
+++ b/Demo/tix/samples/Control.py
@@ -20,7 +20,7 @@
import Tix
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
control = DemoControl(root)
@@ -46,7 +46,7 @@ class DemoControl:
# $w.top.a allows only integer values
#
# [Hint] The -options switch sets the options of the subwidgets.
- # [Hint] We set the label.width subwidget option of the Controls to
+ # [Hint] We set the label.width subwidget option of the Controls to
# be 16 so that their labels appear to be aligned.
#
a = Tix.Control(top, label='Number of Engines: ', integer=1,
@@ -83,7 +83,7 @@ class DemoControl:
def okcmd (self):
# tixDemo:Status "Selected %d of %s engines each of thrust %d", (demo_num_engines.get(), demo_maker.get(), demo_thrust.get())
self.quitcmd()
-
+
def quitcmd (self):
self.exit = 0
@@ -100,9 +100,9 @@ def adjust_maker(w, inc):
i = maker_list.index(demo_maker.get())
i = i + inc
if i >= len(maker_list):
- i = 0
+ i = 0
elif i < 0:
- i = len(maker_list) - 1
+ i = len(maker_list) - 1
# In Tcl/Tix we should return the string maker_list[i]. We can't
# do that in Tkinter so we set the global variable. (This works).
@@ -110,10 +110,10 @@ def adjust_maker(w, inc):
def validate_maker(w):
try:
- i = maker_list.index(demo_maker.get())
+ i = maker_list.index(demo_maker.get())
except ValueError:
- # Works here though. Why ? Beats me.
- return maker_list[0]
+ # Works here though. Why ? Beats me.
+ return maker_list[0]
# Works here though. Why ? Beats me.
return maker_list[i]
diff --git a/Demo/tix/samples/DirList.py b/Demo/tix/samples/DirList.py
index 8d7536c7bd..5fd8c0de7f 100755
--- a/Demo/tix/samples/DirList.py
+++ b/Demo/tix/samples/DirList.py
@@ -1,6 +1,6 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
#
-# $Id$
+# $Id$
#
# Tix Demostration Program
#
@@ -19,21 +19,21 @@
import Tix, os, copy
from Tkconstants import *
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
dirlist = DemoDirList(root)
dirlist.mainloop()
dirlist.destroy()
-
+
class DemoDirList:
def __init__(self, w):
self.root = w
self.exit = -1
-
+
z = w.winfo_toplevel()
z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
+
# Create the tixDirList and the tixLabelEntry widgets on the on the top
# of the dialog box
@@ -48,14 +48,14 @@ class DemoDirList:
#
top.dir = Tix.DirList(top)
top.dir.hlist['width'] = 40
-
+
# When the user presses the ".." button, the selected directory
# is "transferred" into the entry widget
#
top.btn = Tix.Button(top, text = " >> ", pady = 0)
# We use a LabelEntry to hold the installation directory. The user
- # can choose from the DirList widget, or he can type in the directory
+ # can choose from the DirList widget, or he can type in the directory
# manually
#
top.ent = Tix.LabelEntry(top, label="Installation Directory:",
@@ -64,7 +64,7 @@ class DemoDirList:
entry.width 40
label.anchor w
''')
-
+
font = self.root.tk.eval('tix option get fixed_font')
# font = self.root.master.tix_option_get('fixed_font')
top.ent.entry['font'] = font
@@ -129,4 +129,3 @@ if __name__== '__main__' :
for line in traceback.format_exception(t,v,tb):
text = text + line + '\n'
d = tkMessageBox.showerror ( 'Tix Demo Error', text)
-
diff --git a/Demo/tix/samples/DirTree.py b/Demo/tix/samples/DirTree.py
index d007a2ba72..2e4fe0b957 100755
--- a/Demo/tix/samples/DirTree.py
+++ b/Demo/tix/samples/DirTree.py
@@ -1,6 +1,6 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
#
-# $Id$
+# $Id$
#
# Tix Demostration Program
#
@@ -19,7 +19,7 @@
import Tix, os, copy
from Tkconstants import *
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
dirtree = DemoDirTree(root)
@@ -30,7 +30,7 @@ class DemoDirTree:
def __init__(self, w):
self.root = w
self.exit = -1
-
+
z = w.winfo_toplevel()
z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
@@ -48,14 +48,14 @@ class DemoDirTree:
#
top.dir = Tix.DirTree(top)
top.dir.hlist['width'] = 40
-
+
# When the user presses the ".." button, the selected directory
# is "transferred" into the entry widget
#
top.btn = Tix.Button(top, text = " >> ", pady = 0)
# We use a LabelEntry to hold the installation directory. The user
- # can choose from the DirTree widget, or he can type in the directory
+ # can choose from the DirTree widget, or he can type in the directory
# manually
#
top.ent = Tix.LabelEntry(top, label="Installation Directory:",
@@ -115,4 +115,3 @@ class DemoDirTree:
if __name__== '__main__' :
root=Tix.Tk()
RunSample(root)
-
diff --git a/Demo/tix/samples/NoteBook.py b/Demo/tix/samples/NoteBook.py
index abf3bfd954..1e0da3e76a 100755
--- a/Demo/tix/samples/NoteBook.py
+++ b/Demo/tix/samples/NoteBook.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -23,9 +23,9 @@ def RunSample(w):
# notebook, so that they are well-aligned on the screen.
prefix = Tix.OptionName(w)
if prefix:
- prefix = '*'+prefix
+ prefix = '*'+prefix
else:
- prefix = ''
+ prefix = ''
w.option_add(prefix+'*TixControl*entry.width', 10)
w.option_add(prefix+'*TixControl*label.width', 18)
w.option_add(prefix+'*TixControl*label.anchor', Tix.E)
@@ -37,14 +37,14 @@ def RunSample(w):
nb = Tix.NoteBook(w, name='nb', ipadx=6, ipady=6)
nb['bg'] = 'gray'
nb.nbframe['backpagecolor'] = 'gray'
-
+
# Create the two tabs on the notebook. The -underline option
# puts a underline on the first character of the labels of the tabs.
# Keyboard accelerators will be defined automatically according
- # to the underlined character.
+ # to the underlined character.
nb.add('hard_disk', label="Hard Disk", underline=0)
nb.add('network', label="Network", underline=0)
-
+
nb.pack(expand=1, fill=Tix.BOTH, padx=5, pady=5 ,side=Tix.TOP)
#----------------------------------------
@@ -56,62 +56,62 @@ def RunSample(w):
tab=nb.hard_disk
f = Tix.Frame(tab)
common = Tix.Frame(tab)
-
+
f.pack(side=Tix.LEFT, padx=2, pady=2, fill=Tix.BOTH, expand=1)
common.pack(side=Tix.RIGHT, padx=2, fill=Tix.Y)
-
+
a = Tix.Control(f, value=12, label='Access time: ')
w = Tix.Control(f, value=400, label='Write Throughput: ')
r = Tix.Control(f, value=400, label='Read Throughput: ')
c = Tix.Control(f, value=1021, label='Capacity: ')
-
+
a.pack(side=Tix.TOP, padx=20, pady=2)
w.pack(side=Tix.TOP, padx=20, pady=2)
r.pack(side=Tix.TOP, padx=20, pady=2)
c.pack(side=Tix.TOP, padx=20, pady=2)
-
+
# Create the common buttons
createCommonButtons(common)
-
+
#----------------------------------------
- # Create the second page
+ # Create the second page
#----------------------------------------
-
+
tab = nb.network
f = Tix.Frame(tab)
common = Tix.Frame(tab)
-
+
f.pack(side=Tix.LEFT, padx=2, pady=2, fill=Tix.BOTH, expand=1)
common.pack(side=Tix.RIGHT, padx=2, fill=Tix.Y)
-
+
a = Tix.Control(f, value=12, label='Access time: ')
w = Tix.Control(f, value=400, label='Write Throughput: ')
r = Tix.Control(f, value=400, label='Read Throughput: ')
c = Tix.Control(f, value=1021, label='Capacity: ')
u = Tix.Control(f, value=10, label='Users: ')
-
+
a.pack(side=Tix.TOP, padx=20, pady=2)
w.pack(side=Tix.TOP, padx=20, pady=2)
r.pack(side=Tix.TOP, padx=20, pady=2)
c.pack(side=Tix.TOP, padx=20, pady=2)
u.pack(side=Tix.TOP, padx=20, pady=2)
-
+
createCommonButtons(common)
-
+
def doDestroy():
global root
root.destroy()
def createCommonButtons(master):
- ok = Tix.Button(master, name='ok', text='OK', width=6,
- command=doDestroy)
- cancel = Tix.Button(master, name='cancel',
- text='Cancel', width=6,
- command=doDestroy)
-
+ ok = Tix.Button(master, name='ok', text='OK', width=6,
+ command=doDestroy)
+ cancel = Tix.Button(master, name='cancel',
+ text='Cancel', width=6,
+ command=doDestroy)
+
ok.pack(side=Tix.TOP, padx=2, pady=2)
- cancel.pack(side=Tix.TOP, padx=2, pady=2)
+ cancel.pack(side=Tix.TOP, padx=2, pady=2)
if __name__ == '__main__':
root = Tix.Tk()
diff --git a/Demo/tix/samples/OptMenu.py b/Demo/tix/samples/OptMenu.py
index ecb0c86abc..1d39420cd9 100755
--- a/Demo/tix/samples/OptMenu.py
+++ b/Demo/tix/samples/OptMenu.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -16,7 +16,7 @@
import Tix
options = {'text':'Plain Text', 'post':'PostScript', 'html':'HTML',
- 'tex':'LaTeX', 'rtf':'Rich Text Format'}
+ 'tex':'LaTeX', 'rtf':'Rich Text Format'}
def RunSample(w):
global demo_opt_from, demo_opt_to
@@ -27,22 +27,22 @@ def RunSample(w):
top = Tix.Frame(w, bd=1, relief=Tix.RAISED)
from_file = Tix.OptionMenu(top, label="From File Format : ",
- variable=demo_opt_from,
- options = 'label.width 19 label.anchor e menubutton.width 15')
+ variable=demo_opt_from,
+ options = 'label.width 19 label.anchor e menubutton.width 15')
to_file = Tix.OptionMenu(top, label="To File Format : ",
- variable=demo_opt_to,
- options='label.width 19 label.anchor e menubutton.width 15')
+ variable=demo_opt_to,
+ options='label.width 19 label.anchor e menubutton.width 15')
# Add the available options to the two OptionMenu widgets
#
# [Hint] You have to add the options first before you set the
- # global variables "demo_opt_from" and "demo_opt_to". Otherwise
- # the OptionMenu widget will complain about "unknown options"!
+ # global variables "demo_opt_from" and "demo_opt_to". Otherwise
+ # the OptionMenu widget will complain about "unknown options"!
#
for opt in options.keys():
- from_file.add_command(opt, label=options[opt])
- to_file.add_command(opt, label=options[opt])
+ from_file.add_command(opt, label=options[opt])
+ to_file.add_command(opt, label=options[opt])
demo_opt_from.set('html')
demo_opt_to.set('post')
@@ -52,9 +52,9 @@ def RunSample(w):
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='Ok', underline=0, width=6,
- command=lambda w=w: ok_command(w))
+ command=lambda w=w: ok_command(w))
box.add('cancel', text='Cancel', underline=0, width=6,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
diff --git a/Demo/tix/samples/PanedWin.py b/Demo/tix/samples/PanedWin.py
index bfe10c2736..3efc7317c4 100755
--- a/Demo/tix/samples/PanedWin.py
+++ b/Demo/tix/samples/PanedWin.py
@@ -17,7 +17,7 @@
import Tix
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
panedwin = DemoPanedwin(root)
diff --git a/Demo/tix/samples/PopMenu.py b/Demo/tix/samples/PopMenu.py
index 602eafdc5c..32f3229294 100755
--- a/Demo/tix/samples/PopMenu.py
+++ b/Demo/tix/samples/PopMenu.py
@@ -1,6 +1,6 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
#
-# $Id$
+# $Id$
#
# Tix Demostration Program
#
@@ -27,9 +27,9 @@ def RunSample(w):
p.bind_widget(top)
p.bind_widget(but)
- # Set the entries inside the PopupMenu widget.
+ # Set the entries inside the PopupMenu widget.
# [Hint] You have to manipulate the "menu" subwidget.
- # $w.top.p itself is NOT a menu widget.
+ # $w.top.p itself is NOT a menu widget.
# [Hint] Watch carefully how the sub-menu is created
#
p.menu.add_command(label='Desktop', underline=0)
@@ -45,9 +45,9 @@ def RunSample(w):
box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL)
box.add('ok', text='Ok', underline=0, width=6,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.add('cancel', text='Cancel', underline=0, width=6,
- command=lambda w=w: w.destroy())
+ command=lambda w=w: w.destroy())
box.pack(side=Tix.BOTTOM, fill=Tix.X)
top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1)
diff --git a/Demo/tix/samples/SHList1.py b/Demo/tix/samples/SHList1.py
index 0114dc8a53..7ca7b3e7fb 100755
--- a/Demo/tix/samples/SHList1.py
+++ b/Demo/tix/samples/SHList1.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -15,13 +15,13 @@
import Tix
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
shlist = DemoSHList(root)
shlist.mainloop()
shlist.destroy()
-
+
class DemoSHList:
def __init__(self, w):
self.root = w
@@ -29,7 +29,7 @@ class DemoSHList:
z = w.winfo_toplevel()
z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
+
# We create the frame and the ScrolledHList widget
# at the top of the dialog box
#
@@ -61,7 +61,7 @@ class DemoSHList:
hlist=top.a.hlist
- # Let configure the appearance of the HList subwidget
+ # Let configure the appearance of the HList subwidget
#
hlist.config( separator='.', width=25, drawbranch=0, indent=10)
@@ -71,7 +71,7 @@ class DemoSHList:
f=Tix.Frame(hlist, name='sep%d' % count, height=2, width=150,
bd=2, relief=Tix.SUNKEN )
- hlist.add_child( itemtype=Tix.WINDOW,
+ hlist.add_child( itemtype=Tix.WINDOW,
window=f, state=Tix.DISABLED )
hlist.add(boss, itemtype=Tix.TEXT, text=name)
@@ -88,13 +88,13 @@ class DemoSHList:
hlist.add( key, text=name )
# [Hint] Make sure the keys (e.g. 'boss.person') you choose
- # are unique names. If you cannot be sure of this (because of
- # the structure of your database, e.g.) you can use the
- # "add_child" command instead:
+ # are unique names. If you cannot be sure of this (because of
+ # the structure of your database, e.g.) you can use the
+ # "add_child" command instead:
#
# hlist.addchild( boss, text=name)
# ^^^^
- # parent entryPath
+ # parent entryPath
# Use a ButtonBox to hold the buttons.
@@ -129,4 +129,3 @@ class DemoSHList:
if __name__== '__main__' :
root=Tix.Tk()
RunSample(root)
-
diff --git a/Demo/tix/samples/SHList2.py b/Demo/tix/samples/SHList2.py
index e82d1e586a..17fd5519e2 100755
--- a/Demo/tix/samples/SHList2.py
+++ b/Demo/tix/samples/SHList2.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -13,18 +13,18 @@
# This file demonstrates how to use multiple columns and multiple styles
# in the tixHList widget
#
-# In a tixHList widget, you can have one ore more columns.
+# In a tixHList widget, you can have one ore more columns.
#
import Tix
-TCL_ALL_EVENTS = 0
+TCL_ALL_EVENTS = 0
def RunSample (root):
shlist = DemoSHList(root)
shlist.mainloop()
shlist.destroy()
-
+
class DemoSHList:
def __init__(self, w):
self.root = w
@@ -32,7 +32,7 @@ class DemoSHList:
z = w.winfo_toplevel()
z.wm_protocol("WM_DELETE_WINDOW", lambda self=self: self.quitcmd())
-
+
# We create the frame and the ScrolledHList widget
# at the top of the dialog box
#
@@ -47,7 +47,7 @@ class DemoSHList:
hlist=top.a.hlist
# Create the title for the HList widget
- # >> Notice that we have set the hlist.header subwidget option to true
+ # >> Notice that we have set the hlist.header subwidget option to true
# so that the header is displayed
#
@@ -72,22 +72,22 @@ class DemoSHList:
# This is our little relational database
#
- boss = ('doe', 'John Doe', 'Director')
+ boss = ('doe', 'John Doe', 'Director')
managers = [
- ('jeff', 'Jeff Waxman', 'Manager'),
- ('john', 'John Lee', 'Manager'),
- ('peter', 'Peter Kenson', 'Manager')
+ ('jeff', 'Jeff Waxman', 'Manager'),
+ ('john', 'John Lee', 'Manager'),
+ ('peter', 'Peter Kenson', 'Manager')
]
employees = [
- ('alex', 'john', 'Alex Kellman', 'Clerk'),
- ('alan', 'john', 'Alan Adams', 'Clerk'),
- ('andy', 'peter', 'Andreas Crawford', 'Salesman'),
- ('doug', 'jeff', 'Douglas Bloom', 'Clerk'),
- ('jon', 'peter', 'Jon Baraki', 'Salesman'),
- ('chris', 'jeff', 'Chris Geoffrey', 'Clerk'),
- ('chuck', 'jeff', 'Chuck McLean', 'Cleaner')
+ ('alex', 'john', 'Alex Kellman', 'Clerk'),
+ ('alan', 'john', 'Alan Adams', 'Clerk'),
+ ('andy', 'peter', 'Andreas Crawford', 'Salesman'),
+ ('doug', 'jeff', 'Douglas Bloom', 'Clerk'),
+ ('jon', 'peter', 'Jon Baraki', 'Salesman'),
+ ('chris', 'jeff', 'Chris Geoffrey', 'Clerk'),
+ ('chuck', 'jeff', 'Chuck McLean', 'Cleaner')
]
style['mgr_name'] = Tix.DisplayStyle(Tix.TEXT, refwindow=hlist)
@@ -98,7 +98,7 @@ class DemoSHList:
style['empl_posn'] = Tix.DisplayStyle(Tix.TEXT, padx=8, refwindow=hlist)
- # Let configure the appearance of the HList subwidget
+ # Let configure the appearance of the HList subwidget
#
hlist.config(separator='.', width=25, drawbranch=0, indent=10)
hlist.column_width(0, chars=20)
@@ -124,10 +124,10 @@ class DemoSHList:
for key,mgr,name,posn in employees :
# "." is the separator character we chose above
- entrypath = '.' + mgr + '.' + key
+ entrypath = '.' + mgr + '.' + key
# ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
- # parent entryPath / child's name
+ # parent entryPath / child's name
hlist.add(entrypath, text=name, style=style['empl_name'])
hlist.item_create(entrypath, 1, itemtype=Tix.TEXT,
@@ -166,4 +166,3 @@ class DemoSHList:
if __name__== '__main__' :
root=Tix.Tk()
RunSample(root)
-
diff --git a/Demo/tix/samples/Tree.py b/Demo/tix/samples/Tree.py
index 2fdd7c79c5..9a7e4810f5 100755
--- a/Demo/tix/samples/Tree.py
+++ b/Demo/tix/samples/Tree.py
@@ -1,5 +1,5 @@
# -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*-
-#
+#
# $Id$
#
# Tix Demostration Program
@@ -34,17 +34,17 @@ def RunSample(w):
def adddir(tree, dir):
if dir == '/':
- text = '/'
+ text = '/'
else:
- text = os.path.basename(dir)
+ text = os.path.basename(dir)
tree.hlist.add(dir, itemtype=Tix.IMAGETEXT, text=text,
- image=tree.tk.call('tix', 'getimage', 'folder'))
+ image=tree.tk.call('tix', 'getimage', 'folder'))
try:
- os.listdir(dir)
- tree.setmode(dir, 'open')
+ os.listdir(dir)
+ tree.setmode(dir, 'open')
except os.error:
- # No read permission ?
- pass
+ # No read permission ?
+ pass
# This function is called whenever the user presses the (+) indicator or
# double clicks on a directory whose mode is "open". It loads the files
@@ -57,22 +57,22 @@ def adddir(tree, dir):
def opendir(tree, dir):
entries = tree.hlist.info_children(dir)
if entries:
- # We have already loaded this directory. Let's just
- # show all the child entries
- #
- # Note: since we load the directory only once, it will not be
- # refreshed if the you add or remove files from this
- # directory.
- #
- for entry in entries:
- tree.hlist.show_entry(entry)
+ # We have already loaded this directory. Let's just
+ # show all the child entries
+ #
+ # Note: since we load the directory only once, it will not be
+ # refreshed if the you add or remove files from this
+ # directory.
+ #
+ for entry in entries:
+ tree.hlist.show_entry(entry)
files = os.listdir(dir)
for file in files:
- if os.path.isdir(dir + '/' + file):
- adddir(tree, dir + '/' + file)
- else:
- tree.hlist.add(dir + '/' + file, itemtype=Tix.IMAGETEXT, text=file,
- image=tree.tk.call('tix', 'getimage', 'file'))
+ if os.path.isdir(dir + '/' + file):
+ adddir(tree, dir + '/' + file)
+ else:
+ tree.hlist.add(dir + '/' + file, itemtype=Tix.IMAGETEXT, text=file,
+ image=tree.tk.call('tix', 'getimage', 'file'))
if __name__ == '__main__':
root = Tix.Tk()
diff --git a/Demo/tix/tixwidgets.py b/Demo/tix/tixwidgets.py
index ae7b063ee4..de2e22e7eb 100644
--- a/Demo/tix/tixwidgets.py
+++ b/Demo/tix/tixwidgets.py
@@ -4,38 +4,38 @@
#
# tixwidgets.py --
#
-# For Tix, see http://tix.sourceforge.net
+# For Tix, see http://tix.sourceforge.net
#
-# This is a demo program of some of the Tix widgets available in Python.
-# If you have installed Python & Tix properly, you can execute this as
+# This is a demo program of some of the Tix widgets available in Python.
+# If you have installed Python & Tix properly, you can execute this as
#
-# % python tixwidgets.py
+# % python tixwidgets.py
#
import os, os.path, sys, Tix
from Tkconstants import *
import traceback, tkMessageBox
-TCL_DONT_WAIT = 1<<1
-TCL_WINDOW_EVENTS = 1<<2
-TCL_FILE_EVENTS = 1<<3
-TCL_TIMER_EVENTS = 1<<4
-TCL_IDLE_EVENTS = 1<<5
-TCL_ALL_EVENTS = 0
+TCL_DONT_WAIT = 1<<1
+TCL_WINDOW_EVENTS = 1<<2
+TCL_FILE_EVENTS = 1<<3
+TCL_TIMER_EVENTS = 1<<4
+TCL_IDLE_EVENTS = 1<<5
+TCL_ALL_EVENTS = 0
class Demo:
def __init__(self, top):
self.root = top
self.exit = -1
- self.dir = None # script directory
- self.balloon = None # balloon widget
+ self.dir = None # script directory
+ self.balloon = None # balloon widget
self.useBalloons = Tix.StringVar()
self.useBalloons.set('0')
- self.statusbar = None # status bar widget
- self.welmsg = None # Msg widget
- self.welfont = '' # font name
- self.welsize = '' # font size
+ self.statusbar = None # status bar widget
+ self.welmsg = None # Msg widget
+ self.welfont = '' # font name
+ self.welsize = '' # font size
progname = sys.argv[0]
dirname = os.path.dirname(progname)
@@ -72,7 +72,7 @@ class Demo:
variable=self.useBalloons)
# The trace variable option doesn't seem to work, instead I use 'command'
#apply(w.tk.call, ('trace', 'variable', self.useBalloons, 'w',
- # ToggleHelp))
+ # ToggleHelp))
return w
@@ -130,15 +130,15 @@ class Demo:
# To show Tcl errors - uncomment this to see the listbox bug.
# Tkinter defines a Tcl tkerror procedure that in effect
# silences all background Tcl error reporting.
- # root.tk.eval('if {[info commands tkerror] != ""} {rename tkerror pytkerror}')
+ # root.tk.eval('if {[info commands tkerror] != ""} {rename tkerror pytkerror}')
def quitcmd (self):
"""Quit our mainloop. It is up to you to call root.destroy() after."""
self.exit = 0
def loop(self):
- """This is an explict replacement for _tkinter mainloop()
- It lets you catch keyboard interrupts easier, and avoids
- the 20 msec. dead sleep() which burns a constant CPU."""
+ """This is an explict replacement for _tkinter mainloop()
+ It lets you catch keyboard interrupts easier, and avoids
+ the 20 msec. dead sleep() which burns a constant CPU."""
while self.exit < 0:
# There are 2 whiles here. The outer one lets you continue
# after a ^C interrupt.
@@ -221,9 +221,9 @@ def MkWelcomeBar(top):
b2.pack(side=Tix.LEFT, padx=4, pady=4)
demo.balloon.bind_widget(b1, msg='Choose\na font',
- statusmsg='Choose a font for this page')
+ statusmsg='Choose a font for this page')
demo.balloon.bind_widget(b2, msg='Point size',
- statusmsg='Choose the font size for this page')
+ statusmsg='Choose the font size for this page')
return w
def MkWelcomeText(top):
@@ -233,10 +233,10 @@ def MkWelcomeText(top):
win = w.window
text = 'Welcome to TIX in Python'
title = Tix.Label(win,
- bd=0, width=30, anchor=Tix.N, text=text)
+ bd=0, width=30, anchor=Tix.N, text=text)
msg = Tix.Message(win,
- bd=0, width=400, anchor=Tix.N,
- text='Tix is a set of mega-widgets based on TK. This program \
+ bd=0, width=400, anchor=Tix.N,
+ text='Tix is a set of mega-widgets based on TK. This program \
demonstrates the widgets in the Tix widget set. You can choose the pages \
in this window to look at the corresponding widgets. \n\n\
To quit this program, choose the "File | Exit" command.\n\n\
@@ -250,19 +250,19 @@ def MainTextFont(w):
global demo
if not demo.welmsg:
- return
+ return
font = demo.welfont['value']
point = demo.welsize['value']
if font == 'Times Roman':
- font = 'times'
+ font = 'times'
fontstr = '%s %s' % (font, point)
demo.welmsg['font'] = fontstr
def ToggleHelp():
if demo.useBalloons.get() == '1':
- demo.balloon['state'] = 'both'
+ demo.balloon['state'] = 'both'
else:
- demo.balloon['state'] = 'none'
+ demo.balloon['state'] = 'none'
def MkChoosers(nb, name):
w = nb.page(name)
@@ -307,7 +307,7 @@ def MkCombo(w):
static = Tix.ComboBox(w, label='Static', editable=0, options=options)
editable = Tix.ComboBox(w, label='Editable', editable=1, options=options)
history = Tix.ComboBox(w, label='History', editable=1, history=1,
- anchor=Tix.E, options=options)
+ anchor=Tix.E, options=options)
static.insert(Tix.END, 'January')
static.insert(Tix.END, 'February')
static.insert(Tix.END, 'March')
@@ -340,20 +340,20 @@ states = ['Bengal', 'Delhi', 'Karnataka', 'Tamil Nadu']
def spin_cmd(w, inc):
idx = states.index(demo_spintxt.get()) + inc
if idx < 0:
- idx = len(states) - 1
+ idx = len(states) - 1
elif idx >= len(states):
- idx = 0
+ idx = 0
# following doesn't work.
# return states[idx]
- demo_spintxt.set(states[idx]) # this works
+ demo_spintxt.set(states[idx]) # this works
def spin_validate(w):
global states, demo_spintxt
try:
- i = states.index(demo_spintxt.get())
+ i = states.index(demo_spintxt.get())
except ValueError:
- return states[0]
+ return states[0]
return states[i]
# why this procedure works as opposed to the previous one beats me.
@@ -417,8 +417,8 @@ def MkOptMenu(w):
def MkFileEnt(w):
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='Press the "open file" icon button and a TixFileSelectDialog will popup.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='Press the "open file" icon button and a TixFileSelectDialog will popup.')
ent = Tix.FileEntry(w, label='Select a file : ')
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
ent.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3)
@@ -429,8 +429,8 @@ def MkFileBox(w):
and your past selections are recorded.
"""
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The Tix FileSelectBox is a Motif-style box with various enhancements. For example, you can adjust the size of the two listboxes and your past selections are recorded.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The Tix FileSelectBox is a Motif-style box with various enhancements. For example, you can adjust the size of the two listboxes and your past selections are recorded.')
box = Tix.FileSelectBox(w)
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
box.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3)
@@ -443,8 +443,8 @@ def MkToolBar(w):
options='frame.borderWidth 1'
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The Select widget is also good for arranging buttons in a tool bar.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The Select widget is also good for arranging buttons in a tool bar.')
bar = Tix.Frame(w, bd=2, relief=Tix.RAISED)
font = Tix.Select(w, allowzero=1, radio=0, label='', options=options)
para = Tix.Select(w, allowzero=0, radio=1, label='', options=options)
@@ -466,8 +466,8 @@ def MkToolBar(w):
def MkTitle(w):
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='There are many types of "chooser" widgets that allow the user to input different types of information')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='There are many types of "chooser" widgets that allow the user to input different types of information')
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
def MkScroll(nb, name):
@@ -494,8 +494,8 @@ def MkSList(w):
top = Tix.Frame(w, width=300, height=330)
bot = Tix.Frame(w)
msg = Tix.Message(top,
- relief=Tix.FLAT, width=200, anchor=Tix.N,
- text='This TixScrolledListBox is configured so that it uses scrollbars only when it is necessary. Use the handles to resize the listbox and watch the scrollbars automatically appear and disappear.')
+ relief=Tix.FLAT, width=200, anchor=Tix.N,
+ text='This TixScrolledListBox is configured so that it uses scrollbars only when it is necessary. Use the handles to resize the listbox and watch the scrollbars automatically appear and disappear.')
list = Tix.ScrolledListBox(top, scrollbar='auto')
list.place(x=50, y=150, width=120, height=80)
@@ -508,8 +508,8 @@ def MkSList(w):
list.listbox.insert(Tix.END, 'Washington')
rh = Tix.ResizeHandle(top, bg='black',
- relief=Tix.RAISED,
- handlesize=8, gridded=1, minwidth=50, minheight=30)
+ relief=Tix.RAISED,
+ handlesize=8, gridded=1, minwidth=50, minheight=30)
btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=list: SList_reset(w,x))
top.propagate(0)
msg.pack(fill=Tix.X)
@@ -517,7 +517,7 @@ def MkSList(w):
top.pack(expand=1, fill=Tix.BOTH)
bot.pack(fill=Tix.BOTH)
list.bind('<Map>', func=lambda arg=0, rh=rh, list=list:
- list.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(list)))
+ list.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(list)))
def SList_reset(rh, list):
list.place(x=50, y=150, width=120, height=80)
@@ -539,8 +539,8 @@ def MkSWindow(w):
top = Tix.Frame(w, width=330, height=330)
bot = Tix.Frame(w)
msg = Tix.Message(top,
- relief=Tix.FLAT, width=200, anchor=Tix.N,
- text=text)
+ relief=Tix.FLAT, width=200, anchor=Tix.N,
+ text=text)
win = Tix.ScrolledWindow(top, scrollbar='auto')
@@ -551,8 +551,8 @@ def MkSWindow(w):
win.place(x=30, y=150, width=190, height=120)
rh = Tix.ResizeHandle(top, bg='black',
- relief=Tix.RAISED,
- handlesize=8, gridded=1, minwidth=50, minheight=30)
+ relief=Tix.RAISED,
+ handlesize=8, gridded=1, minwidth=50, minheight=30)
btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SWindow_reset(w,x))
top.propagate(0)
msg.pack(fill=Tix.X)
@@ -561,7 +561,7 @@ def MkSWindow(w):
bot.pack(fill=Tix.BOTH)
win.bind('<Map>', func=lambda arg=0, rh=rh, win=win:
- win.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(win)))
+ win.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(win)))
def SWindow_reset(rh, win):
win.place(x=30, y=150, width=190, height=120)
@@ -574,27 +574,27 @@ def MkSText(w):
top = Tix.Frame(w, width=330, height=330)
bot = Tix.Frame(w)
msg = Tix.Message(top,
- relief=Tix.FLAT, width=200, anchor=Tix.N,
- text='The Tix ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.')
+ relief=Tix.FLAT, width=200, anchor=Tix.N,
+ text='The Tix ScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.')
win = Tix.ScrolledText(top, scrollbar='auto')
win.text['wrap'] = 'none'
win.text.insert(Tix.END, '''When -scrollbar is set to "auto", the
-scrollbars are shown only when needed.
+scrollbars are shown only when needed.
Additional modifiers can be used to force a
-scrollbar to be shown or hidden. For example,
-"auto -y" means the horizontal scrollbar
-should be shown when needed but the vertical
+scrollbar to be shown or hidden. For example,
+"auto -y" means the horizontal scrollbar
+should be shown when needed but the vertical
scrollbar should always be hidden;
"auto +x" means the vertical scrollbar
-should be shown when needed but the horizontal
+should be shown when needed but the horizontal
scrollbar should always be shown, and so on.'''
)
win.place(x=30, y=150, width=190, height=100)
rh = Tix.ResizeHandle(top, bg='black',
- relief=Tix.RAISED,
- handlesize=8, gridded=1, minwidth=50, minheight=30)
+ relief=Tix.RAISED,
+ handlesize=8, gridded=1, minwidth=50, minheight=30)
btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SText_reset(w,x))
top.propagate(0)
msg.pack(fill=Tix.X)
@@ -602,7 +602,7 @@ scrollbar should always be shown, and so on.'''
top.pack(expand=1, fill=Tix.BOTH)
bot.pack(fill=Tix.BOTH)
win.bind('<Map>', func=lambda arg=0, rh=rh, win=win:
- win.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(win)))
+ win.tk.call('tixDoWhenIdle', str(rh), 'attachwidget', str(win)))
def SText_reset(rh, win):
win.place(x=30, y=150, width=190, height=120)
@@ -628,8 +628,8 @@ def MkPanedWindow(w):
or horizontally.
"""
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The PanedWindow widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The PanedWindow widget allows the user to interactively manipulate the sizes of several panes. The panes can be arranged either vertically or horizontally.')
group = Tix.LabelEntry(w, label='Newsgroup:', options='entry.width 25')
group.entry.insert(0,'comp.lang.python')
pane = Tix.PanedWindow(w, orientation='vertical')
@@ -671,8 +671,8 @@ together with a bitmap, at the same time, inside a TK button widget.
def MkNoteBook(w):
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The NoteBook widget allows you to layout a complex interface into individual pages.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The NoteBook widget allows you to layout a complex interface into individual pages.')
# prefix = Tix.OptionName(w)
# if not prefix: prefix = ''
# w.option_add('*' + prefix + '*TixNoteBook*tagPadX', 8)
@@ -738,8 +738,8 @@ def MkDirListWidget(w):
directories.
"""
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The Tix DirList widget gives a graphical representation of the file system directory and makes it easy for the user to choose and access directories.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The Tix DirList widget gives a graphical representation of the file system directory and makes it easy for the user to choose and access directories.')
dirlist = Tix.DirList(w, options='hlist.padY 1 hlist.width 25 hlist.height 16')
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
dirlist.pack(side=Tix.TOP, padx=3, pady=3)
@@ -748,8 +748,8 @@ def MkExFileWidget(w):
"""The TixExFileSelectBox widget is more user friendly than the Motif
style FileSelectBox. """
msg = Tix.Message(w,
- relief=Tix.FLAT, width=240, anchor=Tix.N,
- text='The Tix ExFileSelectBox widget is more user friendly than the Motif style FileSelectBox.')
+ relief=Tix.FLAT, width=240, anchor=Tix.N,
+ text='The Tix ExFileSelectBox widget is more user friendly than the Motif style FileSelectBox.')
# There's a bug in the ComboBoxes - the scrolledlistbox is destroyed
box = Tix.ExFileSelectBox(w, bd=2, relief=Tix.RAISED)
msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3)
@@ -758,118 +758,118 @@ def MkExFileWidget(w):
###
### List of all the demos we want to show off
comments = {'widget' : 'Widget Demos', 'image' : 'Image Demos'}
-samples = {'Balloon' : 'Balloon',
- 'Button Box' : 'BtnBox',
- 'Combo Box' : 'ComboBox',
- 'Compound Image' : 'CmpImg',
- 'Directory List' : 'DirList',
- 'Directory Tree' : 'DirTree',
- 'Control' : 'Control',
- 'Notebook' : 'NoteBook',
- 'Option Menu' : 'OptMenu',
- 'Paned Window' : 'PanedWin',
- 'Popup Menu' : 'PopMenu',
- 'ScrolledHList (1)' : 'SHList1',
- 'ScrolledHList (2)' : 'SHList2',
- 'Tree (dynamic)' : 'Tree'
+samples = {'Balloon' : 'Balloon',
+ 'Button Box' : 'BtnBox',
+ 'Combo Box' : 'ComboBox',
+ 'Compound Image' : 'CmpImg',
+ 'Directory List' : 'DirList',
+ 'Directory Tree' : 'DirTree',
+ 'Control' : 'Control',
+ 'Notebook' : 'NoteBook',
+ 'Option Menu' : 'OptMenu',
+ 'Paned Window' : 'PanedWin',
+ 'Popup Menu' : 'PopMenu',
+ 'ScrolledHList (1)' : 'SHList1',
+ 'ScrolledHList (2)' : 'SHList2',
+ 'Tree (dynamic)' : 'Tree'
}
# There are still a lot of demos to be translated:
-## set root {
-## {d "File Selectors" file }
-## {d "Hierachical ListBox" hlist }
-## {d "Tabular ListBox" tlist {c tixTList}}
-## {d "Grid Widget" grid {c tixGrid}}
-## {d "Manager Widgets" manager }
-## {d "Scrolled Widgets" scroll }
-## {d "Miscellaneous Widgets" misc }
-## {d "Image Types" image }
-## }
+## set root {
+## {d "File Selectors" file }
+## {d "Hierachical ListBox" hlist }
+## {d "Tabular ListBox" tlist {c tixTList}}
+## {d "Grid Widget" grid {c tixGrid}}
+## {d "Manager Widgets" manager }
+## {d "Scrolled Widgets" scroll }
+## {d "Miscellaneous Widgets" misc }
+## {d "Image Types" image }
+## }
##
-## set image {
-## {d "Compound Image" cmpimg }
-## {d "XPM Image" xpm {i pixmap}}
-## }
+## set image {
+## {d "Compound Image" cmpimg }
+## {d "XPM Image" xpm {i pixmap}}
+## }
##
-## set cmpimg {
-##done {f "In Buttons" CmpImg.tcl }
-## {f "In NoteBook" CmpImg2.tcl }
-## {f "Notebook Color Tabs" CmpImg4.tcl }
-## {f "Icons" CmpImg3.tcl }
-## }
+## set cmpimg {
+##done {f "In Buttons" CmpImg.tcl }
+## {f "In NoteBook" CmpImg2.tcl }
+## {f "Notebook Color Tabs" CmpImg4.tcl }
+## {f "Icons" CmpImg3.tcl }
+## }
##
-## set xpm {
-## {f "In Button" Xpm.tcl {i pixmap}}
-## {f "In Menu" Xpm1.tcl {i pixmap}}
-## }
+## set xpm {
+## {f "In Button" Xpm.tcl {i pixmap}}
+## {f "In Menu" Xpm1.tcl {i pixmap}}
+## }
##
-## set file {
-##added {f DirList DirList.tcl }
-##added {f DirTree DirTree.tcl }
-## {f DirSelectDialog DirDlg.tcl }
-## {f ExFileSelectDialog EFileDlg.tcl }
-## {f FileSelectDialog FileDlg.tcl }
-## {f FileEntry FileEnt.tcl }
-## }
+## set file {
+##added {f DirList DirList.tcl }
+##added {f DirTree DirTree.tcl }
+## {f DirSelectDialog DirDlg.tcl }
+## {f ExFileSelectDialog EFileDlg.tcl }
+## {f FileSelectDialog FileDlg.tcl }
+## {f FileEntry FileEnt.tcl }
+## }
##
-## set hlist {
-## {f HList HList1.tcl }
-## {f CheckList ChkList.tcl {c tixCheckList}}
-##done {f "ScrolledHList (1)" SHList.tcl }
-##done {f "ScrolledHList (2)" SHList2.tcl }
-##done {f Tree Tree.tcl }
-##done {f "Tree (Dynamic)" DynTree.tcl {v win}}
-## }
+## set hlist {
+## {f HList HList1.tcl }
+## {f CheckList ChkList.tcl {c tixCheckList}}
+##done {f "ScrolledHList (1)" SHList.tcl }
+##done {f "ScrolledHList (2)" SHList2.tcl }
+##done {f Tree Tree.tcl }
+##done {f "Tree (Dynamic)" DynTree.tcl {v win}}
+## }
##
-## set tlist {
-## {f "ScrolledTList (1)" STList1.tcl {c tixTList}}
-## {f "ScrolledTList (2)" STList2.tcl {c tixTList}}
-## }
-## global tcl_platform
-## # This demo hangs windows
-## if {$tcl_platform(platform) != "windows"} {
-##na lappend tlist {f "TList File Viewer" STList3.tcl {c tixTList}}
-## }
+## set tlist {
+## {f "ScrolledTList (1)" STList1.tcl {c tixTList}}
+## {f "ScrolledTList (2)" STList2.tcl {c tixTList}}
+## }
+## global tcl_platform
+## # This demo hangs windows
+## if {$tcl_platform(platform) != "windows"} {
+##na lappend tlist {f "TList File Viewer" STList3.tcl {c tixTList}}
+## }
##
-## set grid {
-##na {f "Simple Grid" SGrid0.tcl {c tixGrid}}
-##na {f "ScrolledGrid" SGrid1.tcl {c tixGrid}}
-##na {f "Editable Grid" EditGrid.tcl {c tixGrid}}
-## }
+## set grid {
+##na {f "Simple Grid" SGrid0.tcl {c tixGrid}}
+##na {f "ScrolledGrid" SGrid1.tcl {c tixGrid}}
+##na {f "Editable Grid" EditGrid.tcl {c tixGrid}}
+## }
##
-## set scroll {
-## {f ScrolledListBox SListBox.tcl }
-## {f ScrolledText SText.tcl }
-## {f ScrolledWindow SWindow.tcl }
-##na {f "Canvas Object View" CObjView.tcl {c tixCObjView}}
-## }
+## set scroll {
+## {f ScrolledListBox SListBox.tcl }
+## {f ScrolledText SText.tcl }
+## {f ScrolledWindow SWindow.tcl }
+##na {f "Canvas Object View" CObjView.tcl {c tixCObjView}}
+## }
##
-## set manager {
-## {f ListNoteBook ListNBK.tcl }
-##done {f NoteBook NoteBook.tcl }
-##done {f PanedWindow PanedWin.tcl }
-## }
+## set manager {
+## {f ListNoteBook ListNBK.tcl }
+##done {f NoteBook NoteBook.tcl }
+##done {f PanedWindow PanedWin.tcl }
+## }
##
-## set misc {
-##done {f Balloon Balloon.tcl }
-##done {f ButtonBox BtnBox.tcl }
-##done {f ComboBox ComboBox.tcl }
-##done {f Control Control.tcl }
-## {f LabelEntry LabEntry.tcl }
-## {f LabelFrame LabFrame.tcl }
-## {f Meter Meter.tcl {c tixMeter}}
-##done {f OptionMenu OptMenu.tcl }
-##done {f PopupMenu PopMenu.tcl }
-## {f Select Select.tcl }
-## {f StdButtonBox StdBBox.tcl }
-## }
+## set misc {
+##done {f Balloon Balloon.tcl }
+##done {f ButtonBox BtnBox.tcl }
+##done {f ComboBox ComboBox.tcl }
+##done {f Control Control.tcl }
+## {f LabelEntry LabEntry.tcl }
+## {f LabelFrame LabFrame.tcl }
+## {f Meter Meter.tcl {c tixMeter}}
+##done {f OptionMenu OptMenu.tcl }
+##done {f PopupMenu PopMenu.tcl }
+## {f Select Select.tcl }
+## {f StdButtonBox StdBBox.tcl }
+## }
##
stypes = {}
stypes['widget'] = ['Balloon', 'Button Box', 'Combo Box', 'Control',
'Directory List', 'Directory Tree',
- 'Notebook', 'Option Menu', 'Popup Menu', 'Paned Window',
- 'ScrolledHList (1)', 'ScrolledHList (2)', 'Tree (dynamic)']
+ 'Notebook', 'Option Menu', 'Popup Menu', 'Paned Window',
+ 'ScrolledHList (1)', 'ScrolledHList (2)', 'Tree (dynamic)']
stypes['image'] = ['Compound Image']
def MkSample(nb, name):
@@ -922,15 +922,15 @@ def MkSample(nb, name):
view['command'] = lambda args=0, w=w,slb=slb,stext=stext,run=run,view=view: Sample_Action(w, slb, stext, run, view, 'view')
for type in ['widget', 'image']:
- if type != 'widget':
- x = Tix.Frame(slb.hlist, bd=2, height=2, width=150,
- relief=Tix.SUNKEN, bg=slb.hlist['bg'])
- slb.hlist.add_child(itemtype=Tix.WINDOW, window=x, state='disabled')
- x = slb.hlist.add_child(itemtype=Tix.TEXT, state='disabled',
- text=comments[type])
- for key in stypes[type]:
- slb.hlist.add_child(x, itemtype=Tix.TEXT, data=key,
- text=key)
+ if type != 'widget':
+ x = Tix.Frame(slb.hlist, bd=2, height=2, width=150,
+ relief=Tix.SUNKEN, bg=slb.hlist['bg'])
+ slb.hlist.add_child(itemtype=Tix.WINDOW, window=x, state='disabled')
+ x = slb.hlist.add_child(itemtype=Tix.TEXT, state='disabled',
+ text=comments[type])
+ for key in stypes[type]:
+ slb.hlist.add_child(x, itemtype=Tix.TEXT, data=key,
+ text=key)
slb.hlist.selection_clear()
run['state'] = 'disabled'
@@ -942,11 +942,11 @@ def Sample_Action(w, slb, stext, run, view, action):
hlist = slb.hlist
anchor = hlist.info_anchor()
if not anchor:
- run['state'] = 'disabled'
- view['state'] = 'disabled'
+ run['state'] = 'disabled'
+ view['state'] = 'disabled'
elif not hlist.info_parent(anchor):
- # a comment
- return
+ # a comment
+ return
run['state'] = 'normal'
view['state'] = 'normal'
@@ -955,17 +955,17 @@ def Sample_Action(w, slb, stext, run, view, action):
prog = samples[key]
if action == 'run':
- exec('import ' + prog)
- w = Tix.Toplevel()
- w.title(title)
- rtn = eval(prog + '.RunSample')
- rtn(w)
+ exec('import ' + prog)
+ w = Tix.Toplevel()
+ w.title(title)
+ rtn = eval(prog + '.RunSample')
+ rtn(w)
elif action == 'view':
- w = Tix.Toplevel()
- w.title('Source view: ' + title)
- LoadFile(w, demo.dir + '/samples/' + prog + '.py')
+ w = Tix.Toplevel()
+ w.title('Source view: ' + title)
+ LoadFile(w, demo.dir + '/samples/' + prog + '.py')
elif action == 'browse':
- ReadFile(stext.text, demo.dir + '/samples/' + prog + '.py')
+ ReadFile(stext.text, demo.dir + '/samples/' + prog + '.py')
def LoadFile(w, fname):
global root
@@ -989,16 +989,15 @@ def ReadFile(w, fname):
w.delete('0.0', Tix.END)
try:
- f = open(fname)
- lines = f.readlines()
- for s in lines:
- w.insert(Tix.END, s)
- f.close()
+ f = open(fname)
+ lines = f.readlines()
+ for s in lines:
+ w.insert(Tix.END, s)
+ f.close()
finally:
-# w.see('1.0')
- w['state'] = old_state
+# w.see('1.0')
+ w['state'] = old_state
if __name__ == '__main__':
root = Tix.Tk()
RunMain(root)
-
diff --git a/Demo/tkinter/guido/AttrDialog.py b/Demo/tkinter/guido/AttrDialog.py
index 4878cb5197..86333adc7d 100755
--- a/Demo/tkinter/guido/AttrDialog.py
+++ b/Demo/tkinter/guido/AttrDialog.py
@@ -16,437 +16,437 @@ from Tkinter import *
class Option:
- varclass = StringVar # May be overridden
-
- def __init__(self, dialog, option):
- self.dialog = dialog
- self.option = option
- self.master = dialog.top
- self.default, self.klass = dialog.options[option]
- self.var = self.varclass(self.master)
- self.frame = Frame(self.master)
- self.frame.pack(fill=X)
- self.label = Label(self.frame, text=(option + ":"))
- self.label.pack(side=LEFT)
- self.update()
- self.addoption()
-
- def refresh(self):
- self.dialog.refresh()
- self.update()
-
- def update(self):
- try:
- self.current = self.dialog.current[self.option]
- except KeyError:
- self.current = self.default
- self.var.set(self.current)
-
- def set(self, e=None): # Should be overridden
- pass
+ varclass = StringVar # May be overridden
+
+ def __init__(self, dialog, option):
+ self.dialog = dialog
+ self.option = option
+ self.master = dialog.top
+ self.default, self.klass = dialog.options[option]
+ self.var = self.varclass(self.master)
+ self.frame = Frame(self.master)
+ self.frame.pack(fill=X)
+ self.label = Label(self.frame, text=(option + ":"))
+ self.label.pack(side=LEFT)
+ self.update()
+ self.addoption()
+
+ def refresh(self):
+ self.dialog.refresh()
+ self.update()
+
+ def update(self):
+ try:
+ self.current = self.dialog.current[self.option]
+ except KeyError:
+ self.current = self.default
+ self.var.set(self.current)
+
+ def set(self, e=None): # Should be overridden
+ pass
class BooleanOption(Option):
- varclass = BooleanVar
+ varclass = BooleanVar
- def addoption(self):
- self.button = Checkbutton(self.frame,
- text='on/off',
- onvalue=1,
- offvalue=0,
- variable=self.var,
- relief=RAISED,
- borderwidth=2,
- command=self.set)
- self.button.pack(side=RIGHT)
+ def addoption(self):
+ self.button = Checkbutton(self.frame,
+ text='on/off',
+ onvalue=1,
+ offvalue=0,
+ variable=self.var,
+ relief=RAISED,
+ borderwidth=2,
+ command=self.set)
+ self.button.pack(side=RIGHT)
class EnumOption(Option):
- def addoption(self):
- self.button = Menubutton(self.frame,
- textvariable=self.var,
- relief=RAISED, borderwidth=2)
- self.button.pack(side=RIGHT)
- self.menu = Menu(self.button)
- self.button['menu'] = self.menu
- for v in self.dialog.classes[self.klass]:
- self.menu.add_radiobutton(
- label=v,
- variable=self.var,
- value=v,
- command=self.set)
+ def addoption(self):
+ self.button = Menubutton(self.frame,
+ textvariable=self.var,
+ relief=RAISED, borderwidth=2)
+ self.button.pack(side=RIGHT)
+ self.menu = Menu(self.button)
+ self.button['menu'] = self.menu
+ for v in self.dialog.classes[self.klass]:
+ self.menu.add_radiobutton(
+ label=v,
+ variable=self.var,
+ value=v,
+ command=self.set)
class StringOption(Option):
- def addoption(self):
- self.entry = Entry(self.frame,
- textvariable=self.var,
- width=10,
- relief=SUNKEN,
- borderwidth=2)
- self.entry.pack(side=RIGHT, fill=X, expand=1)
- self.entry.bind('<Return>', self.set)
+ def addoption(self):
+ self.entry = Entry(self.frame,
+ textvariable=self.var,
+ width=10,
+ relief=SUNKEN,
+ borderwidth=2)
+ self.entry.pack(side=RIGHT, fill=X, expand=1)
+ self.entry.bind('<Return>', self.set)
class ReadonlyOption(Option):
- def addoption(self):
- self.label = Label(self.frame, textvariable=self.var,
- anchor=E)
- self.label.pack(side=RIGHT)
+ def addoption(self):
+ self.label = Label(self.frame, textvariable=self.var,
+ anchor=E)
+ self.label.pack(side=RIGHT)
class Dialog:
- def __init__(self, master):
- self.master = master
- self.fixclasses()
- self.refresh()
- self.top = Toplevel(self.master)
- self.top.title(self.__class__.__name__)
- self.top.minsize(1, 1)
- self.addchoices()
-
- def refresh(self): pass # Must override
-
- def fixclasses(self): pass # May override
-
- def addchoices(self):
- self.choices = {}
- list = []
- for k, dc in self.options.items():
- list.append((k, dc))
- list.sort()
- for k, (d, c) in list:
- try:
- cl = self.classes[c]
- except KeyError:
- cl = 'unknown'
- if type(cl) == TupleType:
- cl = self.enumoption
- elif cl == 'boolean':
- cl = self.booleanoption
- elif cl == 'readonly':
- cl = self.readonlyoption
- else:
- cl = self.stringoption
- self.choices[k] = cl(self, k)
-
- # Must override:
- options = {}
- classes = {}
-
- # May override:
- booleanoption = BooleanOption
- stringoption = StringOption
- enumoption = EnumOption
- readonlyoption = ReadonlyOption
+ def __init__(self, master):
+ self.master = master
+ self.fixclasses()
+ self.refresh()
+ self.top = Toplevel(self.master)
+ self.top.title(self.__class__.__name__)
+ self.top.minsize(1, 1)
+ self.addchoices()
+
+ def refresh(self): pass # Must override
+
+ def fixclasses(self): pass # May override
+
+ def addchoices(self):
+ self.choices = {}
+ list = []
+ for k, dc in self.options.items():
+ list.append((k, dc))
+ list.sort()
+ for k, (d, c) in list:
+ try:
+ cl = self.classes[c]
+ except KeyError:
+ cl = 'unknown'
+ if type(cl) == TupleType:
+ cl = self.enumoption
+ elif cl == 'boolean':
+ cl = self.booleanoption
+ elif cl == 'readonly':
+ cl = self.readonlyoption
+ else:
+ cl = self.stringoption
+ self.choices[k] = cl(self, k)
+
+ # Must override:
+ options = {}
+ classes = {}
+
+ # May override:
+ booleanoption = BooleanOption
+ stringoption = StringOption
+ enumoption = EnumOption
+ readonlyoption = ReadonlyOption
class PackDialog(Dialog):
- def __init__(self, widget):
- self.widget = widget
- Dialog.__init__(self, widget)
-
- def refresh(self):
- self.current = self.widget.info()
- self.current['.class'] = self.widget.winfo_class()
- self.current['.name'] = self.widget._w
-
- class packoption: # Mix-in class
- def set(self, e=None):
- self.current = self.var.get()
- try:
- apply(self.dialog.widget.pack, (),
- {self.option: self.current})
- except TclError, msg:
- print msg
- self.refresh()
-
- class booleanoption(packoption, BooleanOption): pass
- class enumoption(packoption, EnumOption): pass
- class stringoption(packoption, StringOption): pass
- class readonlyoption(packoption, ReadonlyOption): pass
-
- options = {
- '.class': (None, 'Class'),
- '.name': (None, 'Name'),
- 'after': (None, 'Widget'),
- 'anchor': ('center', 'Anchor'),
- 'before': (None, 'Widget'),
- 'expand': ('no', 'Boolean'),
- 'fill': ('none', 'Fill'),
- 'in': (None, 'Widget'),
- 'ipadx': (0, 'Pad'),
- 'ipady': (0, 'Pad'),
- 'padx': (0, 'Pad'),
- 'pady': (0, 'Pad'),
- 'side': ('top', 'Side'),
- }
-
- classes = {
- 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER),
- 'Boolean': 'boolean',
- 'Class': 'readonly',
- 'Expand': 'boolean',
- 'Fill': (NONE, X, Y, BOTH),
- 'Name': 'readonly',
- 'Pad': 'pixel',
- 'Side': (TOP, RIGHT, BOTTOM, LEFT),
- 'Widget': 'readonly',
- }
+ def __init__(self, widget):
+ self.widget = widget
+ Dialog.__init__(self, widget)
+
+ def refresh(self):
+ self.current = self.widget.info()
+ self.current['.class'] = self.widget.winfo_class()
+ self.current['.name'] = self.widget._w
+
+ class packoption: # Mix-in class
+ def set(self, e=None):
+ self.current = self.var.get()
+ try:
+ apply(self.dialog.widget.pack, (),
+ {self.option: self.current})
+ except TclError, msg:
+ print msg
+ self.refresh()
+
+ class booleanoption(packoption, BooleanOption): pass
+ class enumoption(packoption, EnumOption): pass
+ class stringoption(packoption, StringOption): pass
+ class readonlyoption(packoption, ReadonlyOption): pass
+
+ options = {
+ '.class': (None, 'Class'),
+ '.name': (None, 'Name'),
+ 'after': (None, 'Widget'),
+ 'anchor': ('center', 'Anchor'),
+ 'before': (None, 'Widget'),
+ 'expand': ('no', 'Boolean'),
+ 'fill': ('none', 'Fill'),
+ 'in': (None, 'Widget'),
+ 'ipadx': (0, 'Pad'),
+ 'ipady': (0, 'Pad'),
+ 'padx': (0, 'Pad'),
+ 'pady': (0, 'Pad'),
+ 'side': ('top', 'Side'),
+ }
+
+ classes = {
+ 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER),
+ 'Boolean': 'boolean',
+ 'Class': 'readonly',
+ 'Expand': 'boolean',
+ 'Fill': (NONE, X, Y, BOTH),
+ 'Name': 'readonly',
+ 'Pad': 'pixel',
+ 'Side': (TOP, RIGHT, BOTTOM, LEFT),
+ 'Widget': 'readonly',
+ }
class RemotePackDialog(PackDialog):
- def __init__(self, master, app, widget):
- self.master = master
- self.app = app
- self.widget = widget
- self.refresh()
- self.top = Toplevel(self.master)
- self.top.title(self.app + ' PackDialog')
- self.top.minsize(1, 1)
- self.addchoices()
-
- def refresh(self):
- try:
- words = self.master.tk.splitlist(
- self.master.send(self.app,
- 'pack',
- 'info',
- self.widget))
- except TclError, msg:
- print msg
- return
- dict = {}
- for i in range(0, len(words), 2):
- key = words[i][1:]
- value = words[i+1]
- dict[key] = value
- dict['.class'] = self.master.send(self.app,
- 'winfo',
- 'class',
- self.widget)
- dict['.name'] = self.widget
- self.current = dict
-
- class remotepackoption: # Mix-in class
- def set(self, e=None):
- self.current = self.var.get()
- try:
- self.dialog.master.send(
- self.dialog.app,
- 'pack',
- 'config',
- self.dialog.widget,
- '-'+self.option,
- self.dialog.master.tk.merge(
- self.current))
- except TclError, msg:
- print msg
- self.refresh()
-
- class booleanoption(remotepackoption, BooleanOption): pass
- class enumoption(remotepackoption, EnumOption): pass
- class stringoption(remotepackoption, StringOption): pass
- class readonlyoption(remotepackoption, ReadonlyOption): pass
+ def __init__(self, master, app, widget):
+ self.master = master
+ self.app = app
+ self.widget = widget
+ self.refresh()
+ self.top = Toplevel(self.master)
+ self.top.title(self.app + ' PackDialog')
+ self.top.minsize(1, 1)
+ self.addchoices()
+
+ def refresh(self):
+ try:
+ words = self.master.tk.splitlist(
+ self.master.send(self.app,
+ 'pack',
+ 'info',
+ self.widget))
+ except TclError, msg:
+ print msg
+ return
+ dict = {}
+ for i in range(0, len(words), 2):
+ key = words[i][1:]
+ value = words[i+1]
+ dict[key] = value
+ dict['.class'] = self.master.send(self.app,
+ 'winfo',
+ 'class',
+ self.widget)
+ dict['.name'] = self.widget
+ self.current = dict
+
+ class remotepackoption: # Mix-in class
+ def set(self, e=None):
+ self.current = self.var.get()
+ try:
+ self.dialog.master.send(
+ self.dialog.app,
+ 'pack',
+ 'config',
+ self.dialog.widget,
+ '-'+self.option,
+ self.dialog.master.tk.merge(
+ self.current))
+ except TclError, msg:
+ print msg
+ self.refresh()
+
+ class booleanoption(remotepackoption, BooleanOption): pass
+ class enumoption(remotepackoption, EnumOption): pass
+ class stringoption(remotepackoption, StringOption): pass
+ class readonlyoption(remotepackoption, ReadonlyOption): pass
class WidgetDialog(Dialog):
- def __init__(self, widget):
- self.widget = widget
- self.klass = widget.winfo_class()
- Dialog.__init__(self, widget)
-
- def fixclasses(self):
- if self.addclasses.has_key(self.klass):
- classes = {}
- for c in (self.classes,
- self.addclasses[self.klass]):
- for k in c.keys():
- classes[k] = c[k]
- self.classes = classes
-
- def refresh(self):
- self.configuration = self.widget.config()
- self.update()
- self.current['.class'] = self.widget.winfo_class()
- self.current['.name'] = self.widget._w
-
- def update(self):
- self.current = {}
- self.options = {}
- for k, v in self.configuration.items():
- if len(v) > 4:
- self.current[k] = v[4]
- self.options[k] = v[3], v[2] # default, klass
- self.options['.class'] = (None, 'Class')
- self.options['.name'] = (None, 'Name')
-
- class widgetoption: # Mix-in class
- def set(self, e=None):
- self.current = self.var.get()
- try:
- self.dialog.widget[self.option] = self.current
- except TclError, msg:
- print msg
- self.refresh()
-
- class booleanoption(widgetoption, BooleanOption): pass
- class enumoption(widgetoption, EnumOption): pass
- class stringoption(widgetoption, StringOption): pass
- class readonlyoption(widgetoption, ReadonlyOption): pass
-
- # Universal classes
- classes = {
- 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER),
- 'Aspect': 'integer',
- 'Background': 'color',
- 'Bitmap': 'bitmap',
- 'BorderWidth': 'pixel',
- 'Class': 'readonly',
- 'CloseEnough': 'double',
- 'Command': 'command',
- 'Confine': 'boolean',
- 'Cursor': 'cursor',
- 'CursorWidth': 'pixel',
- 'DisabledForeground': 'color',
- 'ExportSelection': 'boolean',
- 'Font': 'font',
- 'Foreground': 'color',
- 'From': 'integer',
- 'Geometry': 'geometry',
- 'Height': 'pixel',
- 'InsertWidth': 'time',
- 'Justify': (LEFT, CENTER, RIGHT),
- 'Label': 'string',
- 'Length': 'pixel',
- 'MenuName': 'widget',
- 'Name': 'readonly',
- 'OffTime': 'time',
- 'OnTime': 'time',
- 'Orient': (HORIZONTAL, VERTICAL),
- 'Pad': 'pixel',
- 'Relief': (RAISED, SUNKEN, FLAT, RIDGE, GROOVE),
- 'RepeatDelay': 'time',
- 'RepeatInterval': 'time',
- 'ScrollCommand': 'command',
- 'ScrollIncrement': 'pixel',
- 'ScrollRegion': 'rectangle',
- 'ShowValue': 'boolean',
- 'SetGrid': 'boolean',
- 'Sliderforeground': 'color',
- 'SliderLength': 'pixel',
- 'Text': 'string',
- 'TickInterval': 'integer',
- 'To': 'integer',
- 'Underline': 'index',
- 'Variable': 'variable',
- 'Value': 'string',
- 'Width': 'pixel',
- 'Wrap': (NONE, CHAR, WORD),
- }
-
- # Classes that (may) differ per widget type
- _tristate = {'State': (NORMAL, ACTIVE, DISABLED)}
- _bistate = {'State': (NORMAL, DISABLED)}
- addclasses = {
- 'Button': _tristate,
- 'Radiobutton': _tristate,
- 'Checkbutton': _tristate,
- 'Entry': _bistate,
- 'Text': _bistate,
- 'Menubutton': _tristate,
- 'Slider': _bistate,
- }
+ def __init__(self, widget):
+ self.widget = widget
+ self.klass = widget.winfo_class()
+ Dialog.__init__(self, widget)
+
+ def fixclasses(self):
+ if self.addclasses.has_key(self.klass):
+ classes = {}
+ for c in (self.classes,
+ self.addclasses[self.klass]):
+ for k in c.keys():
+ classes[k] = c[k]
+ self.classes = classes
+
+ def refresh(self):
+ self.configuration = self.widget.config()
+ self.update()
+ self.current['.class'] = self.widget.winfo_class()
+ self.current['.name'] = self.widget._w
+
+ def update(self):
+ self.current = {}
+ self.options = {}
+ for k, v in self.configuration.items():
+ if len(v) > 4:
+ self.current[k] = v[4]
+ self.options[k] = v[3], v[2] # default, klass
+ self.options['.class'] = (None, 'Class')
+ self.options['.name'] = (None, 'Name')
+
+ class widgetoption: # Mix-in class
+ def set(self, e=None):
+ self.current = self.var.get()
+ try:
+ self.dialog.widget[self.option] = self.current
+ except TclError, msg:
+ print msg
+ self.refresh()
+
+ class booleanoption(widgetoption, BooleanOption): pass
+ class enumoption(widgetoption, EnumOption): pass
+ class stringoption(widgetoption, StringOption): pass
+ class readonlyoption(widgetoption, ReadonlyOption): pass
+
+ # Universal classes
+ classes = {
+ 'Anchor': (N, NE, E, SE, S, SW, W, NW, CENTER),
+ 'Aspect': 'integer',
+ 'Background': 'color',
+ 'Bitmap': 'bitmap',
+ 'BorderWidth': 'pixel',
+ 'Class': 'readonly',
+ 'CloseEnough': 'double',
+ 'Command': 'command',
+ 'Confine': 'boolean',
+ 'Cursor': 'cursor',
+ 'CursorWidth': 'pixel',
+ 'DisabledForeground': 'color',
+ 'ExportSelection': 'boolean',
+ 'Font': 'font',
+ 'Foreground': 'color',
+ 'From': 'integer',
+ 'Geometry': 'geometry',
+ 'Height': 'pixel',
+ 'InsertWidth': 'time',
+ 'Justify': (LEFT, CENTER, RIGHT),
+ 'Label': 'string',
+ 'Length': 'pixel',
+ 'MenuName': 'widget',
+ 'Name': 'readonly',
+ 'OffTime': 'time',
+ 'OnTime': 'time',
+ 'Orient': (HORIZONTAL, VERTICAL),
+ 'Pad': 'pixel',
+ 'Relief': (RAISED, SUNKEN, FLAT, RIDGE, GROOVE),
+ 'RepeatDelay': 'time',
+ 'RepeatInterval': 'time',
+ 'ScrollCommand': 'command',
+ 'ScrollIncrement': 'pixel',
+ 'ScrollRegion': 'rectangle',
+ 'ShowValue': 'boolean',
+ 'SetGrid': 'boolean',
+ 'Sliderforeground': 'color',
+ 'SliderLength': 'pixel',
+ 'Text': 'string',
+ 'TickInterval': 'integer',
+ 'To': 'integer',
+ 'Underline': 'index',
+ 'Variable': 'variable',
+ 'Value': 'string',
+ 'Width': 'pixel',
+ 'Wrap': (NONE, CHAR, WORD),
+ }
+
+ # Classes that (may) differ per widget type
+ _tristate = {'State': (NORMAL, ACTIVE, DISABLED)}
+ _bistate = {'State': (NORMAL, DISABLED)}
+ addclasses = {
+ 'Button': _tristate,
+ 'Radiobutton': _tristate,
+ 'Checkbutton': _tristate,
+ 'Entry': _bistate,
+ 'Text': _bistate,
+ 'Menubutton': _tristate,
+ 'Slider': _bistate,
+ }
class RemoteWidgetDialog(WidgetDialog):
- def __init__(self, master, app, widget):
- self.app = app
- self.widget = widget
- self.klass = master.send(self.app,
- 'winfo',
- 'class',
- self.widget)
- Dialog.__init__(self, master)
-
- def refresh(self):
- try:
- items = self.master.tk.splitlist(
- self.master.send(self.app,
- self.widget,
- 'config'))
- except TclError, msg:
- print msg
- return
- dict = {}
- for item in items:
- words = self.master.tk.splitlist(item)
- key = words[0][1:]
- value = (key,) + words[1:]
- dict[key] = value
- self.configuration = dict
- self.update()
- self.current['.class'] = self.klass
- self.current['.name'] = self.widget
-
- class remotewidgetoption: # Mix-in class
- def set(self, e=None):
- self.current = self.var.get()
- try:
- self.dialog.master.send(
- self.dialog.app,
- self.dialog.widget,
- 'config',
- '-'+self.option,
- self.current)
- except TclError, msg:
- print msg
- self.refresh()
-
- class booleanoption(remotewidgetoption, BooleanOption): pass
- class enumoption(remotewidgetoption, EnumOption): pass
- class stringoption(remotewidgetoption, StringOption): pass
- class readonlyoption(remotewidgetoption, ReadonlyOption): pass
+ def __init__(self, master, app, widget):
+ self.app = app
+ self.widget = widget
+ self.klass = master.send(self.app,
+ 'winfo',
+ 'class',
+ self.widget)
+ Dialog.__init__(self, master)
+
+ def refresh(self):
+ try:
+ items = self.master.tk.splitlist(
+ self.master.send(self.app,
+ self.widget,
+ 'config'))
+ except TclError, msg:
+ print msg
+ return
+ dict = {}
+ for item in items:
+ words = self.master.tk.splitlist(item)
+ key = words[0][1:]
+ value = (key,) + words[1:]
+ dict[key] = value
+ self.configuration = dict
+ self.update()
+ self.current['.class'] = self.klass
+ self.current['.name'] = self.widget
+
+ class remotewidgetoption: # Mix-in class
+ def set(self, e=None):
+ self.current = self.var.get()
+ try:
+ self.dialog.master.send(
+ self.dialog.app,
+ self.dialog.widget,
+ 'config',
+ '-'+self.option,
+ self.current)
+ except TclError, msg:
+ print msg
+ self.refresh()
+
+ class booleanoption(remotewidgetoption, BooleanOption): pass
+ class enumoption(remotewidgetoption, EnumOption): pass
+ class stringoption(remotewidgetoption, StringOption): pass
+ class readonlyoption(remotewidgetoption, ReadonlyOption): pass
def test():
- import sys
- root = Tk()
- root.minsize(1, 1)
- if sys.argv[1:]:
- remotetest(root, sys.argv[1])
- else:
- frame = Frame(root, name='frame')
- frame.pack(expand=1, fill=BOTH)
- button = Button(frame, name='button', text='button')
- button.pack(expand=1)
- canvas = Canvas(frame, name='canvas')
- canvas.pack()
- fpd = PackDialog(frame)
- fwd = WidgetDialog(frame)
- bpd = PackDialog(button)
- bwd = WidgetDialog(button)
- cpd = PackDialog(canvas)
- cwd = WidgetDialog(canvas)
- root.mainloop()
+ import sys
+ root = Tk()
+ root.minsize(1, 1)
+ if sys.argv[1:]:
+ remotetest(root, sys.argv[1])
+ else:
+ frame = Frame(root, name='frame')
+ frame.pack(expand=1, fill=BOTH)
+ button = Button(frame, name='button', text='button')
+ button.pack(expand=1)
+ canvas = Canvas(frame, name='canvas')
+ canvas.pack()
+ fpd = PackDialog(frame)
+ fwd = WidgetDialog(frame)
+ bpd = PackDialog(button)
+ bwd = WidgetDialog(button)
+ cpd = PackDialog(canvas)
+ cwd = WidgetDialog(canvas)
+ root.mainloop()
def remotetest(root, app):
- from listtree import listtree
- list = listtree(root, app)
- list.bind('<Any-Double-1>', opendialogs)
- list.app = app # Pass it on to handler
+ from listtree import listtree
+ list = listtree(root, app)
+ list.bind('<Any-Double-1>', opendialogs)
+ list.app = app # Pass it on to handler
def opendialogs(e):
- import string
- list = e.widget
- sel = list.curselection()
- for i in sel:
- item = list.get(i)
- widget = string.split(item)[0]
- RemoteWidgetDialog(list, list.app, widget)
- if widget == '.': continue
- try:
- RemotePackDialog(list, list.app, widget)
- except TclError, msg:
- print msg
+ import string
+ list = e.widget
+ sel = list.curselection()
+ for i in sel:
+ item = list.get(i)
+ widget = string.split(item)[0]
+ RemoteWidgetDialog(list, list.app, widget)
+ if widget == '.': continue
+ try:
+ RemotePackDialog(list, list.app, widget)
+ except TclError, msg:
+ print msg
test()
diff --git a/Demo/tkinter/guido/ManPage.py b/Demo/tkinter/guido/ManPage.py
index ccd21b4f7e..7d6fe00230 100755
--- a/Demo/tkinter/guido/ManPage.py
+++ b/Demo/tkinter/guido/ManPage.py
@@ -12,173 +12,173 @@ ITALICFONT = '*-Courier-Medium-O-Normal-*-120-*'
# XXX Recognizing footers is system dependent
# (This one works for IRIX 5.2 and Solaris 2.2)
footerprog = regex.compile(
- '^ Page [1-9][0-9]*[ \t]+\|^.*Last change:.*[1-9][0-9]*\n')
+ '^ Page [1-9][0-9]*[ \t]+\|^.*Last change:.*[1-9][0-9]*\n')
emptyprog = regex.compile('^[ \t]*\n')
ulprog = regex.compile('^[ \t]*[Xv!_][Xv!_ \t]*\n')
# Basic Man Page class -- does not disable editing
class EditableManPage(ScrolledText):
- # Initialize instance
- def __init__(self, master=None, **cnf):
- # Initialize base class
- apply(ScrolledText.__init__, (self, master), cnf)
-
- # Define tags for formatting styles
- self.tag_config('X', underline=1)
- self.tag_config('!', font=BOLDFONT)
- self.tag_config('_', font=ITALICFONT)
-
- # Set state to idle
- self.fp = None
- self.lineno = 0
-
- # Test whether we are busy parsing a file
- def busy(self):
- return self.fp != None
-
- # Ensure we're not busy
- def kill(self):
- if self.busy():
- self._endparser()
-
- # Parse a file, in the background
- def asyncparsefile(self, fp):
- self._startparser(fp)
- self.tk.createfilehandler(fp, _tkinter.READABLE,
- self._filehandler)
-
- parsefile = asyncparsefile # Alias
-
- # I/O handler used by background parsing
- def _filehandler(self, fp, mask):
- nextline = self.fp.readline()
- if not nextline:
- self._endparser()
- return
- self._parseline(nextline)
-
- # Parse a file, now (cannot be aborted)
- def syncparsefile(self, fp):
- from select import select
- def avail(fp=fp, tout=0.0, select=select):
- return select([fp], [], [], tout)[0]
- height = self.getint(self['height'])
- self._startparser(fp)
- while 1:
- nextline = fp.readline()
- if not nextline:
- break
- self._parseline(nextline)
- self._endparser()
-
- # Initialize parsing from a particular file -- must not be busy
- def _startparser(self, fp):
- if self.busy():
- raise RuntimeError, 'startparser: still busy'
- fp.fileno() # Test for file-ness
- self.fp = fp
- self.lineno = 0
- self.ok = 0
- self.empty = 0
- self.buffer = None
- savestate = self['state']
- self['state'] = NORMAL
- self.delete('1.0', END)
- self['state'] = savestate
-
- # End parsing -- must be busy, need not be at EOF
- def _endparser(self):
- if not self.busy():
- raise RuntimeError, 'endparser: not busy'
- if self.buffer:
- self._parseline('')
- try:
- self.tk.deletefilehandler(self.fp)
- except TclError, msg:
- pass
- self.fp.close()
- self.fp = None
- del self.ok, self.empty, self.buffer
-
- # Parse a single line
- def _parseline(self, nextline):
- if not self.buffer:
- # Save this line -- we need one line read-ahead
- self.buffer = nextline
- return
- if emptyprog.match(self.buffer) >= 0:
- # Buffered line was empty -- set a flag
- self.empty = 1
- self.buffer = nextline
- return
- textline = self.buffer
- if ulprog.match(nextline) >= 0:
- # Next line is properties for buffered line
- propline = nextline
- self.buffer = None
- else:
- # Next line is read-ahead
- propline = None
- self.buffer = nextline
- if not self.ok:
- # First non blank line after footer must be header
- # -- skip that too
- self.ok = 1
- self.empty = 0
- return
- if footerprog.match(textline) >= 0:
- # Footer -- start skipping until next non-blank line
- self.ok = 0
- self.empty = 0
- return
- savestate = self['state']
- self['state'] = NORMAL
- if TkVersion >= 4.0:
- self.mark_set('insert', 'end-1c')
- else:
- self.mark_set('insert', END)
- if self.empty:
- # One or more previous lines were empty
- # -- insert one blank line in the text
- self._insert_prop('\n')
- self.lineno = self.lineno + 1
- self.empty = 0
- if not propline:
- # No properties
- self._insert_prop(textline)
- else:
- # Search for properties
- p = ''
- j = 0
- for i in range(min(len(propline), len(textline))):
- if propline[i] != p:
- if j < i:
- self._insert_prop(textline[j:i], p)
- j = i
- p = propline[i]
- self._insert_prop(textline[j:])
- self.lineno = self.lineno + 1
- self['state'] = savestate
-
- # Insert a string at the end, with at most one property (tag)
- def _insert_prop(self, str, prop = ' '):
- here = self.index(AtInsert())
- self.insert(AtInsert(), str)
- if TkVersion <= 4.0:
- tags = self.tag_names(here)
- for tag in tags:
- self.tag_remove(tag, here, AtInsert())
- if prop != ' ':
- self.tag_add(prop, here, AtInsert())
+ # Initialize instance
+ def __init__(self, master=None, **cnf):
+ # Initialize base class
+ apply(ScrolledText.__init__, (self, master), cnf)
+
+ # Define tags for formatting styles
+ self.tag_config('X', underline=1)
+ self.tag_config('!', font=BOLDFONT)
+ self.tag_config('_', font=ITALICFONT)
+
+ # Set state to idle
+ self.fp = None
+ self.lineno = 0
+
+ # Test whether we are busy parsing a file
+ def busy(self):
+ return self.fp != None
+
+ # Ensure we're not busy
+ def kill(self):
+ if self.busy():
+ self._endparser()
+
+ # Parse a file, in the background
+ def asyncparsefile(self, fp):
+ self._startparser(fp)
+ self.tk.createfilehandler(fp, _tkinter.READABLE,
+ self._filehandler)
+
+ parsefile = asyncparsefile # Alias
+
+ # I/O handler used by background parsing
+ def _filehandler(self, fp, mask):
+ nextline = self.fp.readline()
+ if not nextline:
+ self._endparser()
+ return
+ self._parseline(nextline)
+
+ # Parse a file, now (cannot be aborted)
+ def syncparsefile(self, fp):
+ from select import select
+ def avail(fp=fp, tout=0.0, select=select):
+ return select([fp], [], [], tout)[0]
+ height = self.getint(self['height'])
+ self._startparser(fp)
+ while 1:
+ nextline = fp.readline()
+ if not nextline:
+ break
+ self._parseline(nextline)
+ self._endparser()
+
+ # Initialize parsing from a particular file -- must not be busy
+ def _startparser(self, fp):
+ if self.busy():
+ raise RuntimeError, 'startparser: still busy'
+ fp.fileno() # Test for file-ness
+ self.fp = fp
+ self.lineno = 0
+ self.ok = 0
+ self.empty = 0
+ self.buffer = None
+ savestate = self['state']
+ self['state'] = NORMAL
+ self.delete('1.0', END)
+ self['state'] = savestate
+
+ # End parsing -- must be busy, need not be at EOF
+ def _endparser(self):
+ if not self.busy():
+ raise RuntimeError, 'endparser: not busy'
+ if self.buffer:
+ self._parseline('')
+ try:
+ self.tk.deletefilehandler(self.fp)
+ except TclError, msg:
+ pass
+ self.fp.close()
+ self.fp = None
+ del self.ok, self.empty, self.buffer
+
+ # Parse a single line
+ def _parseline(self, nextline):
+ if not self.buffer:
+ # Save this line -- we need one line read-ahead
+ self.buffer = nextline
+ return
+ if emptyprog.match(self.buffer) >= 0:
+ # Buffered line was empty -- set a flag
+ self.empty = 1
+ self.buffer = nextline
+ return
+ textline = self.buffer
+ if ulprog.match(nextline) >= 0:
+ # Next line is properties for buffered line
+ propline = nextline
+ self.buffer = None
+ else:
+ # Next line is read-ahead
+ propline = None
+ self.buffer = nextline
+ if not self.ok:
+ # First non blank line after footer must be header
+ # -- skip that too
+ self.ok = 1
+ self.empty = 0
+ return
+ if footerprog.match(textline) >= 0:
+ # Footer -- start skipping until next non-blank line
+ self.ok = 0
+ self.empty = 0
+ return
+ savestate = self['state']
+ self['state'] = NORMAL
+ if TkVersion >= 4.0:
+ self.mark_set('insert', 'end-1c')
+ else:
+ self.mark_set('insert', END)
+ if self.empty:
+ # One or more previous lines were empty
+ # -- insert one blank line in the text
+ self._insert_prop('\n')
+ self.lineno = self.lineno + 1
+ self.empty = 0
+ if not propline:
+ # No properties
+ self._insert_prop(textline)
+ else:
+ # Search for properties
+ p = ''
+ j = 0
+ for i in range(min(len(propline), len(textline))):
+ if propline[i] != p:
+ if j < i:
+ self._insert_prop(textline[j:i], p)
+ j = i
+ p = propline[i]
+ self._insert_prop(textline[j:])
+ self.lineno = self.lineno + 1
+ self['state'] = savestate
+
+ # Insert a string at the end, with at most one property (tag)
+ def _insert_prop(self, str, prop = ' '):
+ here = self.index(AtInsert())
+ self.insert(AtInsert(), str)
+ if TkVersion <= 4.0:
+ tags = self.tag_names(here)
+ for tag in tags:
+ self.tag_remove(tag, here, AtInsert())
+ if prop != ' ':
+ self.tag_add(prop, here, AtInsert())
# Readonly Man Page class -- disables editing, otherwise the same
class ReadonlyManPage(EditableManPage):
- # Initialize instance
- def __init__(self, master=None, **cnf):
- cnf['state'] = DISABLED
- apply(EditableManPage.__init__, (self, master), cnf)
+ # Initialize instance
+ def __init__(self, master=None, **cnf):
+ cnf['state'] = DISABLED
+ apply(EditableManPage.__init__, (self, master), cnf)
# Alias
ManPage = ReadonlyManPage
@@ -187,34 +187,34 @@ ManPage = ReadonlyManPage
# usage: ManPage [manpage]; or ManPage [-f] file
# -f means that the file is nroff -man output run through ul -i
def test():
- import os
- import sys
- # XXX This directory may be different on your system
- MANDIR = '/usr/local/man/mann'
- DEFAULTPAGE = 'Tcl'
- formatted = 0
- if sys.argv[1:] and sys.argv[1] == '-f':
- formatted = 1
- del sys.argv[1]
- if sys.argv[1:]:
- name = sys.argv[1]
- else:
- name = DEFAULTPAGE
- if not formatted:
- if name[-2:-1] != '.':
- name = name + '.n'
- name = os.path.join(MANDIR, name)
- root = Tk()
- root.minsize(1, 1)
- manpage = ManPage(root, relief=SUNKEN, borderwidth=2)
- manpage.pack(expand=1, fill=BOTH)
- if formatted:
- fp = open(name, 'r')
- else:
- fp = os.popen('nroff -man %s | ul -i' % name, 'r')
- manpage.parsefile(fp)
- root.mainloop()
+ import os
+ import sys
+ # XXX This directory may be different on your system
+ MANDIR = '/usr/local/man/mann'
+ DEFAULTPAGE = 'Tcl'
+ formatted = 0
+ if sys.argv[1:] and sys.argv[1] == '-f':
+ formatted = 1
+ del sys.argv[1]
+ if sys.argv[1:]:
+ name = sys.argv[1]
+ else:
+ name = DEFAULTPAGE
+ if not formatted:
+ if name[-2:-1] != '.':
+ name = name + '.n'
+ name = os.path.join(MANDIR, name)
+ root = Tk()
+ root.minsize(1, 1)
+ manpage = ManPage(root, relief=SUNKEN, borderwidth=2)
+ manpage.pack(expand=1, fill=BOTH)
+ if formatted:
+ fp = open(name, 'r')
+ else:
+ fp = os.popen('nroff -man %s | ul -i' % name, 'r')
+ manpage.parsefile(fp)
+ root.mainloop()
# Run the test program when called as a script
if __name__ == '__main__':
- test()
+ test()
diff --git a/Demo/tkinter/guido/MimeViewer.py b/Demo/tkinter/guido/MimeViewer.py
index 2b98579810..7494425895 100755
--- a/Demo/tkinter/guido/MimeViewer.py
+++ b/Demo/tkinter/guido/MimeViewer.py
@@ -9,135 +9,135 @@ from Tkinter import *
from ScrolledText import ScrolledText
class MimeViewer:
- def __init__(self, parent, title, msg):
- self.title = title
- self.msg = msg
- self.frame = Frame(parent, {'relief': 'raised', 'bd': 2})
- self.frame.packing = {'expand': 0, 'fill': 'both'}
- self.button = Checkbutton(self.frame,
- {'text': title,
- 'command': self.toggle})
- self.button.pack({'anchor': 'w'})
- headertext = msg.getheadertext(
- lambda x: x != 'received' and x[:5] != 'x400-')
- height = countlines(headertext, 4)
- if height:
- self.htext = ScrolledText(self.frame,
- {'height': height,
- 'width': 80,
- 'wrap': 'none',
- 'relief': 'raised',
- 'bd': 2})
- self.htext.packing = {'expand': 1, 'fill': 'both',
- 'after': self.button}
- self.htext.insert('end', headertext)
- else:
- self.htext = Frame(self.frame,
- {'relief': 'raised', 'bd': 2})
- self.htext.packing = {'side': 'top',
- 'ipady': 2,
- 'fill': 'x',
- 'after': self.button}
- body = msg.getbody()
- if type(body) == StringType:
- self.pad = None
- height = countlines(body, 10)
- if height:
- self.btext = ScrolledText(self.frame,
- {'height': height,
- 'width': 80,
- 'wrap': 'none',
- 'relief': 'raised',
- 'bd': 2})
- self.btext.packing = {'expand': 1,
- 'fill': 'both'}
- self.btext.insert('end', body)
- else:
- self.btext = None
- self.parts = None
- else:
- self.pad = Frame(self.frame,
- {'relief': 'flat', 'bd': 2})
- self.pad.packing = {'side': 'left', 'ipadx': 10,
- 'fill': 'y', 'after': self.htext}
- self.parts = []
- for i in range(len(body)):
- p = MimeViewer(self.frame,
- '%s.%d' % (title, i+1),
- body[i])
- self.parts.append(p)
- self.btext = None
- self.collapsed = 1
- def pack(self):
- self.frame.pack(self.frame.packing)
- def destroy(self):
- self.frame.destroy()
- def show(self):
- if self.collapsed:
- self.button.invoke()
- def toggle(self):
- if self.collapsed:
- self.explode()
- else:
- self.collapse()
- def collapse(self):
- self.collapsed = 1
- for comp in self.htext, self.btext, self.pad:
- if comp:
- comp.forget()
- if self.parts:
- for part in self.parts:
- part.frame.forget()
- self.frame.pack({'expand': 0})
- def explode(self):
- self.collapsed = 0
- for comp in self.htext, self.btext, self.pad:
- if comp: comp.pack(comp.packing)
- if self.parts:
- for part in self.parts:
- part.pack()
- self.frame.pack({'expand': 1})
+ def __init__(self, parent, title, msg):
+ self.title = title
+ self.msg = msg
+ self.frame = Frame(parent, {'relief': 'raised', 'bd': 2})
+ self.frame.packing = {'expand': 0, 'fill': 'both'}
+ self.button = Checkbutton(self.frame,
+ {'text': title,
+ 'command': self.toggle})
+ self.button.pack({'anchor': 'w'})
+ headertext = msg.getheadertext(
+ lambda x: x != 'received' and x[:5] != 'x400-')
+ height = countlines(headertext, 4)
+ if height:
+ self.htext = ScrolledText(self.frame,
+ {'height': height,
+ 'width': 80,
+ 'wrap': 'none',
+ 'relief': 'raised',
+ 'bd': 2})
+ self.htext.packing = {'expand': 1, 'fill': 'both',
+ 'after': self.button}
+ self.htext.insert('end', headertext)
+ else:
+ self.htext = Frame(self.frame,
+ {'relief': 'raised', 'bd': 2})
+ self.htext.packing = {'side': 'top',
+ 'ipady': 2,
+ 'fill': 'x',
+ 'after': self.button}
+ body = msg.getbody()
+ if type(body) == StringType:
+ self.pad = None
+ height = countlines(body, 10)
+ if height:
+ self.btext = ScrolledText(self.frame,
+ {'height': height,
+ 'width': 80,
+ 'wrap': 'none',
+ 'relief': 'raised',
+ 'bd': 2})
+ self.btext.packing = {'expand': 1,
+ 'fill': 'both'}
+ self.btext.insert('end', body)
+ else:
+ self.btext = None
+ self.parts = None
+ else:
+ self.pad = Frame(self.frame,
+ {'relief': 'flat', 'bd': 2})
+ self.pad.packing = {'side': 'left', 'ipadx': 10,
+ 'fill': 'y', 'after': self.htext}
+ self.parts = []
+ for i in range(len(body)):
+ p = MimeViewer(self.frame,
+ '%s.%d' % (title, i+1),
+ body[i])
+ self.parts.append(p)
+ self.btext = None
+ self.collapsed = 1
+ def pack(self):
+ self.frame.pack(self.frame.packing)
+ def destroy(self):
+ self.frame.destroy()
+ def show(self):
+ if self.collapsed:
+ self.button.invoke()
+ def toggle(self):
+ if self.collapsed:
+ self.explode()
+ else:
+ self.collapse()
+ def collapse(self):
+ self.collapsed = 1
+ for comp in self.htext, self.btext, self.pad:
+ if comp:
+ comp.forget()
+ if self.parts:
+ for part in self.parts:
+ part.frame.forget()
+ self.frame.pack({'expand': 0})
+ def explode(self):
+ self.collapsed = 0
+ for comp in self.htext, self.btext, self.pad:
+ if comp: comp.pack(comp.packing)
+ if self.parts:
+ for part in self.parts:
+ part.pack()
+ self.frame.pack({'expand': 1})
def countlines(str, limit):
- i = 0
- n = 0
- while n < limit:
- i = string.find(str, '\n', i)
- if i < 0: break
- n = n+1
- i = i+1
- return n
+ i = 0
+ n = 0
+ while n < limit:
+ i = string.find(str, '\n', i)
+ if i < 0: break
+ n = n+1
+ i = i+1
+ return n
def main():
- import sys
- import getopt
- import mhlib
- opts, args = getopt.getopt(sys.argv[1:], '')
- for o, a in opts:
- pass
- message = None
- folder = 'inbox'
- for arg in args:
- if arg[:1] == '+':
- folder = arg[1:]
- else:
- message = string.atoi(arg)
+ import sys
+ import getopt
+ import mhlib
+ opts, args = getopt.getopt(sys.argv[1:], '')
+ for o, a in opts:
+ pass
+ message = None
+ folder = 'inbox'
+ for arg in args:
+ if arg[:1] == '+':
+ folder = arg[1:]
+ else:
+ message = string.atoi(arg)
- mh = mhlib.MH()
- f = mh.openfolder(folder)
- if not message:
- message = f.getcurrent()
- m = f.openmessage(message)
+ mh = mhlib.MH()
+ f = mh.openfolder(folder)
+ if not message:
+ message = f.getcurrent()
+ m = f.openmessage(message)
- root = Tk()
- tk = root.tk
+ root = Tk()
+ tk = root.tk
- top = MimeViewer(root, '+%s/%d' % (folder, message), m)
- top.pack()
- top.show()
+ top = MimeViewer(root, '+%s/%d' % (folder, message), m)
+ top.pack()
+ top.show()
- root.minsize(1, 1)
+ root.minsize(1, 1)
- tk.mainloop()
+ tk.mainloop()
if __name__ == '__main__': main()
diff --git a/Demo/tkinter/guido/ShellWindow.py b/Demo/tkinter/guido/ShellWindow.py
index 98fe30f70d..609101bc88 100755
--- a/Demo/tkinter/guido/ShellWindow.py
+++ b/Demo/tkinter/guido/ShellWindow.py
@@ -10,142 +10,142 @@ BUFSIZE = 512
class ShellWindow(ScrolledText):
- def __init__(self, master=None, shell=None, **cnf):
- if not shell:
- try:
- shell = os.environ['SHELL']
- except KeyError:
- shell = '/bin/sh'
- shell = shell + ' -i'
- args = string.split(shell)
- shell = args[0]
-
- apply(ScrolledText.__init__, (self, master), cnf)
- self.pos = '1.0'
- self.bind('<Return>', self.inputhandler)
- self.bind('<Control-c>', self.sigint)
- self.bind('<Control-t>', self.sigterm)
- self.bind('<Control-k>', self.sigkill)
- self.bind('<Control-d>', self.sendeof)
-
- self.pid, self.fromchild, self.tochild = spawn(shell, args)
- self.tk.createfilehandler(self.fromchild, READABLE,
- self.outputhandler)
-
- def outputhandler(self, file, mask):
- data = os.read(file, BUFSIZE)
- if not data:
- self.tk.deletefilehandler(file)
- pid, sts = os.waitpid(self.pid, 0)
- print 'pid', pid, 'status', sts
- self.pid = None
- detail = sts>>8
- cause = sts & 0xff
- if cause == 0:
- msg = "exit status %d" % detail
- else:
- msg = "killed by signal %d" % (cause & 0x7f)
- if cause & 0x80:
- msg = msg + " -- core dumped"
- Dialog(self.master,
- text=msg,
- title="Exit status",
- bitmap='warning',
- default=0,
- strings=('OK',))
- return
- self.insert(END, data)
- self.pos = self.index("end - 1 char")
- self.yview_pickplace(END)
-
- def inputhandler(self, *args):
- if not self.pid:
- self.no_process()
- return "break"
- self.insert(END, "\n")
- line = self.get(self.pos, "end - 1 char")
- self.pos = self.index(END)
- os.write(self.tochild, line)
- return "break"
-
- def sendeof(self, *args):
- if not self.pid:
- self.no_process()
- return "break"
- os.close(self.tochild)
- return "break"
-
- def sendsig(self, sig):
- if not self.pid:
- self.no_process()
- return "break"
- os.kill(self.pid, sig)
- return "break"
-
- def sigint(self, *args):
- return self.sendsig(signal.SIGINT)
-
- def sigquit(self, *args):
- return self.sendsig(signal.SIGQUIT)
-
- def sigterm(self, *args):
- return self.sendsig(signal.SIGTERM)
-
- def sigkill(self, *args):
- return self.sendsig(signal.SIGKILL)
-
- def no_process(self):
- Dialog(self.master,
- text="No active process",
- title="No process",
- bitmap='error',
- default=0,
- strings=('OK',))
-
-MAXFD = 100 # Max number of file descriptors (os.getdtablesize()???)
+ def __init__(self, master=None, shell=None, **cnf):
+ if not shell:
+ try:
+ shell = os.environ['SHELL']
+ except KeyError:
+ shell = '/bin/sh'
+ shell = shell + ' -i'
+ args = string.split(shell)
+ shell = args[0]
+
+ apply(ScrolledText.__init__, (self, master), cnf)
+ self.pos = '1.0'
+ self.bind('<Return>', self.inputhandler)
+ self.bind('<Control-c>', self.sigint)
+ self.bind('<Control-t>', self.sigterm)
+ self.bind('<Control-k>', self.sigkill)
+ self.bind('<Control-d>', self.sendeof)
+
+ self.pid, self.fromchild, self.tochild = spawn(shell, args)
+ self.tk.createfilehandler(self.fromchild, READABLE,
+ self.outputhandler)
+
+ def outputhandler(self, file, mask):
+ data = os.read(file, BUFSIZE)
+ if not data:
+ self.tk.deletefilehandler(file)
+ pid, sts = os.waitpid(self.pid, 0)
+ print 'pid', pid, 'status', sts
+ self.pid = None
+ detail = sts>>8
+ cause = sts & 0xff
+ if cause == 0:
+ msg = "exit status %d" % detail
+ else:
+ msg = "killed by signal %d" % (cause & 0x7f)
+ if cause & 0x80:
+ msg = msg + " -- core dumped"
+ Dialog(self.master,
+ text=msg,
+ title="Exit status",
+ bitmap='warning',
+ default=0,
+ strings=('OK',))
+ return
+ self.insert(END, data)
+ self.pos = self.index("end - 1 char")
+ self.yview_pickplace(END)
+
+ def inputhandler(self, *args):
+ if not self.pid:
+ self.no_process()
+ return "break"
+ self.insert(END, "\n")
+ line = self.get(self.pos, "end - 1 char")
+ self.pos = self.index(END)
+ os.write(self.tochild, line)
+ return "break"
+
+ def sendeof(self, *args):
+ if not self.pid:
+ self.no_process()
+ return "break"
+ os.close(self.tochild)
+ return "break"
+
+ def sendsig(self, sig):
+ if not self.pid:
+ self.no_process()
+ return "break"
+ os.kill(self.pid, sig)
+ return "break"
+
+ def sigint(self, *args):
+ return self.sendsig(signal.SIGINT)
+
+ def sigquit(self, *args):
+ return self.sendsig(signal.SIGQUIT)
+
+ def sigterm(self, *args):
+ return self.sendsig(signal.SIGTERM)
+
+ def sigkill(self, *args):
+ return self.sendsig(signal.SIGKILL)
+
+ def no_process(self):
+ Dialog(self.master,
+ text="No active process",
+ title="No process",
+ bitmap='error',
+ default=0,
+ strings=('OK',))
+
+MAXFD = 100 # Max number of file descriptors (os.getdtablesize()???)
def spawn(prog, args):
- p2cread, p2cwrite = os.pipe()
- c2pread, c2pwrite = os.pipe()
- pid = os.fork()
- if pid == 0:
- # Child
- for i in 0, 1, 2:
- try:
- os.close(i)
- except os.error:
- pass
- if os.dup(p2cread) <> 0:
- sys.stderr.write('popen2: bad read dup\n')
- if os.dup(c2pwrite) <> 1:
- sys.stderr.write('popen2: bad write dup\n')
- if os.dup(c2pwrite) <> 2:
- sys.stderr.write('popen2: bad write dup\n')
- for i in range(3, MAXFD):
- try:
- os.close(i)
- except:
- pass
- try:
- os.execvp(prog, args)
- finally:
- sys.stderr.write('execvp failed\n')
- os._exit(1)
- os.close(p2cread)
- os.close(c2pwrite)
- return pid, c2pread, p2cwrite
+ p2cread, p2cwrite = os.pipe()
+ c2pread, c2pwrite = os.pipe()
+ pid = os.fork()
+ if pid == 0:
+ # Child
+ for i in 0, 1, 2:
+ try:
+ os.close(i)
+ except os.error:
+ pass
+ if os.dup(p2cread) <> 0:
+ sys.stderr.write('popen2: bad read dup\n')
+ if os.dup(c2pwrite) <> 1:
+ sys.stderr.write('popen2: bad write dup\n')
+ if os.dup(c2pwrite) <> 2:
+ sys.stderr.write('popen2: bad write dup\n')
+ for i in range(3, MAXFD):
+ try:
+ os.close(i)
+ except:
+ pass
+ try:
+ os.execvp(prog, args)
+ finally:
+ sys.stderr.write('execvp failed\n')
+ os._exit(1)
+ os.close(p2cread)
+ os.close(c2pwrite)
+ return pid, c2pread, p2cwrite
def test():
- shell = string.join(sys.argv[1:])
- root = Tk()
- root.minsize(1, 1)
- if shell:
- w = ShellWindow(root, shell=shell)
- else:
- w = ShellWindow(root)
- w.pack(expand=1, fill=BOTH)
- w.focus_set()
- w.tk.mainloop()
+ shell = string.join(sys.argv[1:])
+ root = Tk()
+ root.minsize(1, 1)
+ if shell:
+ w = ShellWindow(root, shell=shell)
+ else:
+ w = ShellWindow(root)
+ w.pack(expand=1, fill=BOTH)
+ w.focus_set()
+ w.tk.mainloop()
if __name__ == '__main__':
- test()
+ test()
diff --git a/Demo/tkinter/guido/canvasevents.py b/Demo/tkinter/guido/canvasevents.py
index 60f409659b..74ed76f61b 100644
--- a/Demo/tkinter/guido/canvasevents.py
+++ b/Demo/tkinter/guido/canvasevents.py
@@ -9,7 +9,7 @@ from Canvas import Oval, Group, CanvasText
class Group(Group):
def bind(self, sequence=None, command=None):
- return self.canvas.tag_bind(self.id, sequence, command)
+ return self.canvas.tag_bind(self.id, sequence, command)
class Object:
@@ -33,45 +33,45 @@ class Object:
"""
def __init__(self, canvas, x=0, y=0, fill='red', text='object'):
- self.canvas = canvas
- self.x = x
- self.y = y
- self.pile = None
- self.group = Group(self.canvas)
- self.createitems(fill, text)
+ self.canvas = canvas
+ self.x = x
+ self.y = y
+ self.pile = None
+ self.group = Group(self.canvas)
+ self.createitems(fill, text)
def __str__(self):
- return str(self.group)
+ return str(self.group)
def createitems(self, fill, text):
- self.__oval = Oval(self.canvas,
- self.x-20, self.y-10, self.x+20, self.y+10,
- fill=fill, width=3)
- self.group.addtag_withtag(self.__oval)
- self.__text = CanvasText(self.canvas,
- self.x, self.y, text=text)
- self.group.addtag_withtag(self.__text)
+ self.__oval = Oval(self.canvas,
+ self.x-20, self.y-10, self.x+20, self.y+10,
+ fill=fill, width=3)
+ self.group.addtag_withtag(self.__oval)
+ self.__text = CanvasText(self.canvas,
+ self.x, self.y, text=text)
+ self.group.addtag_withtag(self.__text)
def moveby(self, dx, dy):
- if dx == dy == 0:
- return
- self.group.move(dx, dy)
- self.x = self.x + dx
- self.y = self.y + dy
+ if dx == dy == 0:
+ return
+ self.group.move(dx, dy)
+ self.x = self.x + dx
+ self.y = self.y + dy
def moveto(self, x, y):
- self.moveby(x - self.x, y - self.y)
+ self.moveby(x - self.x, y - self.y)
def transfer(self, pile):
- if self.pile:
- self.pile.delete(self)
- self.pile = None
- self.pile = pile
- if self.pile:
- self.pile.add(self)
+ if self.pile:
+ self.pile.delete(self)
+ self.pile = None
+ self.pile = pile
+ if self.pile:
+ self.pile.add(self)
def tkraise(self):
- self.group.tkraise()
+ self.group.tkraise()
class Bottom(Object):
@@ -79,10 +79,10 @@ class Bottom(Object):
"""An object to serve as the bottom of a pile."""
def createitems(self, *args):
- self.__oval = Oval(self.canvas,
- self.x-20, self.y-10, self.x+20, self.y+10,
- fill='gray', outline='')
- self.group.addtag_withtag(self.__oval)
+ self.__oval = Oval(self.canvas,
+ self.x-20, self.y-10, self.x+20, self.y+10,
+ fill='gray', outline='')
+ self.group.addtag_withtag(self.__oval)
class Pile:
@@ -90,86 +90,86 @@ class Pile:
"""A group of graphical objects."""
def __init__(self, canvas, x, y, tag=None):
- self.canvas = canvas
- self.x = x
- self.y = y
- self.objects = []
- self.bottom = Bottom(self.canvas, self.x, self.y)
- self.group = Group(self.canvas, tag=tag)
- self.group.addtag_withtag(self.bottom.group)
- self.bindhandlers()
+ self.canvas = canvas
+ self.x = x
+ self.y = y
+ self.objects = []
+ self.bottom = Bottom(self.canvas, self.x, self.y)
+ self.group = Group(self.canvas, tag=tag)
+ self.group.addtag_withtag(self.bottom.group)
+ self.bindhandlers()
def bindhandlers(self):
- self.group.bind('<1>', self.clickhandler)
- self.group.bind('<Double-1>', self.doubleclickhandler)
+ self.group.bind('<1>', self.clickhandler)
+ self.group.bind('<Double-1>', self.doubleclickhandler)
def add(self, object):
- self.objects.append(object)
- self.group.addtag_withtag(object.group)
- self.position(object)
+ self.objects.append(object)
+ self.group.addtag_withtag(object.group)
+ self.position(object)
def delete(self, object):
- object.group.dtag(self.group)
- self.objects.remove(object)
+ object.group.dtag(self.group)
+ self.objects.remove(object)
def position(self, object):
- object.tkraise()
- i = self.objects.index(object)
- object.moveto(self.x + i*4, self.y + i*8)
+ object.tkraise()
+ i = self.objects.index(object)
+ object.moveto(self.x + i*4, self.y + i*8)
def clickhandler(self, event):
- pass
+ pass
def doubleclickhandler(self, event):
- pass
+ pass
class MovingPile(Pile):
def bindhandlers(self):
- Pile.bindhandlers(self)
- self.group.bind('<B1-Motion>', self.motionhandler)
- self.group.bind('<ButtonRelease-1>', self.releasehandler)
+ Pile.bindhandlers(self)
+ self.group.bind('<B1-Motion>', self.motionhandler)
+ self.group.bind('<ButtonRelease-1>', self.releasehandler)
movethis = None
def clickhandler(self, event):
- tags = self.canvas.gettags('current')
- for i in range(len(self.objects)):
- o = self.objects[i]
- if o.group.tag in tags:
- break
- else:
- self.movethis = None
- return
- self.movethis = self.objects[i:]
- for o in self.movethis:
- o.tkraise()
- self.lastx = event.x
- self.lasty = event.y
+ tags = self.canvas.gettags('current')
+ for i in range(len(self.objects)):
+ o = self.objects[i]
+ if o.group.tag in tags:
+ break
+ else:
+ self.movethis = None
+ return
+ self.movethis = self.objects[i:]
+ for o in self.movethis:
+ o.tkraise()
+ self.lastx = event.x
+ self.lasty = event.y
doubleclickhandler = clickhandler
def motionhandler(self, event):
- if not self.movethis:
- return
- dx = event.x - self.lastx
- dy = event.y - self.lasty
- self.lastx = event.x
- self.lasty = event.y
- for o in self.movethis:
- o.moveby(dx, dy)
+ if not self.movethis:
+ return
+ dx = event.x - self.lastx
+ dy = event.y - self.lasty
+ self.lastx = event.x
+ self.lasty = event.y
+ for o in self.movethis:
+ o.moveby(dx, dy)
def releasehandler(self, event):
- objects = self.movethis
- if not objects:
- return
- self.movethis = None
- self.finishmove(objects)
+ objects = self.movethis
+ if not objects:
+ return
+ self.movethis = None
+ self.finishmove(objects)
def finishmove(self, objects):
- for o in objects:
- self.position(o)
+ for o in objects:
+ self.position(o)
class Pile1(MovingPile):
@@ -179,29 +179,29 @@ class Pile1(MovingPile):
tag = 'p1'
def __init__(self, demo):
- self.demo = demo
- MovingPile.__init__(self, self.demo.canvas, self.x, self.y, self.tag)
+ self.demo = demo
+ MovingPile.__init__(self, self.demo.canvas, self.x, self.y, self.tag)
def doubleclickhandler(self, event):
- try:
- o = self.objects[-1]
- except IndexError:
- return
- o.transfer(self.other())
- MovingPile.doubleclickhandler(self, event)
+ try:
+ o = self.objects[-1]
+ except IndexError:
+ return
+ o.transfer(self.other())
+ MovingPile.doubleclickhandler(self, event)
def other(self):
- return self.demo.p2
+ return self.demo.p2
def finishmove(self, objects):
- o = objects[0]
- p = self.other()
- x, y = o.x, o.y
- if (x-p.x)**2 + (y-p.y)**2 < (x-self.x)**2 + (y-self.y)**2:
- for o in objects:
- o.transfer(p)
- else:
- MovingPile.finishmove(self, objects)
+ o = objects[0]
+ p = self.other()
+ x, y = o.x, o.y
+ if (x-p.x)**2 + (y-p.y)**2 < (x-self.x)**2 + (y-self.y)**2:
+ for o in objects:
+ o.transfer(p)
+ else:
+ MovingPile.finishmove(self, objects)
class Pile2(Pile1):
@@ -210,26 +210,26 @@ class Pile2(Pile1):
tag = 'p2'
def other(self):
- return self.demo.p1
+ return self.demo.p1
class Demo:
def __init__(self, master):
- self.master = master
- self.canvas = Canvas(master,
- width=200, height=200,
- background='yellow',
- relief=SUNKEN, borderwidth=2)
- self.canvas.pack(expand=1, fill=BOTH)
- self.p1 = Pile1(self)
- self.p2 = Pile2(self)
- o1 = Object(self.canvas, fill='red', text='o1')
- o2 = Object(self.canvas, fill='green', text='o2')
- o3 = Object(self.canvas, fill='light blue', text='o3')
- o1.transfer(self.p1)
- o2.transfer(self.p1)
- o3.transfer(self.p2)
+ self.master = master
+ self.canvas = Canvas(master,
+ width=200, height=200,
+ background='yellow',
+ relief=SUNKEN, borderwidth=2)
+ self.canvas.pack(expand=1, fill=BOTH)
+ self.p1 = Pile1(self)
+ self.p2 = Pile2(self)
+ o1 = Object(self.canvas, fill='red', text='o1')
+ o2 = Object(self.canvas, fill='green', text='o2')
+ o3 = Object(self.canvas, fill='light blue', text='o3')
+ o1.transfer(self.p1)
+ o2.transfer(self.p1)
+ o3.transfer(self.p2)
# Main function, run when invoked as a stand-alone Python program.
diff --git a/Demo/tkinter/guido/dialog.py b/Demo/tkinter/guido/dialog.py
index 1f794ae22a..50d84b9a34 100755
--- a/Demo/tkinter/guido/dialog.py
+++ b/Demo/tkinter/guido/dialog.py
@@ -25,11 +25,11 @@ def dialog(master, title, text, bitmap, default, *args):
# 2. Fill the top part with the bitmap and message.
msg = Message(top, width='3i', text=text,
- font='-Adobe-Times-Medium-R-Normal-*-180-*')
+ font='-Adobe-Times-Medium-R-Normal-*-180-*')
msg.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m')
if bitmap:
- bm = Label(top, bitmap=bitmap)
- bm.pack(side=LEFT, padx='3m', pady='3m')
+ bm = Label(top, bitmap=bitmap)
+ bm.pack(side=LEFT, padx='3m', pady='3m')
# 3. Create a row of buttons at the bottom of the dialog.
@@ -37,27 +37,27 @@ def dialog(master, title, text, bitmap, default, *args):
buttons = []
i = 0
for but in args:
- b = Button(bot, text=but, command=lambda v=var,i=i: v.set(i))
- buttons.append(b)
- if i == default:
- bd = Frame(bot, relief=SUNKEN, borderwidth=1)
- bd.pack(side=LEFT, expand=1, padx='3m', pady='2m')
- b.lift()
- b.pack (in_=bd, side=LEFT,
- padx='2m', pady='2m', ipadx='2m', ipady='1m')
- else:
- b.pack (side=LEFT, expand=1,
- padx='3m', pady='3m', ipadx='2m', ipady='1m')
- i = i+1
+ b = Button(bot, text=but, command=lambda v=var,i=i: v.set(i))
+ buttons.append(b)
+ if i == default:
+ bd = Frame(bot, relief=SUNKEN, borderwidth=1)
+ bd.pack(side=LEFT, expand=1, padx='3m', pady='2m')
+ b.lift()
+ b.pack (in_=bd, side=LEFT,
+ padx='2m', pady='2m', ipadx='2m', ipady='1m')
+ else:
+ b.pack (side=LEFT, expand=1,
+ padx='3m', pady='3m', ipadx='2m', ipady='1m')
+ i = i+1
# 4. Set up a binding for <Return>, if there's a default,
# set a grab, and claim the focus too.
if default >= 0:
- w.bind('<Return>',
- lambda e, b=buttons[default], v=var, i=default:
- (b.flash(),
- v.set(i)))
+ w.bind('<Return>',
+ lambda e, b=buttons[default], v=var, i=default:
+ (b.flash(),
+ v.set(i)))
oldFocus = w.focus_get()
w.grab_set()
@@ -75,23 +75,23 @@ def dialog(master, title, text, bitmap, default, *args):
def go():
i = dialog(mainWidget,
- 'Not Responding',
- "The file server isn't responding right now; "
- "I'll keep trying.",
- '',
- -1,
- 'OK')
+ 'Not Responding',
+ "The file server isn't responding right now; "
+ "I'll keep trying.",
+ '',
+ -1,
+ 'OK')
print 'pressed button', i
i = dialog(mainWidget,
- 'File Modified',
- 'File "tcl.h" has been modified since '
- 'the last time it was saved. '
- 'Do you want to save it before exiting the application?',
- 'warning',
- 0,
- 'Save File',
- 'Discard Changes',
- 'Return To Editor')
+ 'File Modified',
+ 'File "tcl.h" has been modified since '
+ 'the last time it was saved. '
+ 'Do you want to save it before exiting the application?',
+ 'warning',
+ 0,
+ 'Save File',
+ 'Discard Changes',
+ 'Return To Editor')
print 'pressed button', i
def test():
diff --git a/Demo/tkinter/guido/electrons.py b/Demo/tkinter/guido/electrons.py
index 97dad2d733..fdc558f885 100755
--- a/Demo/tkinter/guido/electrons.py
+++ b/Demo/tkinter/guido/electrons.py
@@ -1,6 +1,6 @@
#! /usr/bin/env python
-# Simulate "electrons" migrating across the screen.
+# Simulate "electrons" migrating across the screen.
# An optional bitmap file in can be in the background.
#
# Usage: electrons [n [bitmapfile]]
@@ -18,74 +18,74 @@ import random
# The graphical interface
class Electrons:
- # Create our objects
- def __init__(self, n, bitmap = None):
- self.n = n
- self.tk = tk = Tk()
- self.canvas = c = Canvas(tk)
- c.pack()
- width, height = tk.getint(c['width']), tk.getint(c['height'])
-
- # Add background bitmap
- if bitmap:
- self.bitmap = c.create_bitmap(width/2, height/2,
- bitmap=bitmap,
- foreground='blue')
-
- self.pieces = []
- x1, y1, x2, y2 = 10,70,14,74
- for i in range(n):
- p = c.create_oval(x1, y1, x2, y2, fill='red')
- self.pieces.append(p)
- y1, y2 = y1 +2, y2 + 2
- self.tk.update()
-
- def random_move(self, n):
- c = self.canvas
- for p in self.pieces:
- x = random.choice(range(-2,4))
- y = random.choice(range(-3,4))
- c.move(p, x, y)
- self.tk.update()
-
- # Run -- allow 500 movemens
- def run(self):
- try:
- for i in range(500):
- self.random_move(self.n)
- except TclError:
- try:
- self.tk.destroy()
- except TclError:
- pass
+ # Create our objects
+ def __init__(self, n, bitmap = None):
+ self.n = n
+ self.tk = tk = Tk()
+ self.canvas = c = Canvas(tk)
+ c.pack()
+ width, height = tk.getint(c['width']), tk.getint(c['height'])
+
+ # Add background bitmap
+ if bitmap:
+ self.bitmap = c.create_bitmap(width/2, height/2,
+ bitmap=bitmap,
+ foreground='blue')
+
+ self.pieces = []
+ x1, y1, x2, y2 = 10,70,14,74
+ for i in range(n):
+ p = c.create_oval(x1, y1, x2, y2, fill='red')
+ self.pieces.append(p)
+ y1, y2 = y1 +2, y2 + 2
+ self.tk.update()
+
+ def random_move(self, n):
+ c = self.canvas
+ for p in self.pieces:
+ x = random.choice(range(-2,4))
+ y = random.choice(range(-3,4))
+ c.move(p, x, y)
+ self.tk.update()
+
+ # Run -- allow 500 movemens
+ def run(self):
+ try:
+ for i in range(500):
+ self.random_move(self.n)
+ except TclError:
+ try:
+ self.tk.destroy()
+ except TclError:
+ pass
# Main program
def main():
- import sys, string
+ import sys, string
- # First argument is number of electrons, default 30
- if sys.argv[1:]:
- n = string.atoi(sys.argv[1])
- else:
- n = 30
+ # First argument is number of electrons, default 30
+ if sys.argv[1:]:
+ n = string.atoi(sys.argv[1])
+ else:
+ n = 30
- # Second argument is bitmap file, default none
- if sys.argv[2:]:
- bitmap = sys.argv[2]
- # Reverse meaning of leading '@' compared to Tk
- if bitmap[0] == '@': bitmap = bitmap[1:]
- else: bitmap = '@' + bitmap
- else:
- bitmap = None
+ # Second argument is bitmap file, default none
+ if sys.argv[2:]:
+ bitmap = sys.argv[2]
+ # Reverse meaning of leading '@' compared to Tk
+ if bitmap[0] == '@': bitmap = bitmap[1:]
+ else: bitmap = '@' + bitmap
+ else:
+ bitmap = None
- # Create the graphical objects...
- h = Electrons(n, bitmap)
+ # Create the graphical objects...
+ h = Electrons(n, bitmap)
- # ...and run!
- h.run()
+ # ...and run!
+ h.run()
# Call main when run as script
if __name__ == '__main__':
- main()
+ main()
diff --git a/Demo/tkinter/guido/hanoi.py b/Demo/tkinter/guido/hanoi.py
index 9e566c4a30..078c24611f 100755
--- a/Demo/tkinter/guido/hanoi.py
+++ b/Demo/tkinter/guido/hanoi.py
@@ -16,139 +16,139 @@ from Tkinter import *
# Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c
# as temporary. For each move, call report()
def hanoi(n, a, b, c, report):
- if n <= 0: return
- hanoi(n-1, a, c, b, report)
- report(n, a, b)
- hanoi(n-1, c, b, a, report)
+ if n <= 0: return
+ hanoi(n-1, a, c, b, report)
+ report(n, a, b)
+ hanoi(n-1, c, b, a, report)
# The graphical interface
class Tkhanoi:
- # Create our objects
- def __init__(self, n, bitmap = None):
- self.n = n
- self.tk = tk = Tk()
- self.canvas = c = Canvas(tk)
- c.pack()
- width, height = tk.getint(c['width']), tk.getint(c['height'])
-
- # Add background bitmap
- if bitmap:
- self.bitmap = c.create_bitmap(width/2, height/2,
- bitmap=bitmap,
- foreground='blue')
-
- # Generate pegs
- pegwidth = 10
- pegheight = height/2
- pegdist = width/3
- x1, y1 = (pegdist-pegwidth)/2, height*1/3
- x2, y2 = x1+pegwidth, y1+pegheight
- self.pegs = []
- p = c.create_rectangle(x1, y1, x2, y2, fill='black')
- self.pegs.append(p)
- x1, x2 = x1+pegdist, x2+pegdist
- p = c.create_rectangle(x1, y1, x2, y2, fill='black')
- self.pegs.append(p)
- x1, x2 = x1+pegdist, x2+pegdist
- p = c.create_rectangle(x1, y1, x2, y2, fill='black')
- self.pegs.append(p)
- self.tk.update()
-
- # Generate pieces
- pieceheight = pegheight/16
- maxpiecewidth = pegdist*2/3
- minpiecewidth = 2*pegwidth
- self.pegstate = [[], [], []]
- self.pieces = {}
- x1, y1 = (pegdist-maxpiecewidth)/2, y2-pieceheight-2
- x2, y2 = x1+maxpiecewidth, y1+pieceheight
- dx = (maxpiecewidth-minpiecewidth) / (2*max(1, n-1))
- for i in range(n, 0, -1):
- p = c.create_rectangle(x1, y1, x2, y2, fill='red')
- self.pieces[i] = p
- self.pegstate[0].append(i)
- x1, x2 = x1 + dx, x2-dx
- y1, y2 = y1 - pieceheight-2, y2-pieceheight-2
- self.tk.update()
- self.tk.after(25)
-
- # Run -- never returns
- def run(self):
- while 1:
- hanoi(self.n, 0, 1, 2, self.report)
- hanoi(self.n, 1, 2, 0, self.report)
- hanoi(self.n, 2, 0, 1, self.report)
- hanoi(self.n, 0, 2, 1, self.report)
- hanoi(self.n, 2, 1, 0, self.report)
- hanoi(self.n, 1, 0, 2, self.report)
-
- # Reporting callback for the actual hanoi function
- def report(self, i, a, b):
- if self.pegstate[a][-1] != i: raise RuntimeError # Assertion
- del self.pegstate[a][-1]
- p = self.pieces[i]
- c = self.canvas
-
- # Lift the piece above peg a
- ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a])
- while 1:
- x1, y1, x2, y2 = c.bbox(p)
- if y2 < ay1: break
- c.move(p, 0, -1)
- self.tk.update()
-
- # Move it towards peg b
- bx1, by1, bx2, by2 = c.bbox(self.pegs[b])
- newcenter = (bx1+bx2)/2
- while 1:
- x1, y1, x2, y2 = c.bbox(p)
- center = (x1+x2)/2
- if center == newcenter: break
- if center > newcenter: c.move(p, -1, 0)
- else: c.move(p, 1, 0)
- self.tk.update()
-
- # Move it down on top of the previous piece
- pieceheight = y2-y1
- newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2
- while 1:
- x1, y1, x2, y2 = c.bbox(p)
- if y2 >= newbottom: break
- c.move(p, 0, 1)
- self.tk.update()
-
- # Update peg state
- self.pegstate[b].append(i)
+ # Create our objects
+ def __init__(self, n, bitmap = None):
+ self.n = n
+ self.tk = tk = Tk()
+ self.canvas = c = Canvas(tk)
+ c.pack()
+ width, height = tk.getint(c['width']), tk.getint(c['height'])
+
+ # Add background bitmap
+ if bitmap:
+ self.bitmap = c.create_bitmap(width/2, height/2,
+ bitmap=bitmap,
+ foreground='blue')
+
+ # Generate pegs
+ pegwidth = 10
+ pegheight = height/2
+ pegdist = width/3
+ x1, y1 = (pegdist-pegwidth)/2, height*1/3
+ x2, y2 = x1+pegwidth, y1+pegheight
+ self.pegs = []
+ p = c.create_rectangle(x1, y1, x2, y2, fill='black')
+ self.pegs.append(p)
+ x1, x2 = x1+pegdist, x2+pegdist
+ p = c.create_rectangle(x1, y1, x2, y2, fill='black')
+ self.pegs.append(p)
+ x1, x2 = x1+pegdist, x2+pegdist
+ p = c.create_rectangle(x1, y1, x2, y2, fill='black')
+ self.pegs.append(p)
+ self.tk.update()
+
+ # Generate pieces
+ pieceheight = pegheight/16
+ maxpiecewidth = pegdist*2/3
+ minpiecewidth = 2*pegwidth
+ self.pegstate = [[], [], []]
+ self.pieces = {}
+ x1, y1 = (pegdist-maxpiecewidth)/2, y2-pieceheight-2
+ x2, y2 = x1+maxpiecewidth, y1+pieceheight
+ dx = (maxpiecewidth-minpiecewidth) / (2*max(1, n-1))
+ for i in range(n, 0, -1):
+ p = c.create_rectangle(x1, y1, x2, y2, fill='red')
+ self.pieces[i] = p
+ self.pegstate[0].append(i)
+ x1, x2 = x1 + dx, x2-dx
+ y1, y2 = y1 - pieceheight-2, y2-pieceheight-2
+ self.tk.update()
+ self.tk.after(25)
+
+ # Run -- never returns
+ def run(self):
+ while 1:
+ hanoi(self.n, 0, 1, 2, self.report)
+ hanoi(self.n, 1, 2, 0, self.report)
+ hanoi(self.n, 2, 0, 1, self.report)
+ hanoi(self.n, 0, 2, 1, self.report)
+ hanoi(self.n, 2, 1, 0, self.report)
+ hanoi(self.n, 1, 0, 2, self.report)
+
+ # Reporting callback for the actual hanoi function
+ def report(self, i, a, b):
+ if self.pegstate[a][-1] != i: raise RuntimeError # Assertion
+ del self.pegstate[a][-1]
+ p = self.pieces[i]
+ c = self.canvas
+
+ # Lift the piece above peg a
+ ax1, ay1, ax2, ay2 = c.bbox(self.pegs[a])
+ while 1:
+ x1, y1, x2, y2 = c.bbox(p)
+ if y2 < ay1: break
+ c.move(p, 0, -1)
+ self.tk.update()
+
+ # Move it towards peg b
+ bx1, by1, bx2, by2 = c.bbox(self.pegs[b])
+ newcenter = (bx1+bx2)/2
+ while 1:
+ x1, y1, x2, y2 = c.bbox(p)
+ center = (x1+x2)/2
+ if center == newcenter: break
+ if center > newcenter: c.move(p, -1, 0)
+ else: c.move(p, 1, 0)
+ self.tk.update()
+
+ # Move it down on top of the previous piece
+ pieceheight = y2-y1
+ newbottom = by2 - pieceheight*len(self.pegstate[b]) - 2
+ while 1:
+ x1, y1, x2, y2 = c.bbox(p)
+ if y2 >= newbottom: break
+ c.move(p, 0, 1)
+ self.tk.update()
+
+ # Update peg state
+ self.pegstate[b].append(i)
# Main program
def main():
- import sys, string
+ import sys, string
- # First argument is number of pegs, default 4
- if sys.argv[1:]:
- n = string.atoi(sys.argv[1])
- else:
- n = 4
+ # First argument is number of pegs, default 4
+ if sys.argv[1:]:
+ n = string.atoi(sys.argv[1])
+ else:
+ n = 4
- # Second argument is bitmap file, default none
- if sys.argv[2:]:
- bitmap = sys.argv[2]
- # Reverse meaning of leading '@' compared to Tk
- if bitmap[0] == '@': bitmap = bitmap[1:]
- else: bitmap = '@' + bitmap
- else:
- bitmap = None
+ # Second argument is bitmap file, default none
+ if sys.argv[2:]:
+ bitmap = sys.argv[2]
+ # Reverse meaning of leading '@' compared to Tk
+ if bitmap[0] == '@': bitmap = bitmap[1:]
+ else: bitmap = '@' + bitmap
+ else:
+ bitmap = None
- # Create the graphical objects...
- h = Tkhanoi(n, bitmap)
+ # Create the graphical objects...
+ h = Tkhanoi(n, bitmap)
- # ...and run!
- h.run()
+ # ...and run!
+ h.run()
# Call main when run as script
if __name__ == '__main__':
- main()
+ main()
diff --git a/Demo/tkinter/guido/hello.py b/Demo/tkinter/guido/hello.py
index 237204fab8..358a7ecebd 100755
--- a/Demo/tkinter/guido/hello.py
+++ b/Demo/tkinter/guido/hello.py
@@ -4,14 +4,14 @@ import sys
from Tkinter import *
def main():
- root = Tk()
- button = Button(root)
- button['text'] = 'Hello, world'
- button['command'] = quit_callback # See below
- button.pack()
- root.mainloop()
+ root = Tk()
+ button = Button(root)
+ button['text'] = 'Hello, world'
+ button['command'] = quit_callback # See below
+ button.pack()
+ root.mainloop()
def quit_callback():
- sys.exit(0)
+ sys.exit(0)
main()
diff --git a/Demo/tkinter/guido/kill.py b/Demo/tkinter/guido/kill.py
index 577af8b8b8..e7df261213 100755
--- a/Demo/tkinter/guido/kill.py
+++ b/Demo/tkinter/guido/kill.py
@@ -8,92 +8,91 @@ import commands
import os
class BarButton(Menubutton):
- def __init__(self, master=None, **cnf):
- apply(Menubutton.__init__, (self, master), cnf)
- self.pack(side=LEFT)
- self.menu = Menu(self, name='menu')
- self['menu'] = self.menu
+ def __init__(self, master=None, **cnf):
+ apply(Menubutton.__init__, (self, master), cnf)
+ self.pack(side=LEFT)
+ self.menu = Menu(self, name='menu')
+ self['menu'] = self.menu
class Kill(Frame):
- # List of (name, option, pid_column)
- format_list = [('Default', '', 0),
- ('Long', '-l', 2),
- ('User', '-u', 1),
- ('Jobs', '-j', 1),
- ('Signal', '-s', 1),
- ('Memory', '-m', 0),
- ('VM', '-v', 0),
- ('Hex', '-X', 0)]
- def kill(self, selected):
- c = self.format_list[self.format.get()][2]
- pid = split(selected)[c]
- os.system('kill -9 ' + pid)
- self.do_update()
- def do_update(self):
- name, option, column = self.format_list[self.format.get()]
- s = commands.getoutput('ps -w ' + option)
- list = splitfields(s, '\n')
- self.header.set(list[0])
- del list[0]
- y = self.frame.vscroll.get()[0]
- self.frame.list.delete(0, AtEnd())
- for line in list:
- self.frame.list.insert(0, line)
- self.frame.list.yview(int(y))
- def do_motion(self, e):
- e.widget.select_clear(0, END)
- e.widget.select_set(e.widget.nearest(e.y))
- def do_leave(self, e):
- e.widget.select_clear(0, END)
- def do_1(self, e):
- self.kill(e.widget.get(e.widget.nearest(e.y)))
- def __init__(self, master=None, **cnf):
- Frame.__init__(self, master, cnf)
- self.pack(expand=1, fill=BOTH)
- self.bar = Frame(self, name='bar', relief=RAISED,
- borderwidth=2)
- self.bar.pack(fill=X)
- self.bar.file = BarButton(self.bar, text='File')
- self.bar.file.menu.add_command(
- label='Quit', command=self.quit)
- self.bar.view = BarButton(self.bar, text='View')
- self.format = IntVar(self)
- self.format.set(2)
- for num in range(len(self.format_list)):
- self.bar.view.menu.add_radiobutton(
- label=self.format_list[num][0],
- command=self.do_update,
- variable=self.format,
- value=num)
- #self.bar.view.menu.add_separator()
- #XXX ...
- self.bar.tk_menuBar(self.bar.file, self.bar.view)
- self.frame = Frame(self, relief=RAISED, borderwidth=2)
- self.frame.pack(expand=1, fill=BOTH)
- self.header = StringVar(self)
- self.frame.label = Label(self.frame, relief=FLAT, anchor=NW,
- borderwidth=0,
- textvariable=self.header)
- self.frame.label.pack(fill=X)
- self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL)
- self.frame.list = Listbox(self.frame, relief=SUNKEN,
- selectbackground='#eed5b7',
- selectborderwidth=0,
- yscroll=self.frame.vscroll.set)
- self.frame.vscroll['command'] = self.frame.list.yview
- self.frame.vscroll.pack(side=RIGHT, fill=Y)
- self.frame.list.pack(expand=1, fill=BOTH)
- self.update = Button(self, text="Update",
- command=self.do_update)
- self.update.pack(expand=1, fill=X)
- self.frame.list.bind('<Motion>', self.do_motion)
- self.frame.list.bind('<Leave>', self.do_leave)
- self.frame.list.bind('<1>', self.do_1)
- self.do_update()
+ # List of (name, option, pid_column)
+ format_list = [('Default', '', 0),
+ ('Long', '-l', 2),
+ ('User', '-u', 1),
+ ('Jobs', '-j', 1),
+ ('Signal', '-s', 1),
+ ('Memory', '-m', 0),
+ ('VM', '-v', 0),
+ ('Hex', '-X', 0)]
+ def kill(self, selected):
+ c = self.format_list[self.format.get()][2]
+ pid = split(selected)[c]
+ os.system('kill -9 ' + pid)
+ self.do_update()
+ def do_update(self):
+ name, option, column = self.format_list[self.format.get()]
+ s = commands.getoutput('ps -w ' + option)
+ list = splitfields(s, '\n')
+ self.header.set(list[0])
+ del list[0]
+ y = self.frame.vscroll.get()[0]
+ self.frame.list.delete(0, AtEnd())
+ for line in list:
+ self.frame.list.insert(0, line)
+ self.frame.list.yview(int(y))
+ def do_motion(self, e):
+ e.widget.select_clear(0, END)
+ e.widget.select_set(e.widget.nearest(e.y))
+ def do_leave(self, e):
+ e.widget.select_clear(0, END)
+ def do_1(self, e):
+ self.kill(e.widget.get(e.widget.nearest(e.y)))
+ def __init__(self, master=None, **cnf):
+ Frame.__init__(self, master, cnf)
+ self.pack(expand=1, fill=BOTH)
+ self.bar = Frame(self, name='bar', relief=RAISED,
+ borderwidth=2)
+ self.bar.pack(fill=X)
+ self.bar.file = BarButton(self.bar, text='File')
+ self.bar.file.menu.add_command(
+ label='Quit', command=self.quit)
+ self.bar.view = BarButton(self.bar, text='View')
+ self.format = IntVar(self)
+ self.format.set(2)
+ for num in range(len(self.format_list)):
+ self.bar.view.menu.add_radiobutton(
+ label=self.format_list[num][0],
+ command=self.do_update,
+ variable=self.format,
+ value=num)
+ #self.bar.view.menu.add_separator()
+ #XXX ...
+ self.bar.tk_menuBar(self.bar.file, self.bar.view)
+ self.frame = Frame(self, relief=RAISED, borderwidth=2)
+ self.frame.pack(expand=1, fill=BOTH)
+ self.header = StringVar(self)
+ self.frame.label = Label(self.frame, relief=FLAT, anchor=NW,
+ borderwidth=0,
+ textvariable=self.header)
+ self.frame.label.pack(fill=X)
+ self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL)
+ self.frame.list = Listbox(self.frame, relief=SUNKEN,
+ selectbackground='#eed5b7',
+ selectborderwidth=0,
+ yscroll=self.frame.vscroll.set)
+ self.frame.vscroll['command'] = self.frame.list.yview
+ self.frame.vscroll.pack(side=RIGHT, fill=Y)
+ self.frame.list.pack(expand=1, fill=BOTH)
+ self.update = Button(self, text="Update",
+ command=self.do_update)
+ self.update.pack(expand=1, fill=X)
+ self.frame.list.bind('<Motion>', self.do_motion)
+ self.frame.list.bind('<Leave>', self.do_leave)
+ self.frame.list.bind('<1>', self.do_1)
+ self.do_update()
if __name__ == '__main__':
- kill = Kill(None, borderwidth=5)
- kill.winfo_toplevel().title('Tkinter Process Killer')
- kill.winfo_toplevel().minsize(1, 1)
- kill.mainloop()
-
+ kill = Kill(None, borderwidth=5)
+ kill.winfo_toplevel().title('Tkinter Process Killer')
+ kill.winfo_toplevel().minsize(1, 1)
+ kill.mainloop()
diff --git a/Demo/tkinter/guido/listtree.py b/Demo/tkinter/guido/listtree.py
index 523f2096db..d28ce49ef2 100755
--- a/Demo/tkinter/guido/listtree.py
+++ b/Demo/tkinter/guido/listtree.py
@@ -6,32 +6,32 @@ import string
from Tkinter import *
def listtree(master, app):
- list = Listbox(master, name='list')
- list.pack(expand=1, fill=BOTH)
- listnodes(list, app, '.', 0)
- return list
+ list = Listbox(master, name='list')
+ list.pack(expand=1, fill=BOTH)
+ listnodes(list, app, '.', 0)
+ return list
def listnodes(list, app, widget, level):
- klass = list.send(app, 'winfo', 'class', widget)
-## i = string.rindex(widget, '.')
-## list.insert(END, '%s%s (%s)' % ((level-1)*'. ', widget[i:], klass))
- list.insert(END, '%s (%s)' % (widget, klass))
- children = list.tk.splitlist(
- list.send(app, 'winfo', 'children', widget))
- for c in children:
- listnodes(list, app, c, level+1)
+ klass = list.send(app, 'winfo', 'class', widget)
+## i = string.rindex(widget, '.')
+## list.insert(END, '%s%s (%s)' % ((level-1)*'. ', widget[i:], klass))
+ list.insert(END, '%s (%s)' % (widget, klass))
+ children = list.tk.splitlist(
+ list.send(app, 'winfo', 'children', widget))
+ for c in children:
+ listnodes(list, app, c, level+1)
def main():
- if not sys.argv[1:]:
- sys.stderr.write('Usage: listtree appname\n')
- sys.exit(2)
- app = sys.argv[1]
- tk = Tk()
- tk.minsize(1, 1)
- f = Frame(tk, name='f')
- f.pack(expand=1, fill=BOTH)
- list = listtree(f, app)
- tk.mainloop()
+ if not sys.argv[1:]:
+ sys.stderr.write('Usage: listtree appname\n')
+ sys.exit(2)
+ app = sys.argv[1]
+ tk = Tk()
+ tk.minsize(1, 1)
+ f = Frame(tk, name='f')
+ f.pack(expand=1, fill=BOTH)
+ list = listtree(f, app)
+ tk.mainloop()
if __name__ == '__main__':
- main()
+ main()
diff --git a/Demo/tkinter/guido/mbox.py b/Demo/tkinter/guido/mbox.py
index 6d7a4106cc..9b16f6baa2 100755
--- a/Demo/tkinter/guido/mbox.py
+++ b/Demo/tkinter/guido/mbox.py
@@ -16,270 +16,270 @@ from dialog import dialog
mailbox = os.environ['HOME'] + '/Mail'
def main():
- global root, tk, top, mid, bot
- global folderbox, foldermenu, scanbox, scanmenu, viewer
- global folder, seq
- global mh, mhf
-
- # Parse command line options
+ global root, tk, top, mid, bot
+ global folderbox, foldermenu, scanbox, scanmenu, viewer
+ global folder, seq
+ global mh, mhf
+
+ # Parse command line options
- folder = 'inbox'
- seq = 'all'
- try:
- opts, args = getopt.getopt(sys.argv[1:], '')
- except getopt.error, msg:
- print msg
- sys.exit(2)
- for arg in args:
- if arg[:1] == '+':
- folder = arg[1:]
- else:
- seq = arg
+ folder = 'inbox'
+ seq = 'all'
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], '')
+ except getopt.error, msg:
+ print msg
+ sys.exit(2)
+ for arg in args:
+ if arg[:1] == '+':
+ folder = arg[1:]
+ else:
+ seq = arg
- # Initialize MH
+ # Initialize MH
- mh = mhlib.MH()
- mhf = mh.openfolder(folder)
+ mh = mhlib.MH()
+ mhf = mh.openfolder(folder)
- # Build widget hierarchy
+ # Build widget hierarchy
- root = Tk()
- tk = root.tk
+ root = Tk()
+ tk = root.tk
- top = Frame(root)
- top.pack({'expand': 1, 'fill': 'both'})
+ top = Frame(root)
+ top.pack({'expand': 1, 'fill': 'both'})
- # Build right part: folder list
+ # Build right part: folder list
- right = Frame(top)
- right.pack({'fill': 'y', 'side': 'right'})
+ right = Frame(top)
+ right.pack({'fill': 'y', 'side': 'right'})
- folderbar = Scrollbar(right, {'relief': 'sunken', 'bd': 2})
- folderbar.pack({'fill': 'y', 'side': 'right'})
+ folderbar = Scrollbar(right, {'relief': 'sunken', 'bd': 2})
+ folderbar.pack({'fill': 'y', 'side': 'right'})
- folderbox = Listbox(right, {'exportselection': 0})
- folderbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
+ folderbox = Listbox(right, {'exportselection': 0})
+ folderbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
- foldermenu = Menu(root)
- foldermenu.add('command',
- {'label': 'Open Folder',
- 'command': open_folder})
- foldermenu.add('separator')
- foldermenu.add('command',
- {'label': 'Quit',
- 'command': 'exit'})
- foldermenu.bind('<ButtonRelease-3>', folder_unpost)
+ foldermenu = Menu(root)
+ foldermenu.add('command',
+ {'label': 'Open Folder',
+ 'command': open_folder})
+ foldermenu.add('separator')
+ foldermenu.add('command',
+ {'label': 'Quit',
+ 'command': 'exit'})
+ foldermenu.bind('<ButtonRelease-3>', folder_unpost)
- folderbox['yscrollcommand'] = (folderbar, 'set')
- folderbar['command'] = (folderbox, 'yview')
- folderbox.bind('<Double-1>', open_folder, 1)
- folderbox.bind('<3>', folder_post)
+ folderbox['yscrollcommand'] = (folderbar, 'set')
+ folderbar['command'] = (folderbox, 'yview')
+ folderbox.bind('<Double-1>', open_folder, 1)
+ folderbox.bind('<3>', folder_post)
- # Build left part: scan list
+ # Build left part: scan list
- left = Frame(top)
- left.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
+ left = Frame(top)
+ left.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
- scanbar = Scrollbar(left, {'relief': 'sunken', 'bd': 2})
- scanbar.pack({'fill': 'y', 'side': 'right'})
+ scanbar = Scrollbar(left, {'relief': 'sunken', 'bd': 2})
+ scanbar.pack({'fill': 'y', 'side': 'right'})
- scanbox = Listbox(left, {'font': 'fixed'})
- scanbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
+ scanbox = Listbox(left, {'font': 'fixed'})
+ scanbox.pack({'expand': 1, 'fill': 'both', 'side': 'left'})
- scanmenu = Menu(root)
- scanmenu.add('command',
- {'label': 'Open Message',
- 'command': open_message})
- scanmenu.add('command',
- {'label': 'Remove Message',
- 'command': remove_message})
- scanmenu.add('command',
- {'label': 'Refile Message',
- 'command': refile_message})
- scanmenu.add('separator')
- scanmenu.add('command',
- {'label': 'Quit',
- 'command': 'exit'})
- scanmenu.bind('<ButtonRelease-3>', scan_unpost)
+ scanmenu = Menu(root)
+ scanmenu.add('command',
+ {'label': 'Open Message',
+ 'command': open_message})
+ scanmenu.add('command',
+ {'label': 'Remove Message',
+ 'command': remove_message})
+ scanmenu.add('command',
+ {'label': 'Refile Message',
+ 'command': refile_message})
+ scanmenu.add('separator')
+ scanmenu.add('command',
+ {'label': 'Quit',
+ 'command': 'exit'})
+ scanmenu.bind('<ButtonRelease-3>', scan_unpost)
- scanbox['yscrollcommand'] = (scanbar, 'set')
- scanbar['command'] = (scanbox, 'yview')
- scanbox.bind('<Double-1>', open_message)
- scanbox.bind('<3>', scan_post)
+ scanbox['yscrollcommand'] = (scanbar, 'set')
+ scanbar['command'] = (scanbox, 'yview')
+ scanbox.bind('<Double-1>', open_message)
+ scanbox.bind('<3>', scan_post)
- # Separator between middle and bottom part
+ # Separator between middle and bottom part
- rule2 = Frame(root, {'bg': 'black'})
- rule2.pack({'fill': 'x'})
+ rule2 = Frame(root, {'bg': 'black'})
+ rule2.pack({'fill': 'x'})
- # Build bottom part: current message
+ # Build bottom part: current message
- bot = Frame(root)
- bot.pack({'expand': 1, 'fill': 'both'})
- #
- viewer = None
+ bot = Frame(root)
+ bot.pack({'expand': 1, 'fill': 'both'})
+ #
+ viewer = None
- # Window manager commands
+ # Window manager commands
- root.minsize(800, 1) # Make window resizable
+ root.minsize(800, 1) # Make window resizable
- # Fill folderbox with text
+ # Fill folderbox with text
- setfolders()
+ setfolders()
- # Fill scanbox with text
+ # Fill scanbox with text
- rescan()
+ rescan()
- # Enter mainloop
+ # Enter mainloop
- root.mainloop()
+ root.mainloop()
def folder_post(e):
- x, y = e.x_root, e.y_root
- foldermenu.post(x - 10, y - 10)
- foldermenu.grab_set()
+ x, y = e.x_root, e.y_root
+ foldermenu.post(x - 10, y - 10)
+ foldermenu.grab_set()
def folder_unpost(e):
- tk.call('update', 'idletasks')
- foldermenu.grab_release()
- foldermenu.unpost()
- foldermenu.invoke('active')
+ tk.call('update', 'idletasks')
+ foldermenu.grab_release()
+ foldermenu.unpost()
+ foldermenu.invoke('active')
def scan_post(e):
- x, y = e.x_root, e.y_root
- scanmenu.post(x - 10, y - 10)
- scanmenu.grab_set()
+ x, y = e.x_root, e.y_root
+ scanmenu.post(x - 10, y - 10)
+ scanmenu.grab_set()
def scan_unpost(e):
- tk.call('update', 'idletasks')
- scanmenu.grab_release()
- scanmenu.unpost()
- scanmenu.invoke('active')
+ tk.call('update', 'idletasks')
+ scanmenu.grab_release()
+ scanmenu.unpost()
+ scanmenu.invoke('active')
scanparser = regex.compile('^ *\([0-9]+\)')
def open_folder(e=None):
- global folder, mhf
- sel = folderbox.curselection()
- if len(sel) != 1:
- if len(sel) > 1:
- msg = "Please open one folder at a time"
- else:
- msg = "Please select a folder to open"
- dialog(root, "Can't Open Folder", msg, "", 0, "OK")
- return
- i = sel[0]
- folder = folderbox.get(i)
- mhf = mh.openfolder(folder)
- rescan()
+ global folder, mhf
+ sel = folderbox.curselection()
+ if len(sel) != 1:
+ if len(sel) > 1:
+ msg = "Please open one folder at a time"
+ else:
+ msg = "Please select a folder to open"
+ dialog(root, "Can't Open Folder", msg, "", 0, "OK")
+ return
+ i = sel[0]
+ folder = folderbox.get(i)
+ mhf = mh.openfolder(folder)
+ rescan()
def open_message(e=None):
- global viewer
- sel = scanbox.curselection()
- if len(sel) != 1:
- if len(sel) > 1:
- msg = "Please open one message at a time"
- else:
- msg = "Please select a message to open"
- dialog(root, "Can't Open Message", msg, "", 0, "OK")
- return
- cursor = scanbox['cursor']
- scanbox['cursor'] = 'watch'
- tk.call('update', 'idletasks')
- i = sel[0]
- line = scanbox.get(i)
- if scanparser.match(line) >= 0:
- num = string.atoi(scanparser.group(1))
- m = mhf.openmessage(num)
- if viewer: viewer.destroy()
- from MimeViewer import MimeViewer
- viewer = MimeViewer(bot, '+%s/%d' % (folder, num), m)
- viewer.pack()
- viewer.show()
- scanbox['cursor'] = cursor
+ global viewer
+ sel = scanbox.curselection()
+ if len(sel) != 1:
+ if len(sel) > 1:
+ msg = "Please open one message at a time"
+ else:
+ msg = "Please select a message to open"
+ dialog(root, "Can't Open Message", msg, "", 0, "OK")
+ return
+ cursor = scanbox['cursor']
+ scanbox['cursor'] = 'watch'
+ tk.call('update', 'idletasks')
+ i = sel[0]
+ line = scanbox.get(i)
+ if scanparser.match(line) >= 0:
+ num = string.atoi(scanparser.group(1))
+ m = mhf.openmessage(num)
+ if viewer: viewer.destroy()
+ from MimeViewer import MimeViewer
+ viewer = MimeViewer(bot, '+%s/%d' % (folder, num), m)
+ viewer.pack()
+ viewer.show()
+ scanbox['cursor'] = cursor
def interestingheader(header):
- return header != 'received'
+ return header != 'received'
def remove_message(e=None):
- itop = scanbox.nearest(0)
- sel = scanbox.curselection()
- if not sel:
- dialog(root, "No Message To Remove",
- "Please select a message to remove", "", 0, "OK")
- return
- todo = []
- for i in sel:
- line = scanbox.get(i)
- if scanparser.match(line) >= 0:
- todo.append(string.atoi(scanparser.group(1)))
- mhf.removemessages(todo)
- rescan()
- fixfocus(min(todo), itop)
+ itop = scanbox.nearest(0)
+ sel = scanbox.curselection()
+ if not sel:
+ dialog(root, "No Message To Remove",
+ "Please select a message to remove", "", 0, "OK")
+ return
+ todo = []
+ for i in sel:
+ line = scanbox.get(i)
+ if scanparser.match(line) >= 0:
+ todo.append(string.atoi(scanparser.group(1)))
+ mhf.removemessages(todo)
+ rescan()
+ fixfocus(min(todo), itop)
lastrefile = ''
tofolder = None
def refile_message(e=None):
- global lastrefile, tofolder
- itop = scanbox.nearest(0)
- sel = scanbox.curselection()
- if not sel:
- dialog(root, "No Message To Refile",
- "Please select a message to refile", "", 0, "OK")
- return
- foldersel = folderbox.curselection()
- if len(foldersel) != 1:
- if not foldersel:
- msg = "Please select a folder to refile to"
- else:
- msg = "Please select exactly one folder to refile to"
- dialog(root, "No Folder To Refile", msg, "", 0, "OK")
- return
- refileto = folderbox.get(foldersel[0])
- todo = []
- for i in sel:
- line = scanbox.get(i)
- if scanparser.match(line) >= 0:
- todo.append(string.atoi(scanparser.group(1)))
- if lastrefile != refileto or not tofolder:
- lastrefile = refileto
- tofolder = None
- tofolder = mh.openfolder(lastrefile)
- mhf.refilemessages(todo, tofolder)
- rescan()
- fixfocus(min(todo), itop)
+ global lastrefile, tofolder
+ itop = scanbox.nearest(0)
+ sel = scanbox.curselection()
+ if not sel:
+ dialog(root, "No Message To Refile",
+ "Please select a message to refile", "", 0, "OK")
+ return
+ foldersel = folderbox.curselection()
+ if len(foldersel) != 1:
+ if not foldersel:
+ msg = "Please select a folder to refile to"
+ else:
+ msg = "Please select exactly one folder to refile to"
+ dialog(root, "No Folder To Refile", msg, "", 0, "OK")
+ return
+ refileto = folderbox.get(foldersel[0])
+ todo = []
+ for i in sel:
+ line = scanbox.get(i)
+ if scanparser.match(line) >= 0:
+ todo.append(string.atoi(scanparser.group(1)))
+ if lastrefile != refileto or not tofolder:
+ lastrefile = refileto
+ tofolder = None
+ tofolder = mh.openfolder(lastrefile)
+ mhf.refilemessages(todo, tofolder)
+ rescan()
+ fixfocus(min(todo), itop)
def fixfocus(near, itop):
- n = scanbox.size()
- for i in range(n):
- line = scanbox.get(repr(i))
- if scanparser.match(line) >= 0:
- num = string.atoi(scanparser.group(1))
- if num >= near:
- break
- else:
- i = 'end'
- scanbox.select_from(i)
- scanbox.yview(itop)
+ n = scanbox.size()
+ for i in range(n):
+ line = scanbox.get(repr(i))
+ if scanparser.match(line) >= 0:
+ num = string.atoi(scanparser.group(1))
+ if num >= near:
+ break
+ else:
+ i = 'end'
+ scanbox.select_from(i)
+ scanbox.yview(itop)
def setfolders():
- folderbox.delete(0, 'end')
- for fn in mh.listallfolders():
- folderbox.insert('end', fn)
+ folderbox.delete(0, 'end')
+ for fn in mh.listallfolders():
+ folderbox.insert('end', fn)
def rescan():
- global viewer
- if viewer:
- viewer.destroy()
- viewer = None
- scanbox.delete(0, 'end')
- for line in scanfolder(folder, seq):
- scanbox.insert('end', line)
+ global viewer
+ if viewer:
+ viewer.destroy()
+ viewer = None
+ scanbox.delete(0, 'end')
+ for line in scanfolder(folder, seq):
+ scanbox.insert('end', line)
def scanfolder(folder = 'inbox', sequence = 'all'):
- return map(
- lambda line: line[:-1],
- os.popen('scan +%s %s' % (folder, sequence), 'r').readlines())
+ return map(
+ lambda line: line[:-1],
+ os.popen('scan +%s %s' % (folder, sequence), 'r').readlines())
main()
diff --git a/Demo/tkinter/guido/newmenubardemo.py b/Demo/tkinter/guido/newmenubardemo.py
index cafbf63ef8..57bf13c444 100644
--- a/Demo/tkinter/guido/newmenubardemo.py
+++ b/Demo/tkinter/guido/newmenubardemo.py
@@ -7,35 +7,35 @@ from Tkinter import *
class App:
def __init__(self, master):
- self.master = master
+ self.master = master
- self.menubar = Menu(self.master)
+ self.menubar = Menu(self.master)
- self.filemenu = Menu(self.menubar)
-
- self.filemenu.add_command(label="New")
- self.filemenu.add_command(label="Open...")
- self.filemenu.add_command(label="Close")
- self.filemenu.add_separator()
- self.filemenu.add_command(label="Quit", command=self.master.quit)
+ self.filemenu = Menu(self.menubar)
- self.editmenu = Menu(self.menubar)
+ self.filemenu.add_command(label="New")
+ self.filemenu.add_command(label="Open...")
+ self.filemenu.add_command(label="Close")
+ self.filemenu.add_separator()
+ self.filemenu.add_command(label="Quit", command=self.master.quit)
- self.editmenu.add_command(label="Cut")
- self.editmenu.add_command(label="Copy")
- self.editmenu.add_command(label="Paste")
+ self.editmenu = Menu(self.menubar)
+
+ self.editmenu.add_command(label="Cut")
+ self.editmenu.add_command(label="Copy")
+ self.editmenu.add_command(label="Paste")
self.helpmenu = Menu(self.menubar, name='help')
self.helpmenu.add_command(label="About...")
- self.menubar.add_cascade(label="File", menu=self.filemenu)
- self.menubar.add_cascade(label="Edit", menu=self.editmenu)
- self.menubar.add_cascade(label="Help", menu=self.helpmenu)
+ self.menubar.add_cascade(label="File", menu=self.filemenu)
+ self.menubar.add_cascade(label="Edit", menu=self.editmenu)
+ self.menubar.add_cascade(label="Help", menu=self.helpmenu)
- self.top = Toplevel(menu=self.menubar)
+ self.top = Toplevel(menu=self.menubar)
- # Rest of app goes here...
+ # Rest of app goes here...
def main():
root = Tk()
diff --git a/Demo/tkinter/guido/paint.py b/Demo/tkinter/guido/paint.py
index 743d500d2b..d46e20b9ad 100644
--- a/Demo/tkinter/guido/paint.py
+++ b/Demo/tkinter/guido/paint.py
@@ -12,12 +12,12 @@ here and hope that the person who requested it sees this!
All this does is put up a canvas and draw a smooth black line
whenever you have the mouse button down, but hopefully it will
-be enough to start with.. It would be easy enough to add some
+be enough to start with.. It would be easy enough to add some
options like other shapes or colors...
- yours,
- dave mitchell
- davem@magnet.com
+ yours,
+ dave mitchell
+ davem@magnet.com
"""
from Tkinter import *
@@ -28,33 +28,33 @@ b1 = "up"
xold, yold = None, None
def main():
- root = Tk()
- drawing_area = Canvas(root)
- drawing_area.pack()
- drawing_area.bind("<Motion>", motion)
- drawing_area.bind("<ButtonPress-1>", b1down)
- drawing_area.bind("<ButtonRelease-1>", b1up)
- root.mainloop()
+ root = Tk()
+ drawing_area = Canvas(root)
+ drawing_area.pack()
+ drawing_area.bind("<Motion>", motion)
+ drawing_area.bind("<ButtonPress-1>", b1down)
+ drawing_area.bind("<ButtonRelease-1>", b1up)
+ root.mainloop()
def b1down(event):
- global b1
- b1 = "down" # you only want to draw when the button is down
- # because "Motion" events happen -all the time-
+ global b1
+ b1 = "down" # you only want to draw when the button is down
+ # because "Motion" events happen -all the time-
def b1up(event):
- global b1, xold, yold
- b1 = "up"
- xold = None # reset the line when you let go of the button
- yold = None
+ global b1, xold, yold
+ b1 = "up"
+ xold = None # reset the line when you let go of the button
+ yold = None
def motion(event):
- if b1 == "down":
- global xold, yold
- if xold != None and yold != None:
- event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE)
- # here's where you draw it. smooth. neat.
- xold = event.x
- yold = event.y
+ if b1 == "down":
+ global xold, yold
+ if xold != None and yold != None:
+ event.widget.create_line(xold,yold,event.x,event.y,smooth=TRUE)
+ # here's where you draw it. smooth. neat.
+ xold = event.x
+ yold = event.y
if __name__ == "__main__":
- main()
+ main()
diff --git a/Demo/tkinter/guido/rmt.py b/Demo/tkinter/guido/rmt.py
index 6e9a8288fa..440650c9c4 100755
--- a/Demo/tkinter/guido/rmt.py
+++ b/Demo/tkinter/guido/rmt.py
@@ -28,7 +28,7 @@ s = Scrollbar(f, relief=FLAT)
s.pack(side=RIGHT, fill=Y)
t = Text(f, relief=RAISED, borderwidth=2, yscrollcommand=s.set, setgrid=1)
t.pack(side=LEFT, fill=BOTH, expand=1)
-t.tag_config('bold', font='-Adobe-Courier-Bold-R-Normal-*-120-*')
+t.tag_config('bold', font='-Adobe-Courier-Bold-R-Normal-*-120-*')
s['command'] = t.yview
root.title('Tk Remote Controller')
@@ -42,7 +42,7 @@ file_m = Menu(file)
file['menu'] = file_m
file_m_apps = Menu(file_m, tearoff=0)
file_m.add_cascade(label='Select Application', underline=0,
- menu=file_m_apps)
+ menu=file_m_apps)
file_m.add_command(label='Quit', underline=0, command=sys.exit)
# 3. Create bindings for text widget to allow commands to be
@@ -51,46 +51,46 @@ file_m.add_command(label='Quit', underline=0, command=sys.exit)
# insertion point).
def single1(e):
- x = e.x
- y = e.y
- t.setvar('tk_priv(selectMode)', 'char')
- t.mark_set('anchor', At(x, y))
- # Should focus W
+ x = e.x
+ y = e.y
+ t.setvar('tk_priv(selectMode)', 'char')
+ t.mark_set('anchor', At(x, y))
+ # Should focus W
t.bind('<1>', single1)
def double1(e):
- x = e.x
- y = e.y
- t.setvar('tk_priv(selectMode)', 'word')
- t.tk_textSelectTo(At(x, y))
+ x = e.x
+ y = e.y
+ t.setvar('tk_priv(selectMode)', 'word')
+ t.tk_textSelectTo(At(x, y))
t.bind('<Double-1>', double1)
def triple1(e):
- x = e.x
- y = e.y
- t.setvar('tk_priv(selectMode)', 'line')
- t.tk_textSelectTo(At(x, y))
+ x = e.x
+ y = e.y
+ t.setvar('tk_priv(selectMode)', 'line')
+ t.tk_textSelectTo(At(x, y))
t.bind('<Triple-1>', triple1)
def returnkey(e):
- t.insert(AtInsert(), '\n')
- invoke()
+ t.insert(AtInsert(), '\n')
+ invoke()
t.bind('<Return>', returnkey)
def controlv(e):
- t.insert(AtInsert(), t.selection_get())
- t.yview_pickplace(AtInsert())
- if t.index(AtInsert())[-2:] == '.0':
- invoke()
+ t.insert(AtInsert(), t.selection_get())
+ t.yview_pickplace(AtInsert())
+ if t.index(AtInsert())[-2:] == '.0':
+ invoke()
t.bind('<Control-v>', controlv)
# 4. Procedure to backspace over one character, as long as
# the character isn't part of the prompt.
def backspace(e):
- if t.index('promptEnd') != t.index('insert - 1 char'):
- t.delete('insert - 1 char', AtInsert())
- t.yview_pickplace(AtInsert())
+ if t.index('promptEnd') != t.index('insert - 1 char'):
+ t.delete('insert - 1 char', AtInsert())
+ t.yview_pickplace(AtInsert())
t.bind('<BackSpace>', backspace)
t.bind('<Control-h>', backspace)
t.bind('<Delete>', backspace)
@@ -103,49 +103,49 @@ t.bind('<Delete>', backspace)
# a new prompt.
def invoke():
- cmd = t.get('promptEnd + 1 char', AtInsert())
- if t.getboolean(tk.call('info', 'complete', cmd)): # XXX
- if app == root.winfo_name():
- msg = tk.call('eval', cmd) # XXX
- else:
- msg = t.send(app, cmd)
- if msg:
- t.insert(AtInsert(), msg + '\n')
- prompt()
- t.yview_pickplace(AtInsert())
+ cmd = t.get('promptEnd + 1 char', AtInsert())
+ if t.getboolean(tk.call('info', 'complete', cmd)): # XXX
+ if app == root.winfo_name():
+ msg = tk.call('eval', cmd) # XXX
+ else:
+ msg = t.send(app, cmd)
+ if msg:
+ t.insert(AtInsert(), msg + '\n')
+ prompt()
+ t.yview_pickplace(AtInsert())
def prompt():
- t.insert(AtInsert(), app + ': ')
- t.mark_set('promptEnd', 'insert - 1 char')
- t.tag_add('bold', 'insert linestart', 'promptEnd')
+ t.insert(AtInsert(), app + ': ')
+ t.mark_set('promptEnd', 'insert - 1 char')
+ t.tag_add('bold', 'insert linestart', 'promptEnd')
# 6. Procedure to select a new application. Also changes
# the prompt on the current command line to reflect the new
# name.
def newApp(appName):
- global app
- app = appName
- t.delete('promptEnd linestart', 'promptEnd')
- t.insert('promptEnd', appName + ':')
- t.tag_add('bold', 'promptEnd linestart', 'promptEnd')
+ global app
+ app = appName
+ t.delete('promptEnd linestart', 'promptEnd')
+ t.insert('promptEnd', appName + ':')
+ t.tag_add('bold', 'promptEnd linestart', 'promptEnd')
def fillAppsMenu():
- file_m_apps.add('command')
- file_m_apps.delete(0, 'last')
- names = root.winfo_interps()
- names = map(None, names) # convert tuple to list
- names.sort()
- for name in names:
- try:
- root.send(name, 'winfo name .')
- except TclError:
- # Inoperative window -- ignore it
- pass
- else:
- file_m_apps.add_command(
- label=name,
- command=lambda name=name: newApp(name))
+ file_m_apps.add('command')
+ file_m_apps.delete(0, 'last')
+ names = root.winfo_interps()
+ names = map(None, names) # convert tuple to list
+ names.sort()
+ for name in names:
+ try:
+ root.send(name, 'winfo name .')
+ except TclError:
+ # Inoperative window -- ignore it
+ pass
+ else:
+ file_m_apps.add_command(
+ label=name,
+ command=lambda name=name: newApp(name))
file_m_apps['postcommand'] = fillAppsMenu
mBar.tk_menuBar(file)
diff --git a/Demo/tkinter/guido/solitaire.py b/Demo/tkinter/guido/solitaire.py
index a205afd3ba..50a8b26433 100755
--- a/Demo/tkinter/guido/solitaire.py
+++ b/Demo/tkinter/guido/solitaire.py
@@ -11,7 +11,7 @@ Limitations:
- No keyboard shortcuts.
- Less fancy animation when you win.
- The determination of which stack you drag to is more relaxed.
-
+
Apology:
I'm not much of a card player, so my terminology in these comments may
@@ -35,7 +35,7 @@ from Canvas import Rectangle, CanvasText, Group, Window
class Group(Group):
def bind(self, sequence=None, command=None):
- return self.canvas.tag_bind(self.id, sequence, command)
+ return self.canvas.tag_bind(self.id, sequence, command)
# Constants determining the size and lay-out of cards and stacks. We
@@ -135,7 +135,7 @@ class Card:
Semi-public read-only instance variables (XXX should be made
private):
-
+
group -- the Canvas.Group representing the card
x, y -- the position of the card's top left corner
@@ -150,68 +150,68 @@ class Card:
"""
def __init__(self, suit, value, canvas):
- """Card constructor.
+ """Card constructor.
- Arguments are the card's suit and value, and the canvas widget.
+ Arguments are the card's suit and value, and the canvas widget.
- The card is created at position (0, 0), with its face down
- (adding it to a stack will position it according to that
- stack's rules).
+ The card is created at position (0, 0), with its face down
+ (adding it to a stack will position it according to that
+ stack's rules).
- """
- self.suit = suit
- self.value = value
- self.color = COLOR[suit]
- self.face_shown = 0
+ """
+ self.suit = suit
+ self.value = value
+ self.color = COLOR[suit]
+ self.face_shown = 0
- self.x = self.y = 0
- self.group = Group(canvas)
+ self.x = self.y = 0
+ self.group = Group(canvas)
- text = "%s %s" % (VALNAMES[value], suit)
- self.__text = CanvasText(canvas, CARDWIDTH/2, 0,
- anchor=N, fill=self.color, text=text)
- self.group.addtag_withtag(self.__text)
+ text = "%s %s" % (VALNAMES[value], suit)
+ self.__text = CanvasText(canvas, CARDWIDTH/2, 0,
+ anchor=N, fill=self.color, text=text)
+ self.group.addtag_withtag(self.__text)
- self.__rect = Rectangle(canvas, 0, 0, CARDWIDTH, CARDHEIGHT,
- outline='black', fill='white')
- self.group.addtag_withtag(self.__rect)
+ self.__rect = Rectangle(canvas, 0, 0, CARDWIDTH, CARDHEIGHT,
+ outline='black', fill='white')
+ self.group.addtag_withtag(self.__rect)
- self.__back = Rectangle(canvas, MARGIN, MARGIN,
- CARDWIDTH-MARGIN, CARDHEIGHT-MARGIN,
- outline='black', fill='blue')
- self.group.addtag_withtag(self.__back)
+ self.__back = Rectangle(canvas, MARGIN, MARGIN,
+ CARDWIDTH-MARGIN, CARDHEIGHT-MARGIN,
+ outline='black', fill='blue')
+ self.group.addtag_withtag(self.__back)
def __repr__(self):
- """Return a string for debug print statements."""
- return "Card(%r, %r)" % (self.suit, self.value)
+ """Return a string for debug print statements."""
+ return "Card(%r, %r)" % (self.suit, self.value)
def moveto(self, x, y):
- """Move the card to absolute position (x, y)."""
- self.moveby(x - self.x, y - self.y)
+ """Move the card to absolute position (x, y)."""
+ self.moveby(x - self.x, y - self.y)
def moveby(self, dx, dy):
- """Move the card by (dx, dy)."""
- self.x = self.x + dx
- self.y = self.y + dy
- self.group.move(dx, dy)
+ """Move the card by (dx, dy)."""
+ self.x = self.x + dx
+ self.y = self.y + dy
+ self.group.move(dx, dy)
def tkraise(self):
- """Raise the card above all other objects in its canvas."""
- self.group.tkraise()
+ """Raise the card above all other objects in its canvas."""
+ self.group.tkraise()
def showface(self):
- """Turn the card's face up."""
- self.tkraise()
- self.__rect.tkraise()
- self.__text.tkraise()
- self.face_shown = 1
+ """Turn the card's face up."""
+ self.tkraise()
+ self.__rect.tkraise()
+ self.__text.tkraise()
+ self.face_shown = 1
def showback(self):
- """Turn the card's face down."""
- self.tkraise()
- self.__rect.tkraise()
- self.__back.tkraise()
- self.face_shown = 0
+ """Turn the card's face down."""
+ self.tkraise()
+ self.__rect.tkraise()
+ self.__back.tkraise()
+ self.face_shown = 0
class Stack:
@@ -240,7 +240,7 @@ class Stack:
The default user (single) click handler shows the top card
face up. The default user double click handler calls the user
- single click handler.
+ single click handler.
usermovehandler(cards) -- called to complete a subpile move
@@ -255,133 +255,133 @@ class Stack:
The default event handlers turn the top card of the stack with
its face up on a (single or double) click, and also support
moving a subpile around.
-
+
startmoving(event) -- begin a move operation
finishmoving() -- finish a move operation
"""
def __init__(self, x, y, game=None):
- """Stack constructor.
-
- Arguments are the stack's nominal x and y position (the top
- left corner of the first card placed in the stack), and the
- game object (which is used to get the canvas; subclasses use
- the game object to find other stacks).
-
- """
- self.x = x
- self.y = y
- self.game = game
- self.cards = []
- self.group = Group(self.game.canvas)
- self.group.bind('<1>', self.clickhandler)
- self.group.bind('<Double-1>', self.doubleclickhandler)
- self.group.bind('<B1-Motion>', self.motionhandler)
- self.group.bind('<ButtonRelease-1>', self.releasehandler)
- self.makebottom()
+ """Stack constructor.
+
+ Arguments are the stack's nominal x and y position (the top
+ left corner of the first card placed in the stack), and the
+ game object (which is used to get the canvas; subclasses use
+ the game object to find other stacks).
+
+ """
+ self.x = x
+ self.y = y
+ self.game = game
+ self.cards = []
+ self.group = Group(self.game.canvas)
+ self.group.bind('<1>', self.clickhandler)
+ self.group.bind('<Double-1>', self.doubleclickhandler)
+ self.group.bind('<B1-Motion>', self.motionhandler)
+ self.group.bind('<ButtonRelease-1>', self.releasehandler)
+ self.makebottom()
def makebottom(self):
- pass
+ pass
def __repr__(self):
- """Return a string for debug print statements."""
- return "%s(%d, %d)" % (self.__class__.__name__, self.x, self.y)
+ """Return a string for debug print statements."""
+ return "%s(%d, %d)" % (self.__class__.__name__, self.x, self.y)
# Public methods
def add(self, card):
- self.cards.append(card)
- card.tkraise()
- self.position(card)
- self.group.addtag_withtag(card.group)
+ self.cards.append(card)
+ card.tkraise()
+ self.position(card)
+ self.group.addtag_withtag(card.group)
def delete(self, card):
- self.cards.remove(card)
- card.group.dtag(self.group)
+ self.cards.remove(card)
+ card.group.dtag(self.group)
def showtop(self):
- if self.cards:
- self.cards[-1].showface()
+ if self.cards:
+ self.cards[-1].showface()
def deal(self):
- if not self.cards:
- return None
- card = self.cards[-1]
- self.delete(card)
- return card
+ if not self.cards:
+ return None
+ card = self.cards[-1]
+ self.delete(card)
+ return card
# Subclass overridable methods
def position(self, card):
- card.moveto(self.x, self.y)
+ card.moveto(self.x, self.y)
def userclickhandler(self):
- self.showtop()
+ self.showtop()
def userdoubleclickhandler(self):
- self.userclickhandler()
+ self.userclickhandler()
def usermovehandler(self, cards):
- for card in cards:
- self.position(card)
+ for card in cards:
+ self.position(card)
# Event handlers
def clickhandler(self, event):
- self.finishmoving() # In case we lost an event
- self.userclickhandler()
- self.startmoving(event)
+ self.finishmoving() # In case we lost an event
+ self.userclickhandler()
+ self.startmoving(event)
def motionhandler(self, event):
- self.keepmoving(event)
+ self.keepmoving(event)
def releasehandler(self, event):
- self.keepmoving(event)
- self.finishmoving()
+ self.keepmoving(event)
+ self.finishmoving()
def doubleclickhandler(self, event):
- self.finishmoving() # In case we lost an event
- self.userdoubleclickhandler()
- self.startmoving(event)
+ self.finishmoving() # In case we lost an event
+ self.userdoubleclickhandler()
+ self.startmoving(event)
# Move internals
moving = None
def startmoving(self, event):
- self.moving = None
- tags = self.game.canvas.gettags('current')
- for i in range(len(self.cards)):
- card = self.cards[i]
- if card.group.tag in tags:
- break
- else:
- return
- if not card.face_shown:
- return
- self.moving = self.cards[i:]
- self.lastx = event.x
- self.lasty = event.y
- for card in self.moving:
- card.tkraise()
+ self.moving = None
+ tags = self.game.canvas.gettags('current')
+ for i in range(len(self.cards)):
+ card = self.cards[i]
+ if card.group.tag in tags:
+ break
+ else:
+ return
+ if not card.face_shown:
+ return
+ self.moving = self.cards[i:]
+ self.lastx = event.x
+ self.lasty = event.y
+ for card in self.moving:
+ card.tkraise()
def keepmoving(self, event):
- if not self.moving:
- return
- dx = event.x - self.lastx
- dy = event.y - self.lasty
- self.lastx = event.x
- self.lasty = event.y
- if dx or dy:
- for card in self.moving:
- card.moveby(dx, dy)
+ if not self.moving:
+ return
+ dx = event.x - self.lastx
+ dy = event.y - self.lasty
+ self.lastx = event.x
+ self.lasty = event.y
+ if dx or dy:
+ for card in self.moving:
+ card.moveby(dx, dy)
def finishmoving(self):
- cards = self.moving
- self.moving = None
- if cards:
- self.usermovehandler(cards)
+ cards = self.moving
+ self.moving = None
+ if cards:
+ self.usermovehandler(cards)
class Deck(Stack):
@@ -400,37 +400,37 @@ class Deck(Stack):
"""
def makebottom(self):
- bottom = Rectangle(self.game.canvas,
- self.x, self.y,
- self.x+CARDWIDTH, self.y+CARDHEIGHT,
- outline='black', fill=BACKGROUND)
- self.group.addtag_withtag(bottom)
+ bottom = Rectangle(self.game.canvas,
+ self.x, self.y,
+ self.x+CARDWIDTH, self.y+CARDHEIGHT,
+ outline='black', fill=BACKGROUND)
+ self.group.addtag_withtag(bottom)
def fill(self):
- for suit in ALLSUITS:
- for value in ALLVALUES:
- self.add(Card(suit, value, self.game.canvas))
+ for suit in ALLSUITS:
+ for value in ALLVALUES:
+ self.add(Card(suit, value, self.game.canvas))
def shuffle(self):
- n = len(self.cards)
- newcards = []
- for i in randperm(n):
- newcards.append(self.cards[i])
- self.cards = newcards
+ n = len(self.cards)
+ newcards = []
+ for i in randperm(n):
+ newcards.append(self.cards[i])
+ self.cards = newcards
def userclickhandler(self):
- opendeck = self.game.opendeck
- card = self.deal()
- if not card:
- while 1:
- card = opendeck.deal()
- if not card:
- break
- self.add(card)
- card.showback()
- else:
- self.game.opendeck.add(card)
- card.showface()
+ opendeck = self.game.opendeck
+ card = self.deal()
+ if not card:
+ while 1:
+ card = opendeck.deal()
+ if not card:
+ break
+ self.add(card)
+ card.showback()
+ else:
+ self.game.opendeck.add(card)
+ card.showface()
def randperm(n):
@@ -438,191 +438,191 @@ def randperm(n):
r = range(n)
x = []
while r:
- i = random.choice(r)
- x.append(i)
- r.remove(i)
+ i = random.choice(r)
+ x.append(i)
+ r.remove(i)
return x
class OpenStack(Stack):
def acceptable(self, cards):
- return 0
+ return 0
def usermovehandler(self, cards):
- card = cards[0]
- stack = self.game.closeststack(card)
- if not stack or stack is self or not stack.acceptable(cards):
- Stack.usermovehandler(self, cards)
- else:
- for card in cards:
- self.delete(card)
- stack.add(card)
- self.game.wincheck()
+ card = cards[0]
+ stack = self.game.closeststack(card)
+ if not stack or stack is self or not stack.acceptable(cards):
+ Stack.usermovehandler(self, cards)
+ else:
+ for card in cards:
+ self.delete(card)
+ stack.add(card)
+ self.game.wincheck()
def userdoubleclickhandler(self):
- if not self.cards:
- return
- card = self.cards[-1]
- if not card.face_shown:
- self.userclickhandler()
- return
- for s in self.game.suits:
- if s.acceptable([card]):
- self.delete(card)
- s.add(card)
- self.game.wincheck()
- break
+ if not self.cards:
+ return
+ card = self.cards[-1]
+ if not card.face_shown:
+ self.userclickhandler()
+ return
+ for s in self.game.suits:
+ if s.acceptable([card]):
+ self.delete(card)
+ s.add(card)
+ self.game.wincheck()
+ break
class SuitStack(OpenStack):
def makebottom(self):
- bottom = Rectangle(self.game.canvas,
- self.x, self.y,
- self.x+CARDWIDTH, self.y+CARDHEIGHT,
- outline='black', fill='')
+ bottom = Rectangle(self.game.canvas,
+ self.x, self.y,
+ self.x+CARDWIDTH, self.y+CARDHEIGHT,
+ outline='black', fill='')
def userclickhandler(self):
- pass
+ pass
def userdoubleclickhandler(self):
- pass
+ pass
def acceptable(self, cards):
- if len(cards) != 1:
- return 0
- card = cards[0]
- if not self.cards:
- return card.value == ACE
- topcard = self.cards[-1]
- return card.suit == topcard.suit and card.value == topcard.value + 1
+ if len(cards) != 1:
+ return 0
+ card = cards[0]
+ if not self.cards:
+ return card.value == ACE
+ topcard = self.cards[-1]
+ return card.suit == topcard.suit and card.value == topcard.value + 1
class RowStack(OpenStack):
def acceptable(self, cards):
- card = cards[0]
- if not self.cards:
- return card.value == KING
- topcard = self.cards[-1]
- if not topcard.face_shown:
- return 0
- return card.color != topcard.color and card.value == topcard.value - 1
+ card = cards[0]
+ if not self.cards:
+ return card.value == KING
+ topcard = self.cards[-1]
+ if not topcard.face_shown:
+ return 0
+ return card.color != topcard.color and card.value == topcard.value - 1
def position(self, card):
- y = self.y
- for c in self.cards:
- if c == card:
- break
- if c.face_shown:
- y = y + 2*MARGIN
- else:
- y = y + OFFSET
- card.moveto(self.x, y)
+ y = self.y
+ for c in self.cards:
+ if c == card:
+ break
+ if c.face_shown:
+ y = y + 2*MARGIN
+ else:
+ y = y + OFFSET
+ card.moveto(self.x, y)
class Solitaire:
def __init__(self, master):
- self.master = master
-
- self.canvas = Canvas(self.master,
- background=BACKGROUND,
- highlightthickness=0,
- width=NROWS*XSPACING,
- height=3*YSPACING + 20 + MARGIN)
- self.canvas.pack(fill=BOTH, expand=TRUE)
-
- self.dealbutton = Button(self.canvas,
- text="Deal",
- highlightthickness=0,
- background=BACKGROUND,
- activebackground="green",
- command=self.deal)
- Window(self.canvas, MARGIN, 3*YSPACING + 20,
- window=self.dealbutton, anchor=SW)
-
- x = MARGIN
- y = MARGIN
-
- self.deck = Deck(x, y, self)
-
- x = x + XSPACING
- self.opendeck = OpenStack(x, y, self)
-
- x = x + XSPACING
- self.suits = []
- for i in range(NSUITS):
- x = x + XSPACING
- self.suits.append(SuitStack(x, y, self))
-
- x = MARGIN
- y = y + YSPACING
-
- self.rows = []
- for i in range(NROWS):
- self.rows.append(RowStack(x, y, self))
- x = x + XSPACING
-
- self.openstacks = [self.opendeck] + self.suits + self.rows
-
- self.deck.fill()
- self.deal()
+ self.master = master
+
+ self.canvas = Canvas(self.master,
+ background=BACKGROUND,
+ highlightthickness=0,
+ width=NROWS*XSPACING,
+ height=3*YSPACING + 20 + MARGIN)
+ self.canvas.pack(fill=BOTH, expand=TRUE)
+
+ self.dealbutton = Button(self.canvas,
+ text="Deal",
+ highlightthickness=0,
+ background=BACKGROUND,
+ activebackground="green",
+ command=self.deal)
+ Window(self.canvas, MARGIN, 3*YSPACING + 20,
+ window=self.dealbutton, anchor=SW)
+
+ x = MARGIN
+ y = MARGIN
+
+ self.deck = Deck(x, y, self)
+
+ x = x + XSPACING
+ self.opendeck = OpenStack(x, y, self)
+
+ x = x + XSPACING
+ self.suits = []
+ for i in range(NSUITS):
+ x = x + XSPACING
+ self.suits.append(SuitStack(x, y, self))
+
+ x = MARGIN
+ y = y + YSPACING
+
+ self.rows = []
+ for i in range(NROWS):
+ self.rows.append(RowStack(x, y, self))
+ x = x + XSPACING
+
+ self.openstacks = [self.opendeck] + self.suits + self.rows
+
+ self.deck.fill()
+ self.deal()
def wincheck(self):
- for s in self.suits:
- if len(s.cards) != NVALUES:
- return
- self.win()
- self.deal()
+ for s in self.suits:
+ if len(s.cards) != NVALUES:
+ return
+ self.win()
+ self.deal()
def win(self):
- """Stupid animation when you win."""
- cards = []
- for s in self.openstacks:
- cards = cards + s.cards
- while cards:
- card = random.choice(cards)
- cards.remove(card)
- self.animatedmoveto(card, self.deck)
+ """Stupid animation when you win."""
+ cards = []
+ for s in self.openstacks:
+ cards = cards + s.cards
+ while cards:
+ card = random.choice(cards)
+ cards.remove(card)
+ self.animatedmoveto(card, self.deck)
def animatedmoveto(self, card, dest):
- for i in range(10, 0, -1):
- dx, dy = (dest.x-card.x)/i, (dest.y-card.y)/i
- card.moveby(dx, dy)
- self.master.update_idletasks()
+ for i in range(10, 0, -1):
+ dx, dy = (dest.x-card.x)/i, (dest.y-card.y)/i
+ card.moveby(dx, dy)
+ self.master.update_idletasks()
def closeststack(self, card):
- closest = None
- cdist = 999999999
- # Since we only compare distances,
- # we don't bother to take the square root.
- for stack in self.openstacks:
- dist = (stack.x - card.x)**2 + (stack.y - card.y)**2
- if dist < cdist:
- closest = stack
- cdist = dist
- return closest
+ closest = None
+ cdist = 999999999
+ # Since we only compare distances,
+ # we don't bother to take the square root.
+ for stack in self.openstacks:
+ dist = (stack.x - card.x)**2 + (stack.y - card.y)**2
+ if dist < cdist:
+ closest = stack
+ cdist = dist
+ return closest
def deal(self):
- self.reset()
- self.deck.shuffle()
- for i in range(NROWS):
- for r in self.rows[i:]:
- card = self.deck.deal()
- r.add(card)
- for r in self.rows:
- r.showtop()
+ self.reset()
+ self.deck.shuffle()
+ for i in range(NROWS):
+ for r in self.rows[i:]:
+ card = self.deck.deal()
+ r.add(card)
+ for r in self.rows:
+ r.showtop()
def reset(self):
- for stack in self.openstacks:
- while 1:
- card = stack.deal()
- if not card:
- break
- self.deck.add(card)
- card.showback()
+ for stack in self.openstacks:
+ while 1:
+ card = stack.deal()
+ if not card:
+ break
+ self.deck.add(card)
+ card.showback()
# Main function, run when invoked as a stand-alone Python program.
diff --git a/Demo/tkinter/guido/sortvisu.py b/Demo/tkinter/guido/sortvisu.py
index 6fe40024b3..f18f2c1168 100644
--- a/Demo/tkinter/guido/sortvisu.py
+++ b/Demo/tkinter/guido/sortvisu.py
@@ -32,302 +32,302 @@ WIDTH = 6
class Array:
def __init__(self, master, data=None):
- self.master = master
- self.frame = Frame(self.master)
- self.frame.pack(fill=X)
- self.label = Label(self.frame)
- self.label.pack()
- self.canvas = Canvas(self.frame)
- self.canvas.pack()
- self.report = Label(self.frame)
- self.report.pack()
- self.left = Line(self.canvas, 0, 0, 0, 0)
- self.right = Line(self.canvas, 0, 0, 0, 0)
- self.pivot = Line(self.canvas, 0, 0, 0, 0)
- self.items = []
- self.size = self.maxvalue = 0
- if data:
- self.setdata(data)
+ self.master = master
+ self.frame = Frame(self.master)
+ self.frame.pack(fill=X)
+ self.label = Label(self.frame)
+ self.label.pack()
+ self.canvas = Canvas(self.frame)
+ self.canvas.pack()
+ self.report = Label(self.frame)
+ self.report.pack()
+ self.left = Line(self.canvas, 0, 0, 0, 0)
+ self.right = Line(self.canvas, 0, 0, 0, 0)
+ self.pivot = Line(self.canvas, 0, 0, 0, 0)
+ self.items = []
+ self.size = self.maxvalue = 0
+ if data:
+ self.setdata(data)
def setdata(self, data):
- olditems = self.items
- self.items = []
- for item in olditems:
- item.delete()
- self.size = len(data)
- self.maxvalue = max(data)
- self.canvas.config(width=(self.size+1)*XGRID,
- height=(self.maxvalue+1)*YGRID)
- for i in range(self.size):
- self.items.append(ArrayItem(self, i, data[i]))
- self.reset("Sort demo, size %d" % self.size)
+ olditems = self.items
+ self.items = []
+ for item in olditems:
+ item.delete()
+ self.size = len(data)
+ self.maxvalue = max(data)
+ self.canvas.config(width=(self.size+1)*XGRID,
+ height=(self.maxvalue+1)*YGRID)
+ for i in range(self.size):
+ self.items.append(ArrayItem(self, i, data[i]))
+ self.reset("Sort demo, size %d" % self.size)
speed = "normal"
def setspeed(self, speed):
- self.speed = speed
+ self.speed = speed
def destroy(self):
- self.frame.destroy()
+ self.frame.destroy()
in_mainloop = 0
stop_mainloop = 0
def cancel(self):
- self.stop_mainloop = 1
- if self.in_mainloop:
- self.master.quit()
+ self.stop_mainloop = 1
+ if self.in_mainloop:
+ self.master.quit()
def step(self):
- if self.in_mainloop:
- self.master.quit()
+ if self.in_mainloop:
+ self.master.quit()
- Cancelled = "Array.Cancelled" # Exception
+ Cancelled = "Array.Cancelled" # Exception
def wait(self, msecs):
- if self.speed == "fastest":
- msecs = 0
- elif self.speed == "fast":
- msecs = msecs/10
- elif self.speed == "single-step":
- msecs = 1000000000
- if not self.stop_mainloop:
- self.master.update()
- id = self.master.after(msecs, self.master.quit)
- self.in_mainloop = 1
- self.master.mainloop()
- self.master.after_cancel(id)
- self.in_mainloop = 0
- if self.stop_mainloop:
- self.stop_mainloop = 0
- self.message("Cancelled")
- raise Array.Cancelled
+ if self.speed == "fastest":
+ msecs = 0
+ elif self.speed == "fast":
+ msecs = msecs/10
+ elif self.speed == "single-step":
+ msecs = 1000000000
+ if not self.stop_mainloop:
+ self.master.update()
+ id = self.master.after(msecs, self.master.quit)
+ self.in_mainloop = 1
+ self.master.mainloop()
+ self.master.after_cancel(id)
+ self.in_mainloop = 0
+ if self.stop_mainloop:
+ self.stop_mainloop = 0
+ self.message("Cancelled")
+ raise Array.Cancelled
def getsize(self):
- return self.size
+ return self.size
def show_partition(self, first, last):
- for i in range(self.size):
- item = self.items[i]
- if first <= i < last:
- item.item.config(fill='red')
- else:
- item.item.config(fill='orange')
- self.hide_left_right_pivot()
+ for i in range(self.size):
+ item = self.items[i]
+ if first <= i < last:
+ item.item.config(fill='red')
+ else:
+ item.item.config(fill='orange')
+ self.hide_left_right_pivot()
def hide_partition(self):
- for i in range(self.size):
- item = self.items[i]
- item.item.config(fill='red')
- self.hide_left_right_pivot()
+ for i in range(self.size):
+ item = self.items[i]
+ item.item.config(fill='red')
+ self.hide_left_right_pivot()
def show_left(self, left):
- if not 0 <= left < self.size:
- self.hide_left()
- return
- x1, y1, x2, y2 = self.items[left].position()
-## top, bot = HIRO
- self.left.coords([(x1-2, 0), (x1-2, 9999)])
- self.master.update()
+ if not 0 <= left < self.size:
+ self.hide_left()
+ return
+ x1, y1, x2, y2 = self.items[left].position()
+## top, bot = HIRO
+ self.left.coords([(x1-2, 0), (x1-2, 9999)])
+ self.master.update()
def show_right(self, right):
- if not 0 <= right < self.size:
- self.hide_right()
- return
- x1, y1, x2, y2 = self.items[right].position()
- self.right.coords(((x2+2, 0), (x2+2, 9999)))
- self.master.update()
+ if not 0 <= right < self.size:
+ self.hide_right()
+ return
+ x1, y1, x2, y2 = self.items[right].position()
+ self.right.coords(((x2+2, 0), (x2+2, 9999)))
+ self.master.update()
def hide_left_right_pivot(self):
- self.hide_left()
- self.hide_right()
- self.hide_pivot()
+ self.hide_left()
+ self.hide_right()
+ self.hide_pivot()
def hide_left(self):
- self.left.coords(((0, 0), (0, 0)))
+ self.left.coords(((0, 0), (0, 0)))
def hide_right(self):
- self.right.coords(((0, 0), (0, 0)))
+ self.right.coords(((0, 0), (0, 0)))
def show_pivot(self, pivot):
- x1, y1, x2, y2 = self.items[pivot].position()
- self.pivot.coords(((0, y1-2), (9999, y1-2)))
+ x1, y1, x2, y2 = self.items[pivot].position()
+ self.pivot.coords(((0, y1-2), (9999, y1-2)))
def hide_pivot(self):
- self.pivot.coords(((0, 0), (0, 0)))
+ self.pivot.coords(((0, 0), (0, 0)))
def swap(self, i, j):
- if i == j: return
- self.countswap()
- item = self.items[i]
- other = self.items[j]
- self.items[i], self.items[j] = other, item
- item.swapwith(other)
+ if i == j: return
+ self.countswap()
+ item = self.items[i]
+ other = self.items[j]
+ self.items[i], self.items[j] = other, item
+ item.swapwith(other)
def compare(self, i, j):
- self.countcompare()
- item = self.items[i]
- other = self.items[j]
- return item.compareto(other)
+ self.countcompare()
+ item = self.items[i]
+ other = self.items[j]
+ return item.compareto(other)
def reset(self, msg):
- self.ncompares = 0
- self.nswaps = 0
- self.message(msg)
- self.updatereport()
- self.hide_partition()
+ self.ncompares = 0
+ self.nswaps = 0
+ self.message(msg)
+ self.updatereport()
+ self.hide_partition()
def message(self, msg):
- self.label.config(text=msg)
+ self.label.config(text=msg)
def countswap(self):
- self.nswaps = self.nswaps + 1
- self.updatereport()
+ self.nswaps = self.nswaps + 1
+ self.updatereport()
def countcompare(self):
- self.ncompares = self.ncompares + 1
- self.updatereport()
+ self.ncompares = self.ncompares + 1
+ self.updatereport()
def updatereport(self):
- text = "%d cmps, %d swaps" % (self.ncompares, self.nswaps)
- self.report.config(text=text)
+ text = "%d cmps, %d swaps" % (self.ncompares, self.nswaps)
+ self.report.config(text=text)
class ArrayItem:
def __init__(self, array, index, value):
- self.array = array
- self.index = index
- self.value = value
- x1, y1, x2, y2 = self.position()
- self.item = Rectangle(array.canvas, x1, y1, x2, y2,
- fill='red', outline='black', width=1)
- self.item.bind('<Button-1>', self.mouse_down)
- self.item.bind('<Button1-Motion>', self.mouse_move)
- self.item.bind('<ButtonRelease-1>', self.mouse_up)
+ self.array = array
+ self.index = index
+ self.value = value
+ x1, y1, x2, y2 = self.position()
+ self.item = Rectangle(array.canvas, x1, y1, x2, y2,
+ fill='red', outline='black', width=1)
+ self.item.bind('<Button-1>', self.mouse_down)
+ self.item.bind('<Button1-Motion>', self.mouse_move)
+ self.item.bind('<ButtonRelease-1>', self.mouse_up)
def delete(self):
- item = self.item
- self.array = None
- self.item = None
- item.delete()
+ item = self.item
+ self.array = None
+ self.item = None
+ item.delete()
def mouse_down(self, event):
- self.lastx = event.x
- self.lasty = event.y
- self.origx = event.x
- self.origy = event.y
- self.item.tkraise()
-
+ self.lastx = event.x
+ self.lasty = event.y
+ self.origx = event.x
+ self.origy = event.y
+ self.item.tkraise()
+
def mouse_move(self, event):
- self.item.move(event.x - self.lastx, event.y - self.lasty)
- self.lastx = event.x
- self.lasty = event.y
+ self.item.move(event.x - self.lastx, event.y - self.lasty)
+ self.lastx = event.x
+ self.lasty = event.y
def mouse_up(self, event):
- i = self.nearestindex(event.x)
- if i >= self.array.getsize():
- i = self.array.getsize() - 1
- if i < 0:
- i = 0
- other = self.array.items[i]
- here = self.index
- self.array.items[here], self.array.items[i] = other, self
- self.index = i
- x1, y1, x2, y2 = self.position()
- self.item.coords(((x1, y1), (x2, y2)))
- other.setindex(here)
+ i = self.nearestindex(event.x)
+ if i >= self.array.getsize():
+ i = self.array.getsize() - 1
+ if i < 0:
+ i = 0
+ other = self.array.items[i]
+ here = self.index
+ self.array.items[here], self.array.items[i] = other, self
+ self.index = i
+ x1, y1, x2, y2 = self.position()
+ self.item.coords(((x1, y1), (x2, y2)))
+ other.setindex(here)
def setindex(self, index):
- nsteps = steps(self.index, index)
- if not nsteps: return
- if self.array.speed == "fastest":
- nsteps = 0
- oldpts = self.position()
- self.index = index
- newpts = self.position()
- trajectory = interpolate(oldpts, newpts, nsteps)
- self.item.tkraise()
- for pts in trajectory:
- self.item.coords((pts[:2], pts[2:]))
- self.array.wait(50)
+ nsteps = steps(self.index, index)
+ if not nsteps: return
+ if self.array.speed == "fastest":
+ nsteps = 0
+ oldpts = self.position()
+ self.index = index
+ newpts = self.position()
+ trajectory = interpolate(oldpts, newpts, nsteps)
+ self.item.tkraise()
+ for pts in trajectory:
+ self.item.coords((pts[:2], pts[2:]))
+ self.array.wait(50)
def swapwith(self, other):
- nsteps = steps(self.index, other.index)
- if not nsteps: return
- if self.array.speed == "fastest":
- nsteps = 0
- myoldpts = self.position()
- otheroldpts = other.position()
- self.index, other.index = other.index, self.index
- mynewpts = self.position()
- othernewpts = other.position()
- myfill = self.item['fill']
- otherfill = other.item['fill']
- self.item.config(fill='green')
- other.item.config(fill='yellow')
- self.array.master.update()
- if self.array.speed == "single-step":
- self.item.coords((mynewpts[:2], mynewpts[2:]))
- other.item.coords((othernewpts[:2], othernewpts[2:]))
- self.array.master.update()
- self.item.config(fill=myfill)
- other.item.config(fill=otherfill)
- self.array.wait(0)
- return
- mytrajectory = interpolate(myoldpts, mynewpts, nsteps)
- othertrajectory = interpolate(otheroldpts, othernewpts, nsteps)
- if self.value > other.value:
- self.item.tkraise()
- other.item.tkraise()
- else:
- other.item.tkraise()
- self.item.tkraise()
- try:
- for i in range(len(mytrajectory)):
- mypts = mytrajectory[i]
- otherpts = othertrajectory[i]
- self.item.coords((mypts[:2], mypts[2:]))
- other.item.coords((otherpts[:2], otherpts[2:]))
- self.array.wait(50)
- finally:
- mypts = mytrajectory[-1]
- otherpts = othertrajectory[-1]
- self.item.coords((mypts[:2], mypts[2:]))
- other.item.coords((otherpts[:2], otherpts[2:]))
- self.item.config(fill=myfill)
- other.item.config(fill=otherfill)
+ nsteps = steps(self.index, other.index)
+ if not nsteps: return
+ if self.array.speed == "fastest":
+ nsteps = 0
+ myoldpts = self.position()
+ otheroldpts = other.position()
+ self.index, other.index = other.index, self.index
+ mynewpts = self.position()
+ othernewpts = other.position()
+ myfill = self.item['fill']
+ otherfill = other.item['fill']
+ self.item.config(fill='green')
+ other.item.config(fill='yellow')
+ self.array.master.update()
+ if self.array.speed == "single-step":
+ self.item.coords((mynewpts[:2], mynewpts[2:]))
+ other.item.coords((othernewpts[:2], othernewpts[2:]))
+ self.array.master.update()
+ self.item.config(fill=myfill)
+ other.item.config(fill=otherfill)
+ self.array.wait(0)
+ return
+ mytrajectory = interpolate(myoldpts, mynewpts, nsteps)
+ othertrajectory = interpolate(otheroldpts, othernewpts, nsteps)
+ if self.value > other.value:
+ self.item.tkraise()
+ other.item.tkraise()
+ else:
+ other.item.tkraise()
+ self.item.tkraise()
+ try:
+ for i in range(len(mytrajectory)):
+ mypts = mytrajectory[i]
+ otherpts = othertrajectory[i]
+ self.item.coords((mypts[:2], mypts[2:]))
+ other.item.coords((otherpts[:2], otherpts[2:]))
+ self.array.wait(50)
+ finally:
+ mypts = mytrajectory[-1]
+ otherpts = othertrajectory[-1]
+ self.item.coords((mypts[:2], mypts[2:]))
+ other.item.coords((otherpts[:2], otherpts[2:]))
+ self.item.config(fill=myfill)
+ other.item.config(fill=otherfill)
def compareto(self, other):
- myfill = self.item['fill']
- otherfill = other.item['fill']
- outcome = cmp(self.value, other.value)
- if outcome < 0:
- myflash = 'white'
- otherflash = 'black'
- elif outcome > 0:
- myflash = 'black'
- otherflash = 'white'
- else:
- myflash = otherflash = 'grey'
- try:
- self.item.config(fill=myflash)
- other.item.config(fill=otherflash)
- self.array.wait(500)
- finally:
- self.item.config(fill=myfill)
- other.item.config(fill=otherfill)
- return outcome
+ myfill = self.item['fill']
+ otherfill = other.item['fill']
+ outcome = cmp(self.value, other.value)
+ if outcome < 0:
+ myflash = 'white'
+ otherflash = 'black'
+ elif outcome > 0:
+ myflash = 'black'
+ otherflash = 'white'
+ else:
+ myflash = otherflash = 'grey'
+ try:
+ self.item.config(fill=myflash)
+ other.item.config(fill=otherflash)
+ self.array.wait(500)
+ finally:
+ self.item.config(fill=myfill)
+ other.item.config(fill=otherfill)
+ return outcome
def position(self):
- x1 = (self.index+1)*XGRID - WIDTH/2
- x2 = x1+WIDTH
- y2 = (self.array.maxvalue+1)*YGRID
- y1 = y2 - (self.value)*YGRID
- return x1, y1, x2, y2
+ x1 = (self.index+1)*XGRID - WIDTH/2
+ x2 = x1+WIDTH
+ y2 = (self.array.maxvalue+1)*YGRID
+ y1 = y2 - (self.value)*YGRID
+ return x1, y1, x2, y2
def nearestindex(self, x):
- return int(round(float(x)/XGRID)) - 1
+ return int(round(float(x)/XGRID)) - 1
# Subroutines that don't need an object
@@ -335,22 +335,22 @@ class ArrayItem:
def steps(here, there):
nsteps = abs(here - there)
if nsteps <= 3:
- nsteps = nsteps * 3
+ nsteps = nsteps * 3
elif nsteps <= 5:
- nsteps = nsteps * 2
+ nsteps = nsteps * 2
elif nsteps > 10:
- nsteps = 10
+ nsteps = 10
return nsteps
def interpolate(oldpts, newpts, n):
if len(oldpts) != len(newpts):
- raise ValueError, "can't interpolate arrays of different length"
+ raise ValueError, "can't interpolate arrays of different length"
pts = [0]*len(oldpts)
res = [tuple(oldpts)]
for i in range(1, n):
- for k in range(len(pts)):
- pts[k] = oldpts[k] + (newpts[k] - oldpts[k])*i/n
- res.append(tuple(pts))
+ for k in range(len(pts)):
+ pts[k] = oldpts[k] + (newpts[k] - oldpts[k])*i/n
+ res.append(tuple(pts))
res.append(tuple(newpts))
return res
@@ -371,110 +371,110 @@ def randomize(array):
array.reset("Randomizing")
n = array.getsize()
for i in range(n):
- j = random.randint(0, n-1)
- array.swap(i, j)
+ j = random.randint(0, n-1)
+ array.swap(i, j)
array.message("Randomized")
def insertionsort(array):
size = array.getsize()
array.reset("Insertion sort")
for i in range(1, size):
- j = i-1
- while j >= 0:
- if array.compare(j, j+1) <= 0:
- break
- array.swap(j, j+1)
- j = j-1
+ j = i-1
+ while j >= 0:
+ if array.compare(j, j+1) <= 0:
+ break
+ array.swap(j, j+1)
+ j = j-1
array.message("Sorted")
def selectionsort(array):
size = array.getsize()
array.reset("Selection sort")
try:
- for i in range(size):
- array.show_partition(i, size)
- for j in range(i+1, size):
- if array.compare(i, j) > 0:
- array.swap(i, j)
- array.message("Sorted")
+ for i in range(size):
+ array.show_partition(i, size)
+ for j in range(i+1, size):
+ if array.compare(i, j) > 0:
+ array.swap(i, j)
+ array.message("Sorted")
finally:
- array.hide_partition()
+ array.hide_partition()
def bubblesort(array):
size = array.getsize()
array.reset("Bubble sort")
for i in range(size):
- for j in range(1, size):
- if array.compare(j-1, j) > 0:
- array.swap(j-1, j)
+ for j in range(1, size):
+ if array.compare(j-1, j) > 0:
+ array.swap(j-1, j)
array.message("Sorted")
def quicksort(array):
size = array.getsize()
array.reset("Quicksort")
try:
- stack = [(0, size)]
- while stack:
- first, last = stack[-1]
- del stack[-1]
- array.show_partition(first, last)
- if last-first < 5:
- array.message("Insertion sort")
- for i in range(first+1, last):
- j = i-1
- while j >= first:
- if array.compare(j, j+1) <= 0:
- break
- array.swap(j, j+1)
- j = j-1
- continue
- array.message("Choosing pivot")
- j, i, k = first, (first+last)/2, last-1
- if array.compare(k, i) < 0:
- array.swap(k, i)
- if array.compare(k, j) < 0:
- array.swap(k, j)
- if array.compare(j, i) < 0:
- array.swap(j, i)
- pivot = j
- array.show_pivot(pivot)
- array.message("Pivot at left of partition")
- array.wait(1000)
- left = first
- right = last
- while 1:
- array.message("Sweep right pointer")
- right = right-1
- array.show_right(right)
- while right > first and array.compare(right, pivot) >= 0:
- right = right-1
- array.show_right(right)
- array.message("Sweep left pointer")
- left = left+1
- array.show_left(left)
- while left < last and array.compare(left, pivot) <= 0:
- left = left+1
- array.show_left(left)
- if left > right:
- array.message("End of partition")
- break
- array.message("Swap items")
- array.swap(left, right)
- array.message("Swap pivot back")
- array.swap(pivot, right)
- n1 = right-first
- n2 = last-left
- if n1 > 1: stack.append((first, right))
- if n2 > 1: stack.append((left, last))
- array.message("Sorted")
+ stack = [(0, size)]
+ while stack:
+ first, last = stack[-1]
+ del stack[-1]
+ array.show_partition(first, last)
+ if last-first < 5:
+ array.message("Insertion sort")
+ for i in range(first+1, last):
+ j = i-1
+ while j >= first:
+ if array.compare(j, j+1) <= 0:
+ break
+ array.swap(j, j+1)
+ j = j-1
+ continue
+ array.message("Choosing pivot")
+ j, i, k = first, (first+last)/2, last-1
+ if array.compare(k, i) < 0:
+ array.swap(k, i)
+ if array.compare(k, j) < 0:
+ array.swap(k, j)
+ if array.compare(j, i) < 0:
+ array.swap(j, i)
+ pivot = j
+ array.show_pivot(pivot)
+ array.message("Pivot at left of partition")
+ array.wait(1000)
+ left = first
+ right = last
+ while 1:
+ array.message("Sweep right pointer")
+ right = right-1
+ array.show_right(right)
+ while right > first and array.compare(right, pivot) >= 0:
+ right = right-1
+ array.show_right(right)
+ array.message("Sweep left pointer")
+ left = left+1
+ array.show_left(left)
+ while left < last and array.compare(left, pivot) <= 0:
+ left = left+1
+ array.show_left(left)
+ if left > right:
+ array.message("End of partition")
+ break
+ array.message("Swap items")
+ array.swap(left, right)
+ array.message("Swap pivot back")
+ array.swap(pivot, right)
+ n1 = right-first
+ n2 = last-left
+ if n1 > 1: stack.append((first, right))
+ if n2 > 1: stack.append((left, last))
+ array.message("Sorted")
finally:
- array.hide_partition()
+ array.hide_partition()
def demosort(array):
while 1:
- for alg in [quicksort, insertionsort, selectionsort, bubblesort]:
- randomize(array)
- alg(array)
+ for alg in [quicksort, insertionsort, selectionsort, bubblesort]:
+ randomize(array)
+ alg(array)
# Sort demo class -- usable as a Grail applet
@@ -482,144 +482,144 @@ def demosort(array):
class SortDemo:
def __init__(self, master, size=15):
- self.master = master
- self.size = size
- self.busy = 0
- self.array = Array(self.master)
-
- self.botframe = Frame(master)
- self.botframe.pack(side=BOTTOM)
- self.botleftframe = Frame(self.botframe)
- self.botleftframe.pack(side=LEFT, fill=Y)
- self.botrightframe = Frame(self.botframe)
- self.botrightframe.pack(side=RIGHT, fill=Y)
-
- self.b_qsort = Button(self.botleftframe,
- text="Quicksort", command=self.c_qsort)
- self.b_qsort.pack(fill=X)
- self.b_isort = Button(self.botleftframe,
- text="Insertion sort", command=self.c_isort)
- self.b_isort.pack(fill=X)
- self.b_ssort = Button(self.botleftframe,
- text="Selection sort", command=self.c_ssort)
- self.b_ssort.pack(fill=X)
- self.b_bsort = Button(self.botleftframe,
- text="Bubble sort", command=self.c_bsort)
- self.b_bsort.pack(fill=X)
-
- # Terrible hack to overcome limitation of OptionMenu...
- class MyIntVar(IntVar):
- def __init__(self, master, demo):
- self.demo = demo
- IntVar.__init__(self, master)
- def set(self, value):
- IntVar.set(self, value)
- if str(value) != '0':
- self.demo.resize(value)
-
- self.v_size = MyIntVar(self.master, self)
- self.v_size.set(size)
- sizes = [1, 2, 3, 4] + range(5, 55, 5)
- if self.size not in sizes:
- sizes.append(self.size)
- sizes.sort()
- self.m_size = apply(OptionMenu,
- (self.botleftframe, self.v_size) + tuple(sizes))
- self.m_size.pack(fill=X)
-
- self.v_speed = StringVar(self.master)
- self.v_speed.set("normal")
- self.m_speed = OptionMenu(self.botleftframe, self.v_speed,
- "single-step", "normal", "fast", "fastest")
- self.m_speed.pack(fill=X)
-
- self.b_step = Button(self.botleftframe,
- text="Step", command=self.c_step)
- self.b_step.pack(fill=X)
-
- self.b_randomize = Button(self.botrightframe,
- text="Randomize", command=self.c_randomize)
- self.b_randomize.pack(fill=X)
- self.b_uniform = Button(self.botrightframe,
- text="Uniform", command=self.c_uniform)
- self.b_uniform.pack(fill=X)
- self.b_distinct = Button(self.botrightframe,
- text="Distinct", command=self.c_distinct)
- self.b_distinct.pack(fill=X)
- self.b_demo = Button(self.botrightframe,
- text="Demo", command=self.c_demo)
- self.b_demo.pack(fill=X)
- self.b_cancel = Button(self.botrightframe,
- text="Cancel", command=self.c_cancel)
- self.b_cancel.pack(fill=X)
- self.b_cancel.config(state=DISABLED)
- self.b_quit = Button(self.botrightframe,
- text="Quit", command=self.c_quit)
- self.b_quit.pack(fill=X)
+ self.master = master
+ self.size = size
+ self.busy = 0
+ self.array = Array(self.master)
+
+ self.botframe = Frame(master)
+ self.botframe.pack(side=BOTTOM)
+ self.botleftframe = Frame(self.botframe)
+ self.botleftframe.pack(side=LEFT, fill=Y)
+ self.botrightframe = Frame(self.botframe)
+ self.botrightframe.pack(side=RIGHT, fill=Y)
+
+ self.b_qsort = Button(self.botleftframe,
+ text="Quicksort", command=self.c_qsort)
+ self.b_qsort.pack(fill=X)
+ self.b_isort = Button(self.botleftframe,
+ text="Insertion sort", command=self.c_isort)
+ self.b_isort.pack(fill=X)
+ self.b_ssort = Button(self.botleftframe,
+ text="Selection sort", command=self.c_ssort)
+ self.b_ssort.pack(fill=X)
+ self.b_bsort = Button(self.botleftframe,
+ text="Bubble sort", command=self.c_bsort)
+ self.b_bsort.pack(fill=X)
+
+ # Terrible hack to overcome limitation of OptionMenu...
+ class MyIntVar(IntVar):
+ def __init__(self, master, demo):
+ self.demo = demo
+ IntVar.__init__(self, master)
+ def set(self, value):
+ IntVar.set(self, value)
+ if str(value) != '0':
+ self.demo.resize(value)
+
+ self.v_size = MyIntVar(self.master, self)
+ self.v_size.set(size)
+ sizes = [1, 2, 3, 4] + range(5, 55, 5)
+ if self.size not in sizes:
+ sizes.append(self.size)
+ sizes.sort()
+ self.m_size = apply(OptionMenu,
+ (self.botleftframe, self.v_size) + tuple(sizes))
+ self.m_size.pack(fill=X)
+
+ self.v_speed = StringVar(self.master)
+ self.v_speed.set("normal")
+ self.m_speed = OptionMenu(self.botleftframe, self.v_speed,
+ "single-step", "normal", "fast", "fastest")
+ self.m_speed.pack(fill=X)
+
+ self.b_step = Button(self.botleftframe,
+ text="Step", command=self.c_step)
+ self.b_step.pack(fill=X)
+
+ self.b_randomize = Button(self.botrightframe,
+ text="Randomize", command=self.c_randomize)
+ self.b_randomize.pack(fill=X)
+ self.b_uniform = Button(self.botrightframe,
+ text="Uniform", command=self.c_uniform)
+ self.b_uniform.pack(fill=X)
+ self.b_distinct = Button(self.botrightframe,
+ text="Distinct", command=self.c_distinct)
+ self.b_distinct.pack(fill=X)
+ self.b_demo = Button(self.botrightframe,
+ text="Demo", command=self.c_demo)
+ self.b_demo.pack(fill=X)
+ self.b_cancel = Button(self.botrightframe,
+ text="Cancel", command=self.c_cancel)
+ self.b_cancel.pack(fill=X)
+ self.b_cancel.config(state=DISABLED)
+ self.b_quit = Button(self.botrightframe,
+ text="Quit", command=self.c_quit)
+ self.b_quit.pack(fill=X)
def resize(self, newsize):
- if self.busy:
- self.master.bell()
- return
- self.size = newsize
- self.array.setdata(range(1, self.size+1))
+ if self.busy:
+ self.master.bell()
+ return
+ self.size = newsize
+ self.array.setdata(range(1, self.size+1))
def c_qsort(self):
- self.run(quicksort)
+ self.run(quicksort)
def c_isort(self):
- self.run(insertionsort)
+ self.run(insertionsort)
def c_ssort(self):
- self.run(selectionsort)
+ self.run(selectionsort)
def c_bsort(self):
- self.run(bubblesort)
+ self.run(bubblesort)
def c_demo(self):
- self.run(demosort)
+ self.run(demosort)
def c_randomize(self):
- self.run(randomize)
+ self.run(randomize)
def c_uniform(self):
- self.run(uniform)
+ self.run(uniform)
def c_distinct(self):
- self.run(distinct)
+ self.run(distinct)
def run(self, func):
- if self.busy:
- self.master.bell()
- return
- self.busy = 1
- self.array.setspeed(self.v_speed.get())
- self.b_cancel.config(state=NORMAL)
- try:
- func(self.array)
- except Array.Cancelled:
- pass
- self.b_cancel.config(state=DISABLED)
- self.busy = 0
+ if self.busy:
+ self.master.bell()
+ return
+ self.busy = 1
+ self.array.setspeed(self.v_speed.get())
+ self.b_cancel.config(state=NORMAL)
+ try:
+ func(self.array)
+ except Array.Cancelled:
+ pass
+ self.b_cancel.config(state=DISABLED)
+ self.busy = 0
def c_cancel(self):
- if not self.busy:
- self.master.bell()
- return
- self.array.cancel()
+ if not self.busy:
+ self.master.bell()
+ return
+ self.array.cancel()
def c_step(self):
- if not self.busy:
- self.master.bell()
- return
- self.v_speed.set("single-step")
- self.array.setspeed("single-step")
- self.array.step()
+ if not self.busy:
+ self.master.bell()
+ return
+ self.v_speed.set("single-step")
+ self.array.setspeed("single-step")
+ self.array.step()
def c_quit(self):
- if self.busy:
- self.array.cancel()
- self.master.after_idle(self.master.quit)
+ if self.busy:
+ self.array.cancel()
+ self.master.after_idle(self.master.quit)
# Main program -- for stand-alone operation outside Grail
diff --git a/Demo/tkinter/guido/ss1.py b/Demo/tkinter/guido/ss1.py
index 95b3d813d9..89354753e6 100644
--- a/Demo/tkinter/guido/ss1.py
+++ b/Demo/tkinter/guido/ss1.py
@@ -315,7 +315,7 @@ class BaseCell:
"""Abstract base class for sheet cells.
Subclasses may but needn't provide the following APIs:
-
+
cell.reset() -- prepare for recalculation
cell.recalc(rexec) -> value -- recalculate formula
cell.format() -> (value, alignment) -- return formatted value
diff --git a/Demo/tkinter/guido/svkill.py b/Demo/tkinter/guido/svkill.py
index 1c54e4b165..69f7f3b168 100755
--- a/Demo/tkinter/guido/svkill.py
+++ b/Demo/tkinter/guido/svkill.py
@@ -5,7 +5,7 @@
from Tkinter import *
if TkVersion < 4.0:
- raise ImportError, "This version of svkill requires Tk 4.0 or later"
+ raise ImportError, "This version of svkill requires Tk 4.0 or later"
from string import splitfields
from string import split
@@ -15,114 +15,114 @@ import os
user = os.environ['LOGNAME']
class BarButton(Menubutton):
- def __init__(self, master=None, **cnf):
- apply(Menubutton.__init__, (self, master), cnf)
- self.pack(side=LEFT)
- self.menu = Menu(self, name='menu')
- self['menu'] = self.menu
+ def __init__(self, master=None, **cnf):
+ apply(Menubutton.__init__, (self, master), cnf)
+ self.pack(side=LEFT)
+ self.menu = Menu(self, name='menu')
+ self['menu'] = self.menu
class Kill(Frame):
- # List of (name, option, pid_column)
- view_list = [
- ('Default', ''),
- ('Every (-e)', '-e'),
- ('Non process group leaders (-d)', '-d'),
- ('Non leaders with tty (-a)', '-a'),
- ('For this user (-u %s)' % user, '-u %s' % user),
- ]
- format_list = [
- ('Default', '', 0),
- ('Long (-l)', '-l', 3),
- ('Full (-f)', '-f', 1),
- ('Full Long (-f -l)', '-l -f', 3),
- ('Session and group ID (-j)', '-j', 0),
- ('Scheduler properties (-c)', '-c', 0),
- ]
- def kill(self, selected):
- c = self.format_list[self.format.get()][2]
- pid = split(selected)[c]
- os.system('kill -9 ' + pid)
- self.do_update()
- def do_update(self):
- format = self.format_list[self.format.get()][1]
- view = self.view_list[self.view.get()][1]
- s = commands.getoutput('ps %s %s' % (view, format))
- list = splitfields(s, '\n')
- self.header.set(list[0] + ' ')
- del list[0]
- self.frame.list.delete(0, AtEnd())
- for line in list:
- self.frame.list.insert(0, line)
- def do_motion(self, e):
- e.widget.select_clear('0', 'end')
- e.widget.select_set(e.widget.nearest(e.y))
- def do_leave(self, e):
- e.widget.select_clear('0', 'end')
- def do_1(self, e):
- self.kill(e.widget.get(e.widget.nearest(e.y)))
- def __init__(self, master=None, **cnf):
- apply(Frame.__init__, (self, master), cnf)
- self.pack(expand=1, fill=BOTH)
- self.bar = Frame(self, name='bar', relief=RAISED,
- borderwidth=2)
- self.bar.pack(fill=X)
- self.bar.file = BarButton(self.bar, text='File')
- self.bar.file.menu.add_command(
- label='Quit', command=self.quit)
- self.bar.view = BarButton(self.bar, text='View')
- self.bar.format = BarButton(self.bar, text='Format')
- self.view = IntVar(self)
- self.view.set(0)
- self.format = IntVar(self)
- self.format.set(0)
- for num in range(len(self.view_list)):
- label, option = self.view_list[num]
- self.bar.view.menu.add_radiobutton(
- label=label,
- command=self.do_update,
- variable=self.view,
- value=num)
- for num in range(len(self.format_list)):
- label, option, col = self.format_list[num]
- self.bar.format.menu.add_radiobutton(
- label=label,
- command=self.do_update,
- variable=self.format,
- value=num)
- self.bar.tk_menuBar(self.bar.file,
- self.bar.view,
- self.bar.format)
- self.frame = Frame(self, relief=RAISED, borderwidth=2)
- self.frame.pack(expand=1, fill=BOTH)
- self.header = StringVar(self)
- self.frame.label = Label(
- self.frame, relief=FLAT, anchor=NW, borderwidth=0,
- font='*-Courier-Bold-R-Normal-*-120-*',
- textvariable=self.header)
- self.frame.label.pack(fill=Y, anchor=W)
- self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL)
- self.frame.list = Listbox(
- self.frame,
- relief=SUNKEN,
- font='*-Courier-Medium-R-Normal-*-120-*',
- width=40, height=10,
- selectbackground='#eed5b7',
- selectborderwidth=0,
- selectmode=BROWSE,
- yscroll=self.frame.vscroll.set)
- self.frame.vscroll['command'] = self.frame.list.yview
- self.frame.vscroll.pack(side=RIGHT, fill=Y)
- self.frame.list.pack(expand=1, fill=BOTH)
- self.update = Button(self, text='Update',
- command=self.do_update)
- self.update.pack(fill=X)
- self.frame.list.bind('<Motion>', self.do_motion)
- self.frame.list.bind('<Leave>', self.do_leave)
- self.frame.list.bind('<1>', self.do_1)
- self.do_update()
+ # List of (name, option, pid_column)
+ view_list = [
+ ('Default', ''),
+ ('Every (-e)', '-e'),
+ ('Non process group leaders (-d)', '-d'),
+ ('Non leaders with tty (-a)', '-a'),
+ ('For this user (-u %s)' % user, '-u %s' % user),
+ ]
+ format_list = [
+ ('Default', '', 0),
+ ('Long (-l)', '-l', 3),
+ ('Full (-f)', '-f', 1),
+ ('Full Long (-f -l)', '-l -f', 3),
+ ('Session and group ID (-j)', '-j', 0),
+ ('Scheduler properties (-c)', '-c', 0),
+ ]
+ def kill(self, selected):
+ c = self.format_list[self.format.get()][2]
+ pid = split(selected)[c]
+ os.system('kill -9 ' + pid)
+ self.do_update()
+ def do_update(self):
+ format = self.format_list[self.format.get()][1]
+ view = self.view_list[self.view.get()][1]
+ s = commands.getoutput('ps %s %s' % (view, format))
+ list = splitfields(s, '\n')
+ self.header.set(list[0] + ' ')
+ del list[0]
+ self.frame.list.delete(0, AtEnd())
+ for line in list:
+ self.frame.list.insert(0, line)
+ def do_motion(self, e):
+ e.widget.select_clear('0', 'end')
+ e.widget.select_set(e.widget.nearest(e.y))
+ def do_leave(self, e):
+ e.widget.select_clear('0', 'end')
+ def do_1(self, e):
+ self.kill(e.widget.get(e.widget.nearest(e.y)))
+ def __init__(self, master=None, **cnf):
+ apply(Frame.__init__, (self, master), cnf)
+ self.pack(expand=1, fill=BOTH)
+ self.bar = Frame(self, name='bar', relief=RAISED,
+ borderwidth=2)
+ self.bar.pack(fill=X)
+ self.bar.file = BarButton(self.bar, text='File')
+ self.bar.file.menu.add_command(
+ label='Quit', command=self.quit)
+ self.bar.view = BarButton(self.bar, text='View')
+ self.bar.format = BarButton(self.bar, text='Format')
+ self.view = IntVar(self)
+ self.view.set(0)
+ self.format = IntVar(self)
+ self.format.set(0)
+ for num in range(len(self.view_list)):
+ label, option = self.view_list[num]
+ self.bar.view.menu.add_radiobutton(
+ label=label,
+ command=self.do_update,
+ variable=self.view,
+ value=num)
+ for num in range(len(self.format_list)):
+ label, option, col = self.format_list[num]
+ self.bar.format.menu.add_radiobutton(
+ label=label,
+ command=self.do_update,
+ variable=self.format,
+ value=num)
+ self.bar.tk_menuBar(self.bar.file,
+ self.bar.view,
+ self.bar.format)
+ self.frame = Frame(self, relief=RAISED, borderwidth=2)
+ self.frame.pack(expand=1, fill=BOTH)
+ self.header = StringVar(self)
+ self.frame.label = Label(
+ self.frame, relief=FLAT, anchor=NW, borderwidth=0,
+ font='*-Courier-Bold-R-Normal-*-120-*',
+ textvariable=self.header)
+ self.frame.label.pack(fill=Y, anchor=W)
+ self.frame.vscroll = Scrollbar(self.frame, orient=VERTICAL)
+ self.frame.list = Listbox(
+ self.frame,
+ relief=SUNKEN,
+ font='*-Courier-Medium-R-Normal-*-120-*',
+ width=40, height=10,
+ selectbackground='#eed5b7',
+ selectborderwidth=0,
+ selectmode=BROWSE,
+ yscroll=self.frame.vscroll.set)
+ self.frame.vscroll['command'] = self.frame.list.yview
+ self.frame.vscroll.pack(side=RIGHT, fill=Y)
+ self.frame.list.pack(expand=1, fill=BOTH)
+ self.update = Button(self, text='Update',
+ command=self.do_update)
+ self.update.pack(fill=X)
+ self.frame.list.bind('<Motion>', self.do_motion)
+ self.frame.list.bind('<Leave>', self.do_leave)
+ self.frame.list.bind('<1>', self.do_1)
+ self.do_update()
if __name__ == '__main__':
- kill = Kill(None, borderwidth=5)
- kill.winfo_toplevel().title('Tkinter Process Killer (SYSV)')
- kill.winfo_toplevel().minsize(1, 1)
- kill.mainloop()
+ kill = Kill(None, borderwidth=5)
+ kill.winfo_toplevel().title('Tkinter Process Killer (SYSV)')
+ kill.winfo_toplevel().minsize(1, 1)
+ kill.mainloop()
diff --git a/Demo/tkinter/guido/tkman.py b/Demo/tkinter/guido/tkman.py
index 84672fc9c1..11d9690a12 100755
--- a/Demo/tkinter/guido/tkman.py
+++ b/Demo/tkinter/guido/tkman.py
@@ -15,253 +15,253 @@ MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/local/man/man3']
foundmanndir = 0
for dir in MANNDIRLIST:
if os.path.exists(dir):
- MANNDIR = dir
- foundmanndir = 1
+ MANNDIR = dir
+ foundmanndir = 1
foundman3dir = 0
for dir in MAN3DIRLIST:
if os.path.exists(dir):
- MAN3DIR = dir
- foundman3dir = 1
+ MAN3DIR = dir
+ foundman3dir = 1
if not foundmanndir or not foundman3dir:
sys.stderr.write('\n')
if not foundmanndir:
- msg = """\
+ msg = """\
Failed to find mann directory.
-Please add the correct entry to the MANNDIRLIST
+Please add the correct entry to the MANNDIRLIST
at the top of %s script.""" % \
sys.argv[0]
- sys.stderr.write("%s\n\n" % msg)
+ sys.stderr.write("%s\n\n" % msg)
if not foundman3dir:
- msg = """\
+ msg = """\
Failed to find man3 directory.
-Please add the correct entry to the MAN3DIRLIST
+Please add the correct entry to the MAN3DIRLIST
at the top of %s script.""" % \
sys.argv[0]
- sys.stderr.write("%s\n\n" % msg)
+ sys.stderr.write("%s\n\n" % msg)
sys.exit(1)
del foundmanndir
del foundman3dir
def listmanpages(mandir):
- files = os.listdir(mandir)
- names = []
- for file in files:
- if file[-2:-1] == '.' and (file[-1] in 'ln123456789'):
- names.append(file[:-2])
- names.sort()
- return names
+ files = os.listdir(mandir)
+ names = []
+ for file in files:
+ if file[-2:-1] == '.' and (file[-1] in 'ln123456789'):
+ names.append(file[:-2])
+ names.sort()
+ return names
class SelectionBox:
- def __init__(self, master=None):
- self.choices = []
+ def __init__(self, master=None):
+ self.choices = []
- self.frame = Frame(master, name="frame")
- self.frame.pack(expand=1, fill=BOTH)
- self.master = self.frame.master
- self.subframe = Frame(self.frame, name="subframe")
- self.subframe.pack(expand=0, fill=BOTH)
- self.leftsubframe = Frame(self.subframe, name='leftsubframe')
- self.leftsubframe.pack(side=LEFT, expand=1, fill=BOTH)
- self.rightsubframe = Frame(self.subframe, name='rightsubframe')
- self.rightsubframe.pack(side=RIGHT, expand=1, fill=BOTH)
- self.chaptervar = StringVar(master)
- self.chapter = Menubutton(self.rightsubframe, name='chapter',
- text='Directory', relief=RAISED,
- borderwidth=2)
- self.chapter.pack(side=TOP)
- self.chaptermenu = Menu(self.chapter, name='chaptermenu')
- self.chaptermenu.add_radiobutton(label='C functions',
- value=MAN3DIR,
- variable=self.chaptervar,
- command=self.newchapter)
- self.chaptermenu.add_radiobutton(label='Tcl/Tk functions',
- value=MANNDIR,
- variable=self.chaptervar,
- command=self.newchapter)
- self.chapter['menu'] = self.chaptermenu
- self.listbox = Listbox(self.rightsubframe, name='listbox',
- relief=SUNKEN, borderwidth=2,
- width=20, height=5)
- self.listbox.pack(expand=1, fill=BOTH)
- self.l1 = Button(self.leftsubframe, name='l1',
- text='Display manual page named:',
- command=self.entry_cb)
- self.l1.pack(side=TOP)
- self.entry = Entry(self.leftsubframe, name='entry',
- relief=SUNKEN, borderwidth=2,
- width=20)
- self.entry.pack(expand=0, fill=X)
- self.l2frame = Frame(self.leftsubframe, name='l2frame')
- self.l2frame.pack(expand=0, fill=NONE)
- self.l2 = Button(self.l2frame, name='l2',
- text='Search regexp:',
- command=self.search_cb)
- self.l2.pack(side=LEFT)
- self.casevar = BooleanVar()
- self.casesense = Checkbutton(self.l2frame, name='casesense',
- text='Case sensitive',
- variable=self.casevar,
- relief=FLAT)
- self.casesense.pack(side=LEFT)
- self.search = Entry(self.leftsubframe, name='search',
- relief=SUNKEN, borderwidth=2,
- width=20)
- self.search.pack(expand=0, fill=X)
- self.title = Label(self.leftsubframe, name='title',
- text='(none)')
- self.title.pack(side=BOTTOM)
- self.text = ManPage(self.frame, name='text',
- relief=SUNKEN, borderwidth=2,
- wrap=NONE, width=72,
- selectbackground='pink')
- self.text.pack(expand=1, fill=BOTH)
+ self.frame = Frame(master, name="frame")
+ self.frame.pack(expand=1, fill=BOTH)
+ self.master = self.frame.master
+ self.subframe = Frame(self.frame, name="subframe")
+ self.subframe.pack(expand=0, fill=BOTH)
+ self.leftsubframe = Frame(self.subframe, name='leftsubframe')
+ self.leftsubframe.pack(side=LEFT, expand=1, fill=BOTH)
+ self.rightsubframe = Frame(self.subframe, name='rightsubframe')
+ self.rightsubframe.pack(side=RIGHT, expand=1, fill=BOTH)
+ self.chaptervar = StringVar(master)
+ self.chapter = Menubutton(self.rightsubframe, name='chapter',
+ text='Directory', relief=RAISED,
+ borderwidth=2)
+ self.chapter.pack(side=TOP)
+ self.chaptermenu = Menu(self.chapter, name='chaptermenu')
+ self.chaptermenu.add_radiobutton(label='C functions',
+ value=MAN3DIR,
+ variable=self.chaptervar,
+ command=self.newchapter)
+ self.chaptermenu.add_radiobutton(label='Tcl/Tk functions',
+ value=MANNDIR,
+ variable=self.chaptervar,
+ command=self.newchapter)
+ self.chapter['menu'] = self.chaptermenu
+ self.listbox = Listbox(self.rightsubframe, name='listbox',
+ relief=SUNKEN, borderwidth=2,
+ width=20, height=5)
+ self.listbox.pack(expand=1, fill=BOTH)
+ self.l1 = Button(self.leftsubframe, name='l1',
+ text='Display manual page named:',
+ command=self.entry_cb)
+ self.l1.pack(side=TOP)
+ self.entry = Entry(self.leftsubframe, name='entry',
+ relief=SUNKEN, borderwidth=2,
+ width=20)
+ self.entry.pack(expand=0, fill=X)
+ self.l2frame = Frame(self.leftsubframe, name='l2frame')
+ self.l2frame.pack(expand=0, fill=NONE)
+ self.l2 = Button(self.l2frame, name='l2',
+ text='Search regexp:',
+ command=self.search_cb)
+ self.l2.pack(side=LEFT)
+ self.casevar = BooleanVar()
+ self.casesense = Checkbutton(self.l2frame, name='casesense',
+ text='Case sensitive',
+ variable=self.casevar,
+ relief=FLAT)
+ self.casesense.pack(side=LEFT)
+ self.search = Entry(self.leftsubframe, name='search',
+ relief=SUNKEN, borderwidth=2,
+ width=20)
+ self.search.pack(expand=0, fill=X)
+ self.title = Label(self.leftsubframe, name='title',
+ text='(none)')
+ self.title.pack(side=BOTTOM)
+ self.text = ManPage(self.frame, name='text',
+ relief=SUNKEN, borderwidth=2,
+ wrap=NONE, width=72,
+ selectbackground='pink')
+ self.text.pack(expand=1, fill=BOTH)
- self.entry.bind('<Return>', self.entry_cb)
- self.search.bind('<Return>', self.search_cb)
- self.listbox.bind('<Double-1>', self.listbox_cb)
+ self.entry.bind('<Return>', self.entry_cb)
+ self.search.bind('<Return>', self.search_cb)
+ self.listbox.bind('<Double-1>', self.listbox_cb)
- self.entry.bind('<Tab>', self.entry_tab)
- self.search.bind('<Tab>', self.search_tab)
- self.text.bind('<Tab>', self.text_tab)
+ self.entry.bind('<Tab>', self.entry_tab)
+ self.search.bind('<Tab>', self.search_tab)
+ self.text.bind('<Tab>', self.text_tab)
- self.entry.focus_set()
+ self.entry.focus_set()
- self.chaptervar.set(MANNDIR)
- self.newchapter()
+ self.chaptervar.set(MANNDIR)
+ self.newchapter()
- def newchapter(self):
- mandir = self.chaptervar.get()
- self.choices = []
- self.addlist(listmanpages(mandir))
+ def newchapter(self):
+ mandir = self.chaptervar.get()
+ self.choices = []
+ self.addlist(listmanpages(mandir))
- def addchoice(self, choice):
- if choice not in self.choices:
- self.choices.append(choice)
- self.choices.sort()
- self.update()
+ def addchoice(self, choice):
+ if choice not in self.choices:
+ self.choices.append(choice)
+ self.choices.sort()
+ self.update()
- def addlist(self, list):
- self.choices[len(self.choices):] = list
- self.choices.sort()
- self.update()
+ def addlist(self, list):
+ self.choices[len(self.choices):] = list
+ self.choices.sort()
+ self.update()
- def entry_cb(self, *e):
- self.update()
+ def entry_cb(self, *e):
+ self.update()
- def listbox_cb(self, e):
- selection = self.listbox.curselection()
- if selection and len(selection) == 1:
- name = self.listbox.get(selection[0])
- self.show_page(name)
+ def listbox_cb(self, e):
+ selection = self.listbox.curselection()
+ if selection and len(selection) == 1:
+ name = self.listbox.get(selection[0])
+ self.show_page(name)
- def search_cb(self, *e):
- self.search_string(self.search.get())
+ def search_cb(self, *e):
+ self.search_string(self.search.get())
- def entry_tab(self, e):
- self.search.focus_set()
+ def entry_tab(self, e):
+ self.search.focus_set()
- def search_tab(self, e):
- self.entry.focus_set()
+ def search_tab(self, e):
+ self.entry.focus_set()
- def text_tab(self, e):
- self.entry.focus_set()
+ def text_tab(self, e):
+ self.entry.focus_set()
- def updatelist(self):
- key = self.entry.get()
- ok = filter(lambda name, key=key, n=len(key): name[:n]==key,
- self.choices)
- if not ok:
- self.frame.bell()
- self.listbox.delete(0, AtEnd())
- exactmatch = 0
- for item in ok:
- if item == key: exactmatch = 1
- self.listbox.insert(AtEnd(), item)
- if exactmatch:
- return key
- n = self.listbox.size()
- if n == 1:
- return self.listbox.get(0)
- # Else return None, meaning not a unique selection
+ def updatelist(self):
+ key = self.entry.get()
+ ok = filter(lambda name, key=key, n=len(key): name[:n]==key,
+ self.choices)
+ if not ok:
+ self.frame.bell()
+ self.listbox.delete(0, AtEnd())
+ exactmatch = 0
+ for item in ok:
+ if item == key: exactmatch = 1
+ self.listbox.insert(AtEnd(), item)
+ if exactmatch:
+ return key
+ n = self.listbox.size()
+ if n == 1:
+ return self.listbox.get(0)
+ # Else return None, meaning not a unique selection
- def update(self):
- name = self.updatelist()
- if name:
- self.show_page(name)
- self.entry.delete(0, AtEnd())
- self.updatelist()
+ def update(self):
+ name = self.updatelist()
+ if name:
+ self.show_page(name)
+ self.entry.delete(0, AtEnd())
+ self.updatelist()
- def show_page(self, name):
- file = '%s/%s.?' % (self.chaptervar.get(), name)
- fp = os.popen('nroff -man %s | ul -i' % file, 'r')
- self.text.kill()
- self.title['text'] = name
- self.text.parsefile(fp)
+ def show_page(self, name):
+ file = '%s/%s.?' % (self.chaptervar.get(), name)
+ fp = os.popen('nroff -man %s | ul -i' % file, 'r')
+ self.text.kill()
+ self.title['text'] = name
+ self.text.parsefile(fp)
- def search_string(self, search):
- if not search:
- self.frame.bell()
- print 'Empty search string'
- return
- if not self.casevar.get():
- map = regex.casefold
- else:
- map = None
- try:
- if map:
- prog = regex.compile(search, map)
- else:
- prog = regex.compile(search)
- except regex.error, msg:
- self.frame.bell()
- print 'Regex error:', msg
- return
- here = self.text.index(AtInsert())
- lineno = string.atoi(here[:string.find(here, '.')])
- end = self.text.index(AtEnd())
- endlineno = string.atoi(end[:string.find(end, '.')])
- wraplineno = lineno
- found = 0
- while 1:
- lineno = lineno + 1
- if lineno > endlineno:
- if wraplineno <= 0:
- break
- endlineno = wraplineno
- lineno = 0
- wraplineno = 0
- line = self.text.get('%d.0 linestart' % lineno,
- '%d.0 lineend' % lineno)
- i = prog.search(line)
- if i >= 0:
- found = 1
- n = max(1, len(prog.group(0)))
- try:
- self.text.tag_remove('sel',
- AtSelFirst(),
- AtSelLast())
- except TclError:
- pass
- self.text.tag_add('sel',
- '%d.%d' % (lineno, i),
- '%d.%d' % (lineno, i+n))
- self.text.mark_set(AtInsert(),
- '%d.%d' % (lineno, i))
- self.text.yview_pickplace(AtInsert())
- break
- if not found:
- self.frame.bell()
+ def search_string(self, search):
+ if not search:
+ self.frame.bell()
+ print 'Empty search string'
+ return
+ if not self.casevar.get():
+ map = regex.casefold
+ else:
+ map = None
+ try:
+ if map:
+ prog = regex.compile(search, map)
+ else:
+ prog = regex.compile(search)
+ except regex.error, msg:
+ self.frame.bell()
+ print 'Regex error:', msg
+ return
+ here = self.text.index(AtInsert())
+ lineno = string.atoi(here[:string.find(here, '.')])
+ end = self.text.index(AtEnd())
+ endlineno = string.atoi(end[:string.find(end, '.')])
+ wraplineno = lineno
+ found = 0
+ while 1:
+ lineno = lineno + 1
+ if lineno > endlineno:
+ if wraplineno <= 0:
+ break
+ endlineno = wraplineno
+ lineno = 0
+ wraplineno = 0
+ line = self.text.get('%d.0 linestart' % lineno,
+ '%d.0 lineend' % lineno)
+ i = prog.search(line)
+ if i >= 0:
+ found = 1
+ n = max(1, len(prog.group(0)))
+ try:
+ self.text.tag_remove('sel',
+ AtSelFirst(),
+ AtSelLast())
+ except TclError:
+ pass
+ self.text.tag_add('sel',
+ '%d.%d' % (lineno, i),
+ '%d.%d' % (lineno, i+n))
+ self.text.mark_set(AtInsert(),
+ '%d.%d' % (lineno, i))
+ self.text.yview_pickplace(AtInsert())
+ break
+ if not found:
+ self.frame.bell()
def main():
- root = Tk()
- sb = SelectionBox(root)
- if sys.argv[1:]:
- sb.show_page(sys.argv[1])
- root.minsize(1, 1)
- root.mainloop()
+ root = Tk()
+ sb = SelectionBox(root)
+ if sys.argv[1:]:
+ sb.show_page(sys.argv[1])
+ root.minsize(1, 1)
+ root.mainloop()
main()
diff --git a/Demo/tkinter/guido/wish.py b/Demo/tkinter/guido/wish.py
index 4f6fdee903..0a61ad88d8 100755
--- a/Demo/tkinter/guido/wish.py
+++ b/Demo/tkinter/guido/wish.py
@@ -9,19 +9,19 @@ tk.call('update')
cmd = ''
while 1:
- if cmd: prompt = ''
- else: prompt = '% '
- try:
- line = raw_input(prompt)
- except EOFError:
- break
- cmd = cmd + (line + '\n')
- if tk.getboolean(tk.call('info', 'complete', cmd)):
- tk.record(line)
- try:
- result = tk.call('eval', cmd)
- except _tkinter.TclError, msg:
- print 'TclError:', msg
- else:
- if result: print result
- cmd = ''
+ if cmd: prompt = ''
+ else: prompt = '% '
+ try:
+ line = raw_input(prompt)
+ except EOFError:
+ break
+ cmd = cmd + (line + '\n')
+ if tk.getboolean(tk.call('info', 'complete', cmd)):
+ tk.record(line)
+ try:
+ result = tk.call('eval', cmd)
+ except _tkinter.TclError, msg:
+ print 'TclError:', msg
+ else:
+ if result: print result
+ cmd = ''
diff --git a/Demo/tkinter/matt/00-HELLO-WORLD.py b/Demo/tkinter/matt/00-HELLO-WORLD.py
index a32941ba48..1c3151b117 100644
--- a/Demo/tkinter/matt/00-HELLO-WORLD.py
+++ b/Demo/tkinter/matt/00-HELLO-WORLD.py
@@ -1,27 +1,27 @@
from Tkinter import *
-# note that there is no explicit call to start Tk.
-# Tkinter is smart enough to start the system if it's not already going.
+# note that there is no explicit call to start Tk.
+# Tkinter is smart enough to start the system if it's not already going.
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
-
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
- # a hello button
- self.hi_there = Button(self, text='Hello',
- command=self.printit)
- self.hi_there.pack(side=LEFT)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
+
+ # a hello button
+ self.hi_there = Button(self, text='Hello',
+ command=self.printit)
+ self.hi_there.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/animation-simple.py b/Demo/tkinter/matt/animation-simple.py
index 435d6fabd1..b52e1dc3ae 100644
--- a/Demo/tkinter/matt/animation-simple.py
+++ b/Demo/tkinter/matt/animation-simple.py
@@ -4,30 +4,30 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
+ self.draw = Canvas(self, width="5i", height="5i")
- # all of these work..
- self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue")
- self.draw.pack(side=LEFT)
+ # all of these work..
+ self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue")
+ self.draw.pack(side=LEFT)
def moveThing(self, *args):
- # move 1/10 of an inch every 1/10 sec (1" per second, smoothly)
- self.draw.move("thing", "0.01i", "0.01i")
- self.after(10, self.moveThing)
+ # move 1/10 of an inch every 1/10 sec (1" per second, smoothly)
+ self.draw.move("thing", "0.01i", "0.01i")
+ self.after(10, self.moveThing)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
- self.after(10, self.moveThing)
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+ self.after(10, self.moveThing)
test = Test()
diff --git a/Demo/tkinter/matt/animation-w-velocity-ctrl.py b/Demo/tkinter/matt/animation-w-velocity-ctrl.py
index f3332f2c48..e676338fe5 100644
--- a/Demo/tkinter/matt/animation-w-velocity-ctrl.py
+++ b/Demo/tkinter/matt/animation-w-velocity-ctrl.py
@@ -1,42 +1,42 @@
from Tkinter import *
-# this is the same as simple-demo-1.py, but uses
-# subclassing.
-# note that there is no explicit call to start Tk.
-# Tkinter is smart enough to start the system if it's not already going.
+# this is the same as simple-demo-1.py, but uses
+# subclassing.
+# note that there is no explicit call to start Tk.
+# Tkinter is smart enough to start the system if it's not already going.
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
+ self.draw = Canvas(self, width="5i", height="5i")
- self.speed = Scale(self, orient=HORIZONTAL, from_=-100, to=100)
+ self.speed = Scale(self, orient=HORIZONTAL, from_=-100, to=100)
- self.speed.pack(side=BOTTOM, fill=X)
+ self.speed.pack(side=BOTTOM, fill=X)
- # all of these work..
- self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue")
- self.draw.pack(side=LEFT)
+ # all of these work..
+ self.draw.create_rectangle(0, 0, 10, 10, tags="thing", fill="blue")
+ self.draw.pack(side=LEFT)
def moveThing(self, *args):
- velocity = self.speed.get()
- str = float(velocity) / 1000.0
- str = "%ri" % (str,)
- self.draw.move("thing", str, str)
- self.after(10, self.moveThing)
+ velocity = self.speed.get()
+ str = float(velocity) / 1000.0
+ str = "%ri" % (str,)
+ self.draw.move("thing", str, str)
+ self.after(10, self.moveThing)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
- self.after(10, self.moveThing)
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+ self.after(10, self.moveThing)
test = Test()
diff --git a/Demo/tkinter/matt/bind-w-mult-calls-p-type.py b/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
index 0907e41b07..f3220da508 100644
--- a/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
+++ b/Demo/tkinter/matt/bind-w-mult-calls-p-type.py
@@ -1,34 +1,34 @@
from Tkinter import *
-import string
+import string
# This program shows how to use a simple type-in box
class App(Frame):
def __init__(self, master=None):
- Frame.__init__(self, master)
- self.pack()
+ Frame.__init__(self, master)
+ self.pack()
- self.entrythingy = Entry()
- self.entrythingy.pack()
+ self.entrythingy = Entry()
+ self.entrythingy.pack()
- # and here we get a callback when the user hits return. we could
- # make the key that triggers the callback anything we wanted to.
- # other typical options might be <Key-Tab> or <Key> (for anything)
- self.entrythingy.bind('<Key-Return>', self.print_contents)
+ # and here we get a callback when the user hits return. we could
+ # make the key that triggers the callback anything we wanted to.
+ # other typical options might be <Key-Tab> or <Key> (for anything)
+ self.entrythingy.bind('<Key-Return>', self.print_contents)
- # Note that here is where we bind a completely different callback to
- # the same event. We pass "+" here to indicate that we wish to ADD
- # this callback to the list associated with this event type.
- # Not specifying "+" would simply override whatever callback was
- # defined on this event.
- self.entrythingy.bind('<Key-Return>', self.print_something_else, "+")
+ # Note that here is where we bind a completely different callback to
+ # the same event. We pass "+" here to indicate that we wish to ADD
+ # this callback to the list associated with this event type.
+ # Not specifying "+" would simply override whatever callback was
+ # defined on this event.
+ self.entrythingy.bind('<Key-Return>', self.print_something_else, "+")
def print_contents(self, event):
- print "hi. contents of entry is now ---->", self.entrythingy.get()
+ print "hi. contents of entry is now ---->", self.entrythingy.get()
def print_something_else(self, event):
- print "hi. Now doing something completely different"
+ print "hi. Now doing something completely different"
root = App()
@@ -37,8 +37,8 @@ root.mainloop()
-# secret tip for experts: if you pass *any* non-false value as
-# the third parameter to bind(), Tkinter.py will accumulate
+# secret tip for experts: if you pass *any* non-false value as
+# the third parameter to bind(), Tkinter.py will accumulate
# callbacks instead of overwriting. I use "+" here because that's
-# the Tk notation for getting this sort of behavior. The perfect GUI
+# the Tk notation for getting this sort of behavior. The perfect GUI
# interface would use a less obscure notation.
diff --git a/Demo/tkinter/matt/canvas-demo-simple.py b/Demo/tkinter/matt/canvas-demo-simple.py
index d9896261fa..a01679a663 100644
--- a/Demo/tkinter/matt/canvas-demo-simple.py
+++ b/Demo/tkinter/matt/canvas-demo-simple.py
@@ -4,24 +4,24 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
+ self.draw = Canvas(self, width="5i", height="5i")
- # see the other demos for other ways of specifying coords for a polygon
- self.draw.create_rectangle(0, 0, "3i", "3i", fill="black")
+ # see the other demos for other ways of specifying coords for a polygon
+ self.draw.create_rectangle(0, 0, "3i", "3i", fill="black")
- self.draw.pack(side=LEFT)
+ self.draw.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/canvas-gridding.py b/Demo/tkinter/matt/canvas-gridding.py
index b200ea4484..3c52b91aff 100644
--- a/Demo/tkinter/matt/canvas-gridding.py
+++ b/Demo/tkinter/matt/canvas-gridding.py
@@ -1,60 +1,60 @@
from Tkinter import *
-# this is the same as simple-demo-1.py, but uses
-# subclassing.
-# note that there is no explicit call to start Tk.
-# Tkinter is smart enough to start the system if it's not already going.
+# this is the same as simple-demo-1.py, but uses
+# subclassing.
+# note that there is no explicit call to start Tk.
+# Tkinter is smart enough to start the system if it's not already going.
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT',
- background='red',
- foreground='white',
- height=3,
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT',
+ background='red',
+ foreground='white',
+ height=3,
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.canvasObject = Canvas(self, width="5i", height="5i")
- self.canvasObject.pack(side=LEFT)
+ self.canvasObject = Canvas(self, width="5i", height="5i")
+ self.canvasObject.pack(side=LEFT)
def mouseDown(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- self.startx = self.canvasObject.canvasx(event.x, self.griddingSize)
- self.starty = self.canvasObject.canvasy(event.y, self.griddingSize)
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ self.startx = self.canvasObject.canvasx(event.x, self.griddingSize)
+ self.starty = self.canvasObject.canvasy(event.y, self.griddingSize)
def mouseMotion(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- x = self.canvasObject.canvasx(event.x, self.griddingSize)
- y = self.canvasObject.canvasy(event.y, self.griddingSize)
-
- if (self.startx != event.x) and (self.starty != event.y) :
- self.canvasObject.delete(self.rubberbandBox)
- self.rubberbandBox = self.canvasObject.create_rectangle(
- self.startx, self.starty, x, y)
- # this flushes the output, making sure that
- # the rectangle makes it to the screen
- # before the next event is handled
- self.update_idletasks()
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ x = self.canvasObject.canvasx(event.x, self.griddingSize)
+ y = self.canvasObject.canvasy(event.y, self.griddingSize)
+
+ if (self.startx != event.x) and (self.starty != event.y) :
+ self.canvasObject.delete(self.rubberbandBox)
+ self.rubberbandBox = self.canvasObject.create_rectangle(
+ self.startx, self.starty, x, y)
+ # this flushes the output, making sure that
+ # the rectangle makes it to the screen
+ # before the next event is handled
+ self.update_idletasks()
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
- # this is a "tagOrId" for the rectangle we draw on the canvas
- self.rubberbandBox = None
+ # this is a "tagOrId" for the rectangle we draw on the canvas
+ self.rubberbandBox = None
- # this is the size of the gridding squares
- self.griddingSize = 50
+ # this is the size of the gridding squares
+ self.griddingSize = 50
+
+ Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
+ Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
- Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
- Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
-
test = Test()
diff --git a/Demo/tkinter/matt/canvas-moving-or-creating.py b/Demo/tkinter/matt/canvas-moving-or-creating.py
index 74729a652b..5327c0827d 100644
--- a/Demo/tkinter/matt/canvas-moving-or-creating.py
+++ b/Demo/tkinter/matt/canvas-moving-or-creating.py
@@ -1,6 +1,6 @@
from Tkinter import *
-# this file demonstrates a more sophisticated movement --
+# this file demonstrates a more sophisticated movement --
# move dots or create new ones if you click outside the dots
class Test(Frame):
@@ -8,58 +8,55 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it)
###################################################################
def mouseDown(self, event):
- # see if we're inside a dot. If we are, it
- # gets tagged as CURRENT for free by tk.
- if not event.widget.find_withtag(CURRENT):
- # there is no dot here, so we can make one,
- # and bind some interesting behavior to it.
- # ------
- # create a dot, and mark it as CURRENT
- fred = self.draw.create_oval(
- event.x - 10, event.y -10, event.x +10, event.y + 10,
- fill="green", tags=CURRENT)
-
- self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
- self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
-
- self.lastx = event.x
- self.lasty = event.y
+ # see if we're inside a dot. If we are, it
+ # gets tagged as CURRENT for free by tk.
+ if not event.widget.find_withtag(CURRENT):
+ # there is no dot here, so we can make one,
+ # and bind some interesting behavior to it.
+ # ------
+ # create a dot, and mark it as CURRENT
+ fred = self.draw.create_oval(
+ event.x - 10, event.y -10, event.x +10, event.y + 10,
+ fill="green", tags=CURRENT)
+
+ self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
+ self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
+
+ self.lastx = event.x
+ self.lasty = event.y
def mouseMove(self, event):
- self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
- self.lastx = event.x
- self.lasty = event.y
+ self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
+ self.lastx = event.x
+ self.lasty = event.y
###################################################################
###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
###################################################################
def mouseEnter(self, event):
# the CURRENT tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="red")
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="red")
def mouseLeave(self, event):
- # the CURRENT tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="blue")
+ # the CURRENT tag is applied to the object the cursor is over.
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="blue")
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
- self.draw.pack(side=LEFT)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.draw = Canvas(self, width="5i", height="5i")
+ self.draw.pack(side=LEFT)
- Widget.bind(self.draw, "<1>", self.mouseDown)
- Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
+ Widget.bind(self.draw, "<1>", self.mouseDown)
+ Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
-
-
-
diff --git a/Demo/tkinter/matt/canvas-moving-w-mouse.py b/Demo/tkinter/matt/canvas-moving-w-mouse.py
index 447e29021f..81785d86a8 100644
--- a/Demo/tkinter/matt/canvas-moving-w-mouse.py
+++ b/Demo/tkinter/matt/canvas-moving-w-mouse.py
@@ -7,49 +7,49 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it)
###################################################################
def mouseDown(self, event):
- # remember where the mouse went down
- self.lastx = event.x
- self.lasty = event.y
+ # remember where the mouse went down
+ self.lastx = event.x
+ self.lasty = event.y
def mouseMove(self, event):
- # whatever the mouse is over gets tagged as CURRENT for free by tk.
- self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
- self.lastx = event.x
- self.lasty = event.y
+ # whatever the mouse is over gets tagged as CURRENT for free by tk.
+ self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
+ self.lastx = event.x
+ self.lasty = event.y
###################################################################
###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
###################################################################
def mouseEnter(self, event):
# the CURRENT tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="red")
-
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="red")
+
def mouseLeave(self, event):
- # the CURRENT tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="blue")
+ # the CURRENT tag is applied to the object the cursor is over.
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="blue")
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
- self.draw.pack(side=LEFT)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.draw = Canvas(self, width="5i", height="5i")
+ self.draw.pack(side=LEFT)
- fred = self.draw.create_oval(0, 0, 20, 20,
- fill="green", tags="selected")
+ fred = self.draw.create_oval(0, 0, 20, 20,
+ fill="green", tags="selected")
- self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
- self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
+ self.draw.tag_bind(fred, "<Any-Enter>", self.mouseEnter)
+ self.draw.tag_bind(fred, "<Any-Leave>", self.mouseLeave)
- Widget.bind(self.draw, "<1>", self.mouseDown)
- Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
+ Widget.bind(self.draw, "<1>", self.mouseDown)
+ Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/canvas-mult-item-sel.py b/Demo/tkinter/matt/canvas-mult-item-sel.py
index 2368733d04..a4f267cc13 100644
--- a/Demo/tkinter/matt/canvas-mult-item-sel.py
+++ b/Demo/tkinter/matt/canvas-mult-item-sel.py
@@ -1,6 +1,6 @@
from Tkinter import *
-# allows moving dots with multiple selection.
+# allows moving dots with multiple selection.
SELECTED_COLOR = "red"
UNSELECTED_COLOR = "blue"
@@ -10,72 +10,69 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it)
###################################################################
def mouseDown(self, event):
- # see if we're inside a dot. If we are, it
- # gets tagged as CURRENT for free by tk.
-
- if not event.widget.find_withtag(CURRENT):
- # we clicked outside of all dots on the canvas. unselect all.
-
- # re-color everything back to an unselected color
- self.draw.itemconfig("selected", fill=UNSELECTED_COLOR)
- # unselect everything
- self.draw.dtag("selected")
- else:
- # mark as "selected" the thing the cursor is under
- self.draw.addtag("selected", "withtag", CURRENT)
- # color it as selected
- self.draw.itemconfig("selected", fill=SELECTED_COLOR)
-
- self.lastx = event.x
- self.lasty = event.y
-
-
+ # see if we're inside a dot. If we are, it
+ # gets tagged as CURRENT for free by tk.
+
+ if not event.widget.find_withtag(CURRENT):
+ # we clicked outside of all dots on the canvas. unselect all.
+
+ # re-color everything back to an unselected color
+ self.draw.itemconfig("selected", fill=UNSELECTED_COLOR)
+ # unselect everything
+ self.draw.dtag("selected")
+ else:
+ # mark as "selected" the thing the cursor is under
+ self.draw.addtag("selected", "withtag", CURRENT)
+ # color it as selected
+ self.draw.itemconfig("selected", fill=SELECTED_COLOR)
+
+ self.lastx = event.x
+ self.lasty = event.y
+
+
def mouseMove(self, event):
- self.draw.move("selected", event.x - self.lastx, event.y - self.lasty)
- self.lastx = event.x
- self.lasty = event.y
+ self.draw.move("selected", event.x - self.lastx, event.y - self.lasty)
+ self.lastx = event.x
+ self.lasty = event.y
def makeNewDot(self):
- # create a dot, and mark it as current
- fred = self.draw.create_oval(0, 0, 20, 20,
- fill=SELECTED_COLOR, tags=CURRENT)
- # and make it selected
- self.draw.addtag("selected", "withtag", CURRENT)
-
+ # create a dot, and mark it as current
+ fred = self.draw.create_oval(0, 0, 20, 20,
+ fill=SELECTED_COLOR, tags=CURRENT)
+ # and make it selected
+ self.draw.addtag("selected", "withtag", CURRENT)
+
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
-
- ################
- # make the canvas and bind some behavior to it
- ################
- self.draw = Canvas(self, width="5i", height="5i")
- Widget.bind(self.draw, "<1>", self.mouseDown)
- Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
-
- # and other things.....
- self.button = Button(self, text="make a new dot", foreground="blue",
- command=self.makeNewDot)
-
- message = ("%s dots are selected and can be dragged.\n"
- "%s are not selected.\n"
- "Click in a dot to select it.\n"
- "Click on empty space to deselect all dots."
- ) % (SELECTED_COLOR, UNSELECTED_COLOR)
- self.label = Message(self, width="5i", text=message)
-
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.label.pack(side=BOTTOM, fill=X, expand=1)
- self.button.pack(side=BOTTOM, fill=X)
- self.draw.pack(side=LEFT)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
- def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ ################
+ # make the canvas and bind some behavior to it
+ ################
+ self.draw = Canvas(self, width="5i", height="5i")
+ Widget.bind(self.draw, "<1>", self.mouseDown)
+ Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
-test = Test()
-test.mainloop()
+ # and other things.....
+ self.button = Button(self, text="make a new dot", foreground="blue",
+ command=self.makeNewDot)
+
+ message = ("%s dots are selected and can be dragged.\n"
+ "%s are not selected.\n"
+ "Click in a dot to select it.\n"
+ "Click on empty space to deselect all dots."
+ ) % (SELECTED_COLOR, UNSELECTED_COLOR)
+ self.label = Message(self, width="5i", text=message)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.label.pack(side=BOTTOM, fill=X, expand=1)
+ self.button.pack(side=BOTTOM, fill=X)
+ self.draw.pack(side=LEFT)
+ def __init__(self, master=None):
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+test = Test()
+test.mainloop()
diff --git a/Demo/tkinter/matt/canvas-reading-tag-info.py b/Demo/tkinter/matt/canvas-reading-tag-info.py
index 704469177e..f57ea180a1 100644
--- a/Demo/tkinter/matt/canvas-reading-tag-info.py
+++ b/Demo/tkinter/matt/canvas-reading-tag-info.py
@@ -3,46 +3,46 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
-
- self.drawing = Canvas(self, width="5i", height="5i")
-
- # make a shape
- pgon = self.drawing.create_polygon(
- 10, 10, 110, 10, 110, 110, 10 , 110,
- fill="red", tags=("weee", "foo", "groo"))
-
- # this is how you query an object for its attributes
- # config options FOR CANVAS ITEMS always come back in tuples of length 5.
- # 0 attribute name
- # 1 BLANK
- # 2 BLANK
- # 3 default value
- # 4 current value
- # the blank spots are for consistency with the config command that
- # is used for widgets. (remember, this is for ITEMS drawn
- # on a canvas widget, not widgets)
- option_value = self.drawing.itemconfig(pgon, "stipple")
- print "pgon's current stipple value is -->", option_value[4], "<--"
- option_value = self.drawing.itemconfig(pgon, "fill")
- print "pgon's current fill value is -->", option_value[4], "<--"
- print " when he is usually colored -->", option_value[3], "<--"
-
- ## here we print out all the tags associated with this object
- option_value = self.drawing.itemconfig(pgon, "tags")
- print "pgon's tags are", option_value[4]
-
- self.drawing.pack(side=LEFT)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
+
+ self.drawing = Canvas(self, width="5i", height="5i")
+
+ # make a shape
+ pgon = self.drawing.create_polygon(
+ 10, 10, 110, 10, 110, 110, 10 , 110,
+ fill="red", tags=("weee", "foo", "groo"))
+
+ # this is how you query an object for its attributes
+ # config options FOR CANVAS ITEMS always come back in tuples of length 5.
+ # 0 attribute name
+ # 1 BLANK
+ # 2 BLANK
+ # 3 default value
+ # 4 current value
+ # the blank spots are for consistency with the config command that
+ # is used for widgets. (remember, this is for ITEMS drawn
+ # on a canvas widget, not widgets)
+ option_value = self.drawing.itemconfig(pgon, "stipple")
+ print "pgon's current stipple value is -->", option_value[4], "<--"
+ option_value = self.drawing.itemconfig(pgon, "fill")
+ print "pgon's current fill value is -->", option_value[4], "<--"
+ print " when he is usually colored -->", option_value[3], "<--"
+
+ ## here we print out all the tags associated with this object
+ option_value = self.drawing.itemconfig(pgon, "tags")
+ print "pgon's tags are", option_value[4]
+
+ self.drawing.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/canvas-w-widget-draw-el.py b/Demo/tkinter/matt/canvas-w-widget-draw-el.py
index a1bb3b5790..5b26210c0c 100644
--- a/Demo/tkinter/matt/canvas-w-widget-draw-el.py
+++ b/Demo/tkinter/matt/canvas-w-widget-draw-el.py
@@ -4,32 +4,32 @@ from Tkinter import *
class Test(Frame):
def printhi(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
+ self.draw = Canvas(self, width="5i", height="5i")
- self.button = Button(self, text="this is a button",
- command=self.printhi)
+ self.button = Button(self, text="this is a button",
+ command=self.printhi)
- # note here the coords are given in pixels (form the
- # upper right and corner of the window, as usual for X)
- # but might just have well been given in inches or points or
- # whatever...use the "anchor" option to control what point of the
- # widget (in this case the button) gets mapped to the given x, y.
- # you can specify corners, edges, center, etc...
- self.draw.create_window(300, 300, window=self.button)
+ # note here the coords are given in pixels (form the
+ # upper right and corner of the window, as usual for X)
+ # but might just have well been given in inches or points or
+ # whatever...use the "anchor" option to control what point of the
+ # widget (in this case the button) gets mapped to the given x, y.
+ # you can specify corners, edges, center, etc...
+ self.draw.create_window(300, 300, window=self.button)
- self.draw.pack(side=LEFT)
+ self.draw.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/canvas-with-scrollbars.py b/Demo/tkinter/matt/canvas-with-scrollbars.py
index 60c7b132ea..81ef25a88a 100644
--- a/Demo/tkinter/matt/canvas-with-scrollbars.py
+++ b/Demo/tkinter/matt/canvas-with-scrollbars.py
@@ -1,59 +1,59 @@
from Tkinter import *
-# This example program creates a scroling canvas, and demonstrates
+# This example program creates a scroling canvas, and demonstrates
# how to tie scrollbars and canvses together. The mechanism
# is analogus for listboxes and other widgets with
# "xscroll" and "yscroll" configuration options.
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.question = Label(self, text="Can Find The BLUE Square??????")
- self.question.pack()
+ self.question = Label(self, text="Can Find The BLUE Square??????")
+ self.question.pack()
- self.QUIT = Button(self, text='QUIT', background='red',
- height=3, command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
- spacer = Frame(self, height="0.25i")
- spacer.pack(side=BOTTOM)
+ self.QUIT = Button(self, text='QUIT', background='red',
+ height=3, command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ spacer = Frame(self, height="0.25i")
+ spacer.pack(side=BOTTOM)
- # notice that the scroll region (20" x 20") is larger than
- # displayed size of the widget (5" x 5")
- self.draw = Canvas(self, width="5i", height="5i",
- background="white",
- scrollregion=(0, 0, "20i", "20i"))
+ # notice that the scroll region (20" x 20") is larger than
+ # displayed size of the widget (5" x 5")
+ self.draw = Canvas(self, width="5i", height="5i",
+ background="white",
+ scrollregion=(0, 0, "20i", "20i"))
- self.draw.scrollX = Scrollbar(self, orient=HORIZONTAL)
- self.draw.scrollY = Scrollbar(self, orient=VERTICAL)
+ self.draw.scrollX = Scrollbar(self, orient=HORIZONTAL)
+ self.draw.scrollY = Scrollbar(self, orient=VERTICAL)
- # now tie the three together. This is standard boilerplate text
- self.draw['xscrollcommand'] = self.draw.scrollX.set
- self.draw['yscrollcommand'] = self.draw.scrollY.set
- self.draw.scrollX['command'] = self.draw.xview
- self.draw.scrollY['command'] = self.draw.yview
+ # now tie the three together. This is standard boilerplate text
+ self.draw['xscrollcommand'] = self.draw.scrollX.set
+ self.draw['yscrollcommand'] = self.draw.scrollY.set
+ self.draw.scrollX['command'] = self.draw.xview
+ self.draw.scrollY['command'] = self.draw.yview
- # draw something. Note that the first square
- # is visible, but you need to scroll to see the second one.
- self.draw.create_rectangle(0, 0, "3.5i", "3.5i", fill="black")
- self.draw.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue")
+ # draw something. Note that the first square
+ # is visible, but you need to scroll to see the second one.
+ self.draw.create_rectangle(0, 0, "3.5i", "3.5i", fill="black")
+ self.draw.create_rectangle("10i", "10i", "13.5i", "13.5i", fill="blue")
- # pack 'em up
- self.draw.scrollX.pack(side=BOTTOM, fill=X)
- self.draw.scrollY.pack(side=RIGHT, fill=Y)
- self.draw.pack(side=LEFT)
+ # pack 'em up
+ self.draw.scrollX.pack(side=BOTTOM, fill=X)
+ self.draw.scrollY.pack(side=RIGHT, fill=Y)
+ self.draw.pack(side=LEFT)
- def scrollCanvasX(self, *args):
- print "scrolling", args
- print self.draw.scrollX.get()
+ def scrollCanvasX(self, *args):
+ print "scrolling", args
+ print self.draw.scrollX.get()
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/dialog-box.py b/Demo/tkinter/matt/dialog-box.py
index cbfe29f964..dea8f39007 100644
--- a/Demo/tkinter/matt/dialog-box.py
+++ b/Demo/tkinter/matt/dialog-box.py
@@ -6,59 +6,59 @@ from Dialog import Dialog
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def makeWindow(self):
- """Create a top-level dialog with some buttons.
+ """Create a top-level dialog with some buttons.
- This uses the Dialog class, which is a wrapper around the Tcl/Tk
- tk_dialog script. The function returns 0 if the user clicks 'yes'
- or 1 if the user clicks 'no'.
- """
- # the parameters to this call are as follows:
- d = Dialog(
- self, ## name of a toplevel window
- title="fred the dialog box",## title on the window
- text="click on a choice", ## message to appear in window
- bitmap="info", ## bitmap (if any) to appear;
- ## if none, use ""
- # legal values here are:
- # string what it looks like
- # ----------------------------------------------
- # error a circle with a slash through it
- # grey25 grey square
- # grey50 darker grey square
- # hourglass use for "wait.."
- # info a large, lower case "i"
- # questhead a human head with a "?" in it
- # question a large "?"
- # warning a large "!"
- # @fname X bitmap where fname is the path to the file
- #
- default=0, # the index of the default button choice.
- # hitting return selects this
- strings=("yes", "no"))
- # values of the 'strings' key are the labels for the
- # buttons that appear left to right in the dialog box
- return d.num
+ This uses the Dialog class, which is a wrapper around the Tcl/Tk
+ tk_dialog script. The function returns 0 if the user clicks 'yes'
+ or 1 if the user clicks 'no'.
+ """
+ # the parameters to this call are as follows:
+ d = Dialog(
+ self, ## name of a toplevel window
+ title="fred the dialog box",## title on the window
+ text="click on a choice", ## message to appear in window
+ bitmap="info", ## bitmap (if any) to appear;
+ ## if none, use ""
+ # legal values here are:
+ # string what it looks like
+ # ----------------------------------------------
+ # error a circle with a slash through it
+ # grey25 grey square
+ # grey50 darker grey square
+ # hourglass use for "wait.."
+ # info a large, lower case "i"
+ # questhead a human head with a "?" in it
+ # question a large "?"
+ # warning a large "!"
+ # @fname X bitmap where fname is the path to the file
+ #
+ default=0, # the index of the default button choice.
+ # hitting return selects this
+ strings=("yes", "no"))
+ # values of the 'strings' key are the labels for the
+ # buttons that appear left to right in the dialog box
+ return d.num
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- # a hello button
- self.hi_there = Button(self, text='Make a New Window',
- command=self.makeWindow)
- self.hi_there.pack(side=LEFT)
+ # a hello button
+ self.hi_there = Button(self, text='Make a New Window',
+ command=self.makeWindow)
+ self.hi_there.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.windownum = 0
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.windownum = 0
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/entry-simple.py b/Demo/tkinter/matt/entry-simple.py
index cf82b89ce9..5146e6fd95 100644
--- a/Demo/tkinter/matt/entry-simple.py
+++ b/Demo/tkinter/matt/entry-simple.py
@@ -1,25 +1,24 @@
from Tkinter import *
-import string
+import string
# This program shows how to use a simple type-in box
class App(Frame):
def __init__(self, master=None):
- Frame.__init__(self, master)
- self.pack()
+ Frame.__init__(self, master)
+ self.pack()
- self.entrythingy = Entry()
- self.entrythingy.pack()
+ self.entrythingy = Entry()
+ self.entrythingy.pack()
- # and here we get a callback when the user hits return. we could
- # make the key that triggers the callback anything we wanted to.
- # other typical options might be <Key-Tab> or <Key> (for anything)
- self.entrythingy.bind('<Key-Return>', self.print_contents)
+ # and here we get a callback when the user hits return. we could
+ # make the key that triggers the callback anything we wanted to.
+ # other typical options might be <Key-Tab> or <Key> (for anything)
+ self.entrythingy.bind('<Key-Return>', self.print_contents)
def print_contents(self, event):
- print "hi. contents of entry is now ---->", self.entrythingy.get()
+ print "hi. contents of entry is now ---->", self.entrythingy.get()
root = App()
root.master.title("Foo")
root.mainloop()
-
diff --git a/Demo/tkinter/matt/entry-with-shared-variable.py b/Demo/tkinter/matt/entry-with-shared-variable.py
index 360f97373b..2b76162bd0 100644
--- a/Demo/tkinter/matt/entry-with-shared-variable.py
+++ b/Demo/tkinter/matt/entry-with-shared-variable.py
@@ -1,47 +1,46 @@
from Tkinter import *
-import string
+import string
# This program shows how to make a typein box shadow a program variable.
class App(Frame):
def __init__(self, master=None):
- Frame.__init__(self, master)
- self.pack()
-
- self.entrythingy = Entry(self)
- self.entrythingy.pack()
-
- self.button = Button(self, text="Uppercase The Entry",
- command=self.upper)
- self.button.pack()
-
- # here we have the text in the entry widget tied to a variable.
- # changes in the variable are echoed in the widget and vice versa.
- # Very handy.
- # there are other Variable types. See Tkinter.py for all
- # the other variable types that can be shadowed
- self.contents = StringVar()
- self.contents.set("this is a variable")
- self.entrythingy.config(textvariable=self.contents)
-
- # and here we get a callback when the user hits return. we could
- # make the key that triggers the callback anything we wanted to.
- # other typical options might be <Key-Tab> or <Key> (for anything)
- self.entrythingy.bind('<Key-Return>', self.print_contents)
+ Frame.__init__(self, master)
+ self.pack()
+
+ self.entrythingy = Entry(self)
+ self.entrythingy.pack()
+
+ self.button = Button(self, text="Uppercase The Entry",
+ command=self.upper)
+ self.button.pack()
+
+ # here we have the text in the entry widget tied to a variable.
+ # changes in the variable are echoed in the widget and vice versa.
+ # Very handy.
+ # there are other Variable types. See Tkinter.py for all
+ # the other variable types that can be shadowed
+ self.contents = StringVar()
+ self.contents.set("this is a variable")
+ self.entrythingy.config(textvariable=self.contents)
+
+ # and here we get a callback when the user hits return. we could
+ # make the key that triggers the callback anything we wanted to.
+ # other typical options might be <Key-Tab> or <Key> (for anything)
+ self.entrythingy.bind('<Key-Return>', self.print_contents)
def upper(self):
- # notice here, we don't actually refer to the entry box.
- # we just operate on the string variable and we
+ # notice here, we don't actually refer to the entry box.
+ # we just operate on the string variable and we
# because it's being looked at by the entry widget, changing
- # the variable changes the entry widget display automatically.
- # the strange get/set operators are clunky, true...
- str = string.upper(self.contents.get())
- self.contents.set(str)
+ # the variable changes the entry widget display automatically.
+ # the strange get/set operators are clunky, true...
+ str = string.upper(self.contents.get())
+ self.contents.set(str)
def print_contents(self, event):
- print "hi. contents of entry is now ---->", self.contents.get()
+ print "hi. contents of entry is now ---->", self.contents.get()
root = App()
root.master.title("Foo")
root.mainloop()
-
diff --git a/Demo/tkinter/matt/killing-window-w-wm.py b/Demo/tkinter/matt/killing-window-w-wm.py
index 805a6bc6a8..6a0e2fe621 100644
--- a/Demo/tkinter/matt/killing-window-w-wm.py
+++ b/Demo/tkinter/matt/killing-window-w-wm.py
@@ -1,8 +1,8 @@
from Tkinter import *
-# This file shows how to trap the killing of a window
+# This file shows how to trap the killing of a window
# when the user uses window manager menus (typ. upper left hand corner
-# menu in the decoration border).
+# menu in the decoration border).
### ******* this isn't really called -- read the comments
@@ -11,31 +11,31 @@ def my_delete_callback():
class Test(Frame):
def deathHandler(self, event):
- print self, "is now getting nuked. performing some save here...."
+ print self, "is now getting nuked. performing some save here...."
def createWidgets(self):
- # a hello button
- self.hi_there = Button(self, text='Hello')
- self.hi_there.pack(side=LEFT)
+ # a hello button
+ self.hi_there = Button(self, text='Hello')
+ self.hi_there.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
- ###
- ### PREVENT WM kills from happening
- ###
+ ###
+ ### PREVENT WM kills from happening
+ ###
- # the docs would have you do this:
+ # the docs would have you do this:
-# self.master.protocol("WM_DELETE_WINDOW", my_delete_callback)
+# self.master.protocol("WM_DELETE_WINDOW", my_delete_callback)
- # unfortunately, some window managers will not send this request to a window.
- # the "protocol" function seems incapable of trapping these "aggressive" window kills.
- # this line of code catches everything, tho. The window is deleted, but you have a chance
- # of cleaning up first.
- self.bind_all("<Destroy>", self.deathHandler)
+ # unfortunately, some window managers will not send this request to a window.
+ # the "protocol" function seems incapable of trapping these "aggressive" window kills.
+ # this line of code catches everything, tho. The window is deleted, but you have a chance
+ # of cleaning up first.
+ self.bind_all("<Destroy>", self.deathHandler)
test = Test()
diff --git a/Demo/tkinter/matt/menu-all-types-of-entries.py b/Demo/tkinter/matt/menu-all-types-of-entries.py
index 1ac51c81ff..f4afe4a8b6 100644
--- a/Demo/tkinter/matt/menu-all-types-of-entries.py
+++ b/Demo/tkinter/matt/menu-all-types-of-entries.py
@@ -1,16 +1,16 @@
from Tkinter import *
-# some vocabulary to keep from getting confused. This terminology
-# is something I cooked up for this file, but follows the man pages
+# some vocabulary to keep from getting confused. This terminology
+# is something I cooked up for this file, but follows the man pages
# pretty closely
-#
-#
-#
+#
+#
+#
# This is a MENUBUTTON
# V
# +-------------+
# | |
-#
+#
# +------------++------------++------------+
# | || || |
# | File || Edit || Options | <-------- the MENUBAR
@@ -22,7 +22,7 @@ from Tkinter import *
# | | <-------- This is a MENU. The lines of text in the menu are
# | | MENU ENTRIES
# | +---------------+
-# | Open Files > | file1 |
+# | Open Files > | file1 |
# | | file2 |
# | | another file | <------ this cascading part is also a MENU
# +----------------| |
@@ -53,11 +53,11 @@ def print_anchovies():
print "anchovies?", anchovies
def makeCommandMenu():
- # make menu button
- Command_button = Menubutton(mBar, text='Simple Button Commands',
- underline=0)
+ # make menu button
+ Command_button = Menubutton(mBar, text='Simple Button Commands',
+ underline=0)
Command_button.pack(side=LEFT, padx="2m")
-
+
# make the pulldown part of the File menu. The parameter passed is the master.
# we attach it to the button as a python attribute called "menu" by convention.
# hopefully this isn't too confusing...
@@ -68,28 +68,28 @@ def makeCommandMenu():
# undo is the 0th entry...
Command_button.menu.entryconfig(0, state=DISABLED)
- Command_button.menu.add_command(label='New...', underline=0,
- command=new_file)
- Command_button.menu.add_command(label='Open...', underline=0,
- command=open_file)
+ Command_button.menu.add_command(label='New...', underline=0,
+ command=new_file)
+ Command_button.menu.add_command(label='Open...', underline=0,
+ command=open_file)
Command_button.menu.add_command(label='Different Font', underline=0,
- font='-*-helvetica-*-r-*-*-*-180-*-*-*-*-*-*',
- command=print_something)
-
+ font='-*-helvetica-*-r-*-*-*-180-*-*-*-*-*-*',
+ command=print_something)
+
# we can make bitmaps be menu entries too. File format is X11 bitmap.
# if you use XV, save it under X11 bitmap format. duh-uh.,..
Command_button.menu.add_command(
- bitmap="info")
- #bitmap='@/home/mjc4y/dilbert/project.status.is.doomed.last.panel.bm')
-
+ bitmap="info")
+ #bitmap='@/home/mjc4y/dilbert/project.status.is.doomed.last.panel.bm')
+
# this is just a line
Command_button.menu.add('separator')
# change the color
- Command_button.menu.add_command(label='Quit', underline=0,
- background='red',
- activebackground='green',
- command=Command_button.quit)
+ Command_button.menu.add_command(label='Quit', underline=0,
+ background='red',
+ activebackground='green',
+ command=Command_button.quit)
# set up a pointer from the file menubutton back to the file menu
Command_button['menu'] = Command_button.menu
@@ -99,10 +99,10 @@ def makeCommandMenu():
def makeCascadeMenu():
- # make menu button
+ # make menu button
Cascade_button = Menubutton(mBar, text='Cascading Menus', underline=0)
Cascade_button.pack(side=LEFT, padx="2m")
-
+
# the primary pulldown
Cascade_button.menu = Menu(Cascade_button)
@@ -125,12 +125,12 @@ def makeCascadeMenu():
Cascade_button.menu.choices.add_command(label='Rocky Road')
Cascade_button.menu.choices.add_command(label='BubbleGum')
Cascade_button.menu.choices.add_cascade(
- label='Wierd Flavors',
- menu=Cascade_button.menu.choices.wierdones)
+ label='Wierd Flavors',
+ menu=Cascade_button.menu.choices.wierdones)
# and finally, the definition for the top level
- Cascade_button.menu.add_cascade(label='more choices',
- menu=Cascade_button.menu.choices)
+ Cascade_button.menu.add_cascade(label='more choices',
+ menu=Cascade_button.menu.choices)
Cascade_button['menu'] = Cascade_button.menu
@@ -138,39 +138,39 @@ def makeCascadeMenu():
def makeCheckbuttonMenu():
global fred
- # make menu button
- Checkbutton_button = Menubutton(mBar, text='Checkbutton Menus',
- underline=0)
+ # make menu button
+ Checkbutton_button = Menubutton(mBar, text='Checkbutton Menus',
+ underline=0)
Checkbutton_button.pack(side=LEFT, padx='2m')
-
+
# the primary pulldown
Checkbutton_button.menu = Menu(Checkbutton_button)
# and all the check buttons. Note that the "variable" "onvalue" and "offvalue" options
- # are not supported correctly at present. You have to do all your application
+ # are not supported correctly at present. You have to do all your application
# work through the calback.
Checkbutton_button.menu.add_checkbutton(label='Pepperoni')
Checkbutton_button.menu.add_checkbutton(label='Sausage')
Checkbutton_button.menu.add_checkbutton(label='Extra Cheese')
# so here's a callback
- Checkbutton_button.menu.add_checkbutton(label='Anchovy',
- command=print_anchovies)
+ Checkbutton_button.menu.add_checkbutton(label='Anchovy',
+ command=print_anchovies)
- # and start with anchovies selected to be on. Do this by
+ # and start with anchovies selected to be on. Do this by
# calling invoke on this menu option. To refer to the "anchovy" menu
# entry we need to know it's index. To do this, we use the index method
- # which takes arguments of several forms:
+ # which takes arguments of several forms:
#
# argument what it does
# -----------------------------------
- # a number -- this is useless.
+ # a number -- this is useless.
# "last" -- last option in the menu
# "none" -- used with the activate command. see the man page on menus
# "active" -- the currently active menu option. A menu option is made active
# with the 'activate' method
# "@number" -- where 'number' is an integer and is treated like a y coordinate in pixels
- # string pattern -- this is the option used below, and attempts to match "labels" using the
+ # string pattern -- this is the option used below, and attempts to match "labels" using the
# rules of Tcl_StringMatch
Checkbutton_button.menu.invoke(Checkbutton_button.menu.index('Anchovy'))
@@ -181,16 +181,16 @@ def makeCheckbuttonMenu():
def makeRadiobuttonMenu():
- # make menu button
- Radiobutton_button = Menubutton(mBar, text='Radiobutton Menus',
- underline=0)
+ # make menu button
+ Radiobutton_button = Menubutton(mBar, text='Radiobutton Menus',
+ underline=0)
Radiobutton_button.pack(side=LEFT, padx='2m')
-
+
# the primary pulldown
Radiobutton_button.menu = Menu(Radiobutton_button)
# and all the Radio buttons. Note that the "variable" "onvalue" and "offvalue" options
- # are not supported correctly at present. You have to do all your application
+ # are not supported correctly at present. You have to do all your application
# work through the calback.
Radiobutton_button.menu.add_radiobutton(label='Republican')
Radiobutton_button.menu.add_radiobutton(label='Democrat')
@@ -209,7 +209,7 @@ def makeRadiobuttonMenu():
return Radiobutton_button
-def makeDisabledMenu():
+def makeDisabledMenu():
Dummy_button = Menubutton(mBar, text='Dead Menu', underline=0)
Dummy_button.pack(side=LEFT, padx='2m')
@@ -233,7 +233,7 @@ Checkbutton_button = makeCheckbuttonMenu()
Radiobutton_button = makeRadiobuttonMenu()
NoMenu = makeDisabledMenu()
-# finally, install the buttons in the menu bar.
+# finally, install the buttons in the menu bar.
# This allows for scanning from one menubutton to the next.
mBar.tk_menuBar(Command_button, Cascade_button, Checkbutton_button, Radiobutton_button, NoMenu)
@@ -242,9 +242,3 @@ root.title('menu demo')
root.iconname('menu demo')
root.mainloop()
-
-
-
-
-
-
diff --git a/Demo/tkinter/matt/menu-simple.py b/Demo/tkinter/matt/menu-simple.py
index 28f2c9eff5..46b53642e3 100644
--- a/Demo/tkinter/matt/menu-simple.py
+++ b/Demo/tkinter/matt/menu-simple.py
@@ -1,16 +1,16 @@
from Tkinter import *
-# some vocabulary to keep from getting confused. This terminology
-# is something I cooked up for this file, but follows the man pages
+# some vocabulary to keep from getting confused. This terminology
+# is something I cooked up for this file, but follows the man pages
# pretty closely
-#
-#
-#
+#
+#
+#
# This is a MENUBUTTON
# V
# +-------------+
# | |
-#
+#
# +------------++------------++------------+
# | || || |
# | File || Edit || Options | <-------- the MENUBAR
@@ -22,7 +22,7 @@ from Tkinter import *
# | | <------ This is a MENU. The lines of text in the menu are
# | | MENU ENTRIES
# | +---------------+
-# | Open Files > | file1 |
+# | Open Files > | file1 |
# | | file2 |
# | | another file | <------ this cascading part is also a MENU
# +----------------| |
@@ -46,19 +46,19 @@ def makeFileMenu():
File_button = Menubutton(mBar, text='File', underline=0)
File_button.pack(side=LEFT, padx="1m")
File_button.menu = Menu(File_button)
-
- # add an item. The first param is a menu entry type,
+
+ # add an item. The first param is a menu entry type,
# must be one of: "cascade", "checkbutton", "command", "radiobutton", "seperator"
# see menu-demo-2.py for examples of use
- File_button.menu.add_command(label='New...', underline=0,
- command=new_file)
-
-
- File_button.menu.add_command(label='Open...', underline=0,
- command=open_file)
-
- File_button.menu.add_command(label='Quit', underline=0,
- command='exit')
+ File_button.menu.add_command(label='New...', underline=0,
+ command=new_file)
+
+
+ File_button.menu.add_command(label='Open...', underline=0,
+ command=open_file)
+
+ File_button.menu.add_command(label='Quit', underline=0,
+ command='exit')
# set up a pointer from the file menubutton back to the file menu
File_button['menu'] = File_button.menu
@@ -102,7 +102,7 @@ mBar.pack(fill=X)
File_button = makeFileMenu()
Edit_button = makeEditMenu()
-# finally, install the buttons in the menu bar.
+# finally, install the buttons in the menu bar.
# This allows for scanning from one menubutton to the next.
mBar.tk_menuBar(File_button, Edit_button)
@@ -110,9 +110,3 @@ root.title('menu demo')
root.iconname('packer')
root.mainloop()
-
-
-
-
-
-
diff --git a/Demo/tkinter/matt/not-what-you-might-think-1.py b/Demo/tkinter/matt/not-what-you-might-think-1.py
index 24de2ef202..7b20f02b37 100644
--- a/Demo/tkinter/matt/not-what-you-might-think-1.py
+++ b/Demo/tkinter/matt/not-what-you-might-think-1.py
@@ -4,21 +4,21 @@ from Tkinter import *
class Test(Frame):
def createWidgets(self):
- self.Gpanel = Frame(self, width='1i', height='1i',
- background='green')
- self.Gpanel.pack(side=LEFT)
+ self.Gpanel = Frame(self, width='1i', height='1i',
+ background='green')
+ self.Gpanel.pack(side=LEFT)
- # a QUIT button
- self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT',
- foreground='red',
- command=self.quit)
- self.Gpanel.QUIT.pack(side=LEFT)
+ # a QUIT button
+ self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT',
+ foreground='red',
+ command=self.quit)
+ self.Gpanel.QUIT.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/not-what-you-might-think-2.py b/Demo/tkinter/matt/not-what-you-might-think-2.py
index c01854e96c..9ee197cf98 100644
--- a/Demo/tkinter/matt/not-what-you-might-think-2.py
+++ b/Demo/tkinter/matt/not-what-you-might-think-2.py
@@ -4,23 +4,23 @@ from Tkinter import *
class Test(Frame):
def createWidgets(self):
- self.Gpanel = Frame(self, width='1i', height='1i',
- background='green')
+ self.Gpanel = Frame(self, width='1i', height='1i',
+ background='green')
- # this line turns off the recalculation of geometry by masters.
- self.Gpanel.propagate(0)
+ # this line turns off the recalculation of geometry by masters.
+ self.Gpanel.propagate(0)
- self.Gpanel.pack(side=LEFT)
+ self.Gpanel.pack(side=LEFT)
- # a QUIT button
- self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT', foreground='red',
- command=self.quit)
- self.Gpanel.QUIT.pack(side=LEFT)
+ # a QUIT button
+ self.Gpanel.QUIT = Button(self.Gpanel, text='QUIT', foreground='red',
+ command=self.quit)
+ self.Gpanel.QUIT.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/packer-and-placer-together.py b/Demo/tkinter/matt/packer-and-placer-together.py
index 4ceec542a5..184d56bc1a 100644
--- a/Demo/tkinter/matt/packer-and-placer-together.py
+++ b/Demo/tkinter/matt/packer-and-placer-together.py
@@ -1,6 +1,6 @@
from Tkinter import *
-# This is a program that tests the placer geom manager in conjunction with
+# This is a program that tests the placer geom manager in conjunction with
# the packer. The background (green) is packed, while the widget inside is placed
@@ -17,15 +17,15 @@ def createWidgets(top):
# area is inaccesssible.
f = Frame(top, width=200, height=200, background='green')
- # note that we use a different manager here.
- # This way, the top level frame widget resizes when the
- # application window does.
+ # note that we use a different manager here.
+ # This way, the top level frame widget resizes when the
+ # application window does.
f.pack(fill=BOTH, expand=1)
# now make a button
f.button = Button(f, foreground='red', text='amazing', command=dothis)
- # and place it so that the nw corner is
+ # and place it so that the nw corner is
# 1/2 way along the top X edge of its' parent
f.button.place(relx=0.5, rely=0.0, anchor=NW)
@@ -39,4 +39,3 @@ app = createWidgets(root)
root.geometry("400x400")
root.maxsize(1000, 1000)
root.mainloop()
-
diff --git a/Demo/tkinter/matt/packer-simple.py b/Demo/tkinter/matt/packer-simple.py
index 7773cae65d..f55f1bee72 100644
--- a/Demo/tkinter/matt/packer-simple.py
+++ b/Demo/tkinter/matt/packer-simple.py
@@ -3,30 +3,30 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print self.hi_there["command"]
+ print self.hi_there["command"]
def createWidgets(self):
- # a hello button
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ # a hello button
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- self.hi_there = Button(self, text='Hello',
- command=self.printit)
- self.hi_there.pack(side=LEFT)
+ self.hi_there = Button(self, text='Hello',
+ command=self.printit)
+ self.hi_there.pack(side=LEFT)
- # note how Packer defaults to side=TOP
+ # note how Packer defaults to side=TOP
- self.guy2 = Button(self, text='button 2')
- self.guy2.pack()
+ self.guy2 = Button(self, text='button 2')
+ self.guy2.pack()
- self.guy3 = Button(self, text='button 3')
- self.guy3.pack()
+ self.guy3 = Button(self, text='button 3')
+ self.guy3.pack()
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/placer-simple.py b/Demo/tkinter/matt/placer-simple.py
index b7cae7e59d..30d9e9e901 100644
--- a/Demo/tkinter/matt/placer-simple.py
+++ b/Demo/tkinter/matt/placer-simple.py
@@ -15,7 +15,7 @@ def createWidgets(top):
# area is inaccesssible.
f = Frame(top, width=200, height=200, background='green')
- # place it so the upper left hand corner of
+ # place it so the upper left hand corner of
# the frame is in the upper left corner of
# the parent
f.place(relx=0.0, rely=0.0)
@@ -23,7 +23,7 @@ def createWidgets(top):
# now make a button
f.button = Button(f, foreground='red', text='amazing', command=dothis)
- # and place it so that the nw corner is
+ # and place it so that the nw corner is
# 1/2 way along the top X edge of its' parent
f.button.place(relx=0.5, rely=0.0, anchor=NW)
@@ -37,4 +37,3 @@ app = createWidgets(root)
root.geometry("400x400")
root.maxsize(1000, 1000)
root.mainloop()
-
diff --git a/Demo/tkinter/matt/pong-demo-1.py b/Demo/tkinter/matt/pong-demo-1.py
index a27f334f8a..7fcf800b68 100644
--- a/Demo/tkinter/matt/pong-demo-1.py
+++ b/Demo/tkinter/matt/pong-demo-1.py
@@ -5,48 +5,48 @@ import string
class Pong(Frame):
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- ## The playing field
- self.draw = Canvas(self, width="5i", height="5i")
+ ## The playing field
+ self.draw = Canvas(self, width="5i", height="5i")
- ## The speed control for the ball
- self.speed = Scale(self, orient=HORIZONTAL, label="ball speed",
- from_=-100, to=100)
+ ## The speed control for the ball
+ self.speed = Scale(self, orient=HORIZONTAL, label="ball speed",
+ from_=-100, to=100)
- self.speed.pack(side=BOTTOM, fill=X)
+ self.speed.pack(side=BOTTOM, fill=X)
- # The ball
- self.ball = self.draw.create_oval("0i", "0i", "0.10i", "0.10i",
- fill="red")
- self.x = 0.05
- self.y = 0.05
- self.velocity_x = 0.3
- self.velocity_y = 0.5
+ # The ball
+ self.ball = self.draw.create_oval("0i", "0i", "0.10i", "0.10i",
+ fill="red")
+ self.x = 0.05
+ self.y = 0.05
+ self.velocity_x = 0.3
+ self.velocity_y = 0.5
- self.draw.pack(side=LEFT)
+ self.draw.pack(side=LEFT)
def moveBall(self, *args):
- if (self.x > 5.0) or (self.x < 0.0):
- self.velocity_x = -1.0 * self.velocity_x
- if (self.y > 5.0) or (self.y < 0.0):
- self.velocity_y = -1.0 * self.velocity_y
+ if (self.x > 5.0) or (self.x < 0.0):
+ self.velocity_x = -1.0 * self.velocity_x
+ if (self.y > 5.0) or (self.y < 0.0):
+ self.velocity_y = -1.0 * self.velocity_y
- deltax = (self.velocity_x * self.speed.get() / 100.0)
- deltay = (self.velocity_y * self.speed.get() / 100.0)
- self.x = self.x + deltax
- self.y = self.y + deltay
+ deltax = (self.velocity_x * self.speed.get() / 100.0)
+ deltay = (self.velocity_y * self.speed.get() / 100.0)
+ self.x = self.x + deltax
+ self.y = self.y + deltay
- self.draw.move(self.ball, "%ri" % deltax, "%ri" % deltay)
- self.after(10, self.moveBall)
+ self.draw.move(self.ball, "%ri" % deltax, "%ri" % deltay)
+ self.after(10, self.moveBall)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
- self.after(10, self.moveBall)
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+ self.after(10, self.moveBall)
game = Pong()
diff --git a/Demo/tkinter/matt/printing-coords-of-items.py b/Demo/tkinter/matt/printing-coords-of-items.py
index 6400fd8699..a37733d031 100644
--- a/Demo/tkinter/matt/printing-coords-of-items.py
+++ b/Demo/tkinter/matt/printing-coords-of-items.py
@@ -7,58 +7,55 @@ class Test(Frame):
###### Event callbacks for THE CANVAS (not the stuff drawn on it)
###################################################################
def mouseDown(self, event):
- # see if we're inside a dot. If we are, it
- # gets tagged as CURRENT for free by tk.
-
- if not event.widget.find_withtag(CURRENT):
- # there is no dot here, so we can make one,
- # and bind some interesting behavior to it.
- # ------
- # create a dot, and mark it as current
- fred = self.draw.create_oval(
- event.x - 10, event.y -10, event.x +10, event.y + 10,
- fill="green")
- self.draw.tag_bind(fred, "<Enter>", self.mouseEnter)
- self.draw.tag_bind(fred, "<Leave>", self.mouseLeave)
- self.lastx = event.x
- self.lasty = event.y
+ # see if we're inside a dot. If we are, it
+ # gets tagged as CURRENT for free by tk.
+
+ if not event.widget.find_withtag(CURRENT):
+ # there is no dot here, so we can make one,
+ # and bind some interesting behavior to it.
+ # ------
+ # create a dot, and mark it as current
+ fred = self.draw.create_oval(
+ event.x - 10, event.y -10, event.x +10, event.y + 10,
+ fill="green")
+ self.draw.tag_bind(fred, "<Enter>", self.mouseEnter)
+ self.draw.tag_bind(fred, "<Leave>", self.mouseLeave)
+ self.lastx = event.x
+ self.lasty = event.y
def mouseMove(self, event):
- self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
- self.lastx = event.x
- self.lasty = event.y
+ self.draw.move(CURRENT, event.x - self.lastx, event.y - self.lasty)
+ self.lastx = event.x
+ self.lasty = event.y
###################################################################
###### Event callbacks for canvas ITEMS (stuff drawn on the canvas)
###################################################################
def mouseEnter(self, event):
# the "current" tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="red")
- print self.draw.coords(CURRENT)
-
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="red")
+ print self.draw.coords(CURRENT)
+
def mouseLeave(self, event):
- # the "current" tag is applied to the object the cursor is over.
- # this happens automatically.
- self.draw.itemconfig(CURRENT, fill="blue")
+ # the "current" tag is applied to the object the cursor is over.
+ # this happens automatically.
+ self.draw.itemconfig(CURRENT, fill="blue")
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
- self.draw = Canvas(self, width="5i", height="5i")
- self.draw.pack(side=LEFT)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.draw = Canvas(self, width="5i", height="5i")
+ self.draw.pack(side=LEFT)
- Widget.bind(self.draw, "<1>", self.mouseDown)
- Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
+ Widget.bind(self.draw, "<1>", self.mouseDown)
+ Widget.bind(self.draw, "<B1-Motion>", self.mouseMove)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
-
-
-
diff --git a/Demo/tkinter/matt/radiobutton-simple.py b/Demo/tkinter/matt/radiobutton-simple.py
index 65dfe52ba1..e9d6afee1c 100644
--- a/Demo/tkinter/matt/radiobutton-simple.py
+++ b/Demo/tkinter/matt/radiobutton-simple.py
@@ -1,10 +1,10 @@
from Tkinter import *
-# This is a demo program that shows how to
-# create radio buttons and how to get other widgets to
-# share the information in a radio button.
-#
-# There are other ways of doing this too, but
+# This is a demo program that shows how to
+# create radio buttons and how to get other widgets to
+# share the information in a radio button.
+#
+# There are other ways of doing this too, but
# the "variable" option of radiobuttons seems to be the easiest.
#
# note how each button has a value it sets the variable to as it gets hit.
@@ -12,50 +12,50 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.flavor = StringVar()
- self.flavor.set("chocolate")
-
- self.radioframe = Frame(self)
- self.radioframe.pack()
-
- # 'text' is the label
- # 'variable' is the name of the variable that all these radio buttons share
- # 'value' is the value this variable takes on when the radio button is selected
- # 'anchor' makes the text appear left justified (default is centered. ick)
- self.radioframe.choc = Radiobutton(
- self.radioframe, text="Chocolate Flavor",
- variable=self.flavor, value="chocolate",
- anchor=W)
- self.radioframe.choc.pack(fill=X)
-
- self.radioframe.straw = Radiobutton(
- self.radioframe, text="Strawberry Flavor",
- variable=self.flavor, value="strawberry",
- anchor=W)
- self.radioframe.straw.pack(fill=X)
-
- self.radioframe.lemon = Radiobutton(
- self.radioframe, text="Lemon Flavor",
- variable=self.flavor, value="lemon",
- anchor=W)
- self.radioframe.lemon.pack(fill=X)
-
- # this is a text entry that lets you type in the name of a flavor too.
- self.entry = Entry(self, textvariable=self.flavor)
- self.entry.pack(fill=X)
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.flavor = StringVar()
+ self.flavor.set("chocolate")
+
+ self.radioframe = Frame(self)
+ self.radioframe.pack()
+
+ # 'text' is the label
+ # 'variable' is the name of the variable that all these radio buttons share
+ # 'value' is the value this variable takes on when the radio button is selected
+ # 'anchor' makes the text appear left justified (default is centered. ick)
+ self.radioframe.choc = Radiobutton(
+ self.radioframe, text="Chocolate Flavor",
+ variable=self.flavor, value="chocolate",
+ anchor=W)
+ self.radioframe.choc.pack(fill=X)
+
+ self.radioframe.straw = Radiobutton(
+ self.radioframe, text="Strawberry Flavor",
+ variable=self.flavor, value="strawberry",
+ anchor=W)
+ self.radioframe.straw.pack(fill=X)
+
+ self.radioframe.lemon = Radiobutton(
+ self.radioframe, text="Lemon Flavor",
+ variable=self.flavor, value="lemon",
+ anchor=W)
+ self.radioframe.lemon.pack(fill=X)
+
+ # this is a text entry that lets you type in the name of a flavor too.
+ self.entry = Entry(self, textvariable=self.flavor)
+ self.entry.pack(fill=X)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
diff --git a/Demo/tkinter/matt/rubber-band-box-demo-1.py b/Demo/tkinter/matt/rubber-band-box-demo-1.py
index 5196bf7576..b00518e006 100644
--- a/Demo/tkinter/matt/rubber-band-box-demo-1.py
+++ b/Demo/tkinter/matt/rubber-band-box-demo-1.py
@@ -2,55 +2,55 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT',
- background='red',
- foreground='white',
- height=3,
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT',
+ background='red',
+ foreground='white',
+ height=3,
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.canvasObject = Canvas(self, width="5i", height="5i")
- self.canvasObject.pack(side=LEFT)
+ self.canvasObject = Canvas(self, width="5i", height="5i")
+ self.canvasObject.pack(side=LEFT)
def mouseDown(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- self.startx = self.canvasObject.canvasx(event.x)
- self.starty = self.canvasObject.canvasy(event.y)
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ self.startx = self.canvasObject.canvasx(event.x)
+ self.starty = self.canvasObject.canvasy(event.y)
def mouseMotion(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- x = self.canvasObject.canvasx(event.x)
- y = self.canvasObject.canvasy(event.y)
-
- if (self.startx != event.x) and (self.starty != event.y) :
- self.canvasObject.delete(self.rubberbandBox)
- self.rubberbandBox = self.canvasObject.create_rectangle(
- self.startx, self.starty, x, y)
- # this flushes the output, making sure that
- # the rectangle makes it to the screen
- # before the next event is handled
- self.update_idletasks()
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ x = self.canvasObject.canvasx(event.x)
+ y = self.canvasObject.canvasy(event.y)
+
+ if (self.startx != event.x) and (self.starty != event.y) :
+ self.canvasObject.delete(self.rubberbandBox)
+ self.rubberbandBox = self.canvasObject.create_rectangle(
+ self.startx, self.starty, x, y)
+ # this flushes the output, making sure that
+ # the rectangle makes it to the screen
+ # before the next event is handled
+ self.update_idletasks()
def mouseUp(self, event):
- self.canvasObject.delete(self.rubberbandBox)
-
+ self.canvasObject.delete(self.rubberbandBox)
+
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
-
- # this is a "tagOrId" for the rectangle we draw on the canvas
- self.rubberbandBox = None
-
- # and the bindings that make it work..
- Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
- Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
- Widget.bind(self.canvasObject, "<Button1-ButtonRelease>", self.mouseUp)
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+
+ # this is a "tagOrId" for the rectangle we draw on the canvas
+ self.rubberbandBox = None
+
+ # and the bindings that make it work..
+ Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
+ Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
+ Widget.bind(self.canvasObject, "<Button1-ButtonRelease>", self.mouseUp)
test = Test()
diff --git a/Demo/tkinter/matt/rubber-line-demo-1.py b/Demo/tkinter/matt/rubber-line-demo-1.py
index f6d853560b..59b8bd9929 100644
--- a/Demo/tkinter/matt/rubber-line-demo-1.py
+++ b/Demo/tkinter/matt/rubber-line-demo-1.py
@@ -2,49 +2,49 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT',
- background='red',
- foreground='white',
- height=3,
- command=self.quit)
- self.QUIT.pack(side=BOTTOM, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT',
+ background='red',
+ foreground='white',
+ height=3,
+ command=self.quit)
+ self.QUIT.pack(side=BOTTOM, fill=BOTH)
- self.canvasObject = Canvas(self, width="5i", height="5i")
- self.canvasObject.pack(side=LEFT)
+ self.canvasObject = Canvas(self, width="5i", height="5i")
+ self.canvasObject.pack(side=LEFT)
def mouseDown(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- self.startx = self.canvasObject.canvasx(event.x)
- self.starty = self.canvasObject.canvasy(event.y)
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ self.startx = self.canvasObject.canvasx(event.x)
+ self.starty = self.canvasObject.canvasy(event.y)
def mouseMotion(self, event):
- # canvas x and y take the screen coords from the event and translate
- # them into the coordinate system of the canvas object
- x = self.canvasObject.canvasx(event.x)
- y = self.canvasObject.canvasy(event.y)
-
- if (self.startx != event.x) and (self.starty != event.y) :
- self.canvasObject.delete(self.rubberbandLine)
- self.rubberbandLine = self.canvasObject.create_line(
- self.startx, self.starty, x, y)
- # this flushes the output, making sure that
- # the rectangle makes it to the screen
- # before the next event is handled
- self.update_idletasks()
+ # canvas x and y take the screen coords from the event and translate
+ # them into the coordinate system of the canvas object
+ x = self.canvasObject.canvasx(event.x)
+ y = self.canvasObject.canvasy(event.y)
+
+ if (self.startx != event.x) and (self.starty != event.y) :
+ self.canvasObject.delete(self.rubberbandLine)
+ self.rubberbandLine = self.canvasObject.create_line(
+ self.startx, self.starty, x, y)
+ # this flushes the output, making sure that
+ # the rectangle makes it to the screen
+ # before the next event is handled
+ self.update_idletasks()
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
- # this is a "tagOrId" for the rectangle we draw on the canvas
- self.rubberbandLine = None
- Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
- Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
-
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
+ # this is a "tagOrId" for the rectangle we draw on the canvas
+ self.rubberbandLine = None
+ Widget.bind(self.canvasObject, "<Button-1>", self.mouseDown)
+ Widget.bind(self.canvasObject, "<Button1-Motion>", self.mouseMotion)
+
test = Test()
diff --git a/Demo/tkinter/matt/slider-demo-1.py b/Demo/tkinter/matt/slider-demo-1.py
index 40395df43c..db6114b1a3 100644
--- a/Demo/tkinter/matt/slider-demo-1.py
+++ b/Demo/tkinter/matt/slider-demo-1.py
@@ -5,32 +5,32 @@ from Tkinter import *
class Test(Frame):
def print_value(self, val):
- print "slider now at", val
+ print "slider now at", val
- def reset(self):
- self.slider.set(0)
+ def reset(self):
+ self.slider.set(0)
def createWidgets(self):
- self.slider = Scale(self, from_=0, to=100,
- orient=HORIZONTAL,
- length="3i",
- label="happy slider",
- command=self.print_value)
+ self.slider = Scale(self, from_=0, to=100,
+ orient=HORIZONTAL,
+ length="3i",
+ label="happy slider",
+ command=self.print_value)
- self.reset = Button(self, text='reset slider',
- command=self.reset)
+ self.reset = Button(self, text='reset slider',
+ command=self.reset)
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
- self.slider.pack(side=LEFT)
- self.reset.pack(side=LEFT)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.slider.pack(side=LEFT)
+ self.reset.pack(side=LEFT)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/subclass-existing-widgets.py b/Demo/tkinter/matt/subclass-existing-widgets.py
index e79dd5c875..0e08f92065 100644
--- a/Demo/tkinter/matt/subclass-existing-widgets.py
+++ b/Demo/tkinter/matt/subclass-existing-widgets.py
@@ -5,9 +5,9 @@ from Tkinter import *
class New_Button(Button):
def callback(self):
- print self.counter
- self.counter = self.counter + 1
-
+ print self.counter
+ self.counter = self.counter + 1
+
def createWidgets(top):
f = Frame(top)
f.pack()
@@ -26,4 +26,3 @@ def createWidgets(top):
root = Tk()
createWidgets(root)
root.mainloop()
-
diff --git a/Demo/tkinter/matt/two-radio-groups.py b/Demo/tkinter/matt/two-radio-groups.py
index 5c17333550..9fd8f4f07e 100644
--- a/Demo/tkinter/matt/two-radio-groups.py
+++ b/Demo/tkinter/matt/two-radio-groups.py
@@ -1,44 +1,44 @@
from Tkinter import *
-# The way to think about this is that each radio button menu
-# controls a different variable -- clicking on one of the
-# mutually exclusive choices in a radiobutton assigns some value
-# to an application variable you provide. When you define a
-# radiobutton menu choice, you have the option of specifying the
-# name of a varaible and value to assign to that variable when
-# that choice is selected. This clever mechanism relieves you,
-# the programmer, from having to write a dumb callback that
-# probably wouldn't have done anything more than an assignment
-# anyway. The Tkinter options for this follow their Tk
-# counterparts:
-# {"variable" : my_flavor_variable, "value" : "strawberry"}
+# The way to think about this is that each radio button menu
+# controls a different variable -- clicking on one of the
+# mutually exclusive choices in a radiobutton assigns some value
+# to an application variable you provide. When you define a
+# radiobutton menu choice, you have the option of specifying the
+# name of a varaible and value to assign to that variable when
+# that choice is selected. This clever mechanism relieves you,
+# the programmer, from having to write a dumb callback that
+# probably wouldn't have done anything more than an assignment
+# anyway. The Tkinter options for this follow their Tk
+# counterparts:
+# {"variable" : my_flavor_variable, "value" : "strawberry"}
# where my_flavor_variable is an instance of one of the
# subclasses of Variable, provided in Tkinter.py (there is
-# StringVar(), IntVar(), DoubleVar() and BooleanVar() to choose
-# from)
+# StringVar(), IntVar(), DoubleVar() and BooleanVar() to choose
+# from)
def makePoliticalParties(var):
- # make menu button
- Radiobutton_button = Menubutton(mBar, text='Political Party',
- underline=0)
+ # make menu button
+ Radiobutton_button = Menubutton(mBar, text='Political Party',
+ underline=0)
Radiobutton_button.pack(side=LEFT, padx='2m')
-
+
# the primary pulldown
Radiobutton_button.menu = Menu(Radiobutton_button)
- Radiobutton_button.menu.add_radiobutton(label='Republican',
- variable=var, value=1)
+ Radiobutton_button.menu.add_radiobutton(label='Republican',
+ variable=var, value=1)
+
+ Radiobutton_button.menu.add('radiobutton', {'label': 'Democrat',
+ 'variable' : var,
+ 'value' : 2})
- Radiobutton_button.menu.add('radiobutton', {'label': 'Democrat',
- 'variable' : var,
- 'value' : 2})
+ Radiobutton_button.menu.add('radiobutton', {'label': 'Libertarian',
+ 'variable' : var,
+ 'value' : 3})
- Radiobutton_button.menu.add('radiobutton', {'label': 'Libertarian',
- 'variable' : var,
- 'value' : 3})
-
var.set(2)
# set up a pointer from the file menubutton back to the file menu
@@ -48,22 +48,22 @@ def makePoliticalParties(var):
def makeFlavors(var):
- # make menu button
- Radiobutton_button = Menubutton(mBar, text='Flavors',
- underline=0)
+ # make menu button
+ Radiobutton_button = Menubutton(mBar, text='Flavors',
+ underline=0)
Radiobutton_button.pack(side=LEFT, padx='2m')
# the primary pulldown
Radiobutton_button.menu = Menu(Radiobutton_button)
Radiobutton_button.menu.add_radiobutton(label='Strawberry',
- variable=var, value='Strawberry')
+ variable=var, value='Strawberry')
Radiobutton_button.menu.add_radiobutton(label='Chocolate',
- variable=var, value='Chocolate')
+ variable=var, value='Chocolate')
Radiobutton_button.menu.add_radiobutton(label='Rocky Road',
- variable=var, value='Rocky Road')
+ variable=var, value='Rocky Road')
# choose a default
var.set("Chocolate")
@@ -88,7 +88,7 @@ root = Tk()
mBar = Frame(root, relief=RAISED, borderwidth=2)
mBar.pack(fill=X)
-# make two application variables,
+# make two application variables,
# one to control each radio button set
party = IntVar()
flavor = StringVar()
@@ -96,12 +96,12 @@ flavor = StringVar()
Radiobutton_button = makePoliticalParties(party)
Radiobutton_button2 = makeFlavors(flavor)
-# finally, install the buttons in the menu bar.
+# finally, install the buttons in the menu bar.
# This allows for scanning from one menubutton to the next.
mBar.tk_menuBar(Radiobutton_button, Radiobutton_button2)
b = Button(root, text="print party and flavor", foreground="red",
- command=printStuff)
+ command=printStuff)
b.pack(side=TOP)
root.title('menu demo')
diff --git a/Demo/tkinter/matt/window-creation-more.py b/Demo/tkinter/matt/window-creation-more.py
index 492027af60..eb0eb6fc1c 100644
--- a/Demo/tkinter/matt/window-creation-more.py
+++ b/Demo/tkinter/matt/window-creation-more.py
@@ -5,31 +5,31 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def makeWindow(self):
- fred = Toplevel()
- fred.label = Button(fred,
- text="This is window number %d." % self.windownum,
- command=self.makeWindow)
- fred.label.pack()
- self.windownum = self.windownum + 1
+ fred = Toplevel()
+ fred.label = Button(fred,
+ text="This is window number %d." % self.windownum,
+ command=self.makeWindow)
+ fred.label.pack()
+ self.windownum = self.windownum + 1
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- # a hello button
- self.hi_there = Button(self, text='Make a New Window',
- command=self.makeWindow)
- self.hi_there.pack(side=LEFT)
+ # a hello button
+ self.hi_there = Button(self, text='Make a New Window',
+ command=self.makeWindow)
+ self.hi_there.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.windownum = 0
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.windownum = 0
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/window-creation-simple.py b/Demo/tkinter/matt/window-creation-simple.py
index 969fefb186..c990ed9bf1 100644
--- a/Demo/tkinter/matt/window-creation-simple.py
+++ b/Demo/tkinter/matt/window-creation-simple.py
@@ -4,28 +4,28 @@ from Tkinter import *
class Test(Frame):
def printit(self):
- print "hi"
+ print "hi"
def makeWindow(self):
- fred = Toplevel()
- fred.label = Label(fred, text="Here's a new window")
- fred.label.pack()
+ fred = Toplevel()
+ fred.label = Label(fred, text="Here's a new window")
+ fred.label.pack()
def createWidgets(self):
- self.QUIT = Button(self, text='QUIT', foreground='red',
- command=self.quit)
-
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = Button(self, text='QUIT', foreground='red',
+ command=self.quit)
- # a hello button
- self.hi_there = Button(self, text='Make a New Window',
- command=self.makeWindow)
- self.hi_there.pack(side=LEFT)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
+
+ # a hello button
+ self.hi_there = Button(self, text='Make a New Window',
+ command=self.makeWindow)
+ self.hi_there.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/tkinter/matt/window-creation-w-location.py b/Demo/tkinter/matt/window-creation-w-location.py
index 0ec4e094ec..3f2b5b0695 100644
--- a/Demo/tkinter/matt/window-creation-w-location.py
+++ b/Demo/tkinter/matt/window-creation-w-location.py
@@ -17,29 +17,29 @@ class QuitButton(Button):
class Test(Frame):
def makeWindow(self, *args):
- fred = Toplevel()
+ fred = Toplevel()
- fred.label = Canvas (fred, width="2i", height="2i")
+ fred.label = Canvas (fred, width="2i", height="2i")
- fred.label.create_line("0", "0", "2i", "2i")
- fred.label.create_line("0", "2i", "2i", "0")
- fred.label.pack()
+ fred.label.create_line("0", "0", "2i", "2i")
+ fred.label.create_line("0", "2i", "2i", "0")
+ fred.label.pack()
- ##centerWindow(fred, self.master)
+ ##centerWindow(fred, self.master)
def createWidgets(self):
- self.QUIT = QuitButton(self)
- self.QUIT.pack(side=LEFT, fill=BOTH)
+ self.QUIT = QuitButton(self)
+ self.QUIT.pack(side=LEFT, fill=BOTH)
- self.makeWindow = Button(self, text='Make a New Window',
- width=50, height=20,
- command=self.makeWindow)
- self.makeWindow.pack(side=LEFT)
+ self.makeWindow = Button(self, text='Make a New Window',
+ width=50, height=20,
+ command=self.makeWindow)
+ self.makeWindow.pack(side=LEFT)
def __init__(self, master=None):
- Frame.__init__(self, master)
- Pack.config(self)
- self.createWidgets()
+ Frame.__init__(self, master)
+ Pack.config(self)
+ self.createWidgets()
test = Test()
test.mainloop()
diff --git a/Demo/xml/elem_count.py b/Demo/xml/elem_count.py
index 43161999a1..7b53189c7c 100644
--- a/Demo/xml/elem_count.py
+++ b/Demo/xml/elem_count.py
@@ -30,7 +30,7 @@ class FancyCounter(handler.ContentHandler):
for pair in self._attr_types.items():
print "%20s %d" % pair
-
+
parser = make_parser()
parser.setContentHandler(FancyCounter())
parser.parse(sys.argv[1])
diff --git a/Demo/xml/roundtrip.py b/Demo/xml/roundtrip.py
index e42bf1b3c7..8d7d4374c1 100644
--- a/Demo/xml/roundtrip.py
+++ b/Demo/xml/roundtrip.py
@@ -16,7 +16,7 @@ class ContentGenerator(handler.ContentHandler):
self._out = out
# ContentHandler methods
-
+
def startDocument(self):
self._out.write('<?xml version="1.0" encoding="iso-8859-1"?>\n')
@@ -34,7 +34,7 @@ class ContentGenerator(handler.ContentHandler):
def ignorableWhitespace(self, content):
self._out.write(content)
-
+
def processingInstruction(self, target, data):
self._out.write('<?%s %s?>' % (target, data))
diff --git a/Demo/xml/rss2html.py b/Demo/xml/rss2html.py
index df5d1c7c07..15c9891952 100644
--- a/Demo/xml/rss2html.py
+++ b/Demo/xml/rss2html.py
@@ -80,7 +80,7 @@ class RSSHandler(handler.ContentHandler):
if name == "rss":
self._out.write(bottom)
-
+
def characters(self, content):
self._text = self._text + content
diff --git a/Demo/zlib/minigzip.py b/Demo/zlib/minigzip.py
index dc99d9bc88..e2801de3be 100755
--- a/Demo/zlib/minigzip.py
+++ b/Demo/zlib/minigzip.py
@@ -9,7 +9,7 @@ def write32(output, value):
output.write(chr(value & 255)) ; value=value / 256
output.write(chr(value & 255)) ; value=value / 256
output.write(chr(value & 255))
-
+
def read32(input):
v=ord(input.read(1))
v=v+ (ord(input.read(1))<<8 )
@@ -19,9 +19,9 @@ def read32(input):
import zlib, sys
if len(sys.argv)!=2:
- print 'Usage: minigzip.py <filename>'
- print ' The file will be compressed or decompressed.'
- sys.exit(0)
+ print 'Usage: minigzip.py <filename>'
+ print ' The file will be compressed or decompressed.'
+ sys.exit(0)
filename=sys.argv[1]
compressing=1 ; outputname=filename+'.gz'
@@ -64,7 +64,7 @@ else:
# extra flags, and OS byte.
if flag & FEXTRA:
# Read & discard the extra field, if present
- xlen=ord(input.read(1))
+ xlen=ord(input.read(1))
xlen=xlen+256*ord(input.read(1))
input.read(xlen)
if flag & FNAME:
@@ -92,11 +92,11 @@ else:
decompdata=decompobj.flush()
output.write(decompdata) ; length=length+len(decompdata)
crcval=zlib.crc32(decompdata, crcval)
-
+
# We've read to the end of the file, so we have to rewind in order
# to reread the 8 bytes containing the CRC and the file size. The
# decompressor is smart and knows when to stop, so feeding it
- # extra data is harmless.
+ # extra data is harmless.
input.seek(-8, 2)
crc32=read32(input)
isize=read32(input)
@@ -104,4 +104,3 @@ else:
if isize!=length: print 'Incorrect length of data produced'
input.close() ; output.close()
-
diff --git a/Demo/zlib/zlibdemo.py b/Demo/zlib/zlibdemo.py
index 7c56e3e662..5a0ab63202 100755
--- a/Demo/zlib/zlibdemo.py
+++ b/Demo/zlib/zlibdemo.py
@@ -4,7 +4,7 @@ import zlib, sys
if len(sys.argv)>1: filename=sys.argv[1]
else: filename='zlibdemo.py'
print 'Reading', filename
-f=open(filename, 'r') # Get the data to compress
+f=open(filename, 'r') # Get the data to compress
s=f.read()
f.close()
@@ -24,7 +24,7 @@ decompressor=zlib.decompressobj()
comptext=decomp=''
for i in range(0, len(s), chunk):
comptext=comptext+compressor.compress(s[i:i+chunk])
-comptext=comptext+compressor.flush() # Don't forget to call flush()!!
+comptext=comptext+compressor.flush() # Don't forget to call flush()!!
for i in range(0, len(comptext), chunk):
decomp=decomp+decompressor.decompress(comptext[i:i+chunk])
@@ -33,4 +33,3 @@ decomp=decomp+decompressor.flush()
print 'Progressive compression (level 9):'
print ' Original:', len(s), 'Compressed:', len(comptext),
print 'Uncompressed:', len(decomp)
-
diff --git a/Lib/_threading_local.py b/Lib/_threading_local.py
index 209c03576c..c90fde0653 100644
--- a/Lib/_threading_local.py
+++ b/Lib/_threading_local.py
@@ -81,7 +81,7 @@ Now we have a default number:
2
an initial color:
-
+
>>> mydata.color
'red'
>>> del mydata.color
@@ -216,7 +216,7 @@ class local(_localbase):
# if enumerate fails, as it seems to do during
# shutdown, we'll skip cleanup under the assumption
# that there is nothing to clean up
- return
+ return
for thread in threads:
try:
@@ -228,7 +228,7 @@ class local(_localbase):
if key in __dict__:
try:
del __dict__[key]
- except KeyError:
+ except KeyError:
pass # didn't have anything in this thread
return __del__
diff --git a/Lib/asyncore.py b/Lib/asyncore.py
index 5f602195be..4fb12f1d71 100644
--- a/Lib/asyncore.py
+++ b/Lib/asyncore.py
@@ -268,7 +268,7 @@ class dispatcher:
reuse_constant = socket.SO_EXCLUSIVEADDRUSE
else:
reuse_constant = socket.SO_REUSEADDR
-
+
self.socket.setsockopt(
socket.SOL_SOCKET, reuse_constant,
self.socket.getsockopt(socket.SOL_SOCKET,
@@ -276,7 +276,7 @@ class dispatcher:
)
except socket.error:
pass
-
+
# ==================================================
# predicates for select()
# these are used as filters for the lists of sockets
diff --git a/Lib/bsddb/test/test_basics.py b/Lib/bsddb/test/test_basics.py
index 09571ab26e..155705df1d 100644
--- a/Lib/bsddb/test/test_basics.py
+++ b/Lib/bsddb/test/test_basics.py
@@ -301,7 +301,7 @@ class BasicTestCase(unittest.TestCase):
else:
txn = None
c = self.d.cursor(txn=txn)
-
+
rec = c.first()
count = 0
while rec is not None:
@@ -318,7 +318,7 @@ class BasicTestCase(unittest.TestCase):
else:
self.fail("unexpected DBNotFoundError")
assert c.get_current_size() == len(c.current()[1]), "%s != len(%r)" % (c.get_current_size(), c.current()[1])
-
+
assert count == self._numKeys
@@ -351,7 +351,7 @@ class BasicTestCase(unittest.TestCase):
rec = c.set('empty value')
assert rec[1] == ''
assert c.get_current_size() == 0
-
+
try:
n = c.set('bad key')
except db.DBNotFoundError, val:
diff --git a/Lib/cgitb.py b/Lib/cgitb.py
index d2870016a6..db46b25d60 100644
--- a/Lib/cgitb.py
+++ b/Lib/cgitb.py
@@ -42,13 +42,13 @@ def small(text):
return '<small>' + text + '</small>'
else:
return ''
-
+
def strong(text):
if text:
return '<strong>' + text + '</strong>'
else:
return ''
-
+
def grey(text):
if text:
return '<font color="#909090">' + text + '</font>'
diff --git a/Lib/curses/__init__.py b/Lib/curses/__init__.py
index 1838de8a69..aba540b70e 100644
--- a/Lib/curses/__init__.py
+++ b/Lib/curses/__init__.py
@@ -7,7 +7,7 @@ the package, and perhaps a particular module inside it.
from curses import textpad
curses.initwin()
...
-
+
"""
__revision__ = "$Id$"
@@ -29,13 +29,13 @@ def initscr():
for key, value in _curses.__dict__.items():
if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
setattr(curses, key, value)
-
+
return stdscr
# This is a similar wrapper for start_color(), which adds the COLORS and
# COLOR_PAIRS variables which are only available after start_color() is
# called.
-
+
def start_color():
import _curses, curses
retval = _curses.start_color()
@@ -43,7 +43,7 @@ def start_color():
curses.COLORS = _curses.COLORS
if hasattr(_curses, 'COLOR_PAIRS'):
curses.COLOR_PAIRS = _curses.COLOR_PAIRS
- return retval
+ return retval
# Import Python has_key() implementation if _curses doesn't contain has_key()
@@ -51,4 +51,3 @@ try:
has_key
except NameError:
from has_key import has_key
-
diff --git a/Lib/curses/has_key.py b/Lib/curses/has_key.py
index 0987952588..60b7be9942 100644
--- a/Lib/curses/has_key.py
+++ b/Lib/curses/has_key.py
@@ -8,154 +8,154 @@ import _curses
# Table mapping curses keys to the terminfo capability name
_capability_names = {
- _curses.KEY_A1: 'ka1',
- _curses.KEY_A3: 'ka3',
- _curses.KEY_B2: 'kb2',
- _curses.KEY_BACKSPACE: 'kbs',
- _curses.KEY_BEG: 'kbeg',
- _curses.KEY_BTAB: 'kcbt',
- _curses.KEY_C1: 'kc1',
- _curses.KEY_C3: 'kc3',
- _curses.KEY_CANCEL: 'kcan',
- _curses.KEY_CATAB: 'ktbc',
- _curses.KEY_CLEAR: 'kclr',
- _curses.KEY_CLOSE: 'kclo',
- _curses.KEY_COMMAND: 'kcmd',
- _curses.KEY_COPY: 'kcpy',
- _curses.KEY_CREATE: 'kcrt',
- _curses.KEY_CTAB: 'kctab',
- _curses.KEY_DC: 'kdch1',
- _curses.KEY_DL: 'kdl1',
- _curses.KEY_DOWN: 'kcud1',
- _curses.KEY_EIC: 'krmir',
- _curses.KEY_END: 'kend',
- _curses.KEY_ENTER: 'kent',
- _curses.KEY_EOL: 'kel',
- _curses.KEY_EOS: 'ked',
- _curses.KEY_EXIT: 'kext',
- _curses.KEY_F0: 'kf0',
- _curses.KEY_F1: 'kf1',
- _curses.KEY_F10: 'kf10',
- _curses.KEY_F11: 'kf11',
- _curses.KEY_F12: 'kf12',
- _curses.KEY_F13: 'kf13',
- _curses.KEY_F14: 'kf14',
- _curses.KEY_F15: 'kf15',
- _curses.KEY_F16: 'kf16',
- _curses.KEY_F17: 'kf17',
- _curses.KEY_F18: 'kf18',
- _curses.KEY_F19: 'kf19',
- _curses.KEY_F2: 'kf2',
- _curses.KEY_F20: 'kf20',
- _curses.KEY_F21: 'kf21',
- _curses.KEY_F22: 'kf22',
- _curses.KEY_F23: 'kf23',
- _curses.KEY_F24: 'kf24',
- _curses.KEY_F25: 'kf25',
- _curses.KEY_F26: 'kf26',
- _curses.KEY_F27: 'kf27',
- _curses.KEY_F28: 'kf28',
- _curses.KEY_F29: 'kf29',
- _curses.KEY_F3: 'kf3',
- _curses.KEY_F30: 'kf30',
- _curses.KEY_F31: 'kf31',
- _curses.KEY_F32: 'kf32',
- _curses.KEY_F33: 'kf33',
- _curses.KEY_F34: 'kf34',
- _curses.KEY_F35: 'kf35',
- _curses.KEY_F36: 'kf36',
- _curses.KEY_F37: 'kf37',
- _curses.KEY_F38: 'kf38',
- _curses.KEY_F39: 'kf39',
- _curses.KEY_F4: 'kf4',
- _curses.KEY_F40: 'kf40',
- _curses.KEY_F41: 'kf41',
- _curses.KEY_F42: 'kf42',
- _curses.KEY_F43: 'kf43',
- _curses.KEY_F44: 'kf44',
- _curses.KEY_F45: 'kf45',
- _curses.KEY_F46: 'kf46',
- _curses.KEY_F47: 'kf47',
- _curses.KEY_F48: 'kf48',
- _curses.KEY_F49: 'kf49',
- _curses.KEY_F5: 'kf5',
- _curses.KEY_F50: 'kf50',
- _curses.KEY_F51: 'kf51',
- _curses.KEY_F52: 'kf52',
- _curses.KEY_F53: 'kf53',
- _curses.KEY_F54: 'kf54',
- _curses.KEY_F55: 'kf55',
- _curses.KEY_F56: 'kf56',
- _curses.KEY_F57: 'kf57',
- _curses.KEY_F58: 'kf58',
- _curses.KEY_F59: 'kf59',
- _curses.KEY_F6: 'kf6',
- _curses.KEY_F60: 'kf60',
- _curses.KEY_F61: 'kf61',
- _curses.KEY_F62: 'kf62',
- _curses.KEY_F63: 'kf63',
- _curses.KEY_F7: 'kf7',
- _curses.KEY_F8: 'kf8',
- _curses.KEY_F9: 'kf9',
- _curses.KEY_FIND: 'kfnd',
- _curses.KEY_HELP: 'khlp',
- _curses.KEY_HOME: 'khome',
- _curses.KEY_IC: 'kich1',
- _curses.KEY_IL: 'kil1',
- _curses.KEY_LEFT: 'kcub1',
- _curses.KEY_LL: 'kll',
- _curses.KEY_MARK: 'kmrk',
- _curses.KEY_MESSAGE: 'kmsg',
- _curses.KEY_MOVE: 'kmov',
- _curses.KEY_NEXT: 'knxt',
- _curses.KEY_NPAGE: 'knp',
- _curses.KEY_OPEN: 'kopn',
- _curses.KEY_OPTIONS: 'kopt',
- _curses.KEY_PPAGE: 'kpp',
- _curses.KEY_PREVIOUS: 'kprv',
- _curses.KEY_PRINT: 'kprt',
- _curses.KEY_REDO: 'krdo',
- _curses.KEY_REFERENCE: 'kref',
- _curses.KEY_REFRESH: 'krfr',
- _curses.KEY_REPLACE: 'krpl',
- _curses.KEY_RESTART: 'krst',
- _curses.KEY_RESUME: 'kres',
- _curses.KEY_RIGHT: 'kcuf1',
- _curses.KEY_SAVE: 'ksav',
- _curses.KEY_SBEG: 'kBEG',
- _curses.KEY_SCANCEL: 'kCAN',
- _curses.KEY_SCOMMAND: 'kCMD',
- _curses.KEY_SCOPY: 'kCPY',
- _curses.KEY_SCREATE: 'kCRT',
- _curses.KEY_SDC: 'kDC',
- _curses.KEY_SDL: 'kDL',
- _curses.KEY_SELECT: 'kslt',
- _curses.KEY_SEND: 'kEND',
- _curses.KEY_SEOL: 'kEOL',
- _curses.KEY_SEXIT: 'kEXT',
- _curses.KEY_SF: 'kind',
- _curses.KEY_SFIND: 'kFND',
- _curses.KEY_SHELP: 'kHLP',
- _curses.KEY_SHOME: 'kHOM',
- _curses.KEY_SIC: 'kIC',
- _curses.KEY_SLEFT: 'kLFT',
- _curses.KEY_SMESSAGE: 'kMSG',
- _curses.KEY_SMOVE: 'kMOV',
- _curses.KEY_SNEXT: 'kNXT',
- _curses.KEY_SOPTIONS: 'kOPT',
- _curses.KEY_SPREVIOUS: 'kPRV',
- _curses.KEY_SPRINT: 'kPRT',
- _curses.KEY_SR: 'kri',
- _curses.KEY_SREDO: 'kRDO',
- _curses.KEY_SREPLACE: 'kRPL',
- _curses.KEY_SRIGHT: 'kRIT',
- _curses.KEY_SRSUME: 'kRES',
- _curses.KEY_SSAVE: 'kSAV',
- _curses.KEY_SSUSPEND: 'kSPD',
- _curses.KEY_STAB: 'khts',
- _curses.KEY_SUNDO: 'kUND',
- _curses.KEY_SUSPEND: 'kspd',
- _curses.KEY_UNDO: 'kund',
+ _curses.KEY_A1: 'ka1',
+ _curses.KEY_A3: 'ka3',
+ _curses.KEY_B2: 'kb2',
+ _curses.KEY_BACKSPACE: 'kbs',
+ _curses.KEY_BEG: 'kbeg',
+ _curses.KEY_BTAB: 'kcbt',
+ _curses.KEY_C1: 'kc1',
+ _curses.KEY_C3: 'kc3',
+ _curses.KEY_CANCEL: 'kcan',
+ _curses.KEY_CATAB: 'ktbc',
+ _curses.KEY_CLEAR: 'kclr',
+ _curses.KEY_CLOSE: 'kclo',
+ _curses.KEY_COMMAND: 'kcmd',
+ _curses.KEY_COPY: 'kcpy',
+ _curses.KEY_CREATE: 'kcrt',
+ _curses.KEY_CTAB: 'kctab',
+ _curses.KEY_DC: 'kdch1',
+ _curses.KEY_DL: 'kdl1',
+ _curses.KEY_DOWN: 'kcud1',
+ _curses.KEY_EIC: 'krmir',
+ _curses.KEY_END: 'kend',
+ _curses.KEY_ENTER: 'kent',
+ _curses.KEY_EOL: 'kel',
+ _curses.KEY_EOS: 'ked',
+ _curses.KEY_EXIT: 'kext',
+ _curses.KEY_F0: 'kf0',
+ _curses.KEY_F1: 'kf1',
+ _curses.KEY_F10: 'kf10',
+ _curses.KEY_F11: 'kf11',
+ _curses.KEY_F12: 'kf12',
+ _curses.KEY_F13: 'kf13',
+ _curses.KEY_F14: 'kf14',
+ _curses.KEY_F15: 'kf15',
+ _curses.KEY_F16: 'kf16',
+ _curses.KEY_F17: 'kf17',
+ _curses.KEY_F18: 'kf18',
+ _curses.KEY_F19: 'kf19',
+ _curses.KEY_F2: 'kf2',
+ _curses.KEY_F20: 'kf20',
+ _curses.KEY_F21: 'kf21',
+ _curses.KEY_F22: 'kf22',
+ _curses.KEY_F23: 'kf23',
+ _curses.KEY_F24: 'kf24',
+ _curses.KEY_F25: 'kf25',
+ _curses.KEY_F26: 'kf26',
+ _curses.KEY_F27: 'kf27',
+ _curses.KEY_F28: 'kf28',
+ _curses.KEY_F29: 'kf29',
+ _curses.KEY_F3: 'kf3',
+ _curses.KEY_F30: 'kf30',
+ _curses.KEY_F31: 'kf31',
+ _curses.KEY_F32: 'kf32',
+ _curses.KEY_F33: 'kf33',
+ _curses.KEY_F34: 'kf34',
+ _curses.KEY_F35: 'kf35',
+ _curses.KEY_F36: 'kf36',
+ _curses.KEY_F37: 'kf37',
+ _curses.KEY_F38: 'kf38',
+ _curses.KEY_F39: 'kf39',
+ _curses.KEY_F4: 'kf4',
+ _curses.KEY_F40: 'kf40',
+ _curses.KEY_F41: 'kf41',
+ _curses.KEY_F42: 'kf42',
+ _curses.KEY_F43: 'kf43',
+ _curses.KEY_F44: 'kf44',
+ _curses.KEY_F45: 'kf45',
+ _curses.KEY_F46: 'kf46',
+ _curses.KEY_F47: 'kf47',
+ _curses.KEY_F48: 'kf48',
+ _curses.KEY_F49: 'kf49',
+ _curses.KEY_F5: 'kf5',
+ _curses.KEY_F50: 'kf50',
+ _curses.KEY_F51: 'kf51',
+ _curses.KEY_F52: 'kf52',
+ _curses.KEY_F53: 'kf53',
+ _curses.KEY_F54: 'kf54',
+ _curses.KEY_F55: 'kf55',
+ _curses.KEY_F56: 'kf56',
+ _curses.KEY_F57: 'kf57',
+ _curses.KEY_F58: 'kf58',
+ _curses.KEY_F59: 'kf59',
+ _curses.KEY_F6: 'kf6',
+ _curses.KEY_F60: 'kf60',
+ _curses.KEY_F61: 'kf61',
+ _curses.KEY_F62: 'kf62',
+ _curses.KEY_F63: 'kf63',
+ _curses.KEY_F7: 'kf7',
+ _curses.KEY_F8: 'kf8',
+ _curses.KEY_F9: 'kf9',
+ _curses.KEY_FIND: 'kfnd',
+ _curses.KEY_HELP: 'khlp',
+ _curses.KEY_HOME: 'khome',
+ _curses.KEY_IC: 'kich1',
+ _curses.KEY_IL: 'kil1',
+ _curses.KEY_LEFT: 'kcub1',
+ _curses.KEY_LL: 'kll',
+ _curses.KEY_MARK: 'kmrk',
+ _curses.KEY_MESSAGE: 'kmsg',
+ _curses.KEY_MOVE: 'kmov',
+ _curses.KEY_NEXT: 'knxt',
+ _curses.KEY_NPAGE: 'knp',
+ _curses.KEY_OPEN: 'kopn',
+ _curses.KEY_OPTIONS: 'kopt',
+ _curses.KEY_PPAGE: 'kpp',
+ _curses.KEY_PREVIOUS: 'kprv',
+ _curses.KEY_PRINT: 'kprt',
+ _curses.KEY_REDO: 'krdo',
+ _curses.KEY_REFERENCE: 'kref',
+ _curses.KEY_REFRESH: 'krfr',
+ _curses.KEY_REPLACE: 'krpl',
+ _curses.KEY_RESTART: 'krst',
+ _curses.KEY_RESUME: 'kres',
+ _curses.KEY_RIGHT: 'kcuf1',
+ _curses.KEY_SAVE: 'ksav',
+ _curses.KEY_SBEG: 'kBEG',
+ _curses.KEY_SCANCEL: 'kCAN',
+ _curses.KEY_SCOMMAND: 'kCMD',
+ _curses.KEY_SCOPY: 'kCPY',
+ _curses.KEY_SCREATE: 'kCRT',
+ _curses.KEY_SDC: 'kDC',
+ _curses.KEY_SDL: 'kDL',
+ _curses.KEY_SELECT: 'kslt',
+ _curses.KEY_SEND: 'kEND',
+ _curses.KEY_SEOL: 'kEOL',
+ _curses.KEY_SEXIT: 'kEXT',
+ _curses.KEY_SF: 'kind',
+ _curses.KEY_SFIND: 'kFND',
+ _curses.KEY_SHELP: 'kHLP',
+ _curses.KEY_SHOME: 'kHOM',
+ _curses.KEY_SIC: 'kIC',
+ _curses.KEY_SLEFT: 'kLFT',
+ _curses.KEY_SMESSAGE: 'kMSG',
+ _curses.KEY_SMOVE: 'kMOV',
+ _curses.KEY_SNEXT: 'kNXT',
+ _curses.KEY_SOPTIONS: 'kOPT',
+ _curses.KEY_SPREVIOUS: 'kPRV',
+ _curses.KEY_SPRINT: 'kPRT',
+ _curses.KEY_SR: 'kri',
+ _curses.KEY_SREDO: 'kRDO',
+ _curses.KEY_SREPLACE: 'kRPL',
+ _curses.KEY_SRIGHT: 'kRIT',
+ _curses.KEY_SRSUME: 'kRES',
+ _curses.KEY_SSAVE: 'kSAV',
+ _curses.KEY_SSUSPEND: 'kSPD',
+ _curses.KEY_STAB: 'khts',
+ _curses.KEY_SUNDO: 'kUND',
+ _curses.KEY_SUSPEND: 'kspd',
+ _curses.KEY_UNDO: 'kund',
_curses.KEY_UP: 'kcuu1'
}
@@ -190,5 +190,3 @@ if __name__ == '__main__':
finally:
_curses.endwin()
for i in L: print i
-
-
diff --git a/Lib/curses/panel.py b/Lib/curses/panel.py
index 2c86d4cf36..aacca85151 100644
--- a/Lib/curses/panel.py
+++ b/Lib/curses/panel.py
@@ -6,4 +6,3 @@ Module for using panels with curses.
__revision__ = "$Id$"
from _curses_panel import *
-
diff --git a/Lib/distutils/archive_util.py b/Lib/distutils/archive_util.py
index d5b3096617..55babe6fc6 100644
--- a/Lib/distutils/archive_util.py
+++ b/Lib/distutils/archive_util.py
@@ -68,7 +68,7 @@ def make_zipfile (base_name, base_dir, verbose=0, dry_run=0):
import zipfile
except ImportError:
zipfile = None
-
+
zip_filename = base_name + ".zip"
mkpath(os.path.dirname(zip_filename), dry_run=dry_run)
@@ -79,7 +79,7 @@ def make_zipfile (base_name, base_dir, verbose=0, dry_run=0):
zipoptions = "-r"
else:
zipoptions = "-rq"
-
+
try:
spawn(["zip", zipoptions, zip_filename, base_dir],
dry_run=dry_run)
diff --git a/Lib/distutils/bcppcompiler.py b/Lib/distutils/bcppcompiler.py
index b0360a248e..f995e36711 100644
--- a/Lib/distutils/bcppcompiler.py
+++ b/Lib/distutils/bcppcompiler.py
@@ -85,7 +85,7 @@ class BCPPCompiler(CCompiler) :
def compile(self, sources,
output_dir=None, macros=None, include_dirs=None, debug=0,
extra_preargs=None, extra_postargs=None, depends=None):
-
+
macros, objects, extra_postargs, pp_opts, build = \
self._setup_compile(output_dir, macros, include_dirs, sources,
depends, extra_postargs)
diff --git a/Lib/distutils/ccompiler.py b/Lib/distutils/ccompiler.py
index ebd93c27eb..a3b1ffa4d5 100644
--- a/Lib/distutils/ccompiler.py
+++ b/Lib/distutils/ccompiler.py
@@ -685,7 +685,7 @@ class CCompiler:
# A concrete compiler class can either override this method
# entirely or implement _compile().
-
+
macros, objects, extra_postargs, pp_opts, build = \
self._setup_compile(output_dir, macros, include_dirs, sources,
depends, extra_postargs)
@@ -703,7 +703,7 @@ class CCompiler:
def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
"""Compile 'src' to product 'obj'."""
-
+
# A concrete compiler class that does not override compile()
# should implement _compile().
pass
diff --git a/Lib/distutils/cmd.py b/Lib/distutils/cmd.py
index 9362410487..be8e826fdb 100644
--- a/Lib/distutils/cmd.py
+++ b/Lib/distutils/cmd.py
@@ -79,7 +79,7 @@ class Command:
# verbose is largely ignored, but needs to be set for
# backwards compatibility (I think)?
self.verbose = dist.verbose
-
+
# Some commands define a 'self.force' option to ignore file
# timestamps, but methods defined *here* assume that
# 'self.force' exists for all commands. So define it here
@@ -100,7 +100,7 @@ class Command:
# XXX A more explicit way to customize dry_run would be better.
-
+
def __getattr__ (self, attr):
if attr == 'dry_run':
myval = getattr(self, "_" + attr)
diff --git a/Lib/distutils/command/bdist.py b/Lib/distutils/command/bdist.py
index 7c606ffc4d..4eca9c3426 100644
--- a/Lib/distutils/command/bdist.py
+++ b/Lib/distutils/command/bdist.py
@@ -78,7 +78,7 @@ class bdist (Command):
'wininst': ('bdist_wininst',
"Windows executable installer"),
'zip': ('bdist_dumb', "ZIP file"),
- #'pkgtool': ('bdist_pkgtool',
+ #'pkgtool': ('bdist_pkgtool',
# "Solaris pkgtool distribution"),
#'sdux': ('bdist_sdux', "HP-UX swinstall depot"),
}
diff --git a/Lib/distutils/command/bdist_dumb.py b/Lib/distutils/command/bdist_dumb.py
index 8ee3a5c5f7..3db332d5bd 100644
--- a/Lib/distutils/command/bdist_dumb.py
+++ b/Lib/distutils/command/bdist_dumb.py
@@ -53,7 +53,7 @@ class bdist_dumb (Command):
self.dist_dir = None
self.skip_build = 0
self.relative = 0
-
+
# initialize_options()
diff --git a/Lib/distutils/command/bdist_wininst.py b/Lib/distutils/command/bdist_wininst.py
index 7c593adcaa..d91c08936c 100644
--- a/Lib/distutils/command/bdist_wininst.py
+++ b/Lib/distutils/command/bdist_wininst.py
@@ -115,7 +115,7 @@ class bdist_wininst (Command):
# we do not want to include pyc or pyo files
install_lib.compile = 0
install_lib.optimize = 0
-
+
# If we are building an installer for a Python version other
# than the one we are currently running, then we need to ensure
# our build_lib reflects the other Python version rather than ours.
diff --git a/Lib/distutils/command/build_ext.py b/Lib/distutils/command/build_ext.py
index 0c37768179..04cd742cef 100644
--- a/Lib/distutils/command/build_ext.py
+++ b/Lib/distutils/command/build_ext.py
@@ -173,7 +173,7 @@ class build_ext (Command):
self.include_dirs.append(os.path.join(sys.exec_prefix, 'PC'))
self.library_dirs.append(os.path.join(sys.exec_prefix, 'PCBuild'))
- # OS/2 (EMX) doesn't support Debug vs Release builds, but has the
+ # OS/2 (EMX) doesn't support Debug vs Release builds, but has the
# import libraries in its "Config" subdirectory
if os.name == 'os2':
self.library_dirs.append(os.path.join(sys.exec_prefix, 'Config'))
@@ -636,7 +636,7 @@ class build_ext (Command):
# EMX/GCC requires the python library explicitly, and I
# believe VACPP does as well (though not confirmed) - AIM Apr01
template = "python%d%d"
- # debug versions of the main DLL aren't supported, at least
+ # debug versions of the main DLL aren't supported, at least
# not at this time - AIM Apr01
#if self.debug:
# template = template + '_d'
diff --git a/Lib/distutils/command/build_scripts.py b/Lib/distutils/command/build_scripts.py
index 165a009ded..e0fcc23e13 100644
--- a/Lib/distutils/command/build_scripts.py
+++ b/Lib/distutils/command/build_scripts.py
@@ -94,7 +94,7 @@ class build_scripts (Command):
if not self.dry_run:
outf = open(outfile, "w")
if not sysconfig.python_build:
- outf.write("#!%s%s\n" %
+ outf.write("#!%s%s\n" %
(os.path.normpath(sys.executable),
post_interp))
else:
diff --git a/Lib/distutils/command/install.py b/Lib/distutils/command/install.py
index 3c36ede622..175f785214 100644
--- a/Lib/distutils/command/install.py
+++ b/Lib/distutils/command/install.py
@@ -537,7 +537,7 @@ class install (Command):
not (self.path_file and self.install_path_file) and
install_lib not in sys_path):
log.debug(("modules installed to '%s', which is not in "
- "Python's module search path (sys.path) -- "
+ "Python's module search path (sys.path) -- "
"you'll have to change the search path yourself"),
self.install_lib)
diff --git a/Lib/distutils/command/register.py b/Lib/distutils/command/register.py
index 8e347ce6dc..8104ce0656 100644
--- a/Lib/distutils/command/register.py
+++ b/Lib/distutils/command/register.py
@@ -286,4 +286,3 @@ Your selection [default 1]: ''',
if self.show_response:
print '-'*75, data, '-'*75
return result
-
diff --git a/Lib/distutils/core.py b/Lib/distutils/core.py
index fba463c10b..fef291f656 100644
--- a/Lib/distutils/core.py
+++ b/Lib/distutils/core.py
@@ -239,4 +239,3 @@ def run_setup (script_name, script_args=None, stop_after="run"):
return _setup_distribution
# run_setup ()
-
diff --git a/Lib/distutils/cygwinccompiler.py b/Lib/distutils/cygwinccompiler.py
index 0101bae5b9..a962007601 100644
--- a/Lib/distutils/cygwinccompiler.py
+++ b/Lib/distutils/cygwinccompiler.py
@@ -75,7 +75,7 @@ class CygwinCCompiler (UnixCCompiler):
(status, details))
if status is not CONFIG_H_OK:
self.warn(
- "Python's pyconfig.h doesn't seem to support your compiler. "
+ "Python's pyconfig.h doesn't seem to support your compiler. "
"Reason: %s. "
"Compiling may fail because of undefined preprocessor macros."
% details)
diff --git a/Lib/distutils/debug.py b/Lib/distutils/debug.py
index e195ebdcdf..2a87eb5d28 100644
--- a/Lib/distutils/debug.py
+++ b/Lib/distutils/debug.py
@@ -7,4 +7,3 @@ __revision__ = "$Id$"
# If DISTUTILS_DEBUG is anything other than the empty string, we run in
# debug mode.
DEBUG = os.environ.get('DISTUTILS_DEBUG')
-
diff --git a/Lib/distutils/dir_util.py b/Lib/distutils/dir_util.py
index e479b62415..77f64c4104 100644
--- a/Lib/distutils/dir_util.py
+++ b/Lib/distutils/dir_util.py
@@ -225,4 +225,3 @@ def ensure_relative (path):
if path[0:1] == os.sep:
path = drive + path[1:]
return path
-
diff --git a/Lib/distutils/dist.py b/Lib/distutils/dist.py
index 7d0a7bad3c..b4dd0b9170 100644
--- a/Lib/distutils/dist.py
+++ b/Lib/distutils/dist.py
@@ -231,7 +231,7 @@ class Distribution:
newreq.append((pkg, LooseVersion(ver)))
attrs['requires'] = newreq
- # Build up the provides object. If the setup() has no
+ # Build up the provides object. If the setup() has no
# provides line, we use packages or modules and the version
# to synthesise the provides. If no version is provided (no
# pun intended) we don't have a provides entry at all.
@@ -1137,7 +1137,7 @@ class DistributionMetadata:
return self.download_url or "UNKNOWN"
def get_requires(self):
- return [ '%s%s%s'%(x, (y and '-') or '', y or '')
+ return [ '%s%s%s'%(x, (y and '-') or '', y or '')
for x,y in self.requires ]
def get_provides(self):
diff --git a/Lib/distutils/file_util.py b/Lib/distutils/file_util.py
index e230ce587e..e2b1c51558 100644
--- a/Lib/distutils/file_util.py
+++ b/Lib/distutils/file_util.py
@@ -42,7 +42,7 @@ def _copy_file_contents (src, dst, buffer_size=16*1024):
except os.error, (errno, errstr):
raise DistutilsFileError, \
"could not delete '%s': %s" % (dst, errstr)
-
+
try:
fdst = open(dst, 'wb')
except os.error, (errno, errstr):
diff --git a/Lib/distutils/filelist.py b/Lib/distutils/filelist.py
index 0872e96636..566d87ab28 100644
--- a/Lib/distutils/filelist.py
+++ b/Lib/distutils/filelist.py
@@ -167,7 +167,7 @@ class FileList:
for pattern in patterns:
if not self.include_pattern(pattern, prefix=dir):
log.warn(("warning: no files found matching '%s' " +
- "under directory '%s'"),
+ "under directory '%s'"),
pattern, dir)
elif action == 'recursive-exclude':
diff --git a/Lib/distutils/log.py b/Lib/distutils/log.py
index 01420da9af..024e7c28de 100644
--- a/Lib/distutils/log.py
+++ b/Lib/distutils/log.py
@@ -28,16 +28,16 @@ class Log:
def debug(self, msg, *args):
self._log(DEBUG, msg, args)
-
+
def info(self, msg, *args):
self._log(INFO, msg, args)
-
+
def warn(self, msg, *args):
self._log(WARN, msg, args)
-
+
def error(self, msg, *args):
self._log(ERROR, msg, args)
-
+
def fatal(self, msg, *args):
self._log(FATAL, msg, args)
diff --git a/Lib/distutils/msvccompiler.py b/Lib/distutils/msvccompiler.py
index 1441ea04c3..168881ad2d 100644
--- a/Lib/distutils/msvccompiler.py
+++ b/Lib/distutils/msvccompiler.py
@@ -117,7 +117,7 @@ class MacroExpander:
if d:
self.macros["$(%s)" % macro] = d[key]
break
-
+
def load_macros(self, version):
vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version
self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir")
@@ -166,7 +166,7 @@ def get_build_version():
return majorVersion + minorVersion
# else we don't know what version of the compiler this is
return None
-
+
class MSVCCompiler (CCompiler) :
"""Concrete class that implements an interface to Microsoft Visual C++,
@@ -525,7 +525,7 @@ class MSVCCompiler (CCompiler) :
return fn
return exe
-
+
def get_msvc_paths(self, path, platform='x86'):
"""Get a list of devstudio directories (include, lib or path).
@@ -576,4 +576,3 @@ class MSVCCompiler (CCompiler) :
p = self.get_msvc_paths(name)
if p:
os.environ[name] = string.join(p, ';')
-
diff --git a/Lib/distutils/spawn.py b/Lib/distutils/spawn.py
index 67391e8826..a89b88cebf 100644
--- a/Lib/distutils/spawn.py
+++ b/Lib/distutils/spawn.py
@@ -97,7 +97,7 @@ def _spawn_os2 (cmd,
#cmd = _nt_quote_args(cmd)
if search_path:
# either we find one or it stays the same
- executable = find_executable(executable) or executable
+ executable = find_executable(executable) or executable
log.info(string.join([executable] + cmd[1:], ' '))
if not dry_run:
# spawnv for OS/2 EMX requires a full path to the .exe
diff --git a/Lib/distutils/sysconfig.py b/Lib/distutils/sysconfig.py
index c912a15cdc..0a4e14cc37 100644
--- a/Lib/distutils/sysconfig.py
+++ b/Lib/distutils/sysconfig.py
@@ -367,7 +367,7 @@ def _init_posix():
my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'
% (cur_target, cfg_target))
raise DistutilsPlatformError(my_msg)
-
+
# On AIX, there are wrong paths to the linker scripts in the Makefile
# -- these paths are relative to the Python source, but when installed
# the scripts are in another directory.
diff --git a/Lib/distutils/unixccompiler.py b/Lib/distutils/unixccompiler.py
index 11ecb9f6ae..24cbcb53e5 100644
--- a/Lib/distutils/unixccompiler.py
+++ b/Lib/distutils/unixccompiler.py
@@ -206,7 +206,7 @@ class UnixCCompiler(CCompiler):
elif sys.platform[:5] == "hp-ux":
return "+s -L" + dir
elif compiler[:3] == "gcc" or compiler[:3] == "g++":
- return "-Wl,-R" + dir
+ return "-Wl,-R" + dir
else:
return "-R" + dir
@@ -217,7 +217,7 @@ class UnixCCompiler(CCompiler):
shared_f = self.library_filename(lib, lib_type='shared')
dylib_f = self.library_filename(lib, lib_type='dylib')
static_f = self.library_filename(lib, lib_type='static')
-
+
for dir in dirs:
shared = os.path.join(dir, shared_f)
dylib = os.path.join(dir, dylib_f)
@@ -232,6 +232,6 @@ class UnixCCompiler(CCompiler):
return shared
elif os.path.exists(static):
return static
-
+
# Oops, didn't find it in *any* of 'dirs'
return None
diff --git a/Lib/distutils/util.py b/Lib/distutils/util.py
index 12775d6fc4..387e9bdc93 100644
--- a/Lib/distutils/util.py
+++ b/Lib/distutils/util.py
@@ -300,7 +300,7 @@ def execute (func, args, msg=None, verbose=0, dry_run=0):
def strtobool (val):
"""Convert a string representation of truth to true (1) or false (0).
-
+
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
'val' is anything else.
diff --git a/Lib/dummy_threading.py b/Lib/dummy_threading.py
index 4d0b744a1d..48f7c4c746 100644
--- a/Lib/dummy_threading.py
+++ b/Lib/dummy_threading.py
@@ -46,7 +46,7 @@ try:
held__threading_local = sys_modules['_threading_local']
holding__threading_local = True
del sys_modules['_threading_local']
-
+
import threading
# Need a copy of the code kept somewhere...
sys_modules['_dummy_threading'] = sys_modules['threading']
diff --git a/Lib/lib-old/Para.py b/Lib/lib-old/Para.py
index 2e6aa4cd4a..2fd8dc6499 100644
--- a/Lib/lib-old/Para.py
+++ b/Lib/lib-old/Para.py
@@ -1,4 +1,4 @@
-# Text formatting abstractions
+# Text formatting abstractions
# Note -- this module is obsolete, it's too slow anyway
@@ -14,330 +14,330 @@ Int = type(0)
# different screen locations. Once rendered, it can be queried
# for mouse hits, and parts of the text can be highlighted
class Para:
- #
- def __init__(self):
- self.words = [] # The words
- self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c'
- self.indent_left = self.indent_right = self.indent_hang = 0
- # Final lay-out parameters, may change
- self.left = self.top = self.right = self.bottom = \
- self.width = self.height = self.lines = None
- #
- # Add a word, computing size information for it.
- # Words may also be added manually by appending to self.words
- # Each word should be a 7-tuple:
- # (font, text, width, space, stretch, ascent, descent)
- def addword(self, d, font, text, space, stretch):
- if font is not None:
- d.setfont(font)
- width = d.textwidth(text)
- ascent = d.baseline()
- descent = d.lineheight() - ascent
- spw = d.textwidth(' ')
- space = space * spw
- stretch = stretch * spw
- tuple = (font, text, width, space, stretch, ascent, descent)
- self.words.append(tuple)
- #
- # Hooks to begin and end anchors -- insert numbers in the word list!
- def bgn_anchor(self, id):
- self.words.append(id)
- #
- def end_anchor(self, id):
- self.words.append(0)
- #
- # Return the total length (width) of the text added so far, in pixels
- def getlength(self):
- total = 0
- for word in self.words:
- if type(word) is not Int:
- total = total + word[2] + word[3]
- return total
- #
- # Tab to a given position (relative to the current left indent):
- # remove all stretch, add fixed space up to the new indent.
- # If the current position is already at the tab stop,
- # don't add any new space (but still remove the stretch)
- def tabto(self, tab):
- total = 0
- as, de = 1, 0
- for i in range(len(self.words)):
- word = self.words[i]
- if type(word) is Int: continue
- (fo, te, wi, sp, st, as, de) = word
- self.words[i] = (fo, te, wi, sp, 0, as, de)
- total = total + wi + sp
- if total < tab:
- self.words.append((None, '', 0, tab-total, 0, as, de))
- #
- # Make a hanging tag: tab to hang, increment indent_left by hang,
- # and reset indent_hang to -hang
- def makehangingtag(self, hang):
- self.tabto(hang)
- self.indent_left = self.indent_left + hang
- self.indent_hang = -hang
- #
- # Decide where the line breaks will be given some screen width
- def layout(self, linewidth):
- self.width = linewidth
- height = 0
- self.lines = lines = []
- avail1 = self.width - self.indent_left - self.indent_right
- avail = avail1 - self.indent_hang
- words = self.words
- i = 0
- n = len(words)
- lastfont = None
- while i < n:
- firstfont = lastfont
- charcount = 0
- width = 0
- stretch = 0
- ascent = 0
- descent = 0
- lsp = 0
- j = i
- while i < n:
- word = words[i]
- if type(word) is Int:
- if word > 0 and width >= avail:
- break
- i = i+1
- continue
- fo, te, wi, sp, st, as, de = word
- if width + wi > avail and width > 0 and wi > 0:
- break
- if fo is not None:
- lastfont = fo
- if width == 0:
- firstfont = fo
- charcount = charcount + len(te) + (sp > 0)
- width = width + wi + sp
- lsp = sp
- stretch = stretch + st
- lst = st
- ascent = max(ascent, as)
- descent = max(descent, de)
- i = i+1
- while i > j and type(words[i-1]) is Int and \
- words[i-1] > 0: i = i-1
- width = width - lsp
- if i < n:
- stretch = stretch - lst
- else:
- stretch = 0
- tuple = i-j, firstfont, charcount, width, stretch, \
- ascent, descent
- lines.append(tuple)
- height = height + ascent + descent
- avail = avail1
- self.height = height
- #
- # Call a function for all words in a line
- def visit(self, wordfunc, anchorfunc):
- avail1 = self.width - self.indent_left - self.indent_right
- avail = avail1 - self.indent_hang
- v = self.top
- i = 0
- for tuple in self.lines:
- wordcount, firstfont, charcount, width, stretch, \
- ascent, descent = tuple
- h = self.left + self.indent_left
- if i == 0: h = h + self.indent_hang
- extra = 0
- if self.just == 'r': h = h + avail - width
- elif self.just == 'c': h = h + (avail - width) / 2
- elif self.just == 'lr' and stretch > 0:
- extra = avail - width
- v2 = v + ascent + descent
- for j in range(i, i+wordcount):
- word = self.words[j]
- if type(word) is Int:
- ok = anchorfunc(self, tuple, word, \
- h, v)
- if ok is not None: return ok
- continue
- fo, te, wi, sp, st, as, de = word
- if extra > 0 and stretch > 0:
- ex = extra * st / stretch
- extra = extra - ex
- stretch = stretch - st
- else:
- ex = 0
- h2 = h + wi + sp + ex
- ok = wordfunc(self, tuple, word, h, v, \
- h2, v2, (j==i), (j==i+wordcount-1))
- if ok is not None: return ok
- h = h2
- v = v2
- i = i + wordcount
- avail = avail1
- #
- # Render a paragraph in "drawing object" d, using the rectangle
- # given by (left, top, right) with an unspecified bottom.
- # Return the computed bottom of the text.
- def render(self, d, left, top, right):
- if self.width != right-left:
- self.layout(right-left)
- self.left = left
- self.top = top
- self.right = right
- self.bottom = self.top + self.height
- self.anchorid = 0
- try:
- self.d = d
- self.visit(self.__class__._renderword, \
- self.__class__._renderanchor)
- finally:
- self.d = None
- return self.bottom
- #
- def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast):
- if word[0] is not None: self.d.setfont(word[0])
- baseline = v + tuple[5]
- self.d.text((h, baseline - word[5]), word[1])
- if self.anchorid > 0:
- self.d.line((h, baseline+2), (h2, baseline+2))
- #
- def _renderanchor(self, tuple, word, h, v):
- self.anchorid = word
- #
- # Return which anchor(s) was hit by the mouse
- def hitcheck(self, mouseh, mousev):
- self.mouseh = mouseh
- self.mousev = mousev
- self.anchorid = 0
- self.hits = []
- self.visit(self.__class__._hitcheckword, \
- self.__class__._hitcheckanchor)
- return self.hits
- #
- def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast):
- if self.anchorid > 0 and h <= self.mouseh <= h2 and \
- v <= self.mousev <= v2:
- self.hits.append(self.anchorid)
- #
- def _hitcheckanchor(self, tuple, word, h, v):
- self.anchorid = word
- #
- # Return whether the given anchor id is present
- def hasanchor(self, id):
- return id in self.words or -id in self.words
- #
- # Extract the raw text from the word list, substituting one space
- # for non-empty inter-word space, and terminating with '\n'
- def extract(self):
- text = ''
- for w in self.words:
- if type(w) is not Int:
- word = w[1]
- if w[3]: word = word + ' '
- text = text + word
- return text + '\n'
- #
- # Return which character position was hit by the mouse, as
- # an offset in the entire text as returned by extract().
- # Return None if the mouse was not in this paragraph
- def whereis(self, d, mouseh, mousev):
- if mousev < self.top or mousev > self.bottom:
- return None
- self.mouseh = mouseh
- self.mousev = mousev
- self.lastfont = None
- self.charcount = 0
- try:
- self.d = d
- return self.visit(self.__class__._whereisword, \
- self.__class__._whereisanchor)
- finally:
- self.d = None
- #
- def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
- fo, te, wi, sp, st, as, de = word
- if fo is not None: self.lastfont = fo
- h = h1
- if isfirst: h1 = 0
- if islast: h2 = 999999
- if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2):
- self.charcount = self.charcount + len(te) + (sp > 0)
- return
- if self.lastfont is not None:
- self.d.setfont(self.lastfont)
- cc = 0
- for c in te:
- cw = self.d.textwidth(c)
- if self.mouseh <= h + cw/2:
- return self.charcount + cc
- cc = cc+1
- h = h+cw
- self.charcount = self.charcount + cc
- if self.mouseh <= (h+h2) / 2:
- return self.charcount
- else:
- return self.charcount + 1
- #
- def _whereisanchor(self, tuple, word, h, v):
- pass
- #
- # Return screen position corresponding to position in paragraph.
- # Return tuple (h, vtop, vbaseline, vbottom).
- # This is more or less the inverse of whereis()
- def screenpos(self, d, pos):
- if pos < 0:
- ascent, descent = self.lines[0][5:7]
- return self.left, self.top, self.top + ascent, \
- self.top + ascent + descent
- self.pos = pos
- self.lastfont = None
- try:
- self.d = d
- ok = self.visit(self.__class__._screenposword, \
- self.__class__._screenposanchor)
- finally:
- self.d = None
- if ok is None:
- ascent, descent = self.lines[-1][5:7]
- ok = self.right, self.bottom - ascent - descent, \
- self.bottom - descent, self.bottom
- return ok
- #
- def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
- fo, te, wi, sp, st, as, de = word
- if fo is not None: self.lastfont = fo
- cc = len(te) + (sp > 0)
- if self.pos > cc:
- self.pos = self.pos - cc
- return
- if self.pos < cc:
- self.d.setfont(self.lastfont)
- h = h1 + self.d.textwidth(te[:self.pos])
- else:
- h = h2
- ascent, descent = tuple[5:7]
- return h, v1, v1+ascent, v2
- #
- def _screenposanchor(self, tuple, word, h, v):
- pass
- #
- # Invert the stretch of text between pos1 and pos2.
- # If pos1 is None, the beginning is implied;
- # if pos2 is None, the end is implied.
- # Undoes its own effect when called again with the same arguments
- def invert(self, d, pos1, pos2):
- if pos1 is None:
- pos1 = self.left, self.top, self.top, self.top
- else:
- pos1 = self.screenpos(d, pos1)
- if pos2 is None:
- pos2 = self.right, self.bottom,self.bottom,self.bottom
- else:
- pos2 = self.screenpos(d, pos2)
- h1, top1, baseline1, bottom1 = pos1
- h2, top2, baseline2, bottom2 = pos2
- if bottom1 <= top2:
- d.invert((h1, top1), (self.right, bottom1))
- h1 = self.left
- if bottom1 < top2:
- d.invert((h1, bottom1), (self.right, top2))
- top1, bottom1 = top2, bottom2
- d.invert((h1, top1), (h2, bottom2))
+ #
+ def __init__(self):
+ self.words = [] # The words
+ self.just = 'l' # Justification: 'l', 'r', 'lr' or 'c'
+ self.indent_left = self.indent_right = self.indent_hang = 0
+ # Final lay-out parameters, may change
+ self.left = self.top = self.right = self.bottom = \
+ self.width = self.height = self.lines = None
+ #
+ # Add a word, computing size information for it.
+ # Words may also be added manually by appending to self.words
+ # Each word should be a 7-tuple:
+ # (font, text, width, space, stretch, ascent, descent)
+ def addword(self, d, font, text, space, stretch):
+ if font is not None:
+ d.setfont(font)
+ width = d.textwidth(text)
+ ascent = d.baseline()
+ descent = d.lineheight() - ascent
+ spw = d.textwidth(' ')
+ space = space * spw
+ stretch = stretch * spw
+ tuple = (font, text, width, space, stretch, ascent, descent)
+ self.words.append(tuple)
+ #
+ # Hooks to begin and end anchors -- insert numbers in the word list!
+ def bgn_anchor(self, id):
+ self.words.append(id)
+ #
+ def end_anchor(self, id):
+ self.words.append(0)
+ #
+ # Return the total length (width) of the text added so far, in pixels
+ def getlength(self):
+ total = 0
+ for word in self.words:
+ if type(word) is not Int:
+ total = total + word[2] + word[3]
+ return total
+ #
+ # Tab to a given position (relative to the current left indent):
+ # remove all stretch, add fixed space up to the new indent.
+ # If the current position is already at the tab stop,
+ # don't add any new space (but still remove the stretch)
+ def tabto(self, tab):
+ total = 0
+ as, de = 1, 0
+ for i in range(len(self.words)):
+ word = self.words[i]
+ if type(word) is Int: continue
+ (fo, te, wi, sp, st, as, de) = word
+ self.words[i] = (fo, te, wi, sp, 0, as, de)
+ total = total + wi + sp
+ if total < tab:
+ self.words.append((None, '', 0, tab-total, 0, as, de))
+ #
+ # Make a hanging tag: tab to hang, increment indent_left by hang,
+ # and reset indent_hang to -hang
+ def makehangingtag(self, hang):
+ self.tabto(hang)
+ self.indent_left = self.indent_left + hang
+ self.indent_hang = -hang
+ #
+ # Decide where the line breaks will be given some screen width
+ def layout(self, linewidth):
+ self.width = linewidth
+ height = 0
+ self.lines = lines = []
+ avail1 = self.width - self.indent_left - self.indent_right
+ avail = avail1 - self.indent_hang
+ words = self.words
+ i = 0
+ n = len(words)
+ lastfont = None
+ while i < n:
+ firstfont = lastfont
+ charcount = 0
+ width = 0
+ stretch = 0
+ ascent = 0
+ descent = 0
+ lsp = 0
+ j = i
+ while i < n:
+ word = words[i]
+ if type(word) is Int:
+ if word > 0 and width >= avail:
+ break
+ i = i+1
+ continue
+ fo, te, wi, sp, st, as, de = word
+ if width + wi > avail and width > 0 and wi > 0:
+ break
+ if fo is not None:
+ lastfont = fo
+ if width == 0:
+ firstfont = fo
+ charcount = charcount + len(te) + (sp > 0)
+ width = width + wi + sp
+ lsp = sp
+ stretch = stretch + st
+ lst = st
+ ascent = max(ascent, as)
+ descent = max(descent, de)
+ i = i+1
+ while i > j and type(words[i-1]) is Int and \
+ words[i-1] > 0: i = i-1
+ width = width - lsp
+ if i < n:
+ stretch = stretch - lst
+ else:
+ stretch = 0
+ tuple = i-j, firstfont, charcount, width, stretch, \
+ ascent, descent
+ lines.append(tuple)
+ height = height + ascent + descent
+ avail = avail1
+ self.height = height
+ #
+ # Call a function for all words in a line
+ def visit(self, wordfunc, anchorfunc):
+ avail1 = self.width - self.indent_left - self.indent_right
+ avail = avail1 - self.indent_hang
+ v = self.top
+ i = 0
+ for tuple in self.lines:
+ wordcount, firstfont, charcount, width, stretch, \
+ ascent, descent = tuple
+ h = self.left + self.indent_left
+ if i == 0: h = h + self.indent_hang
+ extra = 0
+ if self.just == 'r': h = h + avail - width
+ elif self.just == 'c': h = h + (avail - width) / 2
+ elif self.just == 'lr' and stretch > 0:
+ extra = avail - width
+ v2 = v + ascent + descent
+ for j in range(i, i+wordcount):
+ word = self.words[j]
+ if type(word) is Int:
+ ok = anchorfunc(self, tuple, word, \
+ h, v)
+ if ok is not None: return ok
+ continue
+ fo, te, wi, sp, st, as, de = word
+ if extra > 0 and stretch > 0:
+ ex = extra * st / stretch
+ extra = extra - ex
+ stretch = stretch - st
+ else:
+ ex = 0
+ h2 = h + wi + sp + ex
+ ok = wordfunc(self, tuple, word, h, v, \
+ h2, v2, (j==i), (j==i+wordcount-1))
+ if ok is not None: return ok
+ h = h2
+ v = v2
+ i = i + wordcount
+ avail = avail1
+ #
+ # Render a paragraph in "drawing object" d, using the rectangle
+ # given by (left, top, right) with an unspecified bottom.
+ # Return the computed bottom of the text.
+ def render(self, d, left, top, right):
+ if self.width != right-left:
+ self.layout(right-left)
+ self.left = left
+ self.top = top
+ self.right = right
+ self.bottom = self.top + self.height
+ self.anchorid = 0
+ try:
+ self.d = d
+ self.visit(self.__class__._renderword, \
+ self.__class__._renderanchor)
+ finally:
+ self.d = None
+ return self.bottom
+ #
+ def _renderword(self, tuple, word, h, v, h2, v2, isfirst, islast):
+ if word[0] is not None: self.d.setfont(word[0])
+ baseline = v + tuple[5]
+ self.d.text((h, baseline - word[5]), word[1])
+ if self.anchorid > 0:
+ self.d.line((h, baseline+2), (h2, baseline+2))
+ #
+ def _renderanchor(self, tuple, word, h, v):
+ self.anchorid = word
+ #
+ # Return which anchor(s) was hit by the mouse
+ def hitcheck(self, mouseh, mousev):
+ self.mouseh = mouseh
+ self.mousev = mousev
+ self.anchorid = 0
+ self.hits = []
+ self.visit(self.__class__._hitcheckword, \
+ self.__class__._hitcheckanchor)
+ return self.hits
+ #
+ def _hitcheckword(self, tuple, word, h, v, h2, v2, isfirst, islast):
+ if self.anchorid > 0 and h <= self.mouseh <= h2 and \
+ v <= self.mousev <= v2:
+ self.hits.append(self.anchorid)
+ #
+ def _hitcheckanchor(self, tuple, word, h, v):
+ self.anchorid = word
+ #
+ # Return whether the given anchor id is present
+ def hasanchor(self, id):
+ return id in self.words or -id in self.words
+ #
+ # Extract the raw text from the word list, substituting one space
+ # for non-empty inter-word space, and terminating with '\n'
+ def extract(self):
+ text = ''
+ for w in self.words:
+ if type(w) is not Int:
+ word = w[1]
+ if w[3]: word = word + ' '
+ text = text + word
+ return text + '\n'
+ #
+ # Return which character position was hit by the mouse, as
+ # an offset in the entire text as returned by extract().
+ # Return None if the mouse was not in this paragraph
+ def whereis(self, d, mouseh, mousev):
+ if mousev < self.top or mousev > self.bottom:
+ return None
+ self.mouseh = mouseh
+ self.mousev = mousev
+ self.lastfont = None
+ self.charcount = 0
+ try:
+ self.d = d
+ return self.visit(self.__class__._whereisword, \
+ self.__class__._whereisanchor)
+ finally:
+ self.d = None
+ #
+ def _whereisword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
+ fo, te, wi, sp, st, as, de = word
+ if fo is not None: self.lastfont = fo
+ h = h1
+ if isfirst: h1 = 0
+ if islast: h2 = 999999
+ if not (v1 <= self.mousev <= v2 and h1 <= self.mouseh <= h2):
+ self.charcount = self.charcount + len(te) + (sp > 0)
+ return
+ if self.lastfont is not None:
+ self.d.setfont(self.lastfont)
+ cc = 0
+ for c in te:
+ cw = self.d.textwidth(c)
+ if self.mouseh <= h + cw/2:
+ return self.charcount + cc
+ cc = cc+1
+ h = h+cw
+ self.charcount = self.charcount + cc
+ if self.mouseh <= (h+h2) / 2:
+ return self.charcount
+ else:
+ return self.charcount + 1
+ #
+ def _whereisanchor(self, tuple, word, h, v):
+ pass
+ #
+ # Return screen position corresponding to position in paragraph.
+ # Return tuple (h, vtop, vbaseline, vbottom).
+ # This is more or less the inverse of whereis()
+ def screenpos(self, d, pos):
+ if pos < 0:
+ ascent, descent = self.lines[0][5:7]
+ return self.left, self.top, self.top + ascent, \
+ self.top + ascent + descent
+ self.pos = pos
+ self.lastfont = None
+ try:
+ self.d = d
+ ok = self.visit(self.__class__._screenposword, \
+ self.__class__._screenposanchor)
+ finally:
+ self.d = None
+ if ok is None:
+ ascent, descent = self.lines[-1][5:7]
+ ok = self.right, self.bottom - ascent - descent, \
+ self.bottom - descent, self.bottom
+ return ok
+ #
+ def _screenposword(self, tuple, word, h1, v1, h2, v2, isfirst, islast):
+ fo, te, wi, sp, st, as, de = word
+ if fo is not None: self.lastfont = fo
+ cc = len(te) + (sp > 0)
+ if self.pos > cc:
+ self.pos = self.pos - cc
+ return
+ if self.pos < cc:
+ self.d.setfont(self.lastfont)
+ h = h1 + self.d.textwidth(te[:self.pos])
+ else:
+ h = h2
+ ascent, descent = tuple[5:7]
+ return h, v1, v1+ascent, v2
+ #
+ def _screenposanchor(self, tuple, word, h, v):
+ pass
+ #
+ # Invert the stretch of text between pos1 and pos2.
+ # If pos1 is None, the beginning is implied;
+ # if pos2 is None, the end is implied.
+ # Undoes its own effect when called again with the same arguments
+ def invert(self, d, pos1, pos2):
+ if pos1 is None:
+ pos1 = self.left, self.top, self.top, self.top
+ else:
+ pos1 = self.screenpos(d, pos1)
+ if pos2 is None:
+ pos2 = self.right, self.bottom,self.bottom,self.bottom
+ else:
+ pos2 = self.screenpos(d, pos2)
+ h1, top1, baseline1, bottom1 = pos1
+ h2, top2, baseline2, bottom2 = pos2
+ if bottom1 <= top2:
+ d.invert((h1, top1), (self.right, bottom1))
+ h1 = self.left
+ if bottom1 < top2:
+ d.invert((h1, bottom1), (self.right, top2))
+ top1, bottom1 = top2, bottom2
+ d.invert((h1, top1), (h2, bottom2))
diff --git a/Lib/lib-old/addpack.py b/Lib/lib-old/addpack.py
index 3d09236ba9..2fb2601096 100644
--- a/Lib/lib-old/addpack.py
+++ b/Lib/lib-old/addpack.py
@@ -33,35 +33,35 @@
#
# If no directory is found, ImportError is raised.
-_packs = {} # {pack: [pathname, ...], ...}
+_packs = {} # {pack: [pathname, ...], ...}
def addpack(pack, *locations):
- import os
- if os.path.isabs(pack):
- base = os.path.basename(pack)
- else:
- base = pack
- if _packs.has_key(base):
- return
- import sys
- path = []
- for loc in _flatten(locations) + sys.path:
- fn = os.path.join(loc, base)
- if fn not in path and os.path.isdir(fn):
- path.append(fn)
- if pack != base and pack not in path and os.path.isdir(pack):
- path.append(pack)
- if not path: raise ImportError, 'package ' + pack + ' not found'
- _packs[base] = path
- for fn in path:
- if fn not in sys.path:
- sys.path.append(fn)
+ import os
+ if os.path.isabs(pack):
+ base = os.path.basename(pack)
+ else:
+ base = pack
+ if _packs.has_key(base):
+ return
+ import sys
+ path = []
+ for loc in _flatten(locations) + sys.path:
+ fn = os.path.join(loc, base)
+ if fn not in path and os.path.isdir(fn):
+ path.append(fn)
+ if pack != base and pack not in path and os.path.isdir(pack):
+ path.append(pack)
+ if not path: raise ImportError, 'package ' + pack + ' not found'
+ _packs[base] = path
+ for fn in path:
+ if fn not in sys.path:
+ sys.path.append(fn)
def _flatten(locations):
- locs = []
- for loc in locations:
- if type(loc) == type(''):
- locs.append(loc)
- else:
- locs = locs + _flatten(loc)
- return locs
+ locs = []
+ for loc in locations:
+ if type(loc) == type(''):
+ locs.append(loc)
+ else:
+ locs = locs + _flatten(loc)
+ return locs
diff --git a/Lib/lib-old/codehack.py b/Lib/lib-old/codehack.py
index 248205bffa..0b5e3a17d9 100644
--- a/Lib/lib-old/codehack.py
+++ b/Lib/lib-old/codehack.py
@@ -36,46 +36,46 @@ identchars = string.ascii_letters + string.digits + '_' # Identifier characters
_namecache = {} # The cache
def getcodename(co):
- try:
- return co.co_name
- except AttributeError:
- pass
- key = `co` # arbitrary but uniquely identifying string
- if _namecache.has_key(key): return _namecache[key]
- filename = co.co_filename
- code = co.co_code
- name = ''
- if ord(code[0]) == SET_LINENO:
- lineno = ord(code[1]) | ord(code[2]) << 8
- line = linecache.getline(filename, lineno)
- words = line.split()
- if len(words) >= 2 and words[0] in ('def', 'class'):
- name = words[1]
- for i in range(len(name)):
- if name[i] not in identchars:
- name = name[:i]
- break
- _namecache[key] = name
- return name
+ try:
+ return co.co_name
+ except AttributeError:
+ pass
+ key = `co` # arbitrary but uniquely identifying string
+ if _namecache.has_key(key): return _namecache[key]
+ filename = co.co_filename
+ code = co.co_code
+ name = ''
+ if ord(code[0]) == SET_LINENO:
+ lineno = ord(code[1]) | ord(code[2]) << 8
+ line = linecache.getline(filename, lineno)
+ words = line.split()
+ if len(words) >= 2 and words[0] in ('def', 'class'):
+ name = words[1]
+ for i in range(len(name)):
+ if name[i] not in identchars:
+ name = name[:i]
+ break
+ _namecache[key] = name
+ return name
# Use the above routine to find a function's name.
def getfuncname(func):
- try:
- return func.func_name
- except AttributeError:
- pass
- return getcodename(func.func_code)
+ try:
+ return func.func_name
+ except AttributeError:
+ pass
+ return getcodename(func.func_code)
# A part of the above code to extract just the line number from a code object.
def getlineno(co):
- try:
- return co.co_firstlineno
- except AttributeError:
- pass
- code = co.co_code
- if ord(code[0]) == SET_LINENO:
- return ord(code[1]) | ord(code[2]) << 8
- else:
- return -1
+ try:
+ return co.co_firstlineno
+ except AttributeError:
+ pass
+ code = co.co_code
+ if ord(code[0]) == SET_LINENO:
+ return ord(code[1]) | ord(code[2]) << 8
+ else:
+ return -1
diff --git a/Lib/lib-old/dump.py b/Lib/lib-old/dump.py
index ec895b7e07..60bdba8ceb 100644
--- a/Lib/lib-old/dump.py
+++ b/Lib/lib-old/dump.py
@@ -23,41 +23,41 @@
# Dump a whole symbol table
#
def dumpsymtab(dict):
- for key in dict.keys():
- dumpvar(key, dict[key])
+ for key in dict.keys():
+ dumpvar(key, dict[key])
# Dump a single variable
#
def dumpvar(name, x):
- import sys
- t = type(x)
- if t == type({}):
- print name, '= {}'
- for key in x.keys():
- item = x[key]
- if not printable(item):
- print '#',
- print name, '[', `key`, '] =', `item`
- elif t in (type(''), type(0), type(0.0), type([]), type(())):
- if not printable(x):
- print '#',
- print name, '=', `x`
- elif t == type(sys):
- print 'import', name, '#', x
- else:
- print '#', name, '=', x
+ import sys
+ t = type(x)
+ if t == type({}):
+ print name, '= {}'
+ for key in x.keys():
+ item = x[key]
+ if not printable(item):
+ print '#',
+ print name, '[', `key`, '] =', `item`
+ elif t in (type(''), type(0), type(0.0), type([]), type(())):
+ if not printable(x):
+ print '#',
+ print name, '=', `x`
+ elif t == type(sys):
+ print 'import', name, '#', x
+ else:
+ print '#', name, '=', x
# check if a value is printable in a way that can be read back with input()
#
def printable(x):
- t = type(x)
- if t in (type(''), type(0), type(0.0)):
- return 1
- if t in (type([]), type(())):
- for item in x:
- if not printable(item):
- return 0
- return 1
- if x == {}:
- return 1
- return 0
+ t = type(x)
+ if t in (type(''), type(0), type(0.0)):
+ return 1
+ if t in (type([]), type(())):
+ for item in x:
+ if not printable(item):
+ return 0
+ return 1
+ if x == {}:
+ return 1
+ return 0
diff --git a/Lib/lib-old/find.py b/Lib/lib-old/find.py
index ccd9fdb965..39ad7717e8 100644
--- a/Lib/lib-old/find.py
+++ b/Lib/lib-old/find.py
@@ -6,21 +6,21 @@ _debug = 0
_prune = ['(*)']
def find(pattern, dir = os.curdir):
- list = []
- names = os.listdir(dir)
- names.sort()
- for name in names:
- if name in (os.curdir, os.pardir):
- continue
- fullname = os.path.join(dir, name)
- if fnmatch.fnmatch(name, pattern):
- list.append(fullname)
- if os.path.isdir(fullname) and not os.path.islink(fullname):
- for p in _prune:
- if fnmatch.fnmatch(name, p):
- if _debug: print "skip", `fullname`
- break
- else:
- if _debug: print "descend into", `fullname`
- list = list + find(pattern, fullname)
- return list
+ list = []
+ names = os.listdir(dir)
+ names.sort()
+ for name in names:
+ if name in (os.curdir, os.pardir):
+ continue
+ fullname = os.path.join(dir, name)
+ if fnmatch.fnmatch(name, pattern):
+ list.append(fullname)
+ if os.path.isdir(fullname) and not os.path.islink(fullname):
+ for p in _prune:
+ if fnmatch.fnmatch(name, p):
+ if _debug: print "skip", `fullname`
+ break
+ else:
+ if _debug: print "descend into", `fullname`
+ list = list + find(pattern, fullname)
+ return list
diff --git a/Lib/lib-old/fmt.py b/Lib/lib-old/fmt.py
index dfea987e8b..997d37a07d 100644
--- a/Lib/lib-old/fmt.py
+++ b/Lib/lib-old/fmt.py
@@ -12,96 +12,96 @@ import Para
# Formatter back-end to do nothing at all with the paragraphs
class NullBackEnd:
- #
- def __init__(self):
- pass
- #
- def addpara(self, p):
- pass
- #
- def bgn_anchor(self, id):
- pass
- #
- def end_anchor(self, id):
- pass
+ #
+ def __init__(self):
+ pass
+ #
+ def addpara(self, p):
+ pass
+ #
+ def bgn_anchor(self, id):
+ pass
+ #
+ def end_anchor(self, id):
+ pass
# Formatter back-end to collect the paragraphs in a list
class SavingBackEnd(NullBackEnd):
- #
- def __init__(self):
- self.paralist = []
- #
- def addpara(self, p):
- self.paralist.append(p)
- #
- def hitcheck(self, h, v):
- hits = []
- for p in self.paralist:
- if p.top <= v <= p.bottom:
- for id in p.hitcheck(h, v):
- if id not in hits:
- hits.append(id)
- return hits
- #
- def extract(self):
- text = ''
- for p in self.paralist:
- text = text + (p.extract())
- return text
- #
- def extractpart(self, long1, long2):
- if long1 > long2: long1, long2 = long2, long1
- para1, pos1 = long1
- para2, pos2 = long2
- text = ''
- while para1 < para2:
- ptext = self.paralist[para1].extract()
- text = text + ptext[pos1:]
- pos1 = 0
- para1 = para1 + 1
- ptext = self.paralist[para2].extract()
- return text + ptext[pos1:pos2]
- #
- def whereis(self, d, h, v):
- total = 0
- for i in range(len(self.paralist)):
- p = self.paralist[i]
- result = p.whereis(d, h, v)
- if result is not None:
- return i, result
- return None
- #
- def roundtowords(self, long1, long2):
- i, offset = long1
- text = self.paralist[i].extract()
- while offset > 0 and text[offset-1] != ' ': offset = offset-1
- long1 = i, offset
- #
- i, offset = long2
- text = self.paralist[i].extract()
- n = len(text)
- while offset < n-1 and text[offset] != ' ': offset = offset+1
- long2 = i, offset
- #
- return long1, long2
- #
- def roundtoparagraphs(self, long1, long2):
- long1 = long1[0], 0
- long2 = long2[0], len(self.paralist[long2[0]].extract())
- return long1, long2
+ #
+ def __init__(self):
+ self.paralist = []
+ #
+ def addpara(self, p):
+ self.paralist.append(p)
+ #
+ def hitcheck(self, h, v):
+ hits = []
+ for p in self.paralist:
+ if p.top <= v <= p.bottom:
+ for id in p.hitcheck(h, v):
+ if id not in hits:
+ hits.append(id)
+ return hits
+ #
+ def extract(self):
+ text = ''
+ for p in self.paralist:
+ text = text + (p.extract())
+ return text
+ #
+ def extractpart(self, long1, long2):
+ if long1 > long2: long1, long2 = long2, long1
+ para1, pos1 = long1
+ para2, pos2 = long2
+ text = ''
+ while para1 < para2:
+ ptext = self.paralist[para1].extract()
+ text = text + ptext[pos1:]
+ pos1 = 0
+ para1 = para1 + 1
+ ptext = self.paralist[para2].extract()
+ return text + ptext[pos1:pos2]
+ #
+ def whereis(self, d, h, v):
+ total = 0
+ for i in range(len(self.paralist)):
+ p = self.paralist[i]
+ result = p.whereis(d, h, v)
+ if result is not None:
+ return i, result
+ return None
+ #
+ def roundtowords(self, long1, long2):
+ i, offset = long1
+ text = self.paralist[i].extract()
+ while offset > 0 and text[offset-1] != ' ': offset = offset-1
+ long1 = i, offset
+ #
+ i, offset = long2
+ text = self.paralist[i].extract()
+ n = len(text)
+ while offset < n-1 and text[offset] != ' ': offset = offset+1
+ long2 = i, offset
+ #
+ return long1, long2
+ #
+ def roundtoparagraphs(self, long1, long2):
+ long1 = long1[0], 0
+ long2 = long2[0], len(self.paralist[long2[0]].extract())
+ return long1, long2
# Formatter back-end to send the text directly to the drawing object
class WritingBackEnd(NullBackEnd):
- #
- def __init__(self, d, width):
- self.d = d
- self.width = width
- self.lineno = 0
- #
- def addpara(self, p):
- self.lineno = p.render(self.d, 0, self.lineno, self.width)
+ #
+ def __init__(self, d, width):
+ self.d = d
+ self.width = width
+ self.lineno = 0
+ #
+ def addpara(self, p):
+ self.lineno = p.render(self.d, 0, self.lineno, self.width)
# A formatter receives a stream of formatting instructions and assembles
@@ -125,192 +125,192 @@ class WritingBackEnd(NullBackEnd):
# needvspace(nlines)
# addword(word, nspaces)
class BaseFormatter:
- #
- def __init__(self, d, b):
- # Drawing object used for text measurements
- self.d = d
- #
- # BackEnd object receiving completed paragraphs
- self.b = b
- #
- # Parameters of the formatting model
- self.leftindent = 0
- self.just = 'l'
- self.font = None
- self.blanklines = 0
- #
- # Parameters derived from the current font
- self.space = d.textwidth(' ')
- self.line = d.lineheight()
- self.ascent = d.baseline()
- self.descent = self.line - self.ascent
- #
- # Parameter derived from the default font
- self.n_space = self.space
- #
- # Current paragraph being built
- self.para = None
- self.nospace = 1
- #
- # Font to set on the next word
- self.nextfont = None
- #
- def newpara(self):
- return Para.Para()
- #
- def setfont(self, font):
- if font is None: return
- self.font = self.nextfont = font
- d = self.d
- d.setfont(font)
- self.space = d.textwidth(' ')
- self.line = d.lineheight()
- self.ascent = d.baseline()
- self.descent = self.line - self.ascent
- #
- def setleftindent(self, nspaces):
- self.leftindent = int(self.n_space * nspaces)
- if self.para:
- hang = self.leftindent - self.para.indent_left
- if hang > 0 and self.para.getlength() <= hang:
- self.para.makehangingtag(hang)
- self.nospace = 1
- else:
- self.flush()
- #
- def setrightindent(self, nspaces):
- self.rightindent = int(self.n_space * nspaces)
- if self.para:
- self.para.indent_right = self.rightindent
- self.flush()
- #
- def setjust(self, just):
- self.just = just
- if self.para:
- self.para.just = self.just
- #
- def flush(self):
- if self.para:
- self.b.addpara(self.para)
- self.para = None
- if self.font is not None:
- self.d.setfont(self.font)
- self.nospace = 1
- #
- def vspace(self, nlines):
- self.flush()
- if nlines > 0:
- self.para = self.newpara()
- tuple = None, '', 0, 0, 0, int(nlines*self.line), 0
- self.para.words.append(tuple)
- self.flush()
- self.blanklines = self.blanklines + nlines
- #
- def needvspace(self, nlines):
- self.flush() # Just to be sure
- if nlines > self.blanklines:
- self.vspace(nlines - self.blanklines)
- #
- def addword(self, text, space):
- if self.nospace and not text:
- return
- self.nospace = 0
- self.blanklines = 0
- if not self.para:
- self.para = self.newpara()
- self.para.indent_left = self.leftindent
- self.para.just = self.just
- self.nextfont = self.font
- space = int(space * self.space)
- self.para.words.append((self.nextfont, text,
- self.d.textwidth(text), space, space,
- self.ascent, self.descent))
- self.nextfont = None
- #
- def bgn_anchor(self, id):
- if not self.para:
- self.nospace = 0
- self.addword('', 0)
- self.para.bgn_anchor(id)
- #
- def end_anchor(self, id):
- if not self.para:
- self.nospace = 0
- self.addword('', 0)
- self.para.end_anchor(id)
+ #
+ def __init__(self, d, b):
+ # Drawing object used for text measurements
+ self.d = d
+ #
+ # BackEnd object receiving completed paragraphs
+ self.b = b
+ #
+ # Parameters of the formatting model
+ self.leftindent = 0
+ self.just = 'l'
+ self.font = None
+ self.blanklines = 0
+ #
+ # Parameters derived from the current font
+ self.space = d.textwidth(' ')
+ self.line = d.lineheight()
+ self.ascent = d.baseline()
+ self.descent = self.line - self.ascent
+ #
+ # Parameter derived from the default font
+ self.n_space = self.space
+ #
+ # Current paragraph being built
+ self.para = None
+ self.nospace = 1
+ #
+ # Font to set on the next word
+ self.nextfont = None
+ #
+ def newpara(self):
+ return Para.Para()
+ #
+ def setfont(self, font):
+ if font is None: return
+ self.font = self.nextfont = font
+ d = self.d
+ d.setfont(font)
+ self.space = d.textwidth(' ')
+ self.line = d.lineheight()
+ self.ascent = d.baseline()
+ self.descent = self.line - self.ascent
+ #
+ def setleftindent(self, nspaces):
+ self.leftindent = int(self.n_space * nspaces)
+ if self.para:
+ hang = self.leftindent - self.para.indent_left
+ if hang > 0 and self.para.getlength() <= hang:
+ self.para.makehangingtag(hang)
+ self.nospace = 1
+ else:
+ self.flush()
+ #
+ def setrightindent(self, nspaces):
+ self.rightindent = int(self.n_space * nspaces)
+ if self.para:
+ self.para.indent_right = self.rightindent
+ self.flush()
+ #
+ def setjust(self, just):
+ self.just = just
+ if self.para:
+ self.para.just = self.just
+ #
+ def flush(self):
+ if self.para:
+ self.b.addpara(self.para)
+ self.para = None
+ if self.font is not None:
+ self.d.setfont(self.font)
+ self.nospace = 1
+ #
+ def vspace(self, nlines):
+ self.flush()
+ if nlines > 0:
+ self.para = self.newpara()
+ tuple = None, '', 0, 0, 0, int(nlines*self.line), 0
+ self.para.words.append(tuple)
+ self.flush()
+ self.blanklines = self.blanklines + nlines
+ #
+ def needvspace(self, nlines):
+ self.flush() # Just to be sure
+ if nlines > self.blanklines:
+ self.vspace(nlines - self.blanklines)
+ #
+ def addword(self, text, space):
+ if self.nospace and not text:
+ return
+ self.nospace = 0
+ self.blanklines = 0
+ if not self.para:
+ self.para = self.newpara()
+ self.para.indent_left = self.leftindent
+ self.para.just = self.just
+ self.nextfont = self.font
+ space = int(space * self.space)
+ self.para.words.append((self.nextfont, text,
+ self.d.textwidth(text), space, space,
+ self.ascent, self.descent))
+ self.nextfont = None
+ #
+ def bgn_anchor(self, id):
+ if not self.para:
+ self.nospace = 0
+ self.addword('', 0)
+ self.para.bgn_anchor(id)
+ #
+ def end_anchor(self, id):
+ if not self.para:
+ self.nospace = 0
+ self.addword('', 0)
+ self.para.end_anchor(id)
# Measuring object for measuring text as viewed on a tty
class NullMeasurer:
- #
- def __init__(self):
- pass
- #
- def setfont(self, font):
- pass
- #
- def textwidth(self, text):
- return len(text)
- #
- def lineheight(self):
- return 1
- #
- def baseline(self):
- return 0
+ #
+ def __init__(self):
+ pass
+ #
+ def setfont(self, font):
+ pass
+ #
+ def textwidth(self, text):
+ return len(text)
+ #
+ def lineheight(self):
+ return 1
+ #
+ def baseline(self):
+ return 0
# Drawing object for writing plain ASCII text to a file
class FileWriter:
- #
- def __init__(self, fp):
- self.fp = fp
- self.lineno, self.colno = 0, 0
- #
- def setfont(self, font):
- pass
- #
- def text(self, (h, v), str):
- if not str: return
- if '\n' in str:
- raise ValueError, 'can\'t write \\n'
- while self.lineno < v:
- self.fp.write('\n')
- self.colno, self.lineno = 0, self.lineno + 1
- while self.lineno > v:
- # XXX This should never happen...
- self.fp.write('\033[A') # ANSI up arrow
- self.lineno = self.lineno - 1
- if self.colno < h:
- self.fp.write(' ' * (h - self.colno))
- elif self.colno > h:
- self.fp.write('\b' * (self.colno - h))
- self.colno = h
- self.fp.write(str)
- self.colno = h + len(str)
+ #
+ def __init__(self, fp):
+ self.fp = fp
+ self.lineno, self.colno = 0, 0
+ #
+ def setfont(self, font):
+ pass
+ #
+ def text(self, (h, v), str):
+ if not str: return
+ if '\n' in str:
+ raise ValueError, 'can\'t write \\n'
+ while self.lineno < v:
+ self.fp.write('\n')
+ self.colno, self.lineno = 0, self.lineno + 1
+ while self.lineno > v:
+ # XXX This should never happen...
+ self.fp.write('\033[A') # ANSI up arrow
+ self.lineno = self.lineno - 1
+ if self.colno < h:
+ self.fp.write(' ' * (h - self.colno))
+ elif self.colno > h:
+ self.fp.write('\b' * (self.colno - h))
+ self.colno = h
+ self.fp.write(str)
+ self.colno = h + len(str)
# Formatting class to do nothing at all with the data
class NullFormatter(BaseFormatter):
- #
- def __init__(self):
- d = NullMeasurer()
- b = NullBackEnd()
- BaseFormatter.__init__(self, d, b)
+ #
+ def __init__(self):
+ d = NullMeasurer()
+ b = NullBackEnd()
+ BaseFormatter.__init__(self, d, b)
# Formatting class to write directly to a file
class WritingFormatter(BaseFormatter):
- #
- def __init__(self, fp, width):
- dm = NullMeasurer()
- dw = FileWriter(fp)
- b = WritingBackEnd(dw, width)
- BaseFormatter.__init__(self, dm, b)
- self.blanklines = 1
- #
- # Suppress multiple blank lines
- def needvspace(self, nlines):
- BaseFormatter.needvspace(self, min(1, nlines))
+ #
+ def __init__(self, fp, width):
+ dm = NullMeasurer()
+ dw = FileWriter(fp)
+ b = WritingBackEnd(dw, width)
+ BaseFormatter.__init__(self, dm, b)
+ self.blanklines = 1
+ #
+ # Suppress multiple blank lines
+ def needvspace(self, nlines):
+ BaseFormatter.needvspace(self, min(1, nlines))
# A "FunnyFormatter" writes ASCII text with a twist: *bold words*,
@@ -320,10 +320,10 @@ class WritingFormatter(BaseFormatter):
# Moreover, if the font is in upper case, the text is converted to
# UPPER CASE.
class FunnyFormatter(WritingFormatter):
- #
- def flush(self):
- if self.para: finalize(self.para)
- WritingFormatter.flush(self)
+ #
+ def flush(self):
+ if self.para: finalize(self.para)
+ WritingFormatter.flush(self)
# Surrounds *bold words* and _italic text_ in a paragraph with
@@ -334,33 +334,33 @@ openchar = \
closechar = \
{'b':'*', 'i':'_', 'u':'_', 'q':'\'', 'B':'*', 'I':'_', 'U':'_', 'Q':'\''}
def finalize(para):
- oldfont = curfont = 'r'
- para.words.append(('r', '', 0, 0, 0, 0)) # temporary, deleted at end
- for i in range(len(para.words)):
- fo, te, wi = para.words[i][:3]
- if fo is not None: curfont = fo
- if curfont != oldfont:
- if closechar.has_key(oldfont):
- c = closechar[oldfont]
- j = i-1
- while j > 0 and para.words[j][1] == '': j = j-1
- fo1, te1, wi1 = para.words[j][:3]
- te1 = te1 + c
- wi1 = wi1 + len(c)
- para.words[j] = (fo1, te1, wi1) + \
- para.words[j][3:]
- if openchar.has_key(curfont) and te:
- c = openchar[curfont]
- te = c + te
- wi = len(c) + wi
- para.words[i] = (fo, te, wi) + \
- para.words[i][3:]
- if te: oldfont = curfont
- else: oldfont = 'r'
- if curfont in string.uppercase:
- te = string.upper(te)
- para.words[i] = (fo, te, wi) + para.words[i][3:]
- del para.words[-1]
+ oldfont = curfont = 'r'
+ para.words.append(('r', '', 0, 0, 0, 0)) # temporary, deleted at end
+ for i in range(len(para.words)):
+ fo, te, wi = para.words[i][:3]
+ if fo is not None: curfont = fo
+ if curfont != oldfont:
+ if closechar.has_key(oldfont):
+ c = closechar[oldfont]
+ j = i-1
+ while j > 0 and para.words[j][1] == '': j = j-1
+ fo1, te1, wi1 = para.words[j][:3]
+ te1 = te1 + c
+ wi1 = wi1 + len(c)
+ para.words[j] = (fo1, te1, wi1) + \
+ para.words[j][3:]
+ if openchar.has_key(curfont) and te:
+ c = openchar[curfont]
+ te = c + te
+ wi = len(c) + wi
+ para.words[i] = (fo, te, wi) + \
+ para.words[i][3:]
+ if te: oldfont = curfont
+ else: oldfont = 'r'
+ if curfont in string.uppercase:
+ te = string.upper(te)
+ para.words[i] = (fo, te, wi) + para.words[i][3:]
+ del para.words[-1]
# Formatter back-end to draw the text in a window.
@@ -368,256 +368,256 @@ def finalize(para):
# to minimize the delay before the user sees anything.
# This manages the entire "document" of the window.
class StdwinBackEnd(SavingBackEnd):
- #
- def __init__(self, window, drawnow):
- self.window = window
- self.drawnow = drawnow
- self.width = window.getwinsize()[0]
- self.selection = None
- self.height = 0
- window.setorigin(0, 0)
- window.setdocsize(0, 0)
- self.d = window.begindrawing()
- SavingBackEnd.__init__(self)
- #
- def finish(self):
- self.d.close()
- self.d = None
- self.window.setdocsize(0, self.height)
- #
- def addpara(self, p):
- self.paralist.append(p)
- if self.drawnow:
- self.height = \
- p.render(self.d, 0, self.height, self.width)
- else:
- p.layout(self.width)
- p.left = 0
- p.top = self.height
- p.right = self.width
- p.bottom = self.height + p.height
- self.height = p.bottom
- #
- def resize(self):
- self.window.change((0, 0), (self.width, self.height))
- self.width = self.window.getwinsize()[0]
- self.height = 0
- for p in self.paralist:
- p.layout(self.width)
- p.left = 0
- p.top = self.height
- p.right = self.width
- p.bottom = self.height + p.height
- self.height = p.bottom
- self.window.change((0, 0), (self.width, self.height))
- self.window.setdocsize(0, self.height)
- #
- def redraw(self, area):
- d = self.window.begindrawing()
- (left, top), (right, bottom) = area
- d.erase(area)
- d.cliprect(area)
- for p in self.paralist:
- if top < p.bottom and p.top < bottom:
- v = p.render(d, p.left, p.top, p.right)
- if self.selection:
- self.invert(d, self.selection)
- d.close()
- #
- def setselection(self, new):
- if new:
- long1, long2 = new
- pos1 = long1[:3]
- pos2 = long2[:3]
- new = pos1, pos2
- if new != self.selection:
- d = self.window.begindrawing()
- if self.selection:
- self.invert(d, self.selection)
- if new:
- self.invert(d, new)
- d.close()
- self.selection = new
- #
- def getselection(self):
- return self.selection
- #
- def extractselection(self):
- if self.selection:
- a, b = self.selection
- return self.extractpart(a, b)
- else:
- return None
- #
- def invert(self, d, region):
- long1, long2 = region
- if long1 > long2: long1, long2 = long2, long1
- para1, pos1 = long1
- para2, pos2 = long2
- while para1 < para2:
- self.paralist[para1].invert(d, pos1, None)
- pos1 = None
- para1 = para1 + 1
- self.paralist[para2].invert(d, pos1, pos2)
- #
- def search(self, prog):
- import re, string
- if type(prog) is type(''):
- prog = re.compile(string.lower(prog))
- if self.selection:
- iold = self.selection[0][0]
- else:
- iold = -1
- hit = None
- for i in range(len(self.paralist)):
- if i == iold or i < iold and hit:
- continue
- p = self.paralist[i]
- text = string.lower(p.extract())
- match = prog.search(text)
- if match:
- a, b = match.group(0)
- long1 = i, a
- long2 = i, b
- hit = long1, long2
- if i > iold:
- break
- if hit:
- self.setselection(hit)
- i = hit[0][0]
- p = self.paralist[i]
- self.window.show((p.left, p.top), (p.right, p.bottom))
- return 1
- else:
- return 0
- #
- def showanchor(self, id):
- for i in range(len(self.paralist)):
- p = self.paralist[i]
- if p.hasanchor(id):
- long1 = i, 0
- long2 = i, len(p.extract())
- hit = long1, long2
- self.setselection(hit)
- self.window.show(
- (p.left, p.top), (p.right, p.bottom))
- break
+ #
+ def __init__(self, window, drawnow):
+ self.window = window
+ self.drawnow = drawnow
+ self.width = window.getwinsize()[0]
+ self.selection = None
+ self.height = 0
+ window.setorigin(0, 0)
+ window.setdocsize(0, 0)
+ self.d = window.begindrawing()
+ SavingBackEnd.__init__(self)
+ #
+ def finish(self):
+ self.d.close()
+ self.d = None
+ self.window.setdocsize(0, self.height)
+ #
+ def addpara(self, p):
+ self.paralist.append(p)
+ if self.drawnow:
+ self.height = \
+ p.render(self.d, 0, self.height, self.width)
+ else:
+ p.layout(self.width)
+ p.left = 0
+ p.top = self.height
+ p.right = self.width
+ p.bottom = self.height + p.height
+ self.height = p.bottom
+ #
+ def resize(self):
+ self.window.change((0, 0), (self.width, self.height))
+ self.width = self.window.getwinsize()[0]
+ self.height = 0
+ for p in self.paralist:
+ p.layout(self.width)
+ p.left = 0
+ p.top = self.height
+ p.right = self.width
+ p.bottom = self.height + p.height
+ self.height = p.bottom
+ self.window.change((0, 0), (self.width, self.height))
+ self.window.setdocsize(0, self.height)
+ #
+ def redraw(self, area):
+ d = self.window.begindrawing()
+ (left, top), (right, bottom) = area
+ d.erase(area)
+ d.cliprect(area)
+ for p in self.paralist:
+ if top < p.bottom and p.top < bottom:
+ v = p.render(d, p.left, p.top, p.right)
+ if self.selection:
+ self.invert(d, self.selection)
+ d.close()
+ #
+ def setselection(self, new):
+ if new:
+ long1, long2 = new
+ pos1 = long1[:3]
+ pos2 = long2[:3]
+ new = pos1, pos2
+ if new != self.selection:
+ d = self.window.begindrawing()
+ if self.selection:
+ self.invert(d, self.selection)
+ if new:
+ self.invert(d, new)
+ d.close()
+ self.selection = new
+ #
+ def getselection(self):
+ return self.selection
+ #
+ def extractselection(self):
+ if self.selection:
+ a, b = self.selection
+ return self.extractpart(a, b)
+ else:
+ return None
+ #
+ def invert(self, d, region):
+ long1, long2 = region
+ if long1 > long2: long1, long2 = long2, long1
+ para1, pos1 = long1
+ para2, pos2 = long2
+ while para1 < para2:
+ self.paralist[para1].invert(d, pos1, None)
+ pos1 = None
+ para1 = para1 + 1
+ self.paralist[para2].invert(d, pos1, pos2)
+ #
+ def search(self, prog):
+ import re, string
+ if type(prog) is type(''):
+ prog = re.compile(string.lower(prog))
+ if self.selection:
+ iold = self.selection[0][0]
+ else:
+ iold = -1
+ hit = None
+ for i in range(len(self.paralist)):
+ if i == iold or i < iold and hit:
+ continue
+ p = self.paralist[i]
+ text = string.lower(p.extract())
+ match = prog.search(text)
+ if match:
+ a, b = match.group(0)
+ long1 = i, a
+ long2 = i, b
+ hit = long1, long2
+ if i > iold:
+ break
+ if hit:
+ self.setselection(hit)
+ i = hit[0][0]
+ p = self.paralist[i]
+ self.window.show((p.left, p.top), (p.right, p.bottom))
+ return 1
+ else:
+ return 0
+ #
+ def showanchor(self, id):
+ for i in range(len(self.paralist)):
+ p = self.paralist[i]
+ if p.hasanchor(id):
+ long1 = i, 0
+ long2 = i, len(p.extract())
+ hit = long1, long2
+ self.setselection(hit)
+ self.window.show(
+ (p.left, p.top), (p.right, p.bottom))
+ break
# GL extensions
class GLFontCache:
- #
- def __init__(self):
- self.reset()
- self.setfont('')
- #
- def reset(self):
- self.fontkey = None
- self.fonthandle = None
- self.fontinfo = None
- self.fontcache = {}
- #
- def close(self):
- self.reset()
- #
- def setfont(self, fontkey):
- if fontkey == '':
- fontkey = 'Times-Roman 12'
- elif ' ' not in fontkey:
- fontkey = fontkey + ' 12'
- if fontkey == self.fontkey:
- return
- if self.fontcache.has_key(fontkey):
- handle = self.fontcache[fontkey]
- else:
- import string
- i = string.index(fontkey, ' ')
- name, sizestr = fontkey[:i], fontkey[i:]
- size = eval(sizestr)
- key1 = name + ' 1'
- key = name + ' ' + `size`
- # NB key may differ from fontkey!
- if self.fontcache.has_key(key):
- handle = self.fontcache[key]
- else:
- if self.fontcache.has_key(key1):
- handle = self.fontcache[key1]
- else:
- import fm
- handle = fm.findfont(name)
- self.fontcache[key1] = handle
- handle = handle.scalefont(size)
- self.fontcache[fontkey] = \
- self.fontcache[key] = handle
- self.fontkey = fontkey
- if self.fonthandle != handle:
- self.fonthandle = handle
- self.fontinfo = handle.getfontinfo()
- handle.setfont()
+ #
+ def __init__(self):
+ self.reset()
+ self.setfont('')
+ #
+ def reset(self):
+ self.fontkey = None
+ self.fonthandle = None
+ self.fontinfo = None
+ self.fontcache = {}
+ #
+ def close(self):
+ self.reset()
+ #
+ def setfont(self, fontkey):
+ if fontkey == '':
+ fontkey = 'Times-Roman 12'
+ elif ' ' not in fontkey:
+ fontkey = fontkey + ' 12'
+ if fontkey == self.fontkey:
+ return
+ if self.fontcache.has_key(fontkey):
+ handle = self.fontcache[fontkey]
+ else:
+ import string
+ i = string.index(fontkey, ' ')
+ name, sizestr = fontkey[:i], fontkey[i:]
+ size = eval(sizestr)
+ key1 = name + ' 1'
+ key = name + ' ' + `size`
+ # NB key may differ from fontkey!
+ if self.fontcache.has_key(key):
+ handle = self.fontcache[key]
+ else:
+ if self.fontcache.has_key(key1):
+ handle = self.fontcache[key1]
+ else:
+ import fm
+ handle = fm.findfont(name)
+ self.fontcache[key1] = handle
+ handle = handle.scalefont(size)
+ self.fontcache[fontkey] = \
+ self.fontcache[key] = handle
+ self.fontkey = fontkey
+ if self.fonthandle != handle:
+ self.fonthandle = handle
+ self.fontinfo = handle.getfontinfo()
+ handle.setfont()
class GLMeasurer(GLFontCache):
- #
- def textwidth(self, text):
- return self.fonthandle.getstrwidth(text)
- #
- def baseline(self):
- return self.fontinfo[6] - self.fontinfo[3]
- #
- def lineheight(self):
- return self.fontinfo[6]
+ #
+ def textwidth(self, text):
+ return self.fonthandle.getstrwidth(text)
+ #
+ def baseline(self):
+ return self.fontinfo[6] - self.fontinfo[3]
+ #
+ def lineheight(self):
+ return self.fontinfo[6]
class GLWriter(GLFontCache):
- #
- # NOTES:
- # (1) Use gl.ortho2 to use X pixel coordinates!
- #
- def text(self, (h, v), text):
- import gl, fm
- gl.cmov2i(h, v + self.fontinfo[6] - self.fontinfo[3])
- fm.prstr(text)
- #
- def setfont(self, fontkey):
- oldhandle = self.fonthandle
- GLFontCache.setfont(fontkey)
- if self.fonthandle != oldhandle:
- handle.setfont()
+ #
+ # NOTES:
+ # (1) Use gl.ortho2 to use X pixel coordinates!
+ #
+ def text(self, (h, v), text):
+ import gl, fm
+ gl.cmov2i(h, v + self.fontinfo[6] - self.fontinfo[3])
+ fm.prstr(text)
+ #
+ def setfont(self, fontkey):
+ oldhandle = self.fonthandle
+ GLFontCache.setfont(fontkey)
+ if self.fonthandle != oldhandle:
+ handle.setfont()
class GLMeasurerWriter(GLMeasurer, GLWriter):
- pass
+ pass
class GLBackEnd(SavingBackEnd):
- #
- def __init__(self, wid):
- import gl
- gl.winset(wid)
- self.wid = wid
- self.width = gl.getsize()[1]
- self.height = 0
- self.d = GLMeasurerWriter()
- SavingBackEnd.__init__(self)
- #
- def finish(self):
- pass
- #
- def addpara(self, p):
- self.paralist.append(p)
- self.height = p.render(self.d, 0, self.height, self.width)
- #
- def redraw(self):
- import gl
- gl.winset(self.wid)
- width = gl.getsize()[1]
- if width != self.width:
- setdocsize = 1
- self.width = width
- for p in self.paralist:
- p.top = p.bottom = None
- d = self.d
- v = 0
- for p in self.paralist:
- v = p.render(d, 0, v, width)
+ #
+ def __init__(self, wid):
+ import gl
+ gl.winset(wid)
+ self.wid = wid
+ self.width = gl.getsize()[1]
+ self.height = 0
+ self.d = GLMeasurerWriter()
+ SavingBackEnd.__init__(self)
+ #
+ def finish(self):
+ pass
+ #
+ def addpara(self, p):
+ self.paralist.append(p)
+ self.height = p.render(self.d, 0, self.height, self.width)
+ #
+ def redraw(self):
+ import gl
+ gl.winset(self.wid)
+ width = gl.getsize()[1]
+ if width != self.width:
+ setdocsize = 1
+ self.width = width
+ for p in self.paralist:
+ p.top = p.bottom = None
+ d = self.d
+ v = 0
+ for p in self.paralist:
+ v = p.render(d, 0, v, width)
diff --git a/Lib/lib-old/grep.py b/Lib/lib-old/grep.py
index bdefbe6c34..292674676b 100644
--- a/Lib/lib-old/grep.py
+++ b/Lib/lib-old/grep.py
@@ -8,72 +8,72 @@ opt_show_filename = 0
opt_show_lineno = 1
def grep(pat, *files):
- return ggrep(RE_SYNTAX_GREP, pat, files)
+ return ggrep(RE_SYNTAX_GREP, pat, files)
def egrep(pat, *files):
- return ggrep(RE_SYNTAX_EGREP, pat, files)
+ return ggrep(RE_SYNTAX_EGREP, pat, files)
def emgrep(pat, *files):
- return ggrep(RE_SYNTAX_EMACS, pat, files)
+ return ggrep(RE_SYNTAX_EMACS, pat, files)
def ggrep(syntax, pat, files):
- if len(files) == 1 and type(files[0]) == type([]):
- files = files[0]
- global opt_show_filename
- opt_show_filename = (len(files) != 1)
- syntax = regex.set_syntax(syntax)
- try:
- prog = regex.compile(pat)
- finally:
- syntax = regex.set_syntax(syntax)
- for filename in files:
- fp = open(filename, 'r')
- lineno = 0
- while 1:
- line = fp.readline()
- if not line: break
- lineno = lineno + 1
- if prog.search(line) >= 0:
- showline(filename, lineno, line, prog)
- fp.close()
+ if len(files) == 1 and type(files[0]) == type([]):
+ files = files[0]
+ global opt_show_filename
+ opt_show_filename = (len(files) != 1)
+ syntax = regex.set_syntax(syntax)
+ try:
+ prog = regex.compile(pat)
+ finally:
+ syntax = regex.set_syntax(syntax)
+ for filename in files:
+ fp = open(filename, 'r')
+ lineno = 0
+ while 1:
+ line = fp.readline()
+ if not line: break
+ lineno = lineno + 1
+ if prog.search(line) >= 0:
+ showline(filename, lineno, line, prog)
+ fp.close()
def pgrep(pat, *files):
- if len(files) == 1 and type(files[0]) == type([]):
- files = files[0]
- global opt_show_filename
- opt_show_filename = (len(files) != 1)
- import re
- prog = re.compile(pat)
- for filename in files:
- fp = open(filename, 'r')
- lineno = 0
- while 1:
- line = fp.readline()
- if not line: break
- lineno = lineno + 1
- if prog.search(line):
- showline(filename, lineno, line, prog)
- fp.close()
+ if len(files) == 1 and type(files[0]) == type([]):
+ files = files[0]
+ global opt_show_filename
+ opt_show_filename = (len(files) != 1)
+ import re
+ prog = re.compile(pat)
+ for filename in files:
+ fp = open(filename, 'r')
+ lineno = 0
+ while 1:
+ line = fp.readline()
+ if not line: break
+ lineno = lineno + 1
+ if prog.search(line):
+ showline(filename, lineno, line, prog)
+ fp.close()
def showline(filename, lineno, line, prog):
- if line[-1:] == '\n': line = line[:-1]
- if opt_show_lineno:
- prefix = `lineno`.rjust(3) + ': '
- else:
- prefix = ''
- if opt_show_filename:
- prefix = filename + ': ' + prefix
- print prefix + line
- if opt_show_where:
- start, end = prog.regs()[0]
- line = line[:start]
- if '\t' not in line:
- prefix = ' ' * (len(prefix) + start)
- else:
- prefix = ' ' * len(prefix)
- for c in line:
- if c != '\t': c = ' '
- prefix = prefix + c
- if start == end: prefix = prefix + '\\'
- else: prefix = prefix + '^'*(end-start)
- print prefix
+ if line[-1:] == '\n': line = line[:-1]
+ if opt_show_lineno:
+ prefix = `lineno`.rjust(3) + ': '
+ else:
+ prefix = ''
+ if opt_show_filename:
+ prefix = filename + ': ' + prefix
+ print prefix + line
+ if opt_show_where:
+ start, end = prog.regs()[0]
+ line = line[:start]
+ if '\t' not in line:
+ prefix = ' ' * (len(prefix) + start)
+ else:
+ prefix = ' ' * len(prefix)
+ for c in line:
+ if c != '\t': c = ' '
+ prefix = prefix + c
+ if start == end: prefix = prefix + '\\'
+ else: prefix = prefix + '^'*(end-start)
+ print prefix
diff --git a/Lib/lib-old/lockfile.py b/Lib/lib-old/lockfile.py
index 3aaeac0916..cde9b48c56 100644
--- a/Lib/lib-old/lockfile.py
+++ b/Lib/lib-old/lockfile.py
@@ -1,15 +1,15 @@
import struct, fcntl
def writelock(f):
- _lock(f, fcntl.F_WRLCK)
+ _lock(f, fcntl.F_WRLCK)
def readlock(f):
- _lock(f, fcntl.F_RDLCK)
+ _lock(f, fcntl.F_RDLCK)
def unlock(f):
- _lock(f, fcntl.F_UNLCK)
+ _lock(f, fcntl.F_UNLCK)
def _lock(f, op):
- dummy = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW,
- struct.pack('2h8l', op,
- 0, 0, 0, 0, 0, 0, 0, 0, 0))
+ dummy = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW,
+ struct.pack('2h8l', op,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0))
diff --git a/Lib/lib-old/newdir.py b/Lib/lib-old/newdir.py
index 937c49e67b..356beccf8f 100644
--- a/Lib/lib-old/newdir.py
+++ b/Lib/lib-old/newdir.py
@@ -5,69 +5,69 @@
# the current local name space by default
def listattrs(x):
- try:
- dictkeys = x.__dict__.keys()
- except (AttributeError, TypeError):
- dictkeys = []
- #
- try:
- methods = x.__methods__
- except (AttributeError, TypeError):
- methods = []
- #
- try:
- members = x.__members__
- except (AttributeError, TypeError):
- members = []
- #
- try:
- the_class = x.__class__
- except (AttributeError, TypeError):
- the_class = None
- #
- try:
- bases = x.__bases__
- except (AttributeError, TypeError):
- bases = ()
- #
- total = dictkeys + methods + members
- if the_class:
- # It's a class instace; add the class's attributes
- # that are functions (methods)...
- class_attrs = listattrs(the_class)
- class_methods = []
- for name in class_attrs:
- if is_function(getattr(the_class, name)):
- class_methods.append(name)
- total = total + class_methods
- elif bases:
- # It's a derived class; add the base class attributes
- for base in bases:
- base_attrs = listattrs(base)
- total = total + base_attrs
- total.sort()
- return total
- i = 0
- while i+1 < len(total):
- if total[i] == total[i+1]:
- del total[i+1]
- else:
- i = i+1
- return total
+ try:
+ dictkeys = x.__dict__.keys()
+ except (AttributeError, TypeError):
+ dictkeys = []
+ #
+ try:
+ methods = x.__methods__
+ except (AttributeError, TypeError):
+ methods = []
+ #
+ try:
+ members = x.__members__
+ except (AttributeError, TypeError):
+ members = []
+ #
+ try:
+ the_class = x.__class__
+ except (AttributeError, TypeError):
+ the_class = None
+ #
+ try:
+ bases = x.__bases__
+ except (AttributeError, TypeError):
+ bases = ()
+ #
+ total = dictkeys + methods + members
+ if the_class:
+ # It's a class instace; add the class's attributes
+ # that are functions (methods)...
+ class_attrs = listattrs(the_class)
+ class_methods = []
+ for name in class_attrs:
+ if is_function(getattr(the_class, name)):
+ class_methods.append(name)
+ total = total + class_methods
+ elif bases:
+ # It's a derived class; add the base class attributes
+ for base in bases:
+ base_attrs = listattrs(base)
+ total = total + base_attrs
+ total.sort()
+ return total
+ i = 0
+ while i+1 < len(total):
+ if total[i] == total[i+1]:
+ del total[i+1]
+ else:
+ i = i+1
+ return total
# Helper to recognize functions
def is_function(x):
- return type(x) == type(is_function)
+ return type(x) == type(is_function)
# Approximation of builtin dir(); but note that this lists the user's
# variables by default, not the current local name space.
def dir(x = None):
- if x is not None:
- return listattrs(x)
- else:
- import __main__
- return listattrs(__main__)
+ if x is not None:
+ return listattrs(x)
+ else:
+ import __main__
+ return listattrs(__main__)
diff --git a/Lib/lib-old/packmail.py b/Lib/lib-old/packmail.py
index 9c2b5662f6..e569108a48 100644
--- a/Lib/lib-old/packmail.py
+++ b/Lib/lib-old/packmail.py
@@ -8,104 +8,104 @@ from stat import ST_MTIME
# Print help
def help():
- print 'All fns have a file open for writing as first parameter'
- print 'pack(f, fullname, name): pack fullname as name'
- print 'packsome(f, directory, namelist): selected files from directory'
- print 'packall(f, directory): pack all files from directory'
- print 'packnotolder(f, directory, name): pack all files from directory'
- print ' that are not older than a file there'
- print 'packtree(f, directory): pack entire directory tree'
+ print 'All fns have a file open for writing as first parameter'
+ print 'pack(f, fullname, name): pack fullname as name'
+ print 'packsome(f, directory, namelist): selected files from directory'
+ print 'packall(f, directory): pack all files from directory'
+ print 'packnotolder(f, directory, name): pack all files from directory'
+ print ' that are not older than a file there'
+ print 'packtree(f, directory): pack entire directory tree'
# Pack one file
def pack(outfp, file, name):
- fp = open(file, 'r')
- outfp.write('echo ' + name + '\n')
- outfp.write('sed "s/^X//" >"' + name + '" <<"!"\n')
- while 1:
- line = fp.readline()
- if not line: break
- if line[-1:] != '\n':
- line = line + '\n'
- outfp.write('X' + line)
- outfp.write('!\n')
- fp.close()
+ fp = open(file, 'r')
+ outfp.write('echo ' + name + '\n')
+ outfp.write('sed "s/^X//" >"' + name + '" <<"!"\n')
+ while 1:
+ line = fp.readline()
+ if not line: break
+ if line[-1:] != '\n':
+ line = line + '\n'
+ outfp.write('X' + line)
+ outfp.write('!\n')
+ fp.close()
# Pack some files from a directory
def packsome(outfp, dirname, names):
- for name in names:
- print name
- file = os.path.join(dirname, name)
- pack(outfp, file, name)
+ for name in names:
+ print name
+ file = os.path.join(dirname, name)
+ pack(outfp, file, name)
# Pack all files from a directory
def packall(outfp, dirname):
- names = os.listdir(dirname)
- try:
- names.remove('.')
- except:
- pass
- try:
- names.remove('..')
- except:
- pass
- names.sort()
- packsome(outfp, dirname, names)
+ names = os.listdir(dirname)
+ try:
+ names.remove('.')
+ except:
+ pass
+ try:
+ names.remove('..')
+ except:
+ pass
+ names.sort()
+ packsome(outfp, dirname, names)
# Pack all files from a directory that are not older than a give one
def packnotolder(outfp, dirname, oldest):
- names = os.listdir(dirname)
- try:
- names.remove('.')
- except:
- pass
- try:
- names.remove('..')
- except:
- pass
- oldest = os.path.join(dirname, oldest)
- st = os.stat(oldest)
- mtime = st[ST_MTIME]
- todo = []
- for name in names:
- print name, '...',
- st = os.stat(os.path.join(dirname, name))
- if st[ST_MTIME] >= mtime:
- print 'Yes.'
- todo.append(name)
- else:
- print 'No.'
- todo.sort()
- packsome(outfp, dirname, todo)
+ names = os.listdir(dirname)
+ try:
+ names.remove('.')
+ except:
+ pass
+ try:
+ names.remove('..')
+ except:
+ pass
+ oldest = os.path.join(dirname, oldest)
+ st = os.stat(oldest)
+ mtime = st[ST_MTIME]
+ todo = []
+ for name in names:
+ print name, '...',
+ st = os.stat(os.path.join(dirname, name))
+ if st[ST_MTIME] >= mtime:
+ print 'Yes.'
+ todo.append(name)
+ else:
+ print 'No.'
+ todo.sort()
+ packsome(outfp, dirname, todo)
# Pack a whole tree (no exceptions)
def packtree(outfp, dirname):
- print 'packtree', dirname
- outfp.write('mkdir ' + unixfix(dirname) + '\n')
- names = os.listdir(dirname)
- try:
- names.remove('.')
- except:
- pass
- try:
- names.remove('..')
- except:
- pass
- subdirs = []
- for name in names:
- fullname = os.path.join(dirname, name)
- if os.path.isdir(fullname):
- subdirs.append(fullname)
- else:
- print 'pack', fullname
- pack(outfp, fullname, unixfix(fullname))
- for subdirname in subdirs:
- packtree(outfp, subdirname)
+ print 'packtree', dirname
+ outfp.write('mkdir ' + unixfix(dirname) + '\n')
+ names = os.listdir(dirname)
+ try:
+ names.remove('.')
+ except:
+ pass
+ try:
+ names.remove('..')
+ except:
+ pass
+ subdirs = []
+ for name in names:
+ fullname = os.path.join(dirname, name)
+ if os.path.isdir(fullname):
+ subdirs.append(fullname)
+ else:
+ print 'pack', fullname
+ pack(outfp, fullname, unixfix(fullname))
+ for subdirname in subdirs:
+ packtree(outfp, subdirname)
def unixfix(name):
- comps = name.split(os.sep)
- res = ''
- for comp in comps:
- if comp:
- if res: res = res + '/'
- res = res + comp
- return res
+ comps = name.split(os.sep)
+ res = ''
+ for comp in comps:
+ if comp:
+ if res: res = res + '/'
+ res = res + comp
+ return res
diff --git a/Lib/lib-old/poly.py b/Lib/lib-old/poly.py
index f89bd14287..fe6a1dcc26 100644
--- a/Lib/lib-old/poly.py
+++ b/Lib/lib-old/poly.py
@@ -6,47 +6,47 @@
# taken out by normalize().
def normalize(p): # Strip unnecessary zero coefficients
- n = len(p)
- while n:
- if p[n-1]: return p[:n]
- n = n-1
- return []
+ n = len(p)
+ while n:
+ if p[n-1]: return p[:n]
+ n = n-1
+ return []
def plus(a, b):
- if len(a) < len(b): a, b = b, a # make sure a is the longest
- res = a[:] # make a copy
- for i in range(len(b)):
- res[i] = res[i] + b[i]
- return normalize(res)
+ if len(a) < len(b): a, b = b, a # make sure a is the longest
+ res = a[:] # make a copy
+ for i in range(len(b)):
+ res[i] = res[i] + b[i]
+ return normalize(res)
def minus(a, b):
- neg_b = map(lambda x: -x, b[:])
- return plus(a, neg_b)
+ neg_b = map(lambda x: -x, b[:])
+ return plus(a, neg_b)
def one(power, coeff): # Representation of coeff * x**power
- res = []
- for i in range(power): res.append(0)
- return res + [coeff]
+ res = []
+ for i in range(power): res.append(0)
+ return res + [coeff]
def times(a, b):
- res = []
- for i in range(len(a)):
- for j in range(len(b)):
- res = plus(res, one(i+j, a[i]*b[j]))
- return res
+ res = []
+ for i in range(len(a)):
+ for j in range(len(b)):
+ res = plus(res, one(i+j, a[i]*b[j]))
+ return res
def power(a, n): # Raise polynomial a to the positive integral power n
- if n == 0: return [1]
- if n == 1: return a
- if n/2*2 == n:
- b = power(a, n/2)
- return times(b, b)
- return times(power(a, n-1), a)
+ if n == 0: return [1]
+ if n == 1: return a
+ if n/2*2 == n:
+ b = power(a, n/2)
+ return times(b, b)
+ return times(power(a, n-1), a)
def der(a): # First derivative
- res = a[1:]
- for i in range(len(res)):
- res[i] = res[i] * (i+1)
- return res
+ res = a[1:]
+ for i in range(len(res)):
+ res[i] = res[i] * (i+1)
+ return res
# Computing a primitive function would require rational arithmetic...
diff --git a/Lib/lib-old/rand.py b/Lib/lib-old/rand.py
index c299d0a9a9..a557b69524 100644
--- a/Lib/lib-old/rand.py
+++ b/Lib/lib-old/rand.py
@@ -4,10 +4,10 @@
import whrandom
def srand(seed):
- whrandom.seed(seed%256, seed/256%256, seed/65536%256)
+ whrandom.seed(seed%256, seed/256%256, seed/65536%256)
def rand():
- return int(whrandom.random() * 32768.0) % 32768
+ return int(whrandom.random() * 32768.0) % 32768
def choice(seq):
- return seq[rand() % len(seq)]
+ return seq[rand() % len(seq)]
diff --git a/Lib/lib-old/tb.py b/Lib/lib-old/tb.py
index 57851aa729..906355978b 100644
--- a/Lib/lib-old/tb.py
+++ b/Lib/lib-old/tb.py
@@ -12,166 +12,166 @@ def br(): browser(sys.last_traceback)
def tb(): printtb(sys.last_traceback)
def browser(tb):
- if not tb:
- print 'No traceback.'
- return
- tblist = []
- while tb:
- tblist.append(tb)
- tb = tb.tb_next
- ptr = len(tblist)-1
- tb = tblist[ptr]
- while 1:
- if tb != tblist[ptr]:
- tb = tblist[ptr]
- print `ptr` + ':',
- printtbheader(tb)
- try:
- line = raw_input('TB: ')
- except KeyboardInterrupt:
- print '\n[Interrupted]'
- break
- except EOFError:
- print '\n[EOF]'
- break
- cmd = line.strip()
- if cmd:
- if cmd == 'quit':
- break
- elif cmd == 'list':
- browserlist(tb)
- elif cmd == 'up':
- if ptr-1 >= 0: ptr = ptr-1
- else: print 'Bottom of stack.'
- elif cmd == 'down':
- if ptr+1 < len(tblist): ptr = ptr+1
- else: print 'Top of stack.'
- elif cmd == 'locals':
- printsymbols(tb.tb_frame.f_locals)
- elif cmd == 'globals':
- printsymbols(tb.tb_frame.f_globals)
- elif cmd in ('?', 'help'):
- browserhelp()
- else:
- browserexec(tb, cmd)
+ if not tb:
+ print 'No traceback.'
+ return
+ tblist = []
+ while tb:
+ tblist.append(tb)
+ tb = tb.tb_next
+ ptr = len(tblist)-1
+ tb = tblist[ptr]
+ while 1:
+ if tb != tblist[ptr]:
+ tb = tblist[ptr]
+ print `ptr` + ':',
+ printtbheader(tb)
+ try:
+ line = raw_input('TB: ')
+ except KeyboardInterrupt:
+ print '\n[Interrupted]'
+ break
+ except EOFError:
+ print '\n[EOF]'
+ break
+ cmd = line.strip()
+ if cmd:
+ if cmd == 'quit':
+ break
+ elif cmd == 'list':
+ browserlist(tb)
+ elif cmd == 'up':
+ if ptr-1 >= 0: ptr = ptr-1
+ else: print 'Bottom of stack.'
+ elif cmd == 'down':
+ if ptr+1 < len(tblist): ptr = ptr+1
+ else: print 'Top of stack.'
+ elif cmd == 'locals':
+ printsymbols(tb.tb_frame.f_locals)
+ elif cmd == 'globals':
+ printsymbols(tb.tb_frame.f_globals)
+ elif cmd in ('?', 'help'):
+ browserhelp()
+ else:
+ browserexec(tb, cmd)
def browserlist(tb):
- filename = tb.tb_frame.f_code.co_filename
- lineno = tb.tb_lineno
- last = lineno
- first = max(1, last-10)
- for i in range(first, last+1):
- if i == lineno: prefix = '***' + `i`.rjust(4) + ':'
- else: prefix = `i`.rjust(7) + ':'
- line = linecache.getline(filename, i)
- if line[-1:] == '\n': line = line[:-1]
- print prefix + line
+ filename = tb.tb_frame.f_code.co_filename
+ lineno = tb.tb_lineno
+ last = lineno
+ first = max(1, last-10)
+ for i in range(first, last+1):
+ if i == lineno: prefix = '***' + `i`.rjust(4) + ':'
+ else: prefix = `i`.rjust(7) + ':'
+ line = linecache.getline(filename, i)
+ if line[-1:] == '\n': line = line[:-1]
+ print prefix + line
def browserexec(tb, cmd):
- locals = tb.tb_frame.f_locals
- globals = tb.tb_frame.f_globals
- try:
- exec cmd+'\n' in globals, locals
- except:
- t, v = sys.exc_info()[:2]
- print '*** Exception:',
- if type(t) is type(''):
- print t,
- else:
- print t.__name__,
- if v is not None:
- print ':', v,
- print
- print 'Type help to get help.'
+ locals = tb.tb_frame.f_locals
+ globals = tb.tb_frame.f_globals
+ try:
+ exec cmd+'\n' in globals, locals
+ except:
+ t, v = sys.exc_info()[:2]
+ print '*** Exception:',
+ if type(t) is type(''):
+ print t,
+ else:
+ print t.__name__,
+ if v is not None:
+ print ':', v,
+ print
+ print 'Type help to get help.'
def browserhelp():
- print
- print ' This is the traceback browser. Commands are:'
- print ' up : move one level up in the call stack'
- print ' down : move one level down in the call stack'
- print ' locals : print all local variables at this level'
- print ' globals : print all global variables at this level'
- print ' list : list source code around the failure'
- print ' help : print help (what you are reading now)'
- print ' quit : back to command interpreter'
- print ' Typing any other 1-line statement will execute it'
- print ' using the current level\'s symbol tables'
- print
+ print
+ print ' This is the traceback browser. Commands are:'
+ print ' up : move one level up in the call stack'
+ print ' down : move one level down in the call stack'
+ print ' locals : print all local variables at this level'
+ print ' globals : print all global variables at this level'
+ print ' list : list source code around the failure'
+ print ' help : print help (what you are reading now)'
+ print ' quit : back to command interpreter'
+ print ' Typing any other 1-line statement will execute it'
+ print ' using the current level\'s symbol tables'
+ print
def printtb(tb):
- while tb:
- print1tb(tb)
- tb = tb.tb_next
+ while tb:
+ print1tb(tb)
+ tb = tb.tb_next
def print1tb(tb):
- printtbheader(tb)
- if tb.tb_frame.f_locals is not tb.tb_frame.f_globals:
- printsymbols(tb.tb_frame.f_locals)
+ printtbheader(tb)
+ if tb.tb_frame.f_locals is not tb.tb_frame.f_globals:
+ printsymbols(tb.tb_frame.f_locals)
def printtbheader(tb):
- filename = tb.tb_frame.f_code.co_filename
- lineno = tb.tb_lineno
- info = '"' + filename + '"(' + `lineno` + ')'
- line = linecache.getline(filename, lineno)
- if line:
- info = info + ': ' + line.strip()
- print info
+ filename = tb.tb_frame.f_code.co_filename
+ lineno = tb.tb_lineno
+ info = '"' + filename + '"(' + `lineno` + ')'
+ line = linecache.getline(filename, lineno)
+ if line:
+ info = info + ': ' + line.strip()
+ print info
def printsymbols(d):
- keys = d.keys()
- keys.sort()
- for name in keys:
- print ' ' + name.ljust(12) + ':',
- printobject(d[name], 4)
- print
+ keys = d.keys()
+ keys.sort()
+ for name in keys:
+ print ' ' + name.ljust(12) + ':',
+ printobject(d[name], 4)
+ print
def printobject(v, maxlevel):
- if v is None:
- print 'None',
- elif type(v) in (type(0), type(0.0)):
- print v,
- elif type(v) is type(''):
- if len(v) > 20:
- print `v[:17] + '...'`,
- else:
- print `v`,
- elif type(v) is type(()):
- print '(',
- printlist(v, maxlevel)
- print ')',
- elif type(v) is type([]):
- print '[',
- printlist(v, maxlevel)
- print ']',
- elif type(v) is type({}):
- print '{',
- printdict(v, maxlevel)
- print '}',
- else:
- print v,
+ if v is None:
+ print 'None',
+ elif type(v) in (type(0), type(0.0)):
+ print v,
+ elif type(v) is type(''):
+ if len(v) > 20:
+ print `v[:17] + '...'`,
+ else:
+ print `v`,
+ elif type(v) is type(()):
+ print '(',
+ printlist(v, maxlevel)
+ print ')',
+ elif type(v) is type([]):
+ print '[',
+ printlist(v, maxlevel)
+ print ']',
+ elif type(v) is type({}):
+ print '{',
+ printdict(v, maxlevel)
+ print '}',
+ else:
+ print v,
def printlist(v, maxlevel):
- n = len(v)
- if n == 0: return
- if maxlevel <= 0:
- print '...',
- return
- for i in range(min(6, n)):
- printobject(v[i], maxlevel-1)
- if i+1 < n: print ',',
- if n > 6: print '...',
+ n = len(v)
+ if n == 0: return
+ if maxlevel <= 0:
+ print '...',
+ return
+ for i in range(min(6, n)):
+ printobject(v[i], maxlevel-1)
+ if i+1 < n: print ',',
+ if n > 6: print '...',
def printdict(v, maxlevel):
- keys = v.keys()
- n = len(keys)
- if n == 0: return
- if maxlevel <= 0:
- print '...',
- return
- keys.sort()
- for i in range(min(6, n)):
- key = keys[i]
- print `key` + ':',
- printobject(v[key], maxlevel-1)
- if i+1 < n: print ',',
- if n > 6: print '...',
+ keys = v.keys()
+ n = len(keys)
+ if n == 0: return
+ if maxlevel <= 0:
+ print '...',
+ return
+ keys.sort()
+ for i in range(min(6, n)):
+ key = keys[i]
+ print `key` + ':',
+ printobject(v[key], maxlevel-1)
+ if i+1 < n: print ',',
+ if n > 6: print '...',
diff --git a/Lib/lib-old/util.py b/Lib/lib-old/util.py
index 6cb1433426..104af1e385 100644
--- a/Lib/lib-old/util.py
+++ b/Lib/lib-old/util.py
@@ -10,16 +10,16 @@
# If it occurs more than once, remove the first occurrence.
#
def remove(item, list):
- if item in list: list.remove(item)
+ if item in list: list.remove(item)
# Return a string containing a file's contents.
#
def readfile(fn):
- return readopenfile(open(fn, 'r'))
+ return readopenfile(open(fn, 'r'))
# Read an open file until EOF.
#
def readopenfile(fp):
- return fp.read()
+ return fp.read()
diff --git a/Lib/lib-old/zmod.py b/Lib/lib-old/zmod.py
index 7259bf8f7c..55f49dff59 100644
--- a/Lib/lib-old/zmod.py
+++ b/Lib/lib-old/zmod.py
@@ -1,7 +1,7 @@
# module 'zmod'
# Compute properties of mathematical "fields" formed by taking
-# Z/n (the whole numbers modulo some whole number n) and an
+# Z/n (the whole numbers modulo some whole number n) and an
# irreducible polynomial (i.e., a polynomial with only complex zeros),
# e.g., Z/5 and X**2 + 2.
#
@@ -30,65 +30,65 @@ P = poly.plus(poly.one(0, 2), poly.one(2, 1)) # 2 + x**2
# Return x modulo y. Returns >= 0 even if x < 0.
def mod(x, y):
- return divmod(x, y)[1]
+ return divmod(x, y)[1]
# Normalize a polynomial modulo n and modulo p.
def norm(a, n, p):
- a = poly.modulo(a, p)
- a = a[:]
- for i in range(len(a)): a[i] = mod(a[i], n)
- a = poly.normalize(a)
- return a
+ a = poly.modulo(a, p)
+ a = a[:]
+ for i in range(len(a)): a[i] = mod(a[i], n)
+ a = poly.normalize(a)
+ return a
# Make a list of all n^d elements of the proposed field.
def make_all(mat):
- all = []
- for row in mat:
- for a in row:
- all.append(a)
- return all
+ all = []
+ for row in mat:
+ for a in row:
+ all.append(a)
+ return all
def make_elements(n, d):
- if d == 0: return [poly.one(0, 0)]
- sub = make_elements(n, d-1)
- all = []
- for a in sub:
- for i in range(n):
- all.append(poly.plus(a, poly.one(d-1, i)))
- return all
+ if d == 0: return [poly.one(0, 0)]
+ sub = make_elements(n, d-1)
+ all = []
+ for a in sub:
+ for i in range(n):
+ all.append(poly.plus(a, poly.one(d-1, i)))
+ return all
def make_inv(all, n, p):
- x = poly.one(1, 1)
- inv = []
- for a in all:
- inv.append(norm(poly.times(a, x), n, p))
- return inv
+ x = poly.one(1, 1)
+ inv = []
+ for a in all:
+ inv.append(norm(poly.times(a, x), n, p))
+ return inv
def checkfield(n, p):
- all = make_elements(n, len(p)-1)
- inv = make_inv(all, n, p)
- all1 = all[:]
- inv1 = inv[:]
- all1.sort()
- inv1.sort()
- if all1 == inv1: print 'BINGO!'
- else:
- print 'Sorry:', n, p
- print all
- print inv
+ all = make_elements(n, len(p)-1)
+ inv = make_inv(all, n, p)
+ all1 = all[:]
+ inv1 = inv[:]
+ all1.sort()
+ inv1.sort()
+ if all1 == inv1: print 'BINGO!'
+ else:
+ print 'Sorry:', n, p
+ print all
+ print inv
def rj(s, width):
- if type(s) is not type(''): s = `s`
- n = len(s)
- if n >= width: return s
- return ' '*(width - n) + s
+ if type(s) is not type(''): s = `s`
+ n = len(s)
+ if n >= width: return s
+ return ' '*(width - n) + s
def lj(s, width):
- if type(s) is not type(''): s = `s`
- n = len(s)
- if n >= width: return s
- return s + ' '*(width - n)
+ if type(s) is not type(''): s = `s`
+ n = len(s)
+ if n >= width: return s
+ return s + ' '*(width - n)
diff --git a/Lib/lib-tk/Tix.py b/Lib/lib-tk/Tix.py
index f19bf97799..eb349ddea5 100755
--- a/Lib/lib-tk/Tix.py
+++ b/Lib/lib-tk/Tix.py
@@ -1104,15 +1104,15 @@ class ListNoteBook(TixWidget):
return self.subwidget_list[name]
def page(self, name):
- return self.subwidget(name)
+ return self.subwidget(name)
def pages(self):
- # Can't call subwidgets_all directly because we don't want .nbframe
- names = self.tk.split(self.tk.call(self._w, 'pages'))
- ret = []
- for x in names:
- ret.append(self.subwidget(x))
- return ret
+ # Can't call subwidgets_all directly because we don't want .nbframe
+ names = self.tk.split(self.tk.call(self._w, 'pages'))
+ ret = []
+ for x in names:
+ ret.append(self.subwidget(x))
+ return ret
def raise_page(self, name): # raise is a python keyword
self.tk.call(self._w, 'raise', name)
@@ -1737,7 +1737,7 @@ class _dummyNoteBookFrame(NoteBookFrame, TixSubWidget):
class _dummyPanedWindow(PanedWindow, TixSubWidget):
def __init__(self, master, name, destroy_physically=1):
- TixSubWidget.__init__(self, master, name, destroy_physically)
+ TixSubWidget.__init__(self, master, name, destroy_physically)
########################
### Utility Routines ###
diff --git a/Lib/lib-tk/Tkinter.py b/Lib/lib-tk/Tkinter.py
index 5ad065da2d..3ffd2dfad0 100644
--- a/Lib/lib-tk/Tkinter.py
+++ b/Lib/lib-tk/Tkinter.py
@@ -1557,7 +1557,7 @@ class Tk(Misc, Wm):
self._tkloaded = 0
# to avoid recursions in the getattr code in case of failure, we
# ensure that self.tk is always _something_.
- self.tk = None
+ self.tk = None
if baseName is None:
import sys, os
baseName = os.path.basename(sys.argv[0])
diff --git a/Lib/lib-tk/tkFileDialog.py b/Lib/lib-tk/tkFileDialog.py
index c2c661cbad..a35feedc50 100644
--- a/Lib/lib-tk/tkFileDialog.py
+++ b/Lib/lib-tk/tkFileDialog.py
@@ -131,8 +131,8 @@ def asksaveasfilename(**options):
def askopenfilenames(**options):
"""Ask for multiple filenames to open
-
- Returns a list of filenames or empty list if
+
+ Returns a list of filenames or empty list if
cancel button selected
"""
options["multiple"]=1
@@ -151,8 +151,8 @@ def askopenfile(mode = "r", **options):
def askopenfiles(mode = "r", **options):
"""Ask for multiple filenames and return the open file
objects
-
- returns a list of open file objects or an empty list if
+
+ returns a list of open file objects or an empty list if
cancel selected
"""
@@ -204,7 +204,7 @@ if __name__ == "__main__":
fp=open(openfilename,"r")
fp.close()
except:
- print "Could not open File: "
+ print "Could not open File: "
print sys.exc_info()[1]
print "open", openfilename.encode(enc)
@@ -213,4 +213,3 @@ if __name__ == "__main__":
saveasfilename=asksaveasfilename()
print "saveas", saveasfilename.encode(enc)
-
diff --git a/Lib/plat-atheos/IN.py b/Lib/plat-atheos/IN.py
index a386a21c28..53f3d5579f 100644
--- a/Lib/plat-atheos/IN.py
+++ b/Lib/plat-atheos/IN.py
@@ -50,7 +50,7 @@ def __P(args): return args
def __PMT(args): return args
-def __P(args): return ()
+def __P(args): return ()
def __PMT(args): return ()
@@ -60,7 +60,7 @@ def __STRING(x): return "x"
def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
-def __attribute__(xyz): return
+def __attribute__(xyz): return
__USE_EXTERN_INLINES = 1
@@ -942,4 +942,3 @@ def IN6_IS_ADDR_MC_SITELOCAL(a): return \
def IN6_IS_ADDR_MC_ORGLOCAL(a): return \
def IN6_IS_ADDR_MC_GLOBAL(a): return \
-
diff --git a/Lib/plat-atheos/TYPES.py b/Lib/plat-atheos/TYPES.py
index 81661089dd..314ca736a8 100644
--- a/Lib/plat-atheos/TYPES.py
+++ b/Lib/plat-atheos/TYPES.py
@@ -50,7 +50,7 @@ def __P(args): return args
def __PMT(args): return args
-def __P(args): return ()
+def __P(args): return ()
def __PMT(args): return ()
@@ -60,7 +60,7 @@ def __STRING(x): return "x"
def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
-def __attribute__(xyz): return
+def __attribute__(xyz): return
__USE_EXTERN_INLINES = 1
@@ -140,4 +140,3 @@ _SYS_SYSMACROS_H = 1
def major(dev): return ( (( (dev) >> 8) & 0xff))
def minor(dev): return ( ((dev) & 0xff))
-
diff --git a/Lib/plat-beos5/IN.py b/Lib/plat-beos5/IN.py
index 1878a85d0b..362cb41fa7 100644
--- a/Lib/plat-beos5/IN.py
+++ b/Lib/plat-beos5/IN.py
@@ -324,4 +324,4 @@ FDSETSIZE = FD_SETSIZE
NFDBITS = 32
def _FDMSKNO(fd): return ((fd) / NFDBITS)
-def _FDBITNO(fd): return ((fd) % NFDBITS) \ No newline at end of file
+def _FDBITNO(fd): return ((fd) % NFDBITS)
diff --git a/Lib/plat-irix5/AL.py b/Lib/plat-irix5/AL.py
index ed17cde2ef..ec941a2bac 100755
--- a/Lib/plat-irix5/AL.py
+++ b/Lib/plat-irix5/AL.py
@@ -1,61 +1,61 @@
-RATE_48000 = 48000
-RATE_44100 = 44100
-RATE_32000 = 32000
-RATE_22050 = 22050
-RATE_16000 = 16000
-RATE_11025 = 11025
-RATE_8000 = 8000
+RATE_48000 = 48000
+RATE_44100 = 44100
+RATE_32000 = 32000
+RATE_22050 = 22050
+RATE_16000 = 16000
+RATE_11025 = 11025
+RATE_8000 = 8000
SAMPFMT_TWOSCOMP= 1
-SAMPFMT_FLOAT = 32
-SAMPFMT_DOUBLE = 64
+SAMPFMT_FLOAT = 32
+SAMPFMT_DOUBLE = 64
-SAMPLE_8 = 1
-SAMPLE_16 = 2
- # SAMPLE_24 is the low 24 bits of a long, sign extended to 32 bits
-SAMPLE_24 = 4
+SAMPLE_8 = 1
+SAMPLE_16 = 2
+ # SAMPLE_24 is the low 24 bits of a long, sign extended to 32 bits
+SAMPLE_24 = 4
-MONO = 1
-STEREO = 2
-QUADRO = 4 # 4CHANNEL is not a legal Python name
+MONO = 1
+STEREO = 2
+QUADRO = 4 # 4CHANNEL is not a legal Python name
-INPUT_LINE = 0
-INPUT_MIC = 1
-INPUT_DIGITAL = 2
+INPUT_LINE = 0
+INPUT_MIC = 1
+INPUT_DIGITAL = 2
-MONITOR_OFF = 0
-MONITOR_ON = 1
+MONITOR_OFF = 0
+MONITOR_ON = 1
-ERROR_NUMBER = 0
-ERROR_TYPE = 1
-ERROR_LOCATION_LSP = 2
-ERROR_LOCATION_MSP = 3
-ERROR_LENGTH = 4
+ERROR_NUMBER = 0
+ERROR_TYPE = 1
+ERROR_LOCATION_LSP = 2
+ERROR_LOCATION_MSP = 3
+ERROR_LENGTH = 4
-ERROR_INPUT_UNDERFLOW = 0
-ERROR_OUTPUT_OVERFLOW = 1
+ERROR_INPUT_UNDERFLOW = 0
+ERROR_OUTPUT_OVERFLOW = 1
# These seem to be not supported anymore:
-##HOLD, RELEASE = 0, 1
-##ATTAIL, ATHEAD, ATMARK, ATTIME = 0, 1, 2, 3
-
-DEFAULT_DEVICE = 1
-
-INPUT_SOURCE = 0
-LEFT_INPUT_ATTEN = 1
-RIGHT_INPUT_ATTEN = 2
-INPUT_RATE = 3
-OUTPUT_RATE = 4
-LEFT_SPEAKER_GAIN = 5
-RIGHT_SPEAKER_GAIN = 6
-INPUT_COUNT = 7
-OUTPUT_COUNT = 8
-UNUSED_COUNT = 9
-SYNC_INPUT_TO_AES = 10
-SYNC_OUTPUT_TO_AES = 11
-MONITOR_CTL = 12
-LEFT_MONITOR_ATTEN = 13
-RIGHT_MONITOR_ATTEN = 14
-
-ENUM_VALUE = 0 # only certain values are valid
-RANGE_VALUE = 1 # any value in range is valid
+##HOLD, RELEASE = 0, 1
+##ATTAIL, ATHEAD, ATMARK, ATTIME = 0, 1, 2, 3
+
+DEFAULT_DEVICE = 1
+
+INPUT_SOURCE = 0
+LEFT_INPUT_ATTEN = 1
+RIGHT_INPUT_ATTEN = 2
+INPUT_RATE = 3
+OUTPUT_RATE = 4
+LEFT_SPEAKER_GAIN = 5
+RIGHT_SPEAKER_GAIN = 6
+INPUT_COUNT = 7
+OUTPUT_COUNT = 8
+UNUSED_COUNT = 9
+SYNC_INPUT_TO_AES = 10
+SYNC_OUTPUT_TO_AES = 11
+MONITOR_CTL = 12
+LEFT_MONITOR_ATTEN = 13
+RIGHT_MONITOR_ATTEN = 14
+
+ENUM_VALUE = 0 # only certain values are valid
+RANGE_VALUE = 1 # any value in range is valid
diff --git a/Lib/plat-irix5/CD.py b/Lib/plat-irix5/CD.py
index ad56561235..8c1e03bc6e 100755
--- a/Lib/plat-irix5/CD.py
+++ b/Lib/plat-irix5/CD.py
@@ -1,34 +1,34 @@
-ERROR = 0
-NODISC = 1
-READY = 2
-PLAYING = 3
-PAUSED = 4
-STILL = 5
+ERROR = 0
+NODISC = 1
+READY = 2
+PLAYING = 3
+PAUSED = 4
+STILL = 5
-AUDIO = 0
-PNUM = 1
-INDEX = 2
-PTIME = 3
-ATIME = 4
-CATALOG = 5
-IDENT = 6
-CONTROL = 7
+AUDIO = 0
+PNUM = 1
+INDEX = 2
+PTIME = 3
+ATIME = 4
+CATALOG = 5
+IDENT = 6
+CONTROL = 7
-CDDA_DATASIZE = 2352
+CDDA_DATASIZE = 2352
-##CDDA_SUBCODESIZE = (sizeof(struct subcodeQ))
-##CDDA_BLOCKSIZE = (sizeof(struct cdframe))
-##CDDA_NUMSAMPLES = (CDDA_DATASIZE/2)
+##CDDA_SUBCODESIZE = (sizeof(struct subcodeQ))
+##CDDA_BLOCKSIZE = (sizeof(struct cdframe))
+##CDDA_NUMSAMPLES = (CDDA_DATASIZE/2)
##
-##CDQ_PREEMP_MASK = 0xd
-##CDQ_COPY_MASK = 0xb
-##CDQ_DDATA_MASK = 0xd
-##CDQ_BROADCAST_MASK = 0x8
-##CDQ_PREEMPHASIS = 0x1
-##CDQ_COPY_PERMITTED = 0x2
-##CDQ_DIGITAL_DATA = 0x4
-##CDQ_BROADCAST_USE = 0x8
+##CDQ_PREEMP_MASK = 0xd
+##CDQ_COPY_MASK = 0xb
+##CDQ_DDATA_MASK = 0xd
+##CDQ_BROADCAST_MASK = 0x8
+##CDQ_PREEMPHASIS = 0x1
+##CDQ_COPY_PERMITTED = 0x2
+##CDQ_DIGITAL_DATA = 0x4
+##CDQ_BROADCAST_USE = 0x8
##
-##CDQ_MODE1 = 0x1
-##CDQ_MODE2 = 0x2
-##CDQ_MODE3 = 0x3
+##CDQ_MODE1 = 0x1
+##CDQ_MODE2 = 0x2
+##CDQ_MODE3 = 0x3
diff --git a/Lib/plat-irix5/CL.py b/Lib/plat-irix5/CL.py
index 468ecaaa68..23259c5548 100755
--- a/Lib/plat-irix5/CL.py
+++ b/Lib/plat-irix5/CL.py
@@ -1,24 +1,24 @@
# Backward compatible module CL.
# All relevant symbols are now defined in the module cl.
try:
- from cl import *
+ from cl import *
except ImportError:
- from CL_old import *
+ from CL_old import *
else:
- del CompressImage
- del DecompressImage
- del GetAlgorithmName
- del OpenCompressor
- del OpenDecompressor
- del QueryAlgorithms
- del QueryMaxHeaderSize
- del QueryScheme
- del QuerySchemeFromName
- del SetDefault
- del SetMax
- del SetMin
- try:
- del cvt_type
- except NameError:
- pass
- del error
+ del CompressImage
+ del DecompressImage
+ del GetAlgorithmName
+ del OpenCompressor
+ del OpenDecompressor
+ del QueryAlgorithms
+ del QueryMaxHeaderSize
+ del QueryScheme
+ del QuerySchemeFromName
+ del SetDefault
+ del SetMax
+ del SetMin
+ try:
+ del cvt_type
+ except NameError:
+ pass
+ del error
diff --git a/Lib/plat-irix5/CL_old.py b/Lib/plat-irix5/CL_old.py
index d9a4100248..967b49708c 100755
--- a/Lib/plat-irix5/CL_old.py
+++ b/Lib/plat-irix5/CL_old.py
@@ -1,8 +1,8 @@
#
# cl.h - Compression Library typedefs and prototypes
#
-# 01/07/92 Cleanup by Brian Knittel
-# 02/18/92 Original Version by Brian Knittel
+# 01/07/92 Cleanup by Brian Knittel
+# 02/18/92 Original Version by Brian Knittel
#
#
@@ -14,13 +14,13 @@ MAX_NUMBER_OF_ORIGINAL_FORMATS = 32
MONO = 0
STEREO_INTERLEAVED = 1
-# Video
+# Video
# YUV is defined to be the same thing as YCrCb (luma and two chroma components).
-# 422 is appended to YUV (or YCrCb) if the chroma is sub-sampled by 2
-# horizontally, packed as U Y1 V Y2 (byte order).
-# 422HC is appended to YUV (or YCrCb) if the chroma is sub-sampled by 2
-# vertically in addition to horizontally, and is packed the same as
-# 422 except that U & V are not valid on the second line.
+# 422 is appended to YUV (or YCrCb) if the chroma is sub-sampled by 2
+# horizontally, packed as U Y1 V Y2 (byte order).
+# 422HC is appended to YUV (or YCrCb) if the chroma is sub-sampled by 2
+# vertically in addition to horizontally, and is packed the same as
+# 422 except that U & V are not valid on the second line.
#
RGB = 0
RGBX = 1
@@ -29,62 +29,62 @@ RGB332 = 3
GRAYSCALE = 4
Y = 4
-YUV = 5
-YCbCr = 5
-YUV422 = 6 # 4:2:2 sampling
-YCbCr422 = 6 # 4:2:2 sampling
-YUV422HC = 7 # 4:1:1 sampling
-YCbCr422HC = 7 # 4:1:1 sampling
-YUV422DC = 7 # 4:1:1 sampling
-YCbCr422DC = 7 # 4:1:1 sampling
+YUV = 5
+YCbCr = 5
+YUV422 = 6 # 4:2:2 sampling
+YCbCr422 = 6 # 4:2:2 sampling
+YUV422HC = 7 # 4:1:1 sampling
+YCbCr422HC = 7 # 4:1:1 sampling
+YUV422DC = 7 # 4:1:1 sampling
+YCbCr422DC = 7 # 4:1:1 sampling
-BEST_FIT = -1
+BEST_FIT = -1
def BytesPerSample(s):
- if s in (MONO, YUV):
- return 2
- elif s == STEREO_INTERLEAVED:
- return 4
- else:
- return 0
+ if s in (MONO, YUV):
+ return 2
+ elif s == STEREO_INTERLEAVED:
+ return 4
+ else:
+ return 0
def BytesPerPixel(f):
- if f in (RGB, YUV):
- return 3
- elif f in (RGBX, RGBA):
- return 4
- elif f in (RGB332, GRAYSCALE):
- return 1
- else:
- return 2
+ if f in (RGB, YUV):
+ return 3
+ elif f in (RGBX, RGBA):
+ return 4
+ elif f in (RGB332, GRAYSCALE):
+ return 1
+ else:
+ return 2
def AudioFormatName(f):
- if f == MONO:
- return 'MONO'
- elif f == STEREO_INTERLEAVED:
- return 'STEREO_INTERLEAVED'
- else:
- return 'Not a valid format'
+ if f == MONO:
+ return 'MONO'
+ elif f == STEREO_INTERLEAVED:
+ return 'STEREO_INTERLEAVED'
+ else:
+ return 'Not a valid format'
def VideoFormatName(f):
- if f == RGB:
- return 'RGB'
- elif f == RGBX:
- return 'RGBX'
- elif f == RGBA:
- return 'RGBA'
- elif f == RGB332:
- return 'RGB332'
- elif f == GRAYSCALE:
- return 'GRAYSCALE'
- elif f == YUV:
- return 'YUV'
- elif f == YUV422:
- return 'YUV422'
- elif f == YUV422DC:
- return 'YUV422DC'
- else:
- return 'Not a valid format'
+ if f == RGB:
+ return 'RGB'
+ elif f == RGBX:
+ return 'RGBX'
+ elif f == RGBA:
+ return 'RGBA'
+ elif f == RGB332:
+ return 'RGB332'
+ elif f == GRAYSCALE:
+ return 'GRAYSCALE'
+ elif f == YUV:
+ return 'YUV'
+ elif f == YUV422:
+ return 'YUV422'
+ elif f == YUV422DC:
+ return 'YUV422DC'
+ else:
+ return 'Not a valid format'
MAX_NUMBER_OF_AUDIO_ALGORITHMS = 32
MAX_NUMBER_OF_VIDEO_ALGORITHMS = 32
@@ -96,11 +96,11 @@ AUDIO = 0
VIDEO = 1
def AlgorithmNumber(scheme):
- return scheme & 0x7fff
+ return scheme & 0x7fff
def AlgorithmType(scheme):
- return (scheme >> 15) & 1
+ return (scheme >> 15) & 1
def Algorithm(type, n):
- return n | ((type & 1) << 15)
+ return n | ((type & 1) << 15)
#
# "compressionScheme" argument values
@@ -114,7 +114,7 @@ G711_ALAW = Algorithm(AUDIO, 2)
ALAW = Algorithm(AUDIO, 2)
AWARE_MPEG_AUDIO = Algorithm(AUDIO, 3)
AWARE_MULTIRATE = Algorithm(AUDIO, 4)
-
+
UNCOMPRESSED = Algorithm(VIDEO, 0)
UNCOMPRESSED_VIDEO = Algorithm(VIDEO, 0)
RLE = Algorithm(VIDEO, 1)
@@ -130,7 +130,7 @@ RTR1 = Algorithm(VIDEO, 5)
MAX_NUMBER_OF_PARAMS = 256
# Default Parameters
IMAGE_WIDTH = 0
-IMAGE_HEIGHT = 1
+IMAGE_HEIGHT = 1
ORIGINAL_FORMAT = 2
INTERNAL_FORMAT = 3
COMPONENTS = 4
@@ -138,7 +138,7 @@ BITS_PER_COMPONENT = 5
FRAME_RATE = 6
COMPRESSION_RATIO = 7
EXACT_COMPRESSION_RATIO = 8
-FRAME_BUFFER_SIZE = 9
+FRAME_BUFFER_SIZE = 9
COMPRESSED_BUFFER_SIZE = 10
BLOCK_SIZE = 11
PREROLL = 12
@@ -165,10 +165,10 @@ ZOOM_Y = NUMBER_OF_PARAMS + 2
#
# Parameter value types
#
-ENUM_VALUE = 0 # only certain constant values are valid
-RANGE_VALUE = 1 # any value in a given range is valid
-FLOATING_ENUM_VALUE = 2 # only certain constant floating point values are valid
-FLOATING_RANGE_VALUE = 3 # any value in a given floating point range is valid
+ENUM_VALUE = 0 # only certain constant values are valid
+RANGE_VALUE = 1 # any value in a given range is valid
+FLOATING_ENUM_VALUE = 2 # only certain constant floating point values are valid
+FLOATING_RANGE_VALUE = 3 # any value in a given floating point range is valid
#
# Algorithm Functionality
@@ -208,29 +208,29 @@ HEADER_START_CODE = 0xc1C0DEC
# error codes
#
-BAD_NO_BUFFERSPACE = -2 # no space for internal buffers
-BAD_PVBUFFER = -3 # param/val buffer doesn't make sense
-BAD_BUFFERLENGTH_NEG = -4 # negative buffer length
-BAD_BUFFERLENGTH_ODD = -5 # odd length parameter/value buffer
-BAD_PARAM = -6 # invalid parameter
-BAD_COMPRESSION_SCHEME = -7 # compression scheme parameter invalid
-BAD_COMPRESSOR_HANDLE = -8 # compression handle parameter invalid
-BAD_COMPRESSOR_HANDLE_POINTER = -9 # compression handle pointer invalid
-BAD_BUFFER_HANDLE = -10 # buffer handle invalid
-BAD_BUFFER_QUERY_SIZE = -11 # buffer query size too large
-JPEG_ERROR = -12 # error from libjpeg
-BAD_FRAME_SIZE = -13 # frame size invalid
-PARAM_OUT_OF_RANGE = -14 # parameter out of range
-ADDED_ALGORITHM_ERROR = -15 # added algorithm had a unique error
-BAD_ALGORITHM_TYPE = -16 # bad algorithm type
-BAD_ALGORITHM_NAME = -17 # bad algorithm name
-BAD_BUFFERING = -18 # bad buffering calls
-BUFFER_NOT_CREATED = -19 # buffer not created
-BAD_BUFFER_EXISTS = -20 # buffer already created
-BAD_INTERNAL_FORMAT = -21 # invalid internal format
-BAD_BUFFER_POINTER = -22 # invalid buffer pointer
-FRAME_BUFFER_SIZE_ZERO = -23 # frame buffer has zero size
-BAD_STREAM_HEADER = -24 # invalid stream header
-
-BAD_LICENSE = -25 # netls license not valid
-AWARE_ERROR = -26 # error from libawcmp
+BAD_NO_BUFFERSPACE = -2 # no space for internal buffers
+BAD_PVBUFFER = -3 # param/val buffer doesn't make sense
+BAD_BUFFERLENGTH_NEG = -4 # negative buffer length
+BAD_BUFFERLENGTH_ODD = -5 # odd length parameter/value buffer
+BAD_PARAM = -6 # invalid parameter
+BAD_COMPRESSION_SCHEME = -7 # compression scheme parameter invalid
+BAD_COMPRESSOR_HANDLE = -8 # compression handle parameter invalid
+BAD_COMPRESSOR_HANDLE_POINTER = -9 # compression handle pointer invalid
+BAD_BUFFER_HANDLE = -10 # buffer handle invalid
+BAD_BUFFER_QUERY_SIZE = -11 # buffer query size too large
+JPEG_ERROR = -12 # error from libjpeg
+BAD_FRAME_SIZE = -13 # frame size invalid
+PARAM_OUT_OF_RANGE = -14 # parameter out of range
+ADDED_ALGORITHM_ERROR = -15 # added algorithm had a unique error
+BAD_ALGORITHM_TYPE = -16 # bad algorithm type
+BAD_ALGORITHM_NAME = -17 # bad algorithm name
+BAD_BUFFERING = -18 # bad buffering calls
+BUFFER_NOT_CREATED = -19 # buffer not created
+BAD_BUFFER_EXISTS = -20 # buffer already created
+BAD_INTERNAL_FORMAT = -21 # invalid internal format
+BAD_BUFFER_POINTER = -22 # invalid buffer pointer
+FRAME_BUFFER_SIZE_ZERO = -23 # frame buffer has zero size
+BAD_STREAM_HEADER = -24 # invalid stream header
+
+BAD_LICENSE = -25 # netls license not valid
+AWARE_ERROR = -26 # error from libawcmp
diff --git a/Lib/plat-irix5/FL.py b/Lib/plat-irix5/FL.py
index ae665e3fe8..727da4c9a0 100755
--- a/Lib/plat-irix5/FL.py
+++ b/Lib/plat-irix5/FL.py
@@ -7,9 +7,9 @@ _v20 = 1
_v21 = 1
##import fl
##try:
-## _v20 = (fl.get_rgbmode is not None)
+## _v20 = (fl.get_rgbmode is not None)
##except:
-## _v20 = 0
+## _v20 = 0
##del fl
NULL = 0
@@ -20,7 +20,7 @@ EVENT = -1
LABEL_SIZE = 64
if _v20:
- SHORTCUT_SIZE = 32
+ SHORTCUT_SIZE = 32
PLACE_FREE = 0
PLACE_SIZE = 1
PLACE_ASPECT = 2
@@ -119,7 +119,7 @@ TOUCH_BUTTON = 4
INOUT_BUTTON = 5
RETURN_BUTTON = 6
if _v20:
- HIDDEN_RET_BUTTON = 7
+ HIDDEN_RET_BUTTON = 7
BUTTON_BOXTYPE = UP_BOX
BUTTON_COL1 = COL1
BUTTON_COL2 = COL1
@@ -129,20 +129,20 @@ BUTTON_MCOL1 = MCOL
BUTTON_MCOL2 = MCOL
BUTTON_BW = BOUND_WIDTH
if _v20:
- CHART = 4
- BAR_CHART = 0
- HORBAR_CHART = 1
- LINE_CHART = 2
- FILLED_CHART = 3
- SPIKE_CHART = 4
- PIE_CHART = 5
- SPECIALPIE_CHART = 6
- CHART_BOXTYPE = BORDER_BOX
- CHART_COL1 = COL1
- CHART_LCOL = LCOL
- CHART_ALIGN = ALIGN_BOTTOM
- CHART_BW = BOUND_WIDTH
- CHART_MAX = 128
+ CHART = 4
+ BAR_CHART = 0
+ HORBAR_CHART = 1
+ LINE_CHART = 2
+ FILLED_CHART = 3
+ SPIKE_CHART = 4
+ PIE_CHART = 5
+ SPECIALPIE_CHART = 6
+ CHART_BOXTYPE = BORDER_BOX
+ CHART_COL1 = COL1
+ CHART_LCOL = LCOL
+ CHART_ALIGN = ALIGN_BOTTOM
+ CHART_BW = BOUND_WIDTH
+ CHART_MAX = 128
CHOICE = 42
NORMAL_CHOICE = 0
CHOICE_BOXTYPE = DOWN_BOX
@@ -173,11 +173,11 @@ COUNTER_COL2 = 4
COUNTER_LCOL = LCOL
COUNTER_ALIGN = ALIGN_BOTTOM
if _v20:
- COUNTER_BW = BOUND_WIDTH
+ COUNTER_BW = BOUND_WIDTH
else:
- DEFAULT = 51
- RETURN_DEFAULT = 0
- ALWAYS_DEFAULT = 1
+ DEFAULT = 51
+ RETURN_DEFAULT = 0
+ ALWAYS_DEFAULT = 1
DIAL = 22
NORMAL_DIAL = 0
LINE_DIAL = 1
@@ -197,14 +197,14 @@ ALL_FREE = 5
INPUT = 31
NORMAL_INPUT = 0
if _v20:
- FLOAT_INPUT = 1
- INT_INPUT = 2
- HIDDEN_INPUT = 3
- if _v21:
- MULTILINE_INPUT = 4
- SECRET_INPUT = 5
+ FLOAT_INPUT = 1
+ INT_INPUT = 2
+ HIDDEN_INPUT = 3
+ if _v21:
+ MULTILINE_INPUT = 4
+ SECRET_INPUT = 5
else:
- ALWAYS_INPUT = 1
+ ALWAYS_INPUT = 1
INPUT_BOXTYPE = DOWN_BOX
INPUT_COL1 = 13
INPUT_COL2 = 5
diff --git a/Lib/plat-irix5/SV.py b/Lib/plat-irix5/SV.py
index 08fb91798a..db8efe52d4 100755
--- a/Lib/plat-irix5/SV.py
+++ b/Lib/plat-irix5/SV.py
@@ -7,16 +7,16 @@ BLANKING_BUFFER_SIZE = 2
MAX_SOURCES = 2
# mode parameter for Bind calls
-IN_OFF = 0 # No Video
-IN_OVER = 1 # Video over graphics
-IN_UNDER = 2 # Video under graphics
-IN_REPLACE = 3 # Video replaces entire win
+IN_OFF = 0 # No Video
+IN_OVER = 1 # Video over graphics
+IN_UNDER = 2 # Video under graphics
+IN_REPLACE = 3 # Video replaces entire win
# mode parameters for LoadMap calls. Specifies buffer, always 256 entries
-INPUT_COLORMAP = 0 # tuples of 8-bit RGB
-CHROMA_KEY_MAP = 1 # tuples of 8-bit RGB
-COLOR_SPACE_MAP = 2 # tuples of 8-bit RGB
-GAMMA_MAP = 3 # tuples of 24-bit red values
+INPUT_COLORMAP = 0 # tuples of 8-bit RGB
+CHROMA_KEY_MAP = 1 # tuples of 8-bit RGB
+COLOR_SPACE_MAP = 2 # tuples of 8-bit RGB
+GAMMA_MAP = 3 # tuples of 24-bit red values
# mode parameters for UseExclusive calls
INPUT = 0
@@ -24,9 +24,9 @@ OUTPUT = 1
IN_OUT = 2
# Format constants for the capture routines
-RGB8_FRAMES = 0 # noninterleaved 8 bit 3:2:3 RBG fields
-RGB32_FRAMES = 1 # 32-bit 8:8:8 RGB frames
-YUV411_FRAMES = 2 # interleaved, 8:2:2 YUV format
+RGB8_FRAMES = 0 # noninterleaved 8 bit 3:2:3 RBG fields
+RGB32_FRAMES = 1 # 32-bit 8:8:8 RGB frames
+YUV411_FRAMES = 2 # interleaved, 8:2:2 YUV format
YUV411_FRAMES_AND_BLANKING_BUFFER = 3
#
diff --git a/Lib/plat-irix5/cddb.py b/Lib/plat-irix5/cddb.py
index c4a95cdc43..7b2711f0b1 100755
--- a/Lib/plat-irix5/cddb.py
+++ b/Lib/plat-irix5/cddb.py
@@ -20,185 +20,185 @@ _cddbrc = '.cddb'
_DB_ID_NTRACKS = 5
_dbid_map = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@_=+abcdefghijklmnopqrstuvwxyz'
def _dbid(v):
- if v >= len(_dbid_map):
- return string.zfill(v, 2)
- else:
- return _dbid_map[v]
+ if v >= len(_dbid_map):
+ return string.zfill(v, 2)
+ else:
+ return _dbid_map[v]
def tochash(toc):
- if type(toc) == type(''):
- tracklist = []
- for i in range(2, len(toc), 4):
- tracklist.append((None,
- (int(toc[i:i+2]),
- int(toc[i+2:i+4]))))
- else:
- tracklist = toc
- ntracks = len(tracklist)
- hash = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF)
- if ntracks <= _DB_ID_NTRACKS:
- nidtracks = ntracks
- else:
- nidtracks = _DB_ID_NTRACKS - 1
- min = 0
- sec = 0
- for track in tracklist:
- start, length = track
- min = min + length[0]
- sec = sec + length[1]
- min = min + sec / 60
- sec = sec % 60
- hash = hash + _dbid(min) + _dbid(sec)
- for i in range(nidtracks):
- start, length = tracklist[i]
- hash = hash + _dbid(length[0]) + _dbid(length[1])
- return hash
-
+ if type(toc) == type(''):
+ tracklist = []
+ for i in range(2, len(toc), 4):
+ tracklist.append((None,
+ (int(toc[i:i+2]),
+ int(toc[i+2:i+4]))))
+ else:
+ tracklist = toc
+ ntracks = len(tracklist)
+ hash = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF)
+ if ntracks <= _DB_ID_NTRACKS:
+ nidtracks = ntracks
+ else:
+ nidtracks = _DB_ID_NTRACKS - 1
+ min = 0
+ sec = 0
+ for track in tracklist:
+ start, length = track
+ min = min + length[0]
+ sec = sec + length[1]
+ min = min + sec / 60
+ sec = sec % 60
+ hash = hash + _dbid(min) + _dbid(sec)
+ for i in range(nidtracks):
+ start, length = tracklist[i]
+ hash = hash + _dbid(length[0]) + _dbid(length[1])
+ return hash
+
class Cddb:
- def __init__(self, tracklist):
- if os.environ.has_key('CDDB_PATH'):
- path = os.environ['CDDB_PATH']
- cddb_path = path.split(',')
- else:
- home = os.environ['HOME']
- cddb_path = [home + '/' + _cddbrc]
+ def __init__(self, tracklist):
+ if os.environ.has_key('CDDB_PATH'):
+ path = os.environ['CDDB_PATH']
+ cddb_path = path.split(',')
+ else:
+ home = os.environ['HOME']
+ cddb_path = [home + '/' + _cddbrc]
- self._get_id(tracklist)
+ self._get_id(tracklist)
- for dir in cddb_path:
- file = dir + '/' + self.id + '.rdb'
- try:
- f = open(file, 'r')
- self.file = file
- break
- except IOError:
- pass
- ntracks = int(self.id[:2], 16)
- self.artist = ''
- self.title = ''
- self.track = [None] + [''] * ntracks
- self.trackartist = [None] + [''] * ntracks
- self.notes = []
- if not hasattr(self, 'file'):
- return
- import re
- reg = re.compile(r'^([^.]*)\.([^:]*):[\t ]+(.*)')
- while 1:
- line = f.readline()
- if not line:
- break
- match = reg.match(line)
- if not match:
- print 'syntax error in ' + file
- continue
- name1, name2, value = match.group(1, 2, 3)
- if name1 == 'album':
- if name2 == 'artist':
- self.artist = value
- elif name2 == 'title':
- self.title = value
- elif name2 == 'toc':
- if not self.toc:
- self.toc = value
- if self.toc != value:
- print 'toc\'s don\'t match'
- elif name2 == 'notes':
- self.notes.append(value)
- elif name1[:5] == 'track':
- try:
- trackno = int(name1[5:])
- except strings.atoi_error:
- print 'syntax error in ' + file
- continue
- if trackno > ntracks:
- print 'track number %r in file %r out of range' % (trackno, file)
- continue
- if name2 == 'title':
- self.track[trackno] = value
- elif name2 == 'artist':
- self.trackartist[trackno] = value
- f.close()
- for i in range(2, len(self.track)):
- track = self.track[i]
- # if track title starts with `,', use initial part
- # of previous track's title
- if track and track[0] == ',':
- try:
- off = self.track[i - 1].index(',')
- except ValueError:
- pass
- else:
- self.track[i] = self.track[i-1][:off] \
- + track
+ for dir in cddb_path:
+ file = dir + '/' + self.id + '.rdb'
+ try:
+ f = open(file, 'r')
+ self.file = file
+ break
+ except IOError:
+ pass
+ ntracks = int(self.id[:2], 16)
+ self.artist = ''
+ self.title = ''
+ self.track = [None] + [''] * ntracks
+ self.trackartist = [None] + [''] * ntracks
+ self.notes = []
+ if not hasattr(self, 'file'):
+ return
+ import re
+ reg = re.compile(r'^([^.]*)\.([^:]*):[\t ]+(.*)')
+ while 1:
+ line = f.readline()
+ if not line:
+ break
+ match = reg.match(line)
+ if not match:
+ print 'syntax error in ' + file
+ continue
+ name1, name2, value = match.group(1, 2, 3)
+ if name1 == 'album':
+ if name2 == 'artist':
+ self.artist = value
+ elif name2 == 'title':
+ self.title = value
+ elif name2 == 'toc':
+ if not self.toc:
+ self.toc = value
+ if self.toc != value:
+ print 'toc\'s don\'t match'
+ elif name2 == 'notes':
+ self.notes.append(value)
+ elif name1[:5] == 'track':
+ try:
+ trackno = int(name1[5:])
+ except strings.atoi_error:
+ print 'syntax error in ' + file
+ continue
+ if trackno > ntracks:
+ print 'track number %r in file %r out of range' % (trackno, file)
+ continue
+ if name2 == 'title':
+ self.track[trackno] = value
+ elif name2 == 'artist':
+ self.trackartist[trackno] = value
+ f.close()
+ for i in range(2, len(self.track)):
+ track = self.track[i]
+ # if track title starts with `,', use initial part
+ # of previous track's title
+ if track and track[0] == ',':
+ try:
+ off = self.track[i - 1].index(',')
+ except ValueError:
+ pass
+ else:
+ self.track[i] = self.track[i-1][:off] \
+ + track
- def _get_id(self, tracklist):
- # fill in self.id and self.toc.
- # if the argument is a string ending in .rdb, the part
- # upto the suffix is taken as the id.
- if type(tracklist) == type(''):
- if tracklist[-4:] == '.rdb':
- self.id = tracklist[:-4]
- self.toc = ''
- return
- t = []
- for i in range(2, len(tracklist), 4):
- t.append((None, \
- (int(tracklist[i:i+2]), \
- int(tracklist[i+2:i+4]))))
- tracklist = t
- ntracks = len(tracklist)
- self.id = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF)
- if ntracks <= _DB_ID_NTRACKS:
- nidtracks = ntracks
- else:
- nidtracks = _DB_ID_NTRACKS - 1
- min = 0
- sec = 0
- for track in tracklist:
- start, length = track
- min = min + length[0]
- sec = sec + length[1]
- min = min + sec / 60
- sec = sec % 60
- self.id = self.id + _dbid(min) + _dbid(sec)
- for i in range(nidtracks):
- start, length = tracklist[i]
- self.id = self.id + _dbid(length[0]) + _dbid(length[1])
- self.toc = string.zfill(ntracks, 2)
- for track in tracklist:
- start, length = track
- self.toc = self.toc + string.zfill(length[0], 2) + \
- string.zfill(length[1], 2)
+ def _get_id(self, tracklist):
+ # fill in self.id and self.toc.
+ # if the argument is a string ending in .rdb, the part
+ # upto the suffix is taken as the id.
+ if type(tracklist) == type(''):
+ if tracklist[-4:] == '.rdb':
+ self.id = tracklist[:-4]
+ self.toc = ''
+ return
+ t = []
+ for i in range(2, len(tracklist), 4):
+ t.append((None, \
+ (int(tracklist[i:i+2]), \
+ int(tracklist[i+2:i+4]))))
+ tracklist = t
+ ntracks = len(tracklist)
+ self.id = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF)
+ if ntracks <= _DB_ID_NTRACKS:
+ nidtracks = ntracks
+ else:
+ nidtracks = _DB_ID_NTRACKS - 1
+ min = 0
+ sec = 0
+ for track in tracklist:
+ start, length = track
+ min = min + length[0]
+ sec = sec + length[1]
+ min = min + sec / 60
+ sec = sec % 60
+ self.id = self.id + _dbid(min) + _dbid(sec)
+ for i in range(nidtracks):
+ start, length = tracklist[i]
+ self.id = self.id + _dbid(length[0]) + _dbid(length[1])
+ self.toc = string.zfill(ntracks, 2)
+ for track in tracklist:
+ start, length = track
+ self.toc = self.toc + string.zfill(length[0], 2) + \
+ string.zfill(length[1], 2)
- def write(self):
- import posixpath
- if os.environ.has_key('CDDB_WRITE_DIR'):
- dir = os.environ['CDDB_WRITE_DIR']
- else:
- dir = os.environ['HOME'] + '/' + _cddbrc
- file = dir + '/' + self.id + '.rdb'
- if posixpath.exists(file):
- # make backup copy
- posix.rename(file, file + '~')
- f = open(file, 'w')
- f.write('album.title:\t' + self.title + '\n')
- f.write('album.artist:\t' + self.artist + '\n')
- f.write('album.toc:\t' + self.toc + '\n')
- for note in self.notes:
- f.write('album.notes:\t' + note + '\n')
- prevpref = None
- for i in range(1, len(self.track)):
- if self.trackartist[i]:
- f.write('track%r.artist:\t%s\n' % (i, self.trackartist[i]))
- track = self.track[i]
- try:
- off = track.index(',')
- except ValuError:
- prevpref = None
- else:
- if prevpref and track[:off] == prevpref:
- track = track[off:]
- else:
- prevpref = track[:off]
- f.write('track%r.title:\t%s\n' % (i, track))
- f.close()
+ def write(self):
+ import posixpath
+ if os.environ.has_key('CDDB_WRITE_DIR'):
+ dir = os.environ['CDDB_WRITE_DIR']
+ else:
+ dir = os.environ['HOME'] + '/' + _cddbrc
+ file = dir + '/' + self.id + '.rdb'
+ if posixpath.exists(file):
+ # make backup copy
+ posix.rename(file, file + '~')
+ f = open(file, 'w')
+ f.write('album.title:\t' + self.title + '\n')
+ f.write('album.artist:\t' + self.artist + '\n')
+ f.write('album.toc:\t' + self.toc + '\n')
+ for note in self.notes:
+ f.write('album.notes:\t' + note + '\n')
+ prevpref = None
+ for i in range(1, len(self.track)):
+ if self.trackartist[i]:
+ f.write('track%r.artist:\t%s\n' % (i, self.trackartist[i]))
+ track = self.track[i]
+ try:
+ off = track.index(',')
+ except ValuError:
+ prevpref = None
+ else:
+ if prevpref and track[:off] == prevpref:
+ track = track[off:]
+ else:
+ prevpref = track[:off]
+ f.write('track%r.title:\t%s\n' % (i, track))
+ f.close()
diff --git a/Lib/plat-irix5/cdplayer.py b/Lib/plat-irix5/cdplayer.py
index 0dd3fe08a6..1c0168f7d2 100755
--- a/Lib/plat-irix5/cdplayer.py
+++ b/Lib/plat-irix5/cdplayer.py
@@ -17,72 +17,72 @@
cdplayerrc = '.cdplayerrc'
class Cdplayer:
- def __init__(self, tracklist):
- import string
- self.artist = ''
- self.title = ''
- if type(tracklist) == type(''):
- t = []
- for i in range(2, len(tracklist), 4):
- t.append((None, \
- (string.atoi(tracklist[i:i+2]), \
- string.atoi(tracklist[i+2:i+4]))))
- tracklist = t
- self.track = [None] + [''] * len(tracklist)
- self.id = 'd' + string.zfill(len(tracklist), 2)
- for track in tracklist:
- start, length = track
- self.id = self.id + string.zfill(length[0], 2) + \
- string.zfill(length[1], 2)
- try:
- import posix
- f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r')
- except IOError:
- return
- import re
- reg = re.compile(r'^([^:]*):\t(.*)')
- s = self.id + '.'
- l = len(s)
- while 1:
- line = f.readline()
- if line == '':
- break
- if line[:l] == s:
- line = line[l:]
- match = reg.match(line)
- if not match:
- print 'syntax error in ~/' + cdplayerrc
- continue
- name, value = match.group(1, 2)
- if name == 'title':
- self.title = value
- elif name == 'artist':
- self.artist = value
- elif name[:5] == 'track':
- trackno = string.atoi(name[6:])
- self.track[trackno] = value
- f.close()
+ def __init__(self, tracklist):
+ import string
+ self.artist = ''
+ self.title = ''
+ if type(tracklist) == type(''):
+ t = []
+ for i in range(2, len(tracklist), 4):
+ t.append((None, \
+ (string.atoi(tracklist[i:i+2]), \
+ string.atoi(tracklist[i+2:i+4]))))
+ tracklist = t
+ self.track = [None] + [''] * len(tracklist)
+ self.id = 'd' + string.zfill(len(tracklist), 2)
+ for track in tracklist:
+ start, length = track
+ self.id = self.id + string.zfill(length[0], 2) + \
+ string.zfill(length[1], 2)
+ try:
+ import posix
+ f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r')
+ except IOError:
+ return
+ import re
+ reg = re.compile(r'^([^:]*):\t(.*)')
+ s = self.id + '.'
+ l = len(s)
+ while 1:
+ line = f.readline()
+ if line == '':
+ break
+ if line[:l] == s:
+ line = line[l:]
+ match = reg.match(line)
+ if not match:
+ print 'syntax error in ~/' + cdplayerrc
+ continue
+ name, value = match.group(1, 2)
+ if name == 'title':
+ self.title = value
+ elif name == 'artist':
+ self.artist = value
+ elif name[:5] == 'track':
+ trackno = string.atoi(name[6:])
+ self.track[trackno] = value
+ f.close()
- def write(self):
- import posix
- filename = posix.environ['HOME'] + '/' + cdplayerrc
- try:
- old = open(filename, 'r')
- except IOError:
- old = open('/dev/null', 'r')
- new = open(filename + '.new', 'w')
- s = self.id + '.'
- l = len(s)
- while 1:
- line = old.readline()
- if line == '':
- break
- if line[:l] != s:
- new.write(line)
- new.write(self.id + '.title:\t' + self.title + '\n')
- new.write(self.id + '.artist:\t' + self.artist + '\n')
- for i in range(1, len(self.track)):
- new.write('%s.track.%r:\t%s\n' % (self.id, i, self.track[i]))
- old.close()
- new.close()
- posix.rename(filename + '.new', filename)
+ def write(self):
+ import posix
+ filename = posix.environ['HOME'] + '/' + cdplayerrc
+ try:
+ old = open(filename, 'r')
+ except IOError:
+ old = open('/dev/null', 'r')
+ new = open(filename + '.new', 'w')
+ s = self.id + '.'
+ l = len(s)
+ while 1:
+ line = old.readline()
+ if line == '':
+ break
+ if line[:l] != s:
+ new.write(line)
+ new.write(self.id + '.title:\t' + self.title + '\n')
+ new.write(self.id + '.artist:\t' + self.artist + '\n')
+ for i in range(1, len(self.track)):
+ new.write('%s.track.%r:\t%s\n' % (self.id, i, self.track[i]))
+ old.close()
+ new.close()
+ posix.rename(filename + '.new', filename)
diff --git a/Lib/plat-irix5/flp.py b/Lib/plat-irix5/flp.py
index b22bc1ae29..4f9175f5fd 100755
--- a/Lib/plat-irix5/flp.py
+++ b/Lib/plat-irix5/flp.py
@@ -80,18 +80,18 @@ def checkcache(filename):
fp.close()
def _unpack_cache(altforms):
- forms = {}
- for name in altforms.keys():
- altobj, altlist = altforms[name]
- obj = _newobj()
- obj.make(altobj)
- list = []
- for altobj in altlist:
- nobj = _newobj()
- nobj.make(altobj)
- list.append(nobj)
- forms[name] = obj, list
- return forms
+ forms = {}
+ for name in altforms.keys():
+ altobj, altlist = altforms[name]
+ obj = _newobj()
+ obj.make(altobj)
+ list = []
+ for altobj in altlist:
+ nobj = _newobj()
+ nobj.make(altobj)
+ list.append(nobj)
+ forms[name] = obj, list
+ return forms
def rdlong(fp):
s = fp.read(4)
@@ -277,8 +277,8 @@ def _parse_line(line):
return line
name, value = match.group(1, 2)
if name[0] == 'N':
- name = string.join(string.split(name),'')
- name = string.lower(name)
+ name = string.join(string.split(name),'')
+ name = string.lower(name)
name = string.capitalize(name)
try:
pf = _parse_func[name]
@@ -292,7 +292,7 @@ def _readline(file):
if not line:
raise EOFError
return line[:-1]
-
+
def _parse_1_line(file):
line = _readline(file)
while line == '':
diff --git a/Lib/plat-irix5/jpeg.py b/Lib/plat-irix5/jpeg.py
index da20d6bf02..f8fc7e7210 100755
--- a/Lib/plat-irix5/jpeg.py
+++ b/Lib/plat-irix5/jpeg.py
@@ -6,7 +6,7 @@
# XXX the resulting file causes weirdness.
class error(Exception):
- pass
+ pass
options = {'quality': 75, 'optimize': 0, 'smooth': 0, 'forcegray': 0}
@@ -14,98 +14,98 @@ comp = None
decomp = None
def compress(imgdata, width, height, bytesperpixel):
- global comp
- import cl
- if comp is None: comp = cl.OpenCompressor(cl.JPEG)
- if bytesperpixel == 1:
- format = cl.GRAYSCALE
- elif bytesperpixel == 4:
- format = cl.RGBX
- if options['forcegray']:
- iformat = cl.GRAYSCALE
- else:
- iformat = cl.YUV
- # XXX How to support 'optimize'?
- params = [cl.IMAGE_WIDTH, width, cl.IMAGE_HEIGHT, height, \
- cl.ORIGINAL_FORMAT, format, \
- cl.ORIENTATION, cl.BOTTOM_UP, \
- cl.QUALITY_FACTOR, options['quality'], \
- cl.INTERNAL_FORMAT, iformat, \
- ]
- comp.SetParams(params)
- jpegdata = comp.Compress(1, imgdata)
- return jpegdata
+ global comp
+ import cl
+ if comp is None: comp = cl.OpenCompressor(cl.JPEG)
+ if bytesperpixel == 1:
+ format = cl.GRAYSCALE
+ elif bytesperpixel == 4:
+ format = cl.RGBX
+ if options['forcegray']:
+ iformat = cl.GRAYSCALE
+ else:
+ iformat = cl.YUV
+ # XXX How to support 'optimize'?
+ params = [cl.IMAGE_WIDTH, width, cl.IMAGE_HEIGHT, height, \
+ cl.ORIGINAL_FORMAT, format, \
+ cl.ORIENTATION, cl.BOTTOM_UP, \
+ cl.QUALITY_FACTOR, options['quality'], \
+ cl.INTERNAL_FORMAT, iformat, \
+ ]
+ comp.SetParams(params)
+ jpegdata = comp.Compress(1, imgdata)
+ return jpegdata
def decompress(jpegdata):
- global decomp
- import cl
- if decomp is None: decomp = cl.OpenDecompressor(cl.JPEG)
- headersize = decomp.ReadHeader(jpegdata)
- params = [cl.IMAGE_WIDTH, 0, cl.IMAGE_HEIGHT, 0, cl.INTERNAL_FORMAT, 0]
- decomp.GetParams(params)
- width, height, format = params[1], params[3], params[5]
- if format == cl.GRAYSCALE or options['forcegray']:
- format = cl.GRAYSCALE
- bytesperpixel = 1
- else:
- format = cl.RGBX
- bytesperpixel = 4
- # XXX How to support 'smooth'?
- params = [cl.ORIGINAL_FORMAT, format, \
- cl.ORIENTATION, cl.BOTTOM_UP, \
- cl.FRAME_BUFFER_SIZE, width*height*bytesperpixel]
- decomp.SetParams(params)
- imgdata = decomp.Decompress(1, jpegdata)
- return imgdata, width, height, bytesperpixel
+ global decomp
+ import cl
+ if decomp is None: decomp = cl.OpenDecompressor(cl.JPEG)
+ headersize = decomp.ReadHeader(jpegdata)
+ params = [cl.IMAGE_WIDTH, 0, cl.IMAGE_HEIGHT, 0, cl.INTERNAL_FORMAT, 0]
+ decomp.GetParams(params)
+ width, height, format = params[1], params[3], params[5]
+ if format == cl.GRAYSCALE or options['forcegray']:
+ format = cl.GRAYSCALE
+ bytesperpixel = 1
+ else:
+ format = cl.RGBX
+ bytesperpixel = 4
+ # XXX How to support 'smooth'?
+ params = [cl.ORIGINAL_FORMAT, format, \
+ cl.ORIENTATION, cl.BOTTOM_UP, \
+ cl.FRAME_BUFFER_SIZE, width*height*bytesperpixel]
+ decomp.SetParams(params)
+ imgdata = decomp.Decompress(1, jpegdata)
+ return imgdata, width, height, bytesperpixel
def setoption(name, value):
- if type(value) is not type(0):
- raise TypeError, 'jpeg.setoption: numeric options only'
- if name == 'forcegrey':
- name = 'forcegray'
- if not options.has_key(name):
- raise KeyError, 'jpeg.setoption: unknown option name'
- options[name] = int(value)
+ if type(value) is not type(0):
+ raise TypeError, 'jpeg.setoption: numeric options only'
+ if name == 'forcegrey':
+ name = 'forcegray'
+ if not options.has_key(name):
+ raise KeyError, 'jpeg.setoption: unknown option name'
+ options[name] = int(value)
def test():
- import sys
- if sys.argv[1:2] == ['-g']:
- del sys.argv[1]
- setoption('forcegray', 1)
- if not sys.argv[1:]:
- sys.argv.append('/usr/local/images/data/jpg/asterix.jpg')
- for file in sys.argv[1:]:
- show(file)
+ import sys
+ if sys.argv[1:2] == ['-g']:
+ del sys.argv[1]
+ setoption('forcegray', 1)
+ if not sys.argv[1:]:
+ sys.argv.append('/usr/local/images/data/jpg/asterix.jpg')
+ for file in sys.argv[1:]:
+ show(file)
def show(file):
- import gl, GL, DEVICE
- jpegdata = open(file, 'r').read()
- imgdata, width, height, bytesperpixel = decompress(jpegdata)
- gl.foreground()
- gl.prefsize(width, height)
- win = gl.winopen(file)
- if bytesperpixel == 1:
- gl.cmode()
- gl.pixmode(GL.PM_SIZE, 8)
- gl.gconfig()
- for i in range(256):
- gl.mapcolor(i, i, i, i)
- else:
- gl.RGBmode()
- gl.pixmode(GL.PM_SIZE, 32)
- gl.gconfig()
- gl.qdevice(DEVICE.REDRAW)
- gl.qdevice(DEVICE.ESCKEY)
- gl.qdevice(DEVICE.WINQUIT)
- gl.qdevice(DEVICE.WINSHUT)
- gl.lrectwrite(0, 0, width-1, height-1, imgdata)
- while 1:
- dev, val = gl.qread()
- if dev in (DEVICE.ESCKEY, DEVICE.WINSHUT, DEVICE.WINQUIT):
- break
- if dev == DEVICE.REDRAW:
- gl.lrectwrite(0, 0, width-1, height-1, imgdata)
- gl.winclose(win)
- # Now test the compression and write the result to a fixed filename
- newjpegdata = compress(imgdata, width, height, bytesperpixel)
- open('/tmp/j.jpg', 'w').write(newjpegdata)
+ import gl, GL, DEVICE
+ jpegdata = open(file, 'r').read()
+ imgdata, width, height, bytesperpixel = decompress(jpegdata)
+ gl.foreground()
+ gl.prefsize(width, height)
+ win = gl.winopen(file)
+ if bytesperpixel == 1:
+ gl.cmode()
+ gl.pixmode(GL.PM_SIZE, 8)
+ gl.gconfig()
+ for i in range(256):
+ gl.mapcolor(i, i, i, i)
+ else:
+ gl.RGBmode()
+ gl.pixmode(GL.PM_SIZE, 32)
+ gl.gconfig()
+ gl.qdevice(DEVICE.REDRAW)
+ gl.qdevice(DEVICE.ESCKEY)
+ gl.qdevice(DEVICE.WINQUIT)
+ gl.qdevice(DEVICE.WINSHUT)
+ gl.lrectwrite(0, 0, width-1, height-1, imgdata)
+ while 1:
+ dev, val = gl.qread()
+ if dev in (DEVICE.ESCKEY, DEVICE.WINSHUT, DEVICE.WINQUIT):
+ break
+ if dev == DEVICE.REDRAW:
+ gl.lrectwrite(0, 0, width-1, height-1, imgdata)
+ gl.winclose(win)
+ # Now test the compression and write the result to a fixed filename
+ newjpegdata = compress(imgdata, width, height, bytesperpixel)
+ open('/tmp/j.jpg', 'w').write(newjpegdata)
diff --git a/Lib/plat-irix5/panel.py b/Lib/plat-irix5/panel.py
index 3aa7448653..12e62a51b4 100755
--- a/Lib/plat-irix5/panel.py
+++ b/Lib/plat-irix5/panel.py
@@ -17,82 +17,82 @@ debug = 0
# Test if an object is a list.
#
def is_list(x):
- return type(x) == type([])
+ return type(x) == type([])
# Reverse a list.
#
def reverse(list):
- res = []
- for item in list:
- res.insert(0, item)
- return res
+ res = []
+ for item in list:
+ res.insert(0, item)
+ return res
# Get an attribute of a list, which may itself be another list.
# Don't use 'prop' for name.
#
def getattrlist(list, name):
- for item in list:
- if item and is_list(item) and item[0] == name:
- return item[1:]
- return []
+ for item in list:
+ if item and is_list(item) and item[0] == name:
+ return item[1:]
+ return []
# Get a property of a list, which may itself be another list.
#
def getproplist(list, name):
- for item in list:
- if item and is_list(item) and item[0] == 'prop':
- if len(item) > 1 and item[1] == name:
- return item[2:]
- return []
+ for item in list:
+ if item and is_list(item) and item[0] == 'prop':
+ if len(item) > 1 and item[1] == name:
+ return item[2:]
+ return []
# Test if an actuator description contains the property 'end-of-group'
#
def is_endgroup(list):
- x = getproplist(list, 'end-of-group')
- return (x and x[0] == '#t')
+ x = getproplist(list, 'end-of-group')
+ return (x and x[0] == '#t')
# Neatly display an actuator definition given as S-expression
# the prefix string is printed before each line.
#
def show_actuator(prefix, a):
- for item in a:
- if not is_list(item):
- print prefix, item
- elif item and item[0] == 'al':
- print prefix, 'Subactuator list:'
- for a in item[1:]:
- show_actuator(prefix + ' ', a)
- elif len(item) == 2:
- print prefix, item[0], '=>', item[1]
- elif len(item) == 3 and item[0] == 'prop':
- print prefix, 'Prop', item[1], '=>',
- print item[2]
- else:
- print prefix, '?', item
+ for item in a:
+ if not is_list(item):
+ print prefix, item
+ elif item and item[0] == 'al':
+ print prefix, 'Subactuator list:'
+ for a in item[1:]:
+ show_actuator(prefix + ' ', a)
+ elif len(item) == 2:
+ print prefix, item[0], '=>', item[1]
+ elif len(item) == 3 and item[0] == 'prop':
+ print prefix, 'Prop', item[1], '=>',
+ print item[2]
+ else:
+ print prefix, '?', item
# Neatly display a panel.
#
def show_panel(prefix, p):
- for item in p:
- if not is_list(item):
- print prefix, item
- elif item and item[0] == 'al':
- print prefix, 'Actuator list:'
- for a in item[1:]:
- show_actuator(prefix + ' ', a)
- elif len(item) == 2:
- print prefix, item[0], '=>', item[1]
- elif len(item) == 3 and item[0] == 'prop':
- print prefix, 'Prop', item[1], '=>',
- print item[2]
- else:
- print prefix, '?', item
+ for item in p:
+ if not is_list(item):
+ print prefix, item
+ elif item and item[0] == 'al':
+ print prefix, 'Actuator list:'
+ for a in item[1:]:
+ show_actuator(prefix + ' ', a)
+ elif len(item) == 2:
+ print prefix, item[0], '=>', item[1]
+ elif len(item) == 3 and item[0] == 'prop':
+ print prefix, 'Prop', item[1], '=>',
+ print item[2]
+ else:
+ print prefix, '?', item
# Exception raised by build_actuator or build_panel.
@@ -103,7 +103,7 @@ panel_error = 'panel error'
# Dummy callback used to initialize the callbacks.
#
def dummy_callback(arg):
- pass
+ pass
# Assign attributes to members of the target.
@@ -111,60 +111,60 @@ def dummy_callback(arg):
# The member name is the attribute name prefixed with the prefix.
#
def assign_members(target, attrlist, exclist, prefix):
- for item in attrlist:
- if is_list(item) and len(item) == 2 and item[0] not in exclist:
- name, value = item[0], item[1]
- ok = 1
- if value[0] in '-0123456789':
- value = eval(value)
- elif value[0] == '"':
- value = value[1:-1]
- elif value == 'move-then-resize':
- # Strange default set by Panel Editor...
- ok = 0
- else:
- print 'unknown value', value, 'for', name
- ok = 0
- if ok:
- lhs = 'target.' + prefix + name
- stmt = lhs + '=' + repr(value)
- if debug: print 'exec', stmt
- try:
- exec stmt + '\n'
- except KeyboardInterrupt: # Don't catch this!
- raise KeyboardInterrupt
- except:
- print 'assign failed:', stmt
+ for item in attrlist:
+ if is_list(item) and len(item) == 2 and item[0] not in exclist:
+ name, value = item[0], item[1]
+ ok = 1
+ if value[0] in '-0123456789':
+ value = eval(value)
+ elif value[0] == '"':
+ value = value[1:-1]
+ elif value == 'move-then-resize':
+ # Strange default set by Panel Editor...
+ ok = 0
+ else:
+ print 'unknown value', value, 'for', name
+ ok = 0
+ if ok:
+ lhs = 'target.' + prefix + name
+ stmt = lhs + '=' + repr(value)
+ if debug: print 'exec', stmt
+ try:
+ exec stmt + '\n'
+ except KeyboardInterrupt: # Don't catch this!
+ raise KeyboardInterrupt
+ except:
+ print 'assign failed:', stmt
# Build a real actuator from an actuator description.
# Return a pair (actuator, name).
#
def build_actuator(descr):
- namelist = getattrlist(descr, 'name')
- if namelist:
- # Assume it is a string
- actuatorname = namelist[0][1:-1]
- else:
- actuatorname = ''
- type = descr[0]
- if type[:4] == 'pnl_': type = type[4:]
- act = pnl.mkact(type)
- act.downfunc = act.activefunc = act.upfunc = dummy_callback
- #
- assign_members(act, descr[1:], ['al', 'data', 'name'], '')
- #
- # Treat actuator-specific data
- #
- datalist = getattrlist(descr, 'data')
- prefix = ''
- if type[-4:] == 'puck':
- prefix = 'puck_'
- elif type == 'mouse':
- prefix = 'mouse_'
- assign_members(act, datalist, [], prefix)
- #
- return act, actuatorname
+ namelist = getattrlist(descr, 'name')
+ if namelist:
+ # Assume it is a string
+ actuatorname = namelist[0][1:-1]
+ else:
+ actuatorname = ''
+ type = descr[0]
+ if type[:4] == 'pnl_': type = type[4:]
+ act = pnl.mkact(type)
+ act.downfunc = act.activefunc = act.upfunc = dummy_callback
+ #
+ assign_members(act, descr[1:], ['al', 'data', 'name'], '')
+ #
+ # Treat actuator-specific data
+ #
+ datalist = getattrlist(descr, 'data')
+ prefix = ''
+ if type[-4:] == 'puck':
+ prefix = 'puck_'
+ elif type == 'mouse':
+ prefix = 'mouse_'
+ assign_members(act, datalist, [], prefix)
+ #
+ return act, actuatorname
# Build all sub-actuators and add them to the super-actuator.
@@ -176,27 +176,27 @@ def build_actuator(descr):
# to a sub-actuator.
#
def build_subactuators(panel, super_act, al):
- #
- # This is nearly the same loop as below in build_panel(),
- # except a call is made to addsubact() instead of addact().
- #
- for a in al:
- act, name = build_actuator(a)
- act.addsubact(super_act)
- if name:
- stmt = 'panel.' + name + ' = act'
- if debug: print 'exec', stmt
- exec stmt + '\n'
- if is_endgroup(a):
- panel.endgroup()
- sub_al = getattrlist(a, 'al')
- if sub_al:
- build_subactuators(panel, act, sub_al)
- #
- # Fix the actuator to which whe just added subactuators.
- # This can't hurt (I hope) and is needed for the scroll actuator.
- #
- super_act.fixact()
+ #
+ # This is nearly the same loop as below in build_panel(),
+ # except a call is made to addsubact() instead of addact().
+ #
+ for a in al:
+ act, name = build_actuator(a)
+ act.addsubact(super_act)
+ if name:
+ stmt = 'panel.' + name + ' = act'
+ if debug: print 'exec', stmt
+ exec stmt + '\n'
+ if is_endgroup(a):
+ panel.endgroup()
+ sub_al = getattrlist(a, 'al')
+ if sub_al:
+ build_subactuators(panel, act, sub_al)
+ #
+ # Fix the actuator to which whe just added subactuators.
+ # This can't hurt (I hope) and is needed for the scroll actuator.
+ #
+ super_act.fixact()
# Build a real panel from a panel definition.
@@ -204,78 +204,78 @@ def build_subactuators(panel, super_act, al):
# reference to a.
#
def build_panel(descr):
- #
- # Sanity check
- #
- if (not descr) or descr[0] != 'panel':
- raise panel_error, 'panel description must start with "panel"'
- #
- if debug: show_panel('', descr)
- #
- # Create an empty panel
- #
- panel = pnl.mkpanel()
- #
- # Assign panel attributes
- #
- assign_members(panel, descr[1:], ['al'], '')
- #
- # Look for actuator list
- #
- al = getattrlist(descr, 'al')
- #
- # The order in which actuators are created is important
- # because of the endgroup() operator.
- # Unfortunately the Panel Editor outputs the actuator list
- # in reverse order, so we reverse it here.
- #
- al = reverse(al)
- #
- for a in al:
- act, name = build_actuator(a)
- act.addact(panel)
- if name:
- stmt = 'panel.' + name + ' = act'
- exec stmt + '\n'
- if is_endgroup(a):
- panel.endgroup()
- sub_al = getattrlist(a, 'al')
- if sub_al:
- build_subactuators(panel, act, sub_al)
- #
- return panel
+ #
+ # Sanity check
+ #
+ if (not descr) or descr[0] != 'panel':
+ raise panel_error, 'panel description must start with "panel"'
+ #
+ if debug: show_panel('', descr)
+ #
+ # Create an empty panel
+ #
+ panel = pnl.mkpanel()
+ #
+ # Assign panel attributes
+ #
+ assign_members(panel, descr[1:], ['al'], '')
+ #
+ # Look for actuator list
+ #
+ al = getattrlist(descr, 'al')
+ #
+ # The order in which actuators are created is important
+ # because of the endgroup() operator.
+ # Unfortunately the Panel Editor outputs the actuator list
+ # in reverse order, so we reverse it here.
+ #
+ al = reverse(al)
+ #
+ for a in al:
+ act, name = build_actuator(a)
+ act.addact(panel)
+ if name:
+ stmt = 'panel.' + name + ' = act'
+ exec stmt + '\n'
+ if is_endgroup(a):
+ panel.endgroup()
+ sub_al = getattrlist(a, 'al')
+ if sub_al:
+ build_subactuators(panel, act, sub_al)
+ #
+ return panel
# Wrapper around pnl.dopanel() which calls call-back functions.
#
def my_dopanel():
- # Extract only the first 4 elements to allow for future expansion
- a, down, active, up = pnl.dopanel()[:4]
- if down:
- down.downfunc(down)
- if active:
- active.activefunc(active)
- if up:
- up.upfunc(up)
- return a
+ # Extract only the first 4 elements to allow for future expansion
+ a, down, active, up = pnl.dopanel()[:4]
+ if down:
+ down.downfunc(down)
+ if active:
+ active.activefunc(active)
+ if up:
+ up.upfunc(up)
+ return a
# Create one or more panels from a description file (S-expressions)
# generated by the Panel Editor.
-#
+#
def defpanellist(file):
- import panelparser
- descrlist = panelparser.parse_file(open(file, 'r'))
- panellist = []
- for descr in descrlist:
- panellist.append(build_panel(descr))
- return panellist
+ import panelparser
+ descrlist = panelparser.parse_file(open(file, 'r'))
+ panellist = []
+ for descr in descrlist:
+ panellist.append(build_panel(descr))
+ return panellist
# Import everything from built-in method pnl, so the user can always
# use panel.foo() instead of pnl.foo().
# This gives *no* performance penalty once this module is imported.
#
-from pnl import * # for export
+from pnl import * # for export
-dopanel = my_dopanel # override pnl.dopanel
+dopanel = my_dopanel # override pnl.dopanel
diff --git a/Lib/plat-irix5/panelparser.py b/Lib/plat-irix5/panelparser.py
index ee50971683..c831c49272 100755
--- a/Lib/plat-irix5/panelparser.py
+++ b/Lib/plat-irix5/panelparser.py
@@ -15,47 +15,47 @@ separators = operators + whitespace + ';' + '"'
# Return a list of tokens (strings).
#
def tokenize_string(s):
- tokens = []
- while s:
- c = s[:1]
- if c in whitespace:
- s = s[1:]
- elif c == ';':
- s = ''
- elif c == '"':
- n = len(s)
- i = 1
- while i < n:
- c = s[i]
- i = i+1
- if c == '"': break
- if c == '\\': i = i+1
- tokens.append(s[:i])
- s = s[i:]
- elif c in operators:
- tokens.append(c)
- s = s[1:]
- else:
- n = len(s)
- i = 1
- while i < n:
- if s[i] in separators: break
- i = i+1
- tokens.append(s[:i])
- s = s[i:]
- return tokens
+ tokens = []
+ while s:
+ c = s[:1]
+ if c in whitespace:
+ s = s[1:]
+ elif c == ';':
+ s = ''
+ elif c == '"':
+ n = len(s)
+ i = 1
+ while i < n:
+ c = s[i]
+ i = i+1
+ if c == '"': break
+ if c == '\\': i = i+1
+ tokens.append(s[:i])
+ s = s[i:]
+ elif c in operators:
+ tokens.append(c)
+ s = s[1:]
+ else:
+ n = len(s)
+ i = 1
+ while i < n:
+ if s[i] in separators: break
+ i = i+1
+ tokens.append(s[:i])
+ s = s[i:]
+ return tokens
# Tokenize a whole file (given as file object, not as file name).
# Return a list of tokens (strings).
#
def tokenize_file(fp):
- tokens = []
- while 1:
- line = fp.readline()
- if not line: break
- tokens = tokens + tokenize_string(line)
- return tokens
+ tokens = []
+ while 1:
+ line = fp.readline()
+ if not line: break
+ tokens = tokens + tokenize_string(line)
+ return tokens
# Exception raised by parse_exr.
@@ -71,50 +71,50 @@ syntax_error = 'syntax error'
# May raise syntax_error.
#
def parse_expr(tokens):
- if (not tokens) or tokens[0] != '(':
- raise syntax_error, 'expected "("'
- tokens = tokens[1:]
- expr = []
- while 1:
- if not tokens:
- raise syntax_error, 'missing ")"'
- if tokens[0] == ')':
- return expr, tokens[1:]
- elif tokens[0] == '(':
- subexpr, tokens = parse_expr(tokens)
- expr.append(subexpr)
- else:
- expr.append(tokens[0])
- tokens = tokens[1:]
+ if (not tokens) or tokens[0] != '(':
+ raise syntax_error, 'expected "("'
+ tokens = tokens[1:]
+ expr = []
+ while 1:
+ if not tokens:
+ raise syntax_error, 'missing ")"'
+ if tokens[0] == ')':
+ return expr, tokens[1:]
+ elif tokens[0] == '(':
+ subexpr, tokens = parse_expr(tokens)
+ expr.append(subexpr)
+ else:
+ expr.append(tokens[0])
+ tokens = tokens[1:]
# Parse a file (given as file object, not as file name).
# Return a list of parsed S-expressions found at the top level.
#
def parse_file(fp):
- tokens = tokenize_file(fp)
- exprlist = []
- while tokens:
- expr, tokens = parse_expr(tokens)
- exprlist.append(expr)
- return exprlist
+ tokens = tokenize_file(fp)
+ exprlist = []
+ while tokens:
+ expr, tokens = parse_expr(tokens)
+ exprlist.append(expr)
+ return exprlist
# EXAMPLE:
#
# The input
-# '(hip (hop hur-ray))'
+# '(hip (hop hur-ray))'
#
# passed to tokenize_string() returns the token list
-# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')']
+# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')']
#
# When this is passed to parse_expr() it returns the expression
-# ['hip', ['hop', 'hur-ray']]
+# ['hip', ['hop', 'hur-ray']]
# plus an empty token list (because there are no tokens left.
#
# When a file containing the example is passed to parse_file() it returns
# a list whose only element is the output of parse_expr() above:
-# [['hip', ['hop', 'hur-ray']]]
+# [['hip', ['hop', 'hur-ray']]]
# TOKENIZING:
@@ -123,6 +123,6 @@ def parse_file(fp):
#
# Tokens are separated by whitespace, except the following characters
# always form a separate token (outside strings):
-# ( ) '
+# ( ) '
# Strings are enclosed in double quotes (") and backslash (\) is used
# as escape character in strings.
diff --git a/Lib/plat-irix5/readcd.py b/Lib/plat-irix5/readcd.py
index f278ba4bf0..5453ce4213 100755
--- a/Lib/plat-irix5/readcd.py
+++ b/Lib/plat-irix5/readcd.py
@@ -3,242 +3,242 @@
import cd, CD
class Error(Exception):
- pass
+ pass
class _Stop(Exception):
- pass
+ pass
def _doatime(self, cb_type, data):
- if ((data[0] * 60) + data[1]) * 75 + data[2] > self.end:
-## print 'done with list entry', repr(self.listindex)
- raise _Stop
- func, arg = self.callbacks[cb_type]
- if func:
- func(arg, cb_type, data)
+ if ((data[0] * 60) + data[1]) * 75 + data[2] > self.end:
+## print 'done with list entry', repr(self.listindex)
+ raise _Stop
+ func, arg = self.callbacks[cb_type]
+ if func:
+ func(arg, cb_type, data)
def _dopnum(self, cb_type, data):
- if data > self.end:
-## print 'done with list entry', repr(self.listindex)
- raise _Stop
- func, arg = self.callbacks[cb_type]
- if func:
- func(arg, cb_type, data)
+ if data > self.end:
+## print 'done with list entry', repr(self.listindex)
+ raise _Stop
+ func, arg = self.callbacks[cb_type]
+ if func:
+ func(arg, cb_type, data)
class Readcd:
- def __init__(self, *arg):
- if len(arg) == 0:
- self.player = cd.open()
- elif len(arg) == 1:
- self.player = cd.open(arg[0])
- elif len(arg) == 2:
- self.player = cd.open(arg[0], arg[1])
- else:
- raise Error, 'bad __init__ call'
- self.list = []
- self.callbacks = [(None, None)] * 8
- self.parser = cd.createparser()
- self.playing = 0
- self.end = 0
- self.status = None
- self.trackinfo = None
-
- def eject(self):
- self.player.eject()
- self.list = []
- self.end = 0
- self.listindex = 0
- self.status = None
- self.trackinfo = None
- if self.playing:
-## print 'stop playing from eject'
- raise _Stop
-
- def pmsf2msf(self, track, min, sec, frame):
- if not self.status:
- self.cachestatus()
- if track < self.status[5] or track > self.status[6]:
- raise Error, 'track number out of range'
- if not self.trackinfo:
- self.cacheinfo()
- start, total = self.trackinfo[track]
- start = ((start[0] * 60) + start[1]) * 75 + start[2]
- total = ((total[0] * 60) + total[1]) * 75 + total[2]
- block = ((min * 60) + sec) * 75 + frame
- if block > total:
- raise Error, 'out of range'
- block = start + block
- min, block = divmod(block, 75*60)
- sec, frame = divmod(block, 75)
- return min, sec, frame
-
- def reset(self):
- self.list = []
-
- def appendtrack(self, track):
- self.appendstretch(track, track)
-
- def appendstretch(self, start, end):
- if not self.status:
- self.cachestatus()
- if not start:
- start = 1
- if not end:
- end = self.status[6]
- if type(end) == type(0):
- if end < self.status[5] or end > self.status[6]:
- raise Error, 'range error'
- else:
- l = len(end)
- if l == 4:
- prog, min, sec, frame = end
- if prog < self.status[5] or prog > self.status[6]:
- raise Error, 'range error'
- end = self.pmsf2msf(prog, min, sec, frame)
- elif l != 3:
- raise Error, 'syntax error'
- if type(start) == type(0):
- if start < self.status[5] or start > self.status[6]:
- raise Error, 'range error'
- if len(self.list) > 0:
- s, e = self.list[-1]
- if type(e) == type(0):
- if start == e+1:
- start = s
- del self.list[-1]
- else:
- l = len(start)
- if l == 4:
- prog, min, sec, frame = start
- if prog < self.status[5] or prog > self.status[6]:
- raise Error, 'range error'
- start = self.pmsf2msf(prog, min, sec, frame)
- elif l != 3:
- raise Error, 'syntax error'
- self.list.append((start, end))
-
- def settracks(self, list):
- self.list = []
- for track in list:
- self.appendtrack(track)
-
- def setcallback(self, cb_type, func, arg):
- if cb_type < 0 or cb_type >= 8:
- raise Error, 'type out of range'
- self.callbacks[cb_type] = (func, arg)
- if self.playing:
- start, end = self.list[self.listindex]
- if type(end) == type(0):
- if cb_type != CD.PNUM:
- self.parser.setcallback(cb_type, func, arg)
- else:
- if cb_type != CD.ATIME:
- self.parser.setcallback(cb_type, func, arg)
-
- def removecallback(self, cb_type):
- if cb_type < 0 or cb_type >= 8:
- raise Error, 'type out of range'
- self.callbacks[cb_type] = (None, None)
- if self.playing:
- start, end = self.list[self.listindex]
- if type(end) == type(0):
- if cb_type != CD.PNUM:
- self.parser.removecallback(cb_type)
- else:
- if cb_type != CD.ATIME:
- self.parser.removecallback(cb_type)
-
- def gettrackinfo(self, *arg):
- if not self.status:
- self.cachestatus()
- if not self.trackinfo:
- self.cacheinfo()
- if len(arg) == 0:
- return self.trackinfo[self.status[5]:self.status[6]+1]
- result = []
- for i in arg:
- if i < self.status[5] or i > self.status[6]:
- raise Error, 'range error'
- result.append(self.trackinfo[i])
- return result
-
- def cacheinfo(self):
- if not self.status:
- self.cachestatus()
- self.trackinfo = []
- for i in range(self.status[5]):
- self.trackinfo.append(None)
- for i in range(self.status[5], self.status[6]+1):
- self.trackinfo.append(self.player.gettrackinfo(i))
-
- def cachestatus(self):
- self.status = self.player.getstatus()
- if self.status[0] == CD.NODISC:
- self.status = None
- raise Error, 'no disc in player'
-
- def getstatus(self):
- return self.player.getstatus()
-
- def play(self):
- if not self.status:
- self.cachestatus()
- size = self.player.bestreadsize()
- self.listindex = 0
- self.playing = 0
- for i in range(8):
- func, arg = self.callbacks[i]
- if func:
- self.parser.setcallback(i, func, arg)
- else:
- self.parser.removecallback(i)
- if len(self.list) == 0:
- for i in range(self.status[5], self.status[6]+1):
- self.appendtrack(i)
- try:
- while 1:
- if not self.playing:
- if self.listindex >= len(self.list):
- return
- start, end = self.list[self.listindex]
- if type(start) == type(0):
- dummy = self.player.seektrack(
- start)
- else:
- min, sec, frame = start
- dummy = self.player.seek(
- min, sec, frame)
- if type(end) == type(0):
- self.parser.setcallback(
- CD.PNUM, _dopnum, self)
- self.end = end
- func, arg = \
- self.callbacks[CD.ATIME]
- if func:
- self.parser.setcallback(CD.ATIME, func, arg)
- else:
- self.parser.removecallback(CD.ATIME)
- else:
- min, sec, frame = end
- self.parser.setcallback(
- CD.ATIME, _doatime,
- self)
- self.end = (min * 60 + sec) * \
- 75 + frame
- func, arg = \
- self.callbacks[CD.PNUM]
- if func:
- self.parser.setcallback(CD.PNUM, func, arg)
- else:
- self.parser.removecallback(CD.PNUM)
- self.playing = 1
- data = self.player.readda(size)
- if data == '':
- self.playing = 0
- self.listindex = self.listindex + 1
- continue
- try:
- self.parser.parseframe(data)
- except _Stop:
- self.playing = 0
- self.listindex = self.listindex + 1
- finally:
- self.playing = 0
+ def __init__(self, *arg):
+ if len(arg) == 0:
+ self.player = cd.open()
+ elif len(arg) == 1:
+ self.player = cd.open(arg[0])
+ elif len(arg) == 2:
+ self.player = cd.open(arg[0], arg[1])
+ else:
+ raise Error, 'bad __init__ call'
+ self.list = []
+ self.callbacks = [(None, None)] * 8
+ self.parser = cd.createparser()
+ self.playing = 0
+ self.end = 0
+ self.status = None
+ self.trackinfo = None
+
+ def eject(self):
+ self.player.eject()
+ self.list = []
+ self.end = 0
+ self.listindex = 0
+ self.status = None
+ self.trackinfo = None
+ if self.playing:
+## print 'stop playing from eject'
+ raise _Stop
+
+ def pmsf2msf(self, track, min, sec, frame):
+ if not self.status:
+ self.cachestatus()
+ if track < self.status[5] or track > self.status[6]:
+ raise Error, 'track number out of range'
+ if not self.trackinfo:
+ self.cacheinfo()
+ start, total = self.trackinfo[track]
+ start = ((start[0] * 60) + start[1]) * 75 + start[2]
+ total = ((total[0] * 60) + total[1]) * 75 + total[2]
+ block = ((min * 60) + sec) * 75 + frame
+ if block > total:
+ raise Error, 'out of range'
+ block = start + block
+ min, block = divmod(block, 75*60)
+ sec, frame = divmod(block, 75)
+ return min, sec, frame
+
+ def reset(self):
+ self.list = []
+
+ def appendtrack(self, track):
+ self.appendstretch(track, track)
+
+ def appendstretch(self, start, end):
+ if not self.status:
+ self.cachestatus()
+ if not start:
+ start = 1
+ if not end:
+ end = self.status[6]
+ if type(end) == type(0):
+ if end < self.status[5] or end > self.status[6]:
+ raise Error, 'range error'
+ else:
+ l = len(end)
+ if l == 4:
+ prog, min, sec, frame = end
+ if prog < self.status[5] or prog > self.status[6]:
+ raise Error, 'range error'
+ end = self.pmsf2msf(prog, min, sec, frame)
+ elif l != 3:
+ raise Error, 'syntax error'
+ if type(start) == type(0):
+ if start < self.status[5] or start > self.status[6]:
+ raise Error, 'range error'
+ if len(self.list) > 0:
+ s, e = self.list[-1]
+ if type(e) == type(0):
+ if start == e+1:
+ start = s
+ del self.list[-1]
+ else:
+ l = len(start)
+ if l == 4:
+ prog, min, sec, frame = start
+ if prog < self.status[5] or prog > self.status[6]:
+ raise Error, 'range error'
+ start = self.pmsf2msf(prog, min, sec, frame)
+ elif l != 3:
+ raise Error, 'syntax error'
+ self.list.append((start, end))
+
+ def settracks(self, list):
+ self.list = []
+ for track in list:
+ self.appendtrack(track)
+
+ def setcallback(self, cb_type, func, arg):
+ if cb_type < 0 or cb_type >= 8:
+ raise Error, 'type out of range'
+ self.callbacks[cb_type] = (func, arg)
+ if self.playing:
+ start, end = self.list[self.listindex]
+ if type(end) == type(0):
+ if cb_type != CD.PNUM:
+ self.parser.setcallback(cb_type, func, arg)
+ else:
+ if cb_type != CD.ATIME:
+ self.parser.setcallback(cb_type, func, arg)
+
+ def removecallback(self, cb_type):
+ if cb_type < 0 or cb_type >= 8:
+ raise Error, 'type out of range'
+ self.callbacks[cb_type] = (None, None)
+ if self.playing:
+ start, end = self.list[self.listindex]
+ if type(end) == type(0):
+ if cb_type != CD.PNUM:
+ self.parser.removecallback(cb_type)
+ else:
+ if cb_type != CD.ATIME:
+ self.parser.removecallback(cb_type)
+
+ def gettrackinfo(self, *arg):
+ if not self.status:
+ self.cachestatus()
+ if not self.trackinfo:
+ self.cacheinfo()
+ if len(arg) == 0:
+ return self.trackinfo[self.status[5]:self.status[6]+1]
+ result = []
+ for i in arg:
+ if i < self.status[5] or i > self.status[6]:
+ raise Error, 'range error'
+ result.append(self.trackinfo[i])
+ return result
+
+ def cacheinfo(self):
+ if not self.status:
+ self.cachestatus()
+ self.trackinfo = []
+ for i in range(self.status[5]):
+ self.trackinfo.append(None)
+ for i in range(self.status[5], self.status[6]+1):
+ self.trackinfo.append(self.player.gettrackinfo(i))
+
+ def cachestatus(self):
+ self.status = self.player.getstatus()
+ if self.status[0] == CD.NODISC:
+ self.status = None
+ raise Error, 'no disc in player'
+
+ def getstatus(self):
+ return self.player.getstatus()
+
+ def play(self):
+ if not self.status:
+ self.cachestatus()
+ size = self.player.bestreadsize()
+ self.listindex = 0
+ self.playing = 0
+ for i in range(8):
+ func, arg = self.callbacks[i]
+ if func:
+ self.parser.setcallback(i, func, arg)
+ else:
+ self.parser.removecallback(i)
+ if len(self.list) == 0:
+ for i in range(self.status[5], self.status[6]+1):
+ self.appendtrack(i)
+ try:
+ while 1:
+ if not self.playing:
+ if self.listindex >= len(self.list):
+ return
+ start, end = self.list[self.listindex]
+ if type(start) == type(0):
+ dummy = self.player.seektrack(
+ start)
+ else:
+ min, sec, frame = start
+ dummy = self.player.seek(
+ min, sec, frame)
+ if type(end) == type(0):
+ self.parser.setcallback(
+ CD.PNUM, _dopnum, self)
+ self.end = end
+ func, arg = \
+ self.callbacks[CD.ATIME]
+ if func:
+ self.parser.setcallback(CD.ATIME, func, arg)
+ else:
+ self.parser.removecallback(CD.ATIME)
+ else:
+ min, sec, frame = end
+ self.parser.setcallback(
+ CD.ATIME, _doatime,
+ self)
+ self.end = (min * 60 + sec) * \
+ 75 + frame
+ func, arg = \
+ self.callbacks[CD.PNUM]
+ if func:
+ self.parser.setcallback(CD.PNUM, func, arg)
+ else:
+ self.parser.removecallback(CD.PNUM)
+ self.playing = 1
+ data = self.player.readda(size)
+ if data == '':
+ self.playing = 0
+ self.listindex = self.listindex + 1
+ continue
+ try:
+ self.parser.parseframe(data)
+ except _Stop:
+ self.playing = 0
+ self.listindex = self.listindex + 1
+ finally:
+ self.playing = 0
diff --git a/Lib/plat-irix5/torgb.py b/Lib/plat-irix5/torgb.py
index c2b1740f20..54c86c477d 100755
--- a/Lib/plat-irix5/torgb.py
+++ b/Lib/plat-irix5/torgb.py
@@ -51,49 +51,49 @@ uncompress.append('uncompress', '--')
class error(Exception):
- pass
+ pass
def torgb(filename):
- temps = []
- ret = None
- try:
- ret = _torgb(filename, temps)
- finally:
- for temp in temps[:]:
- if temp != ret:
- try:
- os.unlink(temp)
- except os.error:
- pass
- temps.remove(temp)
- return ret
+ temps = []
+ ret = None
+ try:
+ ret = _torgb(filename, temps)
+ finally:
+ for temp in temps[:]:
+ if temp != ret:
+ try:
+ os.unlink(temp)
+ except os.error:
+ pass
+ temps.remove(temp)
+ return ret
def _torgb(filename, temps):
- if filename[-2:] == '.Z':
- (fd, fname) = tempfile.mkstemp()
- os.close(fd)
- temps.append(fname)
- sts = uncompress.copy(filename, fname)
- if sts:
- raise error, filename + ': uncompress failed'
- else:
- fname = filename
- try:
- ftype = imghdr.what(fname)
- except IOError, msg:
- if type(msg) == type(()) and len(msg) == 2 and \
- type(msg[0]) == type(0) and type(msg[1]) == type(''):
- msg = msg[1]
- if type(msg) is not type(''):
- msg = repr(msg)
- raise error, filename + ': ' + msg
- if ftype == 'rgb':
- return fname
- if ftype is None or not table.has_key(ftype):
- raise error, '%s: unsupported image file type %r' % (filename, ftype)
- (fd, temp) = tempfile.mkstemp()
- os.close(fd)
- sts = table[ftype].copy(fname, temp)
- if sts:
- raise error, filename + ': conversion to rgb failed'
- return temp
+ if filename[-2:] == '.Z':
+ (fd, fname) = tempfile.mkstemp()
+ os.close(fd)
+ temps.append(fname)
+ sts = uncompress.copy(filename, fname)
+ if sts:
+ raise error, filename + ': uncompress failed'
+ else:
+ fname = filename
+ try:
+ ftype = imghdr.what(fname)
+ except IOError, msg:
+ if type(msg) == type(()) and len(msg) == 2 and \
+ type(msg[0]) == type(0) and type(msg[1]) == type(''):
+ msg = msg[1]
+ if type(msg) is not type(''):
+ msg = repr(msg)
+ raise error, filename + ': ' + msg
+ if ftype == 'rgb':
+ return fname
+ if ftype is None or not table.has_key(ftype):
+ raise error, '%s: unsupported image file type %r' % (filename, ftype)
+ (fd, temp) = tempfile.mkstemp()
+ os.close(fd)
+ sts = table[ftype].copy(fname, temp)
+ if sts:
+ raise error, filename + ': conversion to rgb failed'
+ return temp
diff --git a/Lib/plat-irix6/AL.py b/Lib/plat-irix6/AL.py
index ed17cde2ef..ec941a2bac 100644
--- a/Lib/plat-irix6/AL.py
+++ b/Lib/plat-irix6/AL.py
@@ -1,61 +1,61 @@
-RATE_48000 = 48000
-RATE_44100 = 44100
-RATE_32000 = 32000
-RATE_22050 = 22050
-RATE_16000 = 16000
-RATE_11025 = 11025
-RATE_8000 = 8000
+RATE_48000 = 48000
+RATE_44100 = 44100
+RATE_32000 = 32000
+RATE_22050 = 22050
+RATE_16000 = 16000
+RATE_11025 = 11025
+RATE_8000 = 8000
SAMPFMT_TWOSCOMP= 1
-SAMPFMT_FLOAT = 32
-SAMPFMT_DOUBLE = 64
+SAMPFMT_FLOAT = 32
+SAMPFMT_DOUBLE = 64
-SAMPLE_8 = 1
-SAMPLE_16 = 2
- # SAMPLE_24 is the low 24 bits of a long, sign extended to 32 bits
-SAMPLE_24 = 4
+SAMPLE_8 = 1
+SAMPLE_16 = 2
+ # SAMPLE_24 is the low 24 bits of a long, sign extended to 32 bits
+SAMPLE_24 = 4
-MONO = 1
-STEREO = 2
-QUADRO = 4 # 4CHANNEL is not a legal Python name
+MONO = 1
+STEREO = 2
+QUADRO = 4 # 4CHANNEL is not a legal Python name
-INPUT_LINE = 0
-INPUT_MIC = 1
-INPUT_DIGITAL = 2
+INPUT_LINE = 0
+INPUT_MIC = 1
+INPUT_DIGITAL = 2
-MONITOR_OFF = 0
-MONITOR_ON = 1
+MONITOR_OFF = 0
+MONITOR_ON = 1
-ERROR_NUMBER = 0
-ERROR_TYPE = 1
-ERROR_LOCATION_LSP = 2
-ERROR_LOCATION_MSP = 3
-ERROR_LENGTH = 4
+ERROR_NUMBER = 0
+ERROR_TYPE = 1
+ERROR_LOCATION_LSP = 2
+ERROR_LOCATION_MSP = 3
+ERROR_LENGTH = 4
-ERROR_INPUT_UNDERFLOW = 0
-ERROR_OUTPUT_OVERFLOW = 1
+ERROR_INPUT_UNDERFLOW = 0
+ERROR_OUTPUT_OVERFLOW = 1
# These seem to be not supported anymore:
-##HOLD, RELEASE = 0, 1
-##ATTAIL, ATHEAD, ATMARK, ATTIME = 0, 1, 2, 3
-
-DEFAULT_DEVICE = 1
-
-INPUT_SOURCE = 0
-LEFT_INPUT_ATTEN = 1
-RIGHT_INPUT_ATTEN = 2
-INPUT_RATE = 3
-OUTPUT_RATE = 4
-LEFT_SPEAKER_GAIN = 5
-RIGHT_SPEAKER_GAIN = 6
-INPUT_COUNT = 7
-OUTPUT_COUNT = 8
-UNUSED_COUNT = 9
-SYNC_INPUT_TO_AES = 10
-SYNC_OUTPUT_TO_AES = 11
-MONITOR_CTL = 12
-LEFT_MONITOR_ATTEN = 13
-RIGHT_MONITOR_ATTEN = 14
-
-ENUM_VALUE = 0 # only certain values are valid
-RANGE_VALUE = 1 # any value in range is valid
+##HOLD, RELEASE = 0, 1
+##ATTAIL, ATHEAD, ATMARK, ATTIME = 0, 1, 2, 3
+
+DEFAULT_DEVICE = 1
+
+INPUT_SOURCE = 0
+LEFT_INPUT_ATTEN = 1
+RIGHT_INPUT_ATTEN = 2
+INPUT_RATE = 3
+OUTPUT_RATE = 4
+LEFT_SPEAKER_GAIN = 5
+RIGHT_SPEAKER_GAIN = 6
+INPUT_COUNT = 7
+OUTPUT_COUNT = 8
+UNUSED_COUNT = 9
+SYNC_INPUT_TO_AES = 10
+SYNC_OUTPUT_TO_AES = 11
+MONITOR_CTL = 12
+LEFT_MONITOR_ATTEN = 13
+RIGHT_MONITOR_ATTEN = 14
+
+ENUM_VALUE = 0 # only certain values are valid
+RANGE_VALUE = 1 # any value in range is valid
diff --git a/Lib/plat-irix6/CD.py b/Lib/plat-irix6/CD.py
index ad56561235..8c1e03bc6e 100644
--- a/Lib/plat-irix6/CD.py
+++ b/Lib/plat-irix6/CD.py
@@ -1,34 +1,34 @@
-ERROR = 0
-NODISC = 1
-READY = 2
-PLAYING = 3
-PAUSED = 4
-STILL = 5
+ERROR = 0
+NODISC = 1
+READY = 2
+PLAYING = 3
+PAUSED = 4
+STILL = 5
-AUDIO = 0
-PNUM = 1
-INDEX = 2
-PTIME = 3
-ATIME = 4
-CATALOG = 5
-IDENT = 6
-CONTROL = 7
+AUDIO = 0
+PNUM = 1
+INDEX = 2
+PTIME = 3
+ATIME = 4
+CATALOG = 5
+IDENT = 6
+CONTROL = 7
-CDDA_DATASIZE = 2352
+CDDA_DATASIZE = 2352
-##CDDA_SUBCODESIZE = (sizeof(struct subcodeQ))
-##CDDA_BLOCKSIZE = (sizeof(struct cdframe))
-##CDDA_NUMSAMPLES = (CDDA_DATASIZE/2)
+##CDDA_SUBCODESIZE = (sizeof(struct subcodeQ))
+##CDDA_BLOCKSIZE = (sizeof(struct cdframe))
+##CDDA_NUMSAMPLES = (CDDA_DATASIZE/2)
##
-##CDQ_PREEMP_MASK = 0xd
-##CDQ_COPY_MASK = 0xb
-##CDQ_DDATA_MASK = 0xd
-##CDQ_BROADCAST_MASK = 0x8
-##CDQ_PREEMPHASIS = 0x1
-##CDQ_COPY_PERMITTED = 0x2
-##CDQ_DIGITAL_DATA = 0x4
-##CDQ_BROADCAST_USE = 0x8
+##CDQ_PREEMP_MASK = 0xd
+##CDQ_COPY_MASK = 0xb
+##CDQ_DDATA_MASK = 0xd
+##CDQ_BROADCAST_MASK = 0x8
+##CDQ_PREEMPHASIS = 0x1
+##CDQ_COPY_PERMITTED = 0x2
+##CDQ_DIGITAL_DATA = 0x4
+##CDQ_BROADCAST_USE = 0x8
##
-##CDQ_MODE1 = 0x1
-##CDQ_MODE2 = 0x2
-##CDQ_MODE3 = 0x3
+##CDQ_MODE1 = 0x1
+##CDQ_MODE2 = 0x2
+##CDQ_MODE3 = 0x3
diff --git a/Lib/plat-irix6/CL.py b/Lib/plat-irix6/CL.py
index 468ecaaa68..23259c5548 100644
--- a/Lib/plat-irix6/CL.py
+++ b/Lib/plat-irix6/CL.py
@@ -1,24 +1,24 @@
# Backward compatible module CL.
# All relevant symbols are now defined in the module cl.
try:
- from cl import *
+ from cl import *
except ImportError:
- from CL_old import *
+ from CL_old import *
else:
- del CompressImage
- del DecompressImage
- del GetAlgorithmName
- del OpenCompressor
- del OpenDecompressor
- del QueryAlgorithms
- del QueryMaxHeaderSize
- del QueryScheme
- del QuerySchemeFromName
- del SetDefault
- del SetMax
- del SetMin
- try:
- del cvt_type
- except NameError:
- pass
- del error
+ del CompressImage
+ del DecompressImage
+ del GetAlgorithmName
+ del OpenCompressor
+ del OpenDecompressor
+ del QueryAlgorithms
+ del QueryMaxHeaderSize
+ del QueryScheme
+ del QuerySchemeFromName
+ del SetDefault
+ del SetMax
+ del SetMin
+ try:
+ del cvt_type
+ except NameError:
+ pass
+ del error
diff --git a/Lib/plat-irix6/FILE.py b/Lib/plat-irix6/FILE.py
index 087d2ec96f..ab74d7c679 100644
--- a/Lib/plat-irix6/FILE.py
+++ b/Lib/plat-irix6/FILE.py
@@ -441,7 +441,7 @@ def OFFTOBB(bytes): return (((__uint64_t)(bytes) + BBSIZE - 1) >> BBSHIFT)
def OFFTOBBT(bytes): return ((off_t)(bytes) >> BBSHIFT)
-def BBTOOFF(bbs): return ((off_t)(bbs) << BBSHIFT)
+def BBTOOFF(bbs): return ((off_t)(bbs) << BBSHIFT)
SEEKLIMIT32 = 0x7fffffff
MAXBSIZE = 8192
@@ -489,9 +489,9 @@ MRLOCK_BEHAVIOR = 0x2
MRLOCK_DBLTRIPPABLE = 0x4
MRLOCK_ALLOW_EQUAL_PRI = 0x8
MRLOCK_DEFAULT = MRLOCK_BARRIER
-def mraccess(mrp): return mraccessf(mrp, 0)
+def mraccess(mrp): return mraccessf(mrp, 0)
-def mrupdate(mrp): return mrupdatef(mrp, 0)
+def mrupdate(mrp): return mrupdatef(mrp, 0)
def mp_mutex_unlock(m): return mutex_unlock(m)
diff --git a/Lib/plat-irix6/FL.py b/Lib/plat-irix6/FL.py
index ae665e3fe8..727da4c9a0 100644
--- a/Lib/plat-irix6/FL.py
+++ b/Lib/plat-irix6/FL.py
@@ -7,9 +7,9 @@ _v20 = 1
_v21 = 1
##import fl
##try:
-## _v20 = (fl.get_rgbmode is not None)
+## _v20 = (fl.get_rgbmode is not None)
##except:
-## _v20 = 0
+## _v20 = 0
##del fl
NULL = 0
@@ -20,7 +20,7 @@ EVENT = -1
LABEL_SIZE = 64
if _v20:
- SHORTCUT_SIZE = 32
+ SHORTCUT_SIZE = 32
PLACE_FREE = 0
PLACE_SIZE = 1
PLACE_ASPECT = 2
@@ -119,7 +119,7 @@ TOUCH_BUTTON = 4
INOUT_BUTTON = 5
RETURN_BUTTON = 6
if _v20:
- HIDDEN_RET_BUTTON = 7
+ HIDDEN_RET_BUTTON = 7
BUTTON_BOXTYPE = UP_BOX
BUTTON_COL1 = COL1
BUTTON_COL2 = COL1
@@ -129,20 +129,20 @@ BUTTON_MCOL1 = MCOL
BUTTON_MCOL2 = MCOL
BUTTON_BW = BOUND_WIDTH
if _v20:
- CHART = 4
- BAR_CHART = 0
- HORBAR_CHART = 1
- LINE_CHART = 2
- FILLED_CHART = 3
- SPIKE_CHART = 4
- PIE_CHART = 5
- SPECIALPIE_CHART = 6
- CHART_BOXTYPE = BORDER_BOX
- CHART_COL1 = COL1
- CHART_LCOL = LCOL
- CHART_ALIGN = ALIGN_BOTTOM
- CHART_BW = BOUND_WIDTH
- CHART_MAX = 128
+ CHART = 4
+ BAR_CHART = 0
+ HORBAR_CHART = 1
+ LINE_CHART = 2
+ FILLED_CHART = 3
+ SPIKE_CHART = 4
+ PIE_CHART = 5
+ SPECIALPIE_CHART = 6
+ CHART_BOXTYPE = BORDER_BOX
+ CHART_COL1 = COL1
+ CHART_LCOL = LCOL
+ CHART_ALIGN = ALIGN_BOTTOM
+ CHART_BW = BOUND_WIDTH
+ CHART_MAX = 128
CHOICE = 42
NORMAL_CHOICE = 0
CHOICE_BOXTYPE = DOWN_BOX
@@ -173,11 +173,11 @@ COUNTER_COL2 = 4
COUNTER_LCOL = LCOL
COUNTER_ALIGN = ALIGN_BOTTOM
if _v20:
- COUNTER_BW = BOUND_WIDTH
+ COUNTER_BW = BOUND_WIDTH
else:
- DEFAULT = 51
- RETURN_DEFAULT = 0
- ALWAYS_DEFAULT = 1
+ DEFAULT = 51
+ RETURN_DEFAULT = 0
+ ALWAYS_DEFAULT = 1
DIAL = 22
NORMAL_DIAL = 0
LINE_DIAL = 1
@@ -197,14 +197,14 @@ ALL_FREE = 5
INPUT = 31
NORMAL_INPUT = 0
if _v20:
- FLOAT_INPUT = 1
- INT_INPUT = 2
- HIDDEN_INPUT = 3
- if _v21:
- MULTILINE_INPUT = 4
- SECRET_INPUT = 5
+ FLOAT_INPUT = 1
+ INT_INPUT = 2
+ HIDDEN_INPUT = 3
+ if _v21:
+ MULTILINE_INPUT = 4
+ SECRET_INPUT = 5
else:
- ALWAYS_INPUT = 1
+ ALWAYS_INPUT = 1
INPUT_BOXTYPE = DOWN_BOX
INPUT_COL1 = 13
INPUT_COL2 = 5
diff --git a/Lib/plat-irix6/SV.py b/Lib/plat-irix6/SV.py
index 08fb91798a..db8efe52d4 100644
--- a/Lib/plat-irix6/SV.py
+++ b/Lib/plat-irix6/SV.py
@@ -7,16 +7,16 @@ BLANKING_BUFFER_SIZE = 2
MAX_SOURCES = 2
# mode parameter for Bind calls
-IN_OFF = 0 # No Video
-IN_OVER = 1 # Video over graphics
-IN_UNDER = 2 # Video under graphics
-IN_REPLACE = 3 # Video replaces entire win
+IN_OFF = 0 # No Video
+IN_OVER = 1 # Video over graphics
+IN_UNDER = 2 # Video under graphics
+IN_REPLACE = 3 # Video replaces entire win
# mode parameters for LoadMap calls. Specifies buffer, always 256 entries
-INPUT_COLORMAP = 0 # tuples of 8-bit RGB
-CHROMA_KEY_MAP = 1 # tuples of 8-bit RGB
-COLOR_SPACE_MAP = 2 # tuples of 8-bit RGB
-GAMMA_MAP = 3 # tuples of 24-bit red values
+INPUT_COLORMAP = 0 # tuples of 8-bit RGB
+CHROMA_KEY_MAP = 1 # tuples of 8-bit RGB
+COLOR_SPACE_MAP = 2 # tuples of 8-bit RGB
+GAMMA_MAP = 3 # tuples of 24-bit red values
# mode parameters for UseExclusive calls
INPUT = 0
@@ -24,9 +24,9 @@ OUTPUT = 1
IN_OUT = 2
# Format constants for the capture routines
-RGB8_FRAMES = 0 # noninterleaved 8 bit 3:2:3 RBG fields
-RGB32_FRAMES = 1 # 32-bit 8:8:8 RGB frames
-YUV411_FRAMES = 2 # interleaved, 8:2:2 YUV format
+RGB8_FRAMES = 0 # noninterleaved 8 bit 3:2:3 RBG fields
+RGB32_FRAMES = 1 # 32-bit 8:8:8 RGB frames
+YUV411_FRAMES = 2 # interleaved, 8:2:2 YUV format
YUV411_FRAMES_AND_BLANKING_BUFFER = 3
#
diff --git a/Lib/plat-irix6/cddb.py b/Lib/plat-irix6/cddb.py
index 256927cc80..45883054f8 100644
--- a/Lib/plat-irix6/cddb.py
+++ b/Lib/plat-irix6/cddb.py
@@ -20,185 +20,185 @@ _cddbrc = '.cddb'
_DB_ID_NTRACKS = 5
_dbid_map = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@_=+abcdefghijklmnopqrstuvwxyz'
def _dbid(v):
- if v >= len(_dbid_map):
- return string.zfill(v, 2)
- else:
- return _dbid_map[v]
+ if v >= len(_dbid_map):
+ return string.zfill(v, 2)
+ else:
+ return _dbid_map[v]
def tochash(toc):
- if type(toc) == type(''):
- tracklist = []
- for i in range(2, len(toc), 4):
- tracklist.append((None,
- (int(toc[i:i+2]),
- int(toc[i+2:i+4]))))
- else:
- tracklist = toc
- ntracks = len(tracklist)
- hash = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF)
- if ntracks <= _DB_ID_NTRACKS:
- nidtracks = ntracks
- else:
- nidtracks = _DB_ID_NTRACKS - 1
- min = 0
- sec = 0
- for track in tracklist:
- start, length = track
- min = min + length[0]
- sec = sec + length[1]
- min = min + sec / 60
- sec = sec % 60
- hash = hash + _dbid(min) + _dbid(sec)
- for i in range(nidtracks):
- start, length = tracklist[i]
- hash = hash + _dbid(length[0]) + _dbid(length[1])
- return hash
-
+ if type(toc) == type(''):
+ tracklist = []
+ for i in range(2, len(toc), 4):
+ tracklist.append((None,
+ (int(toc[i:i+2]),
+ int(toc[i+2:i+4]))))
+ else:
+ tracklist = toc
+ ntracks = len(tracklist)
+ hash = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF)
+ if ntracks <= _DB_ID_NTRACKS:
+ nidtracks = ntracks
+ else:
+ nidtracks = _DB_ID_NTRACKS - 1
+ min = 0
+ sec = 0
+ for track in tracklist:
+ start, length = track
+ min = min + length[0]
+ sec = sec + length[1]
+ min = min + sec / 60
+ sec = sec % 60
+ hash = hash + _dbid(min) + _dbid(sec)
+ for i in range(nidtracks):
+ start, length = tracklist[i]
+ hash = hash + _dbid(length[0]) + _dbid(length[1])
+ return hash
+
class Cddb:
- def __init__(self, tracklist):
- if os.environ.has_key('CDDB_PATH'):
- path = os.environ['CDDB_PATH']
- cddb_path = path.split(',')
- else:
- home = os.environ['HOME']
- cddb_path = [home + '/' + _cddbrc]
+ def __init__(self, tracklist):
+ if os.environ.has_key('CDDB_PATH'):
+ path = os.environ['CDDB_PATH']
+ cddb_path = path.split(',')
+ else:
+ home = os.environ['HOME']
+ cddb_path = [home + '/' + _cddbrc]
- self._get_id(tracklist)
+ self._get_id(tracklist)
- for dir in cddb_path:
- file = dir + '/' + self.id + '.rdb'
- try:
- f = open(file, 'r')
- self.file = file
- break
- except IOError:
- pass
- ntracks = int(self.id[:2], 16)
- self.artist = ''
- self.title = ''
- self.track = [None] + [''] * ntracks
- self.trackartist = [None] + [''] * ntracks
- self.notes = []
- if not hasattr(self, 'file'):
- return
- import re
- reg = re.compile(r'^([^.]*)\.([^:]*):[\t ]+(.*)')
- while 1:
- line = f.readline()
- if not line:
- break
- match = reg.match(line)
- if not match:
- print 'syntax error in ' + file
- continue
- name1, name2, value = match.group(1, 2, 3)
- if name1 == 'album':
- if name2 == 'artist':
- self.artist = value
- elif name2 == 'title':
- self.title = value
- elif name2 == 'toc':
- if not self.toc:
- self.toc = value
- if self.toc != value:
- print 'toc\'s don\'t match'
- elif name2 == 'notes':
- self.notes.append(value)
- elif name1[:5] == 'track':
- try:
- trackno = int(name1[5:])
- except ValueError:
- print 'syntax error in ' + file
- continue
- if trackno > ntracks:
- print 'track number %r in file %s out of range' % (trackno, file)
- continue
- if name2 == 'title':
- self.track[trackno] = value
- elif name2 == 'artist':
- self.trackartist[trackno] = value
- f.close()
- for i in range(2, len(self.track)):
- track = self.track[i]
- # if track title starts with `,', use initial part
- # of previous track's title
- if track and track[0] == ',':
- try:
- off = self.track[i - 1].index(',')
- except ValueError:
- pass
- else:
- self.track[i] = self.track[i-1][:off] \
- + track
+ for dir in cddb_path:
+ file = dir + '/' + self.id + '.rdb'
+ try:
+ f = open(file, 'r')
+ self.file = file
+ break
+ except IOError:
+ pass
+ ntracks = int(self.id[:2], 16)
+ self.artist = ''
+ self.title = ''
+ self.track = [None] + [''] * ntracks
+ self.trackartist = [None] + [''] * ntracks
+ self.notes = []
+ if not hasattr(self, 'file'):
+ return
+ import re
+ reg = re.compile(r'^([^.]*)\.([^:]*):[\t ]+(.*)')
+ while 1:
+ line = f.readline()
+ if not line:
+ break
+ match = reg.match(line)
+ if not match:
+ print 'syntax error in ' + file
+ continue
+ name1, name2, value = match.group(1, 2, 3)
+ if name1 == 'album':
+ if name2 == 'artist':
+ self.artist = value
+ elif name2 == 'title':
+ self.title = value
+ elif name2 == 'toc':
+ if not self.toc:
+ self.toc = value
+ if self.toc != value:
+ print 'toc\'s don\'t match'
+ elif name2 == 'notes':
+ self.notes.append(value)
+ elif name1[:5] == 'track':
+ try:
+ trackno = int(name1[5:])
+ except ValueError:
+ print 'syntax error in ' + file
+ continue
+ if trackno > ntracks:
+ print 'track number %r in file %s out of range' % (trackno, file)
+ continue
+ if name2 == 'title':
+ self.track[trackno] = value
+ elif name2 == 'artist':
+ self.trackartist[trackno] = value
+ f.close()
+ for i in range(2, len(self.track)):
+ track = self.track[i]
+ # if track title starts with `,', use initial part
+ # of previous track's title
+ if track and track[0] == ',':
+ try:
+ off = self.track[i - 1].index(',')
+ except ValueError:
+ pass
+ else:
+ self.track[i] = self.track[i-1][:off] \
+ + track
- def _get_id(self, tracklist):
- # fill in self.id and self.toc.
- # if the argument is a string ending in .rdb, the part
- # upto the suffix is taken as the id.
- if type(tracklist) == type(''):
- if tracklist[-4:] == '.rdb':
- self.id = tracklist[:-4]
- self.toc = ''
- return
- t = []
- for i in range(2, len(tracklist), 4):
- t.append((None, \
- (int(tracklist[i:i+2]), \
- int(tracklist[i+2:i+4]))))
- tracklist = t
- ntracks = len(tracklist)
- self.id = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF)
- if ntracks <= _DB_ID_NTRACKS:
- nidtracks = ntracks
- else:
- nidtracks = _DB_ID_NTRACKS - 1
- min = 0
- sec = 0
- for track in tracklist:
- start, length = track
- min = min + length[0]
- sec = sec + length[1]
- min = min + sec / 60
- sec = sec % 60
- self.id = self.id + _dbid(min) + _dbid(sec)
- for i in range(nidtracks):
- start, length = tracklist[i]
- self.id = self.id + _dbid(length[0]) + _dbid(length[1])
- self.toc = string.zfill(ntracks, 2)
- for track in tracklist:
- start, length = track
- self.toc = self.toc + string.zfill(length[0], 2) + \
- string.zfill(length[1], 2)
+ def _get_id(self, tracklist):
+ # fill in self.id and self.toc.
+ # if the argument is a string ending in .rdb, the part
+ # upto the suffix is taken as the id.
+ if type(tracklist) == type(''):
+ if tracklist[-4:] == '.rdb':
+ self.id = tracklist[:-4]
+ self.toc = ''
+ return
+ t = []
+ for i in range(2, len(tracklist), 4):
+ t.append((None, \
+ (int(tracklist[i:i+2]), \
+ int(tracklist[i+2:i+4]))))
+ tracklist = t
+ ntracks = len(tracklist)
+ self.id = _dbid((ntracks >> 4) & 0xF) + _dbid(ntracks & 0xF)
+ if ntracks <= _DB_ID_NTRACKS:
+ nidtracks = ntracks
+ else:
+ nidtracks = _DB_ID_NTRACKS - 1
+ min = 0
+ sec = 0
+ for track in tracklist:
+ start, length = track
+ min = min + length[0]
+ sec = sec + length[1]
+ min = min + sec / 60
+ sec = sec % 60
+ self.id = self.id + _dbid(min) + _dbid(sec)
+ for i in range(nidtracks):
+ start, length = tracklist[i]
+ self.id = self.id + _dbid(length[0]) + _dbid(length[1])
+ self.toc = string.zfill(ntracks, 2)
+ for track in tracklist:
+ start, length = track
+ self.toc = self.toc + string.zfill(length[0], 2) + \
+ string.zfill(length[1], 2)
- def write(self):
- import posixpath
- if os.environ.has_key('CDDB_WRITE_DIR'):
- dir = os.environ['CDDB_WRITE_DIR']
- else:
- dir = os.environ['HOME'] + '/' + _cddbrc
- file = dir + '/' + self.id + '.rdb'
- if posixpath.exists(file):
- # make backup copy
- posix.rename(file, file + '~')
- f = open(file, 'w')
- f.write('album.title:\t' + self.title + '\n')
- f.write('album.artist:\t' + self.artist + '\n')
- f.write('album.toc:\t' + self.toc + '\n')
- for note in self.notes:
- f.write('album.notes:\t' + note + '\n')
- prevpref = None
- for i in range(1, len(self.track)):
- if self.trackartist[i]:
- f.write('track%r.artist:\t%s\n' % (i, self.trackartist[i]))
- track = self.track[i]
- try:
- off = track.index(',')
- except ValueError:
- prevpref = None
- else:
- if prevpref and track[:off] == prevpref:
- track = track[off:]
- else:
- prevpref = track[:off]
- f.write('track%r.title:\t%s\n' % (i, track))
- f.close()
+ def write(self):
+ import posixpath
+ if os.environ.has_key('CDDB_WRITE_DIR'):
+ dir = os.environ['CDDB_WRITE_DIR']
+ else:
+ dir = os.environ['HOME'] + '/' + _cddbrc
+ file = dir + '/' + self.id + '.rdb'
+ if posixpath.exists(file):
+ # make backup copy
+ posix.rename(file, file + '~')
+ f = open(file, 'w')
+ f.write('album.title:\t' + self.title + '\n')
+ f.write('album.artist:\t' + self.artist + '\n')
+ f.write('album.toc:\t' + self.toc + '\n')
+ for note in self.notes:
+ f.write('album.notes:\t' + note + '\n')
+ prevpref = None
+ for i in range(1, len(self.track)):
+ if self.trackartist[i]:
+ f.write('track%r.artist:\t%s\n' % (i, self.trackartist[i]))
+ track = self.track[i]
+ try:
+ off = track.index(',')
+ except ValueError:
+ prevpref = None
+ else:
+ if prevpref and track[:off] == prevpref:
+ track = track[off:]
+ else:
+ prevpref = track[:off]
+ f.write('track%r.title:\t%s\n' % (i, track))
+ f.close()
diff --git a/Lib/plat-irix6/cdplayer.py b/Lib/plat-irix6/cdplayer.py
index 4ba3f51cd7..d4bc7328ac 100644
--- a/Lib/plat-irix6/cdplayer.py
+++ b/Lib/plat-irix6/cdplayer.py
@@ -17,72 +17,72 @@
cdplayerrc = '.cdplayerrc'
class Cdplayer:
- def __init__(self, tracklist):
- import string
- self.artist = ''
- self.title = ''
- if type(tracklist) == type(''):
- t = []
- for i in range(2, len(tracklist), 4):
- t.append((None, \
- (int(tracklist[i:i+2]), \
- int(tracklist[i+2:i+4]))))
- tracklist = t
- self.track = [None] + [''] * len(tracklist)
- self.id = 'd' + string.zfill(len(tracklist), 2)
- for track in tracklist:
- start, length = track
- self.id = self.id + string.zfill(length[0], 2) + \
- string.zfill(length[1], 2)
- try:
- import posix
- f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r')
- except IOError:
- return
- import re
- reg = re.compile(r'^([^:]*):\t(.*)')
- s = self.id + '.'
- l = len(s)
- while 1:
- line = f.readline()
- if line == '':
- break
- if line[:l] == s:
- line = line[l:]
- match = reg.match(line)
- if not match:
- print 'syntax error in ~/' + cdplayerrc
- continue
- name, value = match.group(1, 2)
- if name == 'title':
- self.title = value
- elif name == 'artist':
- self.artist = value
- elif name[:5] == 'track':
- trackno = int(name[6:])
- self.track[trackno] = value
- f.close()
+ def __init__(self, tracklist):
+ import string
+ self.artist = ''
+ self.title = ''
+ if type(tracklist) == type(''):
+ t = []
+ for i in range(2, len(tracklist), 4):
+ t.append((None, \
+ (int(tracklist[i:i+2]), \
+ int(tracklist[i+2:i+4]))))
+ tracklist = t
+ self.track = [None] + [''] * len(tracklist)
+ self.id = 'd' + string.zfill(len(tracklist), 2)
+ for track in tracklist:
+ start, length = track
+ self.id = self.id + string.zfill(length[0], 2) + \
+ string.zfill(length[1], 2)
+ try:
+ import posix
+ f = open(posix.environ['HOME'] + '/' + cdplayerrc, 'r')
+ except IOError:
+ return
+ import re
+ reg = re.compile(r'^([^:]*):\t(.*)')
+ s = self.id + '.'
+ l = len(s)
+ while 1:
+ line = f.readline()
+ if line == '':
+ break
+ if line[:l] == s:
+ line = line[l:]
+ match = reg.match(line)
+ if not match:
+ print 'syntax error in ~/' + cdplayerrc
+ continue
+ name, value = match.group(1, 2)
+ if name == 'title':
+ self.title = value
+ elif name == 'artist':
+ self.artist = value
+ elif name[:5] == 'track':
+ trackno = int(name[6:])
+ self.track[trackno] = value
+ f.close()
- def write(self):
- import posix
- filename = posix.environ['HOME'] + '/' + cdplayerrc
- try:
- old = open(filename, 'r')
- except IOError:
- old = open('/dev/null', 'r')
- new = open(filename + '.new', 'w')
- s = self.id + '.'
- l = len(s)
- while 1:
- line = old.readline()
- if line == '':
- break
- if line[:l] != s:
- new.write(line)
- new.write(self.id + '.title:\t' + self.title + '\n')
- new.write(self.id + '.artist:\t' + self.artist + '\n')
- for i in range(1, len(self.track)):
- new.write('%s.track.%r:\t%s\n' % (i, track))
- old.close()
- new.close()
- posix.rename(filename + '.new', filename)
+ def write(self):
+ import posix
+ filename = posix.environ['HOME'] + '/' + cdplayerrc
+ try:
+ old = open(filename, 'r')
+ except IOError:
+ old = open('/dev/null', 'r')
+ new = open(filename + '.new', 'w')
+ s = self.id + '.'
+ l = len(s)
+ while 1:
+ line = old.readline()
+ if line == '':
+ break
+ if line[:l] != s:
+ new.write(line)
+ new.write(self.id + '.title:\t' + self.title + '\n')
+ new.write(self.id + '.artist:\t' + self.artist + '\n')
+ for i in range(1, len(self.track)):
+ new.write('%s.track.%r:\t%s\n' % (i, track))
+ old.close()
+ new.close()
+ posix.rename(filename + '.new', filename)
diff --git a/Lib/plat-irix6/flp.py b/Lib/plat-irix6/flp.py
index aa231070a4..f745472a70 100644
--- a/Lib/plat-irix6/flp.py
+++ b/Lib/plat-irix6/flp.py
@@ -79,18 +79,18 @@ def checkcache(filename):
fp.close()
def _unpack_cache(altforms):
- forms = {}
- for name in altforms.keys():
- altobj, altlist = altforms[name]
- obj = _newobj()
- obj.make(altobj)
- list = []
- for altobj in altlist:
- nobj = _newobj()
- nobj.make(altobj)
- list.append(nobj)
- forms[name] = obj, list
- return forms
+ forms = {}
+ for name in altforms.keys():
+ altobj, altlist = altforms[name]
+ obj = _newobj()
+ obj.make(altobj)
+ list = []
+ for altobj in altlist:
+ nobj = _newobj()
+ nobj.make(altobj)
+ list.append(nobj)
+ forms[name] = obj, list
+ return forms
def rdlong(fp):
s = fp.read(4)
@@ -276,8 +276,8 @@ def _parse_line(line):
return line
name, value = match.group(1, 2)
if name[0] == 'N':
- name = ''.join(name.split())
- name = name.lower()
+ name = ''.join(name.split())
+ name = name.lower()
name = name.capitalize()
try:
pf = _parse_func[name]
@@ -291,7 +291,7 @@ def _readline(file):
if not line:
raise EOFError
return line[:-1]
-
+
def _parse_1_line(file):
line = _readline(file)
while line == '':
diff --git a/Lib/plat-irix6/jpeg.py b/Lib/plat-irix6/jpeg.py
index 2354f40541..0b52031aa3 100644
--- a/Lib/plat-irix6/jpeg.py
+++ b/Lib/plat-irix6/jpeg.py
@@ -6,7 +6,7 @@
# XXX the resulting file causes weirdness.
class error(Exception):
- pass
+ pass
options = {'quality': 75, 'optimize': 0, 'smooth': 0, 'forcegray': 0}
@@ -14,98 +14,98 @@ comp = None
decomp = None
def compress(imgdata, width, height, bytesperpixel):
- global comp
- import cl
- if comp is None: comp = cl.OpenCompressor(cl.JPEG)
- if bytesperpixel == 1:
- format = cl.GRAYSCALE
- elif bytesperpixel == 4:
- format = cl.RGBX
- if options['forcegray']:
- iformat = cl.GRAYSCALE
- else:
- iformat = cl.YUV
- # XXX How to support 'optimize'?
- params = [cl.IMAGE_WIDTH, width, cl.IMAGE_HEIGHT, height,
- cl.ORIGINAL_FORMAT, format,
- cl.ORIENTATION, cl.BOTTOM_UP,
- cl.QUALITY_FACTOR, options['quality'],
- cl.INTERNAL_FORMAT, iformat,
- ]
- comp.SetParams(params)
- jpegdata = comp.Compress(1, imgdata)
- return jpegdata
+ global comp
+ import cl
+ if comp is None: comp = cl.OpenCompressor(cl.JPEG)
+ if bytesperpixel == 1:
+ format = cl.GRAYSCALE
+ elif bytesperpixel == 4:
+ format = cl.RGBX
+ if options['forcegray']:
+ iformat = cl.GRAYSCALE
+ else:
+ iformat = cl.YUV
+ # XXX How to support 'optimize'?
+ params = [cl.IMAGE_WIDTH, width, cl.IMAGE_HEIGHT, height,
+ cl.ORIGINAL_FORMAT, format,
+ cl.ORIENTATION, cl.BOTTOM_UP,
+ cl.QUALITY_FACTOR, options['quality'],
+ cl.INTERNAL_FORMAT, iformat,
+ ]
+ comp.SetParams(params)
+ jpegdata = comp.Compress(1, imgdata)
+ return jpegdata
def decompress(jpegdata):
- global decomp
- import cl
- if decomp is None: decomp = cl.OpenDecompressor(cl.JPEG)
- headersize = decomp.ReadHeader(jpegdata)
- params = [cl.IMAGE_WIDTH, 0, cl.IMAGE_HEIGHT, 0, cl.INTERNAL_FORMAT, 0]
- decomp.GetParams(params)
- width, height, format = params[1], params[3], params[5]
- if format == cl.GRAYSCALE or options['forcegray']:
- format = cl.GRAYSCALE
- bytesperpixel = 1
- else:
- format = cl.RGBX
- bytesperpixel = 4
- # XXX How to support 'smooth'?
- params = [cl.ORIGINAL_FORMAT, format,
- cl.ORIENTATION, cl.BOTTOM_UP,
- cl.FRAME_BUFFER_SIZE, width*height*bytesperpixel]
- decomp.SetParams(params)
- imgdata = decomp.Decompress(1, jpegdata)
- return imgdata, width, height, bytesperpixel
+ global decomp
+ import cl
+ if decomp is None: decomp = cl.OpenDecompressor(cl.JPEG)
+ headersize = decomp.ReadHeader(jpegdata)
+ params = [cl.IMAGE_WIDTH, 0, cl.IMAGE_HEIGHT, 0, cl.INTERNAL_FORMAT, 0]
+ decomp.GetParams(params)
+ width, height, format = params[1], params[3], params[5]
+ if format == cl.GRAYSCALE or options['forcegray']:
+ format = cl.GRAYSCALE
+ bytesperpixel = 1
+ else:
+ format = cl.RGBX
+ bytesperpixel = 4
+ # XXX How to support 'smooth'?
+ params = [cl.ORIGINAL_FORMAT, format,
+ cl.ORIENTATION, cl.BOTTOM_UP,
+ cl.FRAME_BUFFER_SIZE, width*height*bytesperpixel]
+ decomp.SetParams(params)
+ imgdata = decomp.Decompress(1, jpegdata)
+ return imgdata, width, height, bytesperpixel
def setoption(name, value):
- if type(value) is not type(0):
- raise TypeError, 'jpeg.setoption: numeric options only'
- if name == 'forcegrey':
- name = 'forcegray'
- if not options.has_key(name):
- raise KeyError, 'jpeg.setoption: unknown option name'
- options[name] = int(value)
+ if type(value) is not type(0):
+ raise TypeError, 'jpeg.setoption: numeric options only'
+ if name == 'forcegrey':
+ name = 'forcegray'
+ if not options.has_key(name):
+ raise KeyError, 'jpeg.setoption: unknown option name'
+ options[name] = int(value)
def test():
- import sys
- if sys.argv[1:2] == ['-g']:
- del sys.argv[1]
- setoption('forcegray', 1)
- if not sys.argv[1:]:
- sys.argv.append('/usr/local/images/data/jpg/asterix.jpg')
- for file in sys.argv[1:]:
- show(file)
+ import sys
+ if sys.argv[1:2] == ['-g']:
+ del sys.argv[1]
+ setoption('forcegray', 1)
+ if not sys.argv[1:]:
+ sys.argv.append('/usr/local/images/data/jpg/asterix.jpg')
+ for file in sys.argv[1:]:
+ show(file)
def show(file):
- import gl, GL, DEVICE
- jpegdata = open(file, 'r').read()
- imgdata, width, height, bytesperpixel = decompress(jpegdata)
- gl.foreground()
- gl.prefsize(width, height)
- win = gl.winopen(file)
- if bytesperpixel == 1:
- gl.cmode()
- gl.pixmode(GL.PM_SIZE, 8)
- gl.gconfig()
- for i in range(256):
- gl.mapcolor(i, i, i, i)
- else:
- gl.RGBmode()
- gl.pixmode(GL.PM_SIZE, 32)
- gl.gconfig()
- gl.qdevice(DEVICE.REDRAW)
- gl.qdevice(DEVICE.ESCKEY)
- gl.qdevice(DEVICE.WINQUIT)
- gl.qdevice(DEVICE.WINSHUT)
- gl.lrectwrite(0, 0, width-1, height-1, imgdata)
- while 1:
- dev, val = gl.qread()
- if dev in (DEVICE.ESCKEY, DEVICE.WINSHUT, DEVICE.WINQUIT):
- break
- if dev == DEVICE.REDRAW:
- gl.lrectwrite(0, 0, width-1, height-1, imgdata)
- gl.winclose(win)
- # Now test the compression and write the result to a fixed filename
- newjpegdata = compress(imgdata, width, height, bytesperpixel)
- open('/tmp/j.jpg', 'w').write(newjpegdata)
+ import gl, GL, DEVICE
+ jpegdata = open(file, 'r').read()
+ imgdata, width, height, bytesperpixel = decompress(jpegdata)
+ gl.foreground()
+ gl.prefsize(width, height)
+ win = gl.winopen(file)
+ if bytesperpixel == 1:
+ gl.cmode()
+ gl.pixmode(GL.PM_SIZE, 8)
+ gl.gconfig()
+ for i in range(256):
+ gl.mapcolor(i, i, i, i)
+ else:
+ gl.RGBmode()
+ gl.pixmode(GL.PM_SIZE, 32)
+ gl.gconfig()
+ gl.qdevice(DEVICE.REDRAW)
+ gl.qdevice(DEVICE.ESCKEY)
+ gl.qdevice(DEVICE.WINQUIT)
+ gl.qdevice(DEVICE.WINSHUT)
+ gl.lrectwrite(0, 0, width-1, height-1, imgdata)
+ while 1:
+ dev, val = gl.qread()
+ if dev in (DEVICE.ESCKEY, DEVICE.WINSHUT, DEVICE.WINQUIT):
+ break
+ if dev == DEVICE.REDRAW:
+ gl.lrectwrite(0, 0, width-1, height-1, imgdata)
+ gl.winclose(win)
+ # Now test the compression and write the result to a fixed filename
+ newjpegdata = compress(imgdata, width, height, bytesperpixel)
+ open('/tmp/j.jpg', 'w').write(newjpegdata)
diff --git a/Lib/plat-irix6/panel.py b/Lib/plat-irix6/panel.py
index 3aa7448653..12e62a51b4 100644
--- a/Lib/plat-irix6/panel.py
+++ b/Lib/plat-irix6/panel.py
@@ -17,82 +17,82 @@ debug = 0
# Test if an object is a list.
#
def is_list(x):
- return type(x) == type([])
+ return type(x) == type([])
# Reverse a list.
#
def reverse(list):
- res = []
- for item in list:
- res.insert(0, item)
- return res
+ res = []
+ for item in list:
+ res.insert(0, item)
+ return res
# Get an attribute of a list, which may itself be another list.
# Don't use 'prop' for name.
#
def getattrlist(list, name):
- for item in list:
- if item and is_list(item) and item[0] == name:
- return item[1:]
- return []
+ for item in list:
+ if item and is_list(item) and item[0] == name:
+ return item[1:]
+ return []
# Get a property of a list, which may itself be another list.
#
def getproplist(list, name):
- for item in list:
- if item and is_list(item) and item[0] == 'prop':
- if len(item) > 1 and item[1] == name:
- return item[2:]
- return []
+ for item in list:
+ if item and is_list(item) and item[0] == 'prop':
+ if len(item) > 1 and item[1] == name:
+ return item[2:]
+ return []
# Test if an actuator description contains the property 'end-of-group'
#
def is_endgroup(list):
- x = getproplist(list, 'end-of-group')
- return (x and x[0] == '#t')
+ x = getproplist(list, 'end-of-group')
+ return (x and x[0] == '#t')
# Neatly display an actuator definition given as S-expression
# the prefix string is printed before each line.
#
def show_actuator(prefix, a):
- for item in a:
- if not is_list(item):
- print prefix, item
- elif item and item[0] == 'al':
- print prefix, 'Subactuator list:'
- for a in item[1:]:
- show_actuator(prefix + ' ', a)
- elif len(item) == 2:
- print prefix, item[0], '=>', item[1]
- elif len(item) == 3 and item[0] == 'prop':
- print prefix, 'Prop', item[1], '=>',
- print item[2]
- else:
- print prefix, '?', item
+ for item in a:
+ if not is_list(item):
+ print prefix, item
+ elif item and item[0] == 'al':
+ print prefix, 'Subactuator list:'
+ for a in item[1:]:
+ show_actuator(prefix + ' ', a)
+ elif len(item) == 2:
+ print prefix, item[0], '=>', item[1]
+ elif len(item) == 3 and item[0] == 'prop':
+ print prefix, 'Prop', item[1], '=>',
+ print item[2]
+ else:
+ print prefix, '?', item
# Neatly display a panel.
#
def show_panel(prefix, p):
- for item in p:
- if not is_list(item):
- print prefix, item
- elif item and item[0] == 'al':
- print prefix, 'Actuator list:'
- for a in item[1:]:
- show_actuator(prefix + ' ', a)
- elif len(item) == 2:
- print prefix, item[0], '=>', item[1]
- elif len(item) == 3 and item[0] == 'prop':
- print prefix, 'Prop', item[1], '=>',
- print item[2]
- else:
- print prefix, '?', item
+ for item in p:
+ if not is_list(item):
+ print prefix, item
+ elif item and item[0] == 'al':
+ print prefix, 'Actuator list:'
+ for a in item[1:]:
+ show_actuator(prefix + ' ', a)
+ elif len(item) == 2:
+ print prefix, item[0], '=>', item[1]
+ elif len(item) == 3 and item[0] == 'prop':
+ print prefix, 'Prop', item[1], '=>',
+ print item[2]
+ else:
+ print prefix, '?', item
# Exception raised by build_actuator or build_panel.
@@ -103,7 +103,7 @@ panel_error = 'panel error'
# Dummy callback used to initialize the callbacks.
#
def dummy_callback(arg):
- pass
+ pass
# Assign attributes to members of the target.
@@ -111,60 +111,60 @@ def dummy_callback(arg):
# The member name is the attribute name prefixed with the prefix.
#
def assign_members(target, attrlist, exclist, prefix):
- for item in attrlist:
- if is_list(item) and len(item) == 2 and item[0] not in exclist:
- name, value = item[0], item[1]
- ok = 1
- if value[0] in '-0123456789':
- value = eval(value)
- elif value[0] == '"':
- value = value[1:-1]
- elif value == 'move-then-resize':
- # Strange default set by Panel Editor...
- ok = 0
- else:
- print 'unknown value', value, 'for', name
- ok = 0
- if ok:
- lhs = 'target.' + prefix + name
- stmt = lhs + '=' + repr(value)
- if debug: print 'exec', stmt
- try:
- exec stmt + '\n'
- except KeyboardInterrupt: # Don't catch this!
- raise KeyboardInterrupt
- except:
- print 'assign failed:', stmt
+ for item in attrlist:
+ if is_list(item) and len(item) == 2 and item[0] not in exclist:
+ name, value = item[0], item[1]
+ ok = 1
+ if value[0] in '-0123456789':
+ value = eval(value)
+ elif value[0] == '"':
+ value = value[1:-1]
+ elif value == 'move-then-resize':
+ # Strange default set by Panel Editor...
+ ok = 0
+ else:
+ print 'unknown value', value, 'for', name
+ ok = 0
+ if ok:
+ lhs = 'target.' + prefix + name
+ stmt = lhs + '=' + repr(value)
+ if debug: print 'exec', stmt
+ try:
+ exec stmt + '\n'
+ except KeyboardInterrupt: # Don't catch this!
+ raise KeyboardInterrupt
+ except:
+ print 'assign failed:', stmt
# Build a real actuator from an actuator description.
# Return a pair (actuator, name).
#
def build_actuator(descr):
- namelist = getattrlist(descr, 'name')
- if namelist:
- # Assume it is a string
- actuatorname = namelist[0][1:-1]
- else:
- actuatorname = ''
- type = descr[0]
- if type[:4] == 'pnl_': type = type[4:]
- act = pnl.mkact(type)
- act.downfunc = act.activefunc = act.upfunc = dummy_callback
- #
- assign_members(act, descr[1:], ['al', 'data', 'name'], '')
- #
- # Treat actuator-specific data
- #
- datalist = getattrlist(descr, 'data')
- prefix = ''
- if type[-4:] == 'puck':
- prefix = 'puck_'
- elif type == 'mouse':
- prefix = 'mouse_'
- assign_members(act, datalist, [], prefix)
- #
- return act, actuatorname
+ namelist = getattrlist(descr, 'name')
+ if namelist:
+ # Assume it is a string
+ actuatorname = namelist[0][1:-1]
+ else:
+ actuatorname = ''
+ type = descr[0]
+ if type[:4] == 'pnl_': type = type[4:]
+ act = pnl.mkact(type)
+ act.downfunc = act.activefunc = act.upfunc = dummy_callback
+ #
+ assign_members(act, descr[1:], ['al', 'data', 'name'], '')
+ #
+ # Treat actuator-specific data
+ #
+ datalist = getattrlist(descr, 'data')
+ prefix = ''
+ if type[-4:] == 'puck':
+ prefix = 'puck_'
+ elif type == 'mouse':
+ prefix = 'mouse_'
+ assign_members(act, datalist, [], prefix)
+ #
+ return act, actuatorname
# Build all sub-actuators and add them to the super-actuator.
@@ -176,27 +176,27 @@ def build_actuator(descr):
# to a sub-actuator.
#
def build_subactuators(panel, super_act, al):
- #
- # This is nearly the same loop as below in build_panel(),
- # except a call is made to addsubact() instead of addact().
- #
- for a in al:
- act, name = build_actuator(a)
- act.addsubact(super_act)
- if name:
- stmt = 'panel.' + name + ' = act'
- if debug: print 'exec', stmt
- exec stmt + '\n'
- if is_endgroup(a):
- panel.endgroup()
- sub_al = getattrlist(a, 'al')
- if sub_al:
- build_subactuators(panel, act, sub_al)
- #
- # Fix the actuator to which whe just added subactuators.
- # This can't hurt (I hope) and is needed for the scroll actuator.
- #
- super_act.fixact()
+ #
+ # This is nearly the same loop as below in build_panel(),
+ # except a call is made to addsubact() instead of addact().
+ #
+ for a in al:
+ act, name = build_actuator(a)
+ act.addsubact(super_act)
+ if name:
+ stmt = 'panel.' + name + ' = act'
+ if debug: print 'exec', stmt
+ exec stmt + '\n'
+ if is_endgroup(a):
+ panel.endgroup()
+ sub_al = getattrlist(a, 'al')
+ if sub_al:
+ build_subactuators(panel, act, sub_al)
+ #
+ # Fix the actuator to which whe just added subactuators.
+ # This can't hurt (I hope) and is needed for the scroll actuator.
+ #
+ super_act.fixact()
# Build a real panel from a panel definition.
@@ -204,78 +204,78 @@ def build_subactuators(panel, super_act, al):
# reference to a.
#
def build_panel(descr):
- #
- # Sanity check
- #
- if (not descr) or descr[0] != 'panel':
- raise panel_error, 'panel description must start with "panel"'
- #
- if debug: show_panel('', descr)
- #
- # Create an empty panel
- #
- panel = pnl.mkpanel()
- #
- # Assign panel attributes
- #
- assign_members(panel, descr[1:], ['al'], '')
- #
- # Look for actuator list
- #
- al = getattrlist(descr, 'al')
- #
- # The order in which actuators are created is important
- # because of the endgroup() operator.
- # Unfortunately the Panel Editor outputs the actuator list
- # in reverse order, so we reverse it here.
- #
- al = reverse(al)
- #
- for a in al:
- act, name = build_actuator(a)
- act.addact(panel)
- if name:
- stmt = 'panel.' + name + ' = act'
- exec stmt + '\n'
- if is_endgroup(a):
- panel.endgroup()
- sub_al = getattrlist(a, 'al')
- if sub_al:
- build_subactuators(panel, act, sub_al)
- #
- return panel
+ #
+ # Sanity check
+ #
+ if (not descr) or descr[0] != 'panel':
+ raise panel_error, 'panel description must start with "panel"'
+ #
+ if debug: show_panel('', descr)
+ #
+ # Create an empty panel
+ #
+ panel = pnl.mkpanel()
+ #
+ # Assign panel attributes
+ #
+ assign_members(panel, descr[1:], ['al'], '')
+ #
+ # Look for actuator list
+ #
+ al = getattrlist(descr, 'al')
+ #
+ # The order in which actuators are created is important
+ # because of the endgroup() operator.
+ # Unfortunately the Panel Editor outputs the actuator list
+ # in reverse order, so we reverse it here.
+ #
+ al = reverse(al)
+ #
+ for a in al:
+ act, name = build_actuator(a)
+ act.addact(panel)
+ if name:
+ stmt = 'panel.' + name + ' = act'
+ exec stmt + '\n'
+ if is_endgroup(a):
+ panel.endgroup()
+ sub_al = getattrlist(a, 'al')
+ if sub_al:
+ build_subactuators(panel, act, sub_al)
+ #
+ return panel
# Wrapper around pnl.dopanel() which calls call-back functions.
#
def my_dopanel():
- # Extract only the first 4 elements to allow for future expansion
- a, down, active, up = pnl.dopanel()[:4]
- if down:
- down.downfunc(down)
- if active:
- active.activefunc(active)
- if up:
- up.upfunc(up)
- return a
+ # Extract only the first 4 elements to allow for future expansion
+ a, down, active, up = pnl.dopanel()[:4]
+ if down:
+ down.downfunc(down)
+ if active:
+ active.activefunc(active)
+ if up:
+ up.upfunc(up)
+ return a
# Create one or more panels from a description file (S-expressions)
# generated by the Panel Editor.
-#
+#
def defpanellist(file):
- import panelparser
- descrlist = panelparser.parse_file(open(file, 'r'))
- panellist = []
- for descr in descrlist:
- panellist.append(build_panel(descr))
- return panellist
+ import panelparser
+ descrlist = panelparser.parse_file(open(file, 'r'))
+ panellist = []
+ for descr in descrlist:
+ panellist.append(build_panel(descr))
+ return panellist
# Import everything from built-in method pnl, so the user can always
# use panel.foo() instead of pnl.foo().
# This gives *no* performance penalty once this module is imported.
#
-from pnl import * # for export
+from pnl import * # for export
-dopanel = my_dopanel # override pnl.dopanel
+dopanel = my_dopanel # override pnl.dopanel
diff --git a/Lib/plat-irix6/panelparser.py b/Lib/plat-irix6/panelparser.py
index ee50971683..c831c49272 100644
--- a/Lib/plat-irix6/panelparser.py
+++ b/Lib/plat-irix6/panelparser.py
@@ -15,47 +15,47 @@ separators = operators + whitespace + ';' + '"'
# Return a list of tokens (strings).
#
def tokenize_string(s):
- tokens = []
- while s:
- c = s[:1]
- if c in whitespace:
- s = s[1:]
- elif c == ';':
- s = ''
- elif c == '"':
- n = len(s)
- i = 1
- while i < n:
- c = s[i]
- i = i+1
- if c == '"': break
- if c == '\\': i = i+1
- tokens.append(s[:i])
- s = s[i:]
- elif c in operators:
- tokens.append(c)
- s = s[1:]
- else:
- n = len(s)
- i = 1
- while i < n:
- if s[i] in separators: break
- i = i+1
- tokens.append(s[:i])
- s = s[i:]
- return tokens
+ tokens = []
+ while s:
+ c = s[:1]
+ if c in whitespace:
+ s = s[1:]
+ elif c == ';':
+ s = ''
+ elif c == '"':
+ n = len(s)
+ i = 1
+ while i < n:
+ c = s[i]
+ i = i+1
+ if c == '"': break
+ if c == '\\': i = i+1
+ tokens.append(s[:i])
+ s = s[i:]
+ elif c in operators:
+ tokens.append(c)
+ s = s[1:]
+ else:
+ n = len(s)
+ i = 1
+ while i < n:
+ if s[i] in separators: break
+ i = i+1
+ tokens.append(s[:i])
+ s = s[i:]
+ return tokens
# Tokenize a whole file (given as file object, not as file name).
# Return a list of tokens (strings).
#
def tokenize_file(fp):
- tokens = []
- while 1:
- line = fp.readline()
- if not line: break
- tokens = tokens + tokenize_string(line)
- return tokens
+ tokens = []
+ while 1:
+ line = fp.readline()
+ if not line: break
+ tokens = tokens + tokenize_string(line)
+ return tokens
# Exception raised by parse_exr.
@@ -71,50 +71,50 @@ syntax_error = 'syntax error'
# May raise syntax_error.
#
def parse_expr(tokens):
- if (not tokens) or tokens[0] != '(':
- raise syntax_error, 'expected "("'
- tokens = tokens[1:]
- expr = []
- while 1:
- if not tokens:
- raise syntax_error, 'missing ")"'
- if tokens[0] == ')':
- return expr, tokens[1:]
- elif tokens[0] == '(':
- subexpr, tokens = parse_expr(tokens)
- expr.append(subexpr)
- else:
- expr.append(tokens[0])
- tokens = tokens[1:]
+ if (not tokens) or tokens[0] != '(':
+ raise syntax_error, 'expected "("'
+ tokens = tokens[1:]
+ expr = []
+ while 1:
+ if not tokens:
+ raise syntax_error, 'missing ")"'
+ if tokens[0] == ')':
+ return expr, tokens[1:]
+ elif tokens[0] == '(':
+ subexpr, tokens = parse_expr(tokens)
+ expr.append(subexpr)
+ else:
+ expr.append(tokens[0])
+ tokens = tokens[1:]
# Parse a file (given as file object, not as file name).
# Return a list of parsed S-expressions found at the top level.
#
def parse_file(fp):
- tokens = tokenize_file(fp)
- exprlist = []
- while tokens:
- expr, tokens = parse_expr(tokens)
- exprlist.append(expr)
- return exprlist
+ tokens = tokenize_file(fp)
+ exprlist = []
+ while tokens:
+ expr, tokens = parse_expr(tokens)
+ exprlist.append(expr)
+ return exprlist
# EXAMPLE:
#
# The input
-# '(hip (hop hur-ray))'
+# '(hip (hop hur-ray))'
#
# passed to tokenize_string() returns the token list
-# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')']
+# ['(', 'hip', '(', 'hop', 'hur-ray', ')', ')']
#
# When this is passed to parse_expr() it returns the expression
-# ['hip', ['hop', 'hur-ray']]
+# ['hip', ['hop', 'hur-ray']]
# plus an empty token list (because there are no tokens left.
#
# When a file containing the example is passed to parse_file() it returns
# a list whose only element is the output of parse_expr() above:
-# [['hip', ['hop', 'hur-ray']]]
+# [['hip', ['hop', 'hur-ray']]]
# TOKENIZING:
@@ -123,6 +123,6 @@ def parse_file(fp):
#
# Tokens are separated by whitespace, except the following characters
# always form a separate token (outside strings):
-# ( ) '
+# ( ) '
# Strings are enclosed in double quotes (") and backslash (\) is used
# as escape character in strings.
diff --git a/Lib/plat-irix6/readcd.py b/Lib/plat-irix6/readcd.py
index f278ba4bf0..5453ce4213 100644
--- a/Lib/plat-irix6/readcd.py
+++ b/Lib/plat-irix6/readcd.py
@@ -3,242 +3,242 @@
import cd, CD
class Error(Exception):
- pass
+ pass
class _Stop(Exception):
- pass
+ pass
def _doatime(self, cb_type, data):
- if ((data[0] * 60) + data[1]) * 75 + data[2] > self.end:
-## print 'done with list entry', repr(self.listindex)
- raise _Stop
- func, arg = self.callbacks[cb_type]
- if func:
- func(arg, cb_type, data)
+ if ((data[0] * 60) + data[1]) * 75 + data[2] > self.end:
+## print 'done with list entry', repr(self.listindex)
+ raise _Stop
+ func, arg = self.callbacks[cb_type]
+ if func:
+ func(arg, cb_type, data)
def _dopnum(self, cb_type, data):
- if data > self.end:
-## print 'done with list entry', repr(self.listindex)
- raise _Stop
- func, arg = self.callbacks[cb_type]
- if func:
- func(arg, cb_type, data)
+ if data > self.end:
+## print 'done with list entry', repr(self.listindex)
+ raise _Stop
+ func, arg = self.callbacks[cb_type]
+ if func:
+ func(arg, cb_type, data)
class Readcd:
- def __init__(self, *arg):
- if len(arg) == 0:
- self.player = cd.open()
- elif len(arg) == 1:
- self.player = cd.open(arg[0])
- elif len(arg) == 2:
- self.player = cd.open(arg[0], arg[1])
- else:
- raise Error, 'bad __init__ call'
- self.list = []
- self.callbacks = [(None, None)] * 8
- self.parser = cd.createparser()
- self.playing = 0
- self.end = 0
- self.status = None
- self.trackinfo = None
-
- def eject(self):
- self.player.eject()
- self.list = []
- self.end = 0
- self.listindex = 0
- self.status = None
- self.trackinfo = None
- if self.playing:
-## print 'stop playing from eject'
- raise _Stop
-
- def pmsf2msf(self, track, min, sec, frame):
- if not self.status:
- self.cachestatus()
- if track < self.status[5] or track > self.status[6]:
- raise Error, 'track number out of range'
- if not self.trackinfo:
- self.cacheinfo()
- start, total = self.trackinfo[track]
- start = ((start[0] * 60) + start[1]) * 75 + start[2]
- total = ((total[0] * 60) + total[1]) * 75 + total[2]
- block = ((min * 60) + sec) * 75 + frame
- if block > total:
- raise Error, 'out of range'
- block = start + block
- min, block = divmod(block, 75*60)
- sec, frame = divmod(block, 75)
- return min, sec, frame
-
- def reset(self):
- self.list = []
-
- def appendtrack(self, track):
- self.appendstretch(track, track)
-
- def appendstretch(self, start, end):
- if not self.status:
- self.cachestatus()
- if not start:
- start = 1
- if not end:
- end = self.status[6]
- if type(end) == type(0):
- if end < self.status[5] or end > self.status[6]:
- raise Error, 'range error'
- else:
- l = len(end)
- if l == 4:
- prog, min, sec, frame = end
- if prog < self.status[5] or prog > self.status[6]:
- raise Error, 'range error'
- end = self.pmsf2msf(prog, min, sec, frame)
- elif l != 3:
- raise Error, 'syntax error'
- if type(start) == type(0):
- if start < self.status[5] or start > self.status[6]:
- raise Error, 'range error'
- if len(self.list) > 0:
- s, e = self.list[-1]
- if type(e) == type(0):
- if start == e+1:
- start = s
- del self.list[-1]
- else:
- l = len(start)
- if l == 4:
- prog, min, sec, frame = start
- if prog < self.status[5] or prog > self.status[6]:
- raise Error, 'range error'
- start = self.pmsf2msf(prog, min, sec, frame)
- elif l != 3:
- raise Error, 'syntax error'
- self.list.append((start, end))
-
- def settracks(self, list):
- self.list = []
- for track in list:
- self.appendtrack(track)
-
- def setcallback(self, cb_type, func, arg):
- if cb_type < 0 or cb_type >= 8:
- raise Error, 'type out of range'
- self.callbacks[cb_type] = (func, arg)
- if self.playing:
- start, end = self.list[self.listindex]
- if type(end) == type(0):
- if cb_type != CD.PNUM:
- self.parser.setcallback(cb_type, func, arg)
- else:
- if cb_type != CD.ATIME:
- self.parser.setcallback(cb_type, func, arg)
-
- def removecallback(self, cb_type):
- if cb_type < 0 or cb_type >= 8:
- raise Error, 'type out of range'
- self.callbacks[cb_type] = (None, None)
- if self.playing:
- start, end = self.list[self.listindex]
- if type(end) == type(0):
- if cb_type != CD.PNUM:
- self.parser.removecallback(cb_type)
- else:
- if cb_type != CD.ATIME:
- self.parser.removecallback(cb_type)
-
- def gettrackinfo(self, *arg):
- if not self.status:
- self.cachestatus()
- if not self.trackinfo:
- self.cacheinfo()
- if len(arg) == 0:
- return self.trackinfo[self.status[5]:self.status[6]+1]
- result = []
- for i in arg:
- if i < self.status[5] or i > self.status[6]:
- raise Error, 'range error'
- result.append(self.trackinfo[i])
- return result
-
- def cacheinfo(self):
- if not self.status:
- self.cachestatus()
- self.trackinfo = []
- for i in range(self.status[5]):
- self.trackinfo.append(None)
- for i in range(self.status[5], self.status[6]+1):
- self.trackinfo.append(self.player.gettrackinfo(i))
-
- def cachestatus(self):
- self.status = self.player.getstatus()
- if self.status[0] == CD.NODISC:
- self.status = None
- raise Error, 'no disc in player'
-
- def getstatus(self):
- return self.player.getstatus()
-
- def play(self):
- if not self.status:
- self.cachestatus()
- size = self.player.bestreadsize()
- self.listindex = 0
- self.playing = 0
- for i in range(8):
- func, arg = self.callbacks[i]
- if func:
- self.parser.setcallback(i, func, arg)
- else:
- self.parser.removecallback(i)
- if len(self.list) == 0:
- for i in range(self.status[5], self.status[6]+1):
- self.appendtrack(i)
- try:
- while 1:
- if not self.playing:
- if self.listindex >= len(self.list):
- return
- start, end = self.list[self.listindex]
- if type(start) == type(0):
- dummy = self.player.seektrack(
- start)
- else:
- min, sec, frame = start
- dummy = self.player.seek(
- min, sec, frame)
- if type(end) == type(0):
- self.parser.setcallback(
- CD.PNUM, _dopnum, self)
- self.end = end
- func, arg = \
- self.callbacks[CD.ATIME]
- if func:
- self.parser.setcallback(CD.ATIME, func, arg)
- else:
- self.parser.removecallback(CD.ATIME)
- else:
- min, sec, frame = end
- self.parser.setcallback(
- CD.ATIME, _doatime,
- self)
- self.end = (min * 60 + sec) * \
- 75 + frame
- func, arg = \
- self.callbacks[CD.PNUM]
- if func:
- self.parser.setcallback(CD.PNUM, func, arg)
- else:
- self.parser.removecallback(CD.PNUM)
- self.playing = 1
- data = self.player.readda(size)
- if data == '':
- self.playing = 0
- self.listindex = self.listindex + 1
- continue
- try:
- self.parser.parseframe(data)
- except _Stop:
- self.playing = 0
- self.listindex = self.listindex + 1
- finally:
- self.playing = 0
+ def __init__(self, *arg):
+ if len(arg) == 0:
+ self.player = cd.open()
+ elif len(arg) == 1:
+ self.player = cd.open(arg[0])
+ elif len(arg) == 2:
+ self.player = cd.open(arg[0], arg[1])
+ else:
+ raise Error, 'bad __init__ call'
+ self.list = []
+ self.callbacks = [(None, None)] * 8
+ self.parser = cd.createparser()
+ self.playing = 0
+ self.end = 0
+ self.status = None
+ self.trackinfo = None
+
+ def eject(self):
+ self.player.eject()
+ self.list = []
+ self.end = 0
+ self.listindex = 0
+ self.status = None
+ self.trackinfo = None
+ if self.playing:
+## print 'stop playing from eject'
+ raise _Stop
+
+ def pmsf2msf(self, track, min, sec, frame):
+ if not self.status:
+ self.cachestatus()
+ if track < self.status[5] or track > self.status[6]:
+ raise Error, 'track number out of range'
+ if not self.trackinfo:
+ self.cacheinfo()
+ start, total = self.trackinfo[track]
+ start = ((start[0] * 60) + start[1]) * 75 + start[2]
+ total = ((total[0] * 60) + total[1]) * 75 + total[2]
+ block = ((min * 60) + sec) * 75 + frame
+ if block > total:
+ raise Error, 'out of range'
+ block = start + block
+ min, block = divmod(block, 75*60)
+ sec, frame = divmod(block, 75)
+ return min, sec, frame
+
+ def reset(self):
+ self.list = []
+
+ def appendtrack(self, track):
+ self.appendstretch(track, track)
+
+ def appendstretch(self, start, end):
+ if not self.status:
+ self.cachestatus()
+ if not start:
+ start = 1
+ if not end:
+ end = self.status[6]
+ if type(end) == type(0):
+ if end < self.status[5] or end > self.status[6]:
+ raise Error, 'range error'
+ else:
+ l = len(end)
+ if l == 4:
+ prog, min, sec, frame = end
+ if prog < self.status[5] or prog > self.status[6]:
+ raise Error, 'range error'
+ end = self.pmsf2msf(prog, min, sec, frame)
+ elif l != 3:
+ raise Error, 'syntax error'
+ if type(start) == type(0):
+ if start < self.status[5] or start > self.status[6]:
+ raise Error, 'range error'
+ if len(self.list) > 0:
+ s, e = self.list[-1]
+ if type(e) == type(0):
+ if start == e+1:
+ start = s
+ del self.list[-1]
+ else:
+ l = len(start)
+ if l == 4:
+ prog, min, sec, frame = start
+ if prog < self.status[5] or prog > self.status[6]:
+ raise Error, 'range error'
+ start = self.pmsf2msf(prog, min, sec, frame)
+ elif l != 3:
+ raise Error, 'syntax error'
+ self.list.append((start, end))
+
+ def settracks(self, list):
+ self.list = []
+ for track in list:
+ self.appendtrack(track)
+
+ def setcallback(self, cb_type, func, arg):
+ if cb_type < 0 or cb_type >= 8:
+ raise Error, 'type out of range'
+ self.callbacks[cb_type] = (func, arg)
+ if self.playing:
+ start, end = self.list[self.listindex]
+ if type(end) == type(0):
+ if cb_type != CD.PNUM:
+ self.parser.setcallback(cb_type, func, arg)
+ else:
+ if cb_type != CD.ATIME:
+ self.parser.setcallback(cb_type, func, arg)
+
+ def removecallback(self, cb_type):
+ if cb_type < 0 or cb_type >= 8:
+ raise Error, 'type out of range'
+ self.callbacks[cb_type] = (None, None)
+ if self.playing:
+ start, end = self.list[self.listindex]
+ if type(end) == type(0):
+ if cb_type != CD.PNUM:
+ self.parser.removecallback(cb_type)
+ else:
+ if cb_type != CD.ATIME:
+ self.parser.removecallback(cb_type)
+
+ def gettrackinfo(self, *arg):
+ if not self.status:
+ self.cachestatus()
+ if not self.trackinfo:
+ self.cacheinfo()
+ if len(arg) == 0:
+ return self.trackinfo[self.status[5]:self.status[6]+1]
+ result = []
+ for i in arg:
+ if i < self.status[5] or i > self.status[6]:
+ raise Error, 'range error'
+ result.append(self.trackinfo[i])
+ return result
+
+ def cacheinfo(self):
+ if not self.status:
+ self.cachestatus()
+ self.trackinfo = []
+ for i in range(self.status[5]):
+ self.trackinfo.append(None)
+ for i in range(self.status[5], self.status[6]+1):
+ self.trackinfo.append(self.player.gettrackinfo(i))
+
+ def cachestatus(self):
+ self.status = self.player.getstatus()
+ if self.status[0] == CD.NODISC:
+ self.status = None
+ raise Error, 'no disc in player'
+
+ def getstatus(self):
+ return self.player.getstatus()
+
+ def play(self):
+ if not self.status:
+ self.cachestatus()
+ size = self.player.bestreadsize()
+ self.listindex = 0
+ self.playing = 0
+ for i in range(8):
+ func, arg = self.callbacks[i]
+ if func:
+ self.parser.setcallback(i, func, arg)
+ else:
+ self.parser.removecallback(i)
+ if len(self.list) == 0:
+ for i in range(self.status[5], self.status[6]+1):
+ self.appendtrack(i)
+ try:
+ while 1:
+ if not self.playing:
+ if self.listindex >= len(self.list):
+ return
+ start, end = self.list[self.listindex]
+ if type(start) == type(0):
+ dummy = self.player.seektrack(
+ start)
+ else:
+ min, sec, frame = start
+ dummy = self.player.seek(
+ min, sec, frame)
+ if type(end) == type(0):
+ self.parser.setcallback(
+ CD.PNUM, _dopnum, self)
+ self.end = end
+ func, arg = \
+ self.callbacks[CD.ATIME]
+ if func:
+ self.parser.setcallback(CD.ATIME, func, arg)
+ else:
+ self.parser.removecallback(CD.ATIME)
+ else:
+ min, sec, frame = end
+ self.parser.setcallback(
+ CD.ATIME, _doatime,
+ self)
+ self.end = (min * 60 + sec) * \
+ 75 + frame
+ func, arg = \
+ self.callbacks[CD.PNUM]
+ if func:
+ self.parser.setcallback(CD.PNUM, func, arg)
+ else:
+ self.parser.removecallback(CD.PNUM)
+ self.playing = 1
+ data = self.player.readda(size)
+ if data == '':
+ self.playing = 0
+ self.listindex = self.listindex + 1
+ continue
+ try:
+ self.parser.parseframe(data)
+ except _Stop:
+ self.playing = 0
+ self.listindex = self.listindex + 1
+ finally:
+ self.playing = 0
diff --git a/Lib/plat-irix6/torgb.py b/Lib/plat-irix6/torgb.py
index c2b1740f20..54c86c477d 100644
--- a/Lib/plat-irix6/torgb.py
+++ b/Lib/plat-irix6/torgb.py
@@ -51,49 +51,49 @@ uncompress.append('uncompress', '--')
class error(Exception):
- pass
+ pass
def torgb(filename):
- temps = []
- ret = None
- try:
- ret = _torgb(filename, temps)
- finally:
- for temp in temps[:]:
- if temp != ret:
- try:
- os.unlink(temp)
- except os.error:
- pass
- temps.remove(temp)
- return ret
+ temps = []
+ ret = None
+ try:
+ ret = _torgb(filename, temps)
+ finally:
+ for temp in temps[:]:
+ if temp != ret:
+ try:
+ os.unlink(temp)
+ except os.error:
+ pass
+ temps.remove(temp)
+ return ret
def _torgb(filename, temps):
- if filename[-2:] == '.Z':
- (fd, fname) = tempfile.mkstemp()
- os.close(fd)
- temps.append(fname)
- sts = uncompress.copy(filename, fname)
- if sts:
- raise error, filename + ': uncompress failed'
- else:
- fname = filename
- try:
- ftype = imghdr.what(fname)
- except IOError, msg:
- if type(msg) == type(()) and len(msg) == 2 and \
- type(msg[0]) == type(0) and type(msg[1]) == type(''):
- msg = msg[1]
- if type(msg) is not type(''):
- msg = repr(msg)
- raise error, filename + ': ' + msg
- if ftype == 'rgb':
- return fname
- if ftype is None or not table.has_key(ftype):
- raise error, '%s: unsupported image file type %r' % (filename, ftype)
- (fd, temp) = tempfile.mkstemp()
- os.close(fd)
- sts = table[ftype].copy(fname, temp)
- if sts:
- raise error, filename + ': conversion to rgb failed'
- return temp
+ if filename[-2:] == '.Z':
+ (fd, fname) = tempfile.mkstemp()
+ os.close(fd)
+ temps.append(fname)
+ sts = uncompress.copy(filename, fname)
+ if sts:
+ raise error, filename + ': uncompress failed'
+ else:
+ fname = filename
+ try:
+ ftype = imghdr.what(fname)
+ except IOError, msg:
+ if type(msg) == type(()) and len(msg) == 2 and \
+ type(msg[0]) == type(0) and type(msg[1]) == type(''):
+ msg = msg[1]
+ if type(msg) is not type(''):
+ msg = repr(msg)
+ raise error, filename + ': ' + msg
+ if ftype == 'rgb':
+ return fname
+ if ftype is None or not table.has_key(ftype):
+ raise error, '%s: unsupported image file type %r' % (filename, ftype)
+ (fd, temp) = tempfile.mkstemp()
+ os.close(fd)
+ sts = table[ftype].copy(fname, temp)
+ if sts:
+ raise error, filename + ': conversion to rgb failed'
+ return temp
diff --git a/Lib/plat-linux2/DLFCN.py b/Lib/plat-linux2/DLFCN.py
index 16ec538ac0..e23340a13d 100644
--- a/Lib/plat-linux2/DLFCN.py
+++ b/Lib/plat-linux2/DLFCN.py
@@ -61,11 +61,11 @@ __flexarr = []
__flexarr = [1]
def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
-def __attribute__(xyz): return
+def __attribute__(xyz): return
def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x)))
-def __attribute_format_arg__(x): return
+def __attribute_format_arg__(x): return
__USE_LARGEFILE = 1
__USE_LARGEFILE64 = 1
diff --git a/Lib/plat-linux2/IN.py b/Lib/plat-linux2/IN.py
index c63c15e707..2020b033ac 100644
--- a/Lib/plat-linux2/IN.py
+++ b/Lib/plat-linux2/IN.py
@@ -61,11 +61,11 @@ __flexarr = []
__flexarr = [1]
def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
-def __attribute__(xyz): return
+def __attribute__(xyz): return
def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x)))
-def __attribute_format_arg__(x): return
+def __attribute_format_arg__(x): return
__USE_LARGEFILE = 1
__USE_LARGEFILE64 = 1
@@ -613,4 +613,3 @@ def IN6_IS_ADDR_MC_SITELOCAL(a): return \
def IN6_IS_ADDR_MC_ORGLOCAL(a): return \
def IN6_IS_ADDR_MC_GLOBAL(a): return \
-
diff --git a/Lib/plat-linux2/TYPES.py b/Lib/plat-linux2/TYPES.py
index 2006bfce50..0cdd5995de 100644
--- a/Lib/plat-linux2/TYPES.py
+++ b/Lib/plat-linux2/TYPES.py
@@ -61,11 +61,11 @@ __flexarr = []
__flexarr = [1]
def __ASMNAME(cname): return __ASMNAME2 (__USER_LABEL_PREFIX__, cname)
-def __attribute__(xyz): return
+def __attribute__(xyz): return
def __attribute_format_arg__(x): return __attribute__ ((__format_arg__ (x)))
-def __attribute_format_arg__(x): return
+def __attribute_format_arg__(x): return
__USE_LARGEFILE = 1
__USE_LARGEFILE64 = 1
@@ -168,4 +168,3 @@ def minor(dev): return ((dev).__val[1] & 0xff)
def major(dev): return (((dev).__val[0] >> 8) & 0xff)
def minor(dev): return ((dev).__val[0] & 0xff)
-
diff --git a/Lib/plat-mac/Audio_mac.py b/Lib/plat-mac/Audio_mac.py
index 5350e5588c..fd96095ad6 100644
--- a/Lib/plat-mac/Audio_mac.py
+++ b/Lib/plat-mac/Audio_mac.py
@@ -81,7 +81,7 @@ class Play_Audio_mac:
del self._gc[0]
if self._usercallback:
self._usercallback()
-
+
def setcallback(self, callback):
self._usercallback = callback
diff --git a/Lib/plat-mac/Carbon/Aliases.py b/Lib/plat-mac/Carbon/Aliases.py
index 1211e3d6e9..55e1a1f5a7 100644
--- a/Lib/plat-mac/Carbon/Aliases.py
+++ b/Lib/plat-mac/Carbon/Aliases.py
@@ -3,16 +3,16 @@
def FOUR_CHAR_CODE(x): return x
true = True
false = False
-rAliasType = FOUR_CHAR_CODE('alis')
+rAliasType = FOUR_CHAR_CODE('alis')
kARMMountVol = 0x00000001
kARMNoUI = 0x00000002
kARMMultVols = 0x00000008
kARMSearch = 0x00000100
kARMSearchMore = 0x00000200
-kARMSearchRelFirst = 0x00000400
+kARMSearchRelFirst = 0x00000400
asiZoneName = -3
asiServerName = -2
asiVolumeName = -1
asiAliasName = 0
-asiParentName = 1
-kResolveAliasFileNoUI = 0x00000001
+asiParentName = 1
+kResolveAliasFileNoUI = 0x00000001
diff --git a/Lib/plat-mac/Carbon/Appearance.py b/Lib/plat-mac/Carbon/Appearance.py
index e42e531bf7..d99c6dce0a 100644
--- a/Lib/plat-mac/Carbon/Appearance.py
+++ b/Lib/plat-mac/Carbon/Appearance.py
@@ -5,7 +5,7 @@ kAppearanceEventClass = FOUR_CHAR_CODE('appr')
kAEAppearanceChanged = FOUR_CHAR_CODE('thme')
kAESystemFontChanged = FOUR_CHAR_CODE('sysf')
kAESmallSystemFontChanged = FOUR_CHAR_CODE('ssfn')
-kAEViewsFontChanged = FOUR_CHAR_CODE('vfnt')
+kAEViewsFontChanged = FOUR_CHAR_CODE('vfnt')
kThemeDataFileType = FOUR_CHAR_CODE('thme')
kThemePlatinumFileType = FOUR_CHAR_CODE('pltn')
kThemeCustomThemesFileType = FOUR_CHAR_CODE('scen')
@@ -64,12 +64,12 @@ kThemeBrushDrawerBackground = 51
kThemeBrushToolbarBackground = 52
kThemeBrushSheetBackgroundTransparent = 53
kThemeBrushMenuBackground = 54
-kThemeBrushMenuBackgroundSelected = 55
+kThemeBrushMenuBackgroundSelected = 55
kThemeBrushSheetBackground = kThemeBrushSheetBackgroundOpaque
kThemeBrushBlack = -1
kThemeBrushWhite = -2
kThemeBrushPrimaryHighlightColor = -3
-kThemeBrushSecondaryHighlightColor = -4
+kThemeBrushSecondaryHighlightColor = -4
kThemeTextColorDialogActive = 1
kThemeTextColorDialogInactive = 2
kThemeTextColorAlertActive = 3
@@ -127,7 +127,7 @@ kThemeStateUnavailable = 7
kThemeStateUnavailableInactive = 8
kThemeStateDisabled = 0
kThemeStatePressedUp = 2
-kThemeStatePressedDown = 3
+kThemeStatePressedDown = 3
kThemeArrowCursor = 0
kThemeCopyArrowCursor = 1
kThemeAliasArrowCursor = 2
@@ -165,7 +165,7 @@ kThemeMenuItemAtBottom = 0x0200
kThemeMenuItemHierBackground = 0x0400
kThemeMenuItemPopUpBackground = 0x0800
kThemeMenuItemHasIcon = 0x8000
-kThemeMenuItemNoBackground = 0x4000
+kThemeMenuItemNoBackground = 0x4000
kThemeBackgroundTabPane = 1
kThemeBackgroundPlacard = 2
kThemeBackgroundWindowHeader = 3
@@ -178,7 +178,7 @@ kThemeHighlightColorTag = FOUR_CHAR_CODE('hcol')
kThemeScrollBarArrowStyleTag = FOUR_CHAR_CODE('sbar')
kThemeScrollBarThumbStyleTag = FOUR_CHAR_CODE('sbth')
kThemeSoundsEnabledTag = FOUR_CHAR_CODE('snds')
-kThemeDblClickCollapseTag = FOUR_CHAR_CODE('coll')
+kThemeDblClickCollapseTag = FOUR_CHAR_CODE('coll')
kThemeAppearanceFileNameTag = FOUR_CHAR_CODE('thme')
kThemeSystemFontTag = FOUR_CHAR_CODE('lgsf')
kThemeSmallSystemFontTag = FOUR_CHAR_CODE('smsf')
@@ -195,18 +195,18 @@ kThemeSoundTrackNameTag = FOUR_CHAR_CODE('sndt')
kThemeSoundMaskTag = FOUR_CHAR_CODE('smsk')
kThemeUserDefinedTag = FOUR_CHAR_CODE('user')
kThemeSmoothFontEnabledTag = FOUR_CHAR_CODE('smoo')
-kThemeSmoothFontMinSizeTag = FOUR_CHAR_CODE('smos')
+kThemeSmoothFontMinSizeTag = FOUR_CHAR_CODE('smos')
kTiledOnScreen = 1
kCenterOnScreen = 2
kFitToScreen = 3
kFillScreen = 4
-kUseBestGuess = 5
+kUseBestGuess = 5
kThemeCheckBoxClassicX = 0
-kThemeCheckBoxCheckMark = 1
+kThemeCheckBoxCheckMark = 1
kThemeScrollBarArrowsSingle = 0
-kThemeScrollBarArrowsLowerRight = 1
+kThemeScrollBarArrowsLowerRight = 1
kThemeScrollBarThumbNormal = 0
-kThemeScrollBarThumbProportional = 1
+kThemeScrollBarThumbProportional = 1
kThemeSystemFont = 0
kThemeSmallSystemFont = 1
kThemeSmallEmphasizedSystemFont = 2
@@ -238,7 +238,7 @@ kThemeSmallTabHeight = 16
kThemeLargeTabHeight = 21
kThemeTabPaneOverlap = 3
kThemeSmallTabHeightMax = 19
-kThemeLargeTabHeightMax = 24
+kThemeLargeTabHeightMax = 24
kThemeMediumScrollBar = 0
kThemeSmallScrollBar = 1
kThemeMediumSlider = 2
@@ -309,7 +309,7 @@ kThemeArrow9pt = 3
kThemeGrowLeft = (1 << 0)
kThemeGrowRight = (1 << 1)
kThemeGrowUp = (1 << 2)
-kThemeGrowDown = (1 << 3)
+kThemeGrowDown = (1 << 3)
kThemePushButton = 0
kThemeCheckBox = 1
kThemeRadioButton = 2
@@ -351,7 +351,7 @@ kThemeAdornmentShadowOnly = kThemeAdornmentHeaderButtonShadowOnly
kThemeAdornmentArrowLeftArrow = (1 << 6)
kThemeAdornmentArrowDownArrow = (1 << 7)
kThemeAdornmentArrowDoubleArrow = (1 << 8)
-kThemeAdornmentArrowUpArrow = (1 << 9)
+kThemeAdornmentArrowUpArrow = (1 << 9)
kThemeNoSounds = 0
kThemeWindowSoundsMask = (1 << 0)
kThemeMenuSoundsMask = (1 << 1)
@@ -629,7 +629,7 @@ kThemeSelectedMenuItemTextColor = kThemeTextColorMenuItemSelected
kThemeDisabledMenuItemTextColor = kThemeTextColorMenuItemDisabled
kThemeActivePopupLabelTextColor = kThemeTextColorPopupLabelActive
kThemeInactivePopupLabelTextColor = kThemeTextColorPopupLabelInactive
-kAEThemeSwitch = kAEAppearanceChanged
+kAEThemeSwitch = kAEAppearanceChanged
kThemeNoAdornment = kThemeAdornmentNone
kThemeDefaultAdornment = kThemeAdornmentDefault
kThemeFocusAdornment = kThemeAdornmentFocus
@@ -641,7 +641,7 @@ kThemeMetricRadioButtonGlyphHeight = kThemeMetricRadioButtonHeight
kThemeMetricDisclosureButtonSize = kThemeMetricDisclosureButtonHeight
kThemeMetricBestListHeaderHeight = kThemeMetricListHeaderHeight
kThemeMetricSmallProgressBarThickness = kThemeMetricNormalProgressBarThickness
-kThemeMetricProgressBarThickness = kThemeMetricLargeProgressBarThickness
+kThemeMetricProgressBarThickness = kThemeMetricLargeProgressBarThickness
kThemeScrollBar = kThemeMediumScrollBar
kThemeSlider = kThemeMediumSlider
kThemeProgressBar = kThemeMediumProgressBar
diff --git a/Lib/plat-mac/Carbon/AppleEvents.py b/Lib/plat-mac/Carbon/AppleEvents.py
index 7253a3eac7..e23c0797a5 100644
--- a/Lib/plat-mac/Carbon/AppleEvents.py
+++ b/Lib/plat-mac/Carbon/AppleEvents.py
@@ -44,7 +44,7 @@ typeQDRectangle = FOUR_CHAR_CODE('qdrt')
typeFixed = FOUR_CHAR_CODE('fixd')
typeProcessSerialNumber = FOUR_CHAR_CODE('psn ')
typeApplicationURL = FOUR_CHAR_CODE('aprl')
-typeNull = FOUR_CHAR_CODE('null')
+typeNull = FOUR_CHAR_CODE('null')
typeSessionID = FOUR_CHAR_CODE('ssid')
typeTargetID = FOUR_CHAR_CODE('targ')
typeDispatcherID = FOUR_CHAR_CODE('dspt')
@@ -59,19 +59,19 @@ keyInteractLevelAttr = FOUR_CHAR_CODE('inte')
keyEventSourceAttr = FOUR_CHAR_CODE('esrc')
keyMissedKeywordAttr = FOUR_CHAR_CODE('miss')
keyOriginalAddressAttr = FOUR_CHAR_CODE('from')
-keyAcceptTimeoutAttr = FOUR_CHAR_CODE('actm')
+keyAcceptTimeoutAttr = FOUR_CHAR_CODE('actm')
kAEDescListFactorNone = 0
kAEDescListFactorType = 4
kAEDescListFactorTypeAndSize = 8
kAutoGenerateReturnID = -1
-kAnyTransactionID = 0
+kAnyTransactionID = 0
kAEDataArray = 0
kAEPackedArray = 1
kAEDescArray = 3
kAEKeyDescArray = 4
kAEHandleArray = 2
kAENormalPriority = 0x00000000
-kAEHighPriority = 0x00000001
+kAEHighPriority = 0x00000001
kAENoReply = 0x00000001
kAEQueueReply = 0x00000002
kAEWaitReply = 0x00000003
@@ -83,9 +83,9 @@ kAEAlwaysInteract = 0x00000030
kAECanSwitchLayer = 0x00000040
kAEDontRecord = 0x00001000
kAEDontExecute = 0x00002000
-kAEProcessNonReplyEvents = 0x00008000
+kAEProcessNonReplyEvents = 0x00008000
kAEDefaultTimeout = -1
-kNoTimeOut = -2
+kNoTimeOut = -2
kAEInteractWithSelf = 0
kAEInteractWithLocal = 1
kAEInteractWithAll = 2
@@ -95,9 +95,9 @@ kAEIgnoreAppEventHandler = 0x00000002
kAEIgnoreSysPhacHandler = 0x00000004
kAEIgnoreSysEventHandler = 0x00000008
kAEIngoreBuiltInEventHandler = 0x00000010
-# kAEDontDisposeOnResume = (long)0x80000000
+# kAEDontDisposeOnResume = (long)0x80000000
kAENoDispatch = 0
-# kAEUseStandardDispatch = (long)0xFFFFFFFF
+# kAEUseStandardDispatch = (long)0xFFFFFFFF
keyDirectObject = FOUR_CHAR_CODE('----')
keyErrorNumber = FOUR_CHAR_CODE('errn')
keyErrorString = FOUR_CHAR_CODE('errs')
@@ -105,7 +105,7 @@ keyProcessSerialNumber = FOUR_CHAR_CODE('psn ')
keyPreDispatch = FOUR_CHAR_CODE('phac')
keySelectProc = FOUR_CHAR_CODE('selh')
keyAERecorderCount = FOUR_CHAR_CODE('recr')
-keyAEVersion = FOUR_CHAR_CODE('vers')
+keyAEVersion = FOUR_CHAR_CODE('vers')
kCoreEventClass = FOUR_CHAR_CODE('aevt')
kAEOpenApplication = FOUR_CHAR_CODE('oapp')
kAEOpenDocuments = FOUR_CHAR_CODE('odoc')
@@ -113,12 +113,12 @@ kAEPrintDocuments = FOUR_CHAR_CODE('pdoc')
kAEQuitApplication = FOUR_CHAR_CODE('quit')
kAEAnswer = FOUR_CHAR_CODE('ansr')
kAEApplicationDied = FOUR_CHAR_CODE('obit')
-kAEShowPreferences = FOUR_CHAR_CODE('pref')
+kAEShowPreferences = FOUR_CHAR_CODE('pref')
kAEStartRecording = FOUR_CHAR_CODE('reca')
kAEStopRecording = FOUR_CHAR_CODE('recc')
kAENotifyStartRecording = FOUR_CHAR_CODE('rec1')
kAENotifyStopRecording = FOUR_CHAR_CODE('rec0')
-kAENotifyRecording = FOUR_CHAR_CODE('recr')
+kAENotifyRecording = FOUR_CHAR_CODE('recr')
kAEUnknownSource = 0
kAEDirectCall = 1
kAESameProcess = 2
@@ -143,7 +143,7 @@ cGraphicLine = FOUR_CHAR_CODE('glin')
cGraphicObject = FOUR_CHAR_CODE('cgob')
cGraphicShape = FOUR_CHAR_CODE('cgsh')
cGraphicText = FOUR_CHAR_CODE('cgtx')
-cGroupedGraphic = FOUR_CHAR_CODE('cpic')
+cGroupedGraphic = FOUR_CHAR_CODE('cpic')
cInsertionLoc = FOUR_CHAR_CODE('insl')
cInsertionPoint = FOUR_CHAR_CODE('cins')
cIntlText = FOUR_CHAR_CODE('itxt')
@@ -163,7 +163,7 @@ cMenuItem = FOUR_CHAR_CODE('cmen')
cObject = FOUR_CHAR_CODE('cobj')
cObjectSpecifier = FOUR_CHAR_CODE('obj ')
cOpenableObject = FOUR_CHAR_CODE('coob')
-cOval = FOUR_CHAR_CODE('covl')
+cOval = FOUR_CHAR_CODE('covl')
cParagraph = FOUR_CHAR_CODE('cpar')
cPICT = FOUR_CHAR_CODE('PICT')
cPixel = FOUR_CHAR_CODE('cpxl')
@@ -183,7 +183,7 @@ cTable = FOUR_CHAR_CODE('ctbl')
cText = FOUR_CHAR_CODE('ctxt')
cTextFlow = FOUR_CHAR_CODE('cflo')
cTextStyles = FOUR_CHAR_CODE('tsty')
-cType = FOUR_CHAR_CODE('type')
+cType = FOUR_CHAR_CODE('type')
cVersion = FOUR_CHAR_CODE('vers')
cWindow = FOUR_CHAR_CODE('cwin')
cWord = FOUR_CHAR_CODE('cwor')
@@ -203,7 +203,7 @@ kAEAliasSelection = FOUR_CHAR_CODE('sali')
kAEAllCaps = FOUR_CHAR_CODE('alcp')
kAEArrowAtEnd = FOUR_CHAR_CODE('aren')
kAEArrowAtStart = FOUR_CHAR_CODE('arst')
-kAEArrowBothEnds = FOUR_CHAR_CODE('arbo')
+kAEArrowBothEnds = FOUR_CHAR_CODE('arbo')
kAEAsk = FOUR_CHAR_CODE('ask ')
kAEBefore = FOUR_CHAR_CODE('befo')
kAEBeginning = FOUR_CHAR_CODE('bgng')
@@ -223,7 +223,7 @@ kAECountElements = FOUR_CHAR_CODE('cnte')
kAECreateElement = FOUR_CHAR_CODE('crel')
kAECreatePublisher = FOUR_CHAR_CODE('cpub')
kAECut = FOUR_CHAR_CODE('cut ')
-kAEDelete = FOUR_CHAR_CODE('delo')
+kAEDelete = FOUR_CHAR_CODE('delo')
kAEDoObjectsExist = FOUR_CHAR_CODE('doex')
kAEDoScript = FOUR_CHAR_CODE('dosc')
kAEDrag = FOUR_CHAR_CODE('drag')
@@ -243,7 +243,7 @@ kAEGetClassInfo = FOUR_CHAR_CODE('qobj')
kAEGetData = FOUR_CHAR_CODE('getd')
kAEGetDataSize = FOUR_CHAR_CODE('dsiz')
kAEGetEventInfo = FOUR_CHAR_CODE('gtei')
-kAEGetInfoSelection = FOUR_CHAR_CODE('sinf')
+kAEGetInfoSelection = FOUR_CHAR_CODE('sinf')
kAEGetPrivilegeSelection = FOUR_CHAR_CODE('sprv')
kAEGetSuiteInfo = FOUR_CHAR_CODE('gtsi')
kAEGreaterThan = FOUR_CHAR_CODE('> ')
@@ -263,7 +263,7 @@ kAEMiscStandards = FOUR_CHAR_CODE('misc')
kAEModifiable = FOUR_CHAR_CODE('modf')
kAEMove = FOUR_CHAR_CODE('move')
kAENo = FOUR_CHAR_CODE('no ')
-kAENoArrow = FOUR_CHAR_CODE('arno')
+kAENoArrow = FOUR_CHAR_CODE('arno')
kAENonmodifiable = FOUR_CHAR_CODE('nmod')
kAEOpen = FOUR_CHAR_CODE('odoc')
kAEOpenSelection = FOUR_CHAR_CODE('sope')
@@ -283,7 +283,7 @@ kAEQDBic = FOUR_CHAR_CODE('bic ')
kAEQDBlend = FOUR_CHAR_CODE('blnd')
kAEQDCopy = FOUR_CHAR_CODE('cpy ')
kAEQDNotBic = FOUR_CHAR_CODE('nbic')
-kAEQDNotCopy = FOUR_CHAR_CODE('ncpy')
+kAEQDNotCopy = FOUR_CHAR_CODE('ncpy')
kAEQDNotOr = FOUR_CHAR_CODE('ntor')
kAEQDNotXor = FOUR_CHAR_CODE('nxor')
kAEQDOr = FOUR_CHAR_CODE('or ')
@@ -304,7 +304,7 @@ kAERevert = FOUR_CHAR_CODE('rvrt')
kAERightJustified = FOUR_CHAR_CODE('rght')
kAESave = FOUR_CHAR_CODE('save')
kAESelect = FOUR_CHAR_CODE('slct')
-kAESetData = FOUR_CHAR_CODE('setd')
+kAESetData = FOUR_CHAR_CODE('setd')
kAESetPosition = FOUR_CHAR_CODE('posn')
kAEShadow = FOUR_CHAR_CODE('shad')
kAEShowClipboard = FOUR_CHAR_CODE('shcl')
@@ -322,7 +322,7 @@ kAEUnderline = FOUR_CHAR_CODE('undl')
kAEUndo = FOUR_CHAR_CODE('undo')
kAEWholeWordEquals = FOUR_CHAR_CODE('wweq')
kAEYes = FOUR_CHAR_CODE('yes ')
-kAEZoom = FOUR_CHAR_CODE('zoom')
+kAEZoom = FOUR_CHAR_CODE('zoom')
kAEMouseClass = FOUR_CHAR_CODE('mous')
kAEDown = FOUR_CHAR_CODE('down')
kAEUp = FOUR_CHAR_CODE('up ')
@@ -347,7 +347,7 @@ kAEWakeUpEvent = FOUR_CHAR_CODE('wake')
kAEScrapEvent = FOUR_CHAR_CODE('scrp')
kAEHighLevel = FOUR_CHAR_CODE('high')
keyAEAngle = FOUR_CHAR_CODE('kang')
-keyAEArcAngle = FOUR_CHAR_CODE('parc')
+keyAEArcAngle = FOUR_CHAR_CODE('parc')
keyAEBaseAddr = FOUR_CHAR_CODE('badd')
keyAEBestType = FOUR_CHAR_CODE('pbst')
keyAEBgndColor = FOUR_CHAR_CODE('kbcl')
@@ -367,7 +367,7 @@ keyAEDescType = FOUR_CHAR_CODE('dstp')
keyAEDestination = FOUR_CHAR_CODE('dest')
keyAEDoAntiAlias = FOUR_CHAR_CODE('anta')
keyAEDoDithered = FOUR_CHAR_CODE('gdit')
-keyAEDoRotate = FOUR_CHAR_CODE('kdrt')
+keyAEDoRotate = FOUR_CHAR_CODE('kdrt')
keyAEDoScale = FOUR_CHAR_CODE('ksca')
keyAEDoTranslate = FOUR_CHAR_CODE('ktra')
keyAEEditionFileLoc = FOUR_CHAR_CODE('eloc')
@@ -387,7 +387,7 @@ keyAEGraphicObjects = FOUR_CHAR_CODE('gobs')
keyAEID = FOUR_CHAR_CODE('ID ')
keyAEImageQuality = FOUR_CHAR_CODE('gqua')
keyAEInsertHere = FOUR_CHAR_CODE('insh')
-keyAEKeyForms = FOUR_CHAR_CODE('keyf')
+keyAEKeyForms = FOUR_CHAR_CODE('keyf')
keyAEKeyword = FOUR_CHAR_CODE('kywd')
keyAELevel = FOUR_CHAR_CODE('levl')
keyAELineArrow = FOUR_CHAR_CODE('arro')
@@ -407,7 +407,7 @@ keyAEPixMapMinus = FOUR_CHAR_CODE('kpmm')
keyAEPMTable = FOUR_CHAR_CODE('kpmt')
keyAEPointList = FOUR_CHAR_CODE('ptlt')
keyAEPointSize = FOUR_CHAR_CODE('ptsz')
-keyAEPosition = FOUR_CHAR_CODE('kpos')
+keyAEPosition = FOUR_CHAR_CODE('kpos')
keyAEPropData = FOUR_CHAR_CODE('prdt')
keyAEProperties = FOUR_CHAR_CODE('qpro')
keyAEProperty = FOUR_CHAR_CODE('kprp')
@@ -427,7 +427,7 @@ keyAEScriptTag = FOUR_CHAR_CODE('psct')
keyAEShowWhere = FOUR_CHAR_CODE('show')
keyAEStartAngle = FOUR_CHAR_CODE('pang')
keyAEStartPoint = FOUR_CHAR_CODE('pstp')
-keyAEStyles = FOUR_CHAR_CODE('ksty')
+keyAEStyles = FOUR_CHAR_CODE('ksty')
keyAESuiteID = FOUR_CHAR_CODE('suit')
keyAEText = FOUR_CHAR_CODE('ktxt')
keyAETextColor = FOUR_CHAR_CODE('ptxc')
@@ -444,7 +444,7 @@ keyAEUniformStyles = FOUR_CHAR_CODE('ustl')
keyAEUpdateOn = FOUR_CHAR_CODE('pupd')
keyAEUserTerm = FOUR_CHAR_CODE('utrm')
keyAEWindow = FOUR_CHAR_CODE('wndw')
-keyAEWritingCode = FOUR_CHAR_CODE('wrcd')
+keyAEWritingCode = FOUR_CHAR_CODE('wrcd')
keyMiscellaneous = FOUR_CHAR_CODE('fmsc')
keySelection = FOUR_CHAR_CODE('fsel')
keyWindow = FOUR_CHAR_CODE('kwnd')
@@ -477,7 +477,7 @@ pEnabled = FOUR_CHAR_CODE('enbl')
pEndPoint = FOUR_CHAR_CODE('pend')
pFillColor = FOUR_CHAR_CODE('flcl')
pFillPattern = FOUR_CHAR_CODE('flpt')
-pFont = FOUR_CHAR_CODE('font')
+pFont = FOUR_CHAR_CODE('font')
pFormula = FOUR_CHAR_CODE('pfor')
pGraphicObjects = FOUR_CHAR_CODE('gobs')
pHasCloseBox = FOUR_CHAR_CODE('hclb')
@@ -497,7 +497,7 @@ pItemNumber = FOUR_CHAR_CODE('itmn')
pJustification = FOUR_CHAR_CODE('pjst')
pLineArrow = FOUR_CHAR_CODE('arro')
pMenuID = FOUR_CHAR_CODE('mnid')
-pName = FOUR_CHAR_CODE('pnam')
+pName = FOUR_CHAR_CODE('pnam')
pNewElementLoc = FOUR_CHAR_CODE('pnel')
pPenColor = FOUR_CHAR_CODE('ppcl')
pPenPattern = FOUR_CHAR_CODE('pppa')
@@ -517,7 +517,7 @@ pStartPoint = FOUR_CHAR_CODE('pstp')
pTextColor = FOUR_CHAR_CODE('ptxc')
pTextFont = FOUR_CHAR_CODE('ptxf')
pTextItemDelimiters = FOUR_CHAR_CODE('txdl')
-pTextPointSize = FOUR_CHAR_CODE('ptps')
+pTextPointSize = FOUR_CHAR_CODE('ptps')
pTextStyles = FOUR_CHAR_CODE('txst')
pTransferMode = FOUR_CHAR_CODE('pptm')
pTranslation = FOUR_CHAR_CODE('ptrs')
@@ -525,7 +525,7 @@ pUniformStyles = FOUR_CHAR_CODE('ustl')
pUpdateOn = FOUR_CHAR_CODE('pupd')
pUserSelection = FOUR_CHAR_CODE('pusl')
pVersion = FOUR_CHAR_CODE('vers')
-pVisible = FOUR_CHAR_CODE('pvis')
+pVisible = FOUR_CHAR_CODE('pvis')
typeAEText = FOUR_CHAR_CODE('tTXT')
typeArc = FOUR_CHAR_CODE('carc')
typeBest = FOUR_CHAR_CODE('best')
@@ -539,7 +539,7 @@ typeDrawingArea = FOUR_CHAR_CODE('cdrw')
typeElemInfo = FOUR_CHAR_CODE('elin')
typeEnumeration = FOUR_CHAR_CODE('enum')
typeEPS = FOUR_CHAR_CODE('EPS ')
-typeEventInfo = FOUR_CHAR_CODE('evin')
+typeEventInfo = FOUR_CHAR_CODE('evin')
typeFinderWindow = FOUR_CHAR_CODE('fwin')
typeFixedPoint = FOUR_CHAR_CODE('fpnt')
typeFixedRectangle = FOUR_CHAR_CODE('frct')
@@ -558,7 +558,7 @@ typeLongRectangle = FOUR_CHAR_CODE('lrct')
typeMachineLoc = FOUR_CHAR_CODE('mLoc')
typeOval = FOUR_CHAR_CODE('covl')
typeParamInfo = FOUR_CHAR_CODE('pmin')
-typePict = FOUR_CHAR_CODE('PICT')
+typePict = FOUR_CHAR_CODE('PICT')
typePixelMap = FOUR_CHAR_CODE('cpix')
typePixMapMinus = FOUR_CHAR_CODE('tpmm')
typePolygon = FOUR_CHAR_CODE('cpgn')
@@ -578,9 +578,9 @@ typeScript = FOUR_CHAR_CODE('scpt')
typeStyledText = FOUR_CHAR_CODE('STXT')
typeSuiteInfo = FOUR_CHAR_CODE('suin')
typeTable = FOUR_CHAR_CODE('ctbl')
-typeTextStyles = FOUR_CHAR_CODE('tsty')
+typeTextStyles = FOUR_CHAR_CODE('tsty')
typeTIFF = FOUR_CHAR_CODE('TIFF')
-typeVersion = FOUR_CHAR_CODE('vers')
+typeVersion = FOUR_CHAR_CODE('vers')
kAEMenuClass = FOUR_CHAR_CODE('menu')
kAEMenuSelect = FOUR_CHAR_CODE('mhit')
kAEMouseDown = FOUR_CHAR_CODE('mdwn')
@@ -640,7 +640,7 @@ typeOffsetArray = FOUR_CHAR_CODE('ofay')
typeTextRangeArray = FOUR_CHAR_CODE('tray')
typeLowLevelEventRecord = FOUR_CHAR_CODE('evtr')
typeEventRef = FOUR_CHAR_CODE('evrf')
-typeText = typeChar
+typeText = typeChar
kTSMOutsideOfBody = 1
kTSMInsideOfBody = 2
kTSMInsideOfActiveInputArea = 3
@@ -653,7 +653,7 @@ kConvertedText = 4
kSelectedConvertedText = 5
kBlockFillText = 6
kOutlineText = 7
-kSelectedText = 8
+kSelectedText = 8
keyAEHiliteRange = FOUR_CHAR_CODE('hrng')
keyAEPinRange = FOUR_CHAR_CODE('pnrg')
keyAEClauseOffsets = FOUR_CHAR_CODE('clau')
@@ -661,7 +661,7 @@ keyAEOffset = FOUR_CHAR_CODE('ofst')
keyAEPoint = FOUR_CHAR_CODE('gpos')
keyAELeftSide = FOUR_CHAR_CODE('klef')
keyAERegionClass = FOUR_CHAR_CODE('rgnc')
-keyAEDragging = FOUR_CHAR_CODE('bool')
+keyAEDragging = FOUR_CHAR_CODE('bool')
keyAELeadingEdge = keyAELeftSide
typeUnicodeText = FOUR_CHAR_CODE('utxt')
typeStyledUnicodeText = FOUR_CHAR_CODE('sutx')
@@ -710,7 +710,7 @@ kFAAttachCommand = FOUR_CHAR_CODE('atfa')
kFARemoveCommand = FOUR_CHAR_CODE('rmfa')
kFAEditCommand = FOUR_CHAR_CODE('edfa')
kFAFileParam = FOUR_CHAR_CODE('faal')
-kFAIndexParam = FOUR_CHAR_CODE('indx')
+kFAIndexParam = FOUR_CHAR_CODE('indx')
kAEInternetSuite = FOUR_CHAR_CODE('gurl')
kAEISWebStarSuite = FOUR_CHAR_CODE('WWW\xbd')
kAEISGetURL = FOUR_CHAR_CODE('gurl')
@@ -917,7 +917,7 @@ keyAEObject2 = FOUR_CHAR_CODE('obj2')
keyAEDesiredClass = FOUR_CHAR_CODE('want')
keyAEContainer = FOUR_CHAR_CODE('from')
keyAEKeyForm = FOUR_CHAR_CODE('form')
-keyAEKeyData = FOUR_CHAR_CODE('seld')
+keyAEKeyData = FOUR_CHAR_CODE('seld')
keyAERangeStart = FOUR_CHAR_CODE('star')
keyAERangeStop = FOUR_CHAR_CODE('stop')
keyDisposeTokenProc = FOUR_CHAR_CODE('xtok')
@@ -926,7 +926,7 @@ keyAECountProc = FOUR_CHAR_CODE('cont')
keyAEMarkTokenProc = FOUR_CHAR_CODE('mkid')
keyAEMarkProc = FOUR_CHAR_CODE('mark')
keyAEAdjustMarksProc = FOUR_CHAR_CODE('adjm')
-keyAEGetErrDescProc = FOUR_CHAR_CODE('indc')
+keyAEGetErrDescProc = FOUR_CHAR_CODE('indc')
formAbsolutePosition = FOUR_CHAR_CODE('indx')
formRelativePosition = FOUR_CHAR_CODE('rele')
formTest = FOUR_CHAR_CODE('test')
@@ -943,7 +943,7 @@ typeIndexDescriptor = FOUR_CHAR_CODE('inde')
typeRangeDescriptor = FOUR_CHAR_CODE('rang')
typeLogicalDescriptor = FOUR_CHAR_CODE('logi')
typeCompDescriptor = FOUR_CHAR_CODE('cmpd')
-typeOSLTokenList = FOUR_CHAR_CODE('ostl')
+typeOSLTokenList = FOUR_CHAR_CODE('ostl')
kAEIDoMinimum = 0x0000
kAEIDoWhose = 0x0001
kAEIDoMarking = 0x0004
@@ -957,4 +957,4 @@ typeWhoseRange = FOUR_CHAR_CODE('wrng')
keyAEWhoseRangeStart = FOUR_CHAR_CODE('wstr')
keyAEWhoseRangeStop = FOUR_CHAR_CODE('wstp')
keyAEIndex = FOUR_CHAR_CODE('kidx')
-keyAETest = FOUR_CHAR_CODE('ktst')
+keyAETest = FOUR_CHAR_CODE('ktst')
diff --git a/Lib/plat-mac/Carbon/CarbonEvents.py b/Lib/plat-mac/Carbon/CarbonEvents.py
index ff4f69cda3..357ee5d388 100755
--- a/Lib/plat-mac/Carbon/CarbonEvents.py
+++ b/Lib/plat-mac/Carbon/CarbonEvents.py
@@ -71,9 +71,9 @@ kEventRawKeyRepeat = 2
kEventRawKeyUp = 3
kEventRawKeyModifiersChanged = 4
kEventHotKeyPressed = 5
-kEventHotKeyReleased = 6
+kEventHotKeyReleased = 6
kEventKeyModifierNumLockBit = 16
-kEventKeyModifierFnBit = 17
+kEventKeyModifierFnBit = 17
kEventKeyModifierNumLockMask = 1L << kEventKeyModifierNumLockBit
kEventKeyModifierFnMask = 1L << kEventKeyModifierFnBit
kEventAppActivated = 1
@@ -262,18 +262,18 @@ kControlBoundsChangeSizeChanged = (1 << 2)
kControlBoundsChangePositionChanged = (1 << 3)
kEventTabletPoint = 1
kEventTabletProximity = 2
-kEventTabletPointer = 1
+kEventTabletPointer = 1
kEventVolumeMounted = 1
-kEventVolumeUnmounted = 2
-typeFSVolumeRefNum = FOUR_CHAR_CODE('voln')
+kEventVolumeUnmounted = 2
+typeFSVolumeRefNum = FOUR_CHAR_CODE('voln')
kEventAppearanceScrollBarVariantChanged = 1
kEventServiceCopy = 1
kEventServicePaste = 2
kEventServiceGetTypes = 3
kEventServicePerform = 4
-kEventParamDirectObject = FOUR_CHAR_CODE('----')
+kEventParamDirectObject = FOUR_CHAR_CODE('----')
kEventParamPostTarget = FOUR_CHAR_CODE('ptrg')
-typeEventTargetRef = FOUR_CHAR_CODE('etrg')
+typeEventTargetRef = FOUR_CHAR_CODE('etrg')
kEventParamWindowRef = FOUR_CHAR_CODE('wind')
kEventParamGrafPort = FOUR_CHAR_CODE('graf')
kEventParamDragRef = FOUR_CHAR_CODE('drag')
@@ -304,7 +304,7 @@ typeCFTypeRef = FOUR_CHAR_CODE('cfty')
typeCGContextRef = FOUR_CHAR_CODE('cntx')
typeHIPoint = FOUR_CHAR_CODE('hipt')
typeHISize = FOUR_CHAR_CODE('hisz')
-typeHIRect = FOUR_CHAR_CODE('hirc')
+typeHIRect = FOUR_CHAR_CODE('hirc')
kEventParamMouseLocation = FOUR_CHAR_CODE('mloc')
kEventParamMouseButton = FOUR_CHAR_CODE('mbtn')
kEventParamClickCount = FOUR_CHAR_CODE('ccnt')
@@ -314,13 +314,13 @@ kEventParamMouseDelta = FOUR_CHAR_CODE('mdta')
kEventParamMouseChord = FOUR_CHAR_CODE('chor')
kEventParamTabletEventType = FOUR_CHAR_CODE('tblt')
typeMouseButton = FOUR_CHAR_CODE('mbtn')
-typeMouseWheelAxis = FOUR_CHAR_CODE('mwax')
+typeMouseWheelAxis = FOUR_CHAR_CODE('mwax')
kEventParamKeyCode = FOUR_CHAR_CODE('kcod')
kEventParamKeyMacCharCodes = FOUR_CHAR_CODE('kchr')
kEventParamKeyModifiers = FOUR_CHAR_CODE('kmod')
kEventParamKeyUnicodes = FOUR_CHAR_CODE('kuni')
kEventParamKeyboardType = FOUR_CHAR_CODE('kbdt')
-typeEventHotKeyID = FOUR_CHAR_CODE('hkid')
+typeEventHotKeyID = FOUR_CHAR_CODE('hkid')
kEventParamTextInputSendRefCon = FOUR_CHAR_CODE('tsrc')
kEventParamTextInputSendComponentInstance = FOUR_CHAR_CODE('tsci')
kEventParamTextInputSendSLRec = FOUR_CHAR_CODE('tssl')
@@ -350,9 +350,9 @@ kEventParamTextInputSendShowHide = FOUR_CHAR_CODE('tssh')
kEventParamTextInputReplyShowHide = FOUR_CHAR_CODE('trsh')
kEventParamTextInputSendKeyboardEvent = FOUR_CHAR_CODE('tske')
kEventParamTextInputSendTextServiceEncoding = FOUR_CHAR_CODE('tsse')
-kEventParamTextInputSendTextServiceMacEncoding = FOUR_CHAR_CODE('tssm')
+kEventParamTextInputSendTextServiceMacEncoding = FOUR_CHAR_CODE('tssm')
kEventParamHICommand = FOUR_CHAR_CODE('hcmd')
-typeHICommand = FOUR_CHAR_CODE('hcmd')
+typeHICommand = FOUR_CHAR_CODE('hcmd')
kEventParamWindowFeatures = FOUR_CHAR_CODE('wftr')
kEventParamWindowDefPart = FOUR_CHAR_CODE('wdpc')
kEventParamCurrentBounds = FOUR_CHAR_CODE('crct')
@@ -375,7 +375,7 @@ kEventParamPreviousDockRect = FOUR_CHAR_CODE('pdrc')
kEventParamCurrentDockRect = FOUR_CHAR_CODE('cdrc')
typeWindowRegionCode = FOUR_CHAR_CODE('wshp')
typeWindowDefPartCode = FOUR_CHAR_CODE('wdpt')
-typeClickActivationResult = FOUR_CHAR_CODE('clac')
+typeClickActivationResult = FOUR_CHAR_CODE('clac')
kEventParamControlPart = FOUR_CHAR_CODE('cprt')
kEventParamInitCollection = FOUR_CHAR_CODE('icol')
kEventParamControlMessage = FOUR_CHAR_CODE('cmsg')
@@ -402,7 +402,7 @@ kEventParamControlOriginalOwningWindow = FOUR_CHAR_CODE('coow')
kEventParamControlCurrentOwningWindow = FOUR_CHAR_CODE('ccow')
typeControlActionUPP = FOUR_CHAR_CODE('caup')
typeIndicatorDragConstraint = FOUR_CHAR_CODE('cidc')
-typeControlPartCode = FOUR_CHAR_CODE('cprt')
+typeControlPartCode = FOUR_CHAR_CODE('cprt')
kEventParamCurrentMenuTrackingMode = FOUR_CHAR_CODE('cmtm')
kEventParamNewMenuTrackingMode = FOUR_CHAR_CODE('nmtm')
kEventParamMenuFirstOpen = FOUR_CHAR_CODE('1sto')
@@ -428,24 +428,24 @@ typeMenuCommand = FOUR_CHAR_CODE('mcmd')
typeMenuTrackingMode = FOUR_CHAR_CODE('mtmd')
typeMenuEventOptions = FOUR_CHAR_CODE('meop')
typeThemeMenuState = FOUR_CHAR_CODE('tmns')
-typeThemeMenuItemType = FOUR_CHAR_CODE('tmit')
+typeThemeMenuItemType = FOUR_CHAR_CODE('tmit')
kEventParamProcessID = FOUR_CHAR_CODE('psn ')
kEventParamLaunchRefCon = FOUR_CHAR_CODE('lref')
-kEventParamLaunchErr = FOUR_CHAR_CODE('err ')
+kEventParamLaunchErr = FOUR_CHAR_CODE('err ')
kEventParamTabletPointRec = FOUR_CHAR_CODE('tbrc')
kEventParamTabletProximityRec = FOUR_CHAR_CODE('tbpx')
typeTabletPointRec = FOUR_CHAR_CODE('tbrc')
typeTabletProximityRec = FOUR_CHAR_CODE('tbpx')
kEventParamTabletPointerRec = FOUR_CHAR_CODE('tbrc')
-typeTabletPointerRec = FOUR_CHAR_CODE('tbrc')
-kEventParamNewScrollBarVariant = FOUR_CHAR_CODE('nsbv')
+typeTabletPointerRec = FOUR_CHAR_CODE('tbrc')
+kEventParamNewScrollBarVariant = FOUR_CHAR_CODE('nsbv')
kEventParamScrapRef = FOUR_CHAR_CODE('scrp')
kEventParamServiceCopyTypes = FOUR_CHAR_CODE('svsd')
kEventParamServicePasteTypes = FOUR_CHAR_CODE('svpt')
kEventParamServiceMessageName = FOUR_CHAR_CODE('svmg')
kEventParamServiceUserData = FOUR_CHAR_CODE('svud')
typeScrapRef = FOUR_CHAR_CODE('scrp')
-typeCFMutableArrayRef = FOUR_CHAR_CODE('cfma')
+typeCFMutableArrayRef = FOUR_CHAR_CODE('cfma')
# sHandler = NewEventHandlerUPP( x )
kMouseTrackingMousePressed = kMouseTrackingMouseDown
kMouseTrackingMouseReleased = kMouseTrackingMouseUp
diff --git a/Lib/plat-mac/Carbon/Components.py b/Lib/plat-mac/Carbon/Components.py
index 3fbca0231b..75574cf6d0 100644
--- a/Lib/plat-mac/Carbon/Components.py
+++ b/Lib/plat-mac/Carbon/Components.py
@@ -3,7 +3,7 @@
def FOUR_CHAR_CODE(x): return x
kAppleManufacturer = FOUR_CHAR_CODE('appl')
kComponentResourceType = FOUR_CHAR_CODE('thng')
-kComponentAliasResourceType = FOUR_CHAR_CODE('thga')
+kComponentAliasResourceType = FOUR_CHAR_CODE('thga')
kAnyComponentType = 0
kAnyComponentSubType = 0
kAnyComponentManufacturer = 0
@@ -19,7 +19,7 @@ kComponentTargetSelect = -6
kComponentUnregisterSelect = -7
kComponentGetMPWorkFunctionSelect = -8
kComponentExecuteWiredActionSelect = -9
-kComponentGetPublicResourceSelect = -10
+kComponentGetPublicResourceSelect = -10
componentDoAutoVersion = (1 << 0)
componentWantsUnregister = (1 << 1)
componentAutoVersionIncludeFlags = (1 << 2)
diff --git a/Lib/plat-mac/Carbon/ControlAccessor.py b/Lib/plat-mac/Carbon/ControlAccessor.py
index 791544e788..099892538c 100644
--- a/Lib/plat-mac/Carbon/ControlAccessor.py
+++ b/Lib/plat-mac/Carbon/ControlAccessor.py
@@ -6,22 +6,22 @@ import struct
# These needn't go through this module, but are here for completeness
def SetControlData_Handle(control, part, selector, data):
control.SetControlData_Handle(part, selector, data)
-
+
def GetControlData_Handle(control, part, selector):
return control.GetControlData_Handle(part, selector)
-
+
_accessdict = {
kControlPopupButtonMenuHandleTag: (SetControlData_Handle, GetControlData_Handle),
}
_codingdict = {
kControlPushButtonDefaultTag : ("b", None, None),
-
+
kControlEditTextTextTag: (None, None, None),
kControlEditTextPasswordTag: (None, None, None),
-
+
kControlPopupButtonMenuIDTag: ("h", None, None),
-
+
kControlListBoxDoubleClickTag: ("b", None, None),
}
@@ -38,7 +38,7 @@ def SetControlData(control, part, selector, data):
if structfmt:
data = struct.pack(structfmt, data)
control.SetControlData(part, selector, data)
-
+
def GetControlData(control, part, selector):
if _accessdict.has_key(selector):
setfunc, getfunc = _accessdict[selector]
@@ -54,4 +54,3 @@ def GetControlData(control, part, selector):
if type(data) == type(()) and len(data) == 1:
data = data[0]
return data
-
diff --git a/Lib/plat-mac/Carbon/Controls.py b/Lib/plat-mac/Carbon/Controls.py
index d4bbda3cc9..6e5d8ea7f8 100644
--- a/Lib/plat-mac/Carbon/Controls.py
+++ b/Lib/plat-mac/Carbon/Controls.py
@@ -17,20 +17,20 @@ kControlDefProcResourceType = FOUR_CHAR_CODE('CDEF')
controlNotifyNothing = FOUR_CHAR_CODE('nada')
controlNotifyClick = FOUR_CHAR_CODE('clik')
controlNotifyFocus = FOUR_CHAR_CODE('focu')
-controlNotifyKey = FOUR_CHAR_CODE('key ')
-kControlCanAutoInvalidate = 1L << 0
+controlNotifyKey = FOUR_CHAR_CODE('key ')
+kControlCanAutoInvalidate = 1L << 0
staticTextProc = 256
editTextProc = 272
iconProc = 288
userItemProc = 304
-pictItemProc = 320
+pictItemProc = 320
cFrameColor = 0
cBodyColor = 1
cTextColor = 2
cThumbColor = 3
kNumberCtlCTabEntries = 4
kControlNoVariant = 0
-kControlUsesOwningWindowsFontVariant = 1 << 3
+kControlUsesOwningWindowsFontVariant = 1 << 3
kControlNoPart = 0
kControlIndicatorPart = 129
kControlDisabledPart = 254
@@ -40,7 +40,7 @@ kControlStructureMetaPart = -1
kControlContentMetaPart = -2
kControlFocusNoPart = 0
kControlFocusNextPart = -1
-kControlFocusPrevPart = -2
+kControlFocusPrevPart = -2
kControlCollectionTagBounds = FOUR_CHAR_CODE('boun')
kControlCollectionTagValue = FOUR_CHAR_CODE('valu')
kControlCollectionTagMinimum = FOUR_CHAR_CODE('min ')
@@ -53,7 +53,7 @@ kControlCollectionTagUnicodeTitle = FOUR_CHAR_CODE('uttl')
kControlCollectionTagIDSignature = FOUR_CHAR_CODE('idsi')
kControlCollectionTagIDID = FOUR_CHAR_CODE('idid')
kControlCollectionTagCommand = FOUR_CHAR_CODE('cmd ')
-kControlCollectionTagVarCode = FOUR_CHAR_CODE('varc')
+kControlCollectionTagVarCode = FOUR_CHAR_CODE('varc')
kControlContentTextOnly = 0
kControlNoContent = 0
kControlContentIconSuiteRes = 1
@@ -67,11 +67,11 @@ kControlContentIconRef = 132
kControlContentICON = 133
kControlKeyScriptBehaviorAllowAnyScript = FOUR_CHAR_CODE('any ')
kControlKeyScriptBehaviorPrefersRoman = FOUR_CHAR_CODE('prmn')
-kControlKeyScriptBehaviorRequiresRoman = FOUR_CHAR_CODE('rrmn')
+kControlKeyScriptBehaviorRequiresRoman = FOUR_CHAR_CODE('rrmn')
kControlFontBigSystemFont = -1
kControlFontSmallSystemFont = -2
kControlFontSmallBoldSystemFont = -3
-kControlFontViewSystemFont = -4
+kControlFontViewSystemFont = -4
kControlUseFontMask = 0x0001
kControlUseFaceMask = 0x0002
kControlUseSizeMask = 0x0004
@@ -81,12 +81,12 @@ kControlUseModeMask = 0x0020
kControlUseJustMask = 0x0040
kControlUseAllMask = 0x00FF
kControlAddFontSizeMask = 0x0100
-kControlAddToMetaFontMask = 0x0200
-kControlUseThemeFontIDMask = 0x0080
+kControlAddToMetaFontMask = 0x0200
+kControlUseThemeFontIDMask = 0x0080
kDoNotActivateAndIgnoreClick = 0
kDoNotActivateAndHandleClick = 1
kActivateAndIgnoreClick = 2
-kActivateAndHandleClick = 3
+kActivateAndHandleClick = 3
kControlFontStyleTag = FOUR_CHAR_CODE('font')
kControlKeyFilterTag = FOUR_CHAR_CODE('fltr')
kControlKindTag = FOUR_CHAR_CODE('kind')
@@ -110,7 +110,7 @@ kControlSupportsFlattening = 1 << 19
kControlSupportsSetCursor = 1 << 20
kControlSupportsContextualMenus = 1 << 21
kControlSupportsClickActivation = 1 << 22
-kControlIdlesWithTimer = 1 << 23
+kControlIdlesWithTimer = 1 << 23
drawCntl = 0
testCntl = 1
calcCRgns = 2
@@ -149,7 +149,7 @@ kControlMsgDragWithin = 40
kControlMsgDragReceive = 41
kControlMsgDisplayDebugInfo = 46
kControlMsgContextualMenuClick = 47
-kControlMsgGetClickActivation = 48
+kControlMsgGetClickActivation = 48
kControlSizeNormal = 0
kControlSizeSmall = 1
kControlSizeLarge = 2
@@ -165,9 +165,9 @@ noConstraint = kNoConstraint
hAxisOnly = 1
vAxisOnly = 2
kControlDefProcPtr = 0
-kControlDefObjectClass = 1
+kControlDefObjectClass = 1
kControlKindSignatureApple = FOUR_CHAR_CODE('appl')
-kControlPropertyPersistent = 0x00000001
+kControlPropertyPersistent = 0x00000001
kDragTrackingEnterControl = 2
kDragTrackingInControl = 3
kDragTrackingLeaveControl = 4
@@ -178,7 +178,7 @@ kInIndicatorControlPart = kControlIndicatorPart
kReservedControlPart = kControlDisabledPart
kControlInactiveControlPart = kControlInactivePart
kControlTabListResType = FOUR_CHAR_CODE('tab#')
-kControlListDescResType = FOUR_CHAR_CODE('ldes')
+kControlListDescResType = FOUR_CHAR_CODE('ldes')
kControlCheckBoxUncheckedValue = 0
kControlCheckBoxCheckedValue = 1
kControlCheckBoxMixedValue = 2
@@ -228,7 +228,7 @@ kControlClockMinuteMonthPart = 10
kControlClockSecondYearPart = 11
kControlClockAMPMPart = 12
kControlDataBrowserPart = 24
-kControlDataBrowserDraggedPart = 25
+kControlDataBrowserDraggedPart = 25
kControlBevelButtonSmallBevelProc = 32
kControlBevelButtonNormalBevelProc = 33
kControlBevelButtonLargeBevelProc = 34
@@ -245,7 +245,7 @@ kControlBehaviorSticky = 0x0200
kControlBehaviorSingleValueMenu = 0
kControlBehaviorMultiValueMenu = 0x4000
kControlBehaviorOffsetContents = 0x8000
-kControlBehaviorCommandMenu = 0x2000
+kControlBehaviorCommandMenu = 0x2000
kControlBevelButtonMenuOnBottom = 0
kControlBevelButtonMenuOnRight = (1 << 2)
kControlKindBevelButton = FOUR_CHAR_CODE('bevl')
@@ -279,12 +279,12 @@ kControlBevelButtonTextPlaceTag = FOUR_CHAR_CODE('tplc')
kControlBevelButtonMenuValueTag = FOUR_CHAR_CODE('mval')
kControlBevelButtonMenuHandleTag = FOUR_CHAR_CODE('mhnd')
kControlBevelButtonMenuRefTag = FOUR_CHAR_CODE('mhnd')
-# kControlBevelButtonCenterPopupGlyphTag = FOUR_CHAR_CODE('pglc')
+# kControlBevelButtonCenterPopupGlyphTag = FOUR_CHAR_CODE('pglc')
kControlBevelButtonLastMenuTag = FOUR_CHAR_CODE('lmnu')
-kControlBevelButtonMenuDelayTag = FOUR_CHAR_CODE('mdly')
-kControlBevelButtonScaleIconTag = FOUR_CHAR_CODE('scal')
+kControlBevelButtonMenuDelayTag = FOUR_CHAR_CODE('mdly')
+kControlBevelButtonScaleIconTag = FOUR_CHAR_CODE('scal')
kControlBevelButtonOwnedMenuRefTag = FOUR_CHAR_CODE('omrf')
-kControlBevelButtonKindTag = FOUR_CHAR_CODE('bebk')
+kControlBevelButtonKindTag = FOUR_CHAR_CODE('bebk')
kControlSliderProc = 48
kControlSliderLiveFeedback = (1 << 0)
kControlSliderHasTickMarks = (1 << 1)
@@ -302,18 +302,18 @@ kControlDisclosureTrianglePointDefault = 0
kControlDisclosureTrianglePointRight = 1
kControlDisclosureTrianglePointLeft = 2
kControlKindDisclosureTriangle = FOUR_CHAR_CODE('dist')
-kControlTriangleLastValueTag = FOUR_CHAR_CODE('last')
+kControlTriangleLastValueTag = FOUR_CHAR_CODE('last')
kControlProgressBarProc = 80
kControlRelevanceBarProc = 81
kControlKindProgressBar = FOUR_CHAR_CODE('prgb')
kControlKindRelevanceBar = FOUR_CHAR_CODE('relb')
kControlProgressBarIndeterminateTag = FOUR_CHAR_CODE('inde')
-kControlProgressBarAnimatingTag = FOUR_CHAR_CODE('anim')
+kControlProgressBarAnimatingTag = FOUR_CHAR_CODE('anim')
kControlLittleArrowsProc = 96
kControlKindLittleArrows = FOUR_CHAR_CODE('larr')
kControlChasingArrowsProc = 112
kControlKindChasingArrows = FOUR_CHAR_CODE('carr')
-kControlChasingArrowsAnimatingTag = FOUR_CHAR_CODE('anim')
+kControlChasingArrowsAnimatingTag = FOUR_CHAR_CODE('anim')
kControlTabLargeProc = 128
kControlTabSmallProc = 129
kControlTabLargeNorthProc = 128
@@ -323,7 +323,7 @@ kControlTabSmallSouthProc = 131
kControlTabLargeEastProc = 132
kControlTabSmallEastProc = 133
kControlTabLargeWestProc = 134
-kControlTabSmallWestProc = 135
+kControlTabSmallWestProc = 135
kControlTabDirectionNorth = 0
kControlTabDirectionSouth = 1
kControlTabDirectionEast = 2
@@ -333,11 +333,11 @@ kControlTabSizeSmall = kControlSizeSmall
kControlKindTabs = FOUR_CHAR_CODE('tabs')
kControlTabContentRectTag = FOUR_CHAR_CODE('rect')
kControlTabEnabledFlagTag = FOUR_CHAR_CODE('enab')
-kControlTabFontStyleTag = kControlFontStyleTag
-kControlTabInfoTag = FOUR_CHAR_CODE('tabi')
-kControlTabImageContentTag = FOUR_CHAR_CODE('cont')
+kControlTabFontStyleTag = kControlFontStyleTag
+kControlTabInfoTag = FOUR_CHAR_CODE('tabi')
+kControlTabImageContentTag = FOUR_CHAR_CODE('cont')
kControlTabInfoVersionZero = 0
-kControlTabInfoVersionOne = 1
+kControlTabInfoVersionOne = 1
kControlSeparatorLineProc = 144
kControlKindSeparator = FOUR_CHAR_CODE('sepa')
kControlGroupBoxTextTitleProc = 160
@@ -351,13 +351,13 @@ kControlKindCheckGroupBox = FOUR_CHAR_CODE('cgrp')
kControlKindPopupGroupBox = FOUR_CHAR_CODE('pgrp')
kControlGroupBoxMenuHandleTag = FOUR_CHAR_CODE('mhan')
kControlGroupBoxMenuRefTag = FOUR_CHAR_CODE('mhan')
-kControlGroupBoxFontStyleTag = kControlFontStyleTag
-kControlGroupBoxTitleRectTag = FOUR_CHAR_CODE('trec')
+kControlGroupBoxFontStyleTag = kControlFontStyleTag
+kControlGroupBoxTitleRectTag = FOUR_CHAR_CODE('trec')
kControlImageWellProc = 176
kControlKindImageWell = FOUR_CHAR_CODE('well')
kControlImageWellContentTag = FOUR_CHAR_CODE('cont')
kControlImageWellTransformTag = FOUR_CHAR_CODE('tran')
-kControlImageWellIsDragDestinationTag = FOUR_CHAR_CODE('drag')
+kControlImageWellIsDragDestinationTag = FOUR_CHAR_CODE('drag')
kControlPopupArrowEastProc = 192
kControlPopupArrowWestProc = 193
kControlPopupArrowNorthProc = 194
@@ -392,7 +392,7 @@ kControlClockIsLive = 2
kControlKindClock = FOUR_CHAR_CODE('clck')
kControlClockLongDateTag = FOUR_CHAR_CODE('date')
kControlClockFontStyleTag = kControlFontStyleTag
-kControlClockAnimatingTag = FOUR_CHAR_CODE('anim')
+kControlClockAnimatingTag = FOUR_CHAR_CODE('anim')
kControlUserPaneProc = 256
kControlKindUserPane = FOUR_CHAR_CODE('upan')
kControlUserItemDrawProcTag = FOUR_CHAR_CODE('uidp')
@@ -403,63 +403,63 @@ kControlUserPaneIdleProcTag = FOUR_CHAR_CODE('idle')
kControlUserPaneKeyDownProcTag = FOUR_CHAR_CODE('keyd')
kControlUserPaneActivateProcTag = FOUR_CHAR_CODE('acti')
kControlUserPaneFocusProcTag = FOUR_CHAR_CODE('foci')
-kControlUserPaneBackgroundProcTag = FOUR_CHAR_CODE('back')
+kControlUserPaneBackgroundProcTag = FOUR_CHAR_CODE('back')
kControlEditTextProc = 272
kControlEditTextPasswordProc = 274
-kControlEditTextInlineInputProc = 276
+kControlEditTextInlineInputProc = 276
kControlKindEditText = FOUR_CHAR_CODE('etxt')
kControlEditTextStyleTag = kControlFontStyleTag
kControlEditTextTextTag = FOUR_CHAR_CODE('text')
kControlEditTextTEHandleTag = FOUR_CHAR_CODE('than')
kControlEditTextKeyFilterTag = kControlKeyFilterTag
kControlEditTextSelectionTag = FOUR_CHAR_CODE('sele')
-kControlEditTextPasswordTag = FOUR_CHAR_CODE('pass')
+kControlEditTextPasswordTag = FOUR_CHAR_CODE('pass')
kControlEditTextKeyScriptBehaviorTag = FOUR_CHAR_CODE('kscr')
kControlEditTextLockedTag = FOUR_CHAR_CODE('lock')
kControlEditTextFixedTextTag = FOUR_CHAR_CODE('ftxt')
kControlEditTextValidationProcTag = FOUR_CHAR_CODE('vali')
kControlEditTextInlinePreUpdateProcTag = FOUR_CHAR_CODE('prup')
-kControlEditTextInlinePostUpdateProcTag = FOUR_CHAR_CODE('poup')
+kControlEditTextInlinePostUpdateProcTag = FOUR_CHAR_CODE('poup')
kControlEditTextCFStringTag = FOUR_CHAR_CODE('cfst')
-kControlEditTextPasswordCFStringTag = FOUR_CHAR_CODE('pwcf')
+kControlEditTextPasswordCFStringTag = FOUR_CHAR_CODE('pwcf')
kControlStaticTextProc = 288
kControlKindStaticText = FOUR_CHAR_CODE('stxt')
kControlStaticTextStyleTag = kControlFontStyleTag
kControlStaticTextTextTag = FOUR_CHAR_CODE('text')
-kControlStaticTextTextHeightTag = FOUR_CHAR_CODE('thei')
-kControlStaticTextTruncTag = FOUR_CHAR_CODE('trun')
-kControlStaticTextCFStringTag = FOUR_CHAR_CODE('cfst')
+kControlStaticTextTextHeightTag = FOUR_CHAR_CODE('thei')
+kControlStaticTextTruncTag = FOUR_CHAR_CODE('trun')
+kControlStaticTextCFStringTag = FOUR_CHAR_CODE('cfst')
kControlPictureProc = 304
-kControlPictureNoTrackProc = 305
+kControlPictureNoTrackProc = 305
kControlKindPicture = FOUR_CHAR_CODE('pict')
-kControlPictureHandleTag = FOUR_CHAR_CODE('pich')
+kControlPictureHandleTag = FOUR_CHAR_CODE('pich')
kControlIconProc = 320
kControlIconNoTrackProc = 321
kControlIconSuiteProc = 322
-kControlIconSuiteNoTrackProc = 323
+kControlIconSuiteNoTrackProc = 323
kControlIconRefProc = 324
-kControlIconRefNoTrackProc = 325
+kControlIconRefNoTrackProc = 325
kControlKindIcon = FOUR_CHAR_CODE('icon')
kControlIconTransformTag = FOUR_CHAR_CODE('trfm')
-kControlIconAlignmentTag = FOUR_CHAR_CODE('algn')
+kControlIconAlignmentTag = FOUR_CHAR_CODE('algn')
kControlIconResourceIDTag = FOUR_CHAR_CODE('ires')
-kControlIconContentTag = FOUR_CHAR_CODE('cont')
+kControlIconContentTag = FOUR_CHAR_CODE('cont')
kControlWindowHeaderProc = 336
-kControlWindowListViewHeaderProc = 337
+kControlWindowListViewHeaderProc = 337
kControlKindWindowHeader = FOUR_CHAR_CODE('whed')
kControlListBoxProc = 352
kControlListBoxAutoSizeProc = 353
kControlKindListBox = FOUR_CHAR_CODE('lbox')
kControlListBoxListHandleTag = FOUR_CHAR_CODE('lhan')
kControlListBoxKeyFilterTag = kControlKeyFilterTag
-kControlListBoxFontStyleTag = kControlFontStyleTag
+kControlListBoxFontStyleTag = kControlFontStyleTag
kControlListBoxDoubleClickTag = FOUR_CHAR_CODE('dblc')
-kControlListBoxLDEFTag = FOUR_CHAR_CODE('ldef')
+kControlListBoxLDEFTag = FOUR_CHAR_CODE('ldef')
kControlPushButtonProc = 368
kControlCheckBoxProc = 369
kControlRadioButtonProc = 370
kControlPushButLeftIconProc = 374
-kControlPushButRightIconProc = 375
+kControlPushButRightIconProc = 375
kControlCheckBoxAutoToggleProc = 371
kControlRadioButtonAutoToggleProc = 372
kControlPushButtonIconOnLeft = 6
@@ -469,11 +469,11 @@ kControlKindPushIconButton = FOUR_CHAR_CODE('picn')
kControlKindRadioButton = FOUR_CHAR_CODE('rdio')
kControlKindCheckBox = FOUR_CHAR_CODE('cbox')
kControlPushButtonDefaultTag = FOUR_CHAR_CODE('dflt')
-kControlPushButtonCancelTag = FOUR_CHAR_CODE('cncl')
+kControlPushButtonCancelTag = FOUR_CHAR_CODE('cncl')
kControlScrollBarProc = 384
-kControlScrollBarLiveProc = 386
+kControlScrollBarLiveProc = 386
kControlKindScrollBar = FOUR_CHAR_CODE('sbar')
-kControlScrollBarShowsArrowsTag = FOUR_CHAR_CODE('arro')
+kControlScrollBarShowsArrowsTag = FOUR_CHAR_CODE('arro')
kControlPopupButtonProc = 400
kControlPopupFixedWidthVariant = 1 << 0
kControlPopupVariableWidthVariant = 1 << 1
@@ -482,10 +482,10 @@ kControlPopupUseWFontVariant = kControlUsesOwningWindowsFontVariant
kControlKindPopupButton = FOUR_CHAR_CODE('popb')
kControlPopupButtonMenuHandleTag = FOUR_CHAR_CODE('mhan')
kControlPopupButtonMenuRefTag = FOUR_CHAR_CODE('mhan')
-kControlPopupButtonMenuIDTag = FOUR_CHAR_CODE('mnid')
+kControlPopupButtonMenuIDTag = FOUR_CHAR_CODE('mnid')
kControlPopupButtonExtraHeightTag = FOUR_CHAR_CODE('exht')
-kControlPopupButtonOwnedMenuRefTag = FOUR_CHAR_CODE('omrf')
-kControlPopupButtonCheckCurrentTag = FOUR_CHAR_CODE('chck')
+kControlPopupButtonOwnedMenuRefTag = FOUR_CHAR_CODE('omrf')
+kControlPopupButtonCheckCurrentTag = FOUR_CHAR_CODE('chck')
kControlRadioGroupProc = 416
kControlKindRadioGroup = FOUR_CHAR_CODE('rgrp')
kControlScrollTextBoxProc = 432
@@ -495,14 +495,14 @@ kControlScrollTextBoxDelayBeforeAutoScrollTag = FOUR_CHAR_CODE('stdl')
kControlScrollTextBoxDelayBetweenAutoScrollTag = FOUR_CHAR_CODE('scdl')
kControlScrollTextBoxAutoScrollAmountTag = FOUR_CHAR_CODE('samt')
kControlScrollTextBoxContentsTag = FOUR_CHAR_CODE('tres')
-kControlScrollTextBoxAnimatingTag = FOUR_CHAR_CODE('anim')
+kControlScrollTextBoxAnimatingTag = FOUR_CHAR_CODE('anim')
kControlKindDisclosureButton = FOUR_CHAR_CODE('disb')
kControlDisclosureButtonClosed = 0
kControlDisclosureButtonDisclosed = 1
kControlRoundButtonNormalSize = kControlSizeNormal
kControlRoundButtonLargeSize = kControlSizeLarge
kControlRoundButtonContentTag = FOUR_CHAR_CODE('cont')
-kControlRoundButtonSizeTag = kControlSizeTag
+kControlRoundButtonSizeTag = kControlSizeTag
kControlKindRoundButton = FOUR_CHAR_CODE('rndb')
kControlKindDataBrowser = FOUR_CHAR_CODE('datb')
errDataBrowserNotConfigured = -4970
@@ -511,7 +511,7 @@ errDataBrowserItemNotAdded = -4975
errDataBrowserPropertyNotFound = -4972
errDataBrowserInvalidPropertyPart = -4973
errDataBrowserInvalidPropertyData = -4974
-errDataBrowserPropertyNotSupported = -4979
+errDataBrowserPropertyNotSupported = -4979
kControlDataBrowserIncludesFrameAndFocusTag = FOUR_CHAR_CODE('brdr')
kControlDataBrowserKeyFilterTag = kControlEditTextKeyFilterTag
kControlDataBrowserEditTextKeyFilterTag = kControlDataBrowserKeyFilterTag
@@ -525,23 +525,23 @@ kDataBrowserResetSelection = 1 << 2
kDataBrowserCmdTogglesSelection = 1 << 3
kDataBrowserNoDisjointSelection = 1 << 4
kDataBrowserAlwaysExtendSelection = 1 << 5
-kDataBrowserNeverEmptySelectionSet = 1 << 6
+kDataBrowserNeverEmptySelectionSet = 1 << 6
kDataBrowserOrderUndefined = 0
kDataBrowserOrderIncreasing = 1
kDataBrowserOrderDecreasing = 2
-kDataBrowserNoItem = 0L
+kDataBrowserNoItem = 0L
kDataBrowserItemNoState = 0
# kDataBrowserItemAnyState = (unsigned long)(-1)
kDataBrowserItemIsSelected = 1 << 0
kDataBrowserContainerIsOpen = 1 << 1
-kDataBrowserItemIsDragTarget = 1 << 2
+kDataBrowserItemIsDragTarget = 1 << 2
kDataBrowserRevealOnly = 0
kDataBrowserRevealAndCenterInView = 1 << 0
kDataBrowserRevealWithoutSelecting = 1 << 1
kDataBrowserItemsAdd = 0
kDataBrowserItemsAssign = 1
kDataBrowserItemsToggle = 2
-kDataBrowserItemsRemove = 3
+kDataBrowserItemsRemove = 3
kDataBrowserSelectionAnchorUp = 0
kDataBrowserSelectionAnchorDown = 1
kDataBrowserSelectionAnchorLeft = 2
@@ -568,7 +568,7 @@ kDataBrowserContainerSorted = 12
kDataBrowserUserToggledContainer = 16
kDataBrowserTargetChanged = 15
kDataBrowserUserStateChanged = 13
-kDataBrowserSelectionSetChanged = 14
+kDataBrowserSelectionSetChanged = 14
kDataBrowserItemNoProperty = 0L
kDataBrowserItemIsActiveProperty = 1L
kDataBrowserItemIsSelectableProperty = 2L
@@ -580,7 +580,7 @@ kDataBrowserContainerIsSortableProperty = 7L
kDataBrowserItemSelfIdentityProperty = 8L
kDataBrowserContainerAliasIDProperty = 9L
kDataBrowserColumnViewPreviewProperty = 10L
-kDataBrowserItemParentContainerProperty = 11L
+kDataBrowserItemParentContainerProperty = 11L
kDataBrowserCustomType = 0x3F3F3F3F
kDataBrowserIconType = FOUR_CHAR_CODE('icnr')
kDataBrowserTextType = FOUR_CHAR_CODE('text')
@@ -590,7 +590,7 @@ kDataBrowserCheckboxType = FOUR_CHAR_CODE('chbx')
kDataBrowserProgressBarType = FOUR_CHAR_CODE('prog')
kDataBrowserRelevanceRankType = FOUR_CHAR_CODE('rank')
kDataBrowserPopupMenuType = FOUR_CHAR_CODE('menu')
-kDataBrowserIconAndTextType = FOUR_CHAR_CODE('ticn')
+kDataBrowserIconAndTextType = FOUR_CHAR_CODE('ticn')
kDataBrowserPropertyEnclosingPart = 0L
kDataBrowserPropertyContentPart = FOUR_CHAR_CODE('----')
kDataBrowserPropertyDisclosurePart = FOUR_CHAR_CODE('disc')
@@ -604,7 +604,7 @@ kDataBrowserUniversalPropertyFlagsMask = 0xFF
kDataBrowserPropertyIsMutable = 1 << 0
kDataBrowserDefaultPropertyFlags = 0 << 0
kDataBrowserUniversalPropertyFlags = kDataBrowserUniversalPropertyFlagsMask
-kDataBrowserPropertyIsEditable = kDataBrowserPropertyIsMutable
+kDataBrowserPropertyIsEditable = kDataBrowserPropertyIsMutable
kDataBrowserPropertyFlagsOffset = 8
kDataBrowserPropertyFlagsMask = 0xFF << kDataBrowserPropertyFlagsOffset
kDataBrowserCheckboxTriState = 1 << kDataBrowserPropertyFlagsOffset
@@ -620,10 +620,10 @@ kDataBrowserTruncateTextAtEnd = 2 << kDataBrowserPropertyFlagsOffset
kDataBrowserTruncateTextMiddle = 0 << kDataBrowserPropertyFlagsOffset
kDataBrowserTruncateTextAtStart = 1 << kDataBrowserPropertyFlagsOffset
kDataBrowserPropertyModificationFlags = kDataBrowserPropertyFlagsMask
-kDataBrowserRelativeDateTime = kDataBrowserDateTimeRelative
+kDataBrowserRelativeDateTime = kDataBrowserDateTimeRelative
kDataBrowserViewSpecificFlagsOffset = 16
kDataBrowserViewSpecificFlagsMask = 0xFF << kDataBrowserViewSpecificFlagsOffset
-kDataBrowserViewSpecificPropertyFlags = kDataBrowserViewSpecificFlagsMask
+kDataBrowserViewSpecificPropertyFlags = kDataBrowserViewSpecificFlagsMask
kDataBrowserClientPropertyFlagsOffset = 24
# kDataBrowserClientPropertyFlagsMask = (unsigned long)(0xFF << kDataBrowserClientPropertyFlagsOffset)
kDataBrowserLatestCallbacks = 0
diff --git a/Lib/plat-mac/Carbon/CoreFoundation.py b/Lib/plat-mac/Carbon/CoreFoundation.py
index 2907c1d94d..8d9c894641 100644
--- a/Lib/plat-mac/Carbon/CoreFoundation.py
+++ b/Lib/plat-mac/Carbon/CoreFoundation.py
@@ -16,13 +16,13 @@ kCFStringEncodingNextStepLatin = 0x0B01
kCFStringEncodingASCII = 0x0600
kCFStringEncodingUnicode = 0x0100
kCFStringEncodingUTF8 = 0x08000100
-kCFStringEncodingNonLossyASCII = 0x0BFF
+kCFStringEncodingNonLossyASCII = 0x0BFF
kCFCompareCaseInsensitive = 1
kCFCompareBackwards = 4
kCFCompareAnchored = 8
kCFCompareNonliteral = 16
kCFCompareLocalized = 32
-kCFCompareNumerically = 64
+kCFCompareNumerically = 64
kCFURLPOSIXPathStyle = 0
kCFURLHFSPathStyle = 1
kCFURLWindowsPathStyle = 2
diff --git a/Lib/plat-mac/Carbon/CoreGraphics.py b/Lib/plat-mac/Carbon/CoreGraphics.py
index d7a6f02fe3..f4cb0b9440 100755
--- a/Lib/plat-mac/Carbon/CoreGraphics.py
+++ b/Lib/plat-mac/Carbon/CoreGraphics.py
@@ -25,4 +25,4 @@ kCGEncodingMacRoman = 1
kCGInterpolationDefault = 0
kCGInterpolationNone = 1
kCGInterpolationLow = 2
-kCGInterpolationHigh = 3
+kCGInterpolationHigh = 3
diff --git a/Lib/plat-mac/Carbon/Dialogs.py b/Lib/plat-mac/Carbon/Dialogs.py
index 9d2fa8fd2f..f846d7c39d 100644
--- a/Lib/plat-mac/Carbon/Dialogs.py
+++ b/Lib/plat-mac/Carbon/Dialogs.py
@@ -45,7 +45,7 @@ kAlertCautionAlert = 2
kAlertPlainAlert = 3
kAlertDefaultOKText = -1
kAlertDefaultCancelText = -1
-kAlertDefaultOtherText = -1
+kAlertDefaultOtherText = -1
kAlertStdAlertOKButton = 1
kAlertStdAlertCancelButton = 2
kAlertStdAlertOtherButton = 3
@@ -71,8 +71,8 @@ kDialogFontAddFontSizeMask = 0x0100
kDialogFontUseFontNameMask = 0x0200
kDialogFontAddToMetaFontMask = 0x0400
kDialogFontUseThemeFontIDMask = 0x0080
-kHICommandOther = FOUR_CHAR_CODE('othr')
-kStdCFStringAlertVersionOne = 1
+kHICommandOther = FOUR_CHAR_CODE('othr')
+kStdCFStringAlertVersionOne = 1
kStdAlertDoNotDisposeSheet = 1 << 0
kStdAlertDoNotAnimateOnDefault = 1 << 1
kStdAlertDoNotAnimateOnCancel = 1 << 2
diff --git a/Lib/plat-mac/Carbon/Dragconst.py b/Lib/plat-mac/Carbon/Dragconst.py
index e5c8b89c4c..38e12be7af 100644
--- a/Lib/plat-mac/Carbon/Dragconst.py
+++ b/Lib/plat-mac/Carbon/Dragconst.py
@@ -6,56 +6,56 @@ from Carbon.QuickDraw import *
fkDragActionAll = -1
-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)
kDragHasLeftSenderWindow = (1L << 0)
kDragInsideSenderApplication = (1L << 1)
-kDragInsideSenderWindow = (1L << 2)
+kDragInsideSenderWindow = (1L << 2)
kDragBehaviorNone = 0
-kDragBehaviorZoomBackAnimation = (1L << 0)
-kDragRegionAndImage = (1L << 4)
+kDragBehaviorZoomBackAnimation = (1L << 0)
+kDragRegionAndImage = (1L << 4)
kDragStandardTranslucency = 0L
kDragDarkTranslucency = 1L
kDragDarkerTranslucency = 2L
-kDragOpaqueTranslucency = 3L
+kDragOpaqueTranslucency = 3L
kDragRegionBegin = 1
kDragRegionDraw = 2
kDragRegionHide = 3
kDragRegionIdle = 4
-kDragRegionEnd = 5
+kDragRegionEnd = 5
kZoomNoAcceleration = 0
kZoomAccelerate = 1
-kZoomDecelerate = 2
+kZoomDecelerate = 2
flavorSenderOnly = (1 << 0)
flavorSenderTranslated = (1 << 1)
flavorNotSaved = (1 << 2)
flavorSystemTranslated = (1 << 8)
-flavorDataPromised = (1 << 9)
+flavorDataPromised = (1 << 9)
kDragFlavorTypeHFS = FOUR_CHAR_CODE('hfs ')
kDragFlavorTypePromiseHFS = FOUR_CHAR_CODE('phfs')
flavorTypeHFS = kDragFlavorTypeHFS
-flavorTypePromiseHFS = kDragFlavorTypePromiseHFS
+flavorTypePromiseHFS = kDragFlavorTypePromiseHFS
kDragPromisedFlavorFindFile = FOUR_CHAR_CODE('rWm1')
-kDragPromisedFlavor = FOUR_CHAR_CODE('fssP')
+kDragPromisedFlavor = FOUR_CHAR_CODE('fssP')
kDragPseudoCreatorVolumeOrDirectory = FOUR_CHAR_CODE('MACS')
kDragPseudoFileTypeVolume = FOUR_CHAR_CODE('disk')
-kDragPseudoFileTypeDirectory = FOUR_CHAR_CODE('fold')
-flavorTypeDirectory = FOUR_CHAR_CODE('diry')
+kDragPseudoFileTypeDirectory = FOUR_CHAR_CODE('fold')
+flavorTypeDirectory = FOUR_CHAR_CODE('diry')
kFlavorTypeClippingName = FOUR_CHAR_CODE('clnm')
kFlavorTypeClippingFilename = FOUR_CHAR_CODE('clfn')
kFlavorTypeDragToTrashOnly = FOUR_CHAR_CODE('fdtt')
-kFlavorTypeFinderNoTrackingBehavior = FOUR_CHAR_CODE('fntb')
+kFlavorTypeFinderNoTrackingBehavior = FOUR_CHAR_CODE('fntb')
kDragTrackingEnterHandler = 1
kDragTrackingEnterWindow = 2
kDragTrackingInWindow = 3
kDragTrackingLeaveWindow = 4
-kDragTrackingLeaveHandler = 5
+kDragTrackingLeaveHandler = 5
kDragActionNothing = 0L
kDragActionCopy = 1L
kDragActionAlias = (1L << 1)
@@ -66,21 +66,21 @@ kDragActionDelete = (1L << 5)
# kDragActionAll = (long)0xFFFFFFFF
dragHasLeftSenderWindow = kDragHasLeftSenderWindow
dragInsideSenderApplication = kDragInsideSenderApplication
-dragInsideSenderWindow = kDragInsideSenderWindow
+dragInsideSenderWindow = kDragInsideSenderWindow
dragTrackingEnterHandler = kDragTrackingEnterHandler
dragTrackingEnterWindow = kDragTrackingEnterWindow
dragTrackingInWindow = kDragTrackingInWindow
dragTrackingLeaveWindow = kDragTrackingLeaveWindow
-dragTrackingLeaveHandler = kDragTrackingLeaveHandler
+dragTrackingLeaveHandler = kDragTrackingLeaveHandler
dragRegionBegin = kDragRegionBegin
dragRegionDraw = kDragRegionDraw
dragRegionHide = kDragRegionHide
dragRegionIdle = kDragRegionIdle
-dragRegionEnd = kDragRegionEnd
+dragRegionEnd = kDragRegionEnd
zoomNoAcceleration = kZoomNoAcceleration
zoomAccelerate = kZoomAccelerate
-zoomDecelerate = kZoomDecelerate
+zoomDecelerate = kZoomDecelerate
kDragStandardImage = kDragStandardTranslucency
kDragDarkImage = kDragDarkTranslucency
kDragDarkerImage = kDragDarkerTranslucency
-kDragOpaqueImage = kDragOpaqueTranslucency
+kDragOpaqueImage = kDragOpaqueTranslucency
diff --git a/Lib/plat-mac/Carbon/Events.py b/Lib/plat-mac/Carbon/Events.py
index 48534698f7..269f4f1449 100644
--- a/Lib/plat-mac/Carbon/Events.py
+++ b/Lib/plat-mac/Carbon/Events.py
@@ -21,15 +21,15 @@ diskMask = 1 << diskEvt
activMask = 1 << activateEvt
highLevelEventMask = 0x0400
osMask = 1 << osEvt
-everyEvent = 0xFFFF
+everyEvent = 0xFFFF
charCodeMask = 0x000000FF
keyCodeMask = 0x0000FF00
adbAddrMask = 0x00FF0000
# osEvtMessageMask = (unsigned long)0xFF000000
mouseMovedMessage = 0x00FA
suspendResumeMessage = 0x0001
-resumeFlag = 1
-convertClipboardFlag = 2
+resumeFlag = 1
+convertClipboardFlag = 2
activeFlagBit = 0
btnStateBit = 7
cmdKeyBit = 8
@@ -39,7 +39,7 @@ optionKeyBit = 11
controlKeyBit = 12
rightShiftKeyBit = 13
rightOptionKeyBit = 14
-rightControlKeyBit = 15
+rightControlKeyBit = 15
activeFlag = 1 << activeFlagBit
btnState = 1 << btnStateBit
cmdKey = 1 << cmdKeyBit
@@ -87,7 +87,7 @@ kPencilUnicode = 0x270E
kCheckUnicode = 0x2713
kDiamondUnicode = 0x25C6
kBulletUnicode = 0x2022
-kAppleLogoUnicode = 0xF8FF
+kAppleLogoUnicode = 0xF8FF
networkEvt = 10
driverEvt = 11
app1Evt = 12
diff --git a/Lib/plat-mac/Carbon/Files.py b/Lib/plat-mac/Carbon/Files.py
index 54fe4b8214..678bbc7947 100644
--- a/Lib/plat-mac/Carbon/Files.py
+++ b/Lib/plat-mac/Carbon/Files.py
@@ -9,7 +9,7 @@ fsWrPerm = 0x02
fsRdWrPerm = 0x03
fsRdWrShPerm = 0x04
fsRdDenyPerm = 0x10
-fsWrDenyPerm = 0x20
+fsWrDenyPerm = 0x20
fsRtParID = 1
fsRtDirID = 2
fsAtMark = 0
@@ -27,7 +27,7 @@ forceReadBit = 6
forceReadMask = 0x0040
newLineBit = 7
newLineMask = 0x0080
-newLineCharMask = 0xFF00
+newLineCharMask = 0xFF00
fsSBPartialName = 1
fsSBFullName = 2
fsSBFlAttrib = 4
@@ -69,7 +69,7 @@ fsSBDrCrDatBit = 9
fsSBDrMdDatBit = 10
fsSBDrBkDatBit = 11
fsSBDrFndrInfoBit = 12
-fsSBDrParIDBit = 13
+fsSBDrParIDBit = 13
bLimitFCBs = 31
bLocalWList = 30
bNoMiniFndr = 29
@@ -106,19 +106,19 @@ bSupportsLongNames = 5
bSupportsMultiScriptNames = 6
bSupportsNamedForks = 7
bSupportsSubtreeIterators = 8
-bL2PCanMapFileBlocks = 9
+bL2PCanMapFileBlocks = 9
bParentModDateChanges = 10
-bAncestorModDateChanges = 11
+bAncestorModDateChanges = 11
bSupportsSymbolicLinks = 13
bIsAutoMounted = 14
-bAllowCDiDataHandler = 17
+bAllowCDiDataHandler = 17
kLargeIcon = 1
kLarge4BitIcon = 2
kLarge8BitIcon = 3
kSmallIcon = 4
kSmall4BitIcon = 5
kSmall8BitIcon = 6
-kicnsIconFamily = 239
+kicnsIconFamily = 239
kLargeIconSize = 256
kLarge4BitIconSize = 512
kLarge8BitIconSize = 1024
@@ -229,7 +229,7 @@ kioACAccessOwnerReadMask = 0x00000002
kioACAccessOwnerSearchBit = 0
kioACAccessOwnerSearchMask = 0x00000001
kfullPrivileges = 0x00070007
-kownerPrivileges = 0x00000007
+kownerPrivileges = 0x00000007
knoUser = 0
kadministratorUser = 1
knoGroup = 0
@@ -243,12 +243,12 @@ volMountInteractMask = 0x8000
volMountChangedBit = 14
volMountChangedMask = 0x4000
volMountFSReservedMask = 0x00FF
-volMountSysReservedMask = 0xFF00
-kAFPExtendedFlagsAlternateAddressMask = 1
+volMountSysReservedMask = 0xFF00
+kAFPExtendedFlagsAlternateAddressMask = 1
kAFPTagTypeIP = 0x01
kAFPTagTypeIPPort = 0x02
kAFPTagTypeDDP = 0x03
-kAFPTagTypeDNS = 0x04
+kAFPTagTypeDNS = 0x04
kAFPTagLengthIP = 0x06
kAFPTagLengthIPPort = 0x08
kAFPTagLengthDDP = 0x06
@@ -276,7 +276,7 @@ kFSCatInfoUserAccess = 0x00080000
kFSCatInfoAllDates = 0x000003E0
kFSCatInfoGettableInfo = 0x0003FFFF
kFSCatInfoSettableInfo = 0x00001FE3
-# kFSCatInfoReserved = (long)0xFFFC0000
+# kFSCatInfoReserved = (long)0xFFFC0000
kFSNodeLockedBit = 0
kFSNodeLockedMask = 0x0001
kFSNodeResOpenBit = 2
@@ -311,7 +311,7 @@ kFSAllocDefaultFlags = 0x0000
kFSAllocAllOrNothingMask = 0x0001
kFSAllocContiguousMask = 0x0002
kFSAllocNoRoundUpMask = 0x0004
-kFSAllocReservedMask = 0xFFF8
+kFSAllocReservedMask = 0xFFF8
kFSVolInfoNone = 0x0000
kFSVolInfoCreateDate = 0x0001
kFSVolInfoModDate = 0x0002
@@ -330,7 +330,7 @@ kFSVolInfoFlags = 0x2000
kFSVolInfoFSInfo = 0x4000
kFSVolInfoDriveInfo = 0x8000
kFSVolInfoGettableInfo = 0xFFFF
-kFSVolInfoSettableInfo = 0x3004
+kFSVolInfoSettableInfo = 0x3004
kFSVolFlagDefaultVolumeBit = 5
kFSVolFlagDefaultVolumeMask = 0x0020
kFSVolFlagFilesOpenBit = 6
@@ -341,19 +341,19 @@ kFSVolFlagSoftwareLockedBit = 15
kFSVolFlagSoftwareLockedMask = 0x8000
kFNDirectoryModifiedMessage = 1
kFNNoImplicitAllSubscription = (1 << 0)
-rAliasType = FOUR_CHAR_CODE('alis')
+rAliasType = FOUR_CHAR_CODE('alis')
kARMMountVol = 0x00000001
kARMNoUI = 0x00000002
kARMMultVols = 0x00000008
kARMSearch = 0x00000100
kARMSearchMore = 0x00000200
-kARMSearchRelFirst = 0x00000400
+kARMSearchRelFirst = 0x00000400
asiZoneName = -3
asiServerName = -2
asiVolumeName = -1
asiAliasName = 0
-asiParentName = 1
-kResolveAliasFileNoUI = 0x00000001
+asiParentName = 1
+kResolveAliasFileNoUI = 0x00000001
kClippingCreator = FOUR_CHAR_CODE('drag')
kClippingPictureType = FOUR_CHAR_CODE('clpp')
kClippingTextType = FOUR_CHAR_CODE('clpt')
@@ -369,7 +369,7 @@ kInternetLocationAFP = FOUR_CHAR_CODE('ilaf')
kInternetLocationAppleTalk = FOUR_CHAR_CODE('ilat')
kInternetLocationNSL = FOUR_CHAR_CODE('ilns')
kInternetLocationGeneric = FOUR_CHAR_CODE('ilge')
-kCustomIconResource = -16455
+kCustomIconResource = -16455
kCustomBadgeResourceType = FOUR_CHAR_CODE('badg')
kCustomBadgeResourceID = kCustomIconResource
kCustomBadgeResourceVersion = 0
@@ -388,7 +388,7 @@ kContainerCDROMAliasType = FOUR_CHAR_CODE('cddr')
kApplicationCPAliasType = FOUR_CHAR_CODE('acdp')
kApplicationDAAliasType = FOUR_CHAR_CODE('addp')
kPackageAliasType = FOUR_CHAR_CODE('fpka')
-kAppPackageAliasType = FOUR_CHAR_CODE('fapa')
+kAppPackageAliasType = FOUR_CHAR_CODE('fapa')
kSystemFolderAliasType = FOUR_CHAR_CODE('fasy')
kAppleMenuFolderAliasType = FOUR_CHAR_CODE('faam')
kStartupFolderAliasType = FOUR_CHAR_CODE('fast')
@@ -410,7 +410,7 @@ kIsStationery = 0x0800
kNameLocked = 0x1000
kHasBundle = 0x2000
kIsInvisible = 0x4000
-kIsAlias = 0x8000
+kIsAlias = 0x8000
fOnDesk = kIsOnDesk
fHasBundle = kHasBundle
fInvisible = kIsInvisible
@@ -420,7 +420,7 @@ fDisk = 0
kIsStationary = kIsStationery
kExtendedFlagsAreInvalid = 0x8000
kExtendedFlagHasCustomBadge = 0x0100
-kExtendedFlagHasRoutingInfo = 0x0004
+kExtendedFlagHasRoutingInfo = 0x0004
kFirstMagicBusyFiletype = FOUR_CHAR_CODE('bzy ')
kLastMagicBusyFiletype = FOUR_CHAR_CODE('bzy?')
kMagicBusyCreationDate = 0x4F3AFDB0
diff --git a/Lib/plat-mac/Carbon/Folders.py b/Lib/plat-mac/Carbon/Folders.py
index f22b2bad8a..52cf15808f 100644
--- a/Lib/plat-mac/Carbon/Folders.py
+++ b/Lib/plat-mac/Carbon/Folders.py
@@ -9,7 +9,7 @@ kSystemDomain = -32766
kLocalDomain = -32765
kNetworkDomain = -32764
kUserDomain = -32763
-kClassicDomain = -32762
+kClassicDomain = -32762
kCreateFolder = true
kDontCreateFolder = false
kSystemFolderType = FOUR_CHAR_CODE('macs')
@@ -28,7 +28,7 @@ kExtensionFolderType = FOUR_CHAR_CODE('extn')
kFontsFolderType = FOUR_CHAR_CODE('font')
kPreferencesFolderType = FOUR_CHAR_CODE('pref')
kSystemPreferencesFolderType = FOUR_CHAR_CODE('sprf')
-kTemporaryFolderType = FOUR_CHAR_CODE('temp')
+kTemporaryFolderType = FOUR_CHAR_CODE('temp')
kExtensionDisabledFolderType = FOUR_CHAR_CODE('extD')
kControlPanelDisabledFolderType = FOUR_CHAR_CODE('ctrD')
kSystemExtensionDisabledFolderType = FOUR_CHAR_CODE('macD')
@@ -86,7 +86,7 @@ kKeychainFolderType = FOUR_CHAR_CODE('kchn')
kQuickTimeExtensionsFolderType = FOUR_CHAR_CODE('qtex')
kDisplayExtensionsFolderType = FOUR_CHAR_CODE('dspl')
kMultiprocessingFolderType = FOUR_CHAR_CODE('mpxf')
-kPrintingPlugInsFolderType = FOUR_CHAR_CODE('pplg')
+kPrintingPlugInsFolderType = FOUR_CHAR_CODE('pplg')
kDomainTopLevelFolderType = FOUR_CHAR_CODE('dtop')
kDomainLibraryFolderType = FOUR_CHAR_CODE('dlib')
kColorSyncFolderType = FOUR_CHAR_CODE('sync')
@@ -127,15 +127,15 @@ kInstallerReceiptsFolderType = FOUR_CHAR_CODE('rcpt')
kFileSystemSupportFolderType = FOUR_CHAR_CODE('fsys')
kAppleShareSupportFolderType = FOUR_CHAR_CODE('shar')
kAppleShareAuthenticationFolderType = FOUR_CHAR_CODE('auth')
-kMIDIDriversFolderType = FOUR_CHAR_CODE('midi')
+kMIDIDriversFolderType = FOUR_CHAR_CODE('midi')
kLocalesFolderType = FOUR_CHAR_CODE('\xc4loc')
-kFindByContentPluginsFolderType = FOUR_CHAR_CODE('fbcp')
+kFindByContentPluginsFolderType = FOUR_CHAR_CODE('fbcp')
kUsersFolderType = FOUR_CHAR_CODE('usrs')
kCurrentUserFolderType = FOUR_CHAR_CODE('cusr')
kCurrentUserRemoteFolderLocation = FOUR_CHAR_CODE('rusf')
kCurrentUserRemoteFolderType = FOUR_CHAR_CODE('rusr')
kSharedUserDataFolderType = FOUR_CHAR_CODE('sdat')
-kVolumeSettingsFolderType = FOUR_CHAR_CODE('vsfd')
+kVolumeSettingsFolderType = FOUR_CHAR_CODE('vsfd')
kAppleshareAutomountServerAliasesFolderType = FOUR_CHAR_CODE('srv\xc4')
kPreMacOS91ApplicationsFolderType = FOUR_CHAR_CODE('\x8cpps')
kPreMacOS91InstallerLogsFolderType = FOUR_CHAR_CODE('\x94lgf')
@@ -145,7 +145,7 @@ kPreMacOS91AppleExtrasFolderType = FOUR_CHAR_CODE('\x8cex\xc4')
kPreMacOS91MacOSReadMesFolderType = FOUR_CHAR_CODE('\xb5or\xc4')
kPreMacOS91InternetFolderType = FOUR_CHAR_CODE('\x94nt\xc4')
kPreMacOS91AutomountedServersFolderType = FOUR_CHAR_CODE('\xa7rv\xc4')
-kPreMacOS91StationeryFolderType = FOUR_CHAR_CODE('\xbfdst')
+kPreMacOS91StationeryFolderType = FOUR_CHAR_CODE('\xbfdst')
kCreateFolderAtBoot = 0x00000002
kCreateFolderAtBootBit = 1
kFolderCreatedInvisible = 0x00000004
@@ -171,7 +171,7 @@ kRelativeFolder = FOUR_CHAR_CODE('relf')
kSpecialFolder = FOUR_CHAR_CODE('spcf')
kBlessedFolder = FOUR_CHAR_CODE('blsf')
kRootFolder = FOUR_CHAR_CODE('rotf')
-kCurrentUserFolderLocation = FOUR_CHAR_CODE('cusf')
+kCurrentUserFolderLocation = FOUR_CHAR_CODE('cusf')
kFindFolderRedirectionFlagUseDistinctUserFoldersBit = 0
kFindFolderRedirectionFlagUseGivenVRefAndDirIDAsUserFolderBit = 1
kFindFolderRedirectionFlagsUseGivenVRefNumAndDirIDAsRemoteUserFolderBit = 2
@@ -184,7 +184,7 @@ kFolderManagerNotificationMessagePreUserLogIn = FOUR_CHAR_CODE('logj')
kFolderManagerNotificationMessageUserLogOut = FOUR_CHAR_CODE('log-')
kFolderManagerNotificationMessagePostUserLogOut = FOUR_CHAR_CODE('logp')
kFolderManagerNotificationDiscardCachedData = FOUR_CHAR_CODE('dche')
-kFolderManagerNotificationMessageLoginStartup = FOUR_CHAR_CODE('stup')
+kFolderManagerNotificationMessageLoginStartup = FOUR_CHAR_CODE('stup')
kDoNotRemoveWhenCurrentApplicationQuitsBit = 0
-kDoNotRemoveWheCurrentApplicationQuitsBit = kDoNotRemoveWhenCurrentApplicationQuitsBit
+kDoNotRemoveWheCurrentApplicationQuitsBit = kDoNotRemoveWhenCurrentApplicationQuitsBit
kStopIfAnyNotificationProcReturnsErrorBit = 31
diff --git a/Lib/plat-mac/Carbon/Icons.py b/Lib/plat-mac/Carbon/Icons.py
index 1ed8d50113..86dae632dd 100644
--- a/Lib/plat-mac/Carbon/Icons.py
+++ b/Lib/plat-mac/Carbon/Icons.py
@@ -254,7 +254,7 @@ kTrueTypeFontIcon = FOUR_CHAR_CODE('tfil')
kTrueTypeFlatFontIcon = FOUR_CHAR_CODE('sfnt')
kTrueTypeMultiFlatFontIcon = FOUR_CHAR_CODE('ttcf')
kUserIDiskIcon = FOUR_CHAR_CODE('udsk')
-kInternationResourcesIcon = kInternationalResourcesIcon
+kInternationResourcesIcon = kInternationalResourcesIcon
kInternetLocationHTTPIcon = FOUR_CHAR_CODE('ilht')
kInternetLocationFTPIcon = FOUR_CHAR_CODE('ilft')
kInternetLocationAppleShareIcon = FOUR_CHAR_CODE('ilaf')
diff --git a/Lib/plat-mac/Carbon/LaunchServices.py b/Lib/plat-mac/Carbon/LaunchServices.py
index 22bb42115a..daff446933 100644
--- a/Lib/plat-mac/Carbon/LaunchServices.py
+++ b/Lib/plat-mac/Carbon/LaunchServices.py
@@ -20,10 +20,10 @@ kLSNotRegisteredErr = -10819
kLSAppDoesNotClaimTypeErr = -10820
kLSAppDoesNotSupportSchemeWarning = -10821
kLSServerCommunicationErr = -10822
-kLSCannotSetInfoErr = -10823
+kLSCannotSetInfoErr = -10823
kLSInitializeDefaults = 0x00000001
-kLSMinCatInfoBitmap = (kFSCatInfoNodeFlags | kFSCatInfoParentDirID | kFSCatInfoFinderInfo | kFSCatInfoFinderXInfo)
-# kLSInvalidExtensionIndex = (unsigned long)0xFFFFFFFF
+kLSMinCatInfoBitmap = (kFSCatInfoNodeFlags | kFSCatInfoParentDirID | kFSCatInfoFinderInfo | kFSCatInfoFinderXInfo)
+# kLSInvalidExtensionIndex = (unsigned long)0xFFFFFFFF
kLSRequestExtension = 0x00000001
kLSRequestTypeCreator = 0x00000002
kLSRequestBasicFlagsOnly = 0x00000004
@@ -31,7 +31,7 @@ kLSRequestAppTypeFlags = 0x00000008
kLSRequestAllFlags = 0x00000010
kLSRequestIconAndKind = 0x00000020
kLSRequestExtensionFlagsOnly = 0x00000040
-# kLSRequestAllInfo = (unsigned long)0xFFFFFFFF
+# kLSRequestAllInfo = (unsigned long)0xFFFFFFFF
kLSItemInfoIsPlainFile = 0x00000001
kLSItemInfoIsPackage = 0x00000002
kLSItemInfoIsApplication = 0x00000004
@@ -45,16 +45,16 @@ kLSItemInfoAppPrefersNative = 0x00000200
kLSItemInfoAppPrefersClassic = 0x00000400
kLSItemInfoAppIsScriptable = 0x00000800
kLSItemInfoIsVolume = 0x00001000
-kLSItemInfoExtensionIsHidden = 0x00100000
+kLSItemInfoExtensionIsHidden = 0x00100000
kLSRolesNone = 0x00000001
kLSRolesViewer = 0x00000002
kLSRolesEditor = 0x00000004
-# kLSRolesAll = (unsigned long)0xFFFFFFFF
+# kLSRolesAll = (unsigned long)0xFFFFFFFF
kLSUnknownKindID = 0
# kLSUnknownType = 0
# kLSUnknownCreator = 0
kLSAcceptDefault = 0x00000001
-kLSAcceptAllowLoginUI = 0x00000002
+kLSAcceptAllowLoginUI = 0x00000002
kLSLaunchDefaults = 0x00000001
kLSLaunchAndPrint = 0x00000002
kLSLaunchReserved2 = 0x00000004
@@ -71,4 +71,4 @@ kLSLaunchStartClassic = 0x00020000
kLSLaunchInClassic = 0x00040000
kLSLaunchNewInstance = 0x00080000
kLSLaunchAndHide = 0x00100000
-kLSLaunchAndHideOthers = 0x00200000
+kLSLaunchAndHideOthers = 0x00200000
diff --git a/Lib/plat-mac/Carbon/Lists.py b/Lib/plat-mac/Carbon/Lists.py
index 76518baab8..723294c614 100644
--- a/Lib/plat-mac/Carbon/Lists.py
+++ b/Lib/plat-mac/Carbon/Lists.py
@@ -4,7 +4,7 @@ def FOUR_CHAR_CODE(x): return x
listNotifyNothing = FOUR_CHAR_CODE('nada')
listNotifyClick = FOUR_CHAR_CODE('clik')
listNotifyDoubleClick = FOUR_CHAR_CODE('dblc')
-listNotifyPreClick = FOUR_CHAR_CODE('pclk')
+listNotifyPreClick = FOUR_CHAR_CODE('pclk')
lDrawingModeOffBit = 3
lDoVAutoscrollBit = 1
lDoHAutoscrollBit = 0
diff --git a/Lib/plat-mac/Carbon/MacHelp.py b/Lib/plat-mac/Carbon/MacHelp.py
index a231a8d1f4..06b9912bfc 100644
--- a/Lib/plat-mac/Carbon/MacHelp.py
+++ b/Lib/plat-mac/Carbon/MacHelp.py
@@ -51,8 +51,8 @@ kHMContentProvided = 0
kHMContentNotProvided = 1
kHMContentNotProvidedDontPropagate = 2
kHMMinimumContentIndex = 0
-kHMMaximumContentIndex = 1
+kHMMaximumContentIndex = 1
errHMIllegalContentForMinimumState = -10980
-errHMIllegalContentForMaximumState = -10981
+errHMIllegalContentForMaximumState = -10981
kHMIllegalContentForMinimumState = errHMIllegalContentForMinimumState
kHelpTagEventHandlerTag = FOUR_CHAR_CODE('hevt')
diff --git a/Lib/plat-mac/Carbon/MacTextEditor.py b/Lib/plat-mac/Carbon/MacTextEditor.py
index fcc6fd2e23..4609d8db89 100644
--- a/Lib/plat-mac/Carbon/MacTextEditor.py
+++ b/Lib/plat-mac/Carbon/MacTextEditor.py
@@ -145,7 +145,7 @@ kTXNDropAction = 11
kTXNMoveAction = 12
kTXNFontFeatureAction = 13
kTXNFontVariationAction = 14
-kTXNUndoLastAction = 1024
+kTXNUndoLastAction = 1024
# kTXNClearThisControl = (long)0xFFFFFFFF
# kTXNClearTheseFontFeatures = (long)0x80000000
kTXNReadWrite = false
@@ -176,7 +176,7 @@ kTXNFlushLeft = 1
kTXNFlushRight = 2
kTXNCenter = 4
kTXNFullJust = 8
-kTXNForceFullJust = 16
+kTXNForceFullJust = 16
kScrollBarsAlwaysActive = true
kScrollBarsSyncWithFocus = false
# kTXNDontCareTypeSize = (long)0xFFFFFFFF
@@ -192,7 +192,7 @@ kTXNSingleStylePerTextDocumentResType = FOUR_CHAR_CODE('MPSR')
kTXNMultipleStylesPerTextDocumentResType = FOUR_CHAR_CODE('styl')
kTXNShowStart = false
kTXNShowEnd = true
-kTXNDefaultFontName = 0
+kTXNDefaultFontName = 0
kTXNDefaultFontSize = 0x000C0000
kTXNDefaultFontStyle = normal
kTXNQDFontNameAttribute = FOUR_CHAR_CODE('fntn')
diff --git a/Lib/plat-mac/Carbon/MediaDescr.py b/Lib/plat-mac/Carbon/MediaDescr.py
index acacfb1489..254634bb29 100644
--- a/Lib/plat-mac/Carbon/MediaDescr.py
+++ b/Lib/plat-mac/Carbon/MediaDescr.py
@@ -4,58 +4,58 @@ import struct
Error = 'MediaDescr.Error'
class _MediaDescriptionCodec:
- def __init__(self, trunc, size, names, fmt):
- self.trunc = trunc
- self.size = size
- self.names = names
- self.fmt = fmt
+ def __init__(self, trunc, size, names, fmt):
+ self.trunc = trunc
+ self.size = size
+ self.names = names
+ self.fmt = fmt
- def decode(self, data):
- if self.trunc:
- data = data[:self.size]
- values = struct.unpack(self.fmt, data)
- if len(values) != len(self.names):
- raise Error, ('Format length does not match number of names', descr)
- rv = {}
- for i in range(len(values)):
- name = self.names[i]
- value = values[i]
- if type(name) == type(()):
- name, cod, dec = name
- value = dec(value)
- rv[name] = value
- return rv
+ def decode(self, data):
+ if self.trunc:
+ data = data[:self.size]
+ values = struct.unpack(self.fmt, data)
+ if len(values) != len(self.names):
+ raise Error, ('Format length does not match number of names', descr)
+ rv = {}
+ for i in range(len(values)):
+ name = self.names[i]
+ value = values[i]
+ if type(name) == type(()):
+ name, cod, dec = name
+ value = dec(value)
+ rv[name] = value
+ return rv
- def encode(dict):
- list = [self.fmt]
- for name in self.names:
- if type(name) == type(()):
- name, cod, dec = name
- else:
- cod = dec = None
- value = dict[name]
- if cod:
- value = cod(value)
- list.append(value)
- rv = struct.pack(*list)
- return rv
+ def encode(dict):
+ list = [self.fmt]
+ for name in self.names:
+ if type(name) == type(()):
+ name, cod, dec = name
+ else:
+ cod = dec = None
+ value = dict[name]
+ if cod:
+ value = cod(value)
+ list.append(value)
+ rv = struct.pack(*list)
+ return rv
# Helper functions
def _tofixed(float):
- hi = int(float)
- lo = int(float*0x10000) & 0xffff
- return (hi<<16)|lo
+ hi = int(float)
+ lo = int(float*0x10000) & 0xffff
+ return (hi<<16)|lo
def _fromfixed(fixed):
- hi = (fixed >> 16) & 0xffff
- lo = (fixed & 0xffff)
- return hi + (lo / float(0x10000))
+ hi = (fixed >> 16) & 0xffff
+ lo = (fixed & 0xffff)
+ return hi + (lo / float(0x10000))
def _tostr31(str):
- return chr(len(str)) + str + '\0'*(31-len(str))
+ return chr(len(str)) + str + '\0'*(31-len(str))
def _fromstr31(str31):
- return str31[1:1+ord(str31[0])]
+ return str31[1:1+ord(str31[0])]
SampleDescription = _MediaDescriptionCodec(
1, # May be longer, truncate
diff --git a/Lib/plat-mac/Carbon/Menus.py b/Lib/plat-mac/Carbon/Menus.py
index abdde79e55..01affb0968 100644
--- a/Lib/plat-mac/Carbon/Menus.py
+++ b/Lib/plat-mac/Carbon/Menus.py
@@ -1,7 +1,7 @@
# Generated from 'Menus.h'
def FOUR_CHAR_CODE(x): return x
-noMark = 0
+noMark = 0
kMenuDrawMsg = 0
kMenuSizeMsg = 2
kMenuPopUpMsg = 3
@@ -15,7 +15,7 @@ mChooseMsg = 1
mDrawItemMsg = 4
kMenuChooseMsg = 1
kMenuDrawItemMsg = 4
-kThemeSavvyMenuResponse = 0x7473
+kThemeSavvyMenuResponse = 0x7473
kMenuInitMsg = 8
kMenuDisposeMsg = 9
kMenuFindItemMsg = 10
@@ -26,14 +26,14 @@ hMenuCmd = 27
hierMenu = -1
kInsertHierarchicalMenu = -1
mctAllItems = -98
-mctLastIDIndic = -99
+mctLastIDIndic = -99
kMenuStdMenuProc = 63
kMenuStdMenuBarProc = 63
kMenuNoModifiers = 0
kMenuShiftModifier = (1 << 0)
kMenuOptionModifier = (1 << 1)
kMenuControlModifier = (1 << 2)
-kMenuNoCommandModifier = (1 << 3)
+kMenuNoCommandModifier = (1 << 3)
kMenuNoIcon = 0
kMenuIconType = 1
kMenuShrinkIconType = 2
@@ -43,7 +43,7 @@ kMenuIconSuiteType = 5
kMenuIconRefType = 6
kMenuCGImageRefType = 7
kMenuSystemIconSelectorType = 8
-kMenuIconResourceType = 9
+kMenuIconResourceType = 9
kMenuNullGlyph = 0x00
kMenuTabRightGlyph = 0x02
kMenuTabLeftGlyph = 0x03
@@ -101,7 +101,7 @@ kMenuF12Glyph = 0x7A
kMenuF13Glyph = 0x87
kMenuF14Glyph = 0x88
kMenuF15Glyph = 0x89
-kMenuControlISOGlyph = 0x8A
+kMenuControlISOGlyph = 0x8A
kMenuAttrExcludesMarkColumn = (1 << 0)
kMenuAttrAutoDisable = (1 << 2)
kMenuAttrUsePencilGlyph = (1 << 3)
@@ -147,14 +147,14 @@ kMenuItemDataIndent = (1 << 19)
kMenuItemDataCmdVirtualKey = (1 << 20)
kMenuItemDataAllDataVersionOne = 0x000FFFFF
kMenuItemDataAllDataVersionTwo = kMenuItemDataAllDataVersionOne | kMenuItemDataCmdVirtualKey
-kMenuDefProcPtr = 0
-kMenuPropertyPersistent = 0x00000001
+kMenuDefProcPtr = 0
+kMenuPropertyPersistent = 0x00000001
kHierarchicalFontMenuOption = 0x00000001
gestaltContextualMenuAttr = FOUR_CHAR_CODE('cmnu')
gestaltContextualMenuUnusedBit = 0
gestaltContextualMenuTrapAvailable = 1
gestaltContextualMenuHasAttributeAndModifierKeys = 2
-gestaltContextualMenuHasUnicodeSupport = 3
+gestaltContextualMenuHasUnicodeSupport = 3
kCMHelpItemNoHelp = 0
kCMHelpItemAppleGuide = 1
kCMHelpItemOtherHelp = 2
diff --git a/Lib/plat-mac/Carbon/OSAconst.py b/Lib/plat-mac/Carbon/OSAconst.py
index ccce00a961..3b64c24810 100644
--- a/Lib/plat-mac/Carbon/OSAconst.py
+++ b/Lib/plat-mac/Carbon/OSAconst.py
@@ -18,10 +18,10 @@ typeOSADialectInfo = FOUR_CHAR_CODE('difo')
keyOSADialectName = FOUR_CHAR_CODE('dnam')
keyOSADialectCode = FOUR_CHAR_CODE('dcod')
keyOSADialectLangCode = FOUR_CHAR_CODE('dlcd')
-keyOSADialectScriptCode = FOUR_CHAR_CODE('dscd')
+keyOSADialectScriptCode = FOUR_CHAR_CODE('dscd')
kOSANullScript = 0L
kOSANullMode = 0
-kOSAModeNull = 0
+kOSAModeNull = 0
kOSASupportsCompiling = 0x0002
kOSASupportsGetSource = 0x0004
kOSASupportsAECoercion = 0x0008
@@ -130,4 +130,4 @@ keyProcedureName = FOUR_CHAR_CODE('dfnm')
keyStatementRange = FOUR_CHAR_CODE('dfsr')
keyLocalsNames = FOUR_CHAR_CODE('dfln')
keyGlobalsNames = FOUR_CHAR_CODE('dfgn')
-keyParamsNames = FOUR_CHAR_CODE('dfpn')
+keyParamsNames = FOUR_CHAR_CODE('dfpn')
diff --git a/Lib/plat-mac/Carbon/Qt.py b/Lib/plat-mac/Carbon/Qt.py
index 23d44d2dac..590a92ad17 100644
--- a/Lib/plat-mac/Carbon/Qt.py
+++ b/Lib/plat-mac/Carbon/Qt.py
@@ -3,4 +3,3 @@ try:
_ = AddFilePreview
except:
raise ImportError, "Old (2.3) _Qt.so module loaded in stead of new (2.4) _Qt.so"
- \ No newline at end of file
diff --git a/Lib/plat-mac/Carbon/QuickDraw.py b/Lib/plat-mac/Carbon/QuickDraw.py
index 9209a357f6..65c2f9a946 100644
--- a/Lib/plat-mac/Carbon/QuickDraw.py
+++ b/Lib/plat-mac/Carbon/QuickDraw.py
@@ -2,15 +2,15 @@
def FOUR_CHAR_CODE(x): return x
-normal = 0
-bold = 1
-italic = 2
-underline = 4
-outline = 8
-shadow = 0x10
-condense = 0x20
-extend = 0x40
-invalColReq = -1
+normal = 0
+bold = 1
+italic = 2
+underline = 4
+outline = 8
+shadow = 0x10
+condense = 0x20
+extend = 0x40
+invalColReq = -1
srcCopy = 0
srcOr = 1
srcXor = 2
@@ -68,7 +68,7 @@ picRParen = 1
clutType = 0
fixedType = 1
directType = 2
-gdDevType = 0
+gdDevType = 0
interlacedDevice = 2
hwMirroredDevice = 4
roundedDevice = 5
@@ -85,7 +85,7 @@ hiliteBit = 7
pHiliteBit = 0
defQDColors = 127
RGBDirect = 16
-baseAddr32 = 4
+baseAddr32 = 4
sysPatListID = 0
iBeamCursor = 1
crossCursor = 2
@@ -125,7 +125,7 @@ k32ARGBPixelFormat = 0x00000020
k1IndexedGrayPixelFormat = 0x00000021
k2IndexedGrayPixelFormat = 0x00000022
k4IndexedGrayPixelFormat = 0x00000024
-k8IndexedGrayPixelFormat = 0x00000028
+k8IndexedGrayPixelFormat = 0x00000028
k16LE555PixelFormat = FOUR_CHAR_CODE('L555')
k16LE5551PixelFormat = FOUR_CHAR_CODE('5551')
k16BE565PixelFormat = FOUR_CHAR_CODE('B565')
@@ -141,7 +141,7 @@ kYUV411PixelFormat = FOUR_CHAR_CODE('Y411')
kYVYU422PixelFormat = FOUR_CHAR_CODE('YVYU')
kUYVY422PixelFormat = FOUR_CHAR_CODE('UYVY')
kYUV211PixelFormat = FOUR_CHAR_CODE('Y211')
-k2vuyPixelFormat = FOUR_CHAR_CODE('2vuy')
+k2vuyPixelFormat = FOUR_CHAR_CODE('2vuy')
kCursorImageMajorVersion = 0x0001
kCursorImageMinorVersion = 0x0000
kQDParseRegionFromTop = (1 << 0)
@@ -157,7 +157,7 @@ colorXorXFer = 52
noiseXFer = 53
customXFer = 54
kXFer1PixelAtATime = 0x00000001
-kXFerConvertPixelToRGB32 = 0x00000002
+kXFerConvertPixelToRGB32 = 0x00000002
kCursorComponentsVersion = 0x00010001
kCursorComponentType = FOUR_CHAR_CODE('curs')
cursorDoesAnimate = 1L << 0
@@ -179,20 +179,20 @@ kCursorComponentLastReserved = 0x0050
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
leftCaret = 0
rightCaret = -1
-kHilite = 1
+kHilite = 1
smLeftCaret = 0
smRightCaret = -1
-smHilite = 1
+smHilite = 1
onlyStyleRun = 0
leftStyleRun = 1
rightStyleRun = 2
@@ -200,17 +200,17 @@ middleStyleRun = 3
smOnlyStyleRun = 0
smLeftStyleRun = 1
smRightStyleRun = 2
-smMiddleStyleRun = 3
+smMiddleStyleRun = 3
truncEnd = 0
truncMiddle = 0x4000
smTruncEnd = 0
-smTruncMiddle = 0x4000
+smTruncMiddle = 0x4000
notTruncated = 0
truncated = 1
truncErr = -1
smNotTruncated = 0
smTruncated = 1
-smTruncErr = -1
+smTruncErr = -1
smBreakWord = 0
smBreakChar = 1
smBreakOverflow = 2
diff --git a/Lib/plat-mac/Carbon/QuickTime.py b/Lib/plat-mac/Carbon/QuickTime.py
index 6ab0304fbd..8fba58cb3e 100644
--- a/Lib/plat-mac/Carbon/QuickTime.py
+++ b/Lib/plat-mac/Carbon/QuickTime.py
@@ -118,7 +118,7 @@ dfDropShadow = 1 << 12
dfAntiAlias = 1 << 13
dfKeyedText = 1 << 14
dfInverseHilite = 1 << 15
-dfTextColorHilite = 1 << 16
+dfTextColorHilite = 1 << 16
searchTextDontGoToFoundTime = 1L << 16
searchTextDontHiliteFoundText = 1L << 17
searchTextOneTrackOnly = 1L << 18
@@ -144,7 +144,7 @@ kTextKeyEntry = 18
kTextMouseDown = 19
kTextTextBox = 20
kTextEditState = 21
-kTextLength = 22
+kTextLength = 22
k3DMediaRendererEntry = FOUR_CHAR_CODE('rend')
k3DMediaRendererName = FOUR_CHAR_CODE('name')
k3DMediaRendererCode = FOUR_CHAR_CODE('rcod')
@@ -295,7 +295,7 @@ kActionListPasteFromXML = 13315
kActionListSetMatchingFromXML = 13316
kActionListSetFromURL = 13317
kActionListExchangeLists = 13318
-kActionListServerQuery = 13319
+kActionListServerQuery = 13319
kOperandExpression = 1
kOperandConstant = 2
kOperandSubscribedToChannel = 3
@@ -430,7 +430,7 @@ kOperandFlashTrackVariable = 9216
kOperandStringLength = 10240
kOperandStringCompare = 10241
kOperandStringSubString = 10242
-kOperandStringConcat = 10243
+kOperandStringConcat = 10243
kFirstMovieAction = kActionMovieSetVolume
kLastMovieAction = kActionMovieSetScale
kFirstTrackAction = kActionTrackSetVolume
@@ -477,7 +477,7 @@ kTargetSpriteName = FOUR_CHAR_CODE('spna')
kTargetSpriteID = FOUR_CHAR_CODE('spid')
kTargetSpriteIndex = FOUR_CHAR_CODE('spin')
kTargetQD3DNamedObjectName = FOUR_CHAR_CODE('nana')
-kTargetCurrentQTEventParams = FOUR_CHAR_CODE('evpa')
+kTargetCurrentQTEventParams = FOUR_CHAR_CODE('evpa')
kQTEventType = FOUR_CHAR_CODE('evnt')
kAction = FOUR_CHAR_CODE('actn')
kWhichAction = FOUR_CHAR_CODE('whic')
@@ -508,7 +508,7 @@ kQTEventKey = FOUR_CHAR_CODE('key ')
kQTEventMovieLoaded = FOUR_CHAR_CODE('load')
kQTEventRequestToModifyMovie = FOUR_CHAR_CODE('reqm')
kQTEventListReceived = FOUR_CHAR_CODE('list')
-kQTEventKeyUp = FOUR_CHAR_CODE('keyU')
+kQTEventKeyUp = FOUR_CHAR_CODE('keyU')
kActionFlagActionIsDelta = 1L << 1
kActionFlagParameterWrapsAround = 1L << 2
kActionFlagActionIsToggle = 1L << 3
@@ -574,12 +574,12 @@ callBackAtInterrupt = 0x8000
callBackAtDeferredTask = 0x4000
qtcbNeedsRateChanges = 1
qtcbNeedsTimeChanges = 2
-qtcbNeedsStartStopChanges = 4
+qtcbNeedsStartStopChanges = 4
keepInRam = 1 << 0
unkeepInRam = 1 << 1
flushFromRam = 1 << 2
loadForwardTrackEdits = 1 << 3
-loadBackwardTrackEdits = 1 << 4
+loadBackwardTrackEdits = 1 << 4
newMovieActive = 1 << 0
newMovieDontResolveDataRefs = 1 << 1
newMovieDontAskUnresolvedDataRefs = 1 << 2
@@ -593,7 +593,7 @@ trackUsageInMovie = 1 << 1
trackUsageInPreview = 1 << 2
trackUsageInPoster = 1 << 3
mediaSampleNotSync = 1 << 0
-mediaSampleShadowSync = 1 << 1
+mediaSampleShadowSync = 1 << 1
pasteInParallel = 1 << 0
showUserSettingsDialog = 1 << 1
movieToFileOnlyExport = 1 << 2
@@ -615,17 +615,17 @@ flattenDontInterleaveFlatten = 1L << 3
flattenFSSpecPtrIsDataRefRecordPtr = 1L << 4
flattenCompressMovieResource = 1L << 5
flattenForceMovieResourceBeforeMovieData = 1L << 6
-movieInDataForkResID = -1
+movieInDataForkResID = -1
mcTopLeftMovie = 1 << 0
mcScaleMovieToFit = 1 << 1
mcWithBadge = 1 << 2
mcNotVisible = 1 << 3
-mcWithFrame = 1 << 4
+mcWithFrame = 1 << 4
movieScrapDontZeroScrap = 1 << 0
movieScrapOnlyPutMovie = 1 << 1
dataRefSelfReference = 1 << 0
dataRefWasNotResolved = 1 << 1
-kMovieAnchorDataRefIsDefault = 1 << 0
+kMovieAnchorDataRefIsDefault = 1 << 0
hintsScrubMode = 1 << 0
hintsLoop = 1 << 1
hintsDontPurge = 1 << 2
@@ -667,11 +667,11 @@ kGetMovieImporterValidateToFind = 1L << 0
kGetMovieImporterAllowNewFile = 1L << 1
kGetMovieImporterDontConsiderGraphicsImporters = 1L << 2
kGetMovieImporterDontConsiderFileOnlyImporters = 1L << 6
-kGetMovieImporterAutoImportOnly = 1L << 10
+kGetMovieImporterAutoImportOnly = 1L << 10
kQTGetMIMETypeInfoIsQuickTimeMovieType = FOUR_CHAR_CODE('moov')
-kQTGetMIMETypeInfoIsUnhelpfulType = FOUR_CHAR_CODE('dumb')
+kQTGetMIMETypeInfoIsUnhelpfulType = FOUR_CHAR_CODE('dumb')
kQTCopyUserDataReplace = FOUR_CHAR_CODE('rplc')
-kQTCopyUserDataMerge = FOUR_CHAR_CODE('merg')
+kQTCopyUserDataMerge = FOUR_CHAR_CODE('merg')
kMovieLoadStateError = -1L
kMovieLoadStateLoading = 1000
kMovieLoadStateLoaded = 2000
@@ -682,7 +682,7 @@ kQTDontUseDataToFindImporter = 1L << 0
kQTDontLookForMovieImporterIfGraphicsImporterFound = 1L << 1
kQTAllowOpeningStillImagesAsMovies = 1L << 2
kQTAllowImportersThatWouldCreateNewFile = 1L << 3
-kQTAllowAggressiveImporters = 1L << 4
+kQTAllowAggressiveImporters = 1L << 4
preloadAlways = 1L << 0
preloadOnlyIfEnabled = 1L << 1
fullScreenHideCursor = 1L << 0
@@ -693,13 +693,13 @@ movieExecuteWiredActionDontExecute = 1L << 0
kRefConNavigationNext = 0
kRefConNavigationPrevious = 1
kRefConPropertyCanHaveFocus = 1
-kRefConPropertyHasFocus = 2
+kRefConPropertyHasFocus = 2
kTrackFocusCanEditFlag = FOUR_CHAR_CODE('kedt')
kTrackDefaultFocusFlags = FOUR_CHAR_CODE('kfoc')
kTrackFocusDefaultRefcon = FOUR_CHAR_CODE('kref')
kTrackFocusOn = 1
-kTrackHandlesTabs = 2
-kFlashTrackPropertyAcceptAllClicks = FOUR_CHAR_CODE('clik')
+kTrackHandlesTabs = 2
+kFlashTrackPropertyAcceptAllClicks = FOUR_CHAR_CODE('clik')
kBackgroundSpriteLayerNum = 32767
kSpritePropertyMatrix = 1
kSpritePropertyImageDescription = 2
@@ -746,7 +746,7 @@ kTweenRecordNoFlags = 0
kTweenRecordIsAtInterruptTime = 0x00000001
kEffectNameAtom = FOUR_CHAR_CODE('name')
kEffectTypeAtom = FOUR_CHAR_CODE('type')
-kEffectManufacturerAtom = FOUR_CHAR_CODE('manu')
+kEffectManufacturerAtom = FOUR_CHAR_CODE('manu')
pdActionConfirmDialog = 1
pdActionSetAppleMenu = 2
pdActionSetEditMenu = 3
@@ -781,20 +781,20 @@ pdActionCustomSetEditCallout = 31
pdActionCustomGetEnableValue = 32
pdActionCustomSetSampleTime = 33
pdActionCustomGetValue = 34
-pdActionCustomDoEditCommand = 35
+pdActionCustomDoEditCommand = 35
pdSampleTimeDisplayOptionsNone = 0x00000000
pdActionFocusOff = 0
pdActionFocusFirst = 1
pdActionFocusLast = 2
pdActionFocusForward = 3
-pdActionFocusBackward = 4
-elOptionsIncludeNoneInList = 0x00000001
+pdActionFocusBackward = 4
+elOptionsIncludeNoneInList = 0x00000001
pdOptionsCollectOneValue = 0x00000001
pdOptionsAllowOptionalInterpolations = 0x00000002
pdOptionsModalDialogBox = 0x00000004
pdOptionsEditCurrentEffectOnly = 0x00000008
-pdOptionsHidePreview = 0x00000010
-effectIsRealtime = 0
+pdOptionsHidePreview = 0x00000010
+effectIsRealtime = 0
kAccessKeyAtomType = FOUR_CHAR_CODE('acky')
kAccessKeySystemFlag = 1L << 0
ConnectionSpeedPrefsType = FOUR_CHAR_CODE('cspd')
@@ -818,14 +818,14 @@ kQTParseTextHREFBaseURL = FOUR_CHAR_CODE('burl')
kQTParseTextHREFClickPoint = FOUR_CHAR_CODE('clik')
kQTParseTextHREFUseAltDelim = FOUR_CHAR_CODE('altd')
kQTParseTextHREFDelimiter = FOUR_CHAR_CODE('delm')
-kQTParseTextHREFRecomposeHREF = FOUR_CHAR_CODE('rhrf')
+kQTParseTextHREFRecomposeHREF = FOUR_CHAR_CODE('rhrf')
kQTParseTextHREFURL = FOUR_CHAR_CODE('url ')
kQTParseTextHREFTarget = FOUR_CHAR_CODE('targ')
kQTParseTextHREFChapter = FOUR_CHAR_CODE('chap')
kQTParseTextHREFIsAutoHREF = FOUR_CHAR_CODE('auto')
kQTParseTextHREFIsServerMap = FOUR_CHAR_CODE('smap')
kQTParseTextHREFHREF = FOUR_CHAR_CODE('href')
-kQTParseTextHREFEMBEDArgs = FOUR_CHAR_CODE('mbed')
+kQTParseTextHREFEMBEDArgs = FOUR_CHAR_CODE('mbed')
kTrackReferenceChapterList = FOUR_CHAR_CODE('chap')
kTrackReferenceTimeCode = FOUR_CHAR_CODE('tmcd')
kTrackReferenceModifier = FOUR_CHAR_CODE('ssrc')
@@ -920,16 +920,16 @@ kQTRestrictionEditDontCut = (1L << 1)
kQTRestrictionEditDontPaste = (1L << 2)
kQTRestrictionEditDontClear = (1L << 3)
kQTRestrictionEditDontModify = (1L << 4)
-kQTRestrictionEditDontExtract = (1L << 5)
+kQTRestrictionEditDontExtract = (1L << 5)
videoFlagDontLeanAhead = 1L << 0
txtProcDefaultDisplay = 0
txtProcDontDisplay = 1
-txtProcDoDisplay = 2
+txtProcDoDisplay = 2
findTextEdgeOK = 1 << 0
findTextCaseSensitive = 1 << 1
findTextReverseSearch = 1 << 2
findTextWrapAround = 1 << 3
-findTextUseOffset = 1 << 4
+findTextUseOffset = 1 << 4
dropShadowOffsetType = FOUR_CHAR_CODE('drpo')
dropShadowTranslucencyType = FOUR_CHAR_CODE('drpt')
spriteHitTestBounds = 1L << 0
@@ -937,7 +937,7 @@ spriteHitTestImage = 1L << 1
spriteHitTestInvisibleSprites = 1L << 2
spriteHitTestIsClick = 1L << 3
spriteHitTestLocInDisplayCoordinates = 1L << 4
-spriteHitTestTreatAllSpritesAsHitTestable = 1L << 5
+spriteHitTestTreatAllSpritesAsHitTestable = 1L << 5
kSpriteAtomType = FOUR_CHAR_CODE('sprt')
kSpriteImagesContainerAtomType = FOUR_CHAR_CODE('imct')
kSpriteImageAtomType = FOUR_CHAR_CODE('imag')
@@ -974,7 +974,7 @@ kMovieMediaRegionAtom = FOUR_CHAR_CODE('regi')
kMovieMediaSlaveTrackDuration = FOUR_CHAR_CODE('sltr')
kMovieMediaEnableFrameStepping = FOUR_CHAR_CODE('enfs')
kMovieMediaBackgroundColor = FOUR_CHAR_CODE('bkcl')
-kMovieMediaPrerollTime = FOUR_CHAR_CODE('prer')
+kMovieMediaPrerollTime = FOUR_CHAR_CODE('prer')
kMovieMediaFitNone = 0
kMovieMediaFitScroll = FOUR_CHAR_CODE('scro')
kMovieMediaFitClipIfNecessary = FOUR_CHAR_CODE('hidd')
@@ -992,9 +992,9 @@ kMoviePropertyTimeScale = FOUR_CHAR_CODE('tims')
kMoviePropertyTime = FOUR_CHAR_CODE('timv')
kMoviePropertyNaturalBounds = FOUR_CHAR_CODE('natb')
kMoviePropertyMatrix = FOUR_CHAR_CODE('mtrx')
-kMoviePropertyTrackList = FOUR_CHAR_CODE('tlst')
+kMoviePropertyTrackList = FOUR_CHAR_CODE('tlst')
kTrackPropertyMediaType = FOUR_CHAR_CODE('mtyp')
-kTrackPropertyInstantiation = FOUR_CHAR_CODE('inst')
+kTrackPropertyInstantiation = FOUR_CHAR_CODE('inst')
MovieControllerComponentType = FOUR_CHAR_CODE('play')
kMovieControllerQTVRFlag = 1 << 0
kMovieControllerDontDisplayToUser = 1 << 1
@@ -1074,7 +1074,7 @@ mcActionAppMessageReceived = 85
mcActionEvaluateExpressionWithType = 89
mcActionGetMovieName = 90
mcActionGetMovieID = 91
-mcActionGetMovieActive = 92
+mcActionGetMovieActive = 92
mcFlagSuppressMovieFrame = 1 << 0
mcFlagSuppressStepButtons = 1 << 1
mcFlagSuppressSpeakerButton = 1 << 2
@@ -1114,7 +1114,7 @@ kQTAppMessageSoftwareChanged = 1
kQTAppMessageWindowCloseRequested = 3
kQTAppMessageExitFullScreenRequested = 4
kQTAppMessageDisplayChannels = 5
-kQTAppMessageEnterFullScreenRequested = 6
+kQTAppMessageEnterFullScreenRequested = 6
kFetchAsBooleanPtr = 1
kFetchAsShortPtr = 2
kFetchAsLongPtr = 3
@@ -1324,7 +1324,7 @@ k4444YpCbCrA8CodecType = FOUR_CHAR_CODE('v408')
k422YpCbCr16CodecType = FOUR_CHAR_CODE('v216')
k422YpCbCr10CodecType = FOUR_CHAR_CODE('v210')
k444YpCbCr10CodecType = FOUR_CHAR_CODE('v410')
-k4444YpCbCrA8RCodecType = FOUR_CHAR_CODE('r408')
+k4444YpCbCrA8RCodecType = FOUR_CHAR_CODE('r408')
kBlurImageFilterType = FOUR_CHAR_CODE('blur')
kSharpenImageFilterType = FOUR_CHAR_CODE('shrp')
kEdgeDetectImageFilterType = FOUR_CHAR_CODE('edge')
@@ -1359,10 +1359,10 @@ k64ARGBPixelFormat = FOUR_CHAR_CODE('b64a')
k48RGBPixelFormat = FOUR_CHAR_CODE('b48r')
k32AlphaGrayPixelFormat = FOUR_CHAR_CODE('b32a')
k16GrayPixelFormat = FOUR_CHAR_CODE('b16g')
-k422YpCbCr8PixelFormat = FOUR_CHAR_CODE('2vuy')
+k422YpCbCr8PixelFormat = FOUR_CHAR_CODE('2vuy')
k4444YpCbCrA8PixelFormat = FOUR_CHAR_CODE('v408')
-k4444YpCbCrA8RPixelFormat = FOUR_CHAR_CODE('r408')
-kYUV420PixelFormat = FOUR_CHAR_CODE('y420')
+k4444YpCbCrA8RPixelFormat = FOUR_CHAR_CODE('r408')
+kYUV420PixelFormat = FOUR_CHAR_CODE('y420')
codecInfoDoes1 = (1L << 0)
codecInfoDoes2 = (1L << 1)
codecInfoDoes4 = (1L << 2)
@@ -1386,7 +1386,7 @@ codecInfoDoesBlend = (1L << 19)
codecInfoDoesWarp = (1L << 20)
codecInfoDoesRecompress = (1L << 21)
codecInfoDoesSpool = (1L << 22)
-codecInfoDoesRateConstrain = (1L << 23)
+codecInfoDoesRateConstrain = (1L << 23)
codecInfoDepth1 = (1L << 0)
codecInfoDepth2 = (1L << 1)
codecInfoDepth4 = (1L << 2)
@@ -1400,7 +1400,7 @@ codecInfoDepth36 = (1L << 9)
codecInfoDepth40 = (1L << 10)
codecInfoStoresClut = (1L << 11)
codecInfoDoesLossless = (1L << 12)
-codecInfoSequenceSensitive = (1L << 13)
+codecInfoSequenceSensitive = (1L << 13)
codecFlagUseImageBuffer = (1L << 0)
codecFlagUseScreenBuffer = (1L << 1)
codecFlagUpdatePrevious = (1L << 2)
@@ -1416,7 +1416,7 @@ codecFlagDontUseNewImageBuffer = (1L << 10)
codecFlagInterlaceUpdate = (1L << 11)
codecFlagCatchUpDiff = (1L << 12)
codecFlagSupportDisable = (1L << 13)
-codecFlagReenable = (1L << 14)
+codecFlagReenable = (1L << 14)
codecFlagOutUpdateOnNextIdle = (1L << 9)
codecFlagOutUpdateOnDataSourceChange = (1L << 10)
codecFlagSequenceSensitive = (1L << 11)
@@ -1426,21 +1426,21 @@ codecFlagUsedNewImageBuffer = (1L << 14)
codecFlagUsedImageBuffer = (1L << 15)
codecMinimumDataSize = 32768L
compressorComponentType = FOUR_CHAR_CODE('imco')
-decompressorComponentType = FOUR_CHAR_CODE('imdc')
+decompressorComponentType = FOUR_CHAR_CODE('imdc')
codecLosslessQuality = 0x00000400
codecMaxQuality = 0x000003FF
codecMinQuality = 0x00000000
codecLowQuality = 0x00000100
codecNormalQuality = 0x00000200
codecHighQuality = 0x00000300
-codecLockBitsShieldCursor = (1 << 0)
+codecLockBitsShieldCursor = (1 << 0)
codecCompletionSource = (1 << 0)
codecCompletionDest = (1 << 1)
codecCompletionDontUnshield = (1 << 2)
codecCompletionWentOffscreen = (1 << 3)
codecCompletionUnlockBits = (1 << 4)
codecCompletionForceChainFlush = (1 << 5)
-codecCompletionDropped = (1 << 6)
+codecCompletionDropped = (1 << 6)
codecProgressOpen = 0
codecProgressUpdatePercent = 1
codecProgressClose = 2
@@ -1473,14 +1473,14 @@ codecDSequenceFlushInsteadOfDirtying = (1L << 8)
codecDSequenceEnableSubPixelPositioning = (1L << 9)
kICMSequenceTaskWeight = FOUR_CHAR_CODE('twei')
kICMSequenceTaskName = FOUR_CHAR_CODE('tnam')
-kICMSequenceUserPreferredCodecs = FOUR_CHAR_CODE('punt')
+kICMSequenceUserPreferredCodecs = FOUR_CHAR_CODE('punt')
kImageDescriptionSampleFormat = FOUR_CHAR_CODE('idfm')
kImageDescriptionClassicAtomFormat = FOUR_CHAR_CODE('atom')
kImageDescriptionQTAtomFormat = FOUR_CHAR_CODE('qtat')
kImageDescriptionEffectDataFormat = FOUR_CHAR_CODE('fxat')
kImageDescriptionPrivateDataFormat = FOUR_CHAR_CODE('priv')
kImageDescriptionAlternateCodec = FOUR_CHAR_CODE('subs')
-kImageDescriptionColorSpace = FOUR_CHAR_CODE('cspc')
+kImageDescriptionColorSpace = FOUR_CHAR_CODE('cspc')
sfpItemPreviewAreaUser = 11
sfpItemPreviewStaticText = 12
sfpItemPreviewDividerUser = 13
@@ -1500,14 +1500,14 @@ kICMTempThenAppMemory = 1L << 12
kICMAppThenTempMemory = 1L << 13
kQTUsePlatformDefaultGammaLevel = 0
kQTUseSourceGammaLevel = -1L
-kQTCCIR601VideoGammaLevel = 0x00023333
+kQTCCIR601VideoGammaLevel = 0x00023333
identityMatrixType = 0x00
translateMatrixType = 0x01
scaleMatrixType = 0x02
scaleTranslateMatrixType = 0x03
linearMatrixType = 0x04
linearTranslateMatrixType = 0x05
-perspectiveMatrixType = 0x06
+perspectiveMatrixType = 0x06
GraphicsImporterComponentType = FOUR_CHAR_CODE('grip')
graphicsImporterUsesImageDecompressor = 1L << 23
quickTimeImageFileImageDescriptionAtom = FOUR_CHAR_CODE('idsc')
@@ -1530,12 +1530,12 @@ kQTPhotoshopLayerOpacity = FOUR_CHAR_CODE('lopa')
kQTPhotoshopLayerClipping = FOUR_CHAR_CODE('lclp')
kQTPhotoshopLayerFlags = FOUR_CHAR_CODE('lflg')
kQTPhotoshopLayerName = FOUR_CHAR_CODE('\xa9lnm')
-kQTPhotoshopLayerUnicodeName = FOUR_CHAR_CODE('luni')
+kQTPhotoshopLayerUnicodeName = FOUR_CHAR_CODE('luni')
kQTIndexedImageType = FOUR_CHAR_CODE('nth?')
kQTIndexedImageIsThumbnail = FOUR_CHAR_CODE('n=th')
kQTIndexedImageIsLayer = FOUR_CHAR_CODE('n=ly')
kQTIndexedImageIsPage = FOUR_CHAR_CODE('n=pg')
-kQTIndexedImageIsMultiResolution = FOUR_CHAR_CODE('n=rs')
+kQTIndexedImageIsMultiResolution = FOUR_CHAR_CODE('n=rs')
kQTTIFFUserDataPrefix = 0x74690000
kQTTIFFExifUserDataPrefix = 0x65780000
kQTTIFFExifGPSUserDataPrefix = 0x67700000
@@ -1548,14 +1548,14 @@ kQTTIFFUserDataWhitePoint = 0x7469013E
kQTTIFFUserDataPrimaryChromaticities = 0x7469013F
kQTTIFFUserDataTransferRange = 0x74690156
kQTTIFFUserDataYCbCrPositioning = 0x74690213
-kQTTIFFUserDataReferenceBlackWhite = 0x74690214
+kQTTIFFUserDataReferenceBlackWhite = 0x74690214
kQTTIFFUserDataModelPixelScale = 0x7469830E
kQTTIFFUserDataModelTransformation = 0x746985D8
kQTTIFFUserDataModelTiepoint = 0x74698482
kQTTIFFUserDataGeoKeyDirectory = 0x746987AF
kQTTIFFUserDataGeoDoubleParams = 0x746987B0
kQTTIFFUserDataGeoAsciiParams = 0x746987B1
-kQTTIFFUserDataIntergraphMatrix = 0x74698480
+kQTTIFFUserDataIntergraphMatrix = 0x74698480
kQTExifUserDataExifVersion = 0x65789000
kQTExifUserDataFlashPixVersion = 0x6578A000
kQTExifUserDataColorSpace = 0x6578A001
@@ -1594,7 +1594,7 @@ kQTExifUserDataSubjectLocation = 0x6578A214
kQTExifUserDataExposureIndex = 0x6578A215
kQTExifUserDataSensingMethod = 0x6578A217
kQTExifUserDataFileSource = 0x6578A300
-kQTExifUserDataSceneType = 0x6578A301
+kQTExifUserDataSceneType = 0x6578A301
kQTExifUserDataGPSVersionID = 0x06770000
kQTExifUserDataGPSLatitudeRef = 0x06770001
kQTExifUserDataGPSLatitude = 0x06770002
@@ -1621,7 +1621,7 @@ kQTExifUserDataGPSDestLongitude = 0x06770016
kQTExifUserDataGPSDestBearingRef = 0x06770017
kQTExifUserDataGPSDestBearing = 0x06770018
kQTExifUserDataGPSDestDistanceRef = 0x06770019
-kQTExifUserDataGPSDestDistance = 0x0677001A
+kQTExifUserDataGPSDestDistance = 0x0677001A
GraphicsExporterComponentType = FOUR_CHAR_CODE('grex')
kBaseGraphicsExporterSubType = FOUR_CHAR_CODE('base')
graphicsExporterIsBaseExporter = 1L << 0
@@ -1638,7 +1638,7 @@ kQTMetaData = FOUR_CHAR_CODE('meta')
kQTTIFFCompressionMethod = FOUR_CHAR_CODE('tifc')
kQTTIFFCompression_None = 1
kQTTIFFCompression_PackBits = 32773L
-kQTTIFFLittleEndian = FOUR_CHAR_CODE('tife')
+kQTTIFFLittleEndian = FOUR_CHAR_CODE('tife')
kQTPNGFilterPreference = FOUR_CHAR_CODE('pngf')
kQTPNGFilterBestForColorType = FOUR_CHAR_CODE('bflt')
kQTPNGFilterNone = 0
@@ -1795,10 +1795,10 @@ clockComponentType = FOUR_CHAR_CODE('clok')
systemTickClock = FOUR_CHAR_CODE('tick')
systemSecondClock = FOUR_CHAR_CODE('seco')
systemMillisecondClock = FOUR_CHAR_CODE('mill')
-systemMicrosecondClock = FOUR_CHAR_CODE('micr')
+systemMicrosecondClock = FOUR_CHAR_CODE('micr')
kClockRateIsLinear = 1
kClockImplementsCallBacks = 2
-kClockCanHandleIntermittentSound = 4
+kClockCanHandleIntermittentSound = 4
StandardCompressionType = FOUR_CHAR_CODE('scdi')
StandardCompressionSubType = FOUR_CHAR_CODE('imag')
StandardCompressionSubTypeSound = FOUR_CHAR_CODE('soun')
@@ -1861,21 +1861,21 @@ scCodecManufacturerType = FOUR_CHAR_CODE('cmfr')
scSoundVBRCompressionOK = FOUR_CHAR_CODE('cvbr')
scSoundInputSampleRateType = FOUR_CHAR_CODE('ssir')
scSoundSampleRateChangeOK = FOUR_CHAR_CODE('rcok')
-scAvailableCompressionListType = FOUR_CHAR_CODE('avai')
+scAvailableCompressionListType = FOUR_CHAR_CODE('avai')
scGetCompression = 1
scShowMotionSettings = 1L << 0
scSettingsChangedItem = -1
scCompressFlagIgnoreIdenticalFrames = 1
kQTSettingsVideo = FOUR_CHAR_CODE('vide')
kQTSettingsSound = FOUR_CHAR_CODE('soun')
-kQTSettingsComponentVersion = FOUR_CHAR_CODE('vers')
+kQTSettingsComponentVersion = FOUR_CHAR_CODE('vers')
TweenComponentType = FOUR_CHAR_CODE('twen')
TCSourceRefNameType = FOUR_CHAR_CODE('name')
tcDropFrame = 1 << 0
tc24HourMax = 1 << 1
tcNegTimesOK = 1 << 2
tcCounter = 1 << 3
-tctNegFlag = 0x80
+tctNegFlag = 0x80
tcdfShowTimeCode = 1 << 0
MovieImportType = FOUR_CHAR_CODE('eat ')
MovieExportType = FOUR_CHAR_CODE('spit')
@@ -1938,7 +1938,7 @@ kQTMediaConfigUseAppByDefault = (1L << 28)
kQTMediaConfigUsePluginByDefault = (1L << 29)
kQTMediaConfigDefaultsMask = (kQTMediaConfigUseAppByDefault | kQTMediaConfigUsePluginByDefault)
kQTMediaConfigDefaultsShift = 12
-kQTMediaConfigHasFileHasQTAtoms = (1L << 30)
+kQTMediaConfigHasFileHasQTAtoms = (1L << 30)
kQTMediaConfigStreamGroupID = FOUR_CHAR_CODE('strm')
kQTMediaConfigInteractiveGroupID = FOUR_CHAR_CODE('intr')
kQTMediaConfigVideoGroupID = FOUR_CHAR_CODE('eyes')
@@ -1950,7 +1950,7 @@ kQTMediaConfigMiscGroupID = FOUR_CHAR_CODE('misc')
kQTMediaInfoNetGroup = FOUR_CHAR_CODE('net ')
kQTMediaInfoWinGroup = FOUR_CHAR_CODE('win ')
kQTMediaInfoMacGroup = FOUR_CHAR_CODE('mac ')
-kQTMediaInfoMiscGroup = 0x3F3F3F3F
+kQTMediaInfoMiscGroup = 0x3F3F3F3F
kMimeInfoMimeTypeTag = FOUR_CHAR_CODE('mime')
kMimeInfoFileExtensionTag = FOUR_CHAR_CODE('ext ')
kMimeInfoDescriptionTag = FOUR_CHAR_CODE('desc')
@@ -2008,7 +2008,7 @@ kQTSettingsTime = FOUR_CHAR_CODE('time')
kQTSettingsTimeDuration = FOUR_CHAR_CODE('dura')
kQTSettingsAudioCDTrack = FOUR_CHAR_CODE('trak')
kQTSettingsAudioCDTrackRateShift = FOUR_CHAR_CODE('rshf')
-kQTSettingsDVExportDVFormat = FOUR_CHAR_CODE('dvcf')
+kQTSettingsDVExportDVFormat = FOUR_CHAR_CODE('dvcf')
kQTPresetsListResourceType = FOUR_CHAR_CODE('stg#')
kQTPresetsPlatformListResourceType = FOUR_CHAR_CODE('stgp')
kQTPresetInfoIsDivider = 1
@@ -2021,9 +2021,9 @@ movieExportWidth = FOUR_CHAR_CODE('wdth')
movieExportHeight = FOUR_CHAR_CODE('hegt')
movieExportDuration = FOUR_CHAR_CODE('dura')
movieExportVideoFilter = FOUR_CHAR_CODE('iflt')
-movieExportTimeScale = FOUR_CHAR_CODE('tmsc')
-kQTBrowserInfoCanUseSystemFolderPlugin = (1L << 0)
-kQTPreFlightOpenComponent = (1L << 1)
+movieExportTimeScale = FOUR_CHAR_CODE('tmsc')
+kQTBrowserInfoCanUseSystemFolderPlugin = (1L << 0)
+kQTPreFlightOpenComponent = (1L << 1)
pnotComponentWantsEvents = 1
pnotComponentNeedsNoCache = 2
ShowFilePreviewComponentType = FOUR_CHAR_CODE('pnot')
@@ -2047,29 +2047,29 @@ kDataRefExtensionMacOSFileType = FOUR_CHAR_CODE('ftyp')
kDataRefExtensionInitializationData = FOUR_CHAR_CODE('data')
kDataRefExtensionQuickTimeMediaType = FOUR_CHAR_CODE('mtyp')
kDataHChokeToMovieDataRate = 1 << 0
-kDataHChokeToParam = 1 << 1
+kDataHChokeToParam = 1 << 1
kDataHExtendedSchedule = FOUR_CHAR_CODE('xtnd')
kDataHInfoFlagNeverStreams = 1 << 0
kDataHInfoFlagCanUpdateDataRefs = 1 << 1
-kDataHInfoFlagNeedsNetworkBandwidth = 1 << 2
+kDataHInfoFlagNeedsNetworkBandwidth = 1 << 2
kDataHFileTypeMacOSFileType = FOUR_CHAR_CODE('ftyp')
kDataHFileTypeExtension = FOUR_CHAR_CODE('fext')
kDataHFileTypeMIME = FOUR_CHAR_CODE('mime')
kDataHCreateFileButDontCreateResFile = (1L << 0)
-kDataHMovieUsageDoAppendMDAT = 1L << 0
+kDataHMovieUsageDoAppendMDAT = 1L << 0
kDataHTempUseSameDirectory = 1L << 0
kDataHTempUseSameVolume = 1L << 1
kDataHTempCreateFile = 1L << 2
-kDataHTempOpenFile = 1L << 3
-kDataHGetDataRateInfiniteRate = 0x7FFFFFFF
-kDataHSetTimeHintsSkipBandwidthRequest = 1 << 0
+kDataHTempOpenFile = 1L << 3
+kDataHGetDataRateInfiniteRate = 0x7FFFFFFF
+kDataHSetTimeHintsSkipBandwidthRequest = 1 << 0
videoDigitizerComponentType = FOUR_CHAR_CODE('vdig')
vdigInterfaceRev = 2
ntscIn = 0
currentIn = 0
palIn = 1
secamIn = 2
-ntscReallyIn = 3
+ntscReallyIn = 3
compositeIn = 0
sVideoIn = 1
rgbComponentIn = 2
@@ -2081,16 +2081,16 @@ sdiIn = 7
vdPlayThruOff = 0
vdPlayThruOn = 1
vdDigitizerBW = 0
-vdDigitizerRGB = 1
+vdDigitizerRGB = 1
vdBroadcastMode = 0
-vdVTRMode = 1
+vdVTRMode = 1
vdUseAnyField = 0
vdUseOddField = 1
-vdUseEvenField = 2
+vdUseEvenField = 2
vdTypeBasic = 0
vdTypeAlpha = 1
vdTypeMask = 2
-vdTypeKey = 3
+vdTypeKey = 3
digiInDoesNTSC = 1L << 0
digiInDoesPAL = 1L << 1
digiInDoesSECAM = 1L << 2
@@ -2101,7 +2101,7 @@ digiInDoesComponent = 1L << 10
digiInVTR_Broadcast = 1L << 11
digiInDoesColor = 1L << 12
digiInDoesBW = 1L << 13
-digiInSignalLock = 1L << 31
+digiInSignalLock = 1L << 31
digiOutDoes1 = 1L << 0
digiOutDoes2 = 1L << 1
digiOutDoes4 = 1L << 2
@@ -2132,7 +2132,7 @@ digiOutDoesCompress = 1L << 27
digiOutDoesCompressOnly = 1L << 28
digiOutDoesPlayThruDuringCompress = 1L << 29
digiOutDoesCompressPartiallyVisible = 1L << 30
-digiOutDoesNotNeedCopyOfCompressData = 1L << 31
+digiOutDoesNotNeedCopyOfCompressData = 1L << 31
dmaDepth1 = 1
dmaDepth2 = 2
dmaDepth4 = 4
@@ -2144,7 +2144,7 @@ dmaDepth4Gray = 128
dmaDepth8Gray = 256
kVDIGControlledFrameRate = -1
vdDeviceFlagShowInputsAsDevices = (1 << 0)
-vdDeviceFlagHideDevice = (1 << 1)
+vdDeviceFlagHideDevice = (1 << 1)
vdFlagCaptureStarting = (1 << 0)
vdFlagCaptureStopping = (1 << 1)
vdFlagCaptureIsForPreview = (1 << 2)
@@ -2152,7 +2152,7 @@ vdFlagCaptureIsForRecord = (1 << 3)
vdFlagCaptureLowLatency = (1 << 4)
vdFlagCaptureAlwaysUseTimeBase = (1 << 5)
vdFlagCaptureSetSettingsBegin = (1 << 6)
-vdFlagCaptureSetSettingsEnd = (1 << 7)
+vdFlagCaptureSetSettingsEnd = (1 << 7)
xmlParseComponentType = FOUR_CHAR_CODE('pars')
xmlParseComponentSubType = FOUR_CHAR_CODE('xml ')
xmlIdentifierInvalid = 0
@@ -2164,7 +2164,7 @@ elementFlagAlwaysSelfContained = 1L << 0
elementFlagPreserveWhiteSpace = 1L << 1
xmlParseFlagAllowUppercase = 1L << 0
xmlParseFlagAllowUnquotedAttributeValues = 1L << 1
-xmlParseFlagEventParseOnly = 1L << 2
+xmlParseFlagEventParseOnly = 1L << 2
attributeValueKindCharString = 0
attributeValueKindInteger = 1L << 0
attributeValueKindPercent = 1L << 1
@@ -2195,7 +2195,7 @@ seqGrabRecord = 1
seqGrabPreview = 2
seqGrabPlayDuringRecord = 4
seqGrabLowLatencyCapture = 8
-seqGrabAlwaysUseTimeBase = 16
+seqGrabAlwaysUseTimeBase = 16
seqGrabHasBounds = 1
seqGrabHasVolume = 2
seqGrabHasDiscreteSamples = 4
@@ -2227,9 +2227,9 @@ channelPlayFast = 1
channelPlayHighQuality = 2
channelPlayAllData = 4
sgSetSettingsBegin = (1 << 0)
-sgSetSettingsEnd = (1 << 1)
+sgSetSettingsEnd = (1 << 1)
kSGSmallestDITLSize = -1
-kSGLargestDITLSize = -2
+kSGLargestDITLSize = -2
sgChannelAtom = FOUR_CHAR_CODE('chan')
sgChannelSettingsAtom = FOUR_CHAR_CODE('ctom')
sgChannelDescription = FOUR_CHAR_CODE('cdsc')
@@ -2277,7 +2277,7 @@ kQTVOName = FOUR_CHAR_CODE('name')
kQTVODecompressors = FOUR_CHAR_CODE('deco')
kQTVODecompressorType = FOUR_CHAR_CODE('dety')
kQTVODecompressorContinuous = FOUR_CHAR_CODE('cont')
-kQTVODecompressorComponent = FOUR_CHAR_CODE('cmpt')
+kQTVODecompressorComponent = FOUR_CHAR_CODE('cmpt')
kClockGetTimeSelect = 0x0001
kClockNewCallBackSelect = 0x0002
kClockDisposeCallBackSelect = 0x0003
@@ -2804,7 +2804,7 @@ forceUpdateNewBuffer = 1 << 1
mHitTestBounds = 1L << 0
mHitTestImage = 1L << 1
mHitTestInvisible = 1L << 2
-mHitTestIsClick = 1L << 3
+mHitTestIsClick = 1L << 3
mOpaque = 1L << 0
mInvisible = 1L << 1
kMediaQTIdleFrequencySelector = FOUR_CHAR_CODE('idfq')
@@ -2815,7 +2815,7 @@ kMediaVideoParamSharpness = 4
kMediaVideoParamSaturation = 5
kMediaVideoParamBlackLevel = 6
kMediaVideoParamWhiteLevel = 7
-kMHInfoEncodedFrameRate = FOUR_CHAR_CODE('orat')
+kMHInfoEncodedFrameRate = FOUR_CHAR_CODE('orat')
kEmptyPurgableChunksOverAllowance = 1
kCallComponentExecuteWiredActionSelect = -9
kMediaSetChunkManagementFlagsSelect = 0x0415
@@ -2937,7 +2937,7 @@ kaiLibraryDescType = FOUR_CHAR_CODE('ldsc')
kInstKnobMissingUnknown = 0
kInstKnobMissingDefault = (1 << 0)
kMusicLoopTypeNormal = 0
-kMusicLoopTypePalindrome = 1
+kMusicLoopTypePalindrome = 1
instSamplePreProcessFlag = 1 << 0
kQTMIDIComponentType = FOUR_CHAR_CODE('midi')
kOMSComponentSubType = FOUR_CHAR_CODE('OMS ')
@@ -2946,18 +2946,18 @@ kMIDIManagerComponentSubType = FOUR_CHAR_CODE('mmgr')
kOSXMIDIComponentSubType = FOUR_CHAR_CODE('osxm')
kMusicPacketPortLost = 1
kMusicPacketPortFound = 2
-kMusicPacketTimeGap = 3
+kMusicPacketTimeGap = 3
kAppleSysexID = 0x11
kAppleSysexCmdSampleSize = 0x0001
kAppleSysexCmdSampleBreak = 0x0002
kAppleSysexCmdAtomicInstrument = 0x0010
-kAppleSysexCmdDeveloper = 0x7F00
+kAppleSysexCmdDeveloper = 0x7F00
kSynthesizerConnectionFMS = 1
kSynthesizerConnectionMMgr = 2
kSynthesizerConnectionOMS = 4
kSynthesizerConnectionQT = 8
kSynthesizerConnectionOSXMIDI = 16
-kSynthesizerConnectionUnavailable = 256
+kSynthesizerConnectionUnavailable = 256
kMusicComponentType = FOUR_CHAR_CODE('musi')
kInstrumentComponentType = FOUR_CHAR_CODE('inst')
kSoftSynthComponentSubType = FOUR_CHAR_CODE('ss ')
@@ -2976,7 +2976,7 @@ kSynthesizerSlowSetPart = 1 << 10
kSynthesizerOffline = 1 << 12
kSynthesizerGM = 1 << 14
kSynthesizerDLS = 1 << 15
-kSynthesizerSoundLocalization = 1 << 16
+kSynthesizerSoundLocalization = 1 << 16
kControllerModulationWheel = 1
kControllerBreath = 2
kControllerFoot = 4
@@ -3081,8 +3081,8 @@ kQTMSKnobReverbThresholdID = 0x0200003E
kQTMSKnobVolumeAttackVelScalingID = 0x0200003F
kQTMSKnobLastIDPlus1 = 0x02000040
kControllerMaximum = 0x00007FFF
-# kControllerMinimum = (long)0xFFFF8000
-kVoiceCountDynamic = -1
+# kControllerMinimum = (long)0xFFFF8000
+kVoiceCountDynamic = -1
kFirstGMInstrument = 0x00000001
kLastGMInstrument = 0x00000080
kFirstGSInstrument = 0x00000081
@@ -3116,9 +3116,9 @@ kKnobTypeSetting = 6 << 12
kKnobTypeMilliseconds = 7 << 12
kKnobTypePercentage = 8 << 12
kKnobTypeHertz = 9 << 12
-kKnobTypeButton = 10 << 12
+kKnobTypeButton = 10 << 12
kUnknownKnobValue = 0x7FFFFFFF
-kDefaultKnobValue = 0x7FFFFFFE
+kDefaultKnobValue = 0x7FFFFFFE
notImplementedMusicErr = (0x80000000 | (0xFFFF & (notImplementedMusicOSErr)))
cantSendToSynthesizerErr = (0x80000000 | (0xFFFF & (cantSendToSynthesizerOSErr)))
cantReceiveFromSynthesizerErr = (0x80000000 | (0xFFFF & (cantReceiveFromSynthesizerOSErr)))
@@ -3142,13 +3142,13 @@ kGetAtomicInstNoSamples = kGetAtomicInstNoExpandedSamples | kGetAtomicInstNoOrig
kGetAtomicInstNoKnobList = 1 << 2
kGetAtomicInstNoInstrumentInfo = 1 << 3
kGetAtomicInstOriginalKnobList = 1 << 4
-kGetAtomicInstAllKnobs = 1 << 5
+kGetAtomicInstAllKnobs = 1 << 5
kSetAtomicInstKeepOriginalInstrument = 1 << 0
kSetAtomicInstShareAcrossParts = 1 << 1
kSetAtomicInstCallerTosses = 1 << 2
kSetAtomicInstCallerGuarantees = 1 << 3
kSetAtomicInstInterruptSafe = 1 << 4
-kSetAtomicInstDontPreprocess = 1 << 7
+kSetAtomicInstDontPreprocess = 1 << 7
kInstrumentNamesModifiable = 1
kInstrumentNamesBoth = 2
kGenericMusicComponentSubtype = FOUR_CHAR_CODE('gene')
@@ -3196,13 +3196,13 @@ kGenericMusicCallParts = 1 << 5
kGenericMusicCallInstrument = 1 << 6
kGenericMusicCallNumber = 1 << 7
kGenericMusicCallROMInstrument = 1 << 8
-kGenericMusicAllDefaults = 1 << 9
+kGenericMusicAllDefaults = 1 << 9
kGetInstrumentInfoNoBuiltIn = 1 << 0
kGetInstrumentInfoMidiUserInst = 1 << 1
kGetInstrumentInfoNoIText = 1 << 2
kNoteRequestNoGM = 1
kNoteRequestNoSynthType = 2
-kNoteRequestSynthMustMatch = 4
+kNoteRequestSynthMustMatch = 4
kNoteRequestSpecifyMIDIChannel = 0x80
kPickDontMix = 1
kPickSameSynth = 2
@@ -3210,11 +3210,11 @@ kPickUserInsts = 4
kPickEditAllowEdit = 8
kPickEditAllowPick = 16
kPickEditSynthGlobal = 32
-kPickEditControllers = 64
+kPickEditControllers = 64
kNoteAllocatorComponentType = FOUR_CHAR_CODE('nota')
kNADummyOneSelect = 29
kNADummyTwoSelect = 30
-kTuneQueueDepth = 8
+kTuneQueueDepth = 8
kTunePlayerComponentType = FOUR_CHAR_CODE('tune')
kTuneStartNow = 1
kTuneDontClipNotes = 2
@@ -3227,9 +3227,9 @@ kTuneStartNewMaster = 16384
kTuneStopFade = 1
kTuneStopSustain = 2
kTuneStopInstant = 4
-kTuneStopReleaseChannels = 8
+kTuneStopReleaseChannels = 8
kTuneMixMute = 1
-kTuneMixSolo = 2
+kTuneMixSolo = 2
kRestEventType = 0x00000000
kNoteEventType = 0x00000001
kControlEventType = 0x00000002
@@ -3347,10 +3347,10 @@ kGeneralEventMIDIChannel = 8
kGeneralEventPartChange = 9
kGeneralEventNoOp = 10
kGeneralEventUsedNotes = 11
-kGeneralEventPartMix = 12
+kGeneralEventPartMix = 12
kMarkerEventEnd = 0
kMarkerEventBeat = 1
-kMarkerEventTempo = 2
+kMarkerEventTempo = 2
kCurrentlyNativeEndian = 1
kCurrentlyNotNativeEndian = 2
kQTMIDIGetMIDIPortsSelect = 0x0001
diff --git a/Lib/plat-mac/Carbon/Resources.py b/Lib/plat-mac/Carbon/Resources.py
index 8030396a9f..2cd876168d 100644
--- a/Lib/plat-mac/Carbon/Resources.py
+++ b/Lib/plat-mac/Carbon/Resources.py
@@ -8,7 +8,7 @@ resPreload = 4
resChanged = 2
mapReadOnly = 128
mapCompact = 64
-mapChanged = 32
+mapChanged = 32
resSysRefBit = 7
resSysHeapBit = 6
resPurgeableBit = 5
@@ -18,10 +18,10 @@ resPreloadBit = 2
resChangedBit = 1
mapReadOnlyBit = 7
mapCompactBit = 6
-mapChangedBit = 5
+mapChangedBit = 5
kResFileNotOpened = -1
-kSystemResFile = 0
+kSystemResFile = 0
kRsrcChainBelowSystemMap = 0
kRsrcChainBelowApplicationMap = 1
kRsrcChainAboveApplicationMap = 2
-kRsrcChainAboveAllMaps = 4
+kRsrcChainAboveAllMaps = 4
diff --git a/Lib/plat-mac/Carbon/Sound.py b/Lib/plat-mac/Carbon/Sound.py
index ffe9efaba9..0e7b2fb644 100644
--- a/Lib/plat-mac/Carbon/Sound.py
+++ b/Lib/plat-mac/Carbon/Sound.py
@@ -1,8 +1,8 @@
# Generated from 'Sound.h'
def FOUR_CHAR_CODE(x): return x
-soundListRsrc = FOUR_CHAR_CODE('snd ')
-kSimpleBeepID = 1
+soundListRsrc = FOUR_CHAR_CODE('snd ')
+kSimpleBeepID = 1
# rate48khz = (long)0xBB800000
# rate44khz = (long)0xAC440000
rate32khz = 0x7D000000
@@ -11,21 +11,21 @@ rate22khz = 0x56EE8BA3
rate16khz = 0x3E800000
rate11khz = 0x2B7745D1
rate11025hz = 0x2B110000
-rate8khz = 0x1F400000
-sampledSynth = 5
+rate8khz = 0x1F400000
+sampledSynth = 5
squareWaveSynth = 1
waveTableSynth = 3
MACE3snthID = 11
MACE6snthID = 13
-kMiddleC = 60
+kMiddleC = 60
kNoVolume = 0
-kFullVolume = 0x0100
+kFullVolume = 0x0100
stdQLength = 128
dataOffsetFlag = 0x8000
-kUseOptionalOutputDevice = -1
+kUseOptionalOutputDevice = -1
notCompressed = 0
fixedCompression = -1
-variableCompression = -2
+variableCompression = -2
twoToOne = 1
eightToThree = 2
threeToOne = 3
@@ -35,17 +35,17 @@ threeToOnePacketSize = 16
stateBlockSize = 64
leftOverBlockSize = 32
firstSoundFormat = 0x0001
-secondSoundFormat = 0x0002
+secondSoundFormat = 0x0002
dbBufferReady = 0x00000001
-dbLastBuffer = 0x00000004
+dbLastBuffer = 0x00000004
sysBeepDisable = 0x0000
sysBeepEnable = (1 << 0)
-sysBeepSynchronous = (1 << 1)
+sysBeepSynchronous = (1 << 1)
unitTypeNoSelection = 0xFFFF
unitTypeSeconds = 0x0000
stdSH = 0x00
extSH = 0xFF
-cmpSH = 0xFE
+cmpSH = 0xFE
nullCmd = 0
quietCmd = 3
flushCmd = 4
@@ -84,7 +84,7 @@ continueCmd = 83
doubleBufferCmd = 84
getRateCmd = 85
sizeCmd = 90
-convertCmd = 91
+convertCmd = 91
waveInitChannelMask = 0x07
waveInitChannel0 = 0x04
waveInitChannel1 = 0x05
@@ -93,7 +93,7 @@ waveInitChannel3 = 0x07
initChan0 = waveInitChannel0
initChan1 = waveInitChannel1
initChan2 = waveInitChannel2
-initChan3 = waveInitChannel3
+initChan3 = waveInitChannel3
outsideCmpSH = 0
insideCmpSH = 1
aceSuccess = 0
@@ -102,7 +102,7 @@ aceNilBlock = 2
aceBadComp = 3
aceBadEncode = 4
aceBadDest = 5
-aceBadCmd = 6
+aceBadCmd = 6
initChanLeft = 0x0002
initChanRight = 0x0003
initNoInterp = 0x0004
@@ -114,7 +114,7 @@ initMACE6 = 0x0400
initPanMask = 0x0003
initSRateMask = 0x0030
initStereoMask = 0x00C0
-initCompMask = 0xFF00
+initCompMask = 0xFF00
siActiveChannels = FOUR_CHAR_CODE('chac')
siActiveLevels = FOUR_CHAR_CODE('lmac')
siAGCOnOff = FOUR_CHAR_CODE('agc ')
@@ -200,11 +200,11 @@ siVoxStopInfo = FOUR_CHAR_CODE('voxs')
siWideStereo = FOUR_CHAR_CODE('wide')
siSupportedExtendedFlags = FOUR_CHAR_CODE('exfl')
siRateConverterRollOffSlope = FOUR_CHAR_CODE('rcdb')
-siOutputLatency = FOUR_CHAR_CODE('olte')
+siOutputLatency = FOUR_CHAR_CODE('olte')
siCloseDriver = FOUR_CHAR_CODE('clos')
siInitializeDriver = FOUR_CHAR_CODE('init')
siPauseRecording = FOUR_CHAR_CODE('paus')
-siUserInterruptProc = FOUR_CHAR_CODE('user')
+siUserInterruptProc = FOUR_CHAR_CODE('user')
# kInvalidSource = (long)0xFFFFFFFF
kNoSource = FOUR_CHAR_CODE('none')
kCDSource = FOUR_CHAR_CODE('cd ')
@@ -219,7 +219,7 @@ kModemSource = FOUR_CHAR_CODE('modm')
kPCCardSource = FOUR_CHAR_CODE('pcm ')
kZoomVideoSource = FOUR_CHAR_CODE('zvpc')
kDVDSource = FOUR_CHAR_CODE('dvda')
-kMicrophoneArray = FOUR_CHAR_CODE('mica')
+kMicrophoneArray = FOUR_CHAR_CODE('mica')
kNoSoundComponentType = FOUR_CHAR_CODE('****')
kSoundComponentType = FOUR_CHAR_CODE('sift')
kSoundComponentPPCType = FOUR_CHAR_CODE('nift')
@@ -287,7 +287,7 @@ kOffsetBinary = k8BitOffsetBinaryFormat
kTwosComplement = k16BitBigEndianFormat
kLittleEndianFormat = k16BitLittleEndianFormat
kMPEGLayer3Format = 0x6D730055
-kFullMPEGLay3Format = FOUR_CHAR_CODE('.mp3')
+kFullMPEGLay3Format = FOUR_CHAR_CODE('.mp3')
k16BitNativeEndianFormat = k16BitLittleEndianFormat
k16BitNonNativeEndianFormat = k16BitBigEndianFormat
k16BitNativeEndianFormat = k16BitBigEndianFormat
@@ -323,8 +323,8 @@ kNonPagingMixer = (1 << 10)
kSoundConverterMixer = (1 << 11)
kPagingMixer = (1 << 12)
kVMAwareMixer = (1 << 13)
-kExtendedSoundData = (1 << 14)
-kBestQuality = (1 << 0)
+kExtendedSoundData = (1 << 14)
+kBestQuality = (1 << 0)
kInputMask = 0x000000FF
kOutputMask = 0x0000FF00
kOutputShift = 8
@@ -337,7 +337,7 @@ kAudioTerminatorAtomType = 0
kAVDisplayHeadphoneRemove = 0
kAVDisplayHeadphoneInsert = 1
kAVDisplayPlainTalkRemove = 2
-kAVDisplayPlainTalkInsert = 3
+kAVDisplayPlainTalkInsert = 3
audioAllChannels = 0
audioLeftChannel = 1
audioRightChannel = 2
@@ -345,21 +345,21 @@ audioUnmuted = 0
audioMuted = 1
audioDoesMono = (1L << 0)
audioDoesStereo = (1L << 1)
-audioDoesIndependentChannels = (1L << 2)
+audioDoesIndependentChannels = (1L << 2)
siCDQuality = FOUR_CHAR_CODE('cd ')
siBestQuality = FOUR_CHAR_CODE('best')
siBetterQuality = FOUR_CHAR_CODE('betr')
siGoodQuality = FOUR_CHAR_CODE('good')
-siNoneQuality = FOUR_CHAR_CODE('none')
+siNoneQuality = FOUR_CHAR_CODE('none')
siDeviceIsConnected = 1
siDeviceNotConnected = 0
siDontKnowIfConnected = -1
siReadPermission = 0
-siWritePermission = 1
+siWritePermission = 1
kSoundConverterDidntFillBuffer = (1 << 0)
-kSoundConverterHasLeftOverData = (1 << 1)
+kSoundConverterHasLeftOverData = (1 << 1)
kExtendedSoundSampleCountNotValid = 1L << 0
-kExtendedSoundBufferSizeValid = 1L << 1
+kExtendedSoundBufferSizeValid = 1L << 1
kScheduledSoundDoScheduled = 1 << 0
kScheduledSoundDoCallBack = 1 << 1
kScheduledSoundExtendedHdr = 1 << 2
diff --git a/Lib/plat-mac/Carbon/TextEdit.py b/Lib/plat-mac/Carbon/TextEdit.py
index eb5fb923d4..176795af96 100644
--- a/Lib/plat-mac/Carbon/TextEdit.py
+++ b/Lib/plat-mac/Carbon/TextEdit.py
@@ -7,26 +7,26 @@ teForceLeft = -2
teFlushDefault = 0
teCenter = 1
teFlushRight = -1
-teFlushLeft = -2
+teFlushLeft = -2
fontBit = 0
faceBit = 1
sizeBit = 2
clrBit = 3
addSizeBit = 4
-toggleBit = 5
+toggleBit = 5
doFont = 1
doFace = 2
doSize = 4
doColor = 8
doAll = 15
addSize = 16
-doToggle = 32
+doToggle = 32
EOLHook = 0
DRAWHook = 4
WIDTHHook = 8
HITTESTHook = 12
nWIDTHHook = 24
-TextWidthHook = 28
+TextWidthHook = 28
intEOLHook = 0
intDrawHook = 1
intWidthHook = 2
@@ -34,24 +34,24 @@ intHitTestHook = 3
intNWidthHook = 6
intTextWidthHook = 7
intInlineInputTSMTEPreUpdateHook = 8
-intInlineInputTSMTEPostUpdateHook = 9
+intInlineInputTSMTEPostUpdateHook = 9
teFAutoScroll = 0
teFTextBuffering = 1
teFOutlineHilite = 2
teFInlineInput = 3
teFUseWhiteBackground = 4
teFUseInlineInput = 5
-teFInlineInputAutoScroll = 6
-teFIdleWithEventLoopTimer = 7
+teFInlineInputAutoScroll = 6
+teFIdleWithEventLoopTimer = 7
teBitClear = 0
teBitSet = 1
-teBitTest = -1
+teBitTest = -1
teWordSelect = 4
teWordDrag = 8
teFromFind = 12
-teFromRecal = 16
+teFromRecal = 16
teFind = 0
teHighlight = 1
teDraw = -1
-teCaret = -2
-teFUseTextServices = 4
+teCaret = -2
+teFUseTextServices = 4
diff --git a/Lib/plat-mac/Carbon/Windows.py b/Lib/plat-mac/Carbon/Windows.py
index af8eaf2c88..b09d53710a 100644
--- a/Lib/plat-mac/Carbon/Windows.py
+++ b/Lib/plat-mac/Carbon/Windows.py
@@ -44,7 +44,7 @@ kWindowStandardFloatingAttributes = (kWindowCloseBoxAttribute | kWindowCollapseB
kWindowDefProcType = FOUR_CHAR_CODE('WDEF')
kStandardWindowDefinition = 0
kRoundWindowDefinition = 1
-kFloatingWindowDefinition = 124
+kFloatingWindowDefinition = 124
kDocumentWindowVariantCode = 0
kModalDialogVariantCode = 1
kPlainDialogVariantCode = 2
@@ -109,7 +109,7 @@ kWindowFloatSideHorizZoomGrowProc = 1083
kWindowFloatSideFullZoomProc = 1085
kWindowFloatSideFullZoomGrowProc = 1087
kWindowSheetProc = 1088
-kWindowSheetAlertProc = 1120
+kWindowSheetAlertProc = 1120
kWindowSimpleProc = 1104
kWindowSimpleFrameProc = 1105
kWindowNoPosition = 0x0000
@@ -145,7 +145,7 @@ kWindowStructureRgn = 32
kWindowContentRgn = 33
kWindowUpdateRgn = 34
kWindowOpaqueRgn = 35
-kWindowGlobalPortRgn = 40
+kWindowGlobalPortRgn = 40
dialogKind = 2
userKind = 8
kDialogWindowKind = 2
@@ -163,7 +163,7 @@ inZoomOut = 8
inCollapseBox = 11
inProxyIcon = 12
inToolbarButton = 13
-inStructure = 15
+inStructure = 15
wNoHit = 0
wInContent = 1
wInDrag = 2
@@ -174,7 +174,7 @@ wInZoomOut = 6
wInCollapseBox = 9
wInProxyIcon = 10
wInToolbarButton = 11
-wInStructure = 13
+wInStructure = 13
kWindowMsgDraw = 0
kWindowMsgHitTest = 1
kWindowMsgCalculateShape = 2
@@ -189,8 +189,8 @@ kWindowMsgModified = 10
kWindowMsgDrawInCurrentPort = 11
kWindowMsgSetupProxyDragImage = 12
kWindowMsgStateChanged = 13
-kWindowMsgMeasureTitle = 14
-kWindowMsgGetGrowImageRegion = 19
+kWindowMsgMeasureTitle = 14
+kWindowMsgGetGrowImageRegion = 19
wDraw = 0
wHit = 1
wCalcRgns = 2
@@ -214,7 +214,7 @@ kWindowCanMeasureTitle = (1 << 11)
kWindowWantsDisposeAtProcessDeath = (1 << 12)
kWindowSupportsGetGrowImageRegion = (1 << 13)
kWindowDefSupportsColorGrafPort = 0x40000002
-kWindowIsOpaque = (1 << 14)
+kWindowIsOpaque = (1 << 14)
kWindowSupportsSetGrowImageRegion = (1 << 13)
deskPatID = 16
wContentColor = 0
@@ -228,10 +228,10 @@ kWindowDefinitionVersionTwo = 2
kWindowIsCollapsedState = (1 << 0L)
kStoredWindowSystemTag = FOUR_CHAR_CODE('appl')
kStoredBasicWindowDescriptionID = FOUR_CHAR_CODE('sbas')
-kStoredWindowPascalTitleID = FOUR_CHAR_CODE('s255')
+kStoredWindowPascalTitleID = FOUR_CHAR_CODE('s255')
kWindowDefProcPtr = 0
kWindowDefObjectClass = 1
-kWindowDefProcID = 2
+kWindowDefProcID = 2
kWindowModalityNone = 0
kWindowModalitySystemModal = 1
kWindowModalityAppModal = 2
@@ -252,7 +252,7 @@ kWindowGroupContentsVisible = 1 << 2
kWindowPaintProcOptionsNone = 0
kScrollWindowNoOptions = 0
kScrollWindowInvalidate = (1L << 0)
-kScrollWindowEraseToPortBackground = (1L << 1)
+kScrollWindowEraseToPortBackground = (1L << 1)
kWindowMenuIncludeRotate = 1 << 0
kWindowZoomTransitionEffect = 1
kWindowSheetTransitionEffect = 2
@@ -273,7 +273,7 @@ kWindowLatentVisibleFullScreen = 1 << 2
kWindowLatentVisibleAppHidden = 1 << 3
kWindowLatentVisibleCollapsedOwner = 1 << 4
kWindowLatentVisibleCollapsedGroup = 1 << 5
-kWindowPropertyPersistent = 0x00000001
+kWindowPropertyPersistent = 0x00000001
kWindowGroupAttrSelectable = kWindowGroupAttrSelectAsLayer
kWindowGroupAttrPositionFixed = kWindowGroupAttrMoveTogether
kWindowGroupAttrZOrderFixed = kWindowGroupAttrLayerTogether
diff --git a/Lib/plat-mac/Carbon/__init__.py b/Lib/plat-mac/Carbon/__init__.py
index d0cfec381f..8018c18244 100644
--- a/Lib/plat-mac/Carbon/__init__.py
+++ b/Lib/plat-mac/Carbon/__init__.py
@@ -1,4 +1,4 @@
# Filter out warnings about signed/unsigned constants
import warnings
warnings.filterwarnings("ignore", "", FutureWarning, ".*Controls")
-warnings.filterwarnings("ignore", "", FutureWarning, ".*MacTextEditor") \ No newline at end of file
+warnings.filterwarnings("ignore", "", FutureWarning, ".*MacTextEditor")
diff --git a/Lib/plat-mac/EasyDialogs.py b/Lib/plat-mac/EasyDialogs.py
index 13df7f307f..c622d302f4 100644
--- a/Lib/plat-mac/EasyDialogs.py
+++ b/Lib/plat-mac/EasyDialogs.py
@@ -373,22 +373,22 @@ ARGV_CMDLINE_DATA=14
## MacOS.HandleEvent(ev)
##
def _setmenu(control, items):
- mhandle = control.GetControlData_Handle(Controls.kControlMenuPart,
- Controls.kControlPopupButtonMenuHandleTag)
- menu = Menu.as_Menu(mhandle)
- for item in items:
- if type(item) == type(()):
- label = item[0]
- else:
- label = item
- if label[-1] == '=' or label[-1] == ':':
- label = label[:-1]
- menu.AppendMenu(label)
+ mhandle = control.GetControlData_Handle(Controls.kControlMenuPart,
+ Controls.kControlPopupButtonMenuHandleTag)
+ menu = Menu.as_Menu(mhandle)
+ for item in items:
+ if type(item) == type(()):
+ label = item[0]
+ else:
+ label = item
+ if label[-1] == '=' or label[-1] == ':':
+ label = label[:-1]
+ menu.AppendMenu(label)
## mhandle, mid = menu.getpopupinfo()
## control.SetControlData_Handle(Controls.kControlMenuPart,
## Controls.kControlPopupButtonMenuHandleTag, mhandle)
- control.SetControlMinimum(1)
- control.SetControlMaximum(len(items)+1)
+ control.SetControlMinimum(1)
+ control.SetControlMaximum(len(items)+1)
def _selectoption(d, optionlist, idx):
if idx < 0 or idx >= len(optionlist):
@@ -836,4 +836,3 @@ if __name__ == '__main__':
test()
except KeyboardInterrupt:
Message("Operation Canceled.")
-
diff --git a/Lib/plat-mac/FrameWork.py b/Lib/plat-mac/FrameWork.py
index 7242704fbe..0a8c1b8e6e 100644
--- a/Lib/plat-mac/FrameWork.py
+++ b/Lib/plat-mac/FrameWork.py
@@ -635,7 +635,7 @@ class Menu:
if self._parent:
self._parent.menu.DisableMenuItem(self._parent_item)
if self.bar and self.bar.parent:
- self.bar.parent.needmenubarredraw = 1
+ self.bar.parent.needmenubarredraw = 1
class PopupMenu(Menu):
def __init__(self, bar):
diff --git a/Lib/plat-mac/MiniAEFrame.py b/Lib/plat-mac/MiniAEFrame.py
index 3c5ed9aa5a..98247cbf34 100644
--- a/Lib/plat-mac/MiniAEFrame.py
+++ b/Lib/plat-mac/MiniAEFrame.py
@@ -59,9 +59,9 @@ class MiniApplication:
self.quitting = 1
def dooneevent(self, mask = everyEvent, timeout = 60*60):
- got, event = Evt.WaitNextEvent(mask, timeout)
- if got:
- self.lowlevelhandler(event)
+ got, event = Evt.WaitNextEvent(mask, timeout)
+ if got:
+ self.lowlevelhandler(event)
def lowlevelhandler(self, event):
what, message, when, where, modifiers = event
diff --git a/Lib/plat-mac/PixMapWrapper.py b/Lib/plat-mac/PixMapWrapper.py
index a2d13feecb..7edbac26c8 100644
--- a/Lib/plat-mac/PixMapWrapper.py
+++ b/Lib/plat-mac/PixMapWrapper.py
@@ -1,5 +1,5 @@
"""PixMapWrapper - defines the PixMapWrapper class, which wraps an opaque
-QuickDraw PixMap data structure in a handy Python class. Also provides
+QuickDraw PixMap data structure in a handy Python class. Also provides
methods to convert to/from pixel data (from, e.g., the img module) or a
Python Imaging Library Image object.
@@ -77,7 +77,7 @@ class PixMapWrapper:
2, 5, # cmpCount, cmpSize,
0, 0, 0) # planeBytes, pmTable, pmReserved
self.__dict__['_pm'] = Qd.RawBitMap(self._header)
-
+
def _stuff(self, element, bytes):
offset = _pmElemOffset[element]
fmt = _pmElemFormat[element]
@@ -85,7 +85,7 @@ class PixMapWrapper:
+ struct.pack(fmt, bytes) \
+ self._header[offset + struct.calcsize(fmt):]
self.__dict__['_pm'] = None
-
+
def _unstuff(self, element):
offset = _pmElemOffset[element]
fmt = _pmElemFormat[element]
@@ -113,7 +113,7 @@ class PixMapWrapper:
# any other pm attribute -- just stuff
self._stuff(attr, val)
else:
- self.__dict__[attr] = val
+ self.__dict__[attr] = val
def __getattr__(self, attr):
if attr == 'rowBytes':
@@ -133,9 +133,9 @@ class PixMapWrapper:
# any other pm attribute -- just unstuff
return self._unstuff(attr)
else:
- return self.__dict__[attr]
+ return self.__dict__[attr]
+
-
def PixMap(self):
"Return a QuickDraw PixMap corresponding to this data."
if not self.__dict__['_pm']:
@@ -143,7 +143,7 @@ class PixMapWrapper:
return self.__dict__['_pm']
def blit(self, x1=0,y1=0,x2=None,y2=None, port=None):
- """Draw this pixmap into the given (default current) grafport."""
+ """Draw this pixmap into the given (default current) grafport."""
src = self.bounds
dest = [x1,y1,x2,y2]
if x2 == None:
@@ -153,7 +153,7 @@ class PixMapWrapper:
if not port: port = Qd.GetPort()
Qd.CopyBits(self.PixMap(), port.GetPortBitMapForCopyBits(), src, tuple(dest),
QuickDraw.srcCopy, None)
-
+
def fromstring(self,s,width,height,format=imgformat.macrgb):
"""Stuff this pixmap with raw pixel data from a string.
Supply width, height, and one of the imgformat specifiers."""
@@ -188,7 +188,7 @@ class PixMapWrapper:
"""Initialize this PixMap from a PIL Image object."""
# We need data in ARGB format; PIL can't currently do that,
# but it can do RGBA, which we can use by inserting one null
- # up frontpm =
+ # up frontpm =
if im.mode != 'RGBA': im = im.convert('RGBA')
data = chr(0) + im.tostring()
self.fromstring(data, im.size[0], im.size[1])
@@ -212,4 +212,3 @@ def test():
pm.fromImage( Image.open(path) )
pm.blit(20,20)
return pm
-
diff --git a/Lib/plat-mac/aepack.py b/Lib/plat-mac/aepack.py
index 22dfd21dd1..529a0a4ed8 100644
--- a/Lib/plat-mac/aepack.py
+++ b/Lib/plat-mac/aepack.py
@@ -74,16 +74,16 @@ def packkey(ae, key, value):
def pack(x, forcetype = None):
"""Pack a python object into an AE descriptor"""
-
+
if forcetype:
if type(x) is StringType:
return AE.AECreateDesc(forcetype, x)
else:
return pack(x).AECoerceDesc(forcetype)
-
+
if x == None:
return AE.AECreateDesc('null', '')
-
+
if isinstance(x, AEDescType):
return x
if isinstance(x, FSSType):
@@ -128,11 +128,11 @@ def pack(x, forcetype = None):
def unpack(desc, formodulename=""):
"""Unpack an AE descriptor to a python object"""
t = desc.type
-
+
if unpacker_coercions.has_key(t):
desc = desc.AECoerceDesc(unpacker_coercions[t])
t = desc.type # This is a guess by Jack....
-
+
if t == typeAEList:
l = []
for i in range(desc.AECountItems()):
@@ -248,7 +248,7 @@ def unpack(desc, formodulename=""):
record = desc.AECoerceDesc('reco')
return mklogical(unpack(record, formodulename))
return mkunknown(desc.type, desc.data)
-
+
def coerce(data, egdata):
"""Coerce a python object to another type using the AE coercers"""
pdata = pack(data)
@@ -311,10 +311,10 @@ def mklogical(dict):
def mkstyledtext(dict):
return aetypes.StyledText(dict['ksty'], dict['ktxt'])
-
+
def mkaetext(dict):
return aetypes.AEText(dict[keyAEScriptTag], dict[keyAEStyles], dict[keyAEText])
-
+
def mkinsertionloc(dict):
return aetypes.InsertionLoc(dict[keyAEObject], dict[keyAEPosition])
@@ -355,7 +355,7 @@ def mkobjectfrommodule(dict, modulename):
assert issubclass(classtype, ObjectSpecifier)
newobj.__class__ = classtype
return newobj
-
+
def mktype(typecode, modulename=None):
if modulename:
module = __import__(modulename)
diff --git a/Lib/plat-mac/aetools.py b/Lib/plat-mac/aetools.py
index 347b523796..79f3978316 100644
--- a/Lib/plat-mac/aetools.py
+++ b/Lib/plat-mac/aetools.py
@@ -113,7 +113,7 @@ def keysubst(arguments, keydict):
arguments[keydict[k]] = v
elif k != '----' and k not in ok:
raise TypeError, 'Unknown keyword argument: %s'%k
-
+
def enumsubst(arguments, key, edict):
"""Substitute a single enum keyword argument, if it occurs"""
if not arguments.has_key(key) or edict is None:
@@ -124,7 +124,7 @@ def enumsubst(arguments, key, edict):
arguments[key] = Enum(edict[v])
elif not v in ok:
raise TypeError, 'Unknown enumerator: %s'%v
-
+
def decodeerror(arguments):
"""Create the 'best' argument for a raise MacOS.Error"""
errn = arguments['errn']
@@ -137,7 +137,7 @@ def decodeerror(arguments):
err_a3 = arguments['erob']
else:
err_a3 = None
-
+
return (err_a1, err_a2, err_a3)
class TalkTo:
@@ -146,7 +146,7 @@ class TalkTo:
_moduleName = None # Can be overridden by subclasses
_elemdict = {} # Can be overridden by subclasses
_propdict = {} # Can be overridden by subclasses
-
+
__eventloop_initialized = 0
def __ensure_WMAvailable(klass):
if klass.__eventloop_initialized: return 1
@@ -156,10 +156,10 @@ class TalkTo:
Evt.WaitNextEvent(0,0)
return 1
__ensure_WMAvailable = classmethod(__ensure_WMAvailable)
-
+
def __init__(self, signature=None, start=0, timeout=0):
"""Create a communication channel with a particular application.
-
+
Addressing the application is done by specifying either a
4-byte signature, an AEDesc or an object that will __aepack__
to an AEDesc.
@@ -184,7 +184,7 @@ class TalkTo:
self.send_timeout = AppleEvents.kAEDefaultTimeout
if start:
self._start()
-
+
def _start(self):
"""Start the application, if it is not running yet"""
try:
@@ -199,19 +199,19 @@ class TalkTo:
else:
break
time.sleep(1)
-
+
def start(self):
"""Deprecated, used _start()"""
self._start()
-
+
def newevent(self, code, subcode, parameters = {}, attributes = {}):
"""Create a complete structure for an apple event"""
-
+
event = AE.AECreateAppleEvent(code, subcode, self.target,
AppleEvents.kAutoGenerateReturnID, AppleEvents.kAnyTransactionID)
packevent(event, parameters, attributes)
return event
-
+
def sendevent(self, event):
"""Send a pre-created appleevent, await the reply and unpack it"""
if not self.__ensure_WMAvailable():
@@ -220,11 +220,11 @@ class TalkTo:
self.send_timeout)
parameters, attributes = unpackevent(reply, self._moduleName)
return reply, parameters, attributes
-
+
def send(self, code, subcode, parameters = {}, attributes = {}):
"""Send an appleevent given code/subcode/pars/attrs and unpack the reply"""
return self.sendevent(self.newevent(code, subcode, parameters, attributes))
-
+
#
# The following events are somehow "standard" and don't seem to appear in any
# suite...
@@ -256,9 +256,9 @@ class TalkTo:
if as:
item.__class__ = as
return item
-
+
get = _get
-
+
_argmap_set = {
'to' : 'data',
}
@@ -283,12 +283,12 @@ class TalkTo:
# XXXX Optionally decode result
if _arguments.has_key('----'):
return _arguments['----']
-
+
set = _set
# Magic glue to allow suite-generated classes to function somewhat
# like the "application" class in OSA.
-
+
def __getattr__(self, name):
if self._elemdict.has_key(name):
cls = self._elemdict[name]
@@ -297,7 +297,7 @@ class TalkTo:
cls = self._propdict[name]
return cls()
raise AttributeError, name
-
+
# Tiny Finder class, for local use only
class _miniFinder(TalkTo):
@@ -321,7 +321,7 @@ class _miniFinder(TalkTo):
if _arguments.has_key('----'):
return _arguments['----']
#pass
-
+
_finder = _miniFinder('MACS')
def _launch(appfile):
@@ -332,12 +332,12 @@ def _launch(appfile):
class _application_file(ComponentItem):
"""application file - An application's file on disk"""
want = 'appf'
-
+
_application_file._propdict = {
}
_application_file._elemdict = {
}
-
+
# Test program
# XXXX Should test more, really...
diff --git a/Lib/plat-mac/aetypes.py b/Lib/plat-mac/aetypes.py
index b9386f3bb0..c60b39c7cb 100644
--- a/Lib/plat-mac/aetypes.py
+++ b/Lib/plat-mac/aetypes.py
@@ -12,7 +12,7 @@ import string
def pack(*args, **kwargs):
from aepack import pack
return pack( *args, **kwargs)
-
+
def nice(s):
"""'nice' representation of an object"""
if type(s) is StringType: return repr(s)
@@ -20,29 +20,29 @@ def nice(s):
class Unknown:
"""An uninterpreted AE object"""
-
+
def __init__(self, type, data):
self.type = type
self.data = data
-
+
def __repr__(self):
return "Unknown(%r, %r)" % (self.type, self.data)
-
+
def __aepack__(self):
return pack(self.data, self.type)
class Enum:
"""An AE enumeration value"""
-
+
def __init__(self, enum):
self.enum = "%-4.4s" % str(enum)
-
+
def __repr__(self):
return "Enum(%r)" % (self.enum,)
-
+
def __str__(self):
return string.strip(self.enum)
-
+
def __aepack__(self):
return pack(self.enum, typeEnumeration)
@@ -58,36 +58,36 @@ class InsertionLoc:
def __init__(self, of, pos):
self.of = of
self.pos = pos
-
+
def __repr__(self):
return "InsertionLoc(%r, %r)" % (self.of, self.pos)
-
+
def __aepack__(self):
rec = {'kobj': self.of, 'kpos': self.pos}
return pack(rec, forcetype='insl')
-
+
# Convenience functions for dsp:
def beginning(of):
return InsertionLoc(of, Enum('bgng'))
-
+
def end(of):
return InsertionLoc(of, Enum('end '))
class Boolean:
"""An AE boolean value"""
-
+
def __init__(self, bool):
self.bool = (not not bool)
-
+
def __repr__(self):
return "Boolean(%r)" % (self.bool,)
-
+
def __str__(self):
if self.bool:
return "True"
else:
return "False"
-
+
def __aepack__(self):
return pack(struct.pack('b', self.bool), 'bool')
@@ -100,16 +100,16 @@ def mkboolean(bool):
class Type:
"""An AE 4-char typename object"""
-
+
def __init__(self, type):
self.type = "%-4.4s" % str(type)
-
+
def __repr__(self):
return "Type(%r)" % (self.type,)
-
+
def __str__(self):
return string.strip(self.type)
-
+
def __aepack__(self):
return pack(self.type, typeType)
@@ -123,16 +123,16 @@ def mktype(type):
class Keyword:
"""An AE 4-char keyword object"""
-
+
def __init__(self, keyword):
self.keyword = "%-4.4s" % str(keyword)
-
+
def __repr__(self):
return "Keyword(%r)" % `self.keyword`
-
+
def __str__(self):
return string.strip(self.keyword)
-
+
def __aepack__(self):
return pack(self.keyword, typeKeyword)
@@ -141,17 +141,17 @@ def IsKeyword(x):
class Range:
"""An AE range object"""
-
+
def __init__(self, start, stop):
self.start = start
self.stop = stop
-
+
def __repr__(self):
return "Range(%r, %r)" % (self.start, self.stop)
-
+
def __str__(self):
return "%s thru %s" % (nice(self.start), nice(self.stop))
-
+
def __aepack__(self):
return pack({'star': self.start, 'stop': self.stop}, 'rang')
@@ -160,18 +160,18 @@ def IsRange(x):
class Comparison:
"""An AE Comparison"""
-
+
def __init__(self, obj1, relo, obj2):
self.obj1 = obj1
self.relo = "%-4.4s" % str(relo)
self.obj2 = obj2
-
+
def __repr__(self):
return "Comparison(%r, %r, %r)" % (self.obj1, self.relo, self.obj2)
-
+
def __str__(self):
return "%s %s %s" % (nice(self.obj1), string.strip(self.relo), nice(self.obj2))
-
+
def __aepack__(self):
return pack({'obj1': self.obj1,
'relo': mkenum(self.relo),
@@ -180,48 +180,48 @@ class Comparison:
def IsComparison(x):
return isinstance(x, Comparison)
-
+
class NComparison(Comparison):
# The class attribute 'relo' must be set in a subclass
-
+
def __init__(self, obj1, obj2):
Comparison.__init__(obj1, self.relo, obj2)
class Ordinal:
"""An AE Ordinal"""
-
+
def __init__(self, abso):
# self.obj1 = obj1
self.abso = "%-4.4s" % str(abso)
-
+
def __repr__(self):
return "Ordinal(%r)" % (self.abso,)
-
+
def __str__(self):
return "%s" % (string.strip(self.abso))
-
+
def __aepack__(self):
return pack(self.abso, 'abso')
def IsOrdinal(x):
return isinstance(x, Ordinal)
-
+
class NOrdinal(Ordinal):
# The class attribute 'abso' must be set in a subclass
-
+
def __init__(self):
Ordinal.__init__(self, self.abso)
class Logical:
"""An AE logical expression object"""
-
+
def __init__(self, logc, term):
self.logc = "%-4.4s" % str(logc)
self.term = term
-
+
def __repr__(self):
return "Logical(%r, %r)" % (self.logc, self.term)
-
+
def __str__(self):
if type(self.term) == ListType and len(self.term) == 2:
return "%s %s %s" % (nice(self.term[0]),
@@ -229,7 +229,7 @@ class Logical:
nice(self.term[1]))
else:
return "%s(%s)" % (string.strip(self.logc), nice(self.term))
-
+
def __aepack__(self):
return pack({'logc': mkenum(self.logc), 'term': self.term}, 'logi')
@@ -238,17 +238,17 @@ def IsLogical(x):
class StyledText:
"""An AE object respresenting text in a certain style"""
-
+
def __init__(self, style, text):
self.style = style
self.text = text
-
+
def __repr__(self):
return "StyledText(%r, %r)" % (self.style, self.text)
-
+
def __str__(self):
return self.text
-
+
def __aepack__(self):
return pack({'ksty': self.style, 'ktxt': self.text}, 'STXT')
@@ -257,18 +257,18 @@ def IsStyledText(x):
class AEText:
"""An AE text object with style, script and language specified"""
-
+
def __init__(self, script, style, text):
self.script = script
self.style = style
self.text = text
-
+
def __repr__(self):
return "AEText(%r, %r, %r)" % (self.script, self.style, self.text)
-
+
def __str__(self):
return self.text
-
+
def __aepack__(self):
return pack({keyAEScriptTag: self.script, keyAEStyles: self.style,
keyAEText: self.text}, typeAEText)
@@ -278,18 +278,18 @@ def IsAEText(x):
class IntlText:
"""A text object with script and language specified"""
-
+
def __init__(self, script, language, text):
self.script = script
self.language = language
self.text = text
-
+
def __repr__(self):
return "IntlText(%r, %r, %r)" % (self.script, self.language, self.text)
-
+
def __str__(self):
return self.text
-
+
def __aepack__(self):
return pack(struct.pack('hh', self.script, self.language)+self.text,
typeIntlText)
@@ -299,17 +299,17 @@ def IsIntlText(x):
class IntlWritingCode:
"""An object representing script and language"""
-
+
def __init__(self, script, language):
self.script = script
self.language = language
-
+
def __repr__(self):
return "IntlWritingCode(%r, %r)" % (self.script, self.language)
-
+
def __str__(self):
return "script system %d, language %d"%(self.script, self.language)
-
+
def __aepack__(self):
return pack(struct.pack('hh', self.script, self.language),
typeIntlWritingCode)
@@ -319,17 +319,17 @@ def IsIntlWritingCode(x):
class QDPoint:
"""A point"""
-
+
def __init__(self, v, h):
self.v = v
self.h = h
-
+
def __repr__(self):
return "QDPoint(%r, %r)" % (self.v, self.h)
-
+
def __str__(self):
return "(%d, %d)"%(self.v, self.h)
-
+
def __aepack__(self):
return pack(struct.pack('hh', self.v, self.h),
typeQDPoint)
@@ -339,19 +339,19 @@ def IsQDPoint(x):
class QDRectangle:
"""A rectangle"""
-
+
def __init__(self, v0, h0, v1, h1):
self.v0 = v0
self.h0 = h0
self.v1 = v1
self.h1 = h1
-
+
def __repr__(self):
return "QDRectangle(%r, %r, %r, %r)" % (self.v0, self.h0, self.v1, self.h1)
-
+
def __str__(self):
return "(%d, %d)-(%d, %d)"%(self.v0, self.h0, self.v1, self.h1)
-
+
def __aepack__(self):
return pack(struct.pack('hhhh', self.v0, self.h0, self.v1, self.h1),
typeQDRectangle)
@@ -361,18 +361,18 @@ def IsQDRectangle(x):
class RGBColor:
"""An RGB color"""
-
+
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
-
+
def __repr__(self):
return "RGBColor(%r, %r, %r)" % (self.r, self.g, self.b)
-
+
def __str__(self):
return "0x%x red, 0x%x green, 0x%x blue"% (self.r, self.g, self.b)
-
+
def __aepack__(self):
return pack(struct.pack('hhh', self.r, self.g, self.b),
typeRGBColor)
@@ -381,36 +381,36 @@ def IsRGBColor(x):
return isinstance(x, RGBColor)
class ObjectSpecifier:
-
+
"""A class for constructing and manipulation AE object specifiers in python.
-
+
An object specifier is actually a record with four fields:
-
+
key type description
--- ---- -----------
-
+
'want' type 4-char class code of thing we want,
e.g. word, paragraph or property
-
+
'form' enum how we specify which 'want' thing(s) we want,
e.g. by index, by range, by name, or by property specifier
-
+
'seld' any which thing(s) we want,
e.g. its index, its name, or its property specifier
-
+
'from' object the object in which it is contained,
or null, meaning look for it in the application
-
+
Note that we don't call this class plain "Object", since that name
is likely to be used by the application.
"""
-
+
def __init__(self, want, form, seld, fr = None):
self.want = want
self.form = form
self.seld = seld
self.fr = fr
-
+
def __repr__(self):
s = "ObjectSpecifier(%r, %r, %r" % (self.want, self.form, self.seld)
if self.fr:
@@ -418,7 +418,7 @@ class ObjectSpecifier:
else:
s = s + ")"
return s
-
+
def __aepack__(self):
return pack({'want': mktype(self.want),
'form': mkenum(self.form),
@@ -441,7 +441,7 @@ class Property(ObjectSpecifier):
return "Property(%r, %r)" % (self.seld.type, self.fr)
else:
return "Property(%r)" % (self.seld.type,)
-
+
def __str__(self):
if self.fr:
return "Property %s of %s" % (str(self.seld), str(self.fr))
@@ -460,7 +460,7 @@ class NProperty(ObjectSpecifier):
#except:
# self.want = 'prop'
self.want = 'prop'
- ObjectSpecifier.__init__(self, self.want, 'prop',
+ ObjectSpecifier.__init__(self, self.want, 'prop',
mktype(self.which), fr)
def __repr__(self):
@@ -470,7 +470,7 @@ class NProperty(ObjectSpecifier):
if self.want != 'prop':
rv = rv + ", want=%r" % (self.want,)
return rv + ")"
-
+
def __str__(self):
if self.fr:
return "Property %s of %s" % (str(self.seld), str(self.fr))
@@ -479,7 +479,7 @@ class NProperty(ObjectSpecifier):
class SelectableItem(ObjectSpecifier):
-
+
def __init__(self, want, seld, fr = None):
t = type(seld)
if t == StringType:
@@ -506,12 +506,12 @@ class ComponentItem(SelectableItem):
_elemdict = {}
def __init__(self, which, fr = None):
SelectableItem.__init__(self, self.want, which, fr)
-
+
def __repr__(self):
if not self.fr:
return "%s(%r)" % (self.__class__.__name__, self.seld)
return "%s(%r, %r)" % (self.__class__.__name__, self.seld, self.fr)
-
+
def __str__(self):
seld = self.seld
if type(seld) == StringType:
@@ -528,7 +528,7 @@ class ComponentItem(SelectableItem):
s = "%s %s" % (self.__class__.__name__, ss)
if self.fr: s = s + " of %s" % str(self.fr)
return s
-
+
def __getattr__(self, name):
if self._elemdict.has_key(name):
cls = self._elemdict[name]
@@ -537,19 +537,19 @@ class ComponentItem(SelectableItem):
cls = self._propdict[name]
return cls(self)
raise AttributeError, name
-
-
+
+
class DelayedComponentItem:
def __init__(self, compclass, fr):
self.compclass = compclass
self.fr = fr
-
+
def __call__(self, which):
return self.compclass(which, self.fr)
-
+
def __repr__(self):
return "%s(???, %r)" % (self.__class__.__name__, self.fr)
-
+
def __str__(self):
return "selector for element %s of %s"%(self.__class__.__name__, str(self.fr))
@@ -566,4 +566,3 @@ exec template % ("Window", 'cwin')
exec template % ("Document", 'docu')
exec template % ("File", 'file')
exec template % ("InsertionPoint", 'cins')
-
diff --git a/Lib/plat-mac/applesingle.py b/Lib/plat-mac/applesingle.py
index adbce0c510..7bbe8af8cc 100644
--- a/Lib/plat-mac/applesingle.py
+++ b/Lib/plat-mac/applesingle.py
@@ -78,7 +78,7 @@ class AppleSingle(object):
self.datafork = data
elif restype == AS_RESOURCEFORK:
self.resourcefork = data
-
+
def tofile(self, path, resonly=False):
outfile = open(path, 'wb')
data = False
@@ -99,15 +99,15 @@ class AppleSingle(object):
fp = MacOS.openrf(path, '*wb')
fp.write(self.resourcefork)
fp.close()
-
+
def decode(infile, outpath, resonly=False, verbose=False):
"""decode(infile, outpath [, resonly=False, verbose=False])
Creates a decoded file from an AppleSingle encoded file.
- If resonly is True, then it will create a regular file at
+ If resonly is True, then it will create a regular file at
outpath containing only the resource fork from infile.
Otherwise it will create an AppleDouble file at outpath
- with the data and resource forks from infile. On platforms
+ with the data and resource forks from infile. On platforms
without the MacOS module, it will create inpath and inpath+'.rsrc'
with the data and resource forks respectively.
@@ -121,7 +121,7 @@ def decode(infile, outpath, resonly=False, verbose=False):
as = AppleSingle(infile, verbose=verbose)
as.tofile(outpath, resonly=resonly)
-
+
def _test():
if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4:
print 'Usage: applesingle.py [-r] applesinglefile decodedfile'
@@ -132,6 +132,6 @@ def _test():
else:
resonly = False
decode(sys.argv[1], sys.argv[2], resonly=resonly)
-
+
if __name__ == '__main__':
_test()
diff --git a/Lib/plat-mac/appletrawmain.py b/Lib/plat-mac/appletrawmain.py
index 88259c1b3a..1be9187907 100644
--- a/Lib/plat-mac/appletrawmain.py
+++ b/Lib/plat-mac/appletrawmain.py
@@ -23,7 +23,7 @@ else:
_dir = os.path.split(sys.argv[0])[0]
#
# Add the Resources directory to the path. This is where files installed
-# by BuildApplet.py with the --extra option show up, and if those files are
+# by BuildApplet.py with the --extra option show up, and if those files are
# modules this sys.path modification is necessary to be able to import them.
#
sys.path.insert(0, _dir)
diff --git a/Lib/plat-mac/bgenlocations.py b/Lib/plat-mac/bgenlocations.py
index 19e1f022cb..e7fa354075 100644
--- a/Lib/plat-mac/bgenlocations.py
+++ b/Lib/plat-mac/bgenlocations.py
@@ -31,13 +31,13 @@ TOOLBOXDIR="/Users/jack/src/python/Lib/plat-mac/Carbon"
# Creator for C files:
CREATOR="CWIE"
-# The previous definitions can be overriden by creating a module
-# bgenlocationscustomize.py and putting it in site-packages (or anywere else
+# The previous definitions can be overriden by creating a module
+# bgenlocationscustomize.py and putting it in site-packages (or anywere else
# on sys.path, actually)
try:
- from bgenlocationscustomize import *
+ from bgenlocationscustomize import *
except ImportError:
- pass
+ pass
if not os.path.exists(BGENDIR):
raise Error, "Please fix bgenlocations.py, BGENDIR does not exist: %s" % BGENDIR
@@ -45,7 +45,7 @@ if not os.path.exists(INCLUDEDIR):
raise Error, "Please fix bgenlocations.py, INCLUDEDIR does not exist: %s" % INCLUDEDIR
if not os.path.exists(TOOLBOXDIR):
raise Error, "Please fix bgenlocations.py, TOOLBOXDIR does not exist: %s" % TOOLBOXDIR
-
+
# Sigh, due to the way these are used make sure they end with : or /.
if BGENDIR[-1] != os.sep:
BGENDIR = BGENDIR + os.sep
@@ -53,4 +53,3 @@ if INCLUDEDIR[-1] != os.sep:
INCLUDEDIR = INCLUDEDIR + os.sep
if TOOLBOXDIR[-1] != os.sep:
TOOLBOXDIR = TOOLBOXDIR + os.sep
-
diff --git a/Lib/plat-mac/buildtools.py b/Lib/plat-mac/buildtools.py
index 365772a0d5..17e4076457 100644
--- a/Lib/plat-mac/buildtools.py
+++ b/Lib/plat-mac/buildtools.py
@@ -58,10 +58,10 @@ def findtemplate(template=None):
raise BuildError, "Template %r not found on sys.path" % (template,)
file = file.as_pathname()
return file
-
-def process(template, filename, destname, copy_codefragment=0,
+
+def process(template, filename, destname, copy_codefragment=0,
rsrcname=None, others=[], raw=0, progress="default"):
-
+
if progress == "default":
progress = EasyDialogs.ProgressBar("Processing %s..."%os.path.split(filename)[1], 120)
progress.label("Compiling...")
@@ -72,7 +72,7 @@ def process(template, filename, destname, copy_codefragment=0,
raise BuildError, "BuildApplet could destroy your sourcefile on OSX, please rename: %s" % filename
# Read the source and compile it
# (there's no point overwriting the destination if it has a syntax error)
-
+
fp = open(filename, 'rU')
text = fp.read()
fp.close()
@@ -82,17 +82,17 @@ def process(template, filename, destname, copy_codefragment=0,
raise BuildError, "Syntax error in script %s: %s" % (filename, arg)
except EOFError:
raise BuildError, "End-of-file in script %s" % (filename,)
-
+
# Set the destination file name. Note that basename
# does contain the whole filepath, only a .py is stripped.
-
+
if string.lower(filename[-3:]) == ".py":
basename = filename[:-3]
if MacOS.runtimemodel != 'macho' and not destname:
destname = basename
else:
basename = filename
-
+
if not destname:
if MacOS.runtimemodel == 'macho':
destname = basename + '.app'
@@ -100,16 +100,16 @@ def process(template, filename, destname, copy_codefragment=0,
destname = basename + '.applet'
if not rsrcname:
rsrcname = basename + '.rsrc'
-
+
# Try removing the output file. This fails in MachO, but it should
# do any harm.
try:
os.remove(destname)
except os.error:
pass
- process_common(template, progress, code, rsrcname, destname, 0,
+ process_common(template, progress, code, rsrcname, destname, 0,
copy_codefragment, raw, others, filename)
-
+
def update(template, filename, output):
if MacOS.runtimemodel == 'macho':
@@ -120,7 +120,7 @@ def update(template, filename, output):
progress = None
if not output:
output = filename + ' (updated)'
-
+
# Try removing the output file
try:
os.remove(output)
@@ -129,7 +129,7 @@ def update(template, filename, output):
process_common(template, progress, None, filename, output, 1, 1)
-def process_common(template, progress, code, rsrcname, destname, is_update,
+def process_common(template, progress, code, rsrcname, destname, is_update,
copy_codefragment, raw=0, others=[], filename=None):
if MacOS.runtimemodel == 'macho':
return process_common_macho(template, progress, code, rsrcname, destname,
@@ -139,12 +139,12 @@ def process_common(template, progress, code, rsrcname, destname, is_update,
# Create FSSpecs for the various files
template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1)
template = template_fsr.as_pathname()
-
+
# Copy data (not resources, yet) from the template
if progress:
progress.label("Copy data fork...")
progress.set(10)
-
+
if copy_codefragment:
tmpl = open(template, "rb")
dest = open(destname, "wb")
@@ -155,9 +155,9 @@ def process_common(template, progress, code, rsrcname, destname, is_update,
tmpl.close()
del dest
del tmpl
-
+
# Open the output resource fork
-
+
if progress:
progress.label("Copy resources...")
progress.set(20)
@@ -167,7 +167,7 @@ def process_common(template, progress, code, rsrcname, destname, is_update,
destdir, destfile = os.path.split(destname)
Res.FSCreateResourceFile(destdir, unicode(destfile), RESOURCE_FORK_NAME)
output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE)
-
+
# Copy the resources from the target specific resource template, if any
typesfound, ownertype = [], None
try:
@@ -183,27 +183,27 @@ def process_common(template, progress, code, rsrcname, destname, is_update,
skip_oldfile = []
typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress)
Res.CloseResFile(input)
-
+
# Check which resource-types we should not copy from the template
skiptypes = []
if 'vers' in typesfound: skiptypes.append('vers')
if 'SIZE' in typesfound: skiptypes.append('SIZE')
- if 'BNDL' in typesfound: skiptypes = skiptypes + ['BNDL', 'FREF', 'icl4',
+ if 'BNDL' in typesfound: skiptypes = skiptypes + ['BNDL', 'FREF', 'icl4',
'icl8', 'ics4', 'ics8', 'ICN#', 'ics#']
if not copy_codefragment:
skiptypes.append('cfrg')
## skipowner = (ownertype <> None)
-
+
# Copy the resources from the template
-
+
input = Res.FSOpenResourceFile(template, RESOURCE_FORK_NAME, READ)
dummy, tmplowner = copyres(input, output, skiptypes, 1, progress)
-
+
Res.CloseResFile(input)
## if ownertype == None:
## raise BuildError, "No owner resource found in either resource file or template"
# Make sure we're manipulating the output resource file now
-
+
Res.UseResFile(output)
if ownertype == None:
@@ -213,27 +213,27 @@ def process_common(template, progress, code, rsrcname, destname, is_update,
newres = Res.Resource('\0')
newres.AddResource(DEFAULT_APPLET_CREATOR, 0, "Owner resource")
ownertype = DEFAULT_APPLET_CREATOR
-
+
if code:
# Delete any existing 'PYC ' resource named __main__
-
+
try:
res = Res.Get1NamedResource(RESTYPE, RESNAME)
res.RemoveResource()
except Res.Error:
pass
-
+
# Create the raw data for the resource from the code object
if progress:
progress.label("Write PYC resource...")
progress.set(120)
-
+
data = marshal.dumps(code)
del code
data = (MAGIC + '\0\0\0\0') + data
-
+
# Create the resource and write it
-
+
id = 0
while id < 128:
id = Res.Unique1ID(RESTYPE)
@@ -244,11 +244,11 @@ def process_common(template, progress, code, rsrcname, destname, is_update,
res.SetResAttrs(attrs)
res.WriteResource()
res.ReleaseResource()
-
+
# Close the output file
-
+
Res.CloseResFile(output)
-
+
# Now set the creator, type and bundle bit of the destination.
# Done with FSSpec's, FSRef FInfo isn't good enough yet (2.3a1+)
dest_fss = Carbon.File.FSSpec(destname)
@@ -258,13 +258,13 @@ def process_common(template, progress, code, rsrcname, destname, is_update,
dest_finfo.Flags = dest_finfo.Flags | Carbon.Files.kHasBundle | Carbon.Files.kIsShared
dest_finfo.Flags = dest_finfo.Flags & ~Carbon.Files.kHasBeenInited
dest_fss.FSpSetFInfo(dest_finfo)
-
+
macostools.touched(destname)
if progress:
progress.label("Done.")
progress.inc(0)
-def process_common_macho(template, progress, code, rsrcname, destname, is_update,
+def process_common_macho(template, progress, code, rsrcname, destname, is_update,
raw=0, others=[], filename=None):
# Check that we have a filename
if filename is None:
@@ -304,7 +304,7 @@ def process_common_macho(template, progress, code, rsrcname, destname, is_update
builder.name = shortname
if rsrcname:
realrsrcname = macresource.resource_pathname(rsrcname)
- builder.files.append((realrsrcname,
+ builder.files.append((realrsrcname,
os.path.join('Contents/Resources', os.path.basename(rsrcname))))
for o in others:
if type(o) == str:
@@ -320,10 +320,10 @@ def process_common_macho(template, progress, code, rsrcname, destname, is_update
builder.argv_emulation = 1
builder.setup()
builder.build()
- if progress:
+ if progress:
progress.label('Done.')
progress.inc(0)
-
+
## macostools.touched(dest_fss)
# Copy resources between two resource file descriptors.
@@ -406,7 +406,7 @@ def copyapptree(srctree, dsttree, exceptlist=[], progress=None):
progress.label('Copy '+this)
progress.inc(0)
shutil.copy2(srcpath, dstpath)
-
+
def writepycfile(codeobject, cfile):
import marshal
fc = open(cfile, 'wb')
@@ -417,4 +417,3 @@ def writepycfile(codeobject, cfile):
fc.seek(0, 0)
fc.write(MAGIC)
fc.close()
-
diff --git a/Lib/plat-mac/cfmfile.py b/Lib/plat-mac/cfmfile.py
index 317046a89b..fd1a3e86ca 100644
--- a/Lib/plat-mac/cfmfile.py
+++ b/Lib/plat-mac/cfmfile.py
@@ -18,19 +18,19 @@ error = "cfm.error"
BUFSIZE = 0x80000
def mergecfmfiles(srclist, dst, architecture = 'fat'):
- """Merge all files in srclist into a new file dst.
-
+ """Merge all files in srclist into a new file dst.
+
If architecture is given, only code fragments of that type will be used:
"pwpc" for PPC, "m68k" for cfm68k. This does not work for "classic"
68k code, since it does not use code fragments to begin with.
If architecture is None, all fragments will be used, enabling FAT binaries.
"""
-
+
srclist = list(srclist)
for i in range(len(srclist)):
srclist[i] = Carbon.File.pathname(srclist[i])
dst = Carbon.File.pathname(dst)
-
+
dstfile = open(dst, "wb")
rf = Res.FSpOpenResFile(dst, 3)
try:
@@ -43,9 +43,9 @@ def mergecfmfiles(srclist, dst, architecture = 'fat'):
if frag.architecture == 'm68k' and architecture == 'pwpc':
continue
dstcfrg.append(frag)
-
+
frag.copydata(dstfile)
-
+
cfrgres = Res.Resource(dstcfrg.build())
Res.UseResFile(rf)
cfrgres.AddResource('cfrg', 0, "")
@@ -55,7 +55,7 @@ def mergecfmfiles(srclist, dst, architecture = 'fat'):
class CfrgResource:
-
+
def __init__(self, path = None):
self.version = 1
self.fragments = []
@@ -74,43 +74,43 @@ class CfrgResource:
Res.UseResFile(currentresref)
self.parse(data)
if self.version <> 1:
- raise error, "unknown 'cfrg' resource format"
-
+ raise error, "unknown 'cfrg' resource format"
+
def parse(self, data):
- (res1, res2, self.version,
- res3, res4, res5, res6,
+ (res1, res2, self.version,
+ res3, res4, res5, res6,
self.memberCount) = struct.unpack("8l", data[:32])
data = data[32:]
while data:
frag = FragmentDescriptor(self.path, data)
data = data[frag.memberSize:]
self.fragments.append(frag)
-
+
def build(self):
self.memberCount = len(self.fragments)
data = struct.pack("8l", 0, 0, self.version, 0, 0, 0, 0, self.memberCount)
for frag in self.fragments:
data = data + frag.build()
return data
-
+
def append(self, frag):
self.fragments.append(frag)
class FragmentDescriptor:
-
+
def __init__(self, path, data = None):
self.path = path
if data is not None:
self.parse(data)
-
+
def parse(self, data):
self.architecture = data[:4]
- ( self.updatelevel,
- self.currentVersion,
- self.oldDefVersion,
+ ( self.updatelevel,
+ self.currentVersion,
+ self.oldDefVersion,
self.stacksize,
- self.applibdir,
+ self.applibdir,
self.fragtype,
self.where,
self.offset,
@@ -119,15 +119,15 @@ class FragmentDescriptor:
self.memberSize,) = struct.unpack("4lhBB4lh", data[4:42])
pname = data[42:self.memberSize]
self.name = pname[1:1+ord(pname[0])]
-
+
def build(self):
data = self.architecture
data = data + struct.pack("4lhBB4l",
- self.updatelevel,
- self.currentVersion,
- self.oldDefVersion,
+ self.updatelevel,
+ self.currentVersion,
+ self.oldDefVersion,
self.stacksize,
- self.applibdir,
+ self.applibdir,
self.fragtype,
self.where,
self.offset,
@@ -141,7 +141,7 @@ class FragmentDescriptor:
data = data + self.name
data = data + '\000' * (self.memberSize - len(data))
return data
-
+
def getfragment(self):
if self.where <> 1:
raise error, "can't read fragment, unsupported location"
@@ -153,7 +153,7 @@ class FragmentDescriptor:
frag = f.read()
f.close()
return frag
-
+
def copydata(self, outfile):
if self.where <> 1:
raise error, "can't read fragment, unsupported location"
@@ -161,17 +161,17 @@ class FragmentDescriptor:
if self.length == 0:
infile.seek(0, 2)
self.length = infile.tell()
-
+
# Position input file and record new offset from output file
infile.seek(self.offset)
-
+
# pad to 16 byte boundaries
offset = outfile.tell()
if offset % 16:
offset = offset + 16 - (offset % 16)
outfile.seek(offset)
self.offset = offset
-
+
l = self.length
while l:
if l > BUFSIZE:
@@ -181,4 +181,3 @@ class FragmentDescriptor:
outfile.write(infile.read(l))
l = 0
infile.close()
-
diff --git a/Lib/plat-mac/findertools.py b/Lib/plat-mac/findertools.py
index b3223bd6ab..54b1bdec02 100644
--- a/Lib/plat-mac/findertools.py
+++ b/Lib/plat-mac/findertools.py
@@ -34,22 +34,22 @@ def _getfinder():
global _finder_talker
if not _finder_talker:
_finder_talker = Finder.Finder()
- _finder_talker.send_flags = ( _finder_talker.send_flags |
+ _finder_talker.send_flags = ( _finder_talker.send_flags |
AppleEvents.kAECanInteract | AppleEvents.kAECanSwitchLayer)
return _finder_talker
-
+
def launch(file):
"""Open a file thru the finder. Specify file by name or fsspec"""
finder = _getfinder()
fss = Carbon.File.FSSpec(file)
return finder.open(fss)
-
+
def Print(file):
"""Print a file thru the finder. Specify file by name or fsspec"""
finder = _getfinder()
fss = Carbon.File.FSSpec(file)
return finder._print(fss)
-
+
def copy(src, dstdir):
"""Copy a file to a folder"""
finder = _getfinder()
@@ -73,17 +73,17 @@ def move(src, dstdir):
src_fss = Carbon.File.FSSpec(src)
dst_fss = Carbon.File.FSSpec(dstdir)
return finder.move(src_fss, to=dst_fss)
-
+
def sleep():
"""Put the mac to sleep"""
finder = _getfinder()
finder.sleep()
-
+
def shutdown():
"""Shut the mac down"""
finder = _getfinder()
finder.shut_down()
-
+
def restart():
"""Restart the mac"""
finder = _getfinder()
@@ -100,16 +100,16 @@ def reveal(file):
fsr = Carbon.File.FSRef(file)
file_alias = fsr.FSNewAliasMinimal()
return finder.reveal(file_alias)
-
+
def select(file):
"""select a file in the finder. Specify file by name, fsref or fsspec."""
finder = _getfinder()
fsr = Carbon.File.FSRef(file)
file_alias = fsr.FSNewAliasMinimal()
return finder.select(file_alias)
-
+
def update(file):
- """Update the display of the specified object(s) to match
+ """Update the display of the specified object(s) to match
their on-disk representation. Specify file by name, fsref or fsspec."""
finder = _getfinder()
fsr = Carbon.File.FSRef(file)
@@ -129,7 +129,7 @@ def comment(object, comment=None):
return _getcomment(object_alias)
else:
return _setcomment(object_alias, comment)
-
+
def _setcomment(object_alias, comment):
finder = _getfinder()
args = {}
@@ -219,11 +219,11 @@ def isactiveprocess(processname):
if n == processname:
return 1
return 0
-
+
def processinfo(processname):
"""Return an object with all process properties as attributes for processname. MacOS9"""
p = _process()
-
+
if processname == "Finder":
p.partition = None
p.used = None
@@ -238,7 +238,7 @@ def processinfo(processname):
p.accepthighlevel = _processproperty(processname, 'revt') #Is the process high-level event aware (accepts open application, open document, print document, and quit)?
p.hasscripting = _processproperty(processname, 'hscr') #Does the process have a scripting terminology, i.e., can it be scripted?
return p
-
+
def _processproperty(processname, property):
"""return the partition size and memory used for processname"""
finder = _getfinder()
@@ -256,7 +256,7 @@ def _processproperty(processname, property):
#---------------------------------------------------
# Mess around with Finder windows.
-
+
def openwindow(object):
"""Open a Finder window for object, Specify object by name or fsspec."""
finder = _getfinder()
@@ -271,7 +271,7 @@ def openwindow(object):
_reply, args, attrs = finder.send(_code, _subcode, args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
-
+
def closewindow(object):
"""Close a Finder window for folder, Specify by path."""
finder = _getfinder()
@@ -295,7 +295,7 @@ def location(object, pos=None):
if not pos:
return _getlocation(object_alias)
return _setlocation(object_alias, pos)
-
+
def _setlocation(object_alias, (x, y)):
"""_setlocation: Set the location of the icon for the object."""
finder = _getfinder()
@@ -309,7 +309,7 @@ def _setlocation(object_alias, (x, y)):
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
return (x,y)
-
+
def _getlocation(object_alias):
"""_getlocation: get the location of the icon for the object."""
finder = _getfinder()
@@ -334,7 +334,7 @@ def label(object, index=None):
if index < 0 or index > 7:
index = 0
return _setlabel(object_alias, index)
-
+
def _getlabel(object_alias):
"""label: Get the label for the object."""
finder = _getfinder()
@@ -378,7 +378,7 @@ def windowview(folder, view=None):
if view == None:
return _getwindowview(folder_alias)
return _setwindowview(folder_alias, view)
-
+
def _setwindowview(folder_alias, view=0):
"""set the windowview"""
attrs = {}
@@ -390,13 +390,13 @@ def _setwindowview(folder_alias, view=0):
else:
_v = aetypes.Type('iimg')
finder = _getfinder()
- aeobj_0 = aetypes.ObjectSpecifier(want = aetypes.Type('cfol'),
+ aeobj_0 = aetypes.ObjectSpecifier(want = aetypes.Type('cfol'),
form = 'alis', seld = folder_alias, fr=None)
- aeobj_1 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'),
+ aeobj_1 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'),
form = 'prop', seld = aetypes.Type('cwnd'), fr=aeobj_0)
- aeobj_2 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'),
+ aeobj_2 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'),
form = 'prop', seld = aetypes.Type('pvew'), fr=aeobj_1)
- aeobj_3 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'),
+ aeobj_3 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'),
form = 'prop', seld = _v, fr=None)
_code = 'core'
_subcode = 'setd'
@@ -437,7 +437,7 @@ def windowsize(folder, size=None):
if not size:
return _getwindowsize(folder_alias)
return _setwindowsize(folder_alias, size)
-
+
def _setwindowsize(folder_alias, (w, h)):
"""Set the size of a Finder window for folder to (w, h)"""
finder = _getfinder()
@@ -448,9 +448,9 @@ def _setwindowsize(folder_alias, (w, h)):
aevar00 = [w, h]
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
form="alis", seld=folder_alias, fr=None)
- aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
+ aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0)
- aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
+ aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('ptsz'), fr=aeobj_1)
args['----'] = aeobj_2
args["data"] = aevar00
@@ -458,17 +458,17 @@ def _setwindowsize(folder_alias, (w, h)):
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
return (w, h)
-
+
def _getwindowsize(folder_alias):
"""Set the size of a Finder window for folder to (w, h)"""
finder = _getfinder()
args = {}
attrs = {}
- aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
+ aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
form="alis", seld=folder_alias, fr=None)
- aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
+ aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0)
- aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
+ aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('posn'), fr=aeobj_1)
args['----'] = aeobj_2
_reply, args, attrs = finder.send('core', 'getd', args, attrs)
@@ -488,17 +488,17 @@ def windowposition(folder, pos=None):
# pos might be a QDPoint object as returned by _getwindowposition
pos = (pos.h, pos.v)
return _setwindowposition(folder_alias, pos)
-
+
def _setwindowposition(folder_alias, (x, y)):
"""Set the size of a Finder window for folder to (w, h)."""
finder = _getfinder()
args = {}
attrs = {}
- aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
+ aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
form="alis", seld=folder_alias, fr=None)
- aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
+ aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0)
- aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
+ aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('posn'), fr=aeobj_1)
args['----'] = aeobj_2
args["data"] = [x, y]
@@ -513,11 +513,11 @@ def _getwindowposition(folder_alias):
finder = _getfinder()
args = {}
attrs = {}
- aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
+ aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
form="alis", seld=folder_alias, fr=None)
- aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
+ aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0)
- aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
+ aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('ptsz'), fr=aeobj_1)
args['----'] = aeobj_2
_reply, args, attrs = finder.send('core', 'getd', args, attrs)
@@ -536,15 +536,15 @@ def icon(object, icondata=None):
if icondata == None:
return _geticon(object_alias)
return _seticon(object_alias, icondata)
-
+
def _geticon(object_alias):
"""get the icondata for object. Binary data of some sort."""
finder = _getfinder()
args = {}
attrs = {}
- aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'),
+ aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'),
form="alis", seld=object_alias, fr=None)
- aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
+ aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('iimg'), fr=aeobj_00)
args['----'] = aeobj_01
_reply, args, attrs = finder.send("core", "getd", args, attrs)
@@ -558,9 +558,9 @@ def _seticon(object_alias, icondata):
finder = _getfinder()
args = {}
attrs = {}
- aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'),
+ aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'),
form="alis", seld=object_alias, fr=None)
- aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
+ aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('iimg'), fr=aeobj_00)
args['----'] = aeobj_01
args["data"] = icondata
@@ -573,7 +573,7 @@ def _seticon(object_alias, icondata):
#---------------------------------------------------
# Volumes and servers.
-
+
def mountvolume(volume, server=None, username=None, password=None):
"""mount a volume, local or on a server on AppleTalk.
Note: mounting a ASIP server requires a different operation.
@@ -598,7 +598,7 @@ def mountvolume(volume, server=None, username=None, password=None):
def unmountvolume(volume):
"""unmount a volume that's on the desktop"""
putaway(volume)
-
+
def putaway(object):
"""puth the object away, whereever it came from."""
finder = _getfinder()
@@ -675,7 +675,7 @@ def filesharing():
if args['----'] == 1:
status = 0
return status
-
+
def movetotrash(path):
"""move the object to the trash"""
fss = Carbon.File.FSSpec(path)
@@ -766,7 +766,7 @@ def _test2():
# set the soundvolume in a simple way
print '\tSystem beep volume'
for i in range(0, 7):
- volumelevel(i)
+ volumelevel(i)
MacOS.SysBeep()
# Finder's windows, file location, file attributes
@@ -805,7 +805,7 @@ def _test2():
print '\t', comment(f) # print the Finder comment this file has
s = 'This is a comment no one reads!'
comment(f, s) # set the Finder comment
-
+
def _test3():
print 'MacOS9 or better specific functions'
# processes
@@ -813,7 +813,7 @@ def _test3():
print 'Return a list of current active processes:'
for p in pr:
print '\t', p
-
+
# get attributes of the first process in the list
print 'Attributes of the first process in the list:'
pinfo = processinfo(pr[0][0])
@@ -829,4 +829,3 @@ if __name__ == '__main__':
_test()
_test2()
_test3()
-
diff --git a/Lib/plat-mac/gensuitemodule.py b/Lib/plat-mac/gensuitemodule.py
index ab3c070c81..87132c57fc 100644
--- a/Lib/plat-mac/gensuitemodule.py
+++ b/Lib/plat-mac/gensuitemodule.py
@@ -31,7 +31,7 @@ DEFAULT_USER_PACKAGEFOLDER=distutils.sysconfig.get_python_lib()
def usage():
sys.stderr.write("Usage: %s [opts] application-or-resource-file\n" % sys.argv[0])
sys.stderr.write("""Options:
---output pkgdir Pathname of the output package (short: -o)
+--output pkgdir Pathname of the output package (short: -o)
--resource Parse resource file in stead of launching application (-r)
--base package Use another base package in stead of default StdSuites (-b)
--edit old=new Edit suite names, use empty new to skip a suite (-e)
@@ -49,7 +49,7 @@ def main():
opts, args = getopt.getopt(sys.argv[1:], SHORTOPTS, LONGOPTS)
except getopt.GetoptError:
usage()
-
+
process_func = processfile
basepkgname = 'StdSuites'
output = None
@@ -57,7 +57,7 @@ def main():
creatorsignature = None
dump = None
verbose = None
-
+
for o, a in opts:
if o in ('-r', '--resource'):
process_func = processfile_fromresource
@@ -79,19 +79,19 @@ def main():
dump = sys.stdout
if o in ('-v', '--verbose'):
verbose = sys.stderr
-
-
+
+
if output and len(args) > 1:
sys.stderr.write("%s: cannot specify --output with multiple inputs\n" % sys.argv[0])
sys.exit(1)
-
+
for filename in args:
- process_func(filename, output=output, basepkgname=basepkgname,
+ process_func(filename, output=output, basepkgname=basepkgname,
edit_modnames=edit_modnames, creatorsignature=creatorsignature,
dump=dump, verbose=verbose)
else:
main_interactive()
-
+
def main_interactive(interact=0, basepkgname='StdSuites'):
if interact:
# Ask for save-filename for each module
@@ -119,7 +119,7 @@ def main_interactive(interact=0, basepkgname='StdSuites'):
print "Retry, manually parsing resources"
processfile_fromresource(filename, edit_modnames=edit_modnames,
basepkgname=basepkgname, verbose=sys.stderr)
-
+
def is_scriptable(application):
"""Return true if the application is scriptable"""
if os.path.isdir(application):
@@ -141,7 +141,7 @@ def is_scriptable(application):
UseResFile(currf)
return n_terminology > 0
-def processfile_fromresource(fullname, output=None, basepkgname=None,
+def processfile_fromresource(fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, dump=None, verbose=None):
"""Process all resources in a single file"""
if not is_scriptable(fullname) and verbose:
@@ -159,7 +159,7 @@ def processfile_fromresource(fullname, output=None, basepkgname=None,
for i in range(Count1Resources('aeut')):
res = Get1IndResource('aeut', 1+i)
resources.append(res)
- if verbose:
+ if verbose:
print >>verbose, "\nLISTING aete+aeut RESOURCES IN", repr(fullname)
aetelist = []
for res in resources:
@@ -176,11 +176,11 @@ def processfile_fromresource(fullname, output=None, basepkgname=None,
UseResFile(cur)
if dump:
dumpaetelist(aetelist, dump)
- compileaetelist(aetelist, fullname, output=output,
+ compileaetelist(aetelist, fullname, output=output,
basepkgname=basepkgname, edit_modnames=edit_modnames,
creatorsignature=creatorsignature, verbose=verbose)
-def processfile(fullname, output=None, basepkgname=None,
+def processfile(fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, dump=None,
verbose=None):
"""Ask an application for its terminology and process that"""
@@ -204,7 +204,7 @@ def processfile(fullname, output=None, basepkgname=None,
if verbose:
print >>verbose, "Launched", fullname
raw = aetools.unpack(aedescobj)
- if not raw:
+ if not raw:
if verbose:
print >>verbose, 'Unpack returned empty value:', raw
return
@@ -218,9 +218,9 @@ def processfile(fullname, output=None, basepkgname=None,
dumpaetelist([aete], dump)
return
compileaete(aete, None, fullname, output=output, basepkgname=basepkgname,
- creatorsignature=creatorsignature, edit_modnames=edit_modnames,
+ creatorsignature=creatorsignature, edit_modnames=edit_modnames,
verbose=verbose)
-
+
def getappterminology(fullname, verbose=None):
"""Get application terminology by sending an AppleEvent"""
# First check that we actually can send AppleEvents
@@ -251,19 +251,19 @@ def getappterminology(fullname, verbose=None):
#reply2 = talker.send("ascr", "gdut")
# Now pick the bits out of the return that we need.
return reply[1]['----'], cr
-
-def compileaetelist(aetelist, fullname, output=None, basepkgname=None,
+
+def compileaetelist(aetelist, fullname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, verbose=None):
for aete, resinfo in aetelist:
- compileaete(aete, resinfo, fullname, output=output,
+ compileaete(aete, resinfo, fullname, output=output,
basepkgname=basepkgname, edit_modnames=edit_modnames,
creatorsignature=creatorsignature, verbose=verbose)
def dumpaetelist(aetelist, output):
import pprint
pprint.pprint(aetelist, output)
-
+
def decode(data, verbose=None):
"""Decode a resource into a python data structure"""
f = StringIO.StringIO(data)
@@ -427,7 +427,7 @@ getaete = [
(getlist, "suites", getsuite)
]
-def compileaete(aete, resinfo, fname, output=None, basepkgname=None,
+def compileaete(aete, resinfo, fname, output=None, basepkgname=None,
edit_modnames=None, creatorsignature=None, verbose=None):
"""Generate code for a full aete resource. fname passed for doc purposes"""
[version, language, script, suites] = aete
@@ -500,7 +500,7 @@ def compileaete(aete, resinfo, fname, output=None, basepkgname=None,
fp.write("}\n\n")
for code, modname in suitelist:
fp.write("from %s import *\n"%modname)
-
+
# Generate property dicts and element dicts for all types declared in this module
fp.write("\ndef getbaseclasses(v):\n")
fp.write(" if not getattr(v, '_propdict', None):\n")
@@ -534,7 +534,7 @@ def compileaete(aete, resinfo, fname, output=None, basepkgname=None,
application_class = v
fp.write("}\n")
-
+
if suitelist:
fp.write("\n\nclass %s(%s_Events"%(packagename, suitelist[0][1]))
for code, modname in suitelist[1:]:
@@ -554,22 +554,22 @@ class SuiteCompiler:
self.edit_modnames = edit_modnames
self.output = output
self.verbose = verbose
-
+
# Set by precompilesuite
self.pathname = None
self.modname = None
-
+
# Set by compilesuite
self.fp = None
self.basemodule = None
self.enumsneeded = {}
-
+
def precompilesuite(self):
"""Parse a single suite without generating the output. This step is needed
so we can resolve recursive references by suites to enums/comps/etc declared
in other suites"""
[name, desc, code, level, version, events, classes, comps, enums] = self.suite
-
+
modname = identify(name)
if len(modname) > 28:
modname = modname[:27]
@@ -586,9 +586,9 @@ class SuiteCompiler:
self.pathname = None
if not self.pathname:
return None, None, None
-
+
self.modname = os.path.splitext(os.path.split(self.pathname)[1])[0]
-
+
if self.basepackage and self.basepackage._code_to_module.has_key(code):
# We are an extension of a baseclass (usually an application extending
# Standard_Suite or so). Import everything from our base module
@@ -596,11 +596,11 @@ class SuiteCompiler:
else:
# We are not an extension.
basemodule = None
-
+
self.enumsneeded = {}
for event in events:
self.findenumsinevent(event)
-
+
objc = ObjectCompiler(None, self.modname, basemodule, interact=(self.edit_modnames is None),
verbose=self.verbose)
for cls in classes:
@@ -611,16 +611,16 @@ class SuiteCompiler:
objc.compilecomparison(comp)
for enum in enums:
objc.compileenumeration(enum)
-
+
for enum in self.enumsneeded.keys():
objc.checkforenum(enum)
-
+
objc.dumpindex()
-
+
precompinfo = objc.getprecompinfo(self.modname)
-
+
return code, self.modname, precompinfo
-
+
def compilesuite(self, major, minor, language, script, fname, precompinfo):
"""Generate code for a single suite"""
[name, desc, code, level, version, events, classes, comps, enums] = self.suite
@@ -637,22 +637,22 @@ class SuiteCompiler:
# This is a synonym, the other one is better
return 1
return 0
-
+
events.sort()
classes.sort(class_sorter)
comps.sort()
enums.sort()
-
+
self.fp = fp = open(self.pathname, 'w')
MacOS.SetCreatorAndType(self.pathname, 'Pyth', 'TEXT')
-
+
fp.write('"""Suite %s: %s\n' % (ascii(name), ascii(desc)))
fp.write("Level %d, version %d\n\n" % (level, version))
fp.write("Generated from %s\n"%ascii(fname))
fp.write("AETE/AEUT resource version %d/%d, language %d, script %d\n" % \
(major, minor, language, script))
fp.write('"""\n\n')
-
+
fp.write('import aetools\n')
fp.write('import MacOS\n\n')
fp.write("_code = %r\n\n"% (code,))
@@ -670,14 +670,14 @@ class SuiteCompiler:
basemodule = None
self.basemodule = basemodule
self.compileclassheader()
-
+
self.enumsneeded = {}
if events:
for event in events:
self.compileevent(event)
else:
fp.write(" pass\n\n")
-
+
objc = ObjectCompiler(fp, self.modname, basemodule, precompinfo, interact=(self.edit_modnames is None),
verbose=self.verbose)
for cls in classes:
@@ -688,12 +688,12 @@ class SuiteCompiler:
objc.compilecomparison(comp)
for enum in enums:
objc.compileenumeration(enum)
-
+
for enum in self.enumsneeded.keys():
objc.checkforenum(enum)
-
+
objc.dumpindex()
-
+
def compileclassheader(self):
"""Generate class boilerplate"""
classname = '%s_Events'%self.modname
@@ -703,7 +703,7 @@ class SuiteCompiler:
self.fp.write("class %s(%s):\n\n"%(classname, baseclassname))
else:
self.fp.write("class %s:\n\n"%classname)
-
+
def compileevent(self, event):
"""Generate code for a single event"""
[name, desc, code, subcode, returns, accepts, arguments] = event
@@ -717,13 +717,13 @@ class SuiteCompiler:
for a in arguments:
fp.write(" %r : %r,\n"%(identify(a[0]), a[1]))
fp.write(" }\n\n")
-
+
#
# Generate function header
#
has_arg = (not is_null(accepts))
opt_arg = (has_arg and is_optional(accepts))
-
+
fp.write(" def %s(self, "%funcname)
if has_arg:
if not opt_arg:
@@ -803,7 +803,7 @@ class SuiteCompiler:
fp.write(" # XXXX Should do enum remapping here...\n")
fp.write(" return _arguments['----']\n")
fp.write("\n")
-
+
def findenumsinevent(self, event):
"""Find all enums for a single event"""
[name, desc, code, subcode, returns, accepts, arguments] = event
@@ -812,7 +812,7 @@ class SuiteCompiler:
ename = a[2][0]
if ename <> '****':
self.enumsneeded[ename] = 1
-
+
#
# This class stores the code<->name translations for a single module. It is used
# to keep the information while we're compiling the module, but we also keep these objects
@@ -821,7 +821,7 @@ class SuiteCompiler:
# hand.
#
class CodeNameMapper:
-
+
def __init__(self, interact=1, verbose=None):
self.code2name = {
"property" : {},
@@ -839,21 +839,21 @@ class CodeNameMapper:
self.star_imported = 0
self.can_interact = interact
self.verbose = verbose
-
+
def addnamecode(self, type, name, code):
self.name2code[type][name] = code
if not self.code2name[type].has_key(code):
self.code2name[type][code] = name
-
+
def hasname(self, name):
for dict in self.name2code.values():
if dict.has_key(name):
return True
return False
-
+
def hascode(self, type, code):
return self.code2name[type].has_key(code)
-
+
def findcodename(self, type, code):
if not self.hascode(type, code):
return None, None, None
@@ -863,10 +863,10 @@ class CodeNameMapper:
else:
qualname = name
return name, qualname, self.modulename
-
+
def getall(self, type):
return self.code2name[type].items()
-
+
def addmodule(self, module, name, star_imported):
self.modulename = name
self.star_imported = star_imported
@@ -878,14 +878,14 @@ class CodeNameMapper:
self.addnamecode('enum', '_Enum_'+identify(code), code)
for code, name in module._compdeclarations.items():
self.addnamecode('comparison', name, code)
-
+
def prepareforexport(self, name=None):
if not self.modulename:
self.modulename = name
return self
-
+
class ObjectCompiler:
- def __init__(self, fp, modname, basesuite, othernamemappers=None, interact=1,
+ def __init__(self, fp, modname, basesuite, othernamemappers=None, interact=1,
verbose=None):
self.fp = fp
self.verbose = verbose
@@ -901,7 +901,7 @@ class ObjectCompiler:
basemapper = CodeNameMapper(self.can_interact, self.verbose)
basemapper.addmodule(basesuite, '', 1)
self.namemappers.append(basemapper)
-
+
def getprecompinfo(self, modname):
list = []
for mapper in self.namemappers:
@@ -909,7 +909,7 @@ class ObjectCompiler:
if emapper:
list.append(emapper)
return list
-
+
def findcodename(self, type, code):
while 1:
# First try: check whether we already know about this code.
@@ -935,7 +935,7 @@ class ObjectCompiler:
mapper = CodeNameMapper(self.can_interact, self.verbose)
mapper.addmodule(m, m.__name__, 0)
self.namemappers.append(mapper)
-
+
def hasname(self, name):
for mapper in self.othernamemappers:
if mapper.hasname(name) and mapper.modulename != self.modulename:
@@ -943,7 +943,7 @@ class ObjectCompiler:
print >>self.verbose, "Duplicate Python identifier:", name, self.modulename, mapper.modulename
return True
return False
-
+
def askdefinitionmodule(self, type, code):
if not self.can_interact:
if self.verbose:
@@ -958,7 +958,7 @@ class ObjectCompiler:
m = __import__(modname)
self.fp.write("import %s\n"%modname)
return m
-
+
def compileclass(self, cls):
[name, code, desc, properties, elements] = cls
pname = identify(name)
@@ -980,7 +980,7 @@ class ObjectCompiler:
elements.sort()
for elem in elements:
self.compileelement(elem)
-
+
def compileproperty(self, prop, is_application_class=False):
[name, code, what] = prop
if code == 'c@#!':
@@ -1003,7 +1003,7 @@ class ObjectCompiler:
self.namemappers[0].addnamecode('property', pname, code)
if is_application_class and self.fp:
self.fp.write("%s = _Prop_%s()\n" % (pname, pname))
-
+
def compileelement(self, elem):
[code, keyform] = elem
if self.fp:
@@ -1056,10 +1056,10 @@ class ObjectCompiler:
self.fp.write("# XXXX %s element %r not found!!\n"%(cname, ecode))
else:
elist.append((name, ename))
-
+
plist.sort()
elist.sort()
-
+
if self.fp:
self.fp.write("%s._privpropdict = {\n"%cname)
for n in plist:
@@ -1069,7 +1069,7 @@ class ObjectCompiler:
for n, fulln in elist:
self.fp.write(" '%s' : %s,\n"%(n, fulln))
self.fp.write("}\n")
-
+
def compilecomparison(self, comp):
[name, code, comment] = comp
iname = identify(name)
@@ -1077,7 +1077,7 @@ class ObjectCompiler:
if self.fp:
self.fp.write("class %s(aetools.NComparison):\n" % iname)
self.fp.write(' """%s - %s """\n' % (ascii(name), ascii(comment)))
-
+
def compileenumeration(self, enum):
[code, items] = enum
name = "_Enum_%s" % identify(code)
@@ -1088,11 +1088,11 @@ class ObjectCompiler:
self.fp.write("}\n\n")
self.namemappers[0].addnamecode('enum', name, code)
return code
-
+
def compileenumerator(self, item):
[name, code, desc] = item
self.fp.write(" %r : %r,\t# %s\n" % (identify(name), code, ascii(desc)))
-
+
def checkforenum(self, enum):
"""This enum code is used by an event. Make sure it's available"""
name, fullname, module = self.findcodename('enum', enum)
@@ -1103,33 +1103,33 @@ class ObjectCompiler:
if module:
if self.fp:
self.fp.write("from %s import %s\n"%(module, name))
-
+
def dumpindex(self):
if not self.fp:
return
self.fp.write("\n#\n# Indices of types declared in this module\n#\n")
-
+
self.fp.write("_classdeclarations = {\n")
classlist = self.namemappers[0].getall('class')
classlist.sort()
for k, v in classlist:
self.fp.write(" %r : %s,\n" % (k, v))
self.fp.write("}\n")
-
+
self.fp.write("\n_propdeclarations = {\n")
proplist = self.namemappers[0].getall('property')
proplist.sort()
for k, v in proplist:
self.fp.write(" %r : _Prop_%s,\n" % (k, v))
self.fp.write("}\n")
-
+
self.fp.write("\n_compdeclarations = {\n")
complist = self.namemappers[0].getall('comparison')
complist.sort()
for k, v in complist:
self.fp.write(" %r : %s,\n" % (k, v))
self.fp.write("}\n")
-
+
self.fp.write("\n_enumdeclarations = {\n")
enumlist = self.namemappers[0].getall('enum')
enumlist.sort()
@@ -1140,16 +1140,16 @@ class ObjectCompiler:
def compiledata(data):
[type, description, flags] = data
return "%r -- %r %s" % (type, description, compiledataflags(flags))
-
+
def is_null(data):
return data[0] == 'null'
-
+
def is_optional(data):
return (data[2] & 0x8000)
-
+
def is_enum(data):
return (data[2] & 0x2000)
-
+
def getdatadoc(data):
[type, descr, flags] = data
if descr:
@@ -1170,7 +1170,7 @@ def compiledataflags(flags):
else:
bits.append(repr(i))
return '[%s]' % string.join(bits)
-
+
def ascii(str):
"""Return a string with all non-ascii characters hex-encoded"""
if type(str) != type(''):
@@ -1182,7 +1182,7 @@ def ascii(str):
else:
rv = rv + '\\' + 'x%02.2x' % ord(c)
return rv
-
+
def identify(str):
"""Turn any string into an identifier:
- replace space by _
diff --git a/Lib/plat-mac/ic.py b/Lib/plat-mac/ic.py
index 3236805fce..6575336af1 100644
--- a/Lib/plat-mac/ic.py
+++ b/Lib/plat-mac/ic.py
@@ -38,7 +38,7 @@ class ICOpaqueData:
return "ICOpaqueData(%r)"%(self.data,)
_ICOpaqueDataType=type(ICOpaqueData(''))
-
+
def _decode_default(data, key):
if len(data) == 0:
return data
@@ -46,8 +46,8 @@ def _decode_default(data, key):
# Assume Pstring
return data[1:]
return ICOpaqueData(data)
-
-
+
+
def _decode_multistr(data, key):
numstr = ord(data[0]) << 8 | ord(data[1])
rv = []
@@ -58,54 +58,54 @@ def _decode_multistr(data, key):
rv.append(str)
ptr = ptr + strlen + 1
return rv
-
+
def _decode_fontrecord(data, key):
size = ord(data[0]) << 8 | ord(data[1])
face = ord(data[2])
namelen = ord(data[4])
return size, face, data[5:5+namelen]
-
+
def _decode_boolean(data, key):
return ord(data[0])
-
+
def _decode_text(data, key):
return data
-
+
def _decode_charset(data, key):
return data[:256], data[256:]
-
+
def _decode_appspec(data, key):
namelen = ord(data[4])
return data[0:4], data[5:5+namelen]
def _code_default(data, key):
return chr(len(data)) + data
-
+
def _code_multistr(data, key):
numstr = len(data)
rv = chr((numstr>>8) & 0xff) + chr(numstr & 0xff)
for i in data:
rv = rv + _code_default(i)
return rv
-
+
def _code_fontrecord(data, key):
size, face, name = data
return chr((size>>8) & 0xff) + chr(size & 0xff) + chr(face & 0xff) + \
chr(0) + _code_default(name)
-
+
def _code_boolean(data, key):
print 'XXXX boolean:', repr(data)
return chr(data)
-
+
def _code_text(data, key):
return data
-
+
def _code_charset(data, key):
return data[0] + data[1]
-
+
def _code_appspec(data, key):
return data[0] + _code_default(data[1])
-
+
_decoder_table = {
"ArchieAll" : (_decode_multistr , _code_multistr),
"UMichAll" : (_decode_multistr , _code_multistr),
@@ -118,7 +118,7 @@ _decoder_table = {
"Plan" : (_decode_text , _code_text),
"MailHeaders" : (_decode_text , _code_text),
"NewsHeaders" : (_decode_text , _code_text),
-# "Mapping"
+# "Mapping"
"CharacterSet" : (_decode_charset , _code_charset),
"Helper\245" : (_decode_appspec , _code_appspec),
# "Services" : (_decode_services, ????),
@@ -156,7 +156,7 @@ def _code(data, key):
else:
coder = _code_default
return coder(data, key)
-
+
class IC:
def __init__(self, signature='Pyth', ic=None):
if ic:
@@ -166,7 +166,7 @@ class IC:
if hasattr(self.ic, 'ICFindConfigFile'):
self.ic.ICFindConfigFile()
self.h = Res.Resource('')
-
+
def keys(self):
rv = []
self.ic.ICBegin(icReadOnlyPerm)
@@ -175,32 +175,32 @@ class IC:
rv.append(self.ic.ICGetIndPref(i+1))
self.ic.ICEnd()
return rv
-
+
def has_key(self, key):
return self.__contains__(key)
-
+
def __contains__(self, key):
try:
dummy = self.ic.ICFindPrefHandle(key, self.h)
except icglue.error:
return 0
return 1
-
+
def __getitem__(self, key):
attr = self.ic.ICFindPrefHandle(key, self.h)
return _decode(self.h.data, key)
-
+
def __setitem__(self, key, value):
value = _code(value, key)
self.ic.ICSetPref(key, ICattr_no_change, value)
-
+
def launchurl(self, url, hint=""):
# Work around a bug in ICLaunchURL: file:/foo does
# not work but file:///foo does.
if url[:6] == 'file:/' and url[6] != '/':
url = 'file:///' + url[6:]
self.ic.ICLaunchURL(hint, url, 0, len(url))
-
+
def parseurl(self, data, start=None, end=None, hint=""):
if start == None:
selStart = 0
@@ -211,21 +211,21 @@ class IC:
selEnd = end
selStart, selEnd = self.ic.ICParseURL(hint, data, selStart, selEnd, self.h)
return self.h.data, selStart, selEnd
-
+
def mapfile(self, file):
if type(file) != type(''):
file = file.as_tuple()[2]
return self.ic.ICMapFilename(file)
-
+
def maptypecreator(self, type, creator, filename=""):
return self.ic.ICMapTypeCreator(type, creator, filename)
-
+
def settypecreator(self, file):
file = Carbon.File.pathname(file)
record = self.mapfile(os.path.split(file)[1])
MacOS.SetCreatorAndType(file, record[2], record[1])
macostools.touched(fss)
-
+
# Convenience routines
_dft_ic = None
@@ -233,27 +233,27 @@ def launchurl(url, hint=""):
global _dft_ic
if _dft_ic == None: _dft_ic = IC()
return _dft_ic.launchurl(url, hint)
-
+
def parseurl(data, start=None, end=None, hint=""):
global _dft_ic
if _dft_ic == None: _dft_ic = IC()
return _dft_ic.parseurl(data, start, end, hint)
-
+
def mapfile(filename):
global _dft_ic
if _dft_ic == None: _dft_ic = IC()
return _dft_ic.mapfile(filename)
-
+
def maptypecreator(type, creator, filename=""):
global _dft_ic
if _dft_ic == None: _dft_ic = IC()
return _dft_ic.maptypecreator(type, creator, filename)
-
+
def settypecreator(file):
global _dft_ic
if _dft_ic == None: _dft_ic = IC()
return _dft_ic.settypecreator(file)
-
+
def _test():
ic = IC()
for k in ic.keys():
@@ -263,7 +263,6 @@ def _test():
v = '????'
print k, '\t', v
sys.exit(1)
-
+
if __name__ == '__main__':
_test()
-
diff --git a/Lib/plat-mac/icopen.py b/Lib/plat-mac/icopen.py
index 99e866ecf5..eea6083797 100644
--- a/Lib/plat-mac/icopen.py
+++ b/Lib/plat-mac/icopen.py
@@ -42,18 +42,18 @@ import __builtin__
_builtin_open = globals().get('_builtin_open', __builtin__.open)
def _open_with_typer(*args):
- file = _builtin_open(*args)
- filename = args[0]
- mode = 'r'
- if args[1:]:
- mode = args[1]
- if mode[0] == 'w':
- from ic import error, settypecreator
- try:
- settypecreator(filename)
- except error:
- pass
- return file
+ file = _builtin_open(*args)
+ filename = args[0]
+ mode = 'r'
+ if args[1:]:
+ mode = args[1]
+ if mode[0] == 'w':
+ from ic import error, settypecreator
+ try:
+ settypecreator(filename)
+ except error:
+ pass
+ return file
__builtin__.open = _open_with_typer
diff --git a/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py b/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py
index 033703c3a9..0fd562b95d 100644
--- a/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/CodeWarrior/CodeWarrior_suite.py
@@ -580,44 +580,44 @@ text_document._privelemdict = {
'text' : Standard_Suite.text,
}
_Enum_DKND = {
- 'project' : 'PRJD', # a project document
- 'editor_document' : 'EDIT', # an editor document
- 'message' : 'MSSG', # a message document
- 'file_compare' : 'COMP', # a file compare document
- 'catalog_document' : 'CTLG', # a browser catalog
- 'class_browser' : 'BROW', # a class browser document
- 'single_class_browser' : '1BRW', # a single class browser document
- 'symbol_browser' : 'SYMB', # a symbol browser document
- 'class_hierarchy' : 'HIER', # a class hierarchy document
- 'single_class_hierarchy' : '1HIR', # a single class hierarchy document
- 'project_inspector' : 'INSP', # a project inspector
- 'ToolServer_worksheet' : 'TOOL', # the ToolServer worksheet
- 'build_progress_document' : 'PRGS', # the build progress window
+ 'project' : 'PRJD', # a project document
+ 'editor_document' : 'EDIT', # an editor document
+ 'message' : 'MSSG', # a message document
+ 'file_compare' : 'COMP', # a file compare document
+ 'catalog_document' : 'CTLG', # a browser catalog
+ 'class_browser' : 'BROW', # a class browser document
+ 'single_class_browser' : '1BRW', # a single class browser document
+ 'symbol_browser' : 'SYMB', # a symbol browser document
+ 'class_hierarchy' : 'HIER', # a class hierarchy document
+ 'single_class_hierarchy' : '1HIR', # a single class hierarchy document
+ 'project_inspector' : 'INSP', # a project inspector
+ 'ToolServer_worksheet' : 'TOOL', # the ToolServer worksheet
+ 'build_progress_document' : 'PRGS', # the build progress window
}
_Enum_FTYP = {
- 'library_file' : 'LIBF', # a library file
- 'project_file' : 'PRJF', # a project file
- 'resource_file' : 'RESF', # a resource file
- 'text_file' : 'TXTF', # a text file
- 'unknown_file' : 'UNKN', # unknown file type
+ 'library_file' : 'LIBF', # a library file
+ 'project_file' : 'PRJF', # a project file
+ 'resource_file' : 'RESF', # a resource file
+ 'text_file' : 'TXTF', # a text file
+ 'unknown_file' : 'UNKN', # unknown file type
}
_Enum_Inte = {
- 'never_interact' : 'eNvr', # never allow user interactions
- 'interact_with_self' : 'eInS', # allow user interaction only when an AppleEvent is sent from within CodeWarrior
- 'interact_with_local' : 'eInL', # allow user interaction when AppleEvents are sent from applications on the same machine (default)
- 'interact_with_all' : 'eInA', # allow user interaction from both local and remote AppleEvents
+ 'never_interact' : 'eNvr', # never allow user interactions
+ 'interact_with_self' : 'eInS', # allow user interaction only when an AppleEvent is sent from within CodeWarrior
+ 'interact_with_local' : 'eInL', # allow user interaction when AppleEvents are sent from applications on the same machine (default)
+ 'interact_with_all' : 'eInA', # allow user interaction from both local and remote AppleEvents
}
_Enum_PERM = {
- 'read_write' : 'RdWr', # the file is open with read/write permission
- 'read_only' : 'Read', # the file is open with read/only permission
- 'checked_out_read_write' : 'CkRW', # the file is checked out with read/write permission
- 'checked_out_read_only' : 'CkRO', # the file is checked out with read/only permission
- 'checked_out_read_modify' : 'CkRM', # the file is checked out with read/modify permission
- 'locked' : 'Lock', # the file is locked on disk
- 'none' : 'LNNO', # the file is new
+ 'read_write' : 'RdWr', # the file is open with read/write permission
+ 'read_only' : 'Read', # the file is open with read/only permission
+ 'checked_out_read_write' : 'CkRW', # the file is checked out with read/write permission
+ 'checked_out_read_only' : 'CkRO', # the file is checked out with read/only permission
+ 'checked_out_read_modify' : 'CkRM', # the file is checked out with read/modify permission
+ 'locked' : 'Lock', # the file is locked on disk
+ 'none' : 'LNNO', # the file is new
}
diff --git a/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py b/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py
index 3beb0895f2..909cdc0fea 100644
--- a/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py
@@ -2025,110 +2025,110 @@ Font._privpropdict = {
Font._privelemdict = {
}
_Enum_Acce = {
- 'public' : 'Publ', #
- 'protected' : 'Prot', #
- 'private' : 'Priv', #
+ 'public' : 'Publ', #
+ 'protected' : 'Prot', #
+ 'private' : 'Priv', #
}
_Enum_BXbr = {
- 'Always_Build' : 'BXb1', # Always build the target before running.
- 'Ask_Build' : 'BXb2', # Ask before building the target when running.
- 'Never_Build' : 'BXb3', # Never before building the target before running.
+ 'Always_Build' : 'BXb1', # Always build the target before running.
+ 'Ask_Build' : 'BXb2', # Ask before building the target when running.
+ 'Never_Build' : 'BXb3', # Never before building the target before running.
}
_Enum_DbSA = {
- 'No_Action' : 'DSA1', # Don\xd5t do anything to non-debug windows
- 'Hide_Windows' : 'DSA2', # Hide non-debugging windows
- 'Collapse_Windows' : 'DSA3', # Collapse non-debugging windows
- 'Close_Windows' : 'DSA4', # Close non-debugging windows
+ 'No_Action' : 'DSA1', # Don\xd5t do anything to non-debug windows
+ 'Hide_Windows' : 'DSA2', # Hide non-debugging windows
+ 'Collapse_Windows' : 'DSA3', # Collapse non-debugging windows
+ 'Close_Windows' : 'DSA4', # Close non-debugging windows
}
_Enum_DgBL = {
- 'Always' : 'DgB0', # Always build before debugging.
- 'Never' : 'DgB1', # Never build before debugging.
- 'Ask' : 'DgB2', # Ask about building before debugging.
+ 'Always' : 'DgB0', # Always build before debugging.
+ 'Never' : 'DgB1', # Never build before debugging.
+ 'Ask' : 'DgB2', # Ask about building before debugging.
}
_Enum_ErrT = {
- 'information' : 'ErIn', #
- 'compiler_warning' : 'ErCW', #
- 'compiler_error' : 'ErCE', #
- 'definition' : 'ErDf', #
- 'linker_warning' : 'ErLW', #
- 'linker_error' : 'ErLE', #
- 'find_result' : 'ErFn', #
- 'generic_error' : 'ErGn', #
+ 'information' : 'ErIn', #
+ 'compiler_warning' : 'ErCW', #
+ 'compiler_error' : 'ErCE', #
+ 'definition' : 'ErDf', #
+ 'linker_warning' : 'ErLW', #
+ 'linker_error' : 'ErLE', #
+ 'find_result' : 'ErFn', #
+ 'generic_error' : 'ErGn', #
}
_Enum_Inte = {
- 'never_interact' : 'eNvr', # Never allow user interactions
- 'interact_with_self' : 'eInS', # Allow user interaction only when an AppleEvent is sent from within CodeWarrior
- 'interact_with_local' : 'eInL', # Allow user interaction when AppleEvents are sent from applications on the same machine (default)
- 'interact_with_all' : 'eInA', # Allow user interaction from both local and remote AppleEvents
+ 'never_interact' : 'eNvr', # Never allow user interactions
+ 'interact_with_self' : 'eInS', # Allow user interaction only when an AppleEvent is sent from within CodeWarrior
+ 'interact_with_local' : 'eInL', # Allow user interaction when AppleEvents are sent from applications on the same machine (default)
+ 'interact_with_all' : 'eInA', # Allow user interaction from both local and remote AppleEvents
}
_Enum_Lang = {
- 'C' : 'LC ', #
- 'C_2b__2b_' : 'LC++', #
- 'Pascal' : 'LP ', #
- 'Object_Pascal' : 'LP++', #
- 'Java' : 'LJav', #
- 'Assembler' : 'LAsm', #
- 'Unknown' : 'L? ', #
+ 'C' : 'LC ', #
+ 'C_2b__2b_' : 'LC++', #
+ 'Pascal' : 'LP ', #
+ 'Object_Pascal' : 'LP++', #
+ 'Java' : 'LJav', #
+ 'Assembler' : 'LAsm', #
+ 'Unknown' : 'L? ', #
}
_Enum_PPrm = {
- 'absolute' : 'Abso', # An absolute path name, including volume name.
- 'project_relative' : 'PRel', # A path relative to the current project\xd5s folder.
- 'shell_relative' : 'SRel', # A path relative to the CodeWarrior\xaa folder.
- 'system_relative' : 'YRel', # A path relative to the system folder
- 'root_relative' : 'RRel', #
+ 'absolute' : 'Abso', # An absolute path name, including volume name.
+ 'project_relative' : 'PRel', # A path relative to the current project\xd5s folder.
+ 'shell_relative' : 'SRel', # A path relative to the CodeWarrior\xaa folder.
+ 'system_relative' : 'YRel', # A path relative to the system folder
+ 'root_relative' : 'RRel', #
}
_Enum_PXdg = {
- 'Diagnose_None' : 'PXd1', # No Plugin Diagnostics.
- 'Diagnose_Errors' : 'PXd2', # Plugin Diagnostics for errors only.
- 'Diagnose_All' : 'PXd3', # Plugin Diagnostics for everything.
+ 'Diagnose_None' : 'PXd1', # No Plugin Diagnostics.
+ 'Diagnose_Errors' : 'PXd2', # Plugin Diagnostics for errors only.
+ 'Diagnose_All' : 'PXd3', # Plugin Diagnostics for everything.
}
_Enum_PthF = {
- 'Generic_Path' : 'PFGn', #
- 'MacOS_Path' : 'PFMc', # MacOS path using colon as separator
- 'Windows_Path' : 'PFWn', # Windows path using backslash as separator
- 'Unix_Path' : 'PFUx', # Unix path using slash as separator
+ 'Generic_Path' : 'PFGn', #
+ 'MacOS_Path' : 'PFMc', # MacOS path using colon as separator
+ 'Windows_Path' : 'PFWn', # Windows path using backslash as separator
+ 'Unix_Path' : 'PFUx', # Unix path using slash as separator
}
_Enum_RefP = {
- 'Think_Reference' : 'DanR', #
- 'QuickView' : 'ALTV', #
+ 'Think_Reference' : 'DanR', #
+ 'QuickView' : 'ALTV', #
}
_Enum_STKd = {
- 'Absolute_Path' : 'STK0', # The \xd2path\xd3 property is an absolute path to the location of the source tree.
- 'Registry_Key' : 'STK1', # The \xd2path\xd3 property is the name of a registry key that contains the path to the root.
- 'Environment_Variable' : 'STK2', # The \xd2path\xd3 property is the name of an environment variable that contains the path to the root.
+ 'Absolute_Path' : 'STK0', # The \xd2path\xd3 property is an absolute path to the location of the source tree.
+ 'Registry_Key' : 'STK1', # The \xd2path\xd3 property is the name of a registry key that contains the path to the root.
+ 'Environment_Variable' : 'STK2', # The \xd2path\xd3 property is the name of an environment variable that contains the path to the root.
}
_Enum_SrcT = {
- 'source' : 'FTxt', # A source file (.c, .cp, .p, etc).
- 'unknown' : 'FUnk', # An unknown file type.
+ 'source' : 'FTxt', # A source file (.c, .cp, .p, etc).
+ 'unknown' : 'FUnk', # An unknown file type.
}
_Enum_TmpB = {
- 'User_Specified' : 'Usrs', # Use user specified symbols when setting temporary breakpoints on program launch.
- 'Default' : 'Dflt', # Use system default symbols when setting temporary breakpoints on program launch.
+ 'User_Specified' : 'Usrs', # Use user specified symbols when setting temporary breakpoints on program launch.
+ 'Default' : 'Dflt', # Use system default symbols when setting temporary breakpoints on program launch.
}
_Enum_TxtF = {
- 'MacOS' : 'TxF0', # MacOS text format
- 'DOS' : 'TxF1', # DOS text format
- 'Unix' : 'TxF2', # Unix text format
+ 'MacOS' : 'TxF0', # MacOS text format
+ 'DOS' : 'TxF1', # DOS text format
+ 'Unix' : 'TxF2', # Unix text format
}
_Enum_savo = {
- 'yes' : 'yes ', # Save changes
- 'no' : 'no ', # Do not save changes
- 'ask' : 'ask ', # Ask the user whether to save
+ 'yes' : 'yes ', # Save changes
+ 'no' : 'no ', # Do not save changes
+ 'ask' : 'ask ', # Ask the user whether to save
}
diff --git a/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Required.py b/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Required.py
index a2c0de86a8..b0749e873f 100644
--- a/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Required.py
+++ b/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Required.py
@@ -40,8 +40,8 @@ class Required_Events(Required_Suite_Events):
return _arguments['----']
_Enum_Conv = {
- 'yes' : 'yes ', # Convert the project if necessary on open
- 'no' : 'no ', # Do not convert the project if needed on open
+ 'yes' : 'yes ', # Convert the project if necessary on open
+ 'no' : 'no ', # Do not convert the project if needed on open
}
diff --git a/Lib/plat-mac/lib-scriptpackages/CodeWarrior/__init__.py b/Lib/plat-mac/lib-scriptpackages/CodeWarrior/__init__.py
index 43ae4040e6..5ef7ca964c 100644
--- a/Lib/plat-mac/lib-scriptpackages/CodeWarrior/__init__.py
+++ b/Lib/plat-mac/lib-scriptpackages/CodeWarrior/__init__.py
@@ -187,4 +187,3 @@ class CodeWarrior(CodeWarrior_suite_Events,
_signature = 'CWIE'
_moduleName = 'CodeWarrior'
-
diff --git a/Lib/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py b/Lib/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py
index e023acd31d..0a985d123b 100644
--- a/Lib/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/Explorer/Required_Suite.py
@@ -73,7 +73,7 @@ class Required_Suite_Events(Required_Suite_Events):
return _arguments['----']
def run(self, _no_object=None, _attributes={}, **_arguments):
- """run:
+ """run:
Keyword argument _attributes: AppleEvent attribute dictionary
"""
_code = 'aevt'
diff --git a/Lib/plat-mac/lib-scriptpackages/Explorer/Standard_Suite.py b/Lib/plat-mac/lib-scriptpackages/Explorer/Standard_Suite.py
index af68e25d55..7ead98af96 100644
--- a/Lib/plat-mac/lib-scriptpackages/Explorer/Standard_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/Explorer/Standard_Suite.py
@@ -17,7 +17,7 @@ class Standard_Suite_Events:
}
def get(self, _object, _attributes={}, **_arguments):
- """get:
+ """get:
Required argument: an AE object reference
Keyword argument as: undocumented, typecode 'type'
Keyword argument _attributes: AppleEvent attribute dictionary
diff --git a/Lib/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py b/Lib/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py
index a05d795496..ff808eb968 100644
--- a/Lib/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/Explorer/Web_Browser_Suite.py
@@ -84,7 +84,7 @@ class Web_Browser_Suite_Events:
"""GetWindowInfo: Returns a window info record (URL/Title) for the specified window.
Required argument: Window Identifier of the window
Keyword argument _attributes: AppleEvent attribute dictionary
- Returns:
+ Returns:
"""
_code = 'WWW!'
_subcode = 'WNFO'
diff --git a/Lib/plat-mac/lib-scriptpackages/Finder/Enumerations.py b/Lib/plat-mac/lib-scriptpackages/Finder/Enumerations.py
index 38336cca48..558d7ff23b 100644
--- a/Lib/plat-mac/lib-scriptpackages/Finder/Enumerations.py
+++ b/Lib/plat-mac/lib-scriptpackages/Finder/Enumerations.py
@@ -16,106 +16,106 @@ class Enumerations_Events(Type_Names_Suite_Events):
pass
_Enum_earr = {
- 'not_arranged' : 'narr', #
- 'snap_to_grid' : 'grda', #
- 'arranged_by_name' : 'nama', #
- 'arranged_by_modification_date' : 'mdta', #
- 'arranged_by_creation_date' : 'cdta', #
- 'arranged_by_size' : 'siza', #
- 'arranged_by_kind' : 'kina', #
- 'arranged_by_label' : 'laba', #
+ 'not_arranged' : 'narr', #
+ 'snap_to_grid' : 'grda', #
+ 'arranged_by_name' : 'nama', #
+ 'arranged_by_modification_date' : 'mdta', #
+ 'arranged_by_creation_date' : 'cdta', #
+ 'arranged_by_size' : 'siza', #
+ 'arranged_by_kind' : 'kina', #
+ 'arranged_by_label' : 'laba', #
}
_Enum_ecvw = {
- 'icon_view' : 'icnv', #
- 'list_view' : 'lsvw', #
- 'column_view' : 'clvw', #
+ 'icon_view' : 'icnv', #
+ 'list_view' : 'lsvw', #
+ 'column_view' : 'clvw', #
}
_Enum_edfm = {
- 'Mac_OS_format' : 'dfhf', #
- 'Mac_OS_Extended_format' : 'dfh+', #
- 'UFS_format' : 'dfuf', #
- 'NFS_format' : 'dfnf', #
- 'audio_format' : 'dfau', #
- 'ProDOS_format' : 'dfpr', #
- 'MS_2d_DOS_format' : 'dfms', #
- 'ISO_9660_format' : 'df96', #
- 'High_Sierra_format' : 'dfhs', #
- 'QuickTake_format' : 'dfqt', #
- 'Apple_Photo_format' : 'dfph', #
- 'AppleShare_format' : 'dfas', #
- 'UDF_format' : 'dfud', #
- 'WebDAV_format' : 'dfwd', #
- 'FTP_format' : 'dfft', #
- 'Packet_2d_written_UDF_format' : 'dfpu', #
- 'unknown_format' : 'df??', #
+ 'Mac_OS_format' : 'dfhf', #
+ 'Mac_OS_Extended_format' : 'dfh+', #
+ 'UFS_format' : 'dfuf', #
+ 'NFS_format' : 'dfnf', #
+ 'audio_format' : 'dfau', #
+ 'ProDOS_format' : 'dfpr', #
+ 'MS_2d_DOS_format' : 'dfms', #
+ 'ISO_9660_format' : 'df96', #
+ 'High_Sierra_format' : 'dfhs', #
+ 'QuickTake_format' : 'dfqt', #
+ 'Apple_Photo_format' : 'dfph', #
+ 'AppleShare_format' : 'dfas', #
+ 'UDF_format' : 'dfud', #
+ 'WebDAV_format' : 'dfwd', #
+ 'FTP_format' : 'dfft', #
+ 'Packet_2d_written_UDF_format' : 'dfpu', #
+ 'unknown_format' : 'df??', #
}
_Enum_elsv = {
- 'name_column' : 'elsn', #
- 'modification_date_column' : 'elsm', #
- 'creation_date_column' : 'elsc', #
- 'size_column' : 'elss', #
- 'kind_column' : 'elsk', #
- 'label_column' : 'elsl', #
- 'version_column' : 'elsv', #
- 'comment_column' : 'elsC', #
+ 'name_column' : 'elsn', #
+ 'modification_date_column' : 'elsm', #
+ 'creation_date_column' : 'elsc', #
+ 'size_column' : 'elss', #
+ 'kind_column' : 'elsk', #
+ 'label_column' : 'elsl', #
+ 'version_column' : 'elsv', #
+ 'comment_column' : 'elsC', #
}
_Enum_ipnl = {
- 'General_Information_panel' : 'gpnl', #
- 'Sharing_panel' : 'spnl', #
- 'Memory_panel' : 'mpnl', #
- 'Preview_panel' : 'vpnl', #
- 'Application_panel' : 'apnl', #
- 'Languages_panel' : 'pklg', #
- 'Plugins_panel' : 'pkpg', #
- 'Name__26__Extension_panel' : 'npnl', #
- 'Comments_panel' : 'cpnl', #
- 'Content_Index_panel' : 'cinl', #
+ 'General_Information_panel' : 'gpnl', #
+ 'Sharing_panel' : 'spnl', #
+ 'Memory_panel' : 'mpnl', #
+ 'Preview_panel' : 'vpnl', #
+ 'Application_panel' : 'apnl', #
+ 'Languages_panel' : 'pklg', #
+ 'Plugins_panel' : 'pkpg', #
+ 'Name__26__Extension_panel' : 'npnl', #
+ 'Comments_panel' : 'cpnl', #
+ 'Content_Index_panel' : 'cinl', #
}
_Enum_isiz = {
- 'mini' : 'miic', #
- 'small' : 'smic', #
- 'large' : 'lgic', #
+ 'mini' : 'miic', #
+ 'small' : 'smic', #
+ 'large' : 'lgic', #
}
_Enum_lvic = {
- 'small_icon' : 'smic', #
- 'large_icon' : 'lgic', #
+ 'small_icon' : 'smic', #
+ 'large_icon' : 'lgic', #
}
_Enum_priv = {
- 'read_only' : 'read', #
- 'read_write' : 'rdwr', #
- 'write_only' : 'writ', #
- 'none' : 'none', #
+ 'read_only' : 'read', #
+ 'read_write' : 'rdwr', #
+ 'write_only' : 'writ', #
+ 'none' : 'none', #
}
_Enum_sodr = {
- 'normal' : 'snrm', #
- 'reversed' : 'srvs', #
+ 'normal' : 'snrm', #
+ 'reversed' : 'srvs', #
}
_Enum_vwby = {
- 'conflicts' : 'cflc', #
- 'existing_items' : 'exsi', #
- 'small_icon' : 'smic', #
- 'icon' : 'iimg', #
- 'name' : 'pnam', #
- 'modification_date' : 'asmo', #
- 'size' : 'ptsz', #
- 'kind' : 'kind', #
- 'comment' : 'comt', #
- 'label' : 'labi', #
- 'version' : 'vers', #
- 'creation_date' : 'ascd', #
- 'small_button' : 'smbu', #
- 'large_button' : 'lgbu', #
- 'grid' : 'grid', #
- 'all' : 'kyal', #
+ 'conflicts' : 'cflc', #
+ 'existing_items' : 'exsi', #
+ 'small_icon' : 'smic', #
+ 'icon' : 'iimg', #
+ 'name' : 'pnam', #
+ 'modification_date' : 'asmo', #
+ 'size' : 'ptsz', #
+ 'kind' : 'kind', #
+ 'comment' : 'comt', #
+ 'label' : 'labi', #
+ 'version' : 'vers', #
+ 'creation_date' : 'ascd', #
+ 'small_button' : 'smbu', #
+ 'large_button' : 'lgbu', #
+ 'grid' : 'grid', #
+ 'all' : 'kyal', #
}
diff --git a/Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py b/Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py
index a40510eef3..f4aea730c6 100644
--- a/Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/Netscape/Mozilla_suite.py
@@ -224,29 +224,29 @@ class Mozilla_suite_Events:
return _arguments['----']
_Enum_comp = {
- 'Navigator' : 'navg', # The Navigator component
- 'InBox' : 'inbx', # The InBox component
- 'Newsgroups' : 'colb', # The Newsgroups component
- 'Composer' : 'cpsr', # The Page Composer component
- 'Conference' : 'conf', # The Conference Component
- 'Calendar' : 'cald', # The Calendar Component
+ 'Navigator' : 'navg', # The Navigator component
+ 'InBox' : 'inbx', # The InBox component
+ 'Newsgroups' : 'colb', # The Newsgroups component
+ 'Composer' : 'cpsr', # The Page Composer component
+ 'Conference' : 'conf', # The Conference Component
+ 'Calendar' : 'cald', # The Calendar Component
}
_Enum_dire = {
- 'again' : 'agai', # Again (reload)
- 'home' : 'home', # Home
- 'backward' : 'prev', # Previous page
- 'forward' : 'next', # Next page
+ 'again' : 'agai', # Again (reload)
+ 'home' : 'home', # Home
+ 'backward' : 'prev', # Previous page
+ 'forward' : 'next', # Next page
}
_Enum_ncmd = {
- 'Get_new_mail' : '\x00\x00\x04W', #
- 'Send_queued_messages' : '\x00\x00\x04X', #
- 'Read_newsgroups' : '\x00\x00\x04\x04', #
- 'Show_Inbox' : '\x00\x00\x04\x05', #
- 'Show_Bookmarks_window' : '\x00\x00\x04\x06', #
- 'Show_History_window' : '\x00\x00\x04\x07', #
- 'Show_Address_Book_window' : '\x00\x00\x04\t', #
+ 'Get_new_mail' : '\x00\x00\x04W', #
+ 'Send_queued_messages' : '\x00\x00\x04X', #
+ 'Read_newsgroups' : '\x00\x00\x04\x04', #
+ 'Show_Inbox' : '\x00\x00\x04\x05', #
+ 'Show_Bookmarks_window' : '\x00\x00\x04\x06', #
+ 'Show_History_window' : '\x00\x00\x04\x07', #
+ 'Show_Address_Book_window' : '\x00\x00\x04\t', #
}
diff --git a/Lib/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py b/Lib/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py
index 30fe566769..7767305cb3 100644
--- a/Lib/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py
+++ b/Lib/plat-mac/lib-scriptpackages/Netscape/PowerPlant.py
@@ -1,4 +1,4 @@
-"""Suite PowerPlant:
+"""Suite PowerPlant:
Level 0, version 0
Generated from /Volumes/Sap/Applications (Mac OS 9)/Netscape Communicator\xe2\x84\xa2 Folder/Netscape Communicator\xe2\x84\xa2
@@ -62,10 +62,10 @@ class PowerPlant_Events:
return _arguments['----']
_Enum_dbac = {
- 'DoNothing' : '\x00\x00\x00\x00', # No debugging action is taken.
- 'PostAlert' : '\x00\x00\x00\x01', # Post an alert.
- 'LowLevelDebugger' : '\x00\x00\x00\x02', # Break into the low level debugger (MacsBug).
- 'SourceDebugger' : '\x00\x00\x00\x03', # Break into the source level debugger (if source debugger is executing).
+ 'DoNothing' : '\x00\x00\x00\x00', # No debugging action is taken.
+ 'PostAlert' : '\x00\x00\x00\x01', # Post an alert.
+ 'LowLevelDebugger' : '\x00\x00\x00\x02', # Break into the low level debugger (MacsBug).
+ 'SourceDebugger' : '\x00\x00\x00\x03', # Break into the source level debugger (if source debugger is executing).
}
diff --git a/Lib/plat-mac/lib-scriptpackages/Netscape/Required_suite.py b/Lib/plat-mac/lib-scriptpackages/Netscape/Required_suite.py
index 5352bb18b3..b5c411048c 100644
--- a/Lib/plat-mac/lib-scriptpackages/Netscape/Required_suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/Netscape/Required_suite.py
@@ -1,4 +1,4 @@
-"""Suite Required suite:
+"""Suite Required suite:
Level 0, version 0
Generated from /Volumes/Sap/Applications (Mac OS 9)/Netscape Communicator\xe2\x84\xa2 Folder/Netscape Communicator\xe2\x84\xa2
diff --git a/Lib/plat-mac/lib-scriptpackages/Netscape/Standard_URL_suite.py b/Lib/plat-mac/lib-scriptpackages/Netscape/Standard_URL_suite.py
index 94847aa4be..de4a01c9e5 100644
--- a/Lib/plat-mac/lib-scriptpackages/Netscape/Standard_URL_suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/Netscape/Standard_URL_suite.py
@@ -22,8 +22,8 @@ class Standard_URL_suite_Events:
def GetURL(self, _object, _attributes={}, **_arguments):
"""GetURL: Loads the URL (optionally to disk)
- Required argument: The url
- Keyword argument to: file the URL should be loaded into
+ Required argument: The url
+ Keyword argument to: file the URL should be loaded into
Keyword argument inside: Window the URL should be loaded to
Keyword argument from_: Referrer, to be sent with the HTTP request
Keyword argument _attributes: AppleEvent attribute dictionary
diff --git a/Lib/plat-mac/lib-scriptpackages/Netscape/Text.py b/Lib/plat-mac/lib-scriptpackages/Netscape/Text.py
index 4515d4b11b..2360d949a3 100644
--- a/Lib/plat-mac/lib-scriptpackages/Netscape/Text.py
+++ b/Lib/plat-mac/lib-scriptpackages/Netscape/Text.py
@@ -1,4 +1,4 @@
-"""Suite Text:
+"""Suite Text:
Level 0, version 0
Generated from /Volumes/Sap/Applications (Mac OS 9)/Netscape Communicator\xe2\x84\xa2 Folder/Netscape Communicator\xe2\x84\xa2
diff --git a/Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py b/Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py
index 152c24a9ea..06cbfa7acd 100644
--- a/Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py
@@ -1,4 +1,4 @@
-"""Suite WorldWideWeb suite, as defined in Spyglass spec.:
+"""Suite WorldWideWeb suite, as defined in Spyglass spec.:
Level 1, version 1
Generated from /Volumes/Sap/Applications (Mac OS 9)/Netscape Communicator\xe2\x84\xa2 Folder/Netscape Communicator\xe2\x84\xa2
@@ -317,7 +317,7 @@ class WorldWideWeb_suite_Events:
def unregister_protocol(self, _object=None, _attributes={}, **_arguments):
"""unregister protocol: reverses the effects of \xd2register protocol\xd3
- Required argument: Application sig.
+ Required argument: Application sig.
Keyword argument for_protocol: protocol prefix. If none, unregister for all protocols
Keyword argument _attributes: AppleEvent attribute dictionary
Returns: TRUE if successful
diff --git a/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py b/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py
index 251fd779fa..574043d4a4 100644
--- a/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/StdSuites/AppleScript_Suite.py
@@ -1995,64 +1995,64 @@ zones._privpropdict = {
zones._privelemdict = {
}
_Enum_boov = {
- 'true' : 'true', # the true boolean value
- 'false' : 'fals', # the false boolean value
+ 'true' : 'true', # the true boolean value
+ 'false' : 'fals', # the false boolean value
}
_Enum_cons = {
- 'case' : 'case', # case
- 'diacriticals' : 'diac', # diacriticals
- 'white_space' : 'whit', # white space
- 'hyphens' : 'hyph', # hyphens
- 'expansion' : 'expa', # expansion
- 'punctuation' : 'punc', # punctuation
- 'application_responses' : 'rmte', # remote event replies
+ 'case' : 'case', # case
+ 'diacriticals' : 'diac', # diacriticals
+ 'white_space' : 'whit', # white space
+ 'hyphens' : 'hyph', # hyphens
+ 'expansion' : 'expa', # expansion
+ 'punctuation' : 'punc', # punctuation
+ 'application_responses' : 'rmte', # remote event replies
}
_Enum_eMds = {
- 'option_down' : 'Kopt', #
- 'command_down' : 'Kcmd', #
- 'control_down' : 'Kctl', #
- 'shift_down' : 'Ksft', #
- 'caps_lock_down' : 'Kclk', #
+ 'option_down' : 'Kopt', #
+ 'command_down' : 'Kcmd', #
+ 'control_down' : 'Kctl', #
+ 'shift_down' : 'Ksft', #
+ 'caps_lock_down' : 'Kclk', #
}
_Enum_ekst = {
- 'escape_key' : 'ks5\x00', #
- 'delete_key' : 'ks3\x00', #
- 'tab_key' : 'ks0\x00', #
- 'return_key' : 'ks$\x00', #
- 'clear_key' : 'ksG\x00', #
- 'enter_key' : 'ksL\x00', #
- 'up_arrow_key' : 'ks~\x00', #
- 'down_arrow_key' : 'ks}\x00', #
- 'left_arrow_key' : 'ks{\x00', #
- 'right_arrow_key' : 'ks|\x00', #
- 'help_key' : 'ksr\x00', #
- 'home_key' : 'kss\x00', #
- 'page_up_key' : 'kst\x00', #
- 'page_down_key' : 'ksy\x00', #
- 'forward_del_key' : 'ksu\x00', #
- 'end_key' : 'ksw\x00', #
- 'F1_key' : 'ksz\x00', #
- 'F2_key' : 'ksx\x00', #
- 'F3_key' : 'ksc\x00', #
- 'F4_key' : 'ksv\x00', #
- 'F5_key' : 'ks`\x00', #
- 'F6_key' : 'ksa\x00', #
- 'F7_key' : 'ksb\x00', #
- 'F8_key' : 'ksd\x00', #
- 'F9_key' : 'kse\x00', #
- 'F10_key' : 'ksm\x00', #
- 'F11_key' : 'ksg\x00', #
- 'F12_key' : 'kso\x00', #
- 'F13_key' : 'ksi\x00', #
- 'F14_key' : 'ksk\x00', #
- 'F15_key' : 'ksq\x00', #
+ 'escape_key' : 'ks5\x00', #
+ 'delete_key' : 'ks3\x00', #
+ 'tab_key' : 'ks0\x00', #
+ 'return_key' : 'ks$\x00', #
+ 'clear_key' : 'ksG\x00', #
+ 'enter_key' : 'ksL\x00', #
+ 'up_arrow_key' : 'ks~\x00', #
+ 'down_arrow_key' : 'ks}\x00', #
+ 'left_arrow_key' : 'ks{\x00', #
+ 'right_arrow_key' : 'ks|\x00', #
+ 'help_key' : 'ksr\x00', #
+ 'home_key' : 'kss\x00', #
+ 'page_up_key' : 'kst\x00', #
+ 'page_down_key' : 'ksy\x00', #
+ 'forward_del_key' : 'ksu\x00', #
+ 'end_key' : 'ksw\x00', #
+ 'F1_key' : 'ksz\x00', #
+ 'F2_key' : 'ksx\x00', #
+ 'F3_key' : 'ksc\x00', #
+ 'F4_key' : 'ksv\x00', #
+ 'F5_key' : 'ks`\x00', #
+ 'F6_key' : 'ksa\x00', #
+ 'F7_key' : 'ksb\x00', #
+ 'F8_key' : 'ksd\x00', #
+ 'F9_key' : 'kse\x00', #
+ 'F10_key' : 'ksm\x00', #
+ 'F11_key' : 'ksg\x00', #
+ 'F12_key' : 'kso\x00', #
+ 'F13_key' : 'ksi\x00', #
+ 'F14_key' : 'ksk\x00', #
+ 'F15_key' : 'ksq\x00', #
}
_Enum_misc = {
- 'current_application' : 'cura', # the current application
+ 'current_application' : 'cura', # the current application
}
diff --git a/Lib/plat-mac/lib-scriptpackages/StdSuites/Macintosh_Connectivity_Clas.py b/Lib/plat-mac/lib-scriptpackages/StdSuites/Macintosh_Connectivity_Clas.py
index 5fa06ddfe2..99fe5e348a 100644
--- a/Lib/plat-mac/lib-scriptpackages/StdSuites/Macintosh_Connectivity_Clas.py
+++ b/Lib/plat-mac/lib-scriptpackages/StdSuites/Macintosh_Connectivity_Clas.py
@@ -253,74 +253,74 @@ USB_address._privpropdict = {
USB_address._privelemdict = {
}
_Enum_econ = {
- 'ADB' : 'eadb', #
- 'printer_port' : 'ecpp', #
- 'modem_port' : 'ecmp', #
- 'modem_printer_port' : 'empp', #
- 'LocalTalk' : 'eclt', #
- 'Ethernet' : 'ecen', #
- 'Token_Ring' : 'etok', #
- 'SCSI' : 'ecsc', #
- 'USB' : 'ecus', #
- 'FireWire' : 'ecfw', #
- 'infrared' : 'ecir', #
- 'PC_card' : 'ecpc', #
- 'PCI_bus' : 'ecpi', #
- 'NuBus' : 'enub', #
- 'PDS_slot' : 'ecpd', #
- 'Comm_slot' : 'eccm', #
- 'monitor_out' : 'ecmn', #
- 'video_out' : 'ecvo', #
- 'video_in' : 'ecvi', #
- 'audio_out' : 'ecao', #
- 'audio_line_in' : 'ecai', #
- 'audio_line_out' : 'ecal', #
- 'microphone' : 'ecmi', #
+ 'ADB' : 'eadb', #
+ 'printer_port' : 'ecpp', #
+ 'modem_port' : 'ecmp', #
+ 'modem_printer_port' : 'empp', #
+ 'LocalTalk' : 'eclt', #
+ 'Ethernet' : 'ecen', #
+ 'Token_Ring' : 'etok', #
+ 'SCSI' : 'ecsc', #
+ 'USB' : 'ecus', #
+ 'FireWire' : 'ecfw', #
+ 'infrared' : 'ecir', #
+ 'PC_card' : 'ecpc', #
+ 'PCI_bus' : 'ecpi', #
+ 'NuBus' : 'enub', #
+ 'PDS_slot' : 'ecpd', #
+ 'Comm_slot' : 'eccm', #
+ 'monitor_out' : 'ecmn', #
+ 'video_out' : 'ecvo', #
+ 'video_in' : 'ecvi', #
+ 'audio_out' : 'ecao', #
+ 'audio_line_in' : 'ecai', #
+ 'audio_line_out' : 'ecal', #
+ 'microphone' : 'ecmi', #
}
_Enum_edvt = {
- 'hard_disk_drive' : 'ehd ', #
- 'floppy_disk_drive' : 'efd ', #
- 'CD_ROM_drive' : 'ecd ', #
- 'DVD_drive' : 'edvd', #
- 'storage_device' : 'edst', #
- 'keyboard' : 'ekbd', #
- 'mouse' : 'emou', #
- 'trackball' : 'etrk', #
- 'trackpad' : 'edtp', #
- 'pointing_device' : 'edpd', #
- 'video_monitor' : 'edvm', #
- 'LCD_display' : 'edlc', #
- 'display' : 'edds', #
- 'modem' : 'edmm', #
- 'PC_card' : 'ecpc', #
- 'PCI_card' : 'edpi', #
- 'NuBus_card' : 'ednb', #
- 'printer' : 'edpr', #
- 'speakers' : 'edsp', #
- 'microphone' : 'ecmi', #
+ 'hard_disk_drive' : 'ehd ', #
+ 'floppy_disk_drive' : 'efd ', #
+ 'CD_ROM_drive' : 'ecd ', #
+ 'DVD_drive' : 'edvd', #
+ 'storage_device' : 'edst', #
+ 'keyboard' : 'ekbd', #
+ 'mouse' : 'emou', #
+ 'trackball' : 'etrk', #
+ 'trackpad' : 'edtp', #
+ 'pointing_device' : 'edpd', #
+ 'video_monitor' : 'edvm', #
+ 'LCD_display' : 'edlc', #
+ 'display' : 'edds', #
+ 'modem' : 'edmm', #
+ 'PC_card' : 'ecpc', #
+ 'PCI_card' : 'edpi', #
+ 'NuBus_card' : 'ednb', #
+ 'printer' : 'edpr', #
+ 'speakers' : 'edsp', #
+ 'microphone' : 'ecmi', #
}
_Enum_epro = {
- 'serial' : 'epsr', #
- 'AppleTalk' : 'epat', #
- 'IP' : 'epip', #
- 'SCSI' : 'ecsc', #
- 'ADB' : 'eadb', #
- 'FireWire' : 'ecfw', #
- 'IrDA' : 'epir', #
- 'IRTalk' : 'epit', #
- 'USB' : 'ecus', #
- 'PC_card' : 'ecpc', #
- 'PCI_bus' : 'ecpi', #
- 'NuBus' : 'enub', #
- 'bus' : 'ebus', #
- 'Macintosh_video' : 'epmv', #
- 'SVGA' : 'epsg', #
- 'S_video' : 'epsv', #
- 'analog_audio' : 'epau', #
- 'digital_audio' : 'epda', #
- 'PostScript' : 'epps', #
+ 'serial' : 'epsr', #
+ 'AppleTalk' : 'epat', #
+ 'IP' : 'epip', #
+ 'SCSI' : 'ecsc', #
+ 'ADB' : 'eadb', #
+ 'FireWire' : 'ecfw', #
+ 'IrDA' : 'epir', #
+ 'IRTalk' : 'epit', #
+ 'USB' : 'ecus', #
+ 'PC_card' : 'ecpc', #
+ 'PCI_bus' : 'ecpi', #
+ 'NuBus' : 'enub', #
+ 'bus' : 'ebus', #
+ 'Macintosh_video' : 'epmv', #
+ 'SVGA' : 'epsg', #
+ 'S_video' : 'epsv', #
+ 'analog_audio' : 'epau', #
+ 'digital_audio' : 'epda', #
+ 'PostScript' : 'epps', #
}
diff --git a/Lib/plat-mac/lib-scriptpackages/StdSuites/QuickDraw_Graphics_Suite.py b/Lib/plat-mac/lib-scriptpackages/StdSuites/QuickDraw_Graphics_Suite.py
index f4b59f553b..11747f9c3d 100644
--- a/Lib/plat-mac/lib-scriptpackages/StdSuites/QuickDraw_Graphics_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/StdSuites/QuickDraw_Graphics_Suite.py
@@ -327,28 +327,28 @@ graphic_line._privpropdict = {
graphic_line._privelemdict = {
}
_Enum_arro = {
- 'no_arrow' : 'arno', # No arrow on line
- 'arrow_at_start' : 'arst', # Arrow at start of line
- 'arrow_at_end' : 'aren', # Arrow at end of line
- 'arrow_at_both_ends' : 'arbo', # Arrow at both the start and the end of the line
+ 'no_arrow' : 'arno', # No arrow on line
+ 'arrow_at_start' : 'arst', # Arrow at start of line
+ 'arrow_at_end' : 'aren', # Arrow at end of line
+ 'arrow_at_both_ends' : 'arbo', # Arrow at both the start and the end of the line
}
_Enum_tran = {
- 'copy_pixels' : 'cpy ', #
- 'not_copy_pixels' : 'ncpy', #
- 'or_pixels' : 'or ', #
- 'not_or_pixels' : 'ntor', #
- 'bic_pixels' : 'bic ', #
- 'not_bic_pixels' : 'nbic', #
- 'xor_pixels' : 'xor ', #
- 'not_xor_pixels' : 'nxor', #
- 'add_over_pixels' : 'addo', #
- 'add_pin_pixels' : 'addp', #
- 'sub_over_pixels' : 'subo', #
- 'sub_pin_pixels' : 'subp', #
- 'ad_max_pixels' : 'admx', #
- 'ad_min_pixels' : 'admn', #
- 'blend_pixels' : 'blnd', #
+ 'copy_pixels' : 'cpy ', #
+ 'not_copy_pixels' : 'ncpy', #
+ 'or_pixels' : 'or ', #
+ 'not_or_pixels' : 'ntor', #
+ 'bic_pixels' : 'bic ', #
+ 'not_bic_pixels' : 'nbic', #
+ 'xor_pixels' : 'xor ', #
+ 'not_xor_pixels' : 'nxor', #
+ 'add_over_pixels' : 'addo', #
+ 'add_pin_pixels' : 'addp', #
+ 'sub_over_pixels' : 'subo', #
+ 'sub_pin_pixels' : 'subp', #
+ 'ad_max_pixels' : 'admx', #
+ 'ad_min_pixels' : 'admn', #
+ 'blend_pixels' : 'blnd', #
}
diff --git a/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py b/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py
index de6d5e5c31..86681f57bb 100644
--- a/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/StdSuites/Standard_Suite.py
@@ -656,33 +656,33 @@ class _b2_(aetools.NComparison):
class _b3_(aetools.NComparison):
"""\xb3 - Greater than or equal to """
_Enum_kfrm = {
- 'index' : 'indx', # keyform designating indexed access
- 'named' : 'name', # keyform designating named access
- 'id' : 'ID ', # keyform designating access by unique identifier
+ 'index' : 'indx', # keyform designating indexed access
+ 'named' : 'name', # keyform designating named access
+ 'id' : 'ID ', # keyform designating access by unique identifier
}
_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
}
_Enum_styl = {
- 'plain' : 'plan', # Plain
- 'bold' : 'bold', # Bold
- 'italic' : 'ital', # Italic
- 'outline' : 'outl', # Outline
- 'shadow' : 'shad', # Shadow
- 'underline' : 'undl', # Underline
- 'superscript' : 'spsc', # Superscript
- 'subscript' : 'sbsc', # Subscript
- 'strikethrough' : 'strk', # Strikethrough
- 'small_caps' : 'smcp', # Small caps
- 'all_caps' : 'alcp', # All capital letters
- 'all_lowercase' : 'lowc', # Lowercase
- 'condensed' : 'cond', # Condensed
- 'expanded' : 'pexp', # Expanded
- 'hidden' : 'hidn', # Hidden
+ 'plain' : 'plan', # Plain
+ 'bold' : 'bold', # Bold
+ 'italic' : 'ital', # Italic
+ 'outline' : 'outl', # Outline
+ 'shadow' : 'shad', # Shadow
+ 'underline' : 'undl', # Underline
+ 'superscript' : 'spsc', # Superscript
+ 'subscript' : 'sbsc', # Subscript
+ 'strikethrough' : 'strk', # Strikethrough
+ 'small_caps' : 'smcp', # Small caps
+ 'all_caps' : 'alcp', # All capital letters
+ 'all_lowercase' : 'lowc', # Lowercase
+ 'condensed' : 'cond', # Condensed
+ 'expanded' : 'pexp', # Expanded
+ 'hidden' : 'hidn', # Hidden
}
diff --git a/Lib/plat-mac/lib-scriptpackages/StdSuites/Table_Suite.py b/Lib/plat-mac/lib-scriptpackages/StdSuites/Table_Suite.py
index bb929b8c92..afa01a0e00 100644
--- a/Lib/plat-mac/lib-scriptpackages/StdSuites/Table_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/StdSuites/Table_Suite.py
@@ -74,9 +74,9 @@ tables._privpropdict = {
tables._privelemdict = {
}
_Enum_prtn = {
- 'read_only' : 'nmod', # Can\xd5t change values or formulas
- 'formulas_protected' : 'fpro', # Can changes values but not formulas
- 'read_2f_write' : 'modf', # Can change values and formulas
+ 'read_only' : 'nmod', # Can\xd5t change values or formulas
+ 'formulas_protected' : 'fpro', # Can changes values but not formulas
+ 'read_2f_write' : 'modf', # Can change values and formulas
}
diff --git a/Lib/plat-mac/lib-scriptpackages/StdSuites/Text_Suite.py b/Lib/plat-mac/lib-scriptpackages/StdSuites/Text_Suite.py
index 4edb7f4339..1845f4d435 100644
--- a/Lib/plat-mac/lib-scriptpackages/StdSuites/Text_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/StdSuites/Text_Suite.py
@@ -162,28 +162,28 @@ text_style_info._privpropdict = {
text_style_info._privelemdict = {
}
_Enum_just = {
- 'left' : 'left', # Align with left margin
- 'right' : 'rght', # Align with right margin
- 'center' : 'cent', # Align with center
- 'full' : 'full', # Align with both left and right margins
+ 'left' : 'left', # Align with left margin
+ 'right' : 'rght', # Align with right margin
+ 'center' : 'cent', # Align with center
+ 'full' : 'full', # Align with both left and right margins
}
_Enum_styl = {
- 'plain' : 'plan', # Plain
- 'bold' : 'bold', # Bold
- 'italic' : 'ital', # Italic
- 'outline' : 'outl', # Outline
- 'shadow' : 'shad', # Shadow
- 'underline' : 'undl', # Underline
- 'superscript' : 'spsc', # Superscript
- 'subscript' : 'sbsc', # Subscript
- 'strikethrough' : 'strk', # Strikethrough
- 'small_caps' : 'smcp', # Small caps
- 'all_caps' : 'alcp', # All capital letters
- 'all_lowercase' : 'lowc', # Lowercase
- 'condensed' : 'cond', # Condensed
- 'expanded' : 'pexp', # Expanded
- 'hidden' : 'hidn', # Hidden
+ 'plain' : 'plan', # Plain
+ 'bold' : 'bold', # Bold
+ 'italic' : 'ital', # Italic
+ 'outline' : 'outl', # Outline
+ 'shadow' : 'shad', # Shadow
+ 'underline' : 'undl', # Underline
+ 'superscript' : 'spsc', # Superscript
+ 'subscript' : 'sbsc', # Subscript
+ 'strikethrough' : 'strk', # Strikethrough
+ 'small_caps' : 'smcp', # Small caps
+ 'all_caps' : 'alcp', # All capital letters
+ 'all_lowercase' : 'lowc', # Lowercase
+ 'condensed' : 'cond', # Condensed
+ 'expanded' : 'pexp', # Expanded
+ 'hidden' : 'hidn', # Hidden
}
diff --git a/Lib/plat-mac/lib-scriptpackages/StdSuites/__init__.py b/Lib/plat-mac/lib-scriptpackages/StdSuites/__init__.py
index f648517250..b80e3bacc2 100644
--- a/Lib/plat-mac/lib-scriptpackages/StdSuites/__init__.py
+++ b/Lib/plat-mac/lib-scriptpackages/StdSuites/__init__.py
@@ -469,4 +469,3 @@ class StdSuites(Text_Suite_Events,
_signature = 'ascr'
_moduleName = 'StdSuites'
-
diff --git a/Lib/plat-mac/lib-scriptpackages/SystemEvents/Disk_Folder_File_Suite.py b/Lib/plat-mac/lib-scriptpackages/SystemEvents/Disk_Folder_File_Suite.py
index b9e6b34a77..a9ac3dd279 100644
--- a/Lib/plat-mac/lib-scriptpackages/SystemEvents/Disk_Folder_File_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/SystemEvents/Disk_Folder_File_Suite.py
@@ -313,21 +313,21 @@ file._privelemdict = {
'item' : item,
}
_Enum_edfm = {
- 'MS_2d_DOS_format' : 'dfms', # MS-DOS format
- 'Apple_Photo_format' : 'dfph', # Apple Photo format
- 'ISO_9660_format' : 'df96', # ISO 9660 format
- 'QuickTake_format' : 'dfqt', # QuickTake format
- 'AppleShare_format' : 'dfas', # AppleShare format
- 'High_Sierra_format' : 'dfhs', # High Sierra format
- 'Mac_OS_Extended_format' : 'dfh+', # Mac OS Extended format
- 'UDF_format' : 'dfud', # UDF format
- 'unknown_format' : 'df??', # unknown format
- 'audio_format' : 'dfau', # audio format
- 'Mac_OS_format' : 'dfhf', # Mac OS format
- 'UFS_format' : 'dfuf', # UFS format
- 'NFS_format' : 'dfnf', # NFS format
- 'ProDOS_format' : 'dfpr', # ProDOS format
- 'WebDAV_format' : 'dfwd', # WebDAV format
+ 'MS_2d_DOS_format' : 'dfms', # MS-DOS format
+ 'Apple_Photo_format' : 'dfph', # Apple Photo format
+ 'ISO_9660_format' : 'df96', # ISO 9660 format
+ 'QuickTake_format' : 'dfqt', # QuickTake format
+ 'AppleShare_format' : 'dfas', # AppleShare format
+ 'High_Sierra_format' : 'dfhs', # High Sierra format
+ 'Mac_OS_Extended_format' : 'dfh+', # Mac OS Extended format
+ 'UDF_format' : 'dfud', # UDF format
+ 'unknown_format' : 'df??', # unknown format
+ 'audio_format' : 'dfau', # audio format
+ 'Mac_OS_format' : 'dfhf', # Mac OS format
+ 'UFS_format' : 'dfuf', # UFS format
+ 'NFS_format' : 'dfnf', # NFS format
+ 'ProDOS_format' : 'dfpr', # ProDOS format
+ 'WebDAV_format' : 'dfwd', # WebDAV format
}
diff --git a/Lib/plat-mac/lib-scriptpackages/SystemEvents/Folder_Actions_Suite.py b/Lib/plat-mac/lib-scriptpackages/SystemEvents/Folder_Actions_Suite.py
index 22cf935b5a..c2c7e5e038 100644
--- a/Lib/plat-mac/lib-scriptpackages/SystemEvents/Folder_Actions_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/SystemEvents/Folder_Actions_Suite.py
@@ -252,11 +252,11 @@ script._privpropdict = {
script._privelemdict = {
}
_Enum_actn = {
- 'items_added' : 'fget', # items added
- 'items_removed' : 'flos', # items removed
- 'window_closed' : 'fclo', # window closed
- 'window_moved' : 'fsiz', # window moved
- 'window_opened' : 'fopn', # window opened
+ 'items_added' : 'fget', # items added
+ 'items_removed' : 'flos', # items removed
+ 'window_closed' : 'fclo', # window closed
+ 'window_moved' : 'fsiz', # window moved
+ 'window_opened' : 'fopn', # window opened
}
diff --git a/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py b/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py
index c9f6d446e6..f20ef8434f 100644
--- a/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/SystemEvents/Standard_Suite.py
@@ -524,9 +524,9 @@ class _b2_(aetools.NComparison):
class _b3_(aetools.NComparison):
"""\xb3 - Greater than or equal to """
_Enum_savo = {
- 'ask' : 'ask ', # Ask the user whether or not to save the file.
- 'yes' : 'yes ', # Save the file.
- 'no' : 'no ', # Do not save the file.
+ 'ask' : 'ask ', # Ask the user whether or not to save the file.
+ 'yes' : 'yes ', # Save the file.
+ 'no' : 'no ', # Do not save the file.
}
diff --git a/Lib/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py b/Lib/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py
index 673a31a5e8..035290f32b 100644
--- a/Lib/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/Terminal/Standard_Suite.py
@@ -524,9 +524,9 @@ class _b2_(aetools.NComparison):
class _b3_(aetools.NComparison):
"""\xb3 - Greater than or equal to """
_Enum_savo = {
- 'ask' : 'ask ', # Ask the user whether or not to save the file.
- 'yes' : 'yes ', # Save the file.
- 'no' : 'no ', # Do not save the file.
+ 'ask' : 'ask ', # Ask the user whether or not to save the file.
+ 'yes' : 'yes ', # Save the file.
+ 'no' : 'no ', # Do not save the file.
}
diff --git a/Lib/plat-mac/lib-scriptpackages/_builtinSuites/__init__.py b/Lib/plat-mac/lib-scriptpackages/_builtinSuites/__init__.py
index ac3c0baa59..2c722d9f54 100644
--- a/Lib/plat-mac/lib-scriptpackages/_builtinSuites/__init__.py
+++ b/Lib/plat-mac/lib-scriptpackages/_builtinSuites/__init__.py
@@ -9,20 +9,19 @@ import builtin_Suite
_code_to_module = {
- 'reqd' : builtin_Suite,
- 'core' : builtin_Suite,
+ 'reqd' : builtin_Suite,
+ 'core' : builtin_Suite,
}
_code_to_fullname = {
- 'reqd' : ('_builtinSuites.builtin_Suite', 'builtin_Suite'),
- 'core' : ('_builtinSuites.builtin_Suite', 'builtin_Suite'),
+ 'reqd' : ('_builtinSuites.builtin_Suite', 'builtin_Suite'),
+ 'core' : ('_builtinSuites.builtin_Suite', 'builtin_Suite'),
}
from builtin_Suite import *
class _builtinSuites(builtin_Suite_Events,
- aetools.TalkTo):
- _signature = 'ascr'
-
+ aetools.TalkTo):
+ _signature = 'ascr'
diff --git a/Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py b/Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py
index 117eeddbc9..318250fa27 100644
--- a/Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py
+++ b/Lib/plat-mac/lib-scriptpackages/_builtinSuites/builtin_Suite.py
@@ -9,118 +9,118 @@ _code = 'aevt'
class builtin_Suite_Events:
- def open(self, _object, _attributes={}, **_arguments):
- """open: Open the specified object(s)
- Required argument: list of objects to open
- Keyword argument _attributes: AppleEvent attribute dictionary
- """
- _code = 'aevt'
- _subcode = 'odoc'
-
- if _arguments: raise TypeError, 'No optional args expected'
- _arguments['----'] = _object
-
-
- _reply, _arguments, _attributes = self.send(_code, _subcode,
- _arguments, _attributes)
- if _arguments.get('errn', 0):
- raise aetools.Error, aetools.decodeerror(_arguments)
- # XXXX Optionally decode result
- if _arguments.has_key('----'):
- return _arguments['----']
-
- def run(self, _no_object=None, _attributes={}, **_arguments):
- """run: Run an application. Most applications will open an empty, untitled window.
- Keyword argument _attributes: AppleEvent attribute dictionary
- """
- _code = 'aevt'
- _subcode = 'oapp'
-
- if _arguments: raise TypeError, 'No optional args expected'
- if _no_object != None: raise TypeError, 'No direct arg expected'
-
-
- _reply, _arguments, _attributes = self.send(_code, _subcode,
- _arguments, _attributes)
- if _arguments.get('errn', 0):
- raise aetools.Error, aetools.decodeerror(_arguments)
- # XXXX Optionally decode result
- if _arguments.has_key('----'):
- return _arguments['----']
-
- def reopen(self, _no_object=None, _attributes={}, **_arguments):
- """reopen: Reactivate a running application. Some applications will open a new untitled window if no window is open.
- Keyword argument _attributes: AppleEvent attribute dictionary
- """
- _code = 'aevt'
- _subcode = 'rapp'
-
- if _arguments: raise TypeError, 'No optional args expected'
- if _no_object != None: raise TypeError, 'No direct arg expected'
-
-
- _reply, _arguments, _attributes = self.send(_code, _subcode,
- _arguments, _attributes)
- if _arguments.get('errn', 0):
- raise aetools.Error, aetools.decodeerror(_arguments)
- # XXXX Optionally decode result
- if _arguments.has_key('----'):
- return _arguments['----']
-
- def _print(self, _object, _attributes={}, **_arguments):
- """print: Print the specified object(s)
- Required argument: list of objects to print
- Keyword argument _attributes: AppleEvent attribute dictionary
- """
- _code = 'aevt'
- _subcode = 'pdoc'
-
- if _arguments: raise TypeError, 'No optional args expected'
- _arguments['----'] = _object
-
-
- _reply, _arguments, _attributes = self.send(_code, _subcode,
- _arguments, _attributes)
- if _arguments.get('errn', 0):
- raise aetools.Error, aetools.decodeerror(_arguments)
- # XXXX Optionally decode result
- if _arguments.has_key('----'):
- return _arguments['----']
-
- _argmap_quit = {
- 'saving' : 'savo',
- }
-
- def quit(self, _no_object=None, _attributes={}, **_arguments):
- """quit: Quit an application
- Keyword argument saving: specifies whether to save currently open documents
- Keyword argument _attributes: AppleEvent attribute dictionary
- """
- _code = 'aevt'
- _subcode = 'quit'
-
- aetools.keysubst(_arguments, self._argmap_quit)
- if _no_object != None: raise TypeError, 'No direct arg expected'
-
- aetools.enumsubst(_arguments, 'savo', _Enum_savo)
-
- _reply, _arguments, _attributes = self.send(_code, _subcode,
- _arguments, _attributes)
- if _arguments.get('errn', 0):
- raise aetools.Error, aetools.decodeerror(_arguments)
- # XXXX Optionally decode result
- if _arguments.has_key('----'):
- return _arguments['----']
-
- _argmap_close = {
- 'saving' : 'savo',
- 'saving_in' : 'kfil',
- }
+ def open(self, _object, _attributes={}, **_arguments):
+ """open: Open the specified object(s)
+ Required argument: list of objects to open
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'aevt'
+ _subcode = 'odoc'
+
+ if _arguments: raise TypeError, 'No optional args expected'
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.get('errn', 0):
+ raise aetools.Error, aetools.decodeerror(_arguments)
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ def run(self, _no_object=None, _attributes={}, **_arguments):
+ """run: Run an application. Most applications will open an empty, untitled window.
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'aevt'
+ _subcode = 'oapp'
+
+ if _arguments: raise TypeError, 'No optional args expected'
+ if _no_object != None: raise TypeError, 'No direct arg expected'
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.get('errn', 0):
+ raise aetools.Error, aetools.decodeerror(_arguments)
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ def reopen(self, _no_object=None, _attributes={}, **_arguments):
+ """reopen: Reactivate a running application. Some applications will open a new untitled window if no window is open.
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'aevt'
+ _subcode = 'rapp'
+
+ if _arguments: raise TypeError, 'No optional args expected'
+ if _no_object != None: raise TypeError, 'No direct arg expected'
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.get('errn', 0):
+ raise aetools.Error, aetools.decodeerror(_arguments)
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ def _print(self, _object, _attributes={}, **_arguments):
+ """print: Print the specified object(s)
+ Required argument: list of objects to print
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'aevt'
+ _subcode = 'pdoc'
+
+ if _arguments: raise TypeError, 'No optional args expected'
+ _arguments['----'] = _object
+
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.get('errn', 0):
+ raise aetools.Error, aetools.decodeerror(_arguments)
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ _argmap_quit = {
+ 'saving' : 'savo',
+ }
+
+ def quit(self, _no_object=None, _attributes={}, **_arguments):
+ """quit: Quit an application
+ Keyword argument saving: specifies whether to save currently open documents
+ Keyword argument _attributes: AppleEvent attribute dictionary
+ """
+ _code = 'aevt'
+ _subcode = 'quit'
+
+ aetools.keysubst(_arguments, self._argmap_quit)
+ if _no_object != None: raise TypeError, 'No direct arg expected'
+
+ aetools.enumsubst(_arguments, 'savo', _Enum_savo)
+
+ _reply, _arguments, _attributes = self.send(_code, _subcode,
+ _arguments, _attributes)
+ if _arguments.get('errn', 0):
+ raise aetools.Error, aetools.decodeerror(_arguments)
+ # XXXX Optionally decode result
+ if _arguments.has_key('----'):
+ return _arguments['----']
+
+ _argmap_close = {
+ 'saving' : 'savo',
+ 'saving_in' : 'kfil',
+ }
_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
}
#
@@ -136,5 +136,5 @@ _compdeclarations = {
}
_enumdeclarations = {
- 'savo' : _Enum_savo,
+ 'savo' : _Enum_savo,
}
diff --git a/Lib/plat-mac/macfs.py b/Lib/plat-mac/macfs.py
index 11dbbeb3cd..73815aeb3f 100644
--- a/Lib/plat-mac/macfs.py
+++ b/Lib/plat-mac/macfs.py
@@ -9,7 +9,7 @@ import warnings
warnings.warn("macfs is deprecated, use Carbon.File, Carbon.Folder or EasyDialogs",
DeprecationWarning, stacklevel=2)
-
+
# First step: ensure we also emulate the MACFS module, which contained
# all the constants
@@ -38,7 +38,7 @@ if time.gmtime(0)[0] == 1970:
t = t + 0x10000000L
return (0, int(t), 0)
else:
- def _utc2time(utc):
+ def _utc2time(utc):
t = utc[1]
if t < 0:
t = t + 0x100000000L
@@ -58,26 +58,26 @@ error = Carbon.File.Error
class FSSpec(Carbon.File.FSSpec):
def as_fsref(self):
return FSRef(self)
-
+
def NewAlias(self, src=None):
return Alias(Carbon.File.NewAlias(src, self))
-
+
def GetCreatorType(self):
finfo = self.FSpGetFInfo()
return finfo.Creator, finfo.Type
-
+
def SetCreatorType(self, ctor, tp):
finfo = self.FSpGetFInfo()
finfo.Creator = ctor
finfo.Type = tp
self.FSpSetFInfo(finfo)
-
+
def GetFInfo(self):
return self.FSpGetFInfo()
-
+
def SetFInfo(self, info):
return self.FSpSetFInfo(info)
-
+
def GetDates(self):
catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
catinfo, d1, d2, d3 = FSRef(self).FSGetCatalogInfo(catInfoFlags)
@@ -85,7 +85,7 @@ class FSSpec(Carbon.File.FSSpec):
mdate = catinfo.contentModDate
bdate = catinfo.backupDate
return _utc2time(cdate), _utc2time(mdate), _utc2time(bdate)
-
+
def SetDates(self, cdate, mdate, bdate):
catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
catinfo = Carbon.File.FSCatalogInfo(
@@ -93,23 +93,23 @@ class FSSpec(Carbon.File.FSSpec):
contentModDate = _time2utc(mdate),
backupDate = _time2utc(bdate))
FSRef(self).FSSetCatalogInfo(catInfoFlags, catinfo)
-
+
class FSRef(Carbon.File.FSRef):
def as_fsspec(self):
return FSSpec(self)
-
+
class Alias(Carbon.File.Alias):
def GetInfo(self, index):
return self.GetAliasInfo(index)
-
+
def Update(self, *args):
pass # print "Alias.Update not yet implemented"
-
+
def Resolve(self, src=None):
fss, changed = self.ResolveAlias(src)
return FSSpec(fss), changed
-
+
from Carbon.File import FInfo
# Backward-compatible type names:
@@ -122,19 +122,19 @@ FInfoType = FInfo
def ResolveAliasFile(fss, chain=1):
fss, isdir, isalias = Carbon.File.ResolveAliasFile(fss, chain)
return FSSpec(fss), isdir, isalias
-
+
def RawFSSpec(data):
return FSSpec(rawdata=data)
-
+
def RawAlias(data):
return Alias(rawdata=data)
-
+
def FindApplication(*args):
raise NotImplementedError, "FindApplication no longer implemented"
-
+
def NewAliasMinimalFromFullPath(path):
return Alias(Carbon.File.NewAliasMinimalFromFullPath(path, '', ''))
-
+
# Another global function:
from Carbon.Folder import FindFolder
@@ -148,7 +148,7 @@ def StandardGetFile(*typelist):
"""Ask for an input file, optionally specifying 4-char file types that are
allowable"""
return PromptGetFile('', *typelist)
-
+
def PromptGetFile(prompt, *typelist):
"""Ask for an input file giving the user a prompt message. Optionally you can
specifying 4-char file types that are allowable"""
@@ -157,7 +157,7 @@ def PromptGetFile(prompt, *typelist):
DeprecationWarning, stacklevel=2)
if not typelist:
typelist = None
- fss = EasyDialogs.AskFileForOpen(message=prompt, wanted=FSSpec,
+ fss = EasyDialogs.AskFileForOpen(message=prompt, wanted=FSSpec,
typeList=typelist, defaultLocation=_handleSetFolder())
return fss, not fss is None
@@ -167,10 +167,10 @@ def StandardPutFile(prompt, default=None):
import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2)
- fss = EasyDialogs.AskFileForSave(wanted=FSSpec, message=prompt,
+ fss = EasyDialogs.AskFileForSave(wanted=FSSpec, message=prompt,
savedFileName=default, defaultLocation=_handleSetFolder())
return fss, not fss is None
-
+
def SetFolder(folder):
global _curfolder
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
@@ -181,18 +181,18 @@ def SetFolder(folder):
rv = None
_curfolder = folder
return rv
-
+
def _handleSetFolder():
global _curfolder
rv = _curfolder
_curfolder = None
return rv
-
+
def GetDirectory(prompt=None):
"""Ask the user to select a folder. Optionally you can give a prompt."""
import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2)
- fss = EasyDialogs.AskFolder(message=prompt, wanted=FSSpec,
+ fss = EasyDialogs.AskFolder(message=prompt, wanted=FSSpec,
defaultLocation=_handleSetFolder())
return fss, not fss is None
diff --git a/Lib/plat-mac/macostools.py b/Lib/plat-mac/macostools.py
index 3644e7ec07..06bc92fe5d 100644
--- a/Lib/plat-mac/macostools.py
+++ b/Lib/plat-mac/macostools.py
@@ -41,18 +41,18 @@ def mkalias(src, dst, relative=None):
alias = File.FSNewAlias(relativefsr, srcfsr)
else:
alias = srcfsr.FSNewAliasMinimal()
-
- dstfsr, dstfss = Res.FSCreateResourceFile(dstdirfsr, unicode(dstname),
+
+ dstfsr, dstfss = Res.FSCreateResourceFile(dstdirfsr, unicode(dstname),
File.FSGetResourceForkName())
h = Res.FSOpenResourceFile(dstfsr, File.FSGetResourceForkName(), 3)
resource = Res.Resource(alias.data)
resource.AddResource('alis', 0, '')
Res.CloseResFile(h)
-
+
dstfinfo = dstfss.FSpGetFInfo()
dstfinfo.Flags = dstfinfo.Flags|0x8000 # Alias flag
dstfss.FSpSetFInfo(dstfinfo)
-
+
def mkdirs(dst):
"""Make directories leading to 'dst' if they don't exist yet"""
if dst == '' or os.path.exists(dst):
@@ -62,7 +62,7 @@ def mkdirs(dst):
head = head + ':'
mkdirs(head)
os.mkdir(dst, 0777)
-
+
def touched(dst):
"""Tell the finder a file has changed. No-op on MacOSX."""
if sys.platform != 'mac': return
@@ -80,7 +80,7 @@ def touched(dst):
dir_fss.SetDates(crdate, now, bkdate)
except macfs.error:
pass
-
+
def touched_ae(dst):
"""Tell the finder a file has changed"""
pardir = os.path.split(dst)[0]
@@ -89,14 +89,14 @@ def touched_ae(dst):
import Finder
f = Finder.Finder()
f.update(File.FSRef(pardir))
-
+
def copy(src, dst, createpath=0, copydates=1, forcetype=None):
"""Copy a file, including finder info, resource fork, etc"""
src = File.pathname(src)
dst = File.pathname(dst)
if createpath:
mkdirs(os.path.split(dst)[0])
-
+
ifp = open(src, 'rb')
ofp = open(dst, 'wb')
d = ifp.read(BUFSIZ)
@@ -105,7 +105,7 @@ def copy(src, dst, createpath=0, copydates=1, forcetype=None):
d = ifp.read(BUFSIZ)
ifp.close()
ofp.close()
-
+
ifp = openrf(src, '*rb')
ofp = openrf(dst, '*wb')
d = ifp.read(BUFSIZ)
@@ -114,7 +114,7 @@ def copy(src, dst, createpath=0, copydates=1, forcetype=None):
d = ifp.read(BUFSIZ)
ifp.close()
ofp.close()
-
+
srcfss = File.FSSpec(src)
dstfss = File.FSSpec(dst)
sf = srcfss.FSpGetFInfo()
@@ -130,7 +130,7 @@ def copy(src, dst, createpath=0, copydates=1, forcetype=None):
catinfo, _, _, _ = srcfsr.FSGetCatalogInfo(Files.kFSCatInfoAllDates)
dstfsr.FSSetCatalogInfo(Files.kFSCatInfoAllDates, catinfo)
touched(dstfss)
-
+
def copytree(src, dst, copydates=1):
"""Copy a complete file tree to a new destination"""
if os.path.isdir(src):
diff --git a/Lib/plat-mac/macresource.py b/Lib/plat-mac/macresource.py
index e4c3f62dfc..f68ecdc8a8 100644
--- a/Lib/plat-mac/macresource.py
+++ b/Lib/plat-mac/macresource.py
@@ -15,12 +15,12 @@ def need(restype, resid, filename=None, modname=None):
is available we are done. If it is not available we look for a file filename
(default: modname with .rsrc appended) either in the same folder as
where modname was loaded from, or otherwise across sys.path.
-
+
Returns the refno of the resource file opened (or None)"""
if modname is None and filename is None:
raise ArgumentError, "Either filename or modname argument (or both) must be given"
-
+
if type(resid) is type(1):
try:
h = Res.GetResource(restype, resid)
@@ -35,14 +35,14 @@ def need(restype, resid, filename=None, modname=None):
pass
else:
return None
-
+
# Construct a filename if we don't have one
if not filename:
if '.' in modname:
filename = modname.split('.')[-1] + '.rsrc'
else:
filename = modname + '.rsrc'
-
+
# Now create a list of folders to search
searchdirs = []
if modname == '__main__':
@@ -53,7 +53,7 @@ def need(restype, resid, filename=None, modname=None):
if hasattr(mod, '__file__'):
searchdirs = [os.path.dirname(mod.__file__)]
searchdirs.extend(sys.path)
-
+
# And look for the file
for dir in searchdirs:
pathname = os.path.join(dir, filename)
@@ -61,16 +61,16 @@ def need(restype, resid, filename=None, modname=None):
break
else:
raise ResourceFileNotFoundError, filename
-
+
refno = open_pathname(pathname)
-
+
# And check that the resource exists now
if type(resid) is type(1):
h = Res.GetResource(restype, resid)
else:
h = Res.GetNamedResource(restype, resid)
return refno
-
+
def open_pathname(pathname, verbose=0):
"""Open a resource file given by pathname, possibly decoding an
AppleSingle file"""
@@ -95,7 +95,7 @@ def open_pathname(pathname, verbose=0):
else:
raise
return refno
-
+
def resource_pathname(pathname, verbose=0):
"""Return the pathname for a resource file (either DF or RF based).
If the pathname given already refers to such a file simply return it,
@@ -121,12 +121,12 @@ def resource_pathname(pathname, verbose=0):
else:
raise
return pathname
-
+
def open_error_resource():
"""Open the resource file containing the error code to error message
mapping."""
need('Estr', 1, filename="errors.rsrc", modname=__name__)
-
+
def _decode(pathname, verbose=0):
# Decode an AppleSingle resource file, return the new pathname.
newpathname = pathname + '.df.rsrc'
diff --git a/Lib/plat-mac/pimp.py b/Lib/plat-mac/pimp.py
index 39bc693b08..67fab7607d 100644
--- a/Lib/plat-mac/pimp.py
+++ b/Lib/plat-mac/pimp.py
@@ -1,6 +1,6 @@
"""Package Install Manager for Python.
-This is currently a MacOSX-only strawman implementation.
+This is currently a MacOSX-only strawman implementation.
Despite other rumours the name stands for "Packman IMPlementation".
Tools to allow easy installation of packages. The idea is that there is
@@ -27,7 +27,7 @@ import tempfile
import shutil
import time
-__all__ = ["PimpPreferences", "PimpDatabase", "PimpPackage", "main",
+__all__ = ["PimpPreferences", "PimpDatabase", "PimpPackage", "main",
"PIMP_VERSION", "main"]
_scriptExc_NotInstalled = "pimp._scriptExc_NotInstalled"
@@ -52,12 +52,12 @@ def getDefaultDatabase(experimental=False):
status = "exp"
else:
status = "prod"
-
+
major, minor, micro, state, extra = sys.version_info
pyvers = '%d.%d' % (major, minor)
if state != 'final':
pyvers = pyvers + '%s%d' % (state, extra)
-
+
longplatform = distutils.util.get_platform()
osname, release, machine = longplatform.split('-')
# For some platforms we may want to differentiate between
@@ -94,7 +94,7 @@ def getDefaultDatabase(experimental=False):
def _cmd(output, dir, *cmditems):
"""Internal routine to run a shell command in a given directory."""
-
+
cmd = ("cd \"%s\"; " % dir) + " ".join(cmditems)
if output:
output.write("+ %s\n" % cmd)
@@ -112,22 +112,22 @@ def _cmd(output, dir, *cmditems):
class PimpDownloader:
"""Abstract base class - Downloader for archives"""
-
+
def __init__(self, argument,
dir="",
watcher=None):
self.argument = argument
self._dir = dir
self._watcher = watcher
-
+
def download(self, url, filename, output=None):
return None
-
+
def update(self, str):
if self._watcher:
return self._watcher.update(str)
return True
-
+
class PimpCurlDownloader(PimpDownloader):
def download(self, url, filename, output=None):
@@ -138,7 +138,7 @@ class PimpCurlDownloader(PimpDownloader):
url)
self.update("Downloading %s: finished" % url)
return (not exitstatus)
-
+
class PimpUrllibDownloader(PimpDownloader):
def download(self, url, filename, output=None):
@@ -150,13 +150,13 @@ class PimpUrllibDownloader(PimpDownloader):
length = long(download.headers['content-length'])
else:
length = -1
-
+
data = download.read(4096) #read 4K at a time
dlsize = 0
lasttime = 0
while keepgoing:
dlsize = dlsize + len(data)
- if len(data) == 0:
+ if len(data) == 0:
#this is our exit condition
break
output.write(data)
@@ -171,12 +171,12 @@ class PimpUrllibDownloader(PimpDownloader):
if keepgoing:
self.update("Downloading %s: finished" % url)
return keepgoing
-
+
class PimpUnpacker:
"""Abstract base class - Unpacker for archives"""
-
+
_can_rename = False
-
+
def __init__(self, argument,
dir="",
renames=[],
@@ -187,30 +187,30 @@ class PimpUnpacker:
self._dir = dir
self._renames = renames
self._watcher = watcher
-
+
def unpack(self, archive, output=None, package=None):
return None
-
+
def update(self, str):
if self._watcher:
return self._watcher.update(str)
return True
-
+
class PimpCommandUnpacker(PimpUnpacker):
"""Unpack archives by calling a Unix utility"""
-
+
_can_rename = False
-
+
def unpack(self, archive, output=None, package=None):
cmd = self.argument % archive
if _cmd(output, self._dir, cmd):
return "unpack command failed"
-
+
class PimpTarUnpacker(PimpUnpacker):
"""Unpack tarfiles using the builtin tarfile module"""
-
+
_can_rename = True
-
+
def unpack(self, archive, output=None, package=None):
tf = tarfile.open(archive, "r")
members = tf.getmembers()
@@ -253,7 +253,7 @@ class PimpTarUnpacker(PimpUnpacker):
names = package.filterExpectedSkips(names)
if names:
return "Not all files were unpacked: %s" % " ".join(names)
-
+
ARCHIVE_FORMATS = [
(".tar.Z", PimpTarUnpacker, None),
(".taz", PimpTarUnpacker, None),
@@ -266,8 +266,8 @@ ARCHIVE_FORMATS = [
class PimpPreferences:
"""Container for per-user preferences, such as the database to use
and where to install packages."""
-
- def __init__(self,
+
+ def __init__(self,
flavorOrder=None,
downloadDir=None,
buildDir=None,
@@ -287,10 +287,10 @@ class PimpPreferences:
self.buildDir = buildDir
self.pimpDatabase = pimpDatabase
self.watcher = None
-
+
def setWatcher(self, watcher):
self.watcher = watcher
-
+
def setInstallDir(self, installDir=None):
if installDir:
# Installing to non-standard location.
@@ -303,14 +303,14 @@ class PimpPreferences:
installDir = DEFAULT_INSTALLDIR
self.installLocations = []
self.installDir = installDir
-
+
def isUserInstall(self):
return self.installDir != DEFAULT_INSTALLDIR
def check(self):
"""Check that the preferences make sense: directories exist and are
writable, the install directory is on sys.path, etc."""
-
+
rv = ""
RWX_OK = os.R_OK|os.W_OK|os.X_OK
if not os.path.exists(self.downloadDir):
@@ -337,7 +337,7 @@ class PimpPreferences:
else:
rv += "Warning: Install directory \"%s\" is not on sys.path\n" % self.installDir
return rv
-
+
def compareFlavors(self, left, right):
"""Compare two flavor strings. This is part of your preferences
because whether the user prefers installing from source or binary is."""
@@ -348,13 +348,13 @@ class PimpPreferences:
if right in self.flavorOrder:
return 1
return cmp(left, right)
-
+
class PimpDatabase:
"""Class representing a pimp database. It can actually contain
information from multiple databases through inclusion, but the
toplevel database is considered the master, as its maintainer is
"responsible" for the contents."""
-
+
def __init__(self, prefs):
self._packages = []
self.preferences = prefs
@@ -363,23 +363,23 @@ class PimpDatabase:
self._version = ""
self._maintainer = ""
self._description = ""
-
+
# Accessor functions
def url(self): return self._url
def version(self): return self._version
def maintainer(self): return self._maintainer
def description(self): return self._description
-
+
def close(self):
"""Clean up"""
self._packages = []
self.preferences = None
-
+
def appendURL(self, url, included=0):
"""Append packages from the database with the given URL.
Only the first database should specify included=0, so the
global information (maintainer, description) get stored."""
-
+
if url in self._urllist:
return
self._urllist.append(url)
@@ -396,7 +396,7 @@ class PimpDatabase:
if not self._version:
sys.stderr.write("Warning: database has no Version information\n")
elif self._version > PIMP_VERSION:
- sys.stderr.write("Warning: database version %s newer than pimp version %s\n"
+ sys.stderr.write("Warning: database version %s newer than pimp version %s\n"
% (self._version, PIMP_VERSION))
self._maintainer = plistdata.get('Maintainer', '')
self._description = plistdata.get('Description', '').strip()
@@ -405,12 +405,12 @@ class PimpDatabase:
others = plistdata.get('Include', [])
for url in others:
self.appendURL(url, included=1)
-
+
def _appendPackages(self, packages):
"""Given a list of dictionaries containing package
descriptions create the PimpPackage objects and append them
to our internal storage."""
-
+
for p in packages:
p = dict(p)
flavor = p.get('Flavor')
@@ -421,27 +421,27 @@ class PimpDatabase:
else:
pkg = PimpPackage(self, dict(p))
self._packages.append(pkg)
-
+
def list(self):
"""Return a list of all PimpPackage objects in the database."""
-
+
return self._packages
-
+
def listnames(self):
"""Return a list of names of all packages in the database."""
-
+
rv = []
for pkg in self._packages:
rv.append(pkg.fullname())
rv.sort()
return rv
-
+
def dump(self, pathOrFile):
"""Dump the contents of the database to an XML .plist file.
-
+
The file can be passed as either a file object or a pathname.
All data, including included databases, is dumped."""
-
+
packages = []
for pkg in self._packages:
packages.append(pkg.dump())
@@ -453,15 +453,15 @@ class PimpDatabase:
}
plist = plistlib.Plist(**plistdata)
plist.write(pathOrFile)
-
+
def find(self, ident):
"""Find a package. The package can be specified by name
or as a dictionary with name, version and flavor entries.
-
+
Only name is obligatory. If there are multiple matches the
best one (higher version number, flavors ordered according to
users' preference) is returned."""
-
+
if type(ident) == str:
# Remove ( and ) for pseudo-packages
if ident[0] == '(' and ident[-1] == ')':
@@ -491,7 +491,7 @@ class PimpDatabase:
if not found or found < p:
found = p
return found
-
+
ALLOWED_KEYS = [
"Name",
"Version",
@@ -511,7 +511,7 @@ ALLOWED_KEYS = [
class PimpPackage:
"""Class representing a single package."""
-
+
def __init__(self, db, plistdata):
self._db = db
name = plistdata["Name"]
@@ -519,10 +519,10 @@ class PimpPackage:
if not k in ALLOWED_KEYS:
sys.stderr.write("Warning: %s: unknown key %s\n" % (name, k))
self._dict = plistdata
-
+
def __getitem__(self, key):
return self._dict[key]
-
+
def name(self): return self._dict['Name']
def version(self): return self._dict.get('Version')
def flavor(self): return self._dict.get('Flavor')
@@ -531,13 +531,13 @@ class PimpPackage:
def homepage(self): return self._dict.get('Home-page')
def downloadURL(self): return self._dict.get('Download-URL')
def systemwideOnly(self): return self._dict.get('Systemwide-only')
-
+
def fullname(self):
"""Return the full name "name-version-flavor" of a package.
-
+
If the package is a pseudo-package, something that cannot be
installed through pimp, return the name in (parentheses)."""
-
+
rv = self._dict['Name']
if self._dict.has_key('Version'):
rv = rv + '-%s' % self._dict['Version']
@@ -547,14 +547,14 @@ class PimpPackage:
# Pseudo-package, show in parentheses
rv = '(%s)' % rv
return rv
-
+
def dump(self):
"""Return a dict object containing the information on the package."""
return self._dict
-
+
def __cmp__(self, other):
"""Compare two packages, where the "better" package sorts lower."""
-
+
if not isinstance(other, PimpPackage):
return cmp(id(self), id(other))
if self.name() != other.name():
@@ -562,15 +562,15 @@ class PimpPackage:
if self.version() != other.version():
return -cmp(self.version(), other.version())
return self._db.preferences.compareFlavors(self.flavor(), other.flavor())
-
+
def installed(self):
"""Test wheter the package is installed.
-
+
Returns two values: a status indicator which is one of
"yes", "no", "old" (an older version is installed) or "bad"
(something went wrong during the install test) and a human
readable string which may contain more details."""
-
+
namespace = {
"NotInstalled": _scriptExc_NotInstalled,
"OldInstalled": _scriptExc_OldInstalled,
@@ -602,16 +602,16 @@ class PimpPackage:
sys.stderr.write("-------------------------------------\n")
return "bad", "Package install test got exception"
return "yes", ""
-
+
def prerequisites(self):
"""Return a list of prerequisites for this package.
-
+
The list contains 2-tuples, of which the first item is either
a PimpPackage object or None, and the second is a descriptive
string. The first item can be None if this package depends on
something that isn't pimp-installable, in which case the descriptive
string should tell the user what to do."""
-
+
rv = []
if not self._dict.get('Download-URL'):
# For pseudo-packages that are already installed we don't
@@ -619,7 +619,7 @@ class PimpPackage:
status, _ = self.installed()
if status == "yes":
return []
- return [(None,
+ return [(None,
"%s: This package cannot be installed automatically (no Download-URL field)" %
self.fullname())]
if self.systemwideOnly() and self._db.preferences.isUserInstall():
@@ -645,28 +645,28 @@ class PimpPackage:
descr = pkg.shortdescription()
rv.append((pkg, descr))
return rv
-
-
+
+
def downloadPackageOnly(self, output=None):
"""Download a single package, if needed.
-
+
An MD5 signature is used to determine whether download is needed,
and to test that we actually downloaded what we expected.
If output is given it is a file-like object that will receive a log
of what happens.
-
+
If anything unforeseen happened the method returns an error message
string.
"""
-
+
scheme, loc, path, query, frag = urlparse.urlsplit(self._dict['Download-URL'])
path = urllib.url2pathname(path)
filename = os.path.split(path)[1]
- self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename)
+ self.archiveFilename = os.path.join(self._db.preferences.downloadDir, filename)
if not self._archiveOK():
if scheme == 'manual':
return "Please download package manually and save as %s" % self.archiveFilename
- downloader = PimpUrllibDownloader(None, self._db.preferences.downloadDir,
+ downloader = PimpUrllibDownloader(None, self._db.preferences.downloadDir,
watcher=self._db.preferences.watcher)
if not downloader.download(self._dict['Download-URL'],
self.archiveFilename, output):
@@ -675,10 +675,10 @@ class PimpPackage:
return "archive not found after download"
if not self._archiveOK():
return "archive does not have correct MD5 checksum"
-
+
def _archiveOK(self):
"""Test an archive. It should exist and the MD5 checksum should be correct."""
-
+
if not os.path.exists(self.archiveFilename):
return 0
if not self._dict.get('MD5Sum'):
@@ -687,10 +687,10 @@ class PimpPackage:
data = open(self.archiveFilename, 'rb').read()
checksum = md5.new(data).hexdigest()
return checksum == self._dict['MD5Sum']
-
+
def unpackPackageOnly(self, output=None):
"""Unpack a downloaded package archive."""
-
+
filename = os.path.split(self.archiveFilename)[1]
for ext, unpackerClass, arg in ARCHIVE_FORMATS:
if filename[-len(ext):] == ext:
@@ -698,43 +698,43 @@ class PimpPackage:
else:
return "unknown extension for archive file: %s" % filename
self.basename = filename[:-len(ext)]
- unpacker = unpackerClass(arg, dir=self._db.preferences.buildDir,
+ unpacker = unpackerClass(arg, dir=self._db.preferences.buildDir,
watcher=self._db.preferences.watcher)
rv = unpacker.unpack(self.archiveFilename, output=output)
if rv:
return rv
-
+
def installPackageOnly(self, output=None):
"""Default install method, to be overridden by subclasses"""
return "%s: This package needs to be installed manually (no support for flavor=\"%s\")" \
% (self.fullname(), self._dict.get(flavor, ""))
-
+
def installSinglePackage(self, output=None):
"""Download, unpack and install a single package.
-
+
If output is given it should be a file-like object and it
will receive a log of what happened."""
-
+
if not self._dict.get('Download-URL'):
return "%s: This package needs to be installed manually (no Download-URL field)" % self.fullname()
msg = self.downloadPackageOnly(output)
if msg:
return "%s: download: %s" % (self.fullname(), msg)
-
+
msg = self.unpackPackageOnly(output)
if msg:
return "%s: unpack: %s" % (self.fullname(), msg)
-
+
return self.installPackageOnly(output)
-
+
def beforeInstall(self):
"""Bookkeeping before installation: remember what we have in site-packages"""
self._old_contents = os.listdir(self._db.preferences.installDir)
-
+
def afterInstall(self):
"""Bookkeeping after installation: interpret any new .pth files that have
appeared"""
-
+
new_contents = os.listdir(self._db.preferences.installDir)
for fn in new_contents:
if fn in self._old_contents:
@@ -757,7 +757,7 @@ class PimpPackage:
line = os.path.join(self._db.preferences.installDir, line)
line = os.path.realpath(line)
if not line in sys.path:
- sys.path.append(line)
+ sys.path.append(line)
def filterExpectedSkips(self, names):
"""Return a list that contains only unpexpected skips"""
@@ -780,21 +780,21 @@ class PimpPackage_binary(PimpPackage):
def unpackPackageOnly(self, output=None):
"""We don't unpack binary packages until installing"""
pass
-
+
def installPackageOnly(self, output=None):
"""Install a single source package.
-
+
If output is given it should be a file-like object and it
will receive a log of what happened."""
-
+
if self._dict.has_key('Install-command'):
return "%s: Binary package cannot have Install-command" % self.fullname()
-
+
if self._dict.has_key('Pre-install-command'):
if _cmd(output, self._buildDirname, self._dict['Pre-install-command']):
return "pre-install %s: running \"%s\" failed" % \
(self.fullname(), self._dict['Pre-install-command'])
-
+
self.beforeInstall()
# Install by unpacking
@@ -805,7 +805,7 @@ class PimpPackage_binary(PimpPackage):
else:
return "%s: unknown extension for archive file: %s" % (self.fullname(), filename)
self.basename = filename[:-len(ext)]
-
+
install_renames = []
for k, newloc in self._db.preferences.installLocations:
if not newloc:
@@ -815,22 +815,22 @@ class PimpPackage_binary(PimpPackage):
else:
return "%s: Don't know installLocation %s" % (self.fullname(), k)
install_renames.append((oldloc, newloc))
-
+
unpacker = unpackerClass(arg, dir="/", renames=install_renames)
rv = unpacker.unpack(self.archiveFilename, output=output, package=self)
if rv:
return rv
-
+
self.afterInstall()
-
+
if self._dict.has_key('Post-install-command'):
if _cmd(output, self._buildDirname, self._dict['Post-install-command']):
return "%s: post-install: running \"%s\" failed" % \
(self.fullname(), self._dict['Post-install-command'])
return None
-
-
+
+
class PimpPackage_source(PimpPackage):
def unpackPackageOnly(self, output=None):
@@ -844,15 +844,15 @@ class PimpPackage_source(PimpPackage):
def installPackageOnly(self, output=None):
"""Install a single source package.
-
+
If output is given it should be a file-like object and it
will receive a log of what happened."""
-
+
if self._dict.has_key('Pre-install-command'):
if _cmd(output, self._buildDirname, self._dict['Pre-install-command']):
return "pre-install %s: running \"%s\" failed" % \
(self.fullname(), self._dict['Pre-install-command'])
-
+
self.beforeInstall()
installcmd = self._dict.get('Install-command')
if installcmd and self._install_renames:
@@ -882,45 +882,45 @@ class PimpPackage_source(PimpPackage):
rv = None
shutil.rmtree(unwanted_install_dir)
return rv
-
+
self.afterInstall()
-
+
if self._dict.has_key('Post-install-command'):
if _cmd(output, self._buildDirname, self._dict['Post-install-command']):
return "post-install %s: running \"%s\" failed" % \
(self.fullname(), self._dict['Post-install-command'])
return None
-
-
+
+
class PimpInstaller:
"""Installer engine: computes dependencies and installs
packages in the right order."""
-
+
def __init__(self, db):
self._todo = []
self._db = db
self._curtodo = []
self._curmessages = []
-
+
def __contains__(self, package):
return package in self._todo
-
+
def _addPackages(self, packages):
for package in packages:
if not package in self._todo:
self._todo.append(package)
-
+
def _prepareInstall(self, package, force=0, recursive=1):
"""Internal routine, recursive engine for prepareInstall.
-
+
Test whether the package is installed and (if not installed
or if force==1) prepend it to the temporary todo list and
call ourselves recursively on all prerequisites."""
-
+
if not force:
status, message = package.installed()
if status == "yes":
- return
+ return
if package in self._todo or package in self._curtodo:
return
self._curtodo.insert(0, package)
@@ -932,17 +932,17 @@ class PimpInstaller:
self._prepareInstall(pkg, False, recursive)
else:
self._curmessages.append("Problem with dependency: %s" % descr)
-
+
def prepareInstall(self, package, force=0, recursive=1):
"""Prepare installation of a package.
-
+
If the package is already installed and force is false nothing
is done. If recursive is true prerequisites are installed first.
-
+
Returns a list of packages (to be passed to install) and a list
of messages of any problems encountered.
"""
-
+
self._curtodo = []
self._curmessages = []
self._prepareInstall(package, force, recursive)
@@ -950,10 +950,10 @@ class PimpInstaller:
self._curtodo = []
self._curmessages = []
return rv
-
+
def install(self, packages, output):
"""Install a list of packages."""
-
+
self._addPackages(packages)
status = []
for pkg in self._todo:
@@ -961,12 +961,12 @@ class PimpInstaller:
if msg:
status.append(msg)
return status
-
-
-
+
+
+
def _run(mode, verbose, force, args, prefargs, watcher):
"""Engine for the main program"""
-
+
prefs = PimpPreferences(**prefargs)
if watcher:
prefs.setWatcher(watcher)
@@ -975,7 +975,7 @@ def _run(mode, verbose, force, args, prefargs, watcher):
sys.stdout.write(rv)
db = PimpDatabase(prefs)
db.appendURL(prefs.pimpDatabase)
-
+
if mode == 'dump':
db.dump(sys.stdout)
elif mode =='list':
@@ -1050,7 +1050,7 @@ def _run(mode, verbose, force, args, prefargs, watcher):
def main():
"""Minimal commandline tool to drive pimp."""
-
+
import getopt
def _help():
print "Usage: pimp [options] -s [package ...] List installed status"
@@ -1065,12 +1065,12 @@ def main():
print " (default: %s)" % DEFAULT_INSTALLDIR
print " -u url URL for database"
sys.exit(1)
-
+
class _Watcher:
def update(self, msg):
sys.stderr.write(msg + '\r')
return 1
-
+
try:
opts, args = getopt.getopt(sys.argv[1:], "slifvdD:Vu:")
except getopt.GetoptError:
@@ -1133,8 +1133,6 @@ if __name__ != 'pimp_update':
(pimp_update.PIMP_VERSION, PIMP_VERSION))
else:
from pimp_update import *
-
+
if __name__ == '__main__':
main()
-
-
diff --git a/Lib/plat-mac/videoreader.py b/Lib/plat-mac/videoreader.py
index 646c72628d..f16228b828 100644
--- a/Lib/plat-mac/videoreader.py
+++ b/Lib/plat-mac/videoreader.py
@@ -34,19 +34,19 @@ class VideoFormat:
self.__width = width
self.__height = height
self.__format = format
-
+
def getname(self):
return self.__name
-
+
def getdescr(self):
return self.__descr
-
+
def getsize(self):
return self.__width, self.__height
-
+
def getformat(self):
return self.__format
-
+
class _Reader:
def __init__(self, path):
fd = Qt.OpenMovieFile(path, 0)
@@ -66,8 +66,8 @@ class _Reader:
self.audiodescr = _audiodescr(handle.data)
self.audiotimescale = self.audiomedia.GetMediaTimeScale()
del handle
-
- try:
+
+ try:
self.videotrack = self.movie.GetMovieIndTrackType(1,
QuickTime.VisualMediaCharacteristic, QuickTime.movieTrackCharacteristic)
self.videomedia = self.videotrack.GetTrackMedia()
@@ -81,14 +81,14 @@ class _Reader:
self.videocurtime = None
self.audiocurtime = None
-
+
def __del__(self):
self.audiomedia = None
self.audiotrack = None
self.videomedia = None
self.videotrack = None
self.movie = None
-
+
def _initgworld(self):
old_port, old_dev = Qdoffs.GetGWorld()
try:
@@ -108,34 +108,34 @@ class _Reader:
# XXXX framerate
finally:
Qdoffs.SetGWorld(old_port, old_dev)
-
+
def _gettrackduration_ms(self, track):
tracktime = track.GetTrackDuration()
return self._movietime_to_ms(tracktime)
-
+
def _movietime_to_ms(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.movietimescale, None), 1000)
return value
-
+
def _videotime_to_ms(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.videotimescale, None), 1000)
return value
-
+
def _audiotime_to_ms(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.audiotimescale, None), 1000)
return value
-
+
def _videotime_to_movietime(self, time):
value, d1, d2 = Qt.ConvertTimeScale((time, self.videotimescale, None),
self.movietimescale)
return value
-
+
def HasAudio(self):
return not self.audiotrack is None
-
+
def HasVideo(self):
return not self.videotrack is None
-
+
def GetAudioDuration(self):
if not self.audiotrack:
return 0
@@ -145,7 +145,7 @@ class _Reader:
if not self.videotrack:
return 0
return self._gettrackduration_ms(self.videotrack)
-
+
def GetAudioFormat(self):
if not self.audiodescr:
return None, None, None, None, None
@@ -172,20 +172,20 @@ class _Reader:
encoding = 'linear-signed'
else:
encoding = 'quicktime-coding-%s'%self.audiodescr['dataFormat']
-## return audio.format.AudioFormatLinear('quicktime_audio', 'QuickTime Audio Format',
+## return audio.format.AudioFormatLinear('quicktime_audio', 'QuickTime Audio Format',
## channels, encoding, blocksize=blocksize, fpb=fpb, bps=bps)
return channels, encoding, blocksize, fpb, bps
-
+
def GetAudioFrameRate(self):
if not self.audiodescr:
return None
return int(self.audiodescr['sampleRate'])
-
+
def GetVideoFormat(self):
width = self.videodescr['width']
height = self.videodescr['height']
return VideoFormat('dummy_format', 'Dummy Video Format', width, height, macrgb)
-
+
def GetVideoFrameRate(self):
tv = self.videocurtime
if tv == None:
@@ -194,7 +194,7 @@ class _Reader:
tv, dur = self.videomedia.GetMediaNextInterestingTime(flags, tv, 1.0)
dur = self._videotime_to_ms(dur)
return int((1000.0/dur)+0.5)
-
+
def ReadAudio(self, nframes, time=None):
if not time is None:
self.audiocurtime = time
@@ -210,7 +210,7 @@ class _Reader:
self.audiomedia.GetMediaSample(h, 0, tv, desc_h, nframes)
self.audiocurtime = actualtime + actualcount*sampleduration
return self._audiotime_to_ms(actualtime), h.data
-
+
def ReadVideo(self, time=None):
if not time is None:
self.videocurtime = time
@@ -226,7 +226,7 @@ class _Reader:
self.movie.SetMovieTimeValue(moviecurtime)
self.movie.MoviesTask(0)
return self._videotime_to_ms(self.videocurtime), self._getpixmapcontent()
-
+
def _getpixmapcontent(self):
"""Shuffle the offscreen PixMap data, because it may have funny stride values"""
rowbytes = Qdoffs.GetPixRowBytes(self.pixmap)
@@ -281,12 +281,11 @@ def _test():
wrt.write(data)
timestamp, data = rdr.ReadVideo()
MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG')
- if num > 20:
+ if num > 20:
print 'stopping at 20 frames so your disk does not fill up:-)'
break
print 'Total frames:', num
-
+
if __name__ == '__main__':
_test()
sys.exit(1)
-
diff --git a/Lib/plat-netbsd1/IN.py b/Lib/plat-netbsd1/IN.py
index 020f8e2e85..474c51e6d9 100644
--- a/Lib/plat-netbsd1/IN.py
+++ b/Lib/plat-netbsd1/IN.py
@@ -54,4 +54,3 @@ IPCTL_DIRECTEDBCAST = 6
IPCTL_ALLOWSRCRT = 7
IPCTL_MAXID = 8
def in_nullhost(x): return ((x).s_addr == INADDR_ANY)
-
diff --git a/Lib/plat-os2emx/_emx_link.py b/Lib/plat-os2emx/_emx_link.py
index 04648e2b21..422c2bbf6f 100644
--- a/Lib/plat-os2emx/_emx_link.py
+++ b/Lib/plat-os2emx/_emx_link.py
@@ -2,7 +2,7 @@
# Written by Andrew I MacIntyre, December 2002.
-"""_emx_link.py is a simplistic emulation of the Unix link(2) library routine
+"""_emx_link.py is a simplistic emulation of the Unix link(2) library routine
for creating so-called hard links. It is intended to be imported into
the os module in place of the unimplemented (on OS/2) Posix link()
function (os.link()).
diff --git a/Lib/plat-os2emx/grp.py b/Lib/plat-os2emx/grp.py
index d05ad2765d..fceb4c94f9 100644
--- a/Lib/plat-os2emx/grp.py
+++ b/Lib/plat-os2emx/grp.py
@@ -4,10 +4,10 @@
# written by Andrew MacIntyre, April 2001.
# updated July 2003, adding field accessor support
-# note that this implementation checks whether ":" or ";" as used as
+# note that this implementation checks whether ":" or ";" as used as
# the field separator character.
-"""Replacement for grp standard extension module, intended for use on
+"""Replacement for grp standard extension module, intended for use on
OS/2 and similar systems which don't normally have an /etc/group file.
The standard Unix group database is an ASCII text file with 4 fields per
@@ -17,16 +17,16 @@ record (line), separated by a colon:
- group id (integer)
- group members (comma delimited list of userids, with no spaces)
-Note that members are only included in the group file for groups that
+Note that members are only included in the group file for groups that
aren't their primary groups.
(see the section 8.2 of the Python Library Reference)
-This implementation differs from the standard Unix implementation by
-allowing use of the platform's native path separator character - ';' on OS/2,
-DOS and MS-Windows - as the field separator in addition to the Unix
+This implementation differs from the standard Unix implementation by
+allowing use of the platform's native path separator character - ';' on OS/2,
+DOS and MS-Windows - as the field separator in addition to the Unix
standard ":".
-The module looks for the group database at the following locations
+The module looks for the group database at the following locations
(in order first to last):
- ${ETC_GROUP} (or %ETC_GROUP%)
- ${ETC}/group (or %ETC%/group)
diff --git a/Lib/plat-os2emx/pwd.py b/Lib/plat-os2emx/pwd.py
index 1036fcef36..95d766a79c 100644
--- a/Lib/plat-os2emx/pwd.py
+++ b/Lib/plat-os2emx/pwd.py
@@ -4,14 +4,14 @@
# written by Andrew MacIntyre, April 2001.
# updated July 2003, adding field accessor support
-# note that this implementation checks whether ":" or ";" as used as
+# note that this implementation checks whether ":" or ";" as used as
# the field separator character. Path conversions are are applied when
# the database uses ":" as the field separator character.
-"""Replacement for pwd standard extension module, intended for use on
+"""Replacement for pwd standard extension module, intended for use on
OS/2 and similar systems which don't normally have an /etc/passwd file.
-The standard Unix password database is an ASCII text file with 7 fields
+The standard Unix password database is an ASCII text file with 7 fields
per record (line), separated by a colon:
- user name (string)
- password (encrypted string, or "*" or "")
@@ -23,13 +23,13 @@ per record (line), separated by a colon:
(see the section 8.1 of the Python Library Reference)
-This implementation differs from the standard Unix implementation by
-allowing use of the platform's native path separator character - ';' on OS/2,
-DOS and MS-Windows - as the field separator in addition to the Unix
-standard ":". Additionally, when ":" is the separator path conversions
+This implementation differs from the standard Unix implementation by
+allowing use of the platform's native path separator character - ';' on OS/2,
+DOS and MS-Windows - as the field separator in addition to the Unix
+standard ":". Additionally, when ":" is the separator path conversions
are applied to deal with any munging of the drive letter reference.
-The module looks for the password database at the following locations
+The module looks for the password database at the following locations
(in order first to last):
- ${ETC_PASSWD} (or %ETC_PASSWD%)
- ${ETC}/passwd (or %ETC%/passwd)
@@ -94,8 +94,8 @@ def __unixpathconv(path):
# decide what field separator we can try to use - Unix standard, with
# the platform's path separator as an option. No special field conversion
-# handler is required when using the platform's path separator as field
-# separator, but are required for the home directory and shell fields when
+# handler is required when using the platform's path separator as field
+# separator, but are required for the home directory and shell fields when
# using the standard Unix (":") field separator.
__field_sep = {':': __unixpathconv}
if os.pathsep:
diff --git a/Lib/plat-riscos/rourl2path.py b/Lib/plat-riscos/rourl2path.py
index 494e394ffa..7642b9f21f 100644
--- a/Lib/plat-riscos/rourl2path.py
+++ b/Lib/plat-riscos/rourl2path.py
@@ -25,7 +25,7 @@ def url2pathname(url):
if '$' in components:
del components[0]
else:
- components[0] = '$'
+ components[0] = '$'
# Remove . and embedded ..
i = 0
while i < len(components):
diff --git a/Lib/plat-sunos5/IN.py b/Lib/plat-sunos5/IN.py
index 7e26187ca5..867b9eb5f8 100755
--- a/Lib/plat-sunos5/IN.py
+++ b/Lib/plat-sunos5/IN.py
@@ -836,7 +836,7 @@ TS_PSTART = 0x0800
TS_RESUME = 0x1000
TS_CREATE = 0x2000
TS_ALLSTART = \
- (TS_CSTART|TS_UNPAUSE|TS_XSTART|TS_PSTART|TS_RESUME|TS_CREATE)
+ (TS_CSTART|TS_UNPAUSE|TS_XSTART|TS_PSTART|TS_RESUME|TS_CREATE)
def CPR_VSTOPPED(t): return \
def THREAD_TRANSITION(tp): return thread_transition(tp);
@@ -1014,13 +1014,13 @@ AT_BLKSIZE = 0x1000
AT_NBLOCKS = 0x2000
AT_VCODE = 0x4000
AT_ALL = (AT_TYPE|AT_MODE|AT_UID|AT_GID|AT_FSID|AT_NODEID|\
- AT_NLINK|AT_SIZE|AT_ATIME|AT_MTIME|AT_CTIME|\
- AT_RDEV|AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
+ AT_NLINK|AT_SIZE|AT_ATIME|AT_MTIME|AT_CTIME|\
+ AT_RDEV|AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
AT_STAT = (AT_MODE|AT_UID|AT_GID|AT_FSID|AT_NODEID|AT_NLINK|\
- AT_SIZE|AT_ATIME|AT_MTIME|AT_CTIME|AT_RDEV)
+ AT_SIZE|AT_ATIME|AT_MTIME|AT_CTIME|AT_RDEV)
AT_TIMES = (AT_ATIME|AT_MTIME|AT_CTIME)
AT_NOSET = (AT_NLINK|AT_RDEV|AT_FSID|AT_NODEID|AT_TYPE|\
- AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
+ AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
VSUID = 04000
VSGID = 02000
VSVTX = 01000
diff --git a/Lib/plat-sunos5/STROPTS.py b/Lib/plat-sunos5/STROPTS.py
index 19173bb9e6..e95db932d1 100644
--- a/Lib/plat-sunos5/STROPTS.py
+++ b/Lib/plat-sunos5/STROPTS.py
@@ -833,7 +833,7 @@ TS_PSTART = 0x0800
TS_RESUME = 0x1000
TS_CREATE = 0x2000
TS_ALLSTART = \
- (TS_CSTART|TS_UNPAUSE|TS_XSTART|TS_PSTART|TS_RESUME|TS_CREATE)
+ (TS_CSTART|TS_UNPAUSE|TS_XSTART|TS_PSTART|TS_RESUME|TS_CREATE)
def CPR_VSTOPPED(t): return \
def THREAD_TRANSITION(tp): return thread_transition(tp);
@@ -1393,13 +1393,13 @@ AT_BLKSIZE = 0x1000
AT_NBLOCKS = 0x2000
AT_VCODE = 0x4000
AT_ALL = (AT_TYPE|AT_MODE|AT_UID|AT_GID|AT_FSID|AT_NODEID|\
- AT_NLINK|AT_SIZE|AT_ATIME|AT_MTIME|AT_CTIME|\
- AT_RDEV|AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
+ AT_NLINK|AT_SIZE|AT_ATIME|AT_MTIME|AT_CTIME|\
+ AT_RDEV|AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
AT_STAT = (AT_MODE|AT_UID|AT_GID|AT_FSID|AT_NODEID|AT_NLINK|\
- AT_SIZE|AT_ATIME|AT_MTIME|AT_CTIME|AT_RDEV)
+ AT_SIZE|AT_ATIME|AT_MTIME|AT_CTIME|AT_RDEV)
AT_TIMES = (AT_ATIME|AT_MTIME|AT_CTIME)
AT_NOSET = (AT_NLINK|AT_RDEV|AT_FSID|AT_NODEID|AT_TYPE|\
- AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
+ AT_BLKSIZE|AT_NBLOCKS|AT_VCODE)
VSUID = 04000
VSGID = 02000
VSVTX = 01000
@@ -1682,14 +1682,14 @@ DDI_PROP_TYPE_INT = 0x0100
DDI_PROP_TYPE_STRING = 0x0200
DDI_PROP_TYPE_BYTE = 0x0400
DDI_PROP_TYPE_COMPOSITE = 0x0800
-DDI_PROP_TYPE_ANY = (DDI_PROP_TYPE_INT | \
- DDI_PROP_TYPE_STRING | \
- DDI_PROP_TYPE_BYTE | \
- DDI_PROP_TYPE_COMPOSITE)
-DDI_PROP_TYPE_MASK = (DDI_PROP_TYPE_INT | \
- DDI_PROP_TYPE_STRING | \
- DDI_PROP_TYPE_BYTE | \
- DDI_PROP_TYPE_COMPOSITE)
+DDI_PROP_TYPE_ANY = (DDI_PROP_TYPE_INT | \
+ DDI_PROP_TYPE_STRING | \
+ DDI_PROP_TYPE_BYTE | \
+ DDI_PROP_TYPE_COMPOSITE)
+DDI_PROP_TYPE_MASK = (DDI_PROP_TYPE_INT | \
+ DDI_PROP_TYPE_STRING | \
+ DDI_PROP_TYPE_BYTE | \
+ DDI_PROP_TYPE_COMPOSITE)
DDI_RELATIVE_ADDRESSING = "relative-addressing"
DDI_GENERIC_ADDRESSING = "generic-addressing"
@@ -1704,7 +1704,7 @@ DEVMAP_MAPPING_INVALID = 0x01
DEVMAP_ALLOW_REMAP = 0x02
DEVMAP_USE_PAGESIZE = 0x04
DEVMAP_SETUP_FLAGS = \
- (DEVMAP_MAPPING_INVALID | DEVMAP_ALLOW_REMAP | DEVMAP_USE_PAGESIZE)
+ (DEVMAP_MAPPING_INVALID | DEVMAP_ALLOW_REMAP | DEVMAP_USE_PAGESIZE)
DEVMAP_SETUP_DONE = 0x100
DEVMAP_LOCK_INITED = 0x200
DEVMAP_FAULTING = 0x400
diff --git a/Lib/plat-sunos5/SUNAUDIODEV.py b/Lib/plat-sunos5/SUNAUDIODEV.py
index a81a2abd0a..632139f87d 100755
--- a/Lib/plat-sunos5/SUNAUDIODEV.py
+++ b/Lib/plat-sunos5/SUNAUDIODEV.py
@@ -6,21 +6,21 @@
# Encoding types, for fields i_encoding and o_encoding
-ENCODING_NONE = 0 # no encoding assigned
-ENCODING_ULAW = 1 # u-law encoding
-ENCODING_ALAW = 2 # A-law encoding
-ENCODING_LINEAR = 3 # Linear PCM encoding
+ENCODING_NONE = 0 # no encoding assigned
+ENCODING_ULAW = 1 # u-law encoding
+ENCODING_ALAW = 2 # A-law encoding
+ENCODING_LINEAR = 3 # Linear PCM encoding
# Gain ranges for i_gain, o_gain and monitor_gain
-MIN_GAIN = 0 # minimum gain value
-MAX_GAIN = 255 # maximum gain value
+MIN_GAIN = 0 # minimum gain value
+MAX_GAIN = 255 # maximum gain value
# Balance values for i_balance and o_balance
-LEFT_BALANCE = 0 # left channel only
-MID_BALANCE = 32 # equal left/right channel
-RIGHT_BALANCE = 64 # right channel only
+LEFT_BALANCE = 0 # left channel only
+MID_BALANCE = 32 # equal left/right channel
+RIGHT_BALANCE = 64 # right channel only
BALANCE_SHIFT = 3
# Port names for i_port and o_port
@@ -30,11 +30,11 @@ PORT_B = 2
PORT_C = 3
PORT_D = 4
-SPEAKER = 0x01 # output to built-in speaker
-HEADPHONE = 0x02 # output to headphone jack
-LINE_OUT = 0x04 # output to line out
+SPEAKER = 0x01 # output to built-in speaker
+HEADPHONE = 0x02 # output to headphone jack
+LINE_OUT = 0x04 # output to line out
-MICROPHONE = 0x01 # input from microphone
-LINE_IN = 0x02 # input from line in
+MICROPHONE = 0x01 # input from microphone
+LINE_IN = 0x02 # input from line in
CD = 0x04 # input from on-board CD inputs
INTERNAL_CD_IN = CD # input from internal CDROM
diff --git a/Lib/plat-sunos5/TYPES.py b/Lib/plat-sunos5/TYPES.py
index e7106dd3f3..e8e4a0074f 100644
--- a/Lib/plat-sunos5/TYPES.py
+++ b/Lib/plat-sunos5/TYPES.py
@@ -311,4 +311,3 @@ FD_SETSIZE = 1024
_NBBY = 8
NBBY = _NBBY
def FD_ZERO(p): return bzero((p), sizeof (*(p)))
-
diff --git a/Lib/plat-unixware7/IN.py b/Lib/plat-unixware7/IN.py
index 3f97606751..d66ae970c5 100644
--- a/Lib/plat-unixware7/IN.py
+++ b/Lib/plat-unixware7/IN.py
@@ -172,11 +172,11 @@ SHUT_RDWR = 2
# Included from sys/netconfig.h
# Included from sys/cdefs.h
-def __P(protos): return protos
+def __P(protos): return protos
def __STRING(x): return #x
-def __P(protos): return ()
+def __P(protos): return ()
def __STRING(x): return "x"
@@ -485,7 +485,7 @@ def ATOMIC_INT_INCR(atomic_intp): return _ATOMIC_INT_INCR(atomic_intp)
def ATOMIC_INT_DECR(atomic_intp): return _ATOMIC_INT_DECR(atomic_intp)
-def FSPIN_INIT(lp): return
+def FSPIN_INIT(lp): return
def FSPIN_LOCK(l): return DISABLE()
@@ -493,15 +493,15 @@ def FSPIN_TRYLOCK(l): return (DISABLE(), B_TRUE)
def FSPIN_UNLOCK(l): return ENABLE()
-def LOCK_DEINIT(lp): return
+def LOCK_DEINIT(lp): return
-def LOCK_DEALLOC(lp): return
+def LOCK_DEALLOC(lp): return
def LOCK_OWNED(lp): return (B_TRUE)
-def RW_DEINIT(lp): return
+def RW_DEINIT(lp): return
-def RW_DEALLOC(lp): return
+def RW_DEALLOC(lp): return
def RW_OWNED(lp): return (B_TRUE)
@@ -517,7 +517,7 @@ def RW_RDLOCK_PLMIN(lockp): return LOCK_PLMIN(lockp)
def RW_WRLOCK_PLMIN(lockp): return LOCK_PLMIN(lockp)
-def LOCK_DEINIT(l): return
+def LOCK_DEINIT(l): return
def LOCK_PLMIN(lockp): return LOCK((lockp), PLMIN)
@@ -537,9 +537,9 @@ def FSPIN_OWNED(l): return (B_TRUE)
CR_MLDREAL = 0x00000001
CR_RDUMP = 0x00000002
-def crhold(credp): return crholdn((credp), 1)
+def crhold(credp): return crholdn((credp), 1)
-def crfree(credp): return crfreen((credp), 1)
+def crfree(credp): return crfreen((credp), 1)
# Included from sys/strmdep.h
@@ -823,11 +823,11 @@ INADDR_MAX_LOCAL_GROUP = 0xe00000ff
# Included from sys/inline.h
IP_HIER_BASE = (20)
-def ASSERT_LOCK(x): return
+def ASSERT_LOCK(x): return
-def ASSERT_WRLOCK(x): return
+def ASSERT_WRLOCK(x): return
-def ASSERT_UNLOCK(x): return
+def ASSERT_UNLOCK(x): return
def CANPUT(q): return canput((q))
diff --git a/Lib/posixpath.py b/Lib/posixpath.py
index 223517e416..a344a076e1 100644
--- a/Lib/posixpath.py
+++ b/Lib/posixpath.py
@@ -420,7 +420,7 @@ symbolic links encountered in the path."""
def _resolve_link(path):
"""Internal helper function. Takes a path and follows symlinks
- until we either arrive at something that isn't a symlink, or
+ until we either arrive at something that isn't a symlink, or
encounter a path we've seen before (meaning that there's a loop).
"""
paths_seen = []
diff --git a/Lib/test/test_codecencodings_cn.py b/Lib/test/test_codecencodings_cn.py
index 6d71218972..0638f4f7e6 100644
--- a/Lib/test/test_codecencodings_cn.py
+++ b/Lib/test/test_codecencodings_cn.py
@@ -27,8 +27,8 @@ class Test_GBK(test_multibytecodec_support.TestBase, unittest.TestCase):
tstring = test_multibytecodec_support.load_teststring('gbk')
codectests = (
# invalid bytes
- ("abc\x80\x80\xc1\xc4", "strict", None),
- ("abc\xc8", "strict", None),
+ ("abc\x80\x80\xc1\xc4", "strict", None),
+ ("abc\xc8", "strict", None),
("abc\x80\x80\xc1\xc4", "replace", u"abc\ufffd\u804a"),
("abc\x80\x80\xc1\xc4\xc8", "replace", u"abc\ufffd\u804a\ufffd"),
("abc\x80\x80\xc1\xc4", "ignore", u"abc\u804a"),
diff --git a/Lib/test/test_site.py b/Lib/test/test_site.py
index 6f001dec29..ba6f94d2ec 100644
--- a/Lib/test/test_site.py
+++ b/Lib/test/test_site.py
@@ -110,12 +110,12 @@ class PthFile(object):
"""Create a .pth file with a comment, blank lines, an ``import
<self.imported>``, a line with self.good_dirname, and a line with
self.bad_dirname.
-
+
Creation of the directory for self.good_dir_path (based off of
self.good_dirname) is also performed.
Make sure to call self.cleanup() to undo anything done by this method.
-
+
"""
FILE = open(self.file_path, 'wU')
try:
diff --git a/Lib/test/test_transformer.py b/Lib/test/test_transformer.py
index 2b0f1e89e8..6a8c98a627 100644
--- a/Lib/test/test_transformer.py
+++ b/Lib/test/test_transformer.py
@@ -4,29 +4,29 @@ from compiler import transformer, ast
from compiler import compile
class Tests(unittest.TestCase):
-
- def testMultipleLHS(self):
- """ Test multiple targets on the left hand side. """
-
- snippets = ['a, b = 1, 2',
- '(a, b) = 1, 2',
- '((a, b), c) = (1, 2), 3']
- for s in snippets:
- a = transformer.parse(s)
- assert isinstance(a, ast.Module)
- child1 = a.getChildNodes()[0]
- assert isinstance(child1, ast.Stmt)
- child2 = child1.getChildNodes()[0]
- assert isinstance(child2, ast.Assign)
-
- # This actually tests the compiler, but it's a way to assure the ast
- # is correct
- c = compile(s, '<string>', 'single')
- vals = {}
- exec c in vals
- assert vals['a'] == 1
- assert vals['b'] == 2
+ def testMultipleLHS(self):
+ """ Test multiple targets on the left hand side. """
+
+ snippets = ['a, b = 1, 2',
+ '(a, b) = 1, 2',
+ '((a, b), c) = (1, 2), 3']
+
+ for s in snippets:
+ a = transformer.parse(s)
+ assert isinstance(a, ast.Module)
+ child1 = a.getChildNodes()[0]
+ assert isinstance(child1, ast.Stmt)
+ child2 = child1.getChildNodes()[0]
+ assert isinstance(child2, ast.Assign)
+
+ # This actually tests the compiler, but it's a way to assure the ast
+ # is correct
+ c = compile(s, '<string>', 'single')
+ vals = {}
+ exec c in vals
+ assert vals['a'] == 1
+ assert vals['b'] == 2
def test_main():
test_support.run_unittest(
diff --git a/Lib/urllib.py b/Lib/urllib.py
index f472d42b7a..2969ef01dd 100644
--- a/Lib/urllib.py
+++ b/Lib/urllib.py
@@ -1223,7 +1223,7 @@ if sys.platform == 'darwin':
def getproxies():
return getproxies_environment() or getproxies_internetconfig()
-
+
elif os.name == 'nt':
def getproxies_registry():
"""Return a dictionary of scheme -> proxy server URL mappings.
diff --git a/Lib/xml/sax/_exceptions.py b/Lib/xml/sax/_exceptions.py
index 628e80dff4..fdd614aee6 100644
--- a/Lib/xml/sax/_exceptions.py
+++ b/Lib/xml/sax/_exceptions.py
@@ -93,10 +93,10 @@ class SAXParseException(SAXException):
sysid = "<unknown>"
linenum = self.getLineNumber()
if linenum is None:
- linenum = "?"
+ linenum = "?"
colnum = self.getColumnNumber()
if colnum is None:
- colnum = "?"
+ colnum = "?"
return "%s:%s:%s: %s" % (sysid, linenum, colnum, self._msg)
diff --git a/Mac/Demo/PICTbrowse/ICONbrowse.py b/Mac/Demo/PICTbrowse/ICONbrowse.py
index 1194b7e1e1..701ef7f57f 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 eace8691d5..0adfc83783 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 875c99b07a..84cf8b8107 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 e3d79720ac..d95e7c869a 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 5f5893c359..8600bb2a1e 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 a98eb8a422..a2b09107dc 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 931246ee70..455e78dfa9 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 edac8f47be..172b40819c 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 b814056a42..ac5056161f 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 3016964d40..91210ee351 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 d4a4853462..e0f69644d2 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 a5943a65dd..25f71e47cf 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 2aa7c88c4f..2fb8dc4405 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 9747c4a83d..92cd181af5 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 262c650e4a..28dffd3767 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 094c58e164..9c9eeb72fc 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 381345aa2e..323ea6249a 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 ec4beaec14..00f596e472 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 de64e3f006..2930eac778 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 ae627efb07..528ff16794 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 eacf2b7ede..6ce5779216 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 bf5fa5fe9f..b26d5541af 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 6f8eed6174..98e259059a 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 eee848bcb7..3e91b32a65 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 871076633a..d8cea1b453 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 ca772933e7..2078cce331 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 5d84b402b2..28ee938f71 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 3cd832b4d0..d8fc946b62 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 a9f3140d6f..ae47550e3a 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 ef066b9e67..f78b4b8fc3 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 ee52c89314..f1b58f2ebb 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 424e70d263..a2e8d08fbc 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 80c198c38a..1283c1dcd2 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 17184db473..91c5b82efe 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 cced19f627..0b7fe081f8 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 c91c298ded..c5f24beeea 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 822651d8a1..1b04859ef2 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 a9d87681b8..177dfd55f5 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 c6bf93f1a2..e3c72ae23d 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 3cc1672fbb..77d12b6299 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 aa0ea3de43..d2de92e2da 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 95aeaa765f..87b9a6ff27 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 5d84500d6e..b2e7946195 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 7dc2d54cdf..6eedfbef3f 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 6e56cb2015..087f2393df 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 98018c4568..4109dbabaa 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 6ba024b8d2..fdd9712c3f 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 818541e52b..25333f1fa0 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 b2d9ad55f6..d354d94276 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 3710d5d000..7fb68f7cb1 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 85bc607e81..1c0cc6a9f9 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 282728e288..923a56bd4d 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 c200950428..45838efde6 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 3426b70bfc..02087e14c6 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 e5762d9328..0d0c9ec4df 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 ccdc1c59aa..f58da14a66 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 f8b5ba2f66..8ebc69fe4e 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 f06bbb8f2d..dac706dae0 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 73aad3ef79..334d5eca15 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 07b944eac4..e69205316c 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 39b5a0552a..8c94893011 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 b924615092..b9b64bfb01 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 32a759ab56..50e0919dc5 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 a63060348d..77f5c2ecc9 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 1f05217253..84e4f1e672 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 5d07be1239..5f4132840e 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 c6a39f3648..bdc3b84413 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 ef1dbf3a82..1b153854bd 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 bdda1dee26..621033ba87 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 122278ca19..34c2efbcfd 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 ccf8ee75de..205419524c 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 66cb2adf5d..877f6cb48b 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 e44317a963..93baede806 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 f613d8b5cc..b74301d3a6 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 281cc8693e..ae9465ea14 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 7c4ae0d560..a04b7553cb 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 134bffa30e..adecb4fbec 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 862d0bc898..8dcbed5bb6 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 75e1a0808a..fb8196f67f 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 b0e7f4c29c..8369932db0 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 82e774211c..635114ef24 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 d9e4a152ef..83d81edc92 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 f58bb225aa..85a8cdc04c 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 e361c01af7..d078ac6cda 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 ae7070777d..d456e004e2 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 1bd8f5ab58..16177733d5 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 b756bfe827..a2dba15018 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 20304c98b6..132c2b4f6d 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 98d836d71e..8442011ab9 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 ab60b342f3..b3ef790385 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 47a19a6602..47a97e4285 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 6135560cd7..04a1821b1c 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 0b173a4c88..1fc8191265 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 634a43988f..84a75d22a7 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 a287c73a42..c4a82663db 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 99df5bed8a..cf0fa6ca5d 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 c81a8bf4f8..f5b6fff4d4 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 13f1b9734d..ad6c053a46 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 8298f26d09..b5a2b4310a 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 c669fa13aa..13ddc409cc 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 d79356fc63..01cfe86f38 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 6b08c00195..f78935d0d5 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 640e33a7f9..08a0379c53 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 e986d753c9..4f6604cfeb 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 2745086b48..5359df53c4 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 58d8df6472..ae86b80a99 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 193990402e..2521f06a65 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 e782e8cdbd..0277c7946f 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 7e6586930a..914028c3aa 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 af2bd80320..d7134383ea 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 25dda4fcc4..3cf91532e5 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 0e8850fc8a..9fe1064858 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 ee6355bbd2..0041a17979 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 a19641c9c3..a2dafddfe1 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 397347ed66..0ad3a9ab90 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 6f398d17c8..b8d6489487 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 51ba753b46..5ee92d5020 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 1abd4cd28e..ec666b672d 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 ce228ff6cb..88c72aca49 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 eb37ad3428..41f19424c3 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 3ad02c595b..987eec5d02 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 1ea7711b9d..b8f54a9d8a 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 111a0b069a..4dbe92a13b 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 86009d2a81..ab36fa4a92 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 397b2117c1..3ddeb76f00 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 553391ef09..4cfc77b8f9 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 a5d556b8ec..4eef1204ba 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 58fc31bfb9..00b06ac0d3 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 876f02fee5..9bc45226c7 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 1b66a8bab3..9aeb7c42f6 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 bd119a522a..01a8e1c5c8 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 e09e3343d8..0c515830ef 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 421d558c6a..671aa0964b 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 913797ce4d..eb5936d41d 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 3894e164ed..b3d2f8e4ba 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 90a25fe99d..e84349de62 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 d646bcf905..cb8d855153 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 3ef96613e1..7f6142ed5f 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 8a2ca76d1f..b2cf72eae3 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 5dd3435b6d..41d0ec8bb8 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 8735e171db..bfcdc8b29b 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 2d984c1ddd..d2edb9254c 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 03fc0af267..34c17ffc73 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 089727a81a..301e85ea48 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 dfa2047d40..12343c3007 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 285f51f903..3f4e0b739d 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 e954854b81..cb2aed87fd 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 6490265ebc..1fe5f34af0 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 a9c70c111c..7f635a0d1c 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 e6524c979d..e2eed8b270 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 884d4a4912..a556847670 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 faa203beb3..715b8c62f6 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 0349220d9e..a8193c1206 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()
diff --git a/Misc/BeOS-setup.py b/Misc/BeOS-setup.py
index c1435b60bc..c55d27d68a 100644
--- a/Misc/BeOS-setup.py
+++ b/Misc/BeOS-setup.py
@@ -93,7 +93,7 @@ class PyBuildExt(build_ext):
self.extensions.remove(ext)
# Parse Modules/Setup to figure out which modules are turned
- # on in the file.
+ # on in the file.
input = text_file.TextFile('Modules/Setup', join_lines=1)
remove_modules = []
while 1:
@@ -102,11 +102,11 @@ class PyBuildExt(build_ext):
line = line.split()
remove_modules.append( line[0] )
input.close()
-
+
for ext in self.extensions[:]:
if ext.name in remove_modules:
self.extensions.remove(ext)
-
+
# When you run "make CC=altcc" or something similar, you really want
# those environment variables passed into the setup.py phase. Here's
# a small set of useful ones.
@@ -142,18 +142,18 @@ class PyBuildExt(build_ext):
return platform
def detect_modules(self):
- try:
- belibs = os.environ['BELIBRARIES'].split(';')
- except KeyError:
- belibs = ['/boot/beos/system/lib']
- belibs.append('/boot/home/config/lib')
- self.compiler.library_dirs.append('/boot/home/config/lib')
- try:
- beincl = os.environ['BEINCLUDES'].split(';')
- except KeyError:
- beincl = []
- beincl.append('/boot/home/config/include')
- self.compiler.include_dirs.append('/boot/home/config/include')
+ try:
+ belibs = os.environ['BELIBRARIES'].split(';')
+ except KeyError:
+ belibs = ['/boot/beos/system/lib']
+ belibs.append('/boot/home/config/lib')
+ self.compiler.library_dirs.append('/boot/home/config/lib')
+ try:
+ beincl = os.environ['BEINCLUDES'].split(';')
+ except KeyError:
+ beincl = []
+ beincl.append('/boot/home/config/include')
+ self.compiler.include_dirs.append('/boot/home/config/include')
# lib_dirs and inc_dirs are used to search for files;
# if a file is found in one of those directories, it can
# be assumed that no additional -I,-L directives are needed.
@@ -162,7 +162,7 @@ class PyBuildExt(build_ext):
exts = []
platform = self.get_platform()
-
+
# Check for MacOS X, which doesn't need libm.a at all
math_libs = ['m']
if platform in ['Darwin1.2', 'beos']:
@@ -347,7 +347,7 @@ class PyBuildExt(build_ext):
dblib = []
if self.compiler.find_library_file(lib_dirs, 'db'):
dblib = ['db']
-
+
db185_incs = find_file('db_185.h', inc_dirs,
['/usr/include/db3', '/usr/include/db2'])
db_inc = find_file('db.h', inc_dirs, ['/usr/include/db1'])
@@ -388,7 +388,7 @@ class PyBuildExt(build_ext):
# Generic dynamic loading module
#exts.append( Extension('dl', ['dlmodule.c']) )
-
+
# Sun yellow pages. Some systems have the functions in libc.
if platform not in ['cygwin']:
if (self.compiler.find_library_file(lib_dirs, 'nsl')):
@@ -499,15 +499,15 @@ class PyBuildExt(build_ext):
def detect_tkinter(self, inc_dirs, lib_dirs):
# The _tkinter module.
-
+
# Assume we haven't found any of the libraries or include files
tcllib = tklib = tcl_includes = tk_includes = None
for version in ['8.4', '8.3', '8.2', '8.1', '8.0']:
- tklib = self.compiler.find_library_file(lib_dirs,
- 'tk' + version )
- tcllib = self.compiler.find_library_file(lib_dirs,
- 'tcl' + version )
- if tklib and tcllib:
+ tklib = self.compiler.find_library_file(lib_dirs,
+ 'tk' + version )
+ tcllib = self.compiler.find_library_file(lib_dirs,
+ 'tcl' + version )
+ if tklib and tcllib:
# Exit the loop when we've found the Tcl/Tk libraries
break
diff --git a/Misc/find_recursionlimit.py b/Misc/find_recursionlimit.py
index f16c29f659..e6454c9c30 100644
--- a/Misc/find_recursionlimit.py
+++ b/Misc/find_recursionlimit.py
@@ -57,7 +57,7 @@ class RecursiveBlowup6:
def test_getitem():
return RecursiveBlowup6()[5]
-
+
def test_recurse():
return test_recurse()
@@ -85,4 +85,3 @@ while 1:
check_limit(limit, "test_getitem")
print "Limit of %d is fine" % limit
limit = limit + 100
-
diff --git a/Modules/cgen.py b/Modules/cgen.py
index f47e41f426..f07d9843bd 100644
--- a/Modules/cgen.py
+++ b/Modules/cgen.py
@@ -3,7 +3,7 @@
# Copyright (c) 1995-2000, Corporation for National Research Initiatives.
# Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
# All rights reserved.
-#
+#
# See the file "Misc/COPYRIGHT" for information on usage and
# redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
########################################################################
@@ -12,8 +12,8 @@
# usage: python cgen.py <cstubs >glmodule.c
#
# NOTE: You must first make a python binary without the "GL" option
-# before you can run this, when building Python for the first time.
-# See comments in the Makefile.
+# before you can run this, when building Python for the first time.
+# See comments in the Makefile.
#
# XXX BUG return arrays generate wrong code
# XXX need to change error returns into gotos to free mallocked arrays
@@ -26,14 +26,14 @@ import sys
# Function to print to stderr
#
def err(*args):
- savestdout = sys.stdout
- try:
- sys.stdout = sys.stderr
- for i in args:
- print i,
- print
- finally:
- sys.stdout = savestdout
+ savestdout = sys.stdout
+ try:
+ sys.stdout = sys.stderr
+ for i in args:
+ print i,
+ print
+ finally:
+ sys.stdout = savestdout
# The set of digits that form a number
@@ -46,20 +46,20 @@ digits = '0123456789'
# If no number is found, returns '' and the original string.
#
def getnum(s):
- n = ''
- while s and s[0] in digits:
- n = n + s[0]
- s = s[1:]
- return n, s
+ n = ''
+ while s and s[0] in digits:
+ n = n + s[0]
+ s = s[1:]
+ return n, s
# Function to check if a string is a number
#
def isnum(s):
- if not s: return False
- for c in s:
- if not c in digits: return False
- return True
+ if not s: return False
+ for c in s:
+ if not c in digits: return False
+ return True
# Allowed function return types
@@ -73,26 +73,26 @@ arg_types = ['char', 'string', 'short', 'u_short', 'float', 'long', 'double']
# Need to classify arguments as follows
-# simple input variable
-# simple output variable
-# input array
-# output array
-# input giving size of some array
+# simple input variable
+# simple output variable
+# input array
+# output array
+# input giving size of some array
#
# Array dimensions can be specified as follows
-# constant
-# argN
-# constant * argN
-# retval
-# constant * retval
+# constant
+# argN
+# constant * argN
+# retval
+# constant * retval
#
# The dimensions given as constants * something are really
# arrays of points where points are 2- 3- or 4-tuples
#
# We have to consider three lists:
-# python input arguments
-# C stub arguments (in & out)
-# python output arguments (really return values)
+# python input arguments
+# C stub arguments (in & out)
+# python output arguments (really return values)
#
# There is a mapping from python input arguments to the input arguments
# of the C stub, and a further mapping from C stub arguments to the
@@ -110,69 +110,69 @@ arg_error = 'bad arg'
# Return type, mode, factor, rest of subscript; factor and rest may be empty.
#
def checkarg(type, arg):
- #
- # Turn "char *x" into "string x".
- #
- if type == 'char' and arg[0] == '*':
- type = 'string'
- arg = arg[1:]
- #
- # Check that the type is supported.
- #
- if type not in arg_types:
- raise arg_error, ('bad type', type)
- if type[:2] == 'u_':
- type = 'unsigned ' + type[2:]
- #
- # Split it in the mode (first character) and the rest.
- #
- mode, rest = arg[:1], arg[1:]
- #
- # The mode must be 's' for send (= input) or 'r' for return argument.
- #
- if mode not in ('r', 's'):
- raise arg_error, ('bad arg mode', mode)
- #
- # Is it a simple argument: if so, we are done.
- #
- if not rest:
- return type, mode, '', ''
- #
- # Not a simple argument; must be an array.
- # The 'rest' must be a subscript enclosed in [ and ].
- # The subscript must be one of the following forms,
- # otherwise we don't handle it (where N is a number):
- # N
- # argN
- # retval
- # N*argN
- # N*retval
- #
- if rest[:1] <> '[' or rest[-1:] <> ']':
- raise arg_error, ('subscript expected', rest)
- sub = rest[1:-1]
- #
- # Is there a leading number?
- #
- num, sub = getnum(sub)
- if num:
- # There is a leading number
- if not sub:
- # The subscript is just a number
- return type, mode, num, ''
- if sub[:1] == '*':
- # There is a factor prefix
- sub = sub[1:]
- else:
- raise arg_error, ('\'*\' expected', sub)
- if sub == 'retval':
- # size is retval -- must be a reply argument
- if mode <> 'r':
- raise arg_error, ('non-r mode with [retval]', mode)
- elif not isnum(sub) and (sub[:3] <> 'arg' or not isnum(sub[3:])):
- raise arg_error, ('bad subscript', sub)
- #
- return type, mode, num, sub
+ #
+ # Turn "char *x" into "string x".
+ #
+ if type == 'char' and arg[0] == '*':
+ type = 'string'
+ arg = arg[1:]
+ #
+ # Check that the type is supported.
+ #
+ if type not in arg_types:
+ raise arg_error, ('bad type', type)
+ if type[:2] == 'u_':
+ type = 'unsigned ' + type[2:]
+ #
+ # Split it in the mode (first character) and the rest.
+ #
+ mode, rest = arg[:1], arg[1:]
+ #
+ # The mode must be 's' for send (= input) or 'r' for return argument.
+ #
+ if mode not in ('r', 's'):
+ raise arg_error, ('bad arg mode', mode)
+ #
+ # Is it a simple argument: if so, we are done.
+ #
+ if not rest:
+ return type, mode, '', ''
+ #
+ # Not a simple argument; must be an array.
+ # The 'rest' must be a subscript enclosed in [ and ].
+ # The subscript must be one of the following forms,
+ # otherwise we don't handle it (where N is a number):
+ # N
+ # argN
+ # retval
+ # N*argN
+ # N*retval
+ #
+ if rest[:1] <> '[' or rest[-1:] <> ']':
+ raise arg_error, ('subscript expected', rest)
+ sub = rest[1:-1]
+ #
+ # Is there a leading number?
+ #
+ num, sub = getnum(sub)
+ if num:
+ # There is a leading number
+ if not sub:
+ # The subscript is just a number
+ return type, mode, num, ''
+ if sub[:1] == '*':
+ # There is a factor prefix
+ sub = sub[1:]
+ else:
+ raise arg_error, ('\'*\' expected', sub)
+ if sub == 'retval':
+ # size is retval -- must be a reply argument
+ if mode <> 'r':
+ raise arg_error, ('non-r mode with [retval]', mode)
+ elif not isnum(sub) and (sub[:3] <> 'arg' or not isnum(sub[3:])):
+ raise arg_error, ('bad subscript', sub)
+ #
+ return type, mode, num, sub
# List of functions for which we have generated stubs
@@ -184,243 +184,243 @@ functions = []
# information build by successive calls to checkarg()
#
def generate(type, func, database):
- #
- # Check that we can handle this case:
- # no variable size reply arrays yet
- #
- n_in_args = 0
- n_out_args = 0
- #
- for a_type, a_mode, a_factor, a_sub in database:
- if a_mode == 's':
- n_in_args = n_in_args + 1
- elif a_mode == 'r':
- n_out_args = n_out_args + 1
- else:
- # Can't happen
- raise arg_error, ('bad a_mode', a_mode)
- if (a_mode == 'r' and a_sub) or a_sub == 'retval':
- err('Function', func, 'too complicated:',
- a_type, a_mode, a_factor, a_sub)
- print '/* XXX Too complicated to generate code for */'
- return
- #
- functions.append(func)
- #
- # Stub header
- #
- print
- print 'static PyObject *'
- print 'gl_' + func + '(self, args)'
- print '\tPyObject *self;'
- print '\tPyObject *args;'
- print '{'
- #
- # Declare return value if any
- #
- if type <> 'void':
- print '\t' + type, 'retval;'
- #
- # Declare arguments
- #
- for i in range(len(database)):
- a_type, a_mode, a_factor, a_sub = database[i]
- print '\t' + a_type,
- brac = ket = ''
- if a_sub and not isnum(a_sub):
- if a_factor:
- brac = '('
- ket = ')'
- print brac + '*',
- print 'arg' + repr(i+1) + ket,
- if a_sub and isnum(a_sub):
- print '[', a_sub, ']',
- if a_factor:
- print '[', a_factor, ']',
- print ';'
- #
- # Find input arguments derived from array sizes
- #
- for i in range(len(database)):
- a_type, a_mode, a_factor, a_sub = database[i]
- if a_mode == 's' and a_sub[:3] == 'arg' and isnum(a_sub[3:]):
- # Sending a variable-length array
- n = eval(a_sub[3:])
- if 1 <= n <= len(database):
- b_type, b_mode, b_factor, b_sub = database[n-1]
- if b_mode == 's':
- database[n-1] = b_type, 'i', a_factor, repr(i)
- n_in_args = n_in_args - 1
- #
- # Assign argument positions in the Python argument list
- #
- in_pos = []
- i_in = 0
- for i in range(len(database)):
- a_type, a_mode, a_factor, a_sub = database[i]
- if a_mode == 's':
- in_pos.append(i_in)
- i_in = i_in + 1
- else:
- in_pos.append(-1)
- #
- # Get input arguments
- #
- for i in range(len(database)):
- a_type, a_mode, a_factor, a_sub = database[i]
- if a_type[:9] == 'unsigned ':
- xtype = a_type[9:]
- else:
- xtype = a_type
- if a_mode == 'i':
- #
- # Implicit argument;
- # a_factor is divisor if present,
- # a_sub indicates which arg (`database index`)
- #
- j = eval(a_sub)
- print '\tif',
- print '(!geti' + xtype + 'arraysize(args,',
- print repr(n_in_args) + ',',
- print repr(in_pos[j]) + ',',
- if xtype <> a_type:
- print '('+xtype+' *)',
- print '&arg' + repr(i+1) + '))'
- print '\t\treturn NULL;'
- if a_factor:
- print '\targ' + repr(i+1),
- print '= arg' + repr(i+1),
- print '/', a_factor + ';'
- elif a_mode == 's':
- if a_sub and not isnum(a_sub):
- # Allocate memory for varsize array
- print '\tif ((arg' + repr(i+1), '=',
- if a_factor:
- print '('+a_type+'(*)['+a_factor+'])',
- print 'PyMem_NEW(' + a_type, ',',
- if a_factor:
- print a_factor, '*',
- print a_sub, ')) == NULL)'
- print '\t\treturn PyErr_NoMemory();'
- print '\tif',
- if a_factor or a_sub: # Get a fixed-size array array
- print '(!geti' + xtype + 'array(args,',
- print repr(n_in_args) + ',',
- print repr(in_pos[i]) + ',',
- if a_factor: print a_factor,
- if a_factor and a_sub: print '*',
- if a_sub: print a_sub,
- print ',',
- if (a_sub and a_factor) or xtype <> a_type:
- print '('+xtype+' *)',
- print 'arg' + repr(i+1) + '))'
- else: # Get a simple variable
- print '(!geti' + xtype + 'arg(args,',
- print repr(n_in_args) + ',',
- print repr(in_pos[i]) + ',',
- if xtype <> a_type:
- print '('+xtype+' *)',
- print '&arg' + repr(i+1) + '))'
- print '\t\treturn NULL;'
- #
- # Begin of function call
- #
- if type <> 'void':
- print '\tretval =', func + '(',
- else:
- print '\t' + func + '(',
- #
- # Argument list
- #
- for i in range(len(database)):
- if i > 0: print ',',
- a_type, a_mode, a_factor, a_sub = database[i]
- if a_mode == 'r' and not a_factor:
- print '&',
- print 'arg' + repr(i+1),
- #
- # End of function call
- #
- print ');'
- #
- # Free varsize arrays
- #
- for i in range(len(database)):
- a_type, a_mode, a_factor, a_sub = database[i]
- if a_mode == 's' and a_sub and not isnum(a_sub):
- print '\tPyMem_DEL(arg' + repr(i+1) + ');'
- #
- # Return
- #
- if n_out_args:
- #
- # Multiple return values -- construct a tuple
- #
- if type <> 'void':
- n_out_args = n_out_args + 1
- if n_out_args == 1:
- for i in range(len(database)):
- a_type, a_mode, a_factor, a_sub = database[i]
- if a_mode == 'r':
- break
- else:
- raise arg_error, 'expected r arg not found'
- print '\treturn',
- print mkobject(a_type, 'arg' + repr(i+1)) + ';'
- else:
- print '\t{ PyObject *v = PyTuple_New(',
- print n_out_args, ');'
- print '\t if (v == NULL) return NULL;'
- i_out = 0
- if type <> 'void':
- print '\t PyTuple_SetItem(v,',
- print repr(i_out) + ',',
- print mkobject(type, 'retval') + ');'
- i_out = i_out + 1
- for i in range(len(database)):
- a_type, a_mode, a_factor, a_sub = database[i]
- if a_mode == 'r':
- print '\t PyTuple_SetItem(v,',
- print repr(i_out) + ',',
- s = mkobject(a_type, 'arg' + repr(i+1))
- print s + ');'
- i_out = i_out + 1
- print '\t return v;'
- print '\t}'
- else:
- #
- # Simple function return
- # Return None or return value
- #
- if type == 'void':
- print '\tPy_INCREF(Py_None);'
- print '\treturn Py_None;'
- else:
- print '\treturn', mkobject(type, 'retval') + ';'
- #
- # Stub body closing brace
- #
- print '}'
+ #
+ # Check that we can handle this case:
+ # no variable size reply arrays yet
+ #
+ n_in_args = 0
+ n_out_args = 0
+ #
+ for a_type, a_mode, a_factor, a_sub in database:
+ if a_mode == 's':
+ n_in_args = n_in_args + 1
+ elif a_mode == 'r':
+ n_out_args = n_out_args + 1
+ else:
+ # Can't happen
+ raise arg_error, ('bad a_mode', a_mode)
+ if (a_mode == 'r' and a_sub) or a_sub == 'retval':
+ err('Function', func, 'too complicated:',
+ a_type, a_mode, a_factor, a_sub)
+ print '/* XXX Too complicated to generate code for */'
+ return
+ #
+ functions.append(func)
+ #
+ # Stub header
+ #
+ print
+ print 'static PyObject *'
+ print 'gl_' + func + '(self, args)'
+ print '\tPyObject *self;'
+ print '\tPyObject *args;'
+ print '{'
+ #
+ # Declare return value if any
+ #
+ if type <> 'void':
+ print '\t' + type, 'retval;'
+ #
+ # Declare arguments
+ #
+ for i in range(len(database)):
+ a_type, a_mode, a_factor, a_sub = database[i]
+ print '\t' + a_type,
+ brac = ket = ''
+ if a_sub and not isnum(a_sub):
+ if a_factor:
+ brac = '('
+ ket = ')'
+ print brac + '*',
+ print 'arg' + repr(i+1) + ket,
+ if a_sub and isnum(a_sub):
+ print '[', a_sub, ']',
+ if a_factor:
+ print '[', a_factor, ']',
+ print ';'
+ #
+ # Find input arguments derived from array sizes
+ #
+ for i in range(len(database)):
+ a_type, a_mode, a_factor, a_sub = database[i]
+ if a_mode == 's' and a_sub[:3] == 'arg' and isnum(a_sub[3:]):
+ # Sending a variable-length array
+ n = eval(a_sub[3:])
+ if 1 <= n <= len(database):
+ b_type, b_mode, b_factor, b_sub = database[n-1]
+ if b_mode == 's':
+ database[n-1] = b_type, 'i', a_factor, repr(i)
+ n_in_args = n_in_args - 1
+ #
+ # Assign argument positions in the Python argument list
+ #
+ in_pos = []
+ i_in = 0
+ for i in range(len(database)):
+ a_type, a_mode, a_factor, a_sub = database[i]
+ if a_mode == 's':
+ in_pos.append(i_in)
+ i_in = i_in + 1
+ else:
+ in_pos.append(-1)
+ #
+ # Get input arguments
+ #
+ for i in range(len(database)):
+ a_type, a_mode, a_factor, a_sub = database[i]
+ if a_type[:9] == 'unsigned ':
+ xtype = a_type[9:]
+ else:
+ xtype = a_type
+ if a_mode == 'i':
+ #
+ # Implicit argument;
+ # a_factor is divisor if present,
+ # a_sub indicates which arg (`database index`)
+ #
+ j = eval(a_sub)
+ print '\tif',
+ print '(!geti' + xtype + 'arraysize(args,',
+ print repr(n_in_args) + ',',
+ print repr(in_pos[j]) + ',',
+ if xtype <> a_type:
+ print '('+xtype+' *)',
+ print '&arg' + repr(i+1) + '))'
+ print '\t\treturn NULL;'
+ if a_factor:
+ print '\targ' + repr(i+1),
+ print '= arg' + repr(i+1),
+ print '/', a_factor + ';'
+ elif a_mode == 's':
+ if a_sub and not isnum(a_sub):
+ # Allocate memory for varsize array
+ print '\tif ((arg' + repr(i+1), '=',
+ if a_factor:
+ print '('+a_type+'(*)['+a_factor+'])',
+ print 'PyMem_NEW(' + a_type, ',',
+ if a_factor:
+ print a_factor, '*',
+ print a_sub, ')) == NULL)'
+ print '\t\treturn PyErr_NoMemory();'
+ print '\tif',
+ if a_factor or a_sub: # Get a fixed-size array array
+ print '(!geti' + xtype + 'array(args,',
+ print repr(n_in_args) + ',',
+ print repr(in_pos[i]) + ',',
+ if a_factor: print a_factor,
+ if a_factor and a_sub: print '*',
+ if a_sub: print a_sub,
+ print ',',
+ if (a_sub and a_factor) or xtype <> a_type:
+ print '('+xtype+' *)',
+ print 'arg' + repr(i+1) + '))'
+ else: # Get a simple variable
+ print '(!geti' + xtype + 'arg(args,',
+ print repr(n_in_args) + ',',
+ print repr(in_pos[i]) + ',',
+ if xtype <> a_type:
+ print '('+xtype+' *)',
+ print '&arg' + repr(i+1) + '))'
+ print '\t\treturn NULL;'
+ #
+ # Begin of function call
+ #
+ if type <> 'void':
+ print '\tretval =', func + '(',
+ else:
+ print '\t' + func + '(',
+ #
+ # Argument list
+ #
+ for i in range(len(database)):
+ if i > 0: print ',',
+ a_type, a_mode, a_factor, a_sub = database[i]
+ if a_mode == 'r' and not a_factor:
+ print '&',
+ print 'arg' + repr(i+1),
+ #
+ # End of function call
+ #
+ print ');'
+ #
+ # Free varsize arrays
+ #
+ for i in range(len(database)):
+ a_type, a_mode, a_factor, a_sub = database[i]
+ if a_mode == 's' and a_sub and not isnum(a_sub):
+ print '\tPyMem_DEL(arg' + repr(i+1) + ');'
+ #
+ # Return
+ #
+ if n_out_args:
+ #
+ # Multiple return values -- construct a tuple
+ #
+ if type <> 'void':
+ n_out_args = n_out_args + 1
+ if n_out_args == 1:
+ for i in range(len(database)):
+ a_type, a_mode, a_factor, a_sub = database[i]
+ if a_mode == 'r':
+ break
+ else:
+ raise arg_error, 'expected r arg not found'
+ print '\treturn',
+ print mkobject(a_type, 'arg' + repr(i+1)) + ';'
+ else:
+ print '\t{ PyObject *v = PyTuple_New(',
+ print n_out_args, ');'
+ print '\t if (v == NULL) return NULL;'
+ i_out = 0
+ if type <> 'void':
+ print '\t PyTuple_SetItem(v,',
+ print repr(i_out) + ',',
+ print mkobject(type, 'retval') + ');'
+ i_out = i_out + 1
+ for i in range(len(database)):
+ a_type, a_mode, a_factor, a_sub = database[i]
+ if a_mode == 'r':
+ print '\t PyTuple_SetItem(v,',
+ print repr(i_out) + ',',
+ s = mkobject(a_type, 'arg' + repr(i+1))
+ print s + ');'
+ i_out = i_out + 1
+ print '\t return v;'
+ print '\t}'
+ else:
+ #
+ # Simple function return
+ # Return None or return value
+ #
+ if type == 'void':
+ print '\tPy_INCREF(Py_None);'
+ print '\treturn Py_None;'
+ else:
+ print '\treturn', mkobject(type, 'retval') + ';'
+ #
+ # Stub body closing brace
+ #
+ print '}'
# Subroutine to return a function call to mknew<type>object(<arg>)
#
def mkobject(type, arg):
- if type[:9] == 'unsigned ':
- type = type[9:]
- return 'mknew' + type + 'object((' + type + ') ' + arg + ')'
- return 'mknew' + type + 'object(' + arg + ')'
+ if type[:9] == 'unsigned ':
+ type = type[9:]
+ return 'mknew' + type + 'object((' + type + ') ' + arg + ')'
+ return 'mknew' + type + 'object(' + arg + ')'
defined_archs = []
# usage: cgen [ -Dmach ... ] [ file ]
for arg in sys.argv[1:]:
- if arg[:2] == '-D':
- defined_archs.append(arg[2:])
- else:
- # Open optional file argument
- sys.stdin = open(arg, 'r')
+ if arg[:2] == '-D':
+ defined_archs.append(arg[2:])
+ else:
+ # Open optional file argument
+ sys.stdin = open(arg, 'r')
# Input line number
@@ -428,8 +428,8 @@ lno = 0
# Input is divided in two parts, separated by a line containing '%%'.
-# <part1> -- literally copied to stdout
-# <part2> -- stub definitions
+# <part1> -- literally copied to stdout
+# <part2> -- stub definitions
# Variable indicating the current input part.
#
@@ -438,78 +438,78 @@ part = 1
# Main loop over the input
#
while 1:
- try:
- line = raw_input()
- except EOFError:
- break
- #
- lno = lno+1
- words = string.split(line)
- #
- if part == 1:
- #
- # In part 1, copy everything literally
- # except look for a line of just '%%'
- #
- if words == ['%%']:
- part = part + 1
- else:
- #
- # Look for names of manually written
- # stubs: a single percent followed by the name
- # of the function in Python.
- # The stub name is derived by prefixing 'gl_'.
- #
- if words and words[0][0] == '%':
- func = words[0][1:]
- if (not func) and words[1:]:
- func = words[1]
- if func:
- functions.append(func)
- else:
- print line
- continue
- if not words:
- continue # skip empty line
- elif words[0] == 'if':
- # if XXX rest
- # if !XXX rest
- if words[1][0] == '!':
- if words[1][1:] in defined_archs:
- continue
- elif words[1] not in defined_archs:
- continue
- words = words[2:]
- if words[0] == '#include':
- print line
- elif words[0][:1] == '#':
- pass # ignore comment
- elif words[0] not in return_types:
- err('Line', lno, ': bad return type :', words[0])
- elif len(words) < 2:
- err('Line', lno, ': no funcname :', line)
- else:
- if len(words) % 2 <> 0:
- err('Line', lno, ': odd argument list :', words[2:])
- else:
- database = []
- try:
- for i in range(2, len(words), 2):
- x = checkarg(words[i], words[i+1])
- database.append(x)
- print
- print '/*',
- for w in words: print w,
- print '*/'
- generate(words[0], words[1], database)
- except arg_error, msg:
- err('Line', lno, ':', msg)
+ try:
+ line = raw_input()
+ except EOFError:
+ break
+ #
+ lno = lno+1
+ words = string.split(line)
+ #
+ if part == 1:
+ #
+ # In part 1, copy everything literally
+ # except look for a line of just '%%'
+ #
+ if words == ['%%']:
+ part = part + 1
+ else:
+ #
+ # Look for names of manually written
+ # stubs: a single percent followed by the name
+ # of the function in Python.
+ # The stub name is derived by prefixing 'gl_'.
+ #
+ if words and words[0][0] == '%':
+ func = words[0][1:]
+ if (not func) and words[1:]:
+ func = words[1]
+ if func:
+ functions.append(func)
+ else:
+ print line
+ continue
+ if not words:
+ continue # skip empty line
+ elif words[0] == 'if':
+ # if XXX rest
+ # if !XXX rest
+ if words[1][0] == '!':
+ if words[1][1:] in defined_archs:
+ continue
+ elif words[1] not in defined_archs:
+ continue
+ words = words[2:]
+ if words[0] == '#include':
+ print line
+ elif words[0][:1] == '#':
+ pass # ignore comment
+ elif words[0] not in return_types:
+ err('Line', lno, ': bad return type :', words[0])
+ elif len(words) < 2:
+ err('Line', lno, ': no funcname :', line)
+ else:
+ if len(words) % 2 <> 0:
+ err('Line', lno, ': odd argument list :', words[2:])
+ else:
+ database = []
+ try:
+ for i in range(2, len(words), 2):
+ x = checkarg(words[i], words[i+1])
+ database.append(x)
+ print
+ print '/*',
+ for w in words: print w,
+ print '*/'
+ generate(words[0], words[1], database)
+ except arg_error, msg:
+ err('Line', lno, ':', msg)
print
print 'static struct PyMethodDef gl_methods[] = {'
for func in functions:
- print '\t{"' + func + '", gl_' + func + '},'
+ print '\t{"' + func + '", gl_' + func + '},'
print '\t{NULL, NULL} /* Sentinel */'
print '};'
print
diff --git a/Tools/bgen/bgen/bgenBuffer.py b/Tools/bgen/bgen/bgenBuffer.py
index 4b888d7819..ca7e026341 100644
--- a/Tools/bgen/bgen/bgenBuffer.py
+++ b/Tools/bgen/bgen/bgenBuffer.py
@@ -27,7 +27,7 @@ type2format = {
class FixedInputOutputBufferType(InputOnlyType):
-
+
"""Fixed buffer -- passed as (inbuffer, outbuffer)."""
def __init__(self, size, datatype = 'char', sizetype = 'int', sizeformat = None):
@@ -41,14 +41,14 @@ class FixedInputOutputBufferType(InputOnlyType):
def declare(self, name):
self.declareBuffer(name)
self.declareSize(name)
-
+
def declareBuffer(self, name):
self.declareInputBuffer(name)
self.declareOutputBuffer(name)
-
+
def declareInputBuffer(self, name):
Output("%s *%s__in__;", self.datatype, name)
-
+
def declareOutputBuffer(self, name):
Output("%s %s__out__[%s];", self.datatype, name, self.size)
@@ -61,7 +61,7 @@ class FixedInputOutputBufferType(InputOnlyType):
def getargsArgs(self, name):
return "&%s__in__, &%s__in_len__" % (name, name)
-
+
def getargsCheck(self, name):
Output("if (%s__in_len__ != %s)", name, self.size)
OutLbrace()
@@ -71,19 +71,19 @@ class FixedInputOutputBufferType(InputOnlyType):
self.label_needed = 1
OutRbrace()
self.transferSize(name)
-
+
def transferSize(self, name):
Output("%s__len__ = %s__in_len__;", name, name)
def passOutput(self, name):
return "%s__in__, %s__out__" % (name, name)
-
+
def mkvalueFormat(self):
return "s#"
def mkvalueArgs(self, name):
return "%s__out__, (int)%s" % (name, self.size)
-
+
def cleanup(self, name):
if self.label_needed:
DedentLevel()
@@ -92,9 +92,9 @@ class FixedInputOutputBufferType(InputOnlyType):
class FixedCombinedInputOutputBufferType(FixedInputOutputBufferType):
-
+
"""Like fixed buffer -- but same parameter is input and output."""
-
+
def passOutput(self, name):
return "(%s *)memcpy(%s__out__, %s__in__, %s)" % \
(self.datatype, name, name, self.size)
@@ -112,10 +112,10 @@ class OutputOnlyBufferMixIn(OutputOnlyMixIn):
pass
class OptionalInputBufferMixIn:
-
+
"""Add to input buffers if the buffer may be omitted: pass None in Python
and the C code will get a NULL pointer and zero size"""
-
+
def getargsFormat(self):
return "z#"
@@ -147,63 +147,63 @@ class FixedOutputBufferType(OutputOnlyBufferMixIn, FixedInputOutputBufferType):
class VarInputBufferType(FixedInputBufferType):
"""Variable size input buffer -- passed as (buffer, size).
-
+
Instantiate without size parameter.
"""
-
+
def __init__(self, datatype = 'char', sizetype = 'int', sizeformat = None):
FixedInputBufferType.__init__(self, "0", datatype, sizetype, sizeformat)
-
+
def getargsCheck(self, name):
Output("%s__len__ = %s__in_len__;", name, name)
-
+
def passInput(self, name):
return "%s__in__, %s__len__" % (name, name)
-
+
class ReverseInputBufferMixin:
""" Mixin for input buffers that are passed as (size, buffer) """
-
+
def passInput(self, name):
return "%s__len__, %s__in__" % (name, name)
-
+
class OptionalVarInputBufferType(OptionalInputBufferMixIn, VarInputBufferType):
pass
-
+
# ----- PART 2: Structure buffers -----
class StructInputOutputBufferType(FixedInputOutputBufferType):
-
+
"""Structure buffer -- passed as a structure pointer.
Instantiate with the struct type as parameter.
"""
-
+
def __init__(self, type):
FixedInputOutputBufferType.__init__(self, "sizeof(%s)" % type)
self.typeName = self.type = type
-
+
def declareInputBuffer(self, name):
Output("%s *%s__in__;", self.type, name)
-
+
def declareSize(self, name):
Output("int %s__in_len__;", name)
-
+
def declareOutputBuffer(self, name):
Output("%s %s__out__;", self.type, name)
-
+
def getargsArgs(self, name):
return "(char **)&%s__in__, &%s__in_len__" % (name, name)
-
+
def transferSize(self, name):
pass
-
+
def passInput(self, name):
return "%s__in__" % name
-
+
def passOutput(self, name):
return "%s__in__, &%s__out__" % (name, name)
-
+
def mkvalueArgs(self, name):
return "(char *)&%s__out__, (int)%s" % (name, self.size)
@@ -211,7 +211,7 @@ class StructInputOutputBufferType(FixedInputOutputBufferType):
class StructCombinedInputOutputBufferType(StructInputOutputBufferType):
"""Like structure buffer -- but same parameter is input and output."""
-
+
def passOutput(self, name):
return "(%s *)memcpy((char *)%s__out__, (char *)%s__in__, %s)" % \
(self.type, name, name, self.size)
@@ -242,7 +242,7 @@ class StructOutputBufferType(OutputOnlyBufferMixIn, StructInputOutputBufferType)
Instantiate with the struct type as parameter.
"""
-
+
def declareSize(self, name):
pass
@@ -256,7 +256,7 @@ class ArrayOutputBufferType(OutputOnlyBufferMixIn, StructInputOutputBufferType):
Instantiate with the struct type as parameter.
"""
-
+
def declareSize(self, name):
pass
diff --git a/Tools/bgen/bgen/bgenGenerator.py b/Tools/bgen/bgen/bgenGenerator.py
index f3cdfce917..e1f240c629 100644
--- a/Tools/bgen/bgen/bgenGenerator.py
+++ b/Tools/bgen/bgen/bgenGenerator.py
@@ -55,7 +55,7 @@ class BaseFunctionGenerator:
docstring = self.docstring()
if self.condition:
Output()
- Output(self.condition)
+ Output(self.condition)
Output("{\"%s\", (PyCFunction)%s_%s, 1,", name, self.prefix, self.name)
Output(" PyDoc_STR(%s)},", stringify(docstring))
if self.condition:
@@ -91,7 +91,7 @@ class ManualGenerator(BaseFunctionGenerator):
def functionbody(self):
Output("%s", self.body)
-
+
def setselftype(self, selftype, itselftype):
self.objecttype = selftype
self.itselftype = itselftype
@@ -114,7 +114,7 @@ class FunctionGenerator(BaseFunctionGenerator):
self.argumentList.append(self.rv)
else:
self.rv = None
-
+
def makereturnvar(self):
return Variable(self.returntype, "_rv", OutMode)
@@ -129,7 +129,7 @@ class FunctionGenerator(BaseFunctionGenerator):
if name is None: name = "_arg%d" % iarg
arg = Variable(type, name, mode)
self.argumentList.append(arg)
-
+
def docstring(self):
input = []
output = []
@@ -146,7 +146,7 @@ class FunctionGenerator(BaseFunctionGenerator):
else:
typeName = "?"
print "Nameless type", arg.type
-
+
str = typeName + ' ' + arg.name
if arg.mode in (InMode, InOutMode):
input.append(str)
@@ -161,7 +161,7 @@ class FunctionGenerator(BaseFunctionGenerator):
else:
outstr = "(%s)" % ", ".join(output)
return instr + " -> " + outstr
-
+
def functionbody(self):
self.declarations()
self.precheck()
@@ -195,7 +195,7 @@ class FunctionGenerator(BaseFunctionGenerator):
continue
if arg.mode in (InMode, InOutMode):
arg.getargsCheck()
-
+
def precheck(self):
pass
diff --git a/Tools/bgen/bgen/bgenHeapBuffer.py b/Tools/bgen/bgen/bgenHeapBuffer.py
index 9bfc5a11cd..64cf2a4f86 100644
--- a/Tools/bgen/bgen/bgenHeapBuffer.py
+++ b/Tools/bgen/bgen/bgenHeapBuffer.py
@@ -43,7 +43,7 @@ class HeapInputOutputBufferType(FixedInputOutputBufferType):
class VarHeapInputOutputBufferType(HeapInputOutputBufferType):
"""same as base class, but passed as (inbuffer, outbuffer, &size)"""
-
+
def passOutput(self, name):
return "%s__in__, %s__out__, &%s__len__" % (name, name, name)
@@ -51,7 +51,7 @@ class VarHeapInputOutputBufferType(HeapInputOutputBufferType):
class HeapCombinedInputOutputBufferType(HeapInputOutputBufferType):
"""same as base class, but passed as (inoutbuffer, size)"""
-
+
def passOutput(self, name):
return "(%s *)memcpy(%s__out__, %s__in__, %s__len__)" % \
(self.datatype, name, name, name)
@@ -60,7 +60,7 @@ class HeapCombinedInputOutputBufferType(HeapInputOutputBufferType):
class VarHeapCombinedInputOutputBufferType(HeapInputOutputBufferType):
"""same as base class, but passed as (inoutbuffer, &size)"""
-
+
def passOutput(self, name):
return "(%s *)memcpy(%s__out__, %s__in__, &%s__len__)" % \
(self.datatype, name, name, name)
@@ -73,16 +73,16 @@ class HeapOutputBufferType(OutputOnlyMixIn, HeapInputOutputBufferType):
Instantiate without parameters.
Call from Python with buffer size.
"""
-
+
def declareInputBuffer(self, name):
pass
-
+
def getargsFormat(self):
return "i"
-
+
def getargsArgs(self, name):
return "&%s__in_len__" % name
-
+
def passOutput(self, name):
return "%s__out__, %s__len__" % (name, name)
diff --git a/Tools/bgen/bgen/bgenModule.py b/Tools/bgen/bgen/bgenModule.py
index 3e26b16380..d41aa05c56 100644
--- a/Tools/bgen/bgen/bgenModule.py
+++ b/Tools/bgen/bgen/bgenModule.py
@@ -38,7 +38,7 @@ class Module(GeneratorGroup):
self.declareModuleVariables()
GeneratorGroup.generate(self)
-
+
if self.finalstuff:
Output()
Output("%s", self.finalstuff)
diff --git a/Tools/bgen/bgen/bgenObjectDefinition.py b/Tools/bgen/bgen/bgenObjectDefinition.py
index 9c205e392b..72e2678bb0 100644
--- a/Tools/bgen/bgen/bgenObjectDefinition.py
+++ b/Tools/bgen/bgen/bgenObjectDefinition.py
@@ -9,14 +9,14 @@ class ObjectDefinition(GeneratorGroup):
def __init__(self, name, prefix, itselftype):
"""ObjectDefinition constructor. May be extended, but do not override.
-
+
- name: the object's official name, e.g. 'SndChannel'.
- prefix: the prefix used for the object's functions and data, e.g. 'SndCh'.
- itselftype: the C type actually contained in the object, e.g. 'SndChannelPtr'.
-
+
XXX For official Python data types, rules for the 'Py' prefix are a problem.
"""
-
+
GeneratorGroup.__init__(self, prefix or name)
self.name = name
self.itselftype = itselftype
@@ -35,7 +35,7 @@ class ObjectDefinition(GeneratorGroup):
def reference(self):
# In case we are referenced from a module
pass
-
+
def setmodulename(self, name):
self.modulename = name
@@ -58,7 +58,7 @@ class ObjectDefinition(GeneratorGroup):
Output("} %s;", self.objecttype)
self.outputNew()
-
+
self.outputConvert()
self.outputDealloc()
@@ -71,19 +71,19 @@ class ObjectDefinition(GeneratorGroup):
self.outputGetattr()
self.outputSetattr()
-
+
self.outputCompare()
-
+
self.outputRepr()
-
+
self.outputHash()
-
+
self.outputPEP253Hooks()
-
+
self.outputTypeObject()
OutHeader2("End object type " + self.name)
-
+
def outputMethodChain(self):
Output("%sPyMethodChain %s_chain = { %s_methods, %s };",
self.static, self.prefix, self.prefix, self.basechain)
@@ -108,10 +108,10 @@ class ObjectDefinition(GeneratorGroup):
def outputInitStructMembers(self):
Output("it->ob_itself = %sitself;", self.argref)
-
+
def outputCheckNewArg(self):
- "Override this method to apply additional checks/conversions"
-
+ "Override this method to apply additional checks/conversions"
+
def outputConvert(self):
Output("%sint %s_Convert(PyObject *v, %s *p_itself)", self.static, self.prefix,
self.itselftype)
@@ -206,7 +206,7 @@ class ObjectDefinition(GeneratorGroup):
Output("(hashfunc) %s_hash, /*tp_hash*/", self.prefix)
DedentLevel()
Output("};")
-
+
def outputTypeObjectInitializer(self):
Output("""%s.ob_type = &PyType_Type;""", self.typename)
if self.basetype:
@@ -220,10 +220,10 @@ class ObjectDefinition(GeneratorGroup):
def outputPEP253Hooks(self):
pass
-
+
class PEP252Mixin:
getsetlist = []
-
+
def assertions(self):
# Check that various things aren't overridden. If they are it could
# signify a bgen-client that has been partially converted to PEP252.
@@ -232,21 +232,21 @@ class PEP252Mixin:
assert self.outputGetattrBody == None
assert self.outputGetattrHook == None
assert self.basechain == "NULL"
-
+
def outputGetattr(self):
pass
-
+
outputGetattrBody = None
outputGetattrHook = None
def outputSetattr(self):
pass
-
+
def outputMethodChain(self):
# This is a good place to output the getters and setters
self.outputGetSetList()
-
+
def outputHook(self, name):
methodname = "outputHook_" + name
if hasattr(self, methodname):
@@ -254,7 +254,7 @@ class PEP252Mixin:
func()
else:
Output("0, /*%s*/", name)
-
+
def outputTypeObject(self):
sf = self.static and "static "
Output()
@@ -268,7 +268,7 @@ class PEP252Mixin:
Output("\"%s\", /*tp_name*/", self.name)
Output("sizeof(%s), /*tp_basicsize*/", self.objecttype)
Output("0, /*tp_itemsize*/")
-
+
Output("/* methods */")
Output("(destructor) %s_dealloc, /*tp_dealloc*/", self.prefix)
Output("0, /*tp_print*/")
@@ -276,17 +276,17 @@ class PEP252Mixin:
Output("(setattrfunc)0, /*tp_setattr*/")
Output("(cmpfunc) %s_compare, /*tp_compare*/", self.prefix)
Output("(reprfunc) %s_repr, /*tp_repr*/", self.prefix)
-
+
Output("(PyNumberMethods *)0, /* tp_as_number */")
Output("(PySequenceMethods *)0, /* tp_as_sequence */")
Output("(PyMappingMethods *)0, /* tp_as_mapping */")
-
+
Output("(hashfunc) %s_hash, /*tp_hash*/", self.prefix)
self.outputHook("tp_call")
Output("0, /*tp_str*/")
Output("PyObject_GenericGetAttr, /*tp_getattro*/")
Output("PyObject_GenericSetAttr, /*tp_setattro */")
-
+
self.outputHook("tp_as_buffer")
Output("%s, /* tp_flags */", self.tp_flags)
self.outputHook("tp_doc")
@@ -310,7 +310,7 @@ class PEP252Mixin:
self.outputHook("tp_free")
DedentLevel()
Output("};")
-
+
def outputGetSetList(self):
if self.getsetlist:
for name, get, set, doc in self.getsetlist:
@@ -324,7 +324,7 @@ class PEP252Mixin:
else:
Output("#define %s_set_%s NULL", self.prefix, name)
Output()
-
+
Output("static PyGetSetDef %s_getsetlist[] = {", self.prefix)
IndentLevel()
for name, get, set, doc in self.getsetlist:
@@ -332,7 +332,7 @@ class PEP252Mixin:
doc = '"' + doc + '"'
else:
doc = "NULL"
- Output("{\"%s\", (getter)%s_get_%s, (setter)%s_set_%s, %s},",
+ Output("{\"%s\", (getter)%s_get_%s, (setter)%s_set_%s, %s},",
name, self.prefix, name, self.prefix, name, doc)
Output("{NULL, NULL, NULL, NULL},")
DedentLevel()
@@ -340,7 +340,7 @@ class PEP252Mixin:
else:
Output("#define %s_getsetlist NULL", self.prefix)
Output()
-
+
def outputGetter(self, name, code):
Output("static PyObject *%s_get_%s(%s *self, void *closure)",
self.prefix, name, self.objecttype)
@@ -348,7 +348,7 @@ class PEP252Mixin:
Output(code)
OutRbrace()
Output()
-
+
def outputSetter(self, name, code):
Output("static int %s_set_%s(%s *self, PyObject *v, void *closure)",
self.prefix, name, self.objecttype)
@@ -357,24 +357,24 @@ class PEP252Mixin:
Output("return 0;")
OutRbrace()
Output()
-
+
class PEP253Mixin(PEP252Mixin):
tp_flags = "Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE"
-
+
def outputHook_tp_init(self):
Output("%s_tp_init, /* tp_init */", self.prefix)
-
+
def outputHook_tp_alloc(self):
Output("%s_tp_alloc, /* tp_alloc */", self.prefix)
-
+
def outputHook_tp_new(self):
Output("%s_tp_new, /* tp_new */", self.prefix)
-
+
def outputHook_tp_free(self):
Output("%s_tp_free, /* tp_free */", self.prefix)
-
+
output_tp_initBody = None
-
+
def output_tp_init(self):
if self.output_tp_initBody:
Output("static int %s_tp_init(PyObject *self, PyObject *args, PyObject *kwds)", self.prefix)
@@ -384,9 +384,9 @@ class PEP253Mixin(PEP252Mixin):
else:
Output("#define %s_tp_init 0", self.prefix)
Output()
-
+
output_tp_allocBody = None
-
+
def output_tp_alloc(self):
if self.output_tp_allocBody:
Output("static PyObject *%s_tp_alloc(PyTypeObject *type, int nitems)",
@@ -397,7 +397,7 @@ class PEP253Mixin(PEP252Mixin):
else:
Output("#define %s_tp_alloc PyType_GenericAlloc", self.prefix)
Output()
-
+
def output_tp_newBody(self):
Output("PyObject *self;");
Output("%s itself;", self.itselftype);
@@ -408,7 +408,7 @@ class PEP253Mixin(PEP252Mixin):
Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;")
Output("((%s *)self)->ob_itself = itself;", self.objecttype)
Output("return self;")
-
+
def output_tp_new(self):
if self.output_tp_newBody:
Output("static PyObject *%s_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)", self.prefix)
@@ -418,9 +418,9 @@ class PEP253Mixin(PEP252Mixin):
else:
Output("#define %s_tp_new PyType_GenericNew", self.prefix)
Output()
-
+
output_tp_freeBody = None
-
+
def output_tp_free(self):
if self.output_tp_freeBody:
Output("static void %s_tp_free(PyObject *self)", self.prefix)
@@ -430,7 +430,7 @@ class PEP253Mixin(PEP252Mixin):
else:
Output("#define %s_tp_free PyObject_Del", self.prefix)
Output()
-
+
def outputPEP253Hooks(self):
self.output_tp_init()
self.output_tp_alloc()
@@ -439,7 +439,7 @@ class PEP253Mixin(PEP252Mixin):
class GlobalObjectDefinition(ObjectDefinition):
"""Like ObjectDefinition but exports some parts.
-
+
XXX Should also somehow generate a .h file for them.
"""
@@ -453,7 +453,7 @@ class ObjectIdentityMixin:
be returned by library calls and it is difficult (or impossible) to find
the corresponding Python objects. With this you can create Python object
wrappers on the fly"""
-
+
def outputCompare(self):
Output()
Output("static int %s_compare(%s *self, %s *other)", self.prefix, self.objecttype,
@@ -475,12 +475,10 @@ class ObjectIdentityMixin:
Output("if( v > w ) return 1;")
Output("return 0;")
OutRbrace()
-
+
def outputHash(self):
Output()
Output("static long %s_hash(%s *self)", self.prefix, self.objecttype)
OutLbrace()
Output("return (long)self->ob_itself;")
OutRbrace()
-
-
diff --git a/Tools/bgen/bgen/bgenOutput.py b/Tools/bgen/bgen/bgenOutput.py
index 304a52d91f..53d4f55f1c 100644
--- a/Tools/bgen/bgen/bgenOutput.py
+++ b/Tools/bgen/bgen/bgenOutput.py
@@ -30,7 +30,7 @@ def SetOutputFile(file = None, needclose = 0):
def SetOutputFileName(filename = None):
"""Call this with a filename to make it the output file.
-
+
Call it without arguments to close the current file (if necessary)
and reset it to sys.stdout.
"""
@@ -95,7 +95,7 @@ def DedentLevel(by = 1):
def OutIndent(format = "", *args):
"""Combine Output() followed by IndentLevel().
-
+
If no text is given, acts like lone IndentLevel().
"""
if format: VaOutput(format, args)
@@ -103,7 +103,7 @@ def OutIndent(format = "", *args):
def OutDedent(format = "", *args):
"""Combine Output() followed by DedentLevel().
-
+
If no text is given, acts like loneDedentLevel().
"""
if format: VaOutput(format, args)
@@ -111,7 +111,7 @@ def OutDedent(format = "", *args):
def OutLbrace(format = "", *args):
"""Like Output, but add a '{' and increase the indentation level.
-
+
If no text is given a lone '{' is output.
"""
if format:
@@ -143,13 +143,13 @@ def OutHeader2(text):
def Out(text):
"""Output multiline text that's internally indented.
-
+
Pass this a multiline character string. The whitespace before the
first nonblank line of the string will be subtracted from all lines.
The lines are then output using Output(), but without interpretation
of formatting (if you need formatting you can do it before the call).
Recommended use:
-
+
Out('''
int main(argc, argv)
int argc;
@@ -159,14 +159,14 @@ def Out(text):
exit(0);
}
''')
-
+
Caveat: the indentation must be consistent -- if you use three tabs
in the first line, (up to) three tabs are removed from following lines,
but a line beginning with 24 spaces is not trimmed at all. Don't use
this as a feature.
"""
# (Don't you love using triple quotes *inside* triple quotes? :-)
-
+
lines = text.split('\n')
indent = ""
for line in lines:
@@ -193,7 +193,7 @@ def _test():
Out("""
#include <Python.h>
#include <stdio.h>
-
+
main(argc, argv)
int argc;
char **argv;
diff --git a/Tools/bgen/bgen/bgenStringBuffer.py b/Tools/bgen/bgen/bgenStringBuffer.py
index 39c8cf9d0c..683bc0fa46 100644
--- a/Tools/bgen/bgen/bgenStringBuffer.py
+++ b/Tools/bgen/bgen/bgenStringBuffer.py
@@ -22,13 +22,13 @@ class StringBufferMixIn:
pointer is returned. These are actually easier (no allocation) but far
less common. I'll write the classes when there is demand.)
"""
-
+
def declareSize(self, name):
pass
-
+
def getargsFormat(self):
return "s"
-
+
def getargsArgs(self, name):
return "&%s__in__" % name
diff --git a/Tools/bgen/bgen/bgenType.py b/Tools/bgen/bgen/bgenType.py
index aa87aee032..4f3026a11c 100644
--- a/Tools/bgen/bgen/bgenType.py
+++ b/Tools/bgen/bgen/bgenType.py
@@ -204,8 +204,8 @@ class OpaqueType(Type):
self.convert = arg + '_Convert'
else:
# Three arguments (name, new, convert)
- self.new = arg
- self.convert = extra
+ self.new = arg
+ self.convert = extra
def getargsFormat(self):
return "O&"
@@ -236,7 +236,7 @@ class OpaqueByValueType(OpaqueType):
def mkvalueArgs(self, name):
return "%s, %s" % (self.new, name)
-
+
class OpaqueByValueStructType(OpaqueByValueType):
"""Similar to OpaqueByValueType, but we also pass this to mkvalue by
address, in stead of by value.
diff --git a/Tools/bgen/bgen/macsupport.py b/Tools/bgen/bgen/macsupport.py
index eef6db8412..7cd2b81dad 100644
--- a/Tools/bgen/bgen/macsupport.py
+++ b/Tools/bgen/bgen/macsupport.py
@@ -129,10 +129,10 @@ class VarUnicodeInputBufferType(VarInputBufferType):
def getargsFormat(self):
return "u#"
-
+
class VarUnicodeReverseInputBufferType(ReverseInputBufferMixin, VarUnicodeInputBufferType):
pass
-
+
UnicodeInBuffer = VarUnicodeInputBufferType('UniChar', 'UniCharCount', 'l')
UnicodeReverseInBuffer = VarUnicodeReverseInputBufferType('UniChar', 'UniCharCount', 'l')
UniChar_ptr = InputOnlyType("UniCharPtr", "u")
@@ -180,7 +180,7 @@ class OSErrMethodGenerator(OSErrMixIn, MethodGenerator): pass
class WeakLinkMixIn:
"Mix-in to test the function actually exists (!= NULL) before calling"
-
+
def precheck(self):
Output('#ifndef %s', self.name)
Output('PyMac_PRECHECK(%s);', self.name)
diff --git a/Tools/bgen/bgen/scantools.py b/Tools/bgen/bgen/scantools.py
index 4afd7c8927..df7ddfbe27 100644
--- a/Tools/bgen/bgen/scantools.py
+++ b/Tools/bgen/bgen/scantools.py
@@ -51,15 +51,15 @@ class Scanner:
self.setoutput(output, defsoutput)
if input:
self.setinput(input)
-
+
def initusedtypes(self):
self.usedtypes = {}
-
+
def typeused(self, type, mode):
if not self.usedtypes.has_key(type):
self.usedtypes[type] = {}
self.usedtypes[type][mode] = None
-
+
def reportusedtypes(self):
types = self.usedtypes.keys()
types.sort()
@@ -100,12 +100,12 @@ if missing: raise "Missing Types"
def writeinitialdefs(self):
pass
-
+
def initblacklists(self):
self.blacklistnames = self.makeblacklistnames()
self.blacklisttypes = ["unknown", "-"] + self.makeblacklisttypes()
self.greydictnames = self.greylist2dict(self.makegreylist())
-
+
def greylist2dict(self, list):
rv = {}
for define, namelist in list:
@@ -118,7 +118,7 @@ if missing: raise "Missing Types"
def makeblacklisttypes(self):
return []
-
+
def makegreylist(self):
return []
@@ -128,7 +128,7 @@ if missing: raise "Missing Types"
def makerepairinstructions(self):
"""Parse the repair file into repair instructions.
-
+
The file format is simple:
1) use \ to split a long logical line in multiple physical lines
2) everything after the first # on a line is ignored (as comment)
@@ -216,10 +216,10 @@ if missing: raise "Missing Types"
replacements.append(replacement)
list.append((fpat, patterns, replacements))
return list
-
+
def makeinherentpointertypes(self):
return []
-
+
def openrepairfile(self, filename = "REPAIR"):
try:
return open(filename, "rU")
@@ -337,7 +337,7 @@ if missing: raise "Missing Types"
scan = [scan]
self.allscaninputs = scan
self._nextinput()
-
+
def _nextinput(self):
if not self.allscaninputs:
return 0
@@ -526,7 +526,7 @@ if missing: raise "Missing Types"
type = type.strip()
type = re.sub("[ \t]+", "_", type)
return self.modifyarg(type, name, mode)
-
+
def modifyarg(self, type, name, mode):
if type[:6] == "const_":
type = type[6:]
@@ -567,7 +567,7 @@ if missing: raise "Missing Types"
else: # No patterns match
i = i+1
return arglist
-
+
def matcharg(self, patarg, arg):
return len(filter(None, map(fnmatch.fnmatchcase, arg, patarg))) == 3
@@ -666,4 +666,3 @@ def test():
if __name__ == '__main__':
test()
-
diff --git a/Tools/compiler/astgen.py b/Tools/compiler/astgen.py
index 90201d31e3..08d501bc3c 100644
--- a/Tools/compiler/astgen.py
+++ b/Tools/compiler/astgen.py
@@ -88,7 +88,7 @@ class NodeInfo:
self.args = self.args.replace('*', '')
self.args = self.args.replace('!', '')
self.args = self.args.replace('&', '')
-
+
return d
def gen_source(self):
@@ -158,7 +158,7 @@ class NodeInfo:
template = " nodes.%s(%sself.%s%s)"
for name in self.argnames:
if self.argprops[name] == P_NONE:
- tmp = (" if self.%s is not None:"
+ tmp = (" if self.%s is not None:"
" nodes.append(self.%s)")
print >> buf, tmp % (name, name)
elif self.argprops[name] == P_NESTED:
diff --git a/Tools/compiler/compile.py b/Tools/compiler/compile.py
index c1483c5905..9d50425d38 100644
--- a/Tools/compiler/compile.py
+++ b/Tools/compiler/compile.py
@@ -39,7 +39,7 @@ def main():
filename + ".prof")
else:
compileFile(filename, DISPLAY)
-
+
except SyntaxError, err:
print err
if err.lineno is not None:
diff --git a/Tools/compiler/demo.py b/Tools/compiler/demo.py
index e9ada5ac5a..61c54ee299 100755
--- a/Tools/compiler/demo.py
+++ b/Tools/compiler/demo.py
@@ -14,7 +14,7 @@ class MethodFinder:
Each visit method takes two arguments, the node and its current
scope. The scope is the name of the current class or None.
"""
-
+
def visitClass(self, node, scope=None):
self.visit(node.code, node.name)
@@ -22,7 +22,7 @@ class MethodFinder:
if scope is not None:
print "%s.%s" % (scope, node.name)
self.visit(node.code, None)
-
+
def main(files):
mf = MethodFinder()
for file in files:
@@ -34,5 +34,5 @@ def main(files):
if __name__ == "__main__":
import sys
-
+
main(sys.argv[1:])
diff --git a/Tools/faqwiz/faqconf.py b/Tools/faqwiz/faqconf.py
index ef01aa09f9..0057a93d7d 100644
--- a/Tools/faqwiz/faqconf.py
+++ b/Tools/faqwiz/faqconf.py
@@ -30,11 +30,11 @@ MAXHITS = 10 # Max #hits to be shown directly
COOKIE_LIFETIME = 28*24*3600 # Cookie expiration in seconds
# (28*24*3600 = 28 days = 4 weeks)
PROCESS_PREFORMAT = 1 # toggle whether preformatted text
- # will replace urls and emails with
+ # will replace urls and emails with
# HTML links
# Markers appended to title to indicate recently change
-# (may contain HTML, e.g. <IMG>); and corresponding
+# (may contain HTML, e.g. <IMG>); and corresponding
MARK_VERY_RECENT = " **" # Changed very recently
MARK_RECENT = " *" # Changed recently
diff --git a/Tools/faqwiz/faqwiz.py b/Tools/faqwiz/faqwiz.py
index a44da12e86..00cc65c472 100644
--- a/Tools/faqwiz/faqwiz.py
+++ b/Tools/faqwiz/faqwiz.py
@@ -583,7 +583,7 @@ class FaqWizard:
def do_roulette(self):
import random
files = self.dir.list()
- if not files:
+ if not files:
self.error("No entries.")
return
file = random.choice(files)
@@ -732,7 +732,7 @@ class FaqWizard:
emit(VERSIONCONFLICT, entry, self.ui)
return
commit_ok = ((not PASSWORD
- or self.ui.password == PASSWORD)
+ or self.ui.password == PASSWORD)
and self.ui.author
and '@' in self.ui.email
and self.ui.log)
@@ -820,7 +820,7 @@ class FaqWizard:
log("output: " + output)
log("done: " + str(sts))
log("TempFile:\n" + tf.read() + "end")
-
+
if not sts:
self.prologue(T_COMMITTED)
emit(COMMITTED)
diff --git a/Tools/framer/example.py b/Tools/framer/example.py
index b77f475d7b..96f6278588 100644
--- a/Tools/framer/example.py
+++ b/Tools/framer/example.py
@@ -11,7 +11,7 @@ class cStringIO(Module):
generality of StringIO, but it provides enough for most
applications and is especially useful in conjunction with the
pickle module.
-
+
Usage:
from cStringIO import StringIO
@@ -20,7 +20,7 @@ class cStringIO(Module):
an_output_stream.write(some_stuff)
...
value = an_output_stream.getvalue()
-
+
an_input_stream = StringIO(a_string)
spam = an_input_stream.readline()
spam = an_input_stream.read(5)
@@ -36,7 +36,7 @@ class cStringIO(Module):
class InputType(Type):
"Simple type for treating strings as input file streams"
-
+
abbrev = "input"
struct = """\
@@ -121,7 +121,6 @@ class cStringIO(Module):
def writelines(self, lines):
"""Write each string in lines."""
-
-cStringIO.gen()
+cStringIO.gen()
diff --git a/Tools/framer/framer/__init__.py b/Tools/framer/framer/__init__.py
index ab73a30044..d8f905898f 100644
--- a/Tools/framer/framer/__init__.py
+++ b/Tools/framer/framer/__init__.py
@@ -4,5 +4,3 @@ The basic ideas is the same as modulator, but the code generates code
using many of the new features introduced in Python 2.2. It also
takes a more declarative approach to generating code.
"""
-
-
diff --git a/Tools/framer/framer/bases.py b/Tools/framer/framer/bases.py
index 61052ab3ad..fb3cb036ec 100644
--- a/Tools/framer/framer/bases.py
+++ b/Tools/framer/framer/bases.py
@@ -64,7 +64,7 @@ class ModuleMetaclass(BaseMetaclass):
self.__types[name] = obj
if obj.has_members():
self.__members = True
-
+
def initvars(self):
v = self.__vars = {}
filename = getattr(self, "__file__", None)
@@ -83,7 +83,7 @@ class ModuleMetaclass(BaseMetaclass):
if self.__members:
p(template.member_include)
print >> f
-
+
if self.__doc__:
p(template.module_doc)
@@ -98,7 +98,7 @@ class ModuleMetaclass(BaseMetaclass):
p(template.module_init_start)
for name, type in sortitems(self.__types):
type.dump_init(f)
-
+
p("}")
class Module:
@@ -121,7 +121,7 @@ class TypeMetaclass(BaseMetaclass):
for name, func in sortitems(self.__methods):
func.dump(f)
-
+
self.dump_methoddef(f, self.__methods, self.__vars)
self.dump_memberdef(f)
self.dump_slots(f)
@@ -199,7 +199,7 @@ class TypeMetaclass(BaseMetaclass):
print >> f, templ % vars
if self.struct:
- p(template.dealloc_func, {"name" : self.__slots[TP_DEALLOC]})
+ p(template.dealloc_func, {"name" : self.__slots[TP_DEALLOC]})
p(template.type_struct_start)
for s in Slots[:-5]: # XXX
@@ -218,4 +218,3 @@ class TypeMetaclass(BaseMetaclass):
class Type:
__metaclass__ = TypeMetaclass
-
diff --git a/Tools/framer/framer/function.py b/Tools/framer/framer/function.py
index 595cc8d4ce..306f7e986d 100644
--- a/Tools/framer/framer/function.py
+++ b/Tools/framer/framer/function.py
@@ -55,7 +55,7 @@ class _ArgumentList(object):
def dump_decls(self, f):
pass
-
+
class NoArgs(_ArgumentList):
def __init__(self, args):
@@ -67,7 +67,7 @@ class NoArgs(_ArgumentList):
return "PyObject *self"
class OneArg(_ArgumentList):
-
+
def __init__(self, args):
assert len(args) == 1
super(OneArg, self).__init__(args)
@@ -139,7 +139,7 @@ class Function:
if self.__doc__:
p(template.docstring)
-
+
d = {"name" : self.vars["CName"],
"args" : self.args.c_args(),
}
@@ -149,13 +149,13 @@ class Function:
if self.args.ml_meth == METH_VARARGS:
p(template.varargs)
-
+
p(template.funcdef_end)
def analyze(self):
self.__doc__ = self._func.__doc__
self.args = ArgumentList(self._func, self.method)
-
+
def initvars(self):
v = self.vars = {}
v["PythonName"] = self._func.__name__
diff --git a/Tools/framer/framer/struct.py b/Tools/framer/framer/struct.py
index 3948740884..12ea8d7c48 100644
--- a/Tools/framer/framer/struct.py
+++ b/Tools/framer/framer/struct.py
@@ -35,7 +35,7 @@ def parse(s):
line = line.strip()
if line.startswith("}"):
break
-
+
assert line.endswith(";")
line = line[:-1]
words = line.split()
diff --git a/Tools/framer/framer/structparse.py b/Tools/framer/framer/structparse.py
index 419228a9d9..f24c0da090 100644
--- a/Tools/framer/framer/structparse.py
+++ b/Tools/framer/framer/structparse.py
@@ -29,7 +29,7 @@ def parse(s):
line = line.strip()
if line.startswith("}"):
break
-
+
assert line.endswith(";")
line = line[:-1]
words = line.split()
diff --git a/Tools/framer/framer/template.py b/Tools/framer/framer/template.py
index 8d16204822..41f95371b8 100644
--- a/Tools/framer/framer/template.py
+++ b/Tools/framer/framer/template.py
@@ -20,11 +20,11 @@ static struct PyMethodDef %(MethodDefName)s[] = {"""
methoddef_def = """\
{"%(PythonName)s", (PyCFunction)%(CName)s, %(MethType)s},"""
-
+
methoddef_def_doc = """\
{"%(PythonName)s", (PyCFunction)%(CName)s, %(MethType)s,
%(DocstringVar)s},"""
-
+
methoddef_end = """\
{NULL, NULL}
};
@@ -96,7 +96,7 @@ module_add_type = """\
type_struct_start = """\
static PyTypeObject %(CTypeName)s = {
PyObject_HEAD_INIT(0)"""
-
+
type_struct_end = """\
};
"""
diff --git a/Tools/freeze/bkfile.py b/Tools/freeze/bkfile.py
index d29716a93c..54af2fac89 100644
--- a/Tools/freeze/bkfile.py
+++ b/Tools/freeze/bkfile.py
@@ -1,47 +1,47 @@
_orig_open = open
class _BkFile:
- def __init__(self, file, mode, bufsize):
- import os
- self.__filename = file
- self.__backup = file + '~'
- try:
- os.unlink(self.__backup)
- except os.error:
- pass
- try:
- os.rename(file, self.__backup)
- except os.error:
- self.__backup = None
- self.__file = _orig_open(file, mode, bufsize)
- self.closed = self.__file.closed
- self.fileno = self.__file.fileno
- self.flush = self.__file.flush
- self.isatty = self.__file.isatty
- self.mode = self.__file.mode
- self.name = self.__file.name
- self.read = self.__file.read
- self.readinto = self.__file.readinto
- self.readline = self.__file.readline
- self.readlines = self.__file.readlines
- self.seek = self.__file.seek
- self.softspace = self.__file.softspace
- self.tell = self.__file.tell
- self.truncate = self.__file.truncate
- self.write = self.__file.write
- self.writelines = self.__file.writelines
+ def __init__(self, file, mode, bufsize):
+ import os
+ self.__filename = file
+ self.__backup = file + '~'
+ try:
+ os.unlink(self.__backup)
+ except os.error:
+ pass
+ try:
+ os.rename(file, self.__backup)
+ except os.error:
+ self.__backup = None
+ self.__file = _orig_open(file, mode, bufsize)
+ self.closed = self.__file.closed
+ self.fileno = self.__file.fileno
+ self.flush = self.__file.flush
+ self.isatty = self.__file.isatty
+ self.mode = self.__file.mode
+ self.name = self.__file.name
+ self.read = self.__file.read
+ self.readinto = self.__file.readinto
+ self.readline = self.__file.readline
+ self.readlines = self.__file.readlines
+ self.seek = self.__file.seek
+ self.softspace = self.__file.softspace
+ self.tell = self.__file.tell
+ self.truncate = self.__file.truncate
+ self.write = self.__file.write
+ self.writelines = self.__file.writelines
- def close(self):
- self.__file.close()
- if self.__backup is None:
- return
- import filecmp
- if filecmp.cmp(self.__backup, self.__filename, shallow = 0):
- import os
- os.unlink(self.__filename)
- os.rename(self.__backup, self.__filename)
+ def close(self):
+ self.__file.close()
+ if self.__backup is None:
+ return
+ import filecmp
+ if filecmp.cmp(self.__backup, self.__filename, shallow = 0):
+ import os
+ os.unlink(self.__filename)
+ os.rename(self.__backup, self.__filename)
def open(file, mode = 'r', bufsize = -1):
- if 'w' not in mode:
- return _orig_open(file, mode, bufsize)
- return _BkFile(file, mode, bufsize)
+ if 'w' not in mode:
+ return _orig_open(file, mode, bufsize)
+ return _BkFile(file, mode, bufsize)
diff --git a/Tools/freeze/checkextensions.py b/Tools/freeze/checkextensions.py
index 584f8a66db..334521f559 100644
--- a/Tools/freeze/checkextensions.py
+++ b/Tools/freeze/checkextensions.py
@@ -6,85 +6,85 @@ import os
import parsesetup
def checkextensions(unknown, extensions):
- files = []
- modules = []
- edict = {}
- for e in extensions:
- setup = os.path.join(e, 'Setup')
- liba = os.path.join(e, 'lib.a')
- if not os.path.isfile(liba):
- liba = None
- edict[e] = parsesetup.getsetupinfo(setup), liba
- for mod in unknown:
- for e in extensions:
- (mods, vars), liba = edict[e]
- if not mods.has_key(mod):
- continue
- modules.append(mod)
- if liba:
- # If we find a lib.a, use it, ignore the
- # .o files, and use *all* libraries for
- # *all* modules in the Setup file
- if liba in files:
- break
- files.append(liba)
- for m in mods.keys():
- files = files + select(e, mods, vars,
- m, 1)
- break
- files = files + select(e, mods, vars, mod, 0)
- break
- return files, modules
+ files = []
+ modules = []
+ edict = {}
+ for e in extensions:
+ setup = os.path.join(e, 'Setup')
+ liba = os.path.join(e, 'lib.a')
+ if not os.path.isfile(liba):
+ liba = None
+ edict[e] = parsesetup.getsetupinfo(setup), liba
+ for mod in unknown:
+ for e in extensions:
+ (mods, vars), liba = edict[e]
+ if not mods.has_key(mod):
+ continue
+ modules.append(mod)
+ if liba:
+ # If we find a lib.a, use it, ignore the
+ # .o files, and use *all* libraries for
+ # *all* modules in the Setup file
+ if liba in files:
+ break
+ files.append(liba)
+ for m in mods.keys():
+ files = files + select(e, mods, vars,
+ m, 1)
+ break
+ files = files + select(e, mods, vars, mod, 0)
+ break
+ return files, modules
def select(e, mods, vars, mod, skipofiles):
- files = []
- for w in mods[mod]:
- w = treatword(w)
- if not w:
- continue
- w = expandvars(w, vars)
- for w in w.split():
- if skipofiles and w[-2:] == '.o':
- continue
- # Assume $var expands to absolute pathname
- if w[0] not in ('-', '$') and w[-2:] in ('.o', '.a'):
- w = os.path.join(e, w)
- if w[:2] in ('-L', '-R') and w[2:3] != '$':
- w = w[:2] + os.path.join(e, w[2:])
- files.append(w)
- return files
+ files = []
+ for w in mods[mod]:
+ w = treatword(w)
+ if not w:
+ continue
+ w = expandvars(w, vars)
+ for w in w.split():
+ if skipofiles and w[-2:] == '.o':
+ continue
+ # Assume $var expands to absolute pathname
+ if w[0] not in ('-', '$') and w[-2:] in ('.o', '.a'):
+ w = os.path.join(e, w)
+ if w[:2] in ('-L', '-R') and w[2:3] != '$':
+ w = w[:2] + os.path.join(e, w[2:])
+ files.append(w)
+ return files
cc_flags = ['-I', '-D', '-U']
cc_exts = ['.c', '.C', '.cc', '.c++']
def treatword(w):
- if w[:2] in cc_flags:
- return None
- if w[:1] == '-':
- return w # Assume loader flag
- head, tail = os.path.split(w)
- base, ext = os.path.splitext(tail)
- if ext in cc_exts:
- tail = base + '.o'
- w = os.path.join(head, tail)
- return w
+ if w[:2] in cc_flags:
+ return None
+ if w[:1] == '-':
+ return w # Assume loader flag
+ head, tail = os.path.split(w)
+ base, ext = os.path.splitext(tail)
+ if ext in cc_exts:
+ tail = base + '.o'
+ w = os.path.join(head, tail)
+ return w
def expandvars(str, vars):
- i = 0
- while i < len(str):
- i = k = str.find('$', i)
- if i < 0:
- break
- i = i+1
- var = str[i:i+1]
- i = i+1
- if var == '(':
- j = str.find(')', i)
- if j < 0:
- break
- var = str[i:j]
- i = j+1
- if vars.has_key(var):
- str = str[:k] + vars[var] + str[i:]
- i = k
- return str
+ i = 0
+ while i < len(str):
+ i = k = str.find('$', i)
+ if i < 0:
+ break
+ i = i+1
+ var = str[i:i+1]
+ i = i+1
+ if var == '(':
+ j = str.find(')', i)
+ if j < 0:
+ break
+ var = str[i:j]
+ i = j+1
+ if vars.has_key(var):
+ str = str[:k] + vars[var] + str[i:]
+ i = k
+ return str
diff --git a/Tools/freeze/checkextensions_win32.py b/Tools/freeze/checkextensions_win32.py
index 9a7a6dccec..a198ecf39b 100644
--- a/Tools/freeze/checkextensions_win32.py
+++ b/Tools/freeze/checkextensions_win32.py
@@ -24,142 +24,142 @@ but an obvious enhancement would be to provide command line options.
import os, sys
try:
- import win32api
+ import win32api
except ImportError:
- win32api = None # User has already been warned
+ win32api = None # User has already been warned
class CExtension:
- """An abstraction of an extension implemented in C/C++
- """
- def __init__(self, name, sourceFiles):
- self.name = name
- # A list of strings defining additional compiler options.
- self.sourceFiles = sourceFiles
- # A list of special compiler options to be applied to
- # all source modules in this extension.
- self.compilerOptions = []
- # A list of .lib files the final .EXE will need.
- self.linkerLibs = []
-
- def GetSourceFiles(self):
- return self.sourceFiles
-
- def AddCompilerOption(self, option):
- self.compilerOptions.append(option)
- def GetCompilerOptions(self):
- return self.compilerOptions
-
- def AddLinkerLib(self, lib):
- self.linkerLibs.append(lib)
- def GetLinkerLibs(self):
- return self.linkerLibs
+ """An abstraction of an extension implemented in C/C++
+ """
+ def __init__(self, name, sourceFiles):
+ self.name = name
+ # A list of strings defining additional compiler options.
+ self.sourceFiles = sourceFiles
+ # A list of special compiler options to be applied to
+ # all source modules in this extension.
+ self.compilerOptions = []
+ # A list of .lib files the final .EXE will need.
+ self.linkerLibs = []
+
+ def GetSourceFiles(self):
+ return self.sourceFiles
+
+ def AddCompilerOption(self, option):
+ self.compilerOptions.append(option)
+ def GetCompilerOptions(self):
+ return self.compilerOptions
+
+ def AddLinkerLib(self, lib):
+ self.linkerLibs.append(lib)
+ def GetLinkerLibs(self):
+ return self.linkerLibs
def checkextensions(unknown, extra_inis, prefix):
- # Create a table of frozen extensions
-
- defaultMapName = os.path.join( os.path.split(sys.argv[0])[0], "extensions_win32.ini")
- if not os.path.isfile(defaultMapName):
- sys.stderr.write("WARNING: %s can not be found - standard extensions may not be found\n" % defaultMapName)
- else:
- # must go on end, so other inis can override.
- extra_inis.append(defaultMapName)
-
- ret = []
- for mod in unknown:
- for ini in extra_inis:
-# print "Looking for", mod, "in", win32api.GetFullPathName(ini),"...",
- defn = get_extension_defn( mod, ini, prefix )
- if defn is not None:
-# print "Yay - found it!"
- ret.append( defn )
- break
-# print "Nope!"
- else: # For not broken!
- sys.stderr.write("No definition of module %s in any specified map file.\n" % (mod))
-
- return ret
+ # Create a table of frozen extensions
+
+ defaultMapName = os.path.join( os.path.split(sys.argv[0])[0], "extensions_win32.ini")
+ if not os.path.isfile(defaultMapName):
+ sys.stderr.write("WARNING: %s can not be found - standard extensions may not be found\n" % defaultMapName)
+ else:
+ # must go on end, so other inis can override.
+ extra_inis.append(defaultMapName)
+
+ ret = []
+ for mod in unknown:
+ for ini in extra_inis:
+# print "Looking for", mod, "in", win32api.GetFullPathName(ini),"...",
+ defn = get_extension_defn( mod, ini, prefix )
+ if defn is not None:
+# print "Yay - found it!"
+ ret.append( defn )
+ break
+# print "Nope!"
+ else: # For not broken!
+ sys.stderr.write("No definition of module %s in any specified map file.\n" % (mod))
+
+ return ret
def get_extension_defn(moduleName, mapFileName, prefix):
- if win32api is None: return None
- os.environ['PYTHONPREFIX'] = prefix
- dsp = win32api.GetProfileVal(moduleName, "dsp", "", mapFileName)
- if dsp=="":
- return None
-
- # We allow environment variables in the file name
- dsp = win32api.ExpandEnvironmentStrings(dsp)
- # If the path to the .DSP file is not absolute, assume it is relative
- # to the description file.
- if not os.path.isabs(dsp):
- dsp = os.path.join( os.path.split(mapFileName)[0], dsp)
- # Parse it to extract the source files.
- sourceFiles = parse_dsp(dsp)
- if sourceFiles is None:
- return None
-
- module = CExtension(moduleName, sourceFiles)
- # Put the path to the DSP into the environment so entries can reference it.
- os.environ['dsp_path'] = os.path.split(dsp)[0]
- os.environ['ini_path'] = os.path.split(mapFileName)[0]
-
- cl_options = win32api.GetProfileVal(moduleName, "cl", "", mapFileName)
- if cl_options:
- module.AddCompilerOption(win32api.ExpandEnvironmentStrings(cl_options))
-
- exclude = win32api.GetProfileVal(moduleName, "exclude", "", mapFileName)
- exclude = exclude.split()
-
- if win32api.GetProfileVal(moduleName, "Unicode", 0, mapFileName):
- module.AddCompilerOption('/D UNICODE /D _UNICODE')
-
- libs = win32api.GetProfileVal(moduleName, "libs", "", mapFileName).split()
- for lib in libs:
- module.AddLinkerLib(win32api.ExpandEnvironmentStrings(lib))
-
- for exc in exclude:
- if exc in module.sourceFiles:
- modules.sourceFiles.remove(exc)
-
- return module
+ if win32api is None: return None
+ os.environ['PYTHONPREFIX'] = prefix
+ dsp = win32api.GetProfileVal(moduleName, "dsp", "", mapFileName)
+ if dsp=="":
+ return None
+
+ # We allow environment variables in the file name
+ dsp = win32api.ExpandEnvironmentStrings(dsp)
+ # If the path to the .DSP file is not absolute, assume it is relative
+ # to the description file.
+ if not os.path.isabs(dsp):
+ dsp = os.path.join( os.path.split(mapFileName)[0], dsp)
+ # Parse it to extract the source files.
+ sourceFiles = parse_dsp(dsp)
+ if sourceFiles is None:
+ return None
+
+ module = CExtension(moduleName, sourceFiles)
+ # Put the path to the DSP into the environment so entries can reference it.
+ os.environ['dsp_path'] = os.path.split(dsp)[0]
+ os.environ['ini_path'] = os.path.split(mapFileName)[0]
+
+ cl_options = win32api.GetProfileVal(moduleName, "cl", "", mapFileName)
+ if cl_options:
+ module.AddCompilerOption(win32api.ExpandEnvironmentStrings(cl_options))
+
+ exclude = win32api.GetProfileVal(moduleName, "exclude", "", mapFileName)
+ exclude = exclude.split()
+
+ if win32api.GetProfileVal(moduleName, "Unicode", 0, mapFileName):
+ module.AddCompilerOption('/D UNICODE /D _UNICODE')
+
+ libs = win32api.GetProfileVal(moduleName, "libs", "", mapFileName).split()
+ for lib in libs:
+ module.AddLinkerLib(win32api.ExpandEnvironmentStrings(lib))
+
+ for exc in exclude:
+ if exc in module.sourceFiles:
+ modules.sourceFiles.remove(exc)
+
+ return module
# Given an MSVC DSP file, locate C source files it uses
# returns a list of source files.
def parse_dsp(dsp):
-# print "Processing", dsp
- # For now, only support
- ret = []
- dsp_path, dsp_name = os.path.split(dsp)
- try:
- lines = open(dsp, "r").readlines()
- except IOError, msg:
- sys.stderr.write("%s: %s\n" % (dsp, msg))
- return None
- for line in lines:
- fields = line.strip().split("=", 2)
- if fields[0]=="SOURCE":
- if os.path.splitext(fields[1])[1].lower() in ['.cpp', '.c']:
- ret.append( win32api.GetFullPathName(os.path.join(dsp_path, fields[1] ) ) )
- return ret
+# print "Processing", dsp
+ # For now, only support
+ ret = []
+ dsp_path, dsp_name = os.path.split(dsp)
+ try:
+ lines = open(dsp, "r").readlines()
+ except IOError, msg:
+ sys.stderr.write("%s: %s\n" % (dsp, msg))
+ return None
+ for line in lines:
+ fields = line.strip().split("=", 2)
+ if fields[0]=="SOURCE":
+ if os.path.splitext(fields[1])[1].lower() in ['.cpp', '.c']:
+ ret.append( win32api.GetFullPathName(os.path.join(dsp_path, fields[1] ) ) )
+ return ret
def write_extension_table(fname, modules):
- fp = open(fname, "w")
- try:
- fp.write (ext_src_header)
- # Write fn protos
- for module in modules:
- # bit of a hack for .pyd's as part of packages.
- name = module.name.split('.')[-1]
- fp.write('extern void init%s(void);\n' % (name) )
- # Write the table
- fp.write (ext_tab_header)
- for module in modules:
- name = module.name.split('.')[-1]
- fp.write('\t{"%s", init%s},\n' % (name, name) )
-
- fp.write (ext_tab_footer)
- fp.write(ext_src_footer)
- finally:
- fp.close()
+ fp = open(fname, "w")
+ try:
+ fp.write (ext_src_header)
+ # Write fn protos
+ for module in modules:
+ # bit of a hack for .pyd's as part of packages.
+ name = module.name.split('.')[-1]
+ fp.write('extern void init%s(void);\n' % (name) )
+ # Write the table
+ fp.write (ext_tab_header)
+ for module in modules:
+ name = module.name.split('.')[-1]
+ fp.write('\t{"%s", init%s},\n' % (name, name) )
+
+ fp.write (ext_tab_footer)
+ fp.write(ext_src_footer)
+ finally:
+ fp.close()
ext_src_header = """\
@@ -182,9 +182,7 @@ extern DL_IMPORT(int) PyImport_ExtendInittab(struct _inittab *newtab);
int PyInitFrozenExtensions()
{
- return PyImport_ExtendInittab(extensions);
+ return PyImport_ExtendInittab(extensions);
}
"""
-
-
diff --git a/Tools/freeze/freeze.py b/Tools/freeze/freeze.py
index c2c3c2e14d..836f53261f 100755
--- a/Tools/freeze/freeze.py
+++ b/Tools/freeze/freeze.py
@@ -57,15 +57,15 @@ Options:
are read and the -i option replaced with the parsed
params (note - quoting args in this file is NOT supported)
--s subsystem: Specify the subsystem (For Windows only.);
+-s subsystem: Specify the subsystem (For Windows only.);
'console' (default), 'windows', 'service' or 'com_dll'
-
+
-w: Toggle Windows (NT or 95) behavior.
(For debugging only -- on a win32 platform, win32 behavior
is automatic.)
-r prefix=f: Replace path prefix.
- Replace prefix with f in the source path references
+ Replace prefix with f in the source path references
contained in the resulting binary.
Arguments:
@@ -335,7 +335,7 @@ def main():
winmakemakefile.get_custom_entry_point(subsystem)
except ValueError, why:
usage(why)
-
+
# Actual work starts here...
@@ -343,7 +343,7 @@ def main():
dir = os.path.dirname(scriptfile)
path[0] = dir
mf = modulefinder.ModuleFinder(path, debug, exclude, replace_paths)
-
+
if win and subsystem=='service':
# If a Windows service, then add the "built-in" module.
mod = mf.add_module("servicemanager")
@@ -411,7 +411,7 @@ def main():
else:
# Do the windows thang...
import checkextensions_win32
- # Get a list of CExtension instances, each describing a module
+ # Get a list of CExtension instances, each describing a module
# (including its source files)
frozen_extensions = checkextensions_win32.checkextensions(
unknown, extensions, prefix)
diff --git a/Tools/freeze/makeconfig.py b/Tools/freeze/makeconfig.py
index 2f04ac7f57..7cd9b78478 100644
--- a/Tools/freeze/makeconfig.py
+++ b/Tools/freeze/makeconfig.py
@@ -6,56 +6,56 @@ import re
never = ['marshal', '__main__', '__builtin__', 'sys', 'exceptions']
def makeconfig(infp, outfp, modules, with_ifdef=0):
- m1 = re.compile('-- ADDMODULE MARKER 1 --')
- m2 = re.compile('-- ADDMODULE MARKER 2 --')
- while 1:
- line = infp.readline()
- if not line: break
- outfp.write(line)
- if m1 and m1.search(line):
- m1 = None
- for mod in modules:
- if mod in never:
- continue
- if with_ifdef:
- outfp.write("#ifndef init%s\n"%mod)
- outfp.write('extern void init%s(void);\n' % mod)
- if with_ifdef:
- outfp.write("#endif\n")
- elif m2 and m2.search(line):
- m2 = None
- for mod in modules:
- if mod in never:
- continue
- outfp.write('\t{"%s", init%s},\n' %
- (mod, mod))
- if m1:
- sys.stderr.write('MARKER 1 never found\n')
- elif m2:
- sys.stderr.write('MARKER 2 never found\n')
+ m1 = re.compile('-- ADDMODULE MARKER 1 --')
+ m2 = re.compile('-- ADDMODULE MARKER 2 --')
+ while 1:
+ line = infp.readline()
+ if not line: break
+ outfp.write(line)
+ if m1 and m1.search(line):
+ m1 = None
+ for mod in modules:
+ if mod in never:
+ continue
+ if with_ifdef:
+ outfp.write("#ifndef init%s\n"%mod)
+ outfp.write('extern void init%s(void);\n' % mod)
+ if with_ifdef:
+ outfp.write("#endif\n")
+ elif m2 and m2.search(line):
+ m2 = None
+ for mod in modules:
+ if mod in never:
+ continue
+ outfp.write('\t{"%s", init%s},\n' %
+ (mod, mod))
+ if m1:
+ sys.stderr.write('MARKER 1 never found\n')
+ elif m2:
+ sys.stderr.write('MARKER 2 never found\n')
# Test program.
def test():
- import sys
- if not sys.argv[3:]:
- print 'usage: python makeconfig.py config.c.in outputfile',
- print 'modulename ...'
- sys.exit(2)
- if sys.argv[1] == '-':
- infp = sys.stdin
- else:
- infp = open(sys.argv[1])
- if sys.argv[2] == '-':
- outfp = sys.stdout
- else:
- outfp = open(sys.argv[2], 'w')
- makeconfig(infp, outfp, sys.argv[3:])
- if outfp != sys.stdout:
- outfp.close()
- if infp != sys.stdin:
- infp.close()
+ import sys
+ if not sys.argv[3:]:
+ print 'usage: python makeconfig.py config.c.in outputfile',
+ print 'modulename ...'
+ sys.exit(2)
+ if sys.argv[1] == '-':
+ infp = sys.stdin
+ else:
+ infp = open(sys.argv[1])
+ if sys.argv[2] == '-':
+ outfp = sys.stdout
+ else:
+ outfp = open(sys.argv[2], 'w')
+ makeconfig(infp, outfp, sys.argv[3:])
+ if outfp != sys.stdout:
+ outfp.close()
+ if infp != sys.stdin:
+ infp.close()
if __name__ == '__main__':
- test()
+ test()
diff --git a/Tools/freeze/makefreeze.py b/Tools/freeze/makefreeze.py
index 9ff348c59a..1208b67fe0 100644
--- a/Tools/freeze/makefreeze.py
+++ b/Tools/freeze/makefreeze.py
@@ -19,7 +19,7 @@ default_entry_point = """
int
main(int argc, char **argv)
{
- extern int Py_FrozenMain(int, char **);
+ extern int Py_FrozenMain(int, char **);
""" + ((not __debug__ and """
Py_OptimizeFlag++;
""") or "") + """
diff --git a/Tools/freeze/makemakefile.py b/Tools/freeze/makemakefile.py
index b8b99b8768..ff8b15a199 100644
--- a/Tools/freeze/makemakefile.py
+++ b/Tools/freeze/makemakefile.py
@@ -23,7 +23,7 @@ def makemakefile(outfp, makevars, files, target):
deps.append(dest)
outfp.write("\n%s: %s\n" % (target, ' '.join(deps)))
- outfp.write("\t$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) %s -o %s $(LDLAST)\n" %
+ outfp.write("\t$(LINKCC) $(LDFLAGS) $(LINKFORSHARED) %s -o %s $(LDLAST)\n" %
(' '.join(files), target))
outfp.write("\nclean:\n\t-rm -f *.o %s\n" % target)
diff --git a/Tools/freeze/parsesetup.py b/Tools/freeze/parsesetup.py
index 2b9123ea4d..856234d443 100644
--- a/Tools/freeze/parsesetup.py
+++ b/Tools/freeze/parsesetup.py
@@ -10,32 +10,32 @@ import re
makevardef = re.compile('^([a-zA-Z0-9_]+)[ \t]*=(.*)')
def getmakevars(filename):
- variables = {}
- fp = open(filename)
- pendingline = ""
- try:
- while 1:
- line = fp.readline()
- if pendingline:
- line = pendingline + line
- pendingline = ""
- if not line:
- break
- if line.endswith('\\\n'):
- pendingline = line[:-2]
- matchobj = makevardef.match(line)
- if not matchobj:
- continue
- (name, value) = matchobj.group(1, 2)
- # Strip trailing comment
- i = value.find('#')
- if i >= 0:
- value = value[:i]
- value = value.strip()
- variables[name] = value
- finally:
- fp.close()
- return variables
+ variables = {}
+ fp = open(filename)
+ pendingline = ""
+ try:
+ while 1:
+ line = fp.readline()
+ if pendingline:
+ line = pendingline + line
+ pendingline = ""
+ if not line:
+ break
+ if line.endswith('\\\n'):
+ pendingline = line[:-2]
+ matchobj = makevardef.match(line)
+ if not matchobj:
+ continue
+ (name, value) = matchobj.group(1, 2)
+ # Strip trailing comment
+ i = value.find('#')
+ if i >= 0:
+ value = value[:i]
+ value = value.strip()
+ variables[name] = value
+ finally:
+ fp.close()
+ return variables
# Parse a Python Setup(.in) file.
@@ -46,67 +46,67 @@ def getmakevars(filename):
setupvardef = re.compile('^([a-zA-Z0-9_]+)=(.*)')
def getsetupinfo(filename):
- modules = {}
- variables = {}
- fp = open(filename)
- pendingline = ""
- try:
- while 1:
- line = fp.readline()
- if pendingline:
- line = pendingline + line
- pendingline = ""
- if not line:
- break
- # Strip comments
- i = line.find('#')
- if i >= 0:
- line = line[:i]
- if line.endswith('\\\n'):
- pendingline = line[:-2]
- continue
- matchobj = setupvardef.match(line)
- if matchobj:
- (name, value) = matchobj.group(1, 2)
- variables[name] = value.strip()
- else:
- words = line.split()
- if words:
- modules[words[0]] = words[1:]
- finally:
- fp.close()
- return modules, variables
+ modules = {}
+ variables = {}
+ fp = open(filename)
+ pendingline = ""
+ try:
+ while 1:
+ line = fp.readline()
+ if pendingline:
+ line = pendingline + line
+ pendingline = ""
+ if not line:
+ break
+ # Strip comments
+ i = line.find('#')
+ if i >= 0:
+ line = line[:i]
+ if line.endswith('\\\n'):
+ pendingline = line[:-2]
+ continue
+ matchobj = setupvardef.match(line)
+ if matchobj:
+ (name, value) = matchobj.group(1, 2)
+ variables[name] = value.strip()
+ else:
+ words = line.split()
+ if words:
+ modules[words[0]] = words[1:]
+ finally:
+ fp.close()
+ return modules, variables
# Test the above functions.
def test():
- import sys
- import os
- if not sys.argv[1:]:
- print 'usage: python parsesetup.py Makefile*|Setup* ...'
- sys.exit(2)
- for arg in sys.argv[1:]:
- base = os.path.basename(arg)
- if base[:8] == 'Makefile':
- print 'Make style parsing:', arg
- v = getmakevars(arg)
- prdict(v)
- elif base[:5] == 'Setup':
- print 'Setup style parsing:', arg
- m, v = getsetupinfo(arg)
- prdict(m)
- prdict(v)
- else:
- print arg, 'is neither a Makefile nor a Setup file'
- print '(name must begin with "Makefile" or "Setup")'
+ import sys
+ import os
+ if not sys.argv[1:]:
+ print 'usage: python parsesetup.py Makefile*|Setup* ...'
+ sys.exit(2)
+ for arg in sys.argv[1:]:
+ base = os.path.basename(arg)
+ if base[:8] == 'Makefile':
+ print 'Make style parsing:', arg
+ v = getmakevars(arg)
+ prdict(v)
+ elif base[:5] == 'Setup':
+ print 'Setup style parsing:', arg
+ m, v = getsetupinfo(arg)
+ prdict(m)
+ prdict(v)
+ else:
+ print arg, 'is neither a Makefile nor a Setup file'
+ print '(name must begin with "Makefile" or "Setup")'
def prdict(d):
- keys = d.keys()
- keys.sort()
- for key in keys:
- value = d[key]
- print "%-15s" % key, str(value)
+ keys = d.keys()
+ keys.sort()
+ for key in keys:
+ value = d[key]
+ print "%-15s" % key, str(value)
if __name__ == '__main__':
- test()
+ test()
diff --git a/Tools/i18n/msgfmt.py b/Tools/i18n/msgfmt.py
index 8a2d4e66e7..b4ae3e9437 100755
--- a/Tools/i18n/msgfmt.py
+++ b/Tools/i18n/msgfmt.py
@@ -113,7 +113,7 @@ def make(filename, outfile):
except IOError, msg:
print >> sys.stderr, msg
sys.exit(1)
-
+
section = None
fuzzy = 0
@@ -169,7 +169,7 @@ def make(filename, outfile):
open(outfile,"wb").write(output)
except IOError,msg:
print >> sys.stderr, msg
-
+
def main():
diff --git a/Tools/modulator/Tkextra.py b/Tools/modulator/Tkextra.py
index 00ed5eb981..8f557286f5 100755
--- a/Tools/modulator/Tkextra.py
+++ b/Tools/modulator/Tkextra.py
@@ -105,7 +105,7 @@ def strdialog(master, title, text, bitmap, default, *args):
{'width': '3i',
'text': text,
'font': '-Adobe-Times-Medium-R-Normal-*-180-*',
- Pack: {'side': 'left',
+ Pack: {'side': 'left',
'fill': 'both',
'padx': '3m', 'pady': '3m'}})
@@ -187,7 +187,7 @@ def askstr(str):
def askfile(str): # XXXX For now...
i = strdialog(mainWidget, 'Question', str, '', 0)
return i
-
+
# The rest is the test program.
def _go():
diff --git a/Tools/modulator/genmodule.py b/Tools/modulator/genmodule.py
index 5788b95579..da3068472d 100755
--- a/Tools/modulator/genmodule.py
+++ b/Tools/modulator/genmodule.py
@@ -65,7 +65,7 @@ class writer:
return open(fn, 'r')
raise error, 'Template '+name+' not found for '+self._type+' '+ \
self.name
-
+
class module(writer):
_type = 'module'
@@ -116,7 +116,7 @@ class object(writer):
# Add getattr if we have methods
if self.methodlist and not 'tp_getattr' in self.funclist:
self.funclist.insert(0, 'tp_getattr')
-
+
for fn in FUNCLIST:
setattr(self, fn, '0')
diff --git a/Tools/modulator/modulator.py b/Tools/modulator/modulator.py
index 48287431b0..3e06bc2378 100755
--- a/Tools/modulator/modulator.py
+++ b/Tools/modulator/modulator.py
@@ -49,7 +49,7 @@ def getlistlist(list):
for i in range(n):
rv.append(list.get(i))
return rv
-
+
class UI:
def __init__(self):
self.main = Frame()
@@ -97,7 +97,7 @@ class UI:
o.synchronize()
except oops:
pass
-
+
def cb_save(self, *args):
try:
pycode = self.module.gencode('m', self.objects)
@@ -177,12 +177,12 @@ class UI_module:
'command':self.cb_newobj,
Pack:{'side':'left',
'padx':'0.5m'}})
-
+
def cb_delmethod(self, *args):
list = self.method_list.curselection()
for i in list:
self.method_list.delete(i)
-
+
def cb_newobj(self, *arg):
self.parent.objects.append(UI_object(self.parent))
@@ -208,7 +208,7 @@ class UI_module:
if not checkid(n):
message('Method name not an identifier:\n'+n)
raise oops
-
+
def gencode(self, name, objects):
rv = ''
self.synchronize()
@@ -226,7 +226,7 @@ class UI_module:
rv = rv + '%s.objects = [%s]\n' % (name, ','.join(onames))
rv = rv + '\n'
return rv
-
+
object_number = 0
class UI_object:
@@ -250,7 +250,7 @@ class UI_object:
'fill':'x'}})
self.f4 = Frame(self.frame, {Pack:{'side':'top', 'pady':'0.5m',
'fill':'x'}})
-
+
self.l1 = Label(self.f1, {'text':'Object:', Pack:{'side':'left',
'padx':'0.5m'}})
@@ -305,7 +305,7 @@ class UI_object:
Pack:{'side':'top', 'pady':'0.5m',
'anchor':'w'}})
self.types[i] = b
-
+
def cb_method(self, *arg):
name = self.method_entry.get()
if not name:
@@ -317,7 +317,7 @@ class UI_object:
list = self.method_list.curselection()
for i in list:
self.method_list.delete(i)
-
+
def synchronize(self):
n = self.name_entry.get()
if not n:
@@ -337,7 +337,7 @@ class UI_object:
if m:
self.f5.setvar(self.vpref+'tp_getattr', 1)
pass
-
+
def gencode(self, name):
rv = ''
rv = rv + '%s = genmodule.object()\n' % (name,)
@@ -356,12 +356,12 @@ class UI_object:
vname = self.vpref + fn
if self.f5.getvar(vname) == '1':
fl.append(fn)
-
+
rv = rv + '%s.typelist = %r\n' % (name, fl)
rv = rv + '\n'
return rv
-
+
def main():
if len(sys.argv) < 2:
@@ -379,5 +379,5 @@ def main():
else:
sys.stderr.write('Usage: modulator [file]\n')
sys.exit(1)
-
+
main()
diff --git a/Tools/modulator/varsubst.py b/Tools/modulator/varsubst.py
index 5516be2add..3b33950650 100644
--- a/Tools/modulator/varsubst.py
+++ b/Tools/modulator/varsubst.py
@@ -13,7 +13,7 @@ class Varsubst:
def useindent(self, onoff):
self.do_useindent = onoff
-
+
def subst(self, s):
rv = ''
while 1:
diff --git a/Tools/pynche/ChipViewer.py b/Tools/pynche/ChipViewer.py
index faa6948d3e..05412cec48 100644
--- a/Tools/pynche/ChipViewer.py
+++ b/Tools/pynche/ChipViewer.py
@@ -101,7 +101,7 @@ class ChipViewer:
# shows the name of the nearest color in the database. BAW: should
# an exact match be indicated in some way?
#
- # Always use the #rrggbb style to actually set the color, since we may
+ # Always use the #rrggbb style to actually set the color, since we may
# not be using X color names (e.g. "web-safe" names)
colordb = self.__sb.colordb()
rgbtuple = (red, green, blue)
diff --git a/Tools/pynche/DetailsViewer.py b/Tools/pynche/DetailsViewer.py
index 07f5acd804..11a99a6afc 100644
--- a/Tools/pynche/DetailsViewer.py
+++ b/Tools/pynche/DetailsViewer.py
@@ -2,13 +2,13 @@
This class implements a pure input window which allows you to meticulously
edit the current color. You have both mouse control of the color (via the
-buttons along the bottom row), and there are keyboard bindings for each of the
+buttons along the bottom row), and there are keyboard bindings for each of the
increment/decrement buttons.
The top three check buttons allow you to specify which of the three color
variations are tied together when incrementing and decrementing. Red, green,
and blue are self evident. By tying together red and green, you can modify
-the yellow level of the color. By tying together red and blue, you can modify
+the yellow level of the color. By tying together red and blue, you can modify
the magenta level of the color. By tying together green and blue, you can
modify the cyan level, and by tying all three together, you can modify the
grey level.
diff --git a/Tools/pynche/StripViewer.py b/Tools/pynche/StripViewer.py
index 429cc78436..f7da479dcc 100644
--- a/Tools/pynche/StripViewer.py
+++ b/Tools/pynche/StripViewer.py
@@ -1,6 +1,6 @@
"""Strip viewer and related widgets.
-The classes in this file implement the StripViewer shown in the top two thirds
+The classes in this file implement the StripViewer shown in the top two thirds
of the main Pynche window. It consists of three StripWidgets which display
the variations in red, green, and blue respectively of the currently selected
r/g/b color value.
@@ -182,7 +182,7 @@ class StripWidget:
# the last chip selected
self.__lastchip = None
self.__sb = switchboard
-
+
canvaswidth = numchips * (chipwidth + 1)
canvasheight = chipheight + 43 # BAW: Kludge
@@ -372,7 +372,7 @@ class StripViewer:
hexbtn.grid(row=1, column=1, sticky=W)
# XXX: ignore this feature for now; it doesn't work quite right yet
-
+
## gentypevar = self.__gentypevar = IntVar()
## self.__variations = Radiobutton(frame,
## text='Variations',
diff --git a/Tools/unicode/mkstringprep.py b/Tools/unicode/mkstringprep.py
index c621967ba0..2525f9e5e6 100644
--- a/Tools/unicode/mkstringprep.py
+++ b/Tools/unicode/mkstringprep.py
@@ -429,4 +429,3 @@ print """
def in_table_d2(code):
return unicodedata.bidirectional(code) == "L"
"""
-
diff --git a/Tools/versioncheck/checkversions.py b/Tools/versioncheck/checkversions.py
index 956f553990..fd128b6002 100644
--- a/Tools/versioncheck/checkversions.py
+++ b/Tools/versioncheck/checkversions.py
@@ -1,4 +1,4 @@
-"""Checkversions - recursively search a directory (default: sys.prefix)
+"""Checkversions - recursively search a directory (default: sys.prefix)
for _checkversion.py files, and run each of them. This will tell you of
new versions available for any packages you have installed."""
@@ -29,7 +29,7 @@ def check1dir(dummy, dir, files):
execfile(fullname)
except:
print '** Exception in', fullname
-
+
def walk1tree(tree):
os.path.walk(tree, check1dir, None)
@@ -50,5 +50,3 @@ def main():
if __name__ == '__main__':
main()
-
-
diff --git a/Tools/versioncheck/pyversioncheck.py b/Tools/versioncheck/pyversioncheck.py
index 6ac34c892a..144665383e 100644
--- a/Tools/versioncheck/pyversioncheck.py
+++ b/Tools/versioncheck/pyversioncheck.py
@@ -96,4 +96,3 @@ def _test():
if __name__ == '__main__':
_test()
-
diff --git a/Tools/webchecker/wcgui.py b/Tools/webchecker/wcgui.py
index e467d92299..96aed0a6b2 100755
--- a/Tools/webchecker/wcgui.py
+++ b/Tools/webchecker/wcgui.py
@@ -10,17 +10,17 @@ Checkpoints are not (yet??? ever???) supported.
User interface:
-Enter a root to check in the text entry box. To enter more than one root,
+Enter a root to check in the text entry box. To enter more than one root,
enter them one at a time and press <Return> for each one.
-Command buttons Start, Stop and "Check one" govern the checking process in
-the obvious way. Start and "Check one" also enter the root from the text
+Command buttons Start, Stop and "Check one" govern the checking process in
+the obvious way. Start and "Check one" also enter the root from the text
entry box if one is present. There's also a check box (enabled by default)
to decide whether actually to follow external links (since this can slow
the checking down considerably). Finally there's a Quit button.
-A series of checkbuttons determines whether the corresponding output panel
-is shown. List panels are also automatically shown or hidden when their
+A series of checkbuttons determines whether the corresponding output panel
+is shown. List panels are also automatically shown or hidden when their
status changes between empty to non-empty. There are six panels:
Log -- raw output from the checker (-v, -q affect this)
diff --git a/Tools/webchecker/webchecker.py b/Tools/webchecker/webchecker.py
index 9113c4b650..d918a0c724 100755
--- a/Tools/webchecker/webchecker.py
+++ b/Tools/webchecker/webchecker.py
@@ -297,7 +297,7 @@ class Checker:
def message(self, format, *args):
if args:
format = format%args
- print format
+ print format
def __getstate__(self):
return (self.roots, self.todo, self.done, self.bad, self.round)
@@ -380,7 +380,7 @@ class Checker:
# triples is now a (URL, fragment) pair. The value
# of the "source" variable comes from the list of
# origins, and is a URL, not a pair.
- for url, rawlink, msg in triples:
+ for url, rawlink, msg in triples:
if rawlink != self.format_url(url): s = " (%s)" % rawlink
else: s = ""
self.message(" HREF %s%s\n msg %s",
@@ -462,7 +462,7 @@ class Checker:
self.todo[url] = [origin]
self.note(3, " New todo link %s", self.format_url(url))
- def format_url(self, url):
+ def format_url(self, url):
link, fragment = url
if fragment: return link + "#" + fragment
else: return link
@@ -716,7 +716,7 @@ class Page:
t = t[:-1] + ('',)
rawlink = urlparse.urlunparse(t)
link = urlparse.urljoin(base, rawlink)
- infos.append((link, rawlink, fragment))
+ infos.append((link, rawlink, fragment))
return infos