From c61839cc6e63c15f6abe6c204d5dac4ae56364bb Mon Sep 17 00:00:00 2001 From: "(no author)" <(no author)@6015fed2-1504-0410-9fe1-9d1591cc4771> Date: Tue, 27 Mar 2001 21:38:55 +0000 Subject: [PATCH] This commit was manufactured by cvs2svn to create tag 'mac210b2'. git-svn-id: http://svn.python.org/projects/python/tags/mac210b2@20131 6015fed2-1504-0410-9fe1-9d1591cc4771 --- .cvsignore | 8 - Demo/README | 50 - Demo/classes/Complex.py | 298 - Demo/classes/Dates.py | 218 - Demo/classes/Dbm.py | 66 - Demo/classes/README | 14 - Demo/classes/Range.py | 71 - Demo/classes/Rat.py | 307 - Demo/classes/Rev.py | 89 - Demo/classes/Vec.py | 64 - Demo/classes/bitvec.py | 332 - Demo/classes/class.doc | 110 - Demo/comparisons/README | 60 - Demo/comparisons/patterns | 4 - Demo/comparisons/regextest.py | 50 - Demo/comparisons/sortingtest.py | 50 - Demo/comparisons/systemtest.py | 74 - Demo/curses/README | 28 - Demo/curses/life.py | 223 - Demo/curses/ncurses.py | 273 - Demo/curses/rain.py | 94 - Demo/curses/repeat.py | 58 - Demo/curses/tclock.py | 146 - Demo/curses/xmas.py | 906 --- Demo/dns/README | 16 - Demo/dns/asgethost.py | 35 - Demo/dns/dnsclass.py | 23 - Demo/dns/dnslib.py | 588 -- Demo/dns/dnsopcode.py | 16 - Demo/dns/dnstype.py | 41 - Demo/embed/.cvsignore | 3 - Demo/embed/Makefile | 56 - Demo/embed/README | 19 - Demo/embed/demo.c | 66 - Demo/embed/importexc.c | 17 - Demo/embed/loop.c | 33 - Demo/extend/README | 16 - Demo/extend/make_clean | 5 - Demo/extend/make_shared | 16 - Demo/extend/make_static | 15 - Demo/imputil/importers.py | 248 - Demo/md5test/README | 10 - Demo/md5test/foo | 1 - Demo/md5test/md5driver.py | 125 - Demo/metaclasses/Eiffel.py | 113 - Demo/metaclasses/Enum.py | 169 - Demo/metaclasses/Meta.py | 120 - Demo/metaclasses/Simple.py | 45 - Demo/metaclasses/Synch.py | 256 - Demo/metaclasses/Trace.py | 145 - Demo/metaclasses/index.html | 605 -- Demo/metaclasses/meta-vladimir.txt | 256 - Demo/parser/FILES | 6 - Demo/parser/README | 25 - Demo/parser/docstring.py | 2 - Demo/parser/example.py | 190 - Demo/parser/simple.py | 1 - Demo/parser/source.py | 27 - Demo/parser/test_parser.py | 48 - Demo/parser/texipre.dat | 100 - Demo/pdist/FSProxy.py | 322 - Demo/pdist/RCSProxy.py | 198 - Demo/pdist/README | 121 - Demo/pdist/client.py | 158 - Demo/pdist/cmdfw.py | 144 - Demo/pdist/cmptree.py | 208 - Demo/pdist/cvslib.py | 364 - Demo/pdist/cvslock.py | 280 - Demo/pdist/mac.py | 19 - Demo/pdist/makechangelog.py | 109 - Demo/pdist/new | 1 - Demo/pdist/rcsbump | 33 - Demo/pdist/rcsclient.py | 71 - Demo/pdist/rcslib.py | 339 - Demo/pdist/rcvs | 8 - Demo/pdist/rcvs.py | 481 -- Demo/pdist/rrcs | 8 - Demo/pdist/rrcs.py | 164 - Demo/pdist/security.py | 33 - Demo/pdist/server.py | 145 - Demo/pdist/sumtree.py | 24 - Demo/pysvr/Makefile | 53 - Demo/pysvr/README | 9 - Demo/pysvr/pysvr.c | 369 - Demo/pysvr/pysvr.py | 124 - Demo/rpc/MANIFEST | 10 - Demo/rpc/README | 25 - Demo/rpc/T.py | 22 - Demo/rpc/mountclient.py | 201 - Demo/rpc/nfsclient.py | 201 - Demo/rpc/rnusersclient.py | 98 - Demo/rpc/rpc.py | 891 --- Demo/rpc/test | 24 - Demo/rpc/xdr.py | 201 - Demo/scripts/README | 18 - Demo/scripts/beer.py | 14 - Demo/scripts/eqfix.py | 199 - Demo/scripts/fact.py | 48 - Demo/scripts/freeze.py | 480 -- Demo/scripts/from.py | 35 - Demo/scripts/ftpstats.py | 144 - Demo/scripts/lpwatch.py | 109 - Demo/scripts/makedir.py | 20 - Demo/scripts/markov.py | 116 - Demo/scripts/mboxconvert.py | 123 - Demo/scripts/mkrcs.py | 60 - Demo/scripts/morse.py | 149 - Demo/scripts/mpzpi.py | 34 - Demo/scripts/newslist.doc | 59 - Demo/scripts/newslist.py | 366 - Demo/scripts/pi.py | 33 - Demo/scripts/pp.py | 138 - Demo/scripts/primes.py | 26 - Demo/scripts/queens.py | 85 - Demo/scripts/script.py | 33 - Demo/scripts/unbirthday.py | 106 - Demo/scripts/update.py | 91 - Demo/scripts/wh.py | 2 - Demo/sgi/README | 22 - Demo/sgi/al/.cvsignore | 1 - Demo/sgi/al/README | 15 - Demo/sgi/al/alwatch.py | 33 - Demo/sgi/al/broadcast.py | 27 - Demo/sgi/al/cmpaf.py | 64 - Demo/sgi/al/cmpaf_form.fd | 90 - Demo/sgi/al/intercom.py | 212 - Demo/sgi/al/listen.py | 34 - Demo/sgi/al/names.py | 14 - Demo/sgi/al/playaiff.py | 54 - Demo/sgi/al/playback.py | 23 - Demo/sgi/al/playold.py | 51 - Demo/sgi/al/radio.py | 21 - Demo/sgi/al/rec_play.py | 28 - Demo/sgi/al/record.py | 23 - Demo/sgi/al/unicast.py | 26 - Demo/sgi/al/x.py | 12 - Demo/sgi/audio/README | 8 - Demo/sgi/audio/play.py | 75 - Demo/sgi/cd/CD.doc | 46 - Demo/sgi/cd/README | 28 - Demo/sgi/cd/cdaiff.py | 33 - Demo/sgi/cd/listcd.py | 24 - Demo/sgi/cd/playcd.py | 102 - Demo/sgi/cd/recvcd.py | 36 - Demo/sgi/cd/sendcd.py | 154 - Demo/sgi/flp/.cvsignore | 1 - Demo/sgi/flp/tcache.fd | 51 - Demo/sgi/flp/tcache.py | 32 - Demo/sgi/flp/test_cb.fd | 75 - Demo/sgi/flp/test_cb.py | 61 - Demo/sgi/flp/test_nocb.fd | 75 - Demo/sgi/flp/test_nocb.py | 45 - Demo/sgi/gl/README | 35 - Demo/sgi/gl/backface.py | 140 - Demo/sgi/gl/glinfo.py | 20 - Demo/sgi/gl/kites.py | 194 - Demo/sgi/gl/kunst.py | 426 -- Demo/sgi/gl/mclock.doc | 60 - Demo/sgi/gl/mclock.py | 736 -- Demo/sgi/gl/mixing.py | 116 - Demo/sgi/gl/nurbs.py | 171 - Demo/sgi/gl/zrgb.py | 168 - Demo/sgi/sv/README | 23 - Demo/sgi/sv/burstcapt.py | 52 - Demo/sgi/sv/contcapt.py | 107 - Demo/sgi/sv/rgbgrab.py | 81 - Demo/sgi/sv/simpleinput.py | 22 - Demo/sgi/video/.cvsignore | 1 - Demo/sgi/video/DisplayVideoIn.py | 99 - Demo/sgi/video/Dsend.py | 188 - Demo/sgi/video/IN.py | 54 - Demo/sgi/video/LiveVideoIn.py | 139 - Demo/sgi/video/LiveVideoOut.py | 130 - Demo/sgi/video/Makefile | 7 - Demo/sgi/video/OldVcopy.py | 148 - Demo/sgi/video/README | 113 - Demo/sgi/video/VCR.py | 534 -- Demo/sgi/video/VFile.py | 1193 ---- Demo/sgi/video/VGrabber.py | 80 - Demo/sgi/video/Vaddcache.py | 80 - Demo/sgi/video/Vb.py | 962 --- Demo/sgi/video/VbForm.fd | 615 -- Demo/sgi/video/Vcopy.py | 291 - Demo/sgi/video/VcrIndex.py | 327 - Demo/sgi/video/Vedit.py | 301 - Demo/sgi/video/VeditForm.fd | 435 -- Demo/sgi/video/Vfix.py | 90 - Demo/sgi/video/Vgeneric.py | 2 - Demo/sgi/video/Viewer.py | 255 - Demo/sgi/video/Vinfo.py | 174 - Demo/sgi/video/Vmkjpeg.py | 92 - Demo/sgi/video/Vplay.py | 355 - Demo/sgi/video/Vrec.py | 413 -- Demo/sgi/video/Vrecb.py | 429 -- Demo/sgi/video/Vrecc.py | 281 - Demo/sgi/video/Vreceive.py | 135 - Demo/sgi/video/Vsend.py | 152 - Demo/sgi/video/Vstat.py | 23 - Demo/sgi/video/Vtime.py | 117 - Demo/sgi/video/Vunjpeg.py | 97 - Demo/sgi/video/aplay.py | 167 - Demo/sgi/video/cam.py | 129 - Demo/sgi/video/camcorder.py | 266 - Demo/sgi/video/cmif-film.ms | 200 - Demo/sgi/video/colorsys.py | 106 - Demo/sgi/video/i2v.c | 80 - Demo/sgi/video/imgconv.py | 139 - Demo/sgi/video/makemovie.py | 218 - Demo/sgi/video/rgb2video.py | 79 - Demo/sgi/video/senddefs.py | 11 - Demo/sgi/video/squash.c | 130 - Demo/sgi/video/squash2.c | 72 - Demo/sgi/video/statit.py | 115 - Demo/sgi/video/svgrab24.c | 97 - Demo/sgi/video/syncaudio.py | 94 - Demo/sgi/video/tomono.c | 165 - Demo/sgi/video/tv.py | 79 - Demo/sgi/video/v2i.c | 79 - Demo/sgi/video/vcopy.py | 134 - Demo/sgi/video/video.doc | 109 - Demo/sgi/video/video.py | 218 - Demo/sgi/video/video2rgb.py | 159 - Demo/sgi/video/vinfo.py | 90 - Demo/sgi/video/vpregs.py | 28 - Demo/sgi/video/vtime.py | 106 - Demo/sgi/video/watchcursor.py | 45 - Demo/sockets/ChangeLog | 35 - Demo/sockets/README | 22 - Demo/sockets/broadcast.py | 17 - Demo/sockets/echosvr.py | 31 - Demo/sockets/finger.py | 58 - Demo/sockets/ftp.py | 146 - Demo/sockets/gopher.py | 347 - Demo/sockets/mcast.py | 94 - Demo/sockets/radio.py | 14 - Demo/sockets/rpython.py | 35 - Demo/sockets/rpythond.py | 52 - Demo/sockets/telnet.py | 109 - Demo/sockets/throughput.py | 93 - Demo/sockets/udpecho.py | 63 - Demo/sockets/unicast.py | 16 - Demo/sockets/unixclient.py | 10 - Demo/sockets/unixserver.py | 15 - Demo/threads/Coroutine.py | 160 - Demo/threads/Generator.py | 84 - Demo/threads/README | 14 - Demo/threads/bug.py | 69 - Demo/threads/fcmp.py | 64 - Demo/threads/find.py | 154 - Demo/threads/squasher.py | 105 - Demo/threads/sync.py | 603 -- Demo/threads/telnet.py | 114 - Demo/tix/BUGS.txt | 8 - Demo/tix/INSTALL.txt | 81 - Demo/tix/README.txt | 19 - Demo/tix/bitmaps/about.xpm | 50 - Demo/tix/bitmaps/bold.xbm | 6 - Demo/tix/bitmaps/capital.xbm | 6 - Demo/tix/bitmaps/centerj.xbm | 6 - Demo/tix/bitmaps/combobox.xbm | 14 - Demo/tix/bitmaps/combobox.xpm | 49 - Demo/tix/bitmaps/combobox.xpm.1 | 47 - Demo/tix/bitmaps/drivea.xbm | 14 - Demo/tix/bitmaps/drivea.xpm | 43 - Demo/tix/bitmaps/exit.xpm | 48 - Demo/tix/bitmaps/filebox.xbm | 14 - Demo/tix/bitmaps/filebox.xpm | 49 - Demo/tix/bitmaps/italic.xbm | 6 - Demo/tix/bitmaps/justify.xbm | 6 - Demo/tix/bitmaps/leftj.xbm | 6 - Demo/tix/bitmaps/netw.xbm | 14 - Demo/tix/bitmaps/netw.xpm | 45 - Demo/tix/bitmaps/optmenu.xpm | 48 - Demo/tix/bitmaps/rightj.xbm | 6 - Demo/tix/bitmaps/select.xpm | 52 - Demo/tix/bitmaps/tix.gif | Bin 11042 -> 0 bytes Demo/tix/bitmaps/underline.xbm | 6 - Demo/tix/samples/Balloon.py | 45 - Demo/tix/samples/BtnBox.py | 44 - Demo/tix/samples/CmpImg.py | 197 - Demo/tix/samples/ComboBox.py | 100 - Demo/tix/samples/Control.py | 102 - Demo/tix/samples/NoteBook.py | 119 - Demo/tix/samples/OptMenu.py | 68 - Demo/tix/samples/PopMenu.py | 56 - Demo/tix/samples/SHList1.py | 107 - Demo/tix/samples/SHList2.py | 148 - Demo/tix/samples/Tree.py | 80 - Demo/tix/tixwidgets.py | 819 --- Demo/tkinter/README | 11 - Demo/tkinter/Tree.py | 23 - Demo/tkinter/guido/AttrDialog.py | 452 -- Demo/tkinter/guido/ManPage.py | 220 - Demo/tkinter/guido/MimeViewer.py | 143 - Demo/tkinter/guido/ShellWindow.py | 151 - Demo/tkinter/guido/brownian.py | 50 - Demo/tkinter/guido/canvasevents.py | 244 - Demo/tkinter/guido/dialog.py | 109 - Demo/tkinter/guido/electrons.py | 91 - Demo/tkinter/guido/hanoi.py | 154 - Demo/tkinter/guido/hello.py | 17 - Demo/tkinter/guido/imagedraw.py | 23 - Demo/tkinter/guido/imageview.py | 12 - Demo/tkinter/guido/kill.py | 99 - Demo/tkinter/guido/listtree.py | 37 - Demo/tkinter/guido/mbox.py | 285 - Demo/tkinter/guido/newmenubardemo.py | 47 - Demo/tkinter/guido/optionmenu.py | 27 - Demo/tkinter/guido/paint.py | 60 - Demo/tkinter/guido/rmt.py | 159 - Demo/tkinter/guido/solitaire.py | 637 -- Demo/tkinter/guido/sortvisu.py | 634 -- Demo/tkinter/guido/svkill.py | 128 - Demo/tkinter/guido/switch.py | 55 - Demo/tkinter/guido/tkman.py | 267 - Demo/tkinter/guido/wish.py | 27 - Demo/tkinter/matt/00-HELLO-WORLD.py | 27 - Demo/tkinter/matt/README | 30 - Demo/tkinter/matt/animation-simple.py | 35 - Demo/tkinter/matt/animation-w-velocity-ctrl.py | 44 - Demo/tkinter/matt/bind-w-mult-calls-p-type.py | 44 - Demo/tkinter/matt/canvas-demo-simple.py | 28 - Demo/tkinter/matt/canvas-gridding.py | 61 - Demo/tkinter/matt/canvas-moving-or-creating.py | 65 - Demo/tkinter/matt/canvas-moving-w-mouse.py | 55 - Demo/tkinter/matt/canvas-mult-item-sel.py | 81 - Demo/tkinter/matt/canvas-reading-tag-info.py | 49 - Demo/tkinter/matt/canvas-w-widget-draw-el.py | 36 - Demo/tkinter/matt/canvas-with-scrollbars.py | 60 - Demo/tkinter/matt/dialog-box.py | 64 - Demo/tkinter/matt/entry-simple.py | 25 - Demo/tkinter/matt/entry-with-shared-variable.py | 47 - Demo/tkinter/matt/killing-window-w-wm.py | 42 - Demo/tkinter/matt/menu-all-types-of-entries.py | 250 - Demo/tkinter/matt/menu-simple.py | 118 - Demo/tkinter/matt/not-what-you-might-think-1.py | 28 - Demo/tkinter/matt/not-what-you-might-think-2.py | 30 - Demo/tkinter/matt/packer-and-placer-together.py | 42 - Demo/tkinter/matt/packer-simple.py | 32 - Demo/tkinter/matt/placer-simple.py | 40 - Demo/tkinter/matt/pong-demo-1.py | 54 - Demo/tkinter/matt/printing-coords-of-items.py | 64 - Demo/tkinter/matt/radiobutton-simple.py | 62 - Demo/tkinter/matt/rubber-band-box-demo-1.py | 58 - Demo/tkinter/matt/rubber-line-demo-1.py | 51 - Demo/tkinter/matt/slider-demo-1.py | 36 - Demo/tkinter/matt/subclass-existing-widgets.py | 29 - Demo/tkinter/matt/two-radio-groups.py | 110 - Demo/tkinter/matt/window-creation-more.py | 35 - Demo/tkinter/matt/window-creation-simple.py | 31 - Demo/tkinter/matt/window-creation-w-location.py | 45 - Demo/xml/elem_count.py | 36 - Demo/xml/roundtrip.py | 45 - Demo/xml/rss2html.py | 91 - Demo/zlib/minigzip.py | 107 - Demo/zlib/zlibdemo.py | 36 - Doc/.cvsignore | 3 - Doc/ACKS | 169 - Doc/Makefile | 429 -- Doc/Makefile.deps | 283 - Doc/README | 219 - Doc/TODO | 84 - Doc/api/.cvsignore | 3 - Doc/api/api.tex | 5186 -------------- Doc/api/refcounts.dat | 1355 ---- Doc/dist/.cvsignore | 3 - Doc/dist/dist.tex | 1409 ---- Doc/doc/doc.tex | 1478 ---- Doc/ext/.cvsignore | 3 - Doc/ext/ext.tex | 2581 ------- Doc/html/.cvsignore | 13 - Doc/html/about.dat | 24 - Doc/html/about.html | 74 - Doc/html/icons/blank.gif | Bin 1958 -> 0 bytes Doc/html/icons/blank.png | Bin 1031 -> 0 bytes Doc/html/icons/contents.gif | Bin 438 -> 0 bytes Doc/html/icons/contents.png | Bin 649 -> 0 bytes Doc/html/icons/index.gif | Bin 289 -> 0 bytes Doc/html/icons/index.png | Bin 529 -> 0 bytes Doc/html/icons/modules.gif | Bin 385 -> 0 bytes Doc/html/icons/modules.png | Bin 598 -> 0 bytes Doc/html/icons/next.gif | Bin 253 -> 0 bytes Doc/html/icons/next.png | Bin 511 -> 0 bytes Doc/html/icons/previous.gif | Bin 252 -> 0 bytes Doc/html/icons/previous.png | Bin 511 -> 0 bytes Doc/html/icons/up.gif | Bin 316 -> 0 bytes Doc/html/icons/up.png | Bin 577 -> 0 bytes Doc/html/index.html.in | 117 - Doc/html/stdabout.dat | 48 - Doc/html/style.css | 88 - Doc/info/.cvsignore | 2 - Doc/info/Makefile | 73 - Doc/info/README | 21 - Doc/info/python.dir | 9 - Doc/inst/inst.tex | 1018 --- Doc/lib/.cvsignore | 3 - Doc/lib/internet.tex | 13 - Doc/lib/language.tex | 10 - Doc/lib/lib.tex | 333 - Doc/lib/libaifc.tex | 202 - Doc/lib/libal.tex | 181 - Doc/lib/liballos.tex | 9 - Doc/lib/libamoeba.tex | 132 - Doc/lib/libanydbm.tex | 97 - Doc/lib/libarray.tex | 199 - Doc/lib/libascii.tex | 175 - Doc/lib/libasyncore.tex | 196 - Doc/lib/libatexit.tex | 74 - Doc/lib/libaudioop.tex | 254 - Doc/lib/libbase64.tex | 60 - Doc/lib/libbasehttp.tex | 230 - Doc/lib/libbastion.tex | 52 - Doc/lib/libbinascii.tex | 121 - Doc/lib/libbinhex.tex | 47 - Doc/lib/libbisect.tex | 83 - Doc/lib/libbltin.tex | 11 - Doc/lib/libbsddb.tex | 165 - Doc/lib/libcalendar.tex | 96 - Doc/lib/libcd.tex | 304 - Doc/lib/libcfgparser.tex | 201 - Doc/lib/libcgi.tex | 504 -- Doc/lib/libcgihttp.tex | 65 - Doc/lib/libchunk.tex | 111 - Doc/lib/libcmath.tex | 91 - Doc/lib/libcmd.tex | 146 - Doc/lib/libcmp.tex | 36 - Doc/lib/libcmpcache.tex | 21 - Doc/lib/libcode.tex | 174 - Doc/lib/libcodecs.tex | 405 -- Doc/lib/libcodeop.tex | 43 - Doc/lib/libcolorsys.tex | 54 - Doc/lib/libcommands.tex | 53 - Doc/lib/libcompileall.tex | 42 - Doc/lib/libcookie.tex | 248 - Doc/lib/libcopy.tex | 98 - Doc/lib/libcopyreg.tex | 32 - Doc/lib/libcrypt.tex | 46 - Doc/lib/libcrypto.tex | 23 - Doc/lib/libcurses.tex | 1380 ---- Doc/lib/libcursespanel.tex | 93 - Doc/lib/libdbhash.tex | 90 - Doc/lib/libdbm.tex | 61 - Doc/lib/libdifflib.tex | 317 - Doc/lib/libdircache.tex | 45 - Doc/lib/libdis.tex | 645 -- Doc/lib/libdl.tex | 99 - Doc/lib/libdoctest.tex | 435 -- Doc/lib/liberrno.tex | 149 - Doc/lib/libexcs.tex | 358 - Doc/lib/libfcntl.tex | 119 - Doc/lib/libfilecmp.tex | 138 - Doc/lib/libfileinput.tex | 130 - Doc/lib/libfl.tex | 506 -- Doc/lib/libfm.tex | 94 - Doc/lib/libfnmatch.tex | 49 - Doc/lib/libformatter.tex | 329 - Doc/lib/libfpectl.tex | 122 - Doc/lib/libfpformat.tex | 54 - Doc/lib/libftplib.tex | 289 - Doc/lib/libfuncs.tex | 730 -- Doc/lib/libgc.tex | 132 - Doc/lib/libgdbm.tex | 100 - Doc/lib/libgetopt.tex | 123 - Doc/lib/libgetpass.tex | 32 - Doc/lib/libgettext.tex | 518 -- Doc/lib/libgl.tex | 223 - Doc/lib/libglob.tex | 44 - Doc/lib/libgopherlib.tex | 33 - Doc/lib/libgrp.tex | 47 - Doc/lib/libgzip.tex | 70 - Doc/lib/libhtmllib.tex | 153 - Doc/lib/libhttplib.tex | 148 - Doc/lib/libimageop.tex | 88 - Doc/lib/libimaplib.tex | 300 - Doc/lib/libimgfile.tex | 66 - Doc/lib/libimghdr.tex | 58 - Doc/lib/libimp.tex | 247 - Doc/lib/libinspect.tex | 266 - Doc/lib/libintro.tex | 53 - Doc/lib/libjpeg.tex | 78 - Doc/lib/libkeyword.tex | 13 - Doc/lib/liblinecache.tex | 45 - Doc/lib/liblocale.tex | 351 - Doc/lib/libmailbox.tex | 94 - Doc/lib/libmailcap.tex | 82 - Doc/lib/libmain.tex | 16 - Doc/lib/libmarshal.tex | 96 - Doc/lib/libmath.tex | 140 - Doc/lib/libmd5.tex | 81 - Doc/lib/libmhlib.tex | 168 - Doc/lib/libmimetools.tex | 110 - Doc/lib/libmimetypes.tex | 94 - Doc/lib/libmimewriter.tex | 75 - Doc/lib/libmimify.tex | 89 - Doc/lib/libmisc.tex | 7 - Doc/lib/libmm.tex | 8 - Doc/lib/libmmap.tex | 131 - Doc/lib/libmpz.tex | 98 - Doc/lib/libmsvcrt.tex | 109 - Doc/lib/libmultifile.tex | 166 - Doc/lib/libmutex.tex | 57 - Doc/lib/libnetrc.tex | 61 - Doc/lib/libnew.tex | 58 - Doc/lib/libni.tex | 63 - Doc/lib/libnis.tex | 46 - Doc/lib/libnntplib.tex | 275 - Doc/lib/libobjs.tex | 24 - Doc/lib/liboperator.tex | 283 - Doc/lib/libos.tex | 1159 ---- Doc/lib/libpanel.tex | 77 - Doc/lib/libparser.tex | 711 -- Doc/lib/libpdb.tex | 383 -- Doc/lib/libpickle.tex | 389 -- Doc/lib/libpipes.tex | 84 - Doc/lib/libpopen2.tex | 104 - Doc/lib/libpoplib.tex | 154 - Doc/lib/libposix.tex | 98 - Doc/lib/libposixfile.tex | 175 - Doc/lib/libposixpath.tex | 205 - Doc/lib/libpprint.tex | 175 - Doc/lib/libprofile.tex | 768 --- Doc/lib/libpty.tex | 44 - Doc/lib/libpwd.tex | 52 - Doc/lib/libpyclbr.tex | 65 - Doc/lib/libpycompile.tex | 35 - Doc/lib/libpyexpat.tex | 608 -- Doc/lib/libpython.tex | 8 - Doc/lib/libqueue.tex | 84 - Doc/lib/libquopri.tex | 38 - Doc/lib/librand.tex | 31 - Doc/lib/librandom.tex | 265 - Doc/lib/libre.tex | 761 --- Doc/lib/libreadline.tex | 106 - Doc/lib/libregex.tex | 370 - Doc/lib/libregsub.tex | 74 - Doc/lib/librepr.tex | 127 - Doc/lib/libresource.tex | 207 - Doc/lib/librestricted.tex | 76 - Doc/lib/librexec.tex | 224 - Doc/lib/librfc822.tex | 268 - Doc/lib/librgbimg.tex | 49 - Doc/lib/librlcompleter.tex | 63 - Doc/lib/librobotparser.tex | 68 - Doc/lib/librotor.tex | 107 - Doc/lib/libsched.tex | 97 - Doc/lib/libselect.tex | 131 - Doc/lib/libsgi.tex | 7 - Doc/lib/libsgmllib.tex | 219 - Doc/lib/libsha.tex | 77 - Doc/lib/libshelve.tex | 75 - Doc/lib/libshlex.tex | 185 - Doc/lib/libshutil.tex | 115 - Doc/lib/libsignal.tex | 172 - Doc/lib/libsimplehttp.tex | 72 - Doc/lib/libsite.tex | 88 - Doc/lib/libsmtplib.tex | 265 - Doc/lib/libsndhdr.tex | 41 - Doc/lib/libsocket.tex | 457 -- Doc/lib/libsocksvr.tex | 204 - Doc/lib/libsomeos.tex | 10 - Doc/lib/libstat.tex | 154 - Doc/lib/libstatcache.tex | 54 - Doc/lib/libstatvfs.tex | 55 - Doc/lib/libstdtypes.tex | 1312 ---- Doc/lib/libstdwin.tex | 832 --- Doc/lib/libstring.tex | 276 - Doc/lib/libstringio.tex | 77 - Doc/lib/libstrings.tex | 7 - Doc/lib/libstruct.tex | 188 - Doc/lib/libsun.tex | 6 - Doc/lib/libsunau.tex | 218 - Doc/lib/libsunaudio.tex | 146 - Doc/lib/libsymbol.tex | 30 - Doc/lib/libsys.tex | 439 -- Doc/lib/libsyslog.tex | 76 - Doc/lib/libtabnanny.tex | 62 - Doc/lib/libtelnetlib.tex | 186 - Doc/lib/libtempfile.tex | 78 - Doc/lib/libtermios.tex | 126 - Doc/lib/libthread.tex | 137 - Doc/lib/libthreading.tex | 568 -- Doc/lib/libtime.tex | 298 - Doc/lib/libtoken.tex | 44 - Doc/lib/libtokenize.tex | 50 - Doc/lib/libtraceback.tex | 151 - Doc/lib/libtty.tex | 36 - Doc/lib/libturtle.tex | 159 - Doc/lib/libtypes.tex | 151 - Doc/lib/libundoc.tex | 230 - Doc/lib/libunicodedata.tex | 85 - Doc/lib/libunix.tex | 8 - Doc/lib/liburllib.tex | 339 - Doc/lib/liburllib2.tex | 565 -- Doc/lib/liburlparse.tex | 103 - Doc/lib/libuser.tex | 69 - Doc/lib/libuserdict.tex | 136 - Doc/lib/libuu.tex | 44 - Doc/lib/libwarnings.tex | 206 - Doc/lib/libwave.tex | 169 - Doc/lib/libweakref.tex | 240 - Doc/lib/libwebbrowser.tex | 130 - Doc/lib/libwhichdb.tex | 20 - Doc/lib/libwhrandom.tex | 74 - Doc/lib/libwinreg.tex | 414 -- Doc/lib/libwinsound.tex | 112 - Doc/lib/libxdrlib.tex | 251 - Doc/lib/libxmllib.tex | 287 - Doc/lib/libxreadlines.tex | 55 - Doc/lib/libzipfile.tex | 288 - Doc/lib/libzlib.tex | 154 - Doc/lib/markup.tex | 10 - Doc/lib/netdata.tex | 7 - Doc/lib/windows.tex | 8 - Doc/lib/xmldom.tex | 832 --- Doc/lib/xmldomminidom.tex | 292 - Doc/lib/xmldompulldom.tex | 61 - Doc/lib/xmlsax.tex | 134 - Doc/lib/xmlsaxhandler.tex | 369 - Doc/lib/xmlsaxreader.tex | 337 - Doc/lib/xmlsaxutils.tex | 48 - Doc/libmods.tex | 7 - Doc/libstd.tex | 7 - Doc/mac/.cvsignore | 3 - Doc/mac/libaepack.tex | 73 - Doc/mac/libaetypes.tex | 39 - Doc/mac/libctb.tex | 156 - Doc/mac/libframework.tex | 313 - Doc/mac/libmac.tex | 69 - Doc/mac/libmacconsole.tex | 114 - Doc/mac/libmacdnr.tex | 125 - Doc/mac/libmacfs.tex | 232 - Doc/mac/libmacic.tex | 128 - Doc/mac/libmacos.tex | 98 - Doc/mac/libmacostools.tex | 108 - Doc/mac/libmacspeech.tex | 96 - Doc/mac/libmactcp.tex | 181 - Doc/mac/libmacui.tex | 60 - Doc/mac/libminiae.tex | 65 - Doc/mac/mac.tex | 89 - Doc/mac/toolbox.tex | 126 - Doc/mac/undoc.tex | 119 - Doc/mac/using.tex | 374 -- Doc/paper-a4/.cvsignore | 16 - Doc/paper-a4/pypaper.sty | 5 - Doc/paper-letter/.cvsignore | 16 - Doc/perl/SynopsisTable.pm | 89 - Doc/perl/distutils.perl | 21 - Doc/perl/howto.perl | 12 - Doc/perl/l2hinit.perl | 594 -- Doc/perl/ltxmarkup.perl | 67 - Doc/perl/manual.perl | 15 - Doc/perl/python.perl | 1596 ----- Doc/ref/.cvsignore | 3 - Doc/ref/ref.tex | 66 - Doc/ref/ref1.tex | 85 - Doc/ref/ref2.tex | 566 -- Doc/ref/ref3.tex | 1495 ----- Doc/ref/ref4.tex | 214 - Doc/ref/ref5.tex | 955 --- Doc/ref/ref6.tex | 683 -- Doc/ref/ref7.tex | 406 -- Doc/ref/ref8.tex | 104 - Doc/ref/refa1.tex | 252 - Doc/ref/reswords.py | 32 - Doc/templates/howto.tex | 105 - Doc/templates/manual.tex | 82 - Doc/templates/module.tex | 163 - Doc/texinputs/boilerplate.tex | 10 - Doc/texinputs/copyright.tex | 103 - Doc/texinputs/distutils.sty | 33 - Doc/texinputs/fncychap.sty | 433 -- Doc/texinputs/howto.cls | 106 - Doc/texinputs/ltxmarkup.sty | 40 - Doc/texinputs/manual.cls | 152 - Doc/texinputs/pypaper.sty | 18 - Doc/texinputs/python.ist | 11 - Doc/texinputs/python.sty | 1061 --- Doc/texinputs/reportingbugs.tex | 65 - Doc/tools/anno-api.py | 71 - Doc/tools/buildindex.py | 353 - Doc/tools/checkargs.pm | 112 - Doc/tools/cklatex | 26 - Doc/tools/custlib.py | 73 - Doc/tools/cvsinfo.py | 81 - Doc/tools/findacks | 161 - Doc/tools/findmodrefs | 63 - Doc/tools/fix_hack | 2 - Doc/tools/fix_libaux.sed | 3 - Doc/tools/fixinfo.el | 15 - Doc/tools/getpagecounts | 88 - Doc/tools/html2texi.pl | 1750 ----- Doc/tools/indfix.py | 101 - Doc/tools/keywords.py | 20 - Doc/tools/listmodules | 183 - Doc/tools/mkackshtml | 65 - Doc/tools/mkhowto | 598 -- Doc/tools/mkinfo | 48 - Doc/tools/mkmodindex | 136 - Doc/tools/mksourcepkg | 163 - Doc/tools/node2label.pl | 55 - Doc/tools/push-docs.sh | 42 - Doc/tools/refcounts.py | 97 - Doc/tools/sgmlconv/Makefile | 67 - Doc/tools/sgmlconv/README | 58 - Doc/tools/sgmlconv/conversion.xml | 755 --- Doc/tools/sgmlconv/docfixer.py | 1033 --- Doc/tools/sgmlconv/esis2sgml.py | 263 - Doc/tools/sgmlconv/esistools.py | 309 - Doc/tools/sgmlconv/latex2esis.py | 555 -- Doc/tools/sgmlconv/make.rules | 48 - Doc/tools/support.py | 149 - Doc/tools/toc2bkm.py | 143 - Doc/tools/update-docs.sh | 21 - Doc/tools/whichlibs | 2 - Doc/tut/.cvsignore | 3 - Doc/tut/tut.tex | 4081 ----------- Doc/whatsnew/whatsnew20.tex | 1335 ---- Doc/whatsnew/whatsnew21.tex | 864 --- Grammar/.cvsignore | 3 - Grammar/Grammar | 100 - Include/Python.h | 123 - Include/abstract.h | 1087 --- Include/bitset.h | 32 - Include/bufferobject.h | 33 - Include/cStringIO.h | 131 - Include/cellobject.h | 28 - Include/ceval.h | 121 - Include/classobject.h | 69 - Include/cobject.h | 55 - Include/codecs.h | 123 - Include/compile.h | 75 - Include/complexobject.h | 57 - Include/config.h | 82 - Include/dictobject.h | 35 - Include/errcode.h | 32 - Include/eval.h | 15 - Include/fileobject.h | 29 - Include/floatobject.h | 33 - Include/frameobject.h | 91 - Include/funcobject.h | 48 - Include/graminit.h | 64 - Include/grammar.h | 93 - Include/import.h | 51 - Include/intobject.h | 68 - Include/intrcheck.h | 15 - Include/listobject.h | 51 - Include/longintrepr.h | 52 - Include/longobject.h | 50 - Include/marshal.h | 24 - Include/metagrammar.h | 18 - Include/methodobject.h | 65 - Include/modsupport.h | 95 - Include/moduleobject.h | 23 - Include/node.h | 46 - Include/object.h | 617 -- Include/objimpl.h | 287 - Include/opcode.h | 147 - Include/osdefs.h | 52 - Include/parsetok.h | 28 - Include/patchlevel.h | 40 - Include/pgenheaders.h | 56 - Include/py_curses.h | 133 - Include/pydebug.h | 23 - Include/pyerrors.h | 112 - Include/pyfpe.h | 176 - Include/pygetopt.h | 17 - Include/pymem.h | 170 - Include/pyport.h | 441 -- Include/pystate.h | 91 - Include/pythonrun.h | 130 - Include/pythread.h | 49 - Include/rangeobject.h | 16 - Include/rename1.h | 360 - Include/sliceobject.h | 39 - Include/stringobject.h | 128 - Include/structmember.h | 71 - Include/symtable.h | 99 - Include/sysmodule.h | 28 - Include/token.h | 80 - Include/traceback.h | 24 - Include/tupleobject.h | 48 - Include/ucnhash.h | 29 - Include/unicodeobject.h | 912 --- LICENSE | 183 - Lib/BaseHTTPServer.py | 482 -- Lib/Bastion.py | 175 - Lib/CGIHTTPServer.py | 305 - Lib/ConfigParser.py | 479 -- Lib/Cookie.py | 728 -- Lib/MimeWriter.py | 128 - Lib/Queue.py | 132 - Lib/SimpleHTTPServer.py | 198 - Lib/SocketServer.py | 543 -- Lib/StringIO.py | 208 - Lib/TERMIOS.py | 14 - Lib/UserDict.py | 42 - Lib/UserList.py | 85 - Lib/UserString.py | 173 - Lib/__future__.py | 69 - Lib/aifc.py | 961 --- Lib/anydbm.py | 86 - Lib/asynchat.py | 293 - Lib/asyncore.py | 544 -- Lib/atexit.py | 54 - Lib/audiodev.py | 256 - Lib/base64.py | 81 - Lib/bdb.py | 562 -- Lib/binhex.py | 531 -- Lib/bisect.py | 78 - Lib/builtin.py | 3 - Lib/calendar.py | 209 - Lib/cgi.py | 1000 --- Lib/chunk.py | 167 - Lib/cmd.py | 198 - Lib/code.py | 308 - Lib/codecs.py | 570 -- Lib/codeop.py | 87 - Lib/colorsys.py | 123 - Lib/commands.py | 84 - Lib/compileall.py | 130 - Lib/compiler/__init__.py | 24 - Lib/compiler/ast.py | 687 -- Lib/compiler/consts.py | 9 - Lib/compiler/misc.py | 41 - Lib/compiler/pyassem.py | 656 -- Lib/compiler/pycodegen.py | 1059 --- Lib/compiler/transformer.py | 1296 ---- Lib/compiler/visitor.py | 119 - Lib/copy.py | 318 - Lib/copy_reg.py | 35 - Lib/curses/__init__.py | 41 - Lib/curses/ascii.py | 100 - Lib/curses/has_key.py | 190 - Lib/curses/panel.py | 9 - Lib/curses/textpad.py | 167 - Lib/curses/wrapper.py | 63 - Lib/dbhash.py | 16 - Lib/difflib.py | 781 --- Lib/dircache.py | 44 - Lib/dis.py | 320 - Lib/distutils/README | 18 - Lib/distutils/__init__.py | 13 - Lib/distutils/archive_util.py | 173 - Lib/distutils/bcppcompiler.py | 375 -- Lib/distutils/ccompiler.py | 1046 --- Lib/distutils/cmd.py | 484 -- Lib/distutils/command/__init__.py | 24 - Lib/distutils/command/bdist.py | 139 - Lib/distutils/command/bdist_dumb.py | 95 - Lib/distutils/command/bdist_rpm.py | 485 -- Lib/distutils/command/bdist_wininst.py | 562 -- Lib/distutils/command/build.py | 130 - Lib/distutils/command/build_clib.py | 224 - Lib/distutils/command/build_ext.py | 619 -- Lib/distutils/command/build_py.py | 397 -- Lib/distutils/command/build_scripts.py | 102 - Lib/distutils/command/clean.py | 79 - Lib/distutils/command/command_template | 45 - Lib/distutils/command/config.py | 362 - Lib/distutils/command/install.py | 577 -- Lib/distutils/command/install_data.py | 75 - Lib/distutils/command/install_headers.py | 53 - Lib/distutils/command/install_lib.py | 213 - Lib/distutils/command/install_scripts.py | 63 - Lib/distutils/command/sdist.py | 475 -- Lib/distutils/core.py | 231 - Lib/distutils/cygwinccompiler.py | 442 -- Lib/distutils/dep_util.py | 115 - Lib/distutils/dir_util.py | 219 - Lib/distutils/dist.py | 1079 --- Lib/distutils/errors.py | 99 - Lib/distutils/extension.py | 217 - Lib/distutils/fancy_getopt.py | 504 -- Lib/distutils/file_util.py | 250 - Lib/distutils/filelist.py | 367 - Lib/distutils/msvccompiler.py | 510 -- Lib/distutils/mwerkscompiler.py | 203 - Lib/distutils/spawn.py | 169 - Lib/distutils/sysconfig.py | 389 -- Lib/distutils/text_file.py | 385 -- Lib/distutils/unixccompiler.py | 279 - Lib/distutils/util.py | 456 -- Lib/distutils/version.py | 301 - Lib/doctest.py | 1118 ---- Lib/dospath.py | 332 - Lib/dumbdbm.py | 148 - Lib/encodings/__init__.py | 86 - Lib/encodings/aliases.py | 82 - Lib/encodings/ascii.py | 35 - Lib/encodings/charmap.py | 51 - Lib/encodings/cp037.py | 282 - Lib/encodings/cp1006.py | 140 - Lib/encodings/cp1026.py | 282 - Lib/encodings/cp1250.py | 125 - Lib/encodings/cp1251.py | 159 - Lib/encodings/cp1252.py | 78 - Lib/encodings/cp1253.py | 153 - Lib/encodings/cp1254.py | 84 - Lib/encodings/cp1255.py | 145 - Lib/encodings/cp1256.py | 131 - Lib/encodings/cp1257.py | 133 - Lib/encodings/cp1258.py | 92 - Lib/encodings/cp424.py | 282 - Lib/encodings/cp437.py | 174 - Lib/encodings/cp500.py | 282 - Lib/encodings/cp737.py | 174 - Lib/encodings/cp775.py | 174 - Lib/encodings/cp850.py | 174 - Lib/encodings/cp852.py | 174 - Lib/encodings/cp855.py | 174 - Lib/encodings/cp856.py | 174 - Lib/encodings/cp857.py | 173 - Lib/encodings/cp860.py | 174 - Lib/encodings/cp861.py | 174 - Lib/encodings/cp862.py | 174 - Lib/encodings/cp863.py | 174 - Lib/encodings/cp864.py | 172 - Lib/encodings/cp865.py | 174 - Lib/encodings/cp866.py | 174 - Lib/encodings/cp869.py | 174 - Lib/encodings/cp874.py | 173 - Lib/encodings/cp875.py | 283 - Lib/encodings/iso8859_1.py | 46 - Lib/encodings/iso8859_10.py | 92 - Lib/encodings/iso8859_13.py | 102 - Lib/encodings/iso8859_14.py | 77 - Lib/encodings/iso8859_15.py | 54 - Lib/encodings/iso8859_2.py | 103 - Lib/encodings/iso8859_3.py | 81 - Lib/encodings/iso8859_4.py | 96 - Lib/encodings/iso8859_5.py | 140 - Lib/encodings/iso8859_6.py | 139 - Lib/encodings/iso8859_7.py | 126 - Lib/encodings/iso8859_8.py | 114 - Lib/encodings/iso8859_9.py | 52 - Lib/encodings/koi8_r.py | 174 - Lib/encodings/latin_1.py | 35 - Lib/encodings/mac_cyrillic.py | 169 - Lib/encodings/mac_greek.py | 172 - Lib/encodings/mac_iceland.py | 168 - Lib/encodings/mac_latin2.py | 172 - Lib/encodings/mac_roman.py | 169 - Lib/encodings/mac_turkish.py | 169 - Lib/encodings/mbcs.py | 36 - Lib/encodings/raw_unicode_escape.py | 30 - Lib/encodings/undefined.py | 34 - Lib/encodings/unicode_escape.py | 30 - Lib/encodings/unicode_internal.py | 30 - Lib/encodings/utf_16.py | 31 - Lib/encodings/utf_16_be.py | 31 - Lib/encodings/utf_16_le.py | 31 - Lib/encodings/utf_8.py | 31 - Lib/filecmp.py | 331 - Lib/fileinput.py | 300 - Lib/fnmatch.py | 87 - Lib/formatter.py | 422 -- Lib/fpformat.py | 142 - Lib/ftplib.py | 728 -- Lib/getopt.py | 143 - Lib/getpass.py | 120 - Lib/gettext.py | 301 - Lib/glob.py | 57 - Lib/gopherlib.py | 206 - Lib/gzip.py | 359 - Lib/htmlentitydefs.py | 257 - Lib/htmllib.py | 426 -- Lib/httplib.py | 831 --- Lib/idlelib/AutoExpand.py | 92 - Lib/idlelib/AutoIndent.py | 554 -- Lib/idlelib/Bindings.py | 67 - Lib/idlelib/CallTipWindow.py | 71 - Lib/idlelib/CallTips.py | 190 - Lib/idlelib/ChangeLog | 1017 --- Lib/idlelib/ClassBrowser.py | 224 - Lib/idlelib/ColorDelegator.py | 234 - Lib/idlelib/ConfigParser.py | 382 -- Lib/idlelib/Debugger.py | 308 - Lib/idlelib/Delegator.py | 34 - Lib/idlelib/EditorWindow.py | 749 --- Lib/idlelib/ExecBinding.py | 198 - Lib/idlelib/FileList.py | 150 - Lib/idlelib/FormatParagraph.py | 155 - Lib/idlelib/FrameViewer.py | 38 - Lib/idlelib/GrepDialog.py | 135 - Lib/idlelib/IOBinding.py | 254 - Lib/idlelib/Icons/folder.gif | Bin 120 -> 0 bytes Lib/idlelib/Icons/minusnode.gif | Bin 75 -> 0 bytes Lib/idlelib/Icons/openfolder.gif | Bin 125 -> 0 bytes Lib/idlelib/Icons/plusnode.gif | Bin 79 -> 0 bytes Lib/idlelib/Icons/python.gif | Bin 895 -> 0 bytes Lib/idlelib/Icons/tk.gif | Bin 85 -> 0 bytes Lib/idlelib/IdleConf.py | 113 - Lib/idlelib/IdleHistory.py | 89 - Lib/idlelib/MultiScrolledLists.py | 138 - Lib/idlelib/MultiStatusBar.py | 32 - Lib/idlelib/NEWS.txt | 130 - Lib/idlelib/ObjectBrowser.py | 151 - Lib/idlelib/OldStackViewer.py | 276 - Lib/idlelib/OutputWindow.py | 279 - Lib/idlelib/ParenMatch.py | 192 - Lib/idlelib/PathBrowser.py | 95 - Lib/idlelib/Percolator.py | 85 - Lib/idlelib/PyParse.py | 569 -- Lib/idlelib/PyShell.py | 860 --- Lib/idlelib/README.txt | 121 - Lib/idlelib/Remote.py | 101 - Lib/idlelib/ReplaceDialog.py | 172 - Lib/idlelib/ScriptBinding.py | 169 - Lib/idlelib/ScrolledList.py | 139 - Lib/idlelib/SearchBinding.py | 97 - Lib/idlelib/SearchDialog.py | 67 - Lib/idlelib/SearchDialogBase.py | 129 - Lib/idlelib/SearchEngine.py | 221 - Lib/idlelib/Separator.py | 92 - Lib/idlelib/StackViewer.py | 135 - Lib/idlelib/TODO.txt | 205 - Lib/idlelib/ToolTip.py | 87 - Lib/idlelib/TreeWidget.py | 471 -- Lib/idlelib/UndoDelegator.py | 352 - Lib/idlelib/WidgetRedirector.py | 92 - Lib/idlelib/WindowList.py | 85 - Lib/idlelib/ZoomHeight.py | 46 - Lib/idlelib/__init__.py | 1 - Lib/idlelib/config-unix.txt | 3 - Lib/idlelib/config-win.txt | 3 - Lib/idlelib/config.txt | 66 - Lib/idlelib/eventparse.py | 93 - Lib/idlelib/extend.txt | 106 - Lib/idlelib/help.txt | 155 - Lib/idlelib/idle.bat | 3 - Lib/idlelib/idle.py | 12 - Lib/idlelib/idle.pyw | 12 - Lib/idlelib/idlever.py | 1 - Lib/idlelib/keydefs.py | 55 - Lib/idlelib/loader.py | 64 - Lib/idlelib/protocol.py | 369 - Lib/idlelib/pyclbr.py | 336 - Lib/idlelib/spawn.py | 58 - Lib/idlelib/tabnanny.py | 372 - Lib/idlelib/testcode.py | 31 - Lib/ihooks.py | 511 -- Lib/imaplib.py | 1125 ---- Lib/imghdr.py | 154 - Lib/imputil.py | 701 -- Lib/inspect.py | 644 -- Lib/keyword.py | 96 - Lib/knee.py | 126 - Lib/lib-old/Para.py | 343 - Lib/lib-old/addpack.py | 67 - Lib/lib-old/cmp.py | 63 - Lib/lib-old/cmpcache.py | 64 - Lib/lib-old/codehack.py | 81 - Lib/lib-old/dircmp.py | 202 - Lib/lib-old/dump.py | 63 - Lib/lib-old/find.py | 26 - Lib/lib-old/fmt.py | 623 -- Lib/lib-old/grep.py | 79 - Lib/lib-old/lockfile.py | 15 - Lib/lib-old/newdir.py | 73 - Lib/lib-old/ni.py | 433 -- Lib/lib-old/packmail.py | 111 - Lib/lib-old/poly.py | 52 - Lib/lib-old/rand.py | 13 - Lib/lib-old/tb.py | 177 - Lib/lib-old/util.py | 25 - Lib/lib-old/whatsound.py | 1 - Lib/lib-old/zmod.py | 94 - Lib/lib-tk/Canvas.py | 188 - Lib/lib-tk/Dialog.py | 49 - Lib/lib-tk/FileDialog.py | 273 - Lib/lib-tk/FixTk.py | 6 - Lib/lib-tk/ScrolledText.py | 39 - Lib/lib-tk/SimpleDialog.py | 111 - Lib/lib-tk/Tix.py | 1266 ---- Lib/lib-tk/Tkconstants.py | 103 - Lib/lib-tk/Tkdnd.py | 321 - Lib/lib-tk/Tkinter.py | 3086 --------- Lib/lib-tk/tkColorChooser.py | 74 - Lib/lib-tk/tkCommonDialog.py | 65 - Lib/lib-tk/tkFileDialog.py | 106 - Lib/lib-tk/tkFont.py | 191 - Lib/lib-tk/tkMessageBox.py | 120 - Lib/lib-tk/tkSimpleDialog.py | 297 - Lib/lib-tk/turtle.py | 345 - Lib/linecache.py | 94 - Lib/locale.py | 716 -- Lib/macpath.py | 227 - Lib/macstat.py | 83 - Lib/macurl2path.py | 95 - Lib/mailbox.py | 312 - Lib/mailcap.py | 255 - Lib/mhlib.py | 1003 --- Lib/mimetools.py | 226 - Lib/mimetypes.py | 242 - Lib/mimify.py | 464 -- Lib/multifile.py | 162 - Lib/mutex.py | 51 - Lib/netrc.py | 110 - Lib/nntplib.py | 557 -- Lib/ntpath.py | 424 -- Lib/nturl2path.py | 66 - Lib/os.py | 562 -- Lib/pdb.doc | 192 - Lib/pdb.py | 948 --- Lib/persist.py | 297 - Lib/pickle.py | 979 --- Lib/pipes.py | 298 - Lib/plat-aix3/FCNTL.py | 145 - Lib/plat-aix3/IN.py | 126 - Lib/plat-aix3/regen | 11 - Lib/plat-aix4/FCNTL.py | 387 -- Lib/plat-aix4/IN.py | 165 - Lib/plat-aix4/regen | 11 - Lib/plat-beos5/FCNTL.py | 124 - Lib/plat-beos5/IN.py | 327 - Lib/plat-beos5/regen | 10 - Lib/plat-freebsd2/FCNTL.py | 110 - Lib/plat-freebsd2/IN.py | 187 - Lib/plat-freebsd2/regen | 6 - Lib/plat-freebsd3/FCNTL.py | 111 - Lib/plat-freebsd3/IN.py | 189 - Lib/plat-freebsd3/regen | 6 - Lib/plat-freebsd4/FCNTL.py | 113 - Lib/plat-freebsd4/IN.py | 355 - Lib/plat-freebsd4/regen | 6 - Lib/plat-freebsd5/FCNTL.py | 114 - Lib/plat-freebsd5/IN.py | 355 - Lib/plat-freebsd5/regen | 6 - Lib/plat-generic/regen | 6 - Lib/plat-irix5/AL.py | 61 - Lib/plat-irix5/CD.py | 34 - Lib/plat-irix5/CL.py | 24 - Lib/plat-irix5/CL_old.py | 236 - Lib/plat-irix5/DEVICE.py | 400 -- Lib/plat-irix5/ERRNO.py | 147 - Lib/plat-irix5/FCNTL.py | 97 - Lib/plat-irix5/FILE.py | 239 - Lib/plat-irix5/FL.py | 289 - Lib/plat-irix5/GET.py | 59 - Lib/plat-irix5/GL.py | 393 -- Lib/plat-irix5/GLWS.py | 12 - Lib/plat-irix5/IN.py | 141 - Lib/plat-irix5/IOCTL.py | 233 - Lib/plat-irix5/SV.py | 120 - Lib/plat-irix5/WAIT.py | 14 - Lib/plat-irix5/cddb.py | 206 - Lib/plat-irix5/cdplayer.py | 89 - Lib/plat-irix5/flp.doc | 117 - Lib/plat-irix5/flp.py | 451 -- Lib/plat-irix5/jpeg.py | 111 - Lib/plat-irix5/panel.py | 281 - Lib/plat-irix5/panelparser.py | 128 - Lib/plat-irix5/readcd.doc | 104 - Lib/plat-irix5/readcd.py | 244 - Lib/plat-irix5/regen | 13 - Lib/plat-irix5/torgb.py | 98 - Lib/plat-irix6/AL.py | 61 - Lib/plat-irix6/CD.py | 34 - Lib/plat-irix6/CL.py | 24 - Lib/plat-irix6/DEVICE.py | 400 -- Lib/plat-irix6/ERRNO.py | 163 - Lib/plat-irix6/FCNTL.py | 114 - Lib/plat-irix6/FILE.py | 236 - Lib/plat-irix6/FL.py | 289 - Lib/plat-irix6/GET.py | 59 - Lib/plat-irix6/GL.py | 393 -- Lib/plat-irix6/GLWS.py | 12 - Lib/plat-irix6/IN.py | 133 - Lib/plat-irix6/IOCTL.py | 233 - Lib/plat-irix6/SV.py | 120 - Lib/plat-irix6/WAIT.py | 335 - Lib/plat-irix6/cddb.py | 206 - Lib/plat-irix6/cdplayer.py | 89 - Lib/plat-irix6/flp.doc | 117 - Lib/plat-irix6/flp.py | 450 -- Lib/plat-irix6/jpeg.py | 111 - Lib/plat-irix6/panel.py | 281 - Lib/plat-irix6/panelparser.py | 128 - Lib/plat-irix6/readcd.doc | 104 - Lib/plat-irix6/readcd.py | 244 - Lib/plat-irix6/regen | 13 - Lib/plat-irix6/torgb.py | 98 - Lib/plat-linux1/FCNTL.py | 101 - Lib/plat-linux1/IN.py | 239 - Lib/plat-linux1/regen | 11 - Lib/plat-linux2/CDROM.py | 80 - Lib/plat-linux2/FCNTL.py | 108 - Lib/plat-linux2/IN.py | 430 -- Lib/plat-linux2/regen | 11 - Lib/plat-netbsd1/FCNTL.py | 121 - Lib/plat-netbsd1/IN.py | 57 - Lib/plat-netbsd1/regen | 6 - Lib/plat-next3/regen | 11 - Lib/plat-riscos/riscosenviron.py | 45 - Lib/plat-riscos/riscospath.py | 354 - Lib/plat-riscos/rourl2path.py | 82 - Lib/plat-sunos4/FCNTL.py | 67 - Lib/plat-sunos4/IN.py | 59 - Lib/plat-sunos4/SUNAUDIODEV.py | 38 - Lib/plat-sunos4/WAIT.py | 13 - Lib/plat-sunos4/regen | 12 - Lib/plat-sunos5/CDIO.py | 73 - Lib/plat-sunos5/FCNTL.py | 204 - Lib/plat-sunos5/IN.py | 1086 --- Lib/plat-sunos5/STROPTS.py | 1450 ---- Lib/plat-sunos5/SUNAUDIODEV.py | 40 - Lib/plat-sunos5/regen | 12 - Lib/popen2.py | 198 - Lib/poplib.py | 322 - Lib/posixfile.py | 229 - Lib/posixpath.py | 378 -- Lib/pprint.py | 251 - Lib/pre.py | 654 -- Lib/profile.doc | 702 -- Lib/profile.py | 580 -- Lib/pstats.py | 526 -- Lib/pty.py | 151 - Lib/py_compile.py | 82 - Lib/pyclbr.py | 338 - Lib/pydoc.py | 1593 ----- Lib/quopri.py | 152 - Lib/random.py | 664 -- Lib/re.py | 34 - Lib/reconvert.py | 188 - Lib/regex_syntax.py | 53 - Lib/regsub.py | 198 - Lib/repr.py | 95 - Lib/rexec.py | 426 -- Lib/rfc822.py | 965 --- Lib/rlcompleter.py | 122 - Lib/robotparser.py | 273 - Lib/sched.py | 106 - Lib/sgmllib.py | 533 -- Lib/shelve.py | 158 - Lib/shlex.py | 210 - Lib/shutil.py | 138 - Lib/site-packages/README | 2 - Lib/site.py | 283 - Lib/smtpd.py | 532 -- Lib/smtplib.py | 543 -- Lib/sndhdr.py | 228 - Lib/socket.py | 254 - Lib/sre.py | 261 - Lib/sre_compile.py | 386 -- Lib/sre_constants.py | 256 - Lib/sre_parse.py | 732 -- Lib/stat.py | 86 - Lib/statcache.py | 77 - Lib/statvfs.py | 15 - Lib/string.py | 381 -- Lib/stringold.py | 430 -- Lib/sunau.py | 474 -- Lib/sunaudio.py | 44 - Lib/symbol.py | 93 - Lib/symtable.py | 250 - Lib/tabnanny.py | 373 -- Lib/telnetlib.py | 504 -- Lib/tempfile.py | 205 - Lib/test/README | 212 - Lib/test/__init__.py | 1 - Lib/test/audiotest.au | Bin 23493 -> 0 bytes Lib/test/autotest.py | 6 - Lib/test/greyrgb.uue | 1547 ----- Lib/test/nocaret.py | 2 - Lib/test/output/test_MimeWriter | 110 - Lib/test/output/test_StringIO | 21 - Lib/test/output/test___all__ | 1 - Lib/test/output/test___future__ | 1 - Lib/test/output/test_al | 1 - Lib/test/output/test_array | 1 - Lib/test/output/test_atexit | 4 - Lib/test/output/test_audioop | 1 - Lib/test/output/test_augassign | 48 - Lib/test/output/test_bastion | 10 - Lib/test/output/test_binascii | 29 - Lib/test/output/test_binhex | 1 - Lib/test/output/test_bisect | 1 - Lib/test/output/test_bsddb | 1 - Lib/test/output/test_bufio | 1 - Lib/test/output/test_builtin | 52 - Lib/test/output/test_capi | 1 - Lib/test/output/test_cd | 1 - Lib/test/output/test_cfgparser | 7 - Lib/test/output/test_cgi | 29 - Lib/test/output/test_charmapcodec | 16 - Lib/test/output/test_cl | 1 - Lib/test/output/test_class | 101 - Lib/test/output/test_cmath | 1 - Lib/test/output/test_coercion | 1054 --- Lib/test/output/test_compare | 101 - Lib/test/output/test_compile | 8 - Lib/test/output/test_complex | 1 - Lib/test/output/test_contains | 1 - Lib/test/output/test_cookie | 31 - Lib/test/output/test_copy_reg | 9 - Lib/test/output/test_cpickle | 13 - Lib/test/output/test_crypt | 1 - Lib/test/output/test_dbm | 1 - Lib/test/output/test_difflib | 280 - Lib/test/output/test_dl | 1 - Lib/test/output/test_doctest | 301 - Lib/test/output/test_dospath | 2 - Lib/test/output/test_dumbdbm | 1 - Lib/test/output/test_errno | 1 - Lib/test/output/test_exceptions | 52 - Lib/test/output/test_extcall | 108 - Lib/test/output/test_fcntl | 1 - Lib/test/output/test_file | 1 - Lib/test/output/test_fnmatch | 1 - Lib/test/output/test_fork1 | 1 - Lib/test/output/test_format | 1 - Lib/test/output/test_funcattrs | 1 - Lib/test/output/test_future | 8 - Lib/test/output/test_gc | 1 - Lib/test/output/test_gdbm | 1 - Lib/test/output/test_getopt | 1 - Lib/test/output/test_gettext | 46 - Lib/test/output/test_gl | 1 - Lib/test/output/test_global | 5 - Lib/test/output/test_grammar | 64 - Lib/test/output/test_grp | 1 - Lib/test/output/test_gzip | 1 - Lib/test/output/test_hash | 1 - Lib/test/output/test_imageop | 1 - Lib/test/output/test_imgfile | 1 - Lib/test/output/test_import | 1 - Lib/test/output/test_inspect | 1 - Lib/test/output/test_largefile | 1 - Lib/test/output/test_linuxaudiodev | 7 - Lib/test/output/test_long | 5 - Lib/test/output/test_longexp | 2 - Lib/test/output/test_mailbox | 2 - Lib/test/output/test_math | 26 - Lib/test/output/test_md5 | 9 - Lib/test/output/test_mimetools | 5 - Lib/test/output/test_minidom | 195 - Lib/test/output/test_mmap | 20 - Lib/test/output/test_new | 7 - Lib/test/output/test_nis | 2 - Lib/test/output/test_ntpath | 2 - Lib/test/output/test_opcodes | 6 - Lib/test/output/test_openpty | 2 - Lib/test/output/test_operations | 6 - Lib/test/output/test_operator | 39 - Lib/test/output/test_parser | 92 - Lib/test/output/test_pickle | 13 - Lib/test/output/test_pkg | 45 - Lib/test/output/test_poll | 17 - Lib/test/output/test_popen2 | 9 - Lib/test/output/test_posixpath | 2 - Lib/test/output/test_pow | 29 - Lib/test/output/test_pty | 3 - Lib/test/output/test_pwd | 7 - Lib/test/output/test_pyexpat | 104 - Lib/test/output/test_re | 2 - Lib/test/output/test_regex | 29 - Lib/test/output/test_rfc822 | 1 - Lib/test/output/test_rgbimg | 2 - Lib/test/output/test_richcmp | 187 - Lib/test/output/test_rotor | 5 - Lib/test/output/test_sax | 34 - Lib/test/output/test_scope | 19 - Lib/test/output/test_select | 1 - Lib/test/output/test_sha | 4 - Lib/test/output/test_signal | 2 - Lib/test/output/test_socket | 3 - Lib/test/output/test_sre | 1 - Lib/test/output/test_strftime | 1 - Lib/test/output/test_string | 3 - Lib/test/output/test_strop | 3 - Lib/test/output/test_struct | 1 - Lib/test/output/test_sunaudiodev | 1 - Lib/test/output/test_sundry | 1 - Lib/test/output/test_symtable | 1 - Lib/test/output/test_thread | 6 - Lib/test/output/test_threadedtempfile | 5 - Lib/test/output/test_time | 1 - Lib/test/output/test_timing | 1 - Lib/test/output/test_tokenize | 648 -- Lib/test/output/test_traceback | 1 - Lib/test/output/test_types | 15 - Lib/test/output/test_ucn | 7 - Lib/test/output/test_unicode | 7 - Lib/test/output/test_unicodedata | 5 - Lib/test/output/test_unpack | 1 - Lib/test/output/test_urllib | 1 - Lib/test/output/test_urlparse | 41 - Lib/test/output/test_userdict | 1 - Lib/test/output/test_userlist | 1 - Lib/test/output/test_userstring | 1 - Lib/test/output/test_wave | 1 - Lib/test/output/test_weakref | 1 - Lib/test/output/test_winreg | 3 - Lib/test/output/test_winsound | 2 - Lib/test/output/test_xmllib | 1 - Lib/test/output/test_xreadline | 4 - Lib/test/output/test_zipfile | 1 - Lib/test/output/test_zlib | 11 - Lib/test/pickletester.py | 153 - Lib/test/pystone.py | 252 - Lib/test/re_tests.py | 652 -- Lib/test/regex_tests.py | 287 - Lib/test/regrtest.py | 339 - Lib/test/reperf.py | 23 - Lib/test/sortperf.py | 141 - Lib/test/string_tests.py | 208 - Lib/test/test.xml | 115 - Lib/test/test.xml.out | 115 - Lib/test/test_MimeWriter.py | 170 - Lib/test/test_StringIO.py | 43 - Lib/test/test___all__.py | 153 - Lib/test/test___future__.py | 41 - Lib/test/test_al.py | 23 - Lib/test/test_array.py | 192 - Lib/test/test_atexit.py | 24 - Lib/test/test_audioop.py | 264 - Lib/test/test_augassign.py | 230 - Lib/test/test_b1.py | 507 -- Lib/test/test_b2.py | 323 - Lib/test/test_bastion.py | 3 - Lib/test/test_binascii.py | 112 - Lib/test/test_binhex.py | 47 - Lib/test/test_bisect.py | 127 - Lib/test/test_bsddb.py | 75 - Lib/test/test_bufio.py | 60 - Lib/test/test_builtin.py | 13 - Lib/test/test_capi.py | 16 - Lib/test/test_cd.py | 26 - Lib/test/test_cfgparser.py | 200 - Lib/test/test_cgi.py | 188 - Lib/test/test_charmapcodec.py | 43 - Lib/test/test_cl.py | 78 - Lib/test/test_class.py | 241 - Lib/test/test_cmath.py | 35 - Lib/test/test_coercion.py | 113 - Lib/test/test_compare.py | 48 - Lib/test/test_compile.py | 52 - Lib/test/test_complex.py | 65 - Lib/test/test_contains.py | 168 - Lib/test/test_cookie.py | 43 - Lib/test/test_copy_reg.py | 35 - Lib/test/test_cpickle.py | 3 - Lib/test/test_crypt.py | 11 - Lib/test/test_dbm.py | 43 - Lib/test/test_difflib.py | 2 - Lib/test/test_dl.py | 33 - Lib/test/test_doctest.py | 2 - Lib/test/test_dospath.py | 47 - Lib/test/test_dumbdbm.py | 37 - Lib/test/test_errno.py | 49 - Lib/test/test_exceptions.py | 153 - Lib/test/test_extcall.py | 211 - Lib/test/test_fcntl.py | 36 - Lib/test/test_file.py | 49 - Lib/test/test_fnmatch.py | 42 - Lib/test/test_fork1.py | 72 - Lib/test/test_format.py | 200 - Lib/test/test_funcattrs.py | 207 - Lib/test/test_future.py | 44 - Lib/test/test_future1.py | 11 - Lib/test/test_future2.py | 10 - Lib/test/test_future3.py | 10 - Lib/test/test_future4.py | 10 - Lib/test/test_future5.py | 12 - Lib/test/test_future6.py | 10 - Lib/test/test_future7.py | 11 - Lib/test/test_gc.py | 182 - Lib/test/test_gdbm.py | 46 - Lib/test/test_getopt.py | 110 - Lib/test/test_gettext.py | 200 - Lib/test/test_gl.py | 150 - Lib/test/test_global.py | 51 - Lib/test/test_grammar.py | 694 -- Lib/test/test_grp.py | 25 - Lib/test/test_gzip.py | 54 - Lib/test/test_hash.py | 23 - Lib/test/test_imageop.py | 171 - Lib/test/test_imgfile.py | 116 - Lib/test/test_import.py | 58 - Lib/test/test_inspect.py | 215 - Lib/test/test_largefile.py | 132 - Lib/test/test_linuxaudiodev.py | 89 - Lib/test/test_long.py | 259 - Lib/test/test_longexp.py | 4 - Lib/test/test_mailbox.py | 28 - Lib/test/test_math.py | 195 - Lib/test/test_md5.py | 30 - Lib/test/test_mimetools.py | 18 - Lib/test/test_minidom.py | 550 -- Lib/test/test_mmap.py | 124 - Lib/test/test_new.py | 84 - Lib/test/test_nis.py | 32 - Lib/test/test_ntpath.py | 49 - Lib/test/test_opcodes.py | 101 - Lib/test/test_openpty.py | 21 - Lib/test/test_operations.py | 28 - Lib/test/test_operator.py | 77 - Lib/test/test_parser.py | 222 - Lib/test/test_pickle.py | 3 - Lib/test/test_pkg.py | 259 - Lib/test/test_poll.py | 172 - Lib/test/test_popen2.py | 72 - Lib/test/test_posixpath.py | 40 - Lib/test/test_pow.py | 120 - Lib/test/test_pty.py | 102 - Lib/test/test_pwd.py | 71 - Lib/test/test_pyexpat.py | 183 - Lib/test/test_re.py | 386 -- Lib/test/test_regex.py | 113 - Lib/test/test_rfc822.py | 126 - Lib/test/test_rgbimg.py | 63 - Lib/test/test_richcmp.py | 233 - Lib/test/test_rotor.py | 28 - Lib/test/test_sax.py | 607 -- Lib/test/test_scope.py | 437 -- Lib/test/test_select.py | 62 - Lib/test/test_sha.py | 28 - Lib/test/test_signal.py | 66 - Lib/test/test_socket.py | 146 - Lib/test/test_sre.py | 378 -- Lib/test/test_strftime.py | 146 - Lib/test/test_string.py | 37 - Lib/test/test_strop.py | 87 - Lib/test/test_struct.py | 121 - Lib/test/test_sunaudiodev.py | 20 - Lib/test/test_sundry.py | 105 - Lib/test/test_support.py | 127 - Lib/test/test_symtable.py | 8 - Lib/test/test_thread.py | 113 - Lib/test/test_threadedtempfile.py | 85 - Lib/test/test_time.py | 39 - Lib/test/test_timing.py | 21 - Lib/test/test_tokenize.py | 9 - Lib/test/test_traceback.py | 40 - Lib/test/test_types.py | 291 - Lib/test/test_ucn.py | 113 - Lib/test/test_unicode.py | 541 -- Lib/test/test_unicodedata.py | 125 - Lib/test/test_unpack.py | 144 - Lib/test/test_urllib.py | 109 - Lib/test/test_urlparse.py | 66 - Lib/test/test_userdict.py | 102 - Lib/test/test_userlist.py | 201 - Lib/test/test_userstring.py | 45 - Lib/test/test_wave.py | 34 - Lib/test/test_weakref.py | 266 - Lib/test/test_winreg.py | 148 - Lib/test/test_winsound.py | 6 - Lib/test/test_xmllib.py | 25 - Lib/test/test_xreadline.py | 43 - Lib/test/test_zipfile.py | 61 - Lib/test/test_zlib.py | 185 - Lib/test/testall.py | 4 - Lib/test/testcodec.py | 48 - Lib/test/testimg.uue | 1170 ---- Lib/test/testimgr.uue | 1170 ---- Lib/test/testrgb.uue | 971 --- Lib/test/tokenize_tests.py | 175 - Lib/threading.py | 631 -- Lib/toaiff.py | 106 - Lib/token.py | 139 - Lib/tokenize.py | 240 - Lib/traceback.py | 300 - Lib/tty.py | 36 - Lib/types.py | 68 - Lib/tzparse.py | 98 - Lib/unittest.py | 681 -- Lib/urllib.py | 1381 ---- Lib/urllib2.py | 1137 ---- Lib/urlparse.py | 261 - Lib/user.py | 43 - Lib/uu.py | 187 - Lib/warnings.py | 251 - Lib/wave.py | 489 -- Lib/weakref.py | 179 - Lib/webbrowser.py | 273 - Lib/whichdb.py | 88 - Lib/whrandom.py | 140 - Lib/xdrlib.py | 281 - Lib/xml/__init__.py | 42 - Lib/xml/dom/__init__.py | 119 - Lib/xml/dom/domreg.py | 76 - Lib/xml/dom/minidom.py | 847 --- Lib/xml/dom/pulldom.py | 302 - Lib/xml/parsers/__init__.py | 8 - Lib/xml/parsers/expat.py | 4 - Lib/xml/sax/__init__.py | 103 - Lib/xml/sax/_exceptions.py | 126 - Lib/xml/sax/expatreader.py | 240 - Lib/xml/sax/handler.py | 321 - Lib/xml/sax/saxutils.py | 239 - Lib/xml/sax/xmlreader.py | 378 -- Lib/xmllib.py | 929 --- Lib/zipfile.py | 556 -- Mac/MPW/buildall | 29 - Mac/PlugIns/readme.txt | 1 - Mac/Unsupported/mactcp/dnrglue.c | 301 - Mac/errno_unix.h | 18 - Mac/fopenRF.c | 336 - Mac/mkapplet.py | 257 - Mac/mwerks/mwerks_config.h | 2 - Mac/mwerks/mwerks_shlib_config.h | 3 - Mac/mwerksglue.c | 43 - Makefile.pre.in | 803 --- Misc/ACKS | 428 -- Misc/AIX-NOTES | 140 - Misc/BLURB | 29 - Misc/BLURB.LUTZ | 122 - Misc/BLURB.WINDOWS | 81 - Misc/BeOS-NOTES | 129 - Misc/HISTORY | 8194 ----------------------- Misc/HPUX-NOTES | 24 - Misc/HYPE | 70 - Misc/Makefile.pre.in | 304 - Misc/NEWS | 1600 ----- Misc/NEXT-NOTES | 81 - Misc/PURIFY.README | 81 - Misc/Porting | 42 - Misc/README | 40 - Misc/RFD | 114 - Misc/RPM/BeOpen-Python-Setup.patch | 178 - Misc/RPM/README | 19 - Misc/RPM/Tkinter/setup.cfg | 4 - Misc/RPM/Tkinter/setup.py | 27 - Misc/RPM/beopen-python.spec | 175 - Misc/RPM/make-spec.sh | 11 - Misc/cheatsheet | 541 -- Misc/comparisons | 129 - Misc/editline-fix | 80 - Misc/faq2html.py | 167 - Misc/find_recursionlimit.py | 88 - Misc/fixfuncptrs.sh | 47 - Misc/gdbinit | 27 - Misc/indent.pro | 15 - Misc/python-mode.el | 3142 --------- Misc/python.man | 345 - Misc/renumber.py | 110 - Misc/setuid-prog.c | 176 - Misc/unicode.txt | 1115 --- Misc/vgrindefs | 10 - Modules/.cvsignore | 9 - Modules/Setup.config.in | 16 - Modules/Setup.dist | 466 -- Modules/_codecsmodule.c | 664 -- Modules/_curses_panel.c | 495 -- Modules/_cursesmodule.c | 2619 -------- Modules/_localemodule.c | 458 -- Modules/_sre.c | 2432 ------- Modules/_testcapimodule.c | 114 - Modules/_tkinter.c | 2257 ------- Modules/_weakref.c | 804 --- Modules/almodule.c | 3238 --------- Modules/ar_beos | 73 - Modules/arraymodule.c | 1563 ----- Modules/audioop.c | 1340 ---- Modules/binascii.c | 1013 --- Modules/bsddbmodule.c | 872 --- Modules/cPickle.c | 4610 ------------- Modules/cStringIO.c | 777 --- Modules/ccpython.cc | 11 - Modules/cdmodule.c | 795 --- Modules/cgen.py | 520 -- Modules/cgensupport.c | 310 - Modules/cgensupport.h | 64 - Modules/clmodule.c | 2568 ------- Modules/cmathmodule.c | 420 -- Modules/config.c.in | 44 - Modules/cryptmodule.c | 42 - Modules/cstubs | 1364 ---- Modules/dbmmodule.c | 357 - Modules/dlmodule.c | 251 - Modules/errnomodule.c | 791 --- Modules/fcntlmodule.c | 341 - Modules/flmodule.c | 2134 ------ Modules/fmmodule.c | 276 - Modules/fpectlmodule.c | 270 - Modules/fpetestmodule.c | 184 - Modules/gcmodule.c | 738 -- Modules/gdbmmodule.c | 521 -- Modules/getbuildinfo.c | 38 - Modules/getpath.c | 622 -- Modules/glmodule.c | 7630 --------------------- Modules/grpmodule.c | 130 - Modules/imageop.c | 708 -- Modules/imgfile.c | 514 -- Modules/ld_so_aix | 183 - Modules/ld_so_beos | 78 - Modules/license.terms | 39 - Modules/linuxaudiodev.c | 493 -- Modules/main.c | 358 - Modules/makesetup | 296 - Modules/makexp_aix | 75 - Modules/mathmodule.c | 291 - Modules/md5.h | 64 - Modules/md5c.c | 314 - Modules/md5module.c | 274 - Modules/mmapmodule.c | 999 --- Modules/mpzmodule.c | 1751 ----- Modules/newmodule.c | 228 - Modules/nismodule.c | 382 -- Modules/operator.c | 260 - Modules/parsermodule.c | 2858 -------- Modules/pcre-int.h | 303 - Modules/pcre.h | 84 - Modules/pcremodule.c | 638 -- Modules/posixmodule.c | 5633 ---------------- Modules/puremodule.c | 986 --- Modules/pwdmodule.c | 124 - Modules/pyexpat.c | 1814 ----- Modules/pypcre.c | 4752 ------------- Modules/python.c | 11 - Modules/readline.c | 509 -- Modules/regexmodule.c | 692 -- Modules/regexpr.c | 2095 ------ Modules/regexpr.h | 155 - Modules/resource.c | 244 - Modules/rgbimgmodule.c | 766 --- Modules/rotormodule.c | 624 -- Modules/selectmodule.c | 678 -- Modules/sgimodule.c | 56 - Modules/shamodule.c | 545 -- Modules/signalmodule.c | 666 -- Modules/socketmodule.c | 2947 -------- Modules/sre.h | 85 - Modules/sre_constants.h | 83 - Modules/stropmodule.c | 1232 ---- Modules/structmodule.c | 1271 ---- Modules/sunaudiodev.c | 485 -- Modules/svmodule.c | 964 --- Modules/symtablemodule.c | 73 - Modules/syslogmodule.c | 235 - Modules/tclNotify.c | 964 --- Modules/termios.c | 881 --- Modules/threadmodule.c | 395 -- Modules/timemodule.c | 846 --- Modules/timing.h | 67 - Modules/timingmodule.c | 75 - Modules/tkappinit.c | 88 - Modules/unicodedata.c | 481 -- Modules/unicodedata_db.h | 1939 ------ Modules/unicodename_db.h | 7538 --------------------- Modules/xreadlinesmodule.c | 122 - Modules/xxmodule.c | 211 - Modules/yuv.h | 99 - Modules/yuvconvert.c | 118 - Modules/zlibmodule.c | 828 --- Objects/.cvsignore | 2 - Objects/abstract.c | 1740 ----- Objects/bufferobject.c | 557 -- Objects/cellobject.c | 116 - Objects/classobject.c | 2043 ------ Objects/cobject.c | 146 - Objects/complexobject.c | 629 -- Objects/dictobject.c | 1312 ---- Objects/fileobject.c | 1482 ---- Objects/floatobject.c | 762 --- Objects/frameobject.c | 391 -- Objects/funcobject.c | 344 - Objects/intobject.c | 905 --- Objects/listobject.c | 1649 ----- Objects/longobject.c | 1874 ------ Objects/methodobject.c | 250 - Objects/moduleobject.c | 251 - Objects/object.c | 1649 ----- Objects/obmalloc.c | 743 -- Objects/rangeobject.c | 335 - Objects/sliceobject.c | 194 - Objects/stringobject.c | 3229 --------- Objects/tupleobject.c | 565 -- Objects/typeobject.c | 57 - Objects/unicodectype.c | 412 -- Objects/unicodeobject.c | 5217 --------------- Objects/unicodetype_db.h | 577 -- Objects/xxobject.c | 108 - PC/WinMain.c | 18 - PC/_winreg.c | 1495 ----- PC/config.c | 118 - PC/config.h | 634 -- PC/dl_nt.c | 39 - PC/dllbase_nt.txt | 53 - PC/example_nt/.cvsignore | 5 - PC/example_nt/example.c | 20 - PC/example_nt/example.def | 2 - PC/example_nt/example.dsp | 117 - PC/example_nt/example.dsw | 29 - PC/example_nt/readme.txt | 165 - PC/frozen_dllmain.c | 134 - PC/getpathp.c | 612 -- PC/import_nt.c | 86 - PC/msvcrtmodule.c | 232 - PC/os2vacpp/_tkinter.def | 8 - PC/os2vacpp/config.c | 114 - PC/os2vacpp/config.h | 202 - PC/os2vacpp/getpathp.c | 471 -- PC/os2vacpp/makefile | 1925 ------ PC/os2vacpp/makefile.omk | 1310 ---- PC/os2vacpp/python.def | 475 -- PC/os2vacpp/readme.txt | 114 - PC/py.ico | Bin 766 -> 0 bytes PC/pyc.ico | Bin 766 -> 0 bytes PC/pycon.ico | Bin 766 -> 0 bytes PC/python.mk | 5 - PC/python_exe.rc | 1 - PC/python_nt.rc | 86 - PC/readme.txt | 95 - PC/testpy.py | 32 - PC/w9xpopen.c | 63 - PC/winsound.c | 225 - PCbuild/.cvsignore | 14 - PCbuild/BUILDno.txt | 59 - PCbuild/_socket.dsp | 99 - PCbuild/_sre.dsp | 182 - PCbuild/_symtable.dsp | 99 - PCbuild/_testcapi.dsp | 99 - PCbuild/_tkinter.dsp | 197 - PCbuild/bsddb.dsp | 188 - PCbuild/mmap.dsp | 99 - PCbuild/parser.dsp | 182 - PCbuild/pcbuild.dsw | 281 - PCbuild/pyexpat.dsp | 190 - PCbuild/python.dsp | 170 - PCbuild/python20.wse | 1508 ----- PCbuild/pythoncore.dsp | 1754 ----- PCbuild/pythonw.dsp | 184 - PCbuild/readme.txt | 120 - PCbuild/rmpyc.py | 26 - PCbuild/rt.bat | 41 - PCbuild/select.dsp | 99 - PCbuild/unicodedata.dsp | 99 - PCbuild/w9xpopen.dsp | 97 - PCbuild/winreg.dsp | 108 - PCbuild/winsound.dsp | 99 - PCbuild/zlib.dsp | 109 - Parser/.cvsignore | 3 - Parser/acceler.c | 144 - Parser/assert.h | 19 - Parser/bitset.c | 66 - Parser/firstsets.c | 109 - Parser/grammar.c | 224 - Parser/grammar1.c | 57 - Parser/intrcheck.c | 196 - Parser/listnode.c | 66 - Parser/metagrammar.c | 153 - Parser/myreadline.c | 134 - Parser/node.c | 72 - Parser/parser.c | 370 - Parser/parser.h | 39 - Parser/parsetok.c | 158 - Parser/pgen.c | 699 -- Parser/pgen.h | 18 - Parser/pgenmain.c | 193 - Parser/printgrammar.c | 113 - Parser/tokenizer.c | 896 --- Parser/tokenizer.h | 51 - Python/.cvsignore | 2 - Python/atof.c | 50 - Python/bltinmodule.c | 2316 ------- Python/ceval.c | 3546 ---------- Python/codecs.c | 436 -- Python/compile.c | 5227 --------------- Python/dup2.c | 30 - Python/dynload_aix.c | 201 - Python/dynload_beos.c | 252 - Python/dynload_dl.c | 26 - Python/dynload_hpux.c | 54 - Python/dynload_mac.c | 119 - Python/dynload_next.c | 169 - Python/dynload_os2.c | 46 - Python/dynload_shlib.c | 101 - Python/dynload_stub.c | 11 - Python/dynload_win.c | 273 - Python/errors.c | 745 --- Python/exceptions.c | 1154 ---- Python/fmod.c | 27 - Python/frozen.c | 31 - Python/frozenmain.c | 77 - Python/future.c | 241 - Python/getargs.c | 1316 ---- Python/getcompiler.c | 28 - Python/getcopyright.c | 23 - Python/getcwd.c | 79 - Python/getmtime.c | 17 - Python/getopt.c | 83 - Python/getplatform.c | 12 - Python/getversion.c | 15 - Python/graminit.c | 1693 ----- Python/hypot.c | 23 - Python/import.c | 2422 ------- Python/importdl.c | 79 - Python/importdl.h | 51 - Python/marshal.c | 834 --- Python/memmove.c | 25 - Python/modsupport.c | 491 -- Python/mystrtoul.c | 153 - Python/pyfpe.c | 23 - Python/pystate.c | 244 - Python/pythonmain.c | 211 - Python/pythonrun.c | 1419 ---- Python/sigcheck.c | 19 - Python/strdup.c | 14 - Python/strerror.c | 23 - Python/strtod.c | 156 - Python/structmember.c | 246 - Python/symtable.c | 150 - Python/sysmodule.c | 893 --- Python/thread.c | 145 - Python/thread_beos.h | 356 - Python/thread_cthread.h | 190 - Python/thread_foobar.h | 149 - Python/thread_lwp.h | 180 - Python/thread_nt.h | 332 - Python/thread_os2.h | 207 - Python/thread_pth.h | 295 - Python/thread_pthread.h | 444 -- Python/thread_sgi.h | 503 -- Python/thread_solaris.h | 236 - Python/thread_wince.h | 171 - Python/traceback.c | 240 - README | 870 --- RISCOS/Makefile | 418 -- RISCOS/Modules/config.c | 68 - RISCOS/Modules/drawfmodule.c | 664 -- RISCOS/Modules/getpath_riscos.c | 56 - RISCOS/Modules/riscosmodule.c | 283 - RISCOS/Modules/swimodule.c | 431 -- RISCOS/Python/dynload_riscos.c | 63 - RISCOS/Python/getcwd_riscos.c | 5 - RISCOS/Python/getmtime_riscos.c | 20 - RISCOS/README | 36 - RISCOS/config.h | 488 -- RISCOS/unixstuff.c | 62 - RISCOS/unixstuff.h | 13 - Tools/README | 30 - Tools/audiopy/README | 112 - Tools/audiopy/audiopy | 508 -- Tools/bgen/README | 7 - Tools/bgen/bgen/bgen.py | 12 - Tools/bgen/bgen/bgenBuffer.py | 255 - Tools/bgen/bgen/bgenGenerator.py | 274 - Tools/bgen/bgen/bgenGeneratorGroup.py | 39 - Tools/bgen/bgen/bgenHeapBuffer.py | 110 - Tools/bgen/bgen/bgenModule.py | 88 - Tools/bgen/bgen/bgenObjectDefinition.py | 261 - Tools/bgen/bgen/bgenOutput.py | 221 - Tools/bgen/bgen/bgenStackBuffer.py | 59 - Tools/bgen/bgen/bgenStringBuffer.py | 64 - Tools/bgen/bgen/bgenType.py | 249 - Tools/bgen/bgen/bgenVariable.py | 88 - Tools/bgen/bgen/bgenlocations.py | 13 - Tools/bgen/bgen/macsupport.py | 158 - Tools/bgen/bgen/scantools.py | 599 -- Tools/compiler/ast.txt | 77 - Tools/compiler/astgen.py | 182 - Tools/compiler/compile.py | 31 - Tools/compiler/compiler/__init__.py | 24 - Tools/compiler/compiler/ast.py | 687 -- Tools/compiler/compiler/ast.txt | 77 - Tools/compiler/compiler/astgen.py | 182 - Tools/compiler/compiler/consts.py | 9 - Tools/compiler/compiler/misc.py | 41 - Tools/compiler/compiler/pyassem.py | 656 -- Tools/compiler/compiler/pycodegen.py | 1059 --- Tools/compiler/compiler/transformer.py | 1296 ---- Tools/compiler/compiler/visitor.py | 119 - Tools/compiler/demo.py | 38 - Tools/compiler/dumppyc.py | 39 - Tools/compiler/regrtest.py | 55 - Tools/compiler/setup.py | 9 - Tools/faqwiz/README | 113 - Tools/faqwiz/faqconf.py | 577 -- Tools/faqwiz/faqcust.py | 1 - Tools/faqwiz/faqw.py | 36 - Tools/faqwiz/faqwiz.py | 841 --- Tools/freeze/.cvsignore | 6 - Tools/freeze/README | 296 - Tools/freeze/bkfile.py | 47 - Tools/freeze/checkextensions.py | 91 - Tools/freeze/checkextensions_win32.py | 190 - Tools/freeze/extensions_win32.ini | 167 - Tools/freeze/freeze.py | 465 -- Tools/freeze/hello.py | 1 - Tools/freeze/makeconfig.py | 61 - Tools/freeze/makefreeze.py | 86 - Tools/freeze/makemakefile.py | 30 - Tools/freeze/modulefinder.py | 466 -- Tools/freeze/parsesetup.py | 113 - Tools/freeze/win32.html | 120 - Tools/freeze/winmakemakefile.py | 146 - Tools/i18n/msgfmt.py | 203 - Tools/i18n/pygettext.py | 496 -- Tools/idle/AutoExpand.py | 91 - Tools/idle/AutoIndent.py | 553 -- Tools/idle/Bindings.py | 57 - Tools/idle/BrowserControl.py | 157 - Tools/idle/CallTipWindow.py | 71 - Tools/idle/CallTips.py | 190 - Tools/idle/ChangeLog | 1017 --- Tools/idle/ClassBrowser.py | 224 - Tools/idle/ColorDelegator.py | 247 - Tools/idle/Debugger.py | 308 - Tools/idle/Delegator.py | 33 - Tools/idle/EditorWindow.py | 735 -- Tools/idle/FileList.py | 142 - Tools/idle/FormatParagraph.py | 155 - Tools/idle/FrameViewer.py | 38 - Tools/idle/GrepDialog.py | 135 - Tools/idle/IOBinding.py | 232 - Tools/idle/Icons/folder.gif | Bin 120 -> 0 bytes Tools/idle/Icons/minusnode.gif | Bin 96 -> 0 bytes Tools/idle/Icons/openfolder.gif | Bin 125 -> 0 bytes Tools/idle/Icons/plusnode.gif | Bin 79 -> 0 bytes Tools/idle/Icons/python.gif | Bin 125 -> 0 bytes Tools/idle/Icons/tk.gif | Bin 85 -> 0 bytes Tools/idle/IdleConf.py | 112 - Tools/idle/IdleHistory.py | 88 - Tools/idle/MultiScrolledLists.py | 138 - Tools/idle/MultiStatusBar.py | 32 - Tools/idle/NEWS.txt | 130 - Tools/idle/ObjectBrowser.py | 151 - Tools/idle/OldStackViewer.py | 276 - Tools/idle/OutputWindow.py | 148 - Tools/idle/ParenMatch.py | 191 - Tools/idle/PathBrowser.py | 95 - Tools/idle/Percolator.py | 85 - Tools/idle/PyParse.py | 588 -- Tools/idle/PyShell.py | 781 --- Tools/idle/README.txt | 52 - Tools/idle/RemoteInterp.py | 342 - Tools/idle/ReplaceDialog.py | 188 - Tools/idle/ScriptBinding.py | 173 - Tools/idle/ScrolledList.py | 139 - Tools/idle/SearchBinding.py | 97 - Tools/idle/SearchDialog.py | 67 - Tools/idle/SearchDialogBase.py | 129 - Tools/idle/SearchEngine.py | 221 - Tools/idle/Separator.py | 92 - Tools/idle/StackViewer.py | 135 - Tools/idle/TODO.txt | 211 - Tools/idle/ToolTip.py | 87 - Tools/idle/TreeWidget.py | 471 -- Tools/idle/UndoDelegator.py | 352 - Tools/idle/WidgetRedirector.py | 92 - Tools/idle/WindowList.py | 85 - Tools/idle/ZoomHeight.py | 46 - Tools/idle/__init__.py | 1 - Tools/idle/config-unix.txt | 3 - Tools/idle/config-win.txt | 3 - Tools/idle/config.txt | 64 - Tools/idle/eventparse.py | 93 - Tools/idle/extend.txt | 106 - Tools/idle/help.txt | 156 - Tools/idle/idle | 12 - Tools/idle/idle.bat | 3 - Tools/idle/idle.py | 12 - Tools/idle/idle.pyw | 8 - Tools/idle/idlever.py | 1 - Tools/idle/keydefs.py | 55 - Tools/idle/setup.py | 81 - Tools/idle/testcode.py | 31 - Tools/modulator/EXAMPLE.py | 53 - Tools/modulator/README | 25 - Tools/modulator/ScrolledListbox.py | 37 - Tools/modulator/Templates/copyright | 0 Tools/modulator/Templates/module_head | 6 - Tools/modulator/Templates/module_method | 16 - Tools/modulator/Templates/module_tail | 37 - Tools/modulator/Templates/object_head | 13 - Tools/modulator/Templates/object_method | 16 - Tools/modulator/Templates/object_mlist | 8 - Tools/modulator/Templates/object_new | 13 - Tools/modulator/Templates/object_structure | 42 - Tools/modulator/Templates/object_tail | 33 - Tools/modulator/Templates/object_tp_as_mapping | 34 - Tools/modulator/Templates/object_tp_as_number | 206 - Tools/modulator/Templates/object_tp_as_sequence | 73 - Tools/modulator/Templates/object_tp_call | 10 - Tools/modulator/Templates/object_tp_compare | 7 - Tools/modulator/Templates/object_tp_dealloc | 8 - Tools/modulator/Templates/object_tp_getattr | 9 - Tools/modulator/Templates/object_tp_hash | 7 - Tools/modulator/Templates/object_tp_print | 10 - Tools/modulator/Templates/object_tp_repr | 10 - Tools/modulator/Templates/object_tp_setattr | 12 - Tools/modulator/Templates/object_tp_str | 11 - Tools/modulator/Tkextra.py | 235 - Tools/modulator/genmodule.py | 161 - Tools/modulator/modulator.py | 380 -- Tools/modulator/varsubst.py | 61 - Tools/pynche/ChipViewer.py | 109 - Tools/pynche/ColorDB.py | 289 - Tools/pynche/DetailsViewer.py | 273 - Tools/pynche/ListViewer.py | 176 - Tools/pynche/Main.py | 222 - Tools/pynche/PyncheWidget.py | 310 - Tools/pynche/README | 377 -- Tools/pynche/StripViewer.py | 432 -- Tools/pynche/Switchboard.py | 138 - Tools/pynche/TextViewer.py | 187 - Tools/pynche/TypeinViewer.py | 158 - Tools/pynche/X/rgb.txt | 753 --- Tools/pynche/X/xlicense.txt | 29 - Tools/pynche/__init__.py | 1 - Tools/pynche/html40colors.txt | 17 - Tools/pynche/namedcolors.txt | 100 - Tools/pynche/pyColorChooser.py | 123 - Tools/pynche/pynche | 7 - Tools/pynche/pynche.pyw | 7 - Tools/pynche/webcolors.txt | 141 - Tools/pynche/websafe.txt | 217 - Tools/scripts/README | 47 - Tools/scripts/byteyears.py | 57 - Tools/scripts/checkappend.py | 168 - Tools/scripts/checkpyc.py | 65 - Tools/scripts/classfix.py | 192 - Tools/scripts/copytime.py | 25 - Tools/scripts/crlf.py | 19 - Tools/scripts/cvsfiles.py | 72 - Tools/scripts/dutree.doc | 54 - Tools/scripts/dutree.py | 59 - Tools/scripts/eptags.py | 56 - Tools/scripts/findlinksto.py | 42 - Tools/scripts/fixcid.py | 318 - Tools/scripts/fixheader.py | 49 - Tools/scripts/fixnotice.py | 48 - Tools/scripts/fixps.py | 33 - Tools/scripts/ftpmirror.py | 397 -- Tools/scripts/gencodec.py | 317 - Tools/scripts/h2py.py | 150 - Tools/scripts/ifdef.py | 113 - Tools/scripts/lfcr.py | 19 - Tools/scripts/linktree.py | 79 - Tools/scripts/lll.py | 25 - Tools/scripts/logmerge.py | 135 - Tools/scripts/mailerdaemon.py | 238 - Tools/scripts/methfix.py | 173 - Tools/scripts/mkreal.py | 65 - Tools/scripts/ndiff.py | 345 - Tools/scripts/nm2def.py | 103 - Tools/scripts/objgraph.py | 215 - Tools/scripts/parseentities.py | 64 - Tools/scripts/pathfix.py | 149 - Tools/scripts/pdeps.py | 167 - Tools/scripts/pindent.py | 543 -- Tools/scripts/ptags.py | 51 - Tools/scripts/pydoc | 4 - Tools/scripts/pydoc.pyw | 2 - Tools/scripts/redemo.py | 171 - Tools/scripts/reindent.py | 258 - Tools/scripts/rgrep.py | 65 - Tools/scripts/suff.py | 29 - Tools/scripts/sum5.py | 97 - Tools/scripts/texi2html.py | 1613 ----- Tools/scripts/trace.py | 660 -- Tools/scripts/treesync.py | 204 - Tools/scripts/untabify.py | 53 - Tools/scripts/which.py | 56 - Tools/scripts/xxci.py | 117 - Tools/unicode/makeunicodedata.py | 678 -- Tools/versioncheck/README | 41 - Tools/versioncheck/_checkversion.py | 16 - Tools/versioncheck/checkversions.py | 55 - Tools/versioncheck/pyversioncheck.py | 101 - Tools/webchecker/README | 20 - Tools/webchecker/tktools.py | 367 - Tools/webchecker/wcgui.py | 464 -- Tools/webchecker/wcmac.py | 7 - Tools/webchecker/webchecker.py | 824 --- Tools/webchecker/websucker.py | 126 - Tools/webchecker/wsgui.py | 243 - Tools/world/README | 85 - Tools/world/world | 546 -- acconfig.h | 208 - config.h.in | 649 -- configure | 6602 ------------------ configure.in | 1351 ---- install-sh | 251 - setup.py | 602 -- 2177 files changed, 526636 deletions(-) delete mode 100644 .cvsignore delete mode 100644 Demo/README delete mode 100755 Demo/classes/Complex.py delete mode 100755 Demo/classes/Dates.py delete mode 100755 Demo/classes/Dbm.py delete mode 100644 Demo/classes/README delete mode 100755 Demo/classes/Range.py delete mode 100755 Demo/classes/Rat.py delete mode 100755 Demo/classes/Rev.py delete mode 100755 Demo/classes/Vec.py delete mode 100755 Demo/classes/bitvec.py delete mode 100755 Demo/classes/class.doc delete mode 100644 Demo/comparisons/README delete mode 100755 Demo/comparisons/patterns delete mode 100755 Demo/comparisons/regextest.py delete mode 100755 Demo/comparisons/sortingtest.py delete mode 100755 Demo/comparisons/systemtest.py delete mode 100644 Demo/curses/README delete mode 100755 Demo/curses/life.py delete mode 100644 Demo/curses/ncurses.py delete mode 100644 Demo/curses/rain.py delete mode 100755 Demo/curses/repeat.py delete mode 100644 Demo/curses/tclock.py delete mode 100644 Demo/curses/xmas.py delete mode 100644 Demo/dns/README delete mode 100755 Demo/dns/asgethost.py delete mode 100755 Demo/dns/dnsclass.py delete mode 100755 Demo/dns/dnslib.py delete mode 100755 Demo/dns/dnsopcode.py delete mode 100755 Demo/dns/dnstype.py delete mode 100644 Demo/embed/.cvsignore delete mode 100644 Demo/embed/Makefile delete mode 100644 Demo/embed/README delete mode 100644 Demo/embed/demo.c delete mode 100644 Demo/embed/importexc.c delete mode 100644 Demo/embed/loop.c delete mode 100644 Demo/extend/README delete mode 100755 Demo/extend/make_clean delete mode 100755 Demo/extend/make_shared delete mode 100755 Demo/extend/make_static delete mode 100644 Demo/imputil/importers.py delete mode 100644 Demo/md5test/README delete mode 100755 Demo/md5test/foo delete mode 100755 Demo/md5test/md5driver.py delete mode 100644 Demo/metaclasses/Eiffel.py delete mode 100644 Demo/metaclasses/Enum.py delete mode 100644 Demo/metaclasses/Meta.py delete mode 100644 Demo/metaclasses/Simple.py delete mode 100644 Demo/metaclasses/Synch.py delete mode 100644 Demo/metaclasses/Trace.py delete mode 100644 Demo/metaclasses/index.html delete mode 100644 Demo/metaclasses/meta-vladimir.txt delete mode 100644 Demo/parser/FILES delete mode 100644 Demo/parser/README delete mode 100644 Demo/parser/docstring.py delete mode 100644 Demo/parser/example.py delete mode 100644 Demo/parser/simple.py delete mode 100644 Demo/parser/source.py delete mode 100755 Demo/parser/test_parser.py delete mode 100644 Demo/parser/texipre.dat delete mode 100755 Demo/pdist/FSProxy.py delete mode 100755 Demo/pdist/RCSProxy.py delete mode 100644 Demo/pdist/README delete mode 100755 Demo/pdist/client.py delete mode 100755 Demo/pdist/cmdfw.py delete mode 100755 Demo/pdist/cmptree.py delete mode 100755 Demo/pdist/cvslib.py delete mode 100755 Demo/pdist/cvslock.py delete mode 100755 Demo/pdist/mac.py delete mode 100755 Demo/pdist/makechangelog.py delete mode 100755 Demo/pdist/new delete mode 100755 Demo/pdist/rcsbump delete mode 100755 Demo/pdist/rcsclient.py delete mode 100755 Demo/pdist/rcslib.py delete mode 100755 Demo/pdist/rcvs delete mode 100755 Demo/pdist/rcvs.py delete mode 100755 Demo/pdist/rrcs delete mode 100755 Demo/pdist/rrcs.py delete mode 100755 Demo/pdist/security.py delete mode 100755 Demo/pdist/server.py delete mode 100755 Demo/pdist/sumtree.py delete mode 100644 Demo/pysvr/Makefile delete mode 100644 Demo/pysvr/README delete mode 100644 Demo/pysvr/pysvr.c delete mode 100755 Demo/pysvr/pysvr.py delete mode 100644 Demo/rpc/MANIFEST delete mode 100644 Demo/rpc/README delete mode 100644 Demo/rpc/T.py delete mode 100644 Demo/rpc/mountclient.py delete mode 100644 Demo/rpc/nfsclient.py delete mode 100644 Demo/rpc/rnusersclient.py delete mode 100644 Demo/rpc/rpc.py delete mode 100755 Demo/rpc/test delete mode 100644 Demo/rpc/xdr.py delete mode 100644 Demo/scripts/README delete mode 100644 Demo/scripts/beer.py delete mode 100755 Demo/scripts/eqfix.py delete mode 100755 Demo/scripts/fact.py delete mode 100755 Demo/scripts/freeze.py delete mode 100755 Demo/scripts/from.py delete mode 100755 Demo/scripts/ftpstats.py delete mode 100755 Demo/scripts/lpwatch.py delete mode 100755 Demo/scripts/makedir.py delete mode 100755 Demo/scripts/markov.py delete mode 100755 Demo/scripts/mboxconvert.py delete mode 100755 Demo/scripts/mkrcs.py delete mode 100755 Demo/scripts/morse.py delete mode 100755 Demo/scripts/mpzpi.py delete mode 100755 Demo/scripts/newslist.doc delete mode 100755 Demo/scripts/newslist.py delete mode 100755 Demo/scripts/pi.py delete mode 100755 Demo/scripts/pp.py delete mode 100755 Demo/scripts/primes.py delete mode 100755 Demo/scripts/queens.py delete mode 100755 Demo/scripts/script.py delete mode 100755 Demo/scripts/unbirthday.py delete mode 100755 Demo/scripts/update.py delete mode 100755 Demo/scripts/wh.py delete mode 100644 Demo/sgi/README delete mode 100644 Demo/sgi/al/.cvsignore delete mode 100644 Demo/sgi/al/README delete mode 100755 Demo/sgi/al/alwatch.py delete mode 100755 Demo/sgi/al/broadcast.py delete mode 100755 Demo/sgi/al/cmpaf.py delete mode 100755 Demo/sgi/al/cmpaf_form.fd delete mode 100755 Demo/sgi/al/intercom.py delete mode 100755 Demo/sgi/al/listen.py delete mode 100755 Demo/sgi/al/names.py delete mode 100755 Demo/sgi/al/playaiff.py delete mode 100755 Demo/sgi/al/playback.py delete mode 100755 Demo/sgi/al/playold.py delete mode 100755 Demo/sgi/al/radio.py delete mode 100755 Demo/sgi/al/rec_play.py delete mode 100755 Demo/sgi/al/record.py delete mode 100755 Demo/sgi/al/unicast.py delete mode 100755 Demo/sgi/al/x.py delete mode 100644 Demo/sgi/audio/README delete mode 100755 Demo/sgi/audio/play.py delete mode 100755 Demo/sgi/cd/CD.doc delete mode 100644 Demo/sgi/cd/README delete mode 100755 Demo/sgi/cd/cdaiff.py delete mode 100755 Demo/sgi/cd/listcd.py delete mode 100755 Demo/sgi/cd/playcd.py delete mode 100755 Demo/sgi/cd/recvcd.py delete mode 100755 Demo/sgi/cd/sendcd.py delete mode 100644 Demo/sgi/flp/.cvsignore delete mode 100755 Demo/sgi/flp/tcache.fd delete mode 100755 Demo/sgi/flp/tcache.py delete mode 100755 Demo/sgi/flp/test_cb.fd delete mode 100755 Demo/sgi/flp/test_cb.py delete mode 100755 Demo/sgi/flp/test_nocb.fd delete mode 100755 Demo/sgi/flp/test_nocb.py delete mode 100644 Demo/sgi/gl/README delete mode 100755 Demo/sgi/gl/backface.py delete mode 100755 Demo/sgi/gl/glinfo.py delete mode 100755 Demo/sgi/gl/kites.py delete mode 100755 Demo/sgi/gl/kunst.py delete mode 100755 Demo/sgi/gl/mclock.doc delete mode 100755 Demo/sgi/gl/mclock.py delete mode 100755 Demo/sgi/gl/mixing.py delete mode 100755 Demo/sgi/gl/nurbs.py delete mode 100755 Demo/sgi/gl/zrgb.py delete mode 100644 Demo/sgi/sv/README delete mode 100755 Demo/sgi/sv/burstcapt.py delete mode 100755 Demo/sgi/sv/contcapt.py delete mode 100755 Demo/sgi/sv/rgbgrab.py delete mode 100755 Demo/sgi/sv/simpleinput.py delete mode 100755 Demo/sgi/video/.cvsignore delete mode 100755 Demo/sgi/video/DisplayVideoIn.py delete mode 100755 Demo/sgi/video/Dsend.py delete mode 100755 Demo/sgi/video/IN.py delete mode 100755 Demo/sgi/video/LiveVideoIn.py delete mode 100755 Demo/sgi/video/LiveVideoOut.py delete mode 100755 Demo/sgi/video/Makefile delete mode 100755 Demo/sgi/video/OldVcopy.py delete mode 100644 Demo/sgi/video/README delete mode 100755 Demo/sgi/video/VCR.py delete mode 100755 Demo/sgi/video/VFile.py delete mode 100755 Demo/sgi/video/VGrabber.py delete mode 100755 Demo/sgi/video/Vaddcache.py delete mode 100755 Demo/sgi/video/Vb.py delete mode 100644 Demo/sgi/video/VbForm.fd delete mode 100755 Demo/sgi/video/Vcopy.py delete mode 100755 Demo/sgi/video/VcrIndex.py delete mode 100755 Demo/sgi/video/Vedit.py delete mode 100644 Demo/sgi/video/VeditForm.fd delete mode 100755 Demo/sgi/video/Vfix.py delete mode 100755 Demo/sgi/video/Vgeneric.py delete mode 100755 Demo/sgi/video/Viewer.py delete mode 100755 Demo/sgi/video/Vinfo.py delete mode 100755 Demo/sgi/video/Vmkjpeg.py delete mode 100755 Demo/sgi/video/Vplay.py delete mode 100755 Demo/sgi/video/Vrec.py delete mode 100755 Demo/sgi/video/Vrecb.py delete mode 100755 Demo/sgi/video/Vrecc.py delete mode 100755 Demo/sgi/video/Vreceive.py delete mode 100755 Demo/sgi/video/Vsend.py delete mode 100755 Demo/sgi/video/Vstat.py delete mode 100755 Demo/sgi/video/Vtime.py delete mode 100755 Demo/sgi/video/Vunjpeg.py delete mode 100755 Demo/sgi/video/aplay.py delete mode 100755 Demo/sgi/video/cam.py delete mode 100755 Demo/sgi/video/camcorder.py delete mode 100755 Demo/sgi/video/cmif-film.ms delete mode 100755 Demo/sgi/video/colorsys.py delete mode 100755 Demo/sgi/video/i2v.c delete mode 100755 Demo/sgi/video/imgconv.py delete mode 100755 Demo/sgi/video/makemovie.py delete mode 100755 Demo/sgi/video/rgb2video.py delete mode 100755 Demo/sgi/video/senddefs.py delete mode 100755 Demo/sgi/video/squash.c delete mode 100755 Demo/sgi/video/squash2.c delete mode 100755 Demo/sgi/video/statit.py delete mode 100755 Demo/sgi/video/svgrab24.c delete mode 100755 Demo/sgi/video/syncaudio.py delete mode 100755 Demo/sgi/video/tomono.c delete mode 100755 Demo/sgi/video/tv.py delete mode 100755 Demo/sgi/video/v2i.c delete mode 100755 Demo/sgi/video/vcopy.py delete mode 100755 Demo/sgi/video/video.doc delete mode 100755 Demo/sgi/video/video.py delete mode 100755 Demo/sgi/video/video2rgb.py delete mode 100755 Demo/sgi/video/vinfo.py delete mode 100755 Demo/sgi/video/vpregs.py delete mode 100755 Demo/sgi/video/vtime.py delete mode 100755 Demo/sgi/video/watchcursor.py delete mode 100755 Demo/sockets/ChangeLog delete mode 100644 Demo/sockets/README delete mode 100755 Demo/sockets/broadcast.py delete mode 100755 Demo/sockets/echosvr.py delete mode 100755 Demo/sockets/finger.py delete mode 100755 Demo/sockets/ftp.py delete mode 100755 Demo/sockets/gopher.py delete mode 100755 Demo/sockets/mcast.py delete mode 100755 Demo/sockets/radio.py delete mode 100755 Demo/sockets/rpython.py delete mode 100755 Demo/sockets/rpythond.py delete mode 100755 Demo/sockets/telnet.py delete mode 100755 Demo/sockets/throughput.py delete mode 100755 Demo/sockets/udpecho.py delete mode 100644 Demo/sockets/unicast.py delete mode 100644 Demo/sockets/unixclient.py delete mode 100644 Demo/sockets/unixserver.py delete mode 100644 Demo/threads/Coroutine.py delete mode 100644 Demo/threads/Generator.py delete mode 100644 Demo/threads/README delete mode 100644 Demo/threads/bug.py delete mode 100644 Demo/threads/fcmp.py delete mode 100644 Demo/threads/find.py delete mode 100644 Demo/threads/squasher.py delete mode 100644 Demo/threads/sync.py delete mode 100644 Demo/threads/telnet.py delete mode 100644 Demo/tix/BUGS.txt delete mode 100644 Demo/tix/INSTALL.txt delete mode 100644 Demo/tix/README.txt delete mode 100755 Demo/tix/bitmaps/about.xpm delete mode 100755 Demo/tix/bitmaps/bold.xbm delete mode 100755 Demo/tix/bitmaps/capital.xbm delete mode 100755 Demo/tix/bitmaps/centerj.xbm delete mode 100755 Demo/tix/bitmaps/combobox.xbm delete mode 100755 Demo/tix/bitmaps/combobox.xpm delete mode 100755 Demo/tix/bitmaps/combobox.xpm.1 delete mode 100755 Demo/tix/bitmaps/drivea.xbm delete mode 100755 Demo/tix/bitmaps/drivea.xpm delete mode 100755 Demo/tix/bitmaps/exit.xpm delete mode 100755 Demo/tix/bitmaps/filebox.xbm delete mode 100755 Demo/tix/bitmaps/filebox.xpm delete mode 100755 Demo/tix/bitmaps/italic.xbm delete mode 100755 Demo/tix/bitmaps/justify.xbm delete mode 100755 Demo/tix/bitmaps/leftj.xbm delete mode 100755 Demo/tix/bitmaps/netw.xbm delete mode 100755 Demo/tix/bitmaps/netw.xpm delete mode 100755 Demo/tix/bitmaps/optmenu.xpm delete mode 100755 Demo/tix/bitmaps/rightj.xbm delete mode 100755 Demo/tix/bitmaps/select.xpm delete mode 100755 Demo/tix/bitmaps/tix.gif delete mode 100755 Demo/tix/bitmaps/underline.xbm delete mode 100755 Demo/tix/samples/Balloon.py delete mode 100755 Demo/tix/samples/BtnBox.py delete mode 100755 Demo/tix/samples/CmpImg.py delete mode 100755 Demo/tix/samples/ComboBox.py delete mode 100755 Demo/tix/samples/Control.py delete mode 100755 Demo/tix/samples/NoteBook.py delete mode 100755 Demo/tix/samples/OptMenu.py delete mode 100755 Demo/tix/samples/PopMenu.py delete mode 100755 Demo/tix/samples/SHList1.py delete mode 100755 Demo/tix/samples/SHList2.py delete mode 100755 Demo/tix/samples/Tree.py delete mode 100644 Demo/tix/tixwidgets.py delete mode 100644 Demo/tkinter/README delete mode 100644 Demo/tkinter/Tree.py delete mode 100755 Demo/tkinter/guido/AttrDialog.py delete mode 100755 Demo/tkinter/guido/ManPage.py delete mode 100755 Demo/tkinter/guido/MimeViewer.py delete mode 100755 Demo/tkinter/guido/ShellWindow.py delete mode 100644 Demo/tkinter/guido/brownian.py delete mode 100644 Demo/tkinter/guido/canvasevents.py delete mode 100755 Demo/tkinter/guido/dialog.py delete mode 100755 Demo/tkinter/guido/electrons.py delete mode 100755 Demo/tkinter/guido/hanoi.py delete mode 100755 Demo/tkinter/guido/hello.py delete mode 100755 Demo/tkinter/guido/imagedraw.py delete mode 100755 Demo/tkinter/guido/imageview.py delete mode 100755 Demo/tkinter/guido/kill.py delete mode 100755 Demo/tkinter/guido/listtree.py delete mode 100755 Demo/tkinter/guido/mbox.py delete mode 100644 Demo/tkinter/guido/newmenubardemo.py delete mode 100644 Demo/tkinter/guido/optionmenu.py delete mode 100644 Demo/tkinter/guido/paint.py delete mode 100755 Demo/tkinter/guido/rmt.py delete mode 100755 Demo/tkinter/guido/solitaire.py delete mode 100644 Demo/tkinter/guido/sortvisu.py delete mode 100755 Demo/tkinter/guido/svkill.py delete mode 100644 Demo/tkinter/guido/switch.py delete mode 100755 Demo/tkinter/guido/tkman.py delete mode 100755 Demo/tkinter/guido/wish.py delete mode 100644 Demo/tkinter/matt/00-HELLO-WORLD.py delete mode 100644 Demo/tkinter/matt/README delete mode 100644 Demo/tkinter/matt/animation-simple.py delete mode 100644 Demo/tkinter/matt/animation-w-velocity-ctrl.py delete mode 100644 Demo/tkinter/matt/bind-w-mult-calls-p-type.py delete mode 100644 Demo/tkinter/matt/canvas-demo-simple.py delete mode 100644 Demo/tkinter/matt/canvas-gridding.py delete mode 100644 Demo/tkinter/matt/canvas-moving-or-creating.py delete mode 100644 Demo/tkinter/matt/canvas-moving-w-mouse.py delete mode 100644 Demo/tkinter/matt/canvas-mult-item-sel.py delete mode 100644 Demo/tkinter/matt/canvas-reading-tag-info.py delete mode 100644 Demo/tkinter/matt/canvas-w-widget-draw-el.py delete mode 100644 Demo/tkinter/matt/canvas-with-scrollbars.py delete mode 100644 Demo/tkinter/matt/dialog-box.py delete mode 100644 Demo/tkinter/matt/entry-simple.py delete mode 100644 Demo/tkinter/matt/entry-with-shared-variable.py delete mode 100644 Demo/tkinter/matt/killing-window-w-wm.py delete mode 100644 Demo/tkinter/matt/menu-all-types-of-entries.py delete mode 100644 Demo/tkinter/matt/menu-simple.py delete mode 100644 Demo/tkinter/matt/not-what-you-might-think-1.py delete mode 100644 Demo/tkinter/matt/not-what-you-might-think-2.py delete mode 100644 Demo/tkinter/matt/packer-and-placer-together.py delete mode 100644 Demo/tkinter/matt/packer-simple.py delete mode 100644 Demo/tkinter/matt/placer-simple.py delete mode 100644 Demo/tkinter/matt/pong-demo-1.py delete mode 100644 Demo/tkinter/matt/printing-coords-of-items.py delete mode 100644 Demo/tkinter/matt/radiobutton-simple.py delete mode 100644 Demo/tkinter/matt/rubber-band-box-demo-1.py delete mode 100644 Demo/tkinter/matt/rubber-line-demo-1.py delete mode 100644 Demo/tkinter/matt/slider-demo-1.py delete mode 100644 Demo/tkinter/matt/subclass-existing-widgets.py delete mode 100644 Demo/tkinter/matt/two-radio-groups.py delete mode 100644 Demo/tkinter/matt/window-creation-more.py delete mode 100644 Demo/tkinter/matt/window-creation-simple.py delete mode 100644 Demo/tkinter/matt/window-creation-w-location.py delete mode 100644 Demo/xml/elem_count.py delete mode 100644 Demo/xml/roundtrip.py delete mode 100644 Demo/xml/rss2html.py delete mode 100755 Demo/zlib/minigzip.py delete mode 100755 Demo/zlib/zlibdemo.py delete mode 100755 Doc/.cvsignore delete mode 100644 Doc/ACKS delete mode 100644 Doc/Makefile delete mode 100644 Doc/Makefile.deps delete mode 100644 Doc/README delete mode 100644 Doc/TODO delete mode 100644 Doc/api/.cvsignore delete mode 100644 Doc/api/api.tex delete mode 100644 Doc/api/refcounts.dat delete mode 100644 Doc/dist/.cvsignore delete mode 100644 Doc/dist/dist.tex delete mode 100644 Doc/doc/doc.tex delete mode 100644 Doc/ext/.cvsignore delete mode 100644 Doc/ext/ext.tex delete mode 100644 Doc/html/.cvsignore delete mode 100644 Doc/html/about.dat delete mode 100644 Doc/html/about.html delete mode 100644 Doc/html/icons/blank.gif delete mode 100644 Doc/html/icons/blank.png delete mode 100644 Doc/html/icons/contents.gif delete mode 100644 Doc/html/icons/contents.png delete mode 100644 Doc/html/icons/index.gif delete mode 100644 Doc/html/icons/index.png delete mode 100644 Doc/html/icons/modules.gif delete mode 100644 Doc/html/icons/modules.png delete mode 100644 Doc/html/icons/next.gif delete mode 100644 Doc/html/icons/next.png delete mode 100644 Doc/html/icons/previous.gif delete mode 100644 Doc/html/icons/previous.png delete mode 100644 Doc/html/icons/up.gif delete mode 100644 Doc/html/icons/up.png delete mode 100644 Doc/html/index.html.in delete mode 100644 Doc/html/stdabout.dat delete mode 100644 Doc/html/style.css delete mode 100644 Doc/info/.cvsignore delete mode 100644 Doc/info/Makefile delete mode 100644 Doc/info/README delete mode 100644 Doc/info/python.dir delete mode 100644 Doc/inst/inst.tex delete mode 100644 Doc/lib/.cvsignore delete mode 100644 Doc/lib/internet.tex delete mode 100644 Doc/lib/language.tex delete mode 100644 Doc/lib/lib.tex delete mode 100644 Doc/lib/libaifc.tex delete mode 100644 Doc/lib/libal.tex delete mode 100644 Doc/lib/liballos.tex delete mode 100644 Doc/lib/libamoeba.tex delete mode 100644 Doc/lib/libanydbm.tex delete mode 100644 Doc/lib/libarray.tex delete mode 100644 Doc/lib/libascii.tex delete mode 100644 Doc/lib/libasyncore.tex delete mode 100644 Doc/lib/libatexit.tex delete mode 100644 Doc/lib/libaudioop.tex delete mode 100644 Doc/lib/libbase64.tex delete mode 100644 Doc/lib/libbasehttp.tex delete mode 100644 Doc/lib/libbastion.tex delete mode 100644 Doc/lib/libbinascii.tex delete mode 100644 Doc/lib/libbinhex.tex delete mode 100644 Doc/lib/libbisect.tex delete mode 100644 Doc/lib/libbltin.tex delete mode 100644 Doc/lib/libbsddb.tex delete mode 100644 Doc/lib/libcalendar.tex delete mode 100644 Doc/lib/libcd.tex delete mode 100644 Doc/lib/libcfgparser.tex delete mode 100644 Doc/lib/libcgi.tex delete mode 100644 Doc/lib/libcgihttp.tex delete mode 100644 Doc/lib/libchunk.tex delete mode 100644 Doc/lib/libcmath.tex delete mode 100644 Doc/lib/libcmd.tex delete mode 100644 Doc/lib/libcmp.tex delete mode 100644 Doc/lib/libcmpcache.tex delete mode 100644 Doc/lib/libcode.tex delete mode 100644 Doc/lib/libcodecs.tex delete mode 100644 Doc/lib/libcodeop.tex delete mode 100644 Doc/lib/libcolorsys.tex delete mode 100644 Doc/lib/libcommands.tex delete mode 100644 Doc/lib/libcompileall.tex delete mode 100644 Doc/lib/libcookie.tex delete mode 100644 Doc/lib/libcopy.tex delete mode 100644 Doc/lib/libcopyreg.tex delete mode 100644 Doc/lib/libcrypt.tex delete mode 100644 Doc/lib/libcrypto.tex delete mode 100644 Doc/lib/libcurses.tex delete mode 100644 Doc/lib/libcursespanel.tex delete mode 100644 Doc/lib/libdbhash.tex delete mode 100644 Doc/lib/libdbm.tex delete mode 100644 Doc/lib/libdifflib.tex delete mode 100644 Doc/lib/libdircache.tex delete mode 100644 Doc/lib/libdis.tex delete mode 100644 Doc/lib/libdl.tex delete mode 100644 Doc/lib/libdoctest.tex delete mode 100644 Doc/lib/liberrno.tex delete mode 100644 Doc/lib/libexcs.tex delete mode 100644 Doc/lib/libfcntl.tex delete mode 100644 Doc/lib/libfilecmp.tex delete mode 100644 Doc/lib/libfileinput.tex delete mode 100644 Doc/lib/libfl.tex delete mode 100644 Doc/lib/libfm.tex delete mode 100644 Doc/lib/libfnmatch.tex delete mode 100644 Doc/lib/libformatter.tex delete mode 100644 Doc/lib/libfpectl.tex delete mode 100644 Doc/lib/libfpformat.tex delete mode 100644 Doc/lib/libftplib.tex delete mode 100644 Doc/lib/libfuncs.tex delete mode 100644 Doc/lib/libgc.tex delete mode 100644 Doc/lib/libgdbm.tex delete mode 100644 Doc/lib/libgetopt.tex delete mode 100644 Doc/lib/libgetpass.tex delete mode 100644 Doc/lib/libgettext.tex delete mode 100644 Doc/lib/libgl.tex delete mode 100644 Doc/lib/libglob.tex delete mode 100644 Doc/lib/libgopherlib.tex delete mode 100644 Doc/lib/libgrp.tex delete mode 100644 Doc/lib/libgzip.tex delete mode 100644 Doc/lib/libhtmllib.tex delete mode 100644 Doc/lib/libhttplib.tex delete mode 100644 Doc/lib/libimageop.tex delete mode 100644 Doc/lib/libimaplib.tex delete mode 100644 Doc/lib/libimgfile.tex delete mode 100644 Doc/lib/libimghdr.tex delete mode 100644 Doc/lib/libimp.tex delete mode 100644 Doc/lib/libinspect.tex delete mode 100644 Doc/lib/libintro.tex delete mode 100644 Doc/lib/libjpeg.tex delete mode 100644 Doc/lib/libkeyword.tex delete mode 100644 Doc/lib/liblinecache.tex delete mode 100644 Doc/lib/liblocale.tex delete mode 100644 Doc/lib/libmailbox.tex delete mode 100644 Doc/lib/libmailcap.tex delete mode 100644 Doc/lib/libmain.tex delete mode 100644 Doc/lib/libmarshal.tex delete mode 100644 Doc/lib/libmath.tex delete mode 100644 Doc/lib/libmd5.tex delete mode 100644 Doc/lib/libmhlib.tex delete mode 100644 Doc/lib/libmimetools.tex delete mode 100644 Doc/lib/libmimetypes.tex delete mode 100644 Doc/lib/libmimewriter.tex delete mode 100644 Doc/lib/libmimify.tex delete mode 100644 Doc/lib/libmisc.tex delete mode 100644 Doc/lib/libmm.tex delete mode 100644 Doc/lib/libmmap.tex delete mode 100644 Doc/lib/libmpz.tex delete mode 100644 Doc/lib/libmsvcrt.tex delete mode 100644 Doc/lib/libmultifile.tex delete mode 100644 Doc/lib/libmutex.tex delete mode 100644 Doc/lib/libnetrc.tex delete mode 100644 Doc/lib/libnew.tex delete mode 100644 Doc/lib/libni.tex delete mode 100644 Doc/lib/libnis.tex delete mode 100644 Doc/lib/libnntplib.tex delete mode 100644 Doc/lib/libobjs.tex delete mode 100644 Doc/lib/liboperator.tex delete mode 100644 Doc/lib/libos.tex delete mode 100644 Doc/lib/libpanel.tex delete mode 100644 Doc/lib/libparser.tex delete mode 100644 Doc/lib/libpdb.tex delete mode 100644 Doc/lib/libpickle.tex delete mode 100644 Doc/lib/libpipes.tex delete mode 100644 Doc/lib/libpopen2.tex delete mode 100644 Doc/lib/libpoplib.tex delete mode 100644 Doc/lib/libposix.tex delete mode 100644 Doc/lib/libposixfile.tex delete mode 100644 Doc/lib/libposixpath.tex delete mode 100644 Doc/lib/libpprint.tex delete mode 100644 Doc/lib/libprofile.tex delete mode 100644 Doc/lib/libpty.tex delete mode 100644 Doc/lib/libpwd.tex delete mode 100644 Doc/lib/libpyclbr.tex delete mode 100644 Doc/lib/libpycompile.tex delete mode 100644 Doc/lib/libpyexpat.tex delete mode 100644 Doc/lib/libpython.tex delete mode 100644 Doc/lib/libqueue.tex delete mode 100644 Doc/lib/libquopri.tex delete mode 100644 Doc/lib/librand.tex delete mode 100644 Doc/lib/librandom.tex delete mode 100644 Doc/lib/libre.tex delete mode 100644 Doc/lib/libreadline.tex delete mode 100644 Doc/lib/libregex.tex delete mode 100644 Doc/lib/libregsub.tex delete mode 100644 Doc/lib/librepr.tex delete mode 100644 Doc/lib/libresource.tex delete mode 100644 Doc/lib/librestricted.tex delete mode 100644 Doc/lib/librexec.tex delete mode 100644 Doc/lib/librfc822.tex delete mode 100644 Doc/lib/librgbimg.tex delete mode 100644 Doc/lib/librlcompleter.tex delete mode 100644 Doc/lib/librobotparser.tex delete mode 100644 Doc/lib/librotor.tex delete mode 100644 Doc/lib/libsched.tex delete mode 100644 Doc/lib/libselect.tex delete mode 100644 Doc/lib/libsgi.tex delete mode 100644 Doc/lib/libsgmllib.tex delete mode 100644 Doc/lib/libsha.tex delete mode 100644 Doc/lib/libshelve.tex delete mode 100644 Doc/lib/libshlex.tex delete mode 100644 Doc/lib/libshutil.tex delete mode 100644 Doc/lib/libsignal.tex delete mode 100644 Doc/lib/libsimplehttp.tex delete mode 100644 Doc/lib/libsite.tex delete mode 100644 Doc/lib/libsmtplib.tex delete mode 100644 Doc/lib/libsndhdr.tex delete mode 100644 Doc/lib/libsocket.tex delete mode 100644 Doc/lib/libsocksvr.tex delete mode 100644 Doc/lib/libsomeos.tex delete mode 100644 Doc/lib/libstat.tex delete mode 100644 Doc/lib/libstatcache.tex delete mode 100644 Doc/lib/libstatvfs.tex delete mode 100644 Doc/lib/libstdtypes.tex delete mode 100644 Doc/lib/libstdwin.tex delete mode 100644 Doc/lib/libstring.tex delete mode 100644 Doc/lib/libstringio.tex delete mode 100644 Doc/lib/libstrings.tex delete mode 100644 Doc/lib/libstruct.tex delete mode 100644 Doc/lib/libsun.tex delete mode 100644 Doc/lib/libsunau.tex delete mode 100644 Doc/lib/libsunaudio.tex delete mode 100644 Doc/lib/libsymbol.tex delete mode 100644 Doc/lib/libsys.tex delete mode 100644 Doc/lib/libsyslog.tex delete mode 100644 Doc/lib/libtabnanny.tex delete mode 100644 Doc/lib/libtelnetlib.tex delete mode 100644 Doc/lib/libtempfile.tex delete mode 100644 Doc/lib/libtermios.tex delete mode 100644 Doc/lib/libthread.tex delete mode 100644 Doc/lib/libthreading.tex delete mode 100644 Doc/lib/libtime.tex delete mode 100644 Doc/lib/libtoken.tex delete mode 100644 Doc/lib/libtokenize.tex delete mode 100644 Doc/lib/libtraceback.tex delete mode 100644 Doc/lib/libtty.tex delete mode 100644 Doc/lib/libturtle.tex delete mode 100644 Doc/lib/libtypes.tex delete mode 100644 Doc/lib/libundoc.tex delete mode 100644 Doc/lib/libunicodedata.tex delete mode 100644 Doc/lib/libunix.tex delete mode 100644 Doc/lib/liburllib.tex delete mode 100644 Doc/lib/liburllib2.tex delete mode 100644 Doc/lib/liburlparse.tex delete mode 100644 Doc/lib/libuser.tex delete mode 100644 Doc/lib/libuserdict.tex delete mode 100644 Doc/lib/libuu.tex delete mode 100644 Doc/lib/libwarnings.tex delete mode 100644 Doc/lib/libwave.tex delete mode 100644 Doc/lib/libweakref.tex delete mode 100644 Doc/lib/libwebbrowser.tex delete mode 100644 Doc/lib/libwhichdb.tex delete mode 100644 Doc/lib/libwhrandom.tex delete mode 100644 Doc/lib/libwinreg.tex delete mode 100644 Doc/lib/libwinsound.tex delete mode 100644 Doc/lib/libxdrlib.tex delete mode 100644 Doc/lib/libxmllib.tex delete mode 100644 Doc/lib/libxreadlines.tex delete mode 100644 Doc/lib/libzipfile.tex delete mode 100644 Doc/lib/libzlib.tex delete mode 100644 Doc/lib/markup.tex delete mode 100644 Doc/lib/netdata.tex delete mode 100644 Doc/lib/windows.tex delete mode 100644 Doc/lib/xmldom.tex delete mode 100644 Doc/lib/xmldomminidom.tex delete mode 100644 Doc/lib/xmldompulldom.tex delete mode 100644 Doc/lib/xmlsax.tex delete mode 100644 Doc/lib/xmlsaxhandler.tex delete mode 100644 Doc/lib/xmlsaxreader.tex delete mode 100644 Doc/lib/xmlsaxutils.tex delete mode 100755 Doc/libmods.tex delete mode 100755 Doc/libstd.tex delete mode 100644 Doc/mac/.cvsignore delete mode 100644 Doc/mac/libaepack.tex delete mode 100644 Doc/mac/libaetypes.tex delete mode 100644 Doc/mac/libctb.tex delete mode 100644 Doc/mac/libframework.tex delete mode 100644 Doc/mac/libmac.tex delete mode 100644 Doc/mac/libmacconsole.tex delete mode 100644 Doc/mac/libmacdnr.tex delete mode 100644 Doc/mac/libmacfs.tex delete mode 100644 Doc/mac/libmacic.tex delete mode 100644 Doc/mac/libmacos.tex delete mode 100644 Doc/mac/libmacostools.tex delete mode 100644 Doc/mac/libmacspeech.tex delete mode 100644 Doc/mac/libmactcp.tex delete mode 100644 Doc/mac/libmacui.tex delete mode 100644 Doc/mac/libminiae.tex delete mode 100644 Doc/mac/mac.tex delete mode 100644 Doc/mac/toolbox.tex delete mode 100644 Doc/mac/undoc.tex delete mode 100644 Doc/mac/using.tex delete mode 100644 Doc/paper-a4/.cvsignore delete mode 100644 Doc/paper-a4/pypaper.sty delete mode 100644 Doc/paper-letter/.cvsignore delete mode 100644 Doc/perl/SynopsisTable.pm delete mode 100644 Doc/perl/distutils.perl delete mode 100644 Doc/perl/howto.perl delete mode 100644 Doc/perl/l2hinit.perl delete mode 100644 Doc/perl/ltxmarkup.perl delete mode 100644 Doc/perl/manual.perl delete mode 100644 Doc/perl/python.perl delete mode 100644 Doc/ref/.cvsignore delete mode 100644 Doc/ref/ref.tex delete mode 100644 Doc/ref/ref1.tex delete mode 100644 Doc/ref/ref2.tex delete mode 100644 Doc/ref/ref3.tex delete mode 100644 Doc/ref/ref4.tex delete mode 100644 Doc/ref/ref5.tex delete mode 100644 Doc/ref/ref6.tex delete mode 100644 Doc/ref/ref7.tex delete mode 100644 Doc/ref/ref8.tex delete mode 100644 Doc/ref/refa1.tex delete mode 100644 Doc/ref/reswords.py delete mode 100644 Doc/templates/howto.tex delete mode 100644 Doc/templates/manual.tex delete mode 100644 Doc/templates/module.tex delete mode 100644 Doc/texinputs/boilerplate.tex delete mode 100644 Doc/texinputs/copyright.tex delete mode 100644 Doc/texinputs/distutils.sty delete mode 100644 Doc/texinputs/fncychap.sty delete mode 100644 Doc/texinputs/howto.cls delete mode 100644 Doc/texinputs/ltxmarkup.sty delete mode 100644 Doc/texinputs/manual.cls delete mode 100644 Doc/texinputs/pypaper.sty delete mode 100644 Doc/texinputs/python.ist delete mode 100644 Doc/texinputs/python.sty delete mode 100644 Doc/texinputs/reportingbugs.tex delete mode 100755 Doc/tools/anno-api.py delete mode 100755 Doc/tools/buildindex.py delete mode 100644 Doc/tools/checkargs.pm delete mode 100755 Doc/tools/cklatex delete mode 100644 Doc/tools/custlib.py delete mode 100644 Doc/tools/cvsinfo.py delete mode 100755 Doc/tools/findacks delete mode 100755 Doc/tools/findmodrefs delete mode 100755 Doc/tools/fix_hack delete mode 100755 Doc/tools/fix_libaux.sed delete mode 100644 Doc/tools/fixinfo.el delete mode 100755 Doc/tools/getpagecounts delete mode 100755 Doc/tools/html2texi.pl delete mode 100755 Doc/tools/indfix.py delete mode 100644 Doc/tools/keywords.py delete mode 100755 Doc/tools/listmodules delete mode 100755 Doc/tools/mkackshtml delete mode 100755 Doc/tools/mkhowto delete mode 100755 Doc/tools/mkinfo delete mode 100755 Doc/tools/mkmodindex delete mode 100755 Doc/tools/mksourcepkg delete mode 100755 Doc/tools/node2label.pl delete mode 100755 Doc/tools/push-docs.sh delete mode 100644 Doc/tools/refcounts.py delete mode 100644 Doc/tools/sgmlconv/Makefile delete mode 100644 Doc/tools/sgmlconv/README delete mode 100644 Doc/tools/sgmlconv/conversion.xml delete mode 100755 Doc/tools/sgmlconv/docfixer.py delete mode 100755 Doc/tools/sgmlconv/esis2sgml.py delete mode 100644 Doc/tools/sgmlconv/esistools.py delete mode 100755 Doc/tools/sgmlconv/latex2esis.py delete mode 100644 Doc/tools/sgmlconv/make.rules delete mode 100644 Doc/tools/support.py delete mode 100755 Doc/tools/toc2bkm.py delete mode 100755 Doc/tools/update-docs.sh delete mode 100755 Doc/tools/whichlibs delete mode 100644 Doc/tut/.cvsignore delete mode 100644 Doc/tut/tut.tex delete mode 100644 Doc/whatsnew/whatsnew20.tex delete mode 100644 Doc/whatsnew/whatsnew21.tex delete mode 100644 Grammar/.cvsignore delete mode 100644 Grammar/Grammar delete mode 100644 Include/Python.h delete mode 100644 Include/abstract.h delete mode 100644 Include/bitset.h delete mode 100644 Include/bufferobject.h delete mode 100644 Include/cStringIO.h delete mode 100644 Include/cellobject.h delete mode 100644 Include/ceval.h delete mode 100644 Include/classobject.h delete mode 100644 Include/cobject.h delete mode 100644 Include/codecs.h delete mode 100644 Include/compile.h delete mode 100644 Include/complexobject.h delete mode 100755 Include/config.h delete mode 100644 Include/dictobject.h delete mode 100644 Include/errcode.h delete mode 100644 Include/eval.h delete mode 100644 Include/fileobject.h delete mode 100644 Include/floatobject.h delete mode 100644 Include/frameobject.h delete mode 100644 Include/funcobject.h delete mode 100644 Include/graminit.h delete mode 100644 Include/grammar.h delete mode 100644 Include/import.h delete mode 100644 Include/intobject.h delete mode 100644 Include/intrcheck.h delete mode 100644 Include/listobject.h delete mode 100644 Include/longintrepr.h delete mode 100644 Include/longobject.h delete mode 100644 Include/marshal.h delete mode 100644 Include/metagrammar.h delete mode 100644 Include/methodobject.h delete mode 100644 Include/modsupport.h delete mode 100644 Include/moduleobject.h delete mode 100644 Include/node.h delete mode 100644 Include/object.h delete mode 100644 Include/objimpl.h delete mode 100644 Include/opcode.h delete mode 100644 Include/osdefs.h delete mode 100644 Include/parsetok.h delete mode 100644 Include/patchlevel.h delete mode 100644 Include/pgenheaders.h delete mode 100644 Include/py_curses.h delete mode 100644 Include/pydebug.h delete mode 100644 Include/pyerrors.h delete mode 100644 Include/pyfpe.h delete mode 100644 Include/pygetopt.h delete mode 100644 Include/pymem.h delete mode 100644 Include/pyport.h delete mode 100644 Include/pystate.h delete mode 100644 Include/pythonrun.h delete mode 100644 Include/pythread.h delete mode 100644 Include/rangeobject.h delete mode 100755 Include/rename1.h delete mode 100644 Include/sliceobject.h delete mode 100644 Include/stringobject.h delete mode 100644 Include/structmember.h delete mode 100644 Include/symtable.h delete mode 100644 Include/sysmodule.h delete mode 100644 Include/token.h delete mode 100644 Include/traceback.h delete mode 100644 Include/tupleobject.h delete mode 100644 Include/ucnhash.h delete mode 100644 Include/unicodeobject.h delete mode 100644 LICENSE delete mode 100644 Lib/BaseHTTPServer.py delete mode 100644 Lib/Bastion.py delete mode 100644 Lib/CGIHTTPServer.py delete mode 100644 Lib/ConfigParser.py delete mode 100644 Lib/Cookie.py delete mode 100644 Lib/MimeWriter.py delete mode 100644 Lib/Queue.py delete mode 100644 Lib/SimpleHTTPServer.py delete mode 100644 Lib/SocketServer.py delete mode 100644 Lib/StringIO.py delete mode 100644 Lib/TERMIOS.py delete mode 100644 Lib/UserDict.py delete mode 100644 Lib/UserList.py delete mode 100755 Lib/UserString.py delete mode 100644 Lib/__future__.py delete mode 100644 Lib/aifc.py delete mode 100644 Lib/anydbm.py delete mode 100644 Lib/asynchat.py delete mode 100644 Lib/asyncore.py delete mode 100644 Lib/atexit.py delete mode 100644 Lib/audiodev.py delete mode 100755 Lib/base64.py delete mode 100644 Lib/bdb.py delete mode 100644 Lib/binhex.py delete mode 100644 Lib/bisect.py delete mode 100755 Lib/builtin.py delete mode 100644 Lib/calendar.py delete mode 100755 Lib/cgi.py delete mode 100644 Lib/chunk.py delete mode 100644 Lib/cmd.py delete mode 100644 Lib/code.py delete mode 100644 Lib/codecs.py delete mode 100644 Lib/codeop.py delete mode 100644 Lib/colorsys.py delete mode 100644 Lib/commands.py delete mode 100644 Lib/compileall.py delete mode 100644 Lib/compiler/__init__.py delete mode 100644 Lib/compiler/ast.py delete mode 100644 Lib/compiler/consts.py delete mode 100644 Lib/compiler/misc.py delete mode 100644 Lib/compiler/pyassem.py delete mode 100644 Lib/compiler/pycodegen.py delete mode 100644 Lib/compiler/transformer.py delete mode 100644 Lib/compiler/visitor.py delete mode 100644 Lib/copy.py delete mode 100644 Lib/copy_reg.py delete mode 100644 Lib/curses/__init__.py delete mode 100644 Lib/curses/ascii.py delete mode 100644 Lib/curses/has_key.py delete mode 100644 Lib/curses/panel.py delete mode 100644 Lib/curses/textpad.py delete mode 100644 Lib/curses/wrapper.py delete mode 100644 Lib/dbhash.py delete mode 100644 Lib/difflib.py delete mode 100644 Lib/dircache.py delete mode 100644 Lib/dis.py delete mode 100644 Lib/distutils/README delete mode 100644 Lib/distutils/__init__.py delete mode 100644 Lib/distutils/archive_util.py delete mode 100644 Lib/distutils/bcppcompiler.py delete mode 100644 Lib/distutils/ccompiler.py delete mode 100644 Lib/distutils/cmd.py delete mode 100644 Lib/distutils/command/__init__.py delete mode 100644 Lib/distutils/command/bdist.py delete mode 100644 Lib/distutils/command/bdist_dumb.py delete mode 100644 Lib/distutils/command/bdist_rpm.py delete mode 100644 Lib/distutils/command/bdist_wininst.py delete mode 100644 Lib/distutils/command/build.py delete mode 100644 Lib/distutils/command/build_clib.py delete mode 100644 Lib/distutils/command/build_ext.py delete mode 100644 Lib/distutils/command/build_py.py delete mode 100644 Lib/distutils/command/build_scripts.py delete mode 100644 Lib/distutils/command/clean.py delete mode 100644 Lib/distutils/command/command_template delete mode 100644 Lib/distutils/command/config.py delete mode 100644 Lib/distutils/command/install.py delete mode 100644 Lib/distutils/command/install_data.py delete mode 100644 Lib/distutils/command/install_headers.py delete mode 100644 Lib/distutils/command/install_lib.py delete mode 100644 Lib/distutils/command/install_scripts.py delete mode 100644 Lib/distutils/command/sdist.py delete mode 100644 Lib/distutils/core.py delete mode 100644 Lib/distutils/cygwinccompiler.py delete mode 100644 Lib/distutils/dep_util.py delete mode 100644 Lib/distutils/dir_util.py delete mode 100644 Lib/distutils/dist.py delete mode 100644 Lib/distutils/errors.py delete mode 100644 Lib/distutils/extension.py delete mode 100644 Lib/distutils/fancy_getopt.py delete mode 100644 Lib/distutils/file_util.py delete mode 100644 Lib/distutils/filelist.py delete mode 100644 Lib/distutils/msvccompiler.py delete mode 100644 Lib/distutils/mwerkscompiler.py delete mode 100644 Lib/distutils/spawn.py delete mode 100644 Lib/distutils/sysconfig.py delete mode 100644 Lib/distutils/text_file.py delete mode 100644 Lib/distutils/unixccompiler.py delete mode 100644 Lib/distutils/util.py delete mode 100644 Lib/distutils/version.py delete mode 100644 Lib/doctest.py delete mode 100644 Lib/dospath.py delete mode 100644 Lib/dumbdbm.py delete mode 100644 Lib/encodings/__init__.py delete mode 100644 Lib/encodings/aliases.py delete mode 100644 Lib/encodings/ascii.py delete mode 100644 Lib/encodings/charmap.py delete mode 100644 Lib/encodings/cp037.py delete mode 100644 Lib/encodings/cp1006.py delete mode 100644 Lib/encodings/cp1026.py delete mode 100644 Lib/encodings/cp1250.py delete mode 100644 Lib/encodings/cp1251.py delete mode 100644 Lib/encodings/cp1252.py delete mode 100644 Lib/encodings/cp1253.py delete mode 100644 Lib/encodings/cp1254.py delete mode 100644 Lib/encodings/cp1255.py delete mode 100644 Lib/encodings/cp1256.py delete mode 100644 Lib/encodings/cp1257.py delete mode 100644 Lib/encodings/cp1258.py delete mode 100644 Lib/encodings/cp424.py delete mode 100644 Lib/encodings/cp437.py delete mode 100644 Lib/encodings/cp500.py delete mode 100644 Lib/encodings/cp737.py delete mode 100644 Lib/encodings/cp775.py delete mode 100644 Lib/encodings/cp850.py delete mode 100644 Lib/encodings/cp852.py delete mode 100644 Lib/encodings/cp855.py delete mode 100644 Lib/encodings/cp856.py delete mode 100644 Lib/encodings/cp857.py delete mode 100644 Lib/encodings/cp860.py delete mode 100644 Lib/encodings/cp861.py delete mode 100644 Lib/encodings/cp862.py delete mode 100644 Lib/encodings/cp863.py delete mode 100644 Lib/encodings/cp864.py delete mode 100644 Lib/encodings/cp865.py delete mode 100644 Lib/encodings/cp866.py delete mode 100644 Lib/encodings/cp869.py delete mode 100644 Lib/encodings/cp874.py delete mode 100644 Lib/encodings/cp875.py delete mode 100644 Lib/encodings/iso8859_1.py delete mode 100644 Lib/encodings/iso8859_10.py delete mode 100644 Lib/encodings/iso8859_13.py delete mode 100644 Lib/encodings/iso8859_14.py delete mode 100644 Lib/encodings/iso8859_15.py delete mode 100644 Lib/encodings/iso8859_2.py delete mode 100644 Lib/encodings/iso8859_3.py delete mode 100644 Lib/encodings/iso8859_4.py delete mode 100644 Lib/encodings/iso8859_5.py delete mode 100644 Lib/encodings/iso8859_6.py delete mode 100644 Lib/encodings/iso8859_7.py delete mode 100644 Lib/encodings/iso8859_8.py delete mode 100644 Lib/encodings/iso8859_9.py delete mode 100644 Lib/encodings/koi8_r.py delete mode 100644 Lib/encodings/latin_1.py delete mode 100644 Lib/encodings/mac_cyrillic.py delete mode 100644 Lib/encodings/mac_greek.py delete mode 100644 Lib/encodings/mac_iceland.py delete mode 100644 Lib/encodings/mac_latin2.py delete mode 100644 Lib/encodings/mac_roman.py delete mode 100644 Lib/encodings/mac_turkish.py delete mode 100644 Lib/encodings/mbcs.py delete mode 100644 Lib/encodings/raw_unicode_escape.py delete mode 100644 Lib/encodings/undefined.py delete mode 100644 Lib/encodings/unicode_escape.py delete mode 100644 Lib/encodings/unicode_internal.py delete mode 100644 Lib/encodings/utf_16.py delete mode 100644 Lib/encodings/utf_16_be.py delete mode 100644 Lib/encodings/utf_16_le.py delete mode 100644 Lib/encodings/utf_8.py delete mode 100644 Lib/filecmp.py delete mode 100644 Lib/fileinput.py delete mode 100644 Lib/fnmatch.py delete mode 100644 Lib/formatter.py delete mode 100644 Lib/fpformat.py delete mode 100644 Lib/ftplib.py delete mode 100644 Lib/getopt.py delete mode 100644 Lib/getpass.py delete mode 100644 Lib/gettext.py delete mode 100644 Lib/glob.py delete mode 100644 Lib/gopherlib.py delete mode 100644 Lib/gzip.py delete mode 100644 Lib/htmlentitydefs.py delete mode 100644 Lib/htmllib.py delete mode 100644 Lib/httplib.py delete mode 100644 Lib/idlelib/AutoExpand.py delete mode 100644 Lib/idlelib/AutoIndent.py delete mode 100644 Lib/idlelib/Bindings.py delete mode 100644 Lib/idlelib/CallTipWindow.py delete mode 100644 Lib/idlelib/CallTips.py delete mode 100644 Lib/idlelib/ChangeLog delete mode 100644 Lib/idlelib/ClassBrowser.py delete mode 100644 Lib/idlelib/ColorDelegator.py delete mode 100644 Lib/idlelib/ConfigParser.py delete mode 100644 Lib/idlelib/Debugger.py delete mode 100644 Lib/idlelib/Delegator.py delete mode 100644 Lib/idlelib/EditorWindow.py delete mode 100644 Lib/idlelib/ExecBinding.py delete mode 100644 Lib/idlelib/FileList.py delete mode 100644 Lib/idlelib/FormatParagraph.py delete mode 100644 Lib/idlelib/FrameViewer.py delete mode 100644 Lib/idlelib/GrepDialog.py delete mode 100644 Lib/idlelib/IOBinding.py delete mode 100644 Lib/idlelib/Icons/folder.gif delete mode 100644 Lib/idlelib/Icons/minusnode.gif delete mode 100644 Lib/idlelib/Icons/openfolder.gif delete mode 100644 Lib/idlelib/Icons/plusnode.gif delete mode 100644 Lib/idlelib/Icons/python.gif delete mode 100644 Lib/idlelib/Icons/tk.gif delete mode 100644 Lib/idlelib/IdleConf.py delete mode 100644 Lib/idlelib/IdleHistory.py delete mode 100644 Lib/idlelib/MultiScrolledLists.py delete mode 100644 Lib/idlelib/MultiStatusBar.py delete mode 100644 Lib/idlelib/NEWS.txt delete mode 100644 Lib/idlelib/ObjectBrowser.py delete mode 100644 Lib/idlelib/OldStackViewer.py delete mode 100644 Lib/idlelib/OutputWindow.py delete mode 100644 Lib/idlelib/ParenMatch.py delete mode 100644 Lib/idlelib/PathBrowser.py delete mode 100644 Lib/idlelib/Percolator.py delete mode 100644 Lib/idlelib/PyParse.py delete mode 100644 Lib/idlelib/PyShell.py delete mode 100644 Lib/idlelib/README.txt delete mode 100644 Lib/idlelib/Remote.py delete mode 100644 Lib/idlelib/ReplaceDialog.py delete mode 100644 Lib/idlelib/ScriptBinding.py delete mode 100644 Lib/idlelib/ScrolledList.py delete mode 100644 Lib/idlelib/SearchBinding.py delete mode 100644 Lib/idlelib/SearchDialog.py delete mode 100644 Lib/idlelib/SearchDialogBase.py delete mode 100644 Lib/idlelib/SearchEngine.py delete mode 100644 Lib/idlelib/Separator.py delete mode 100644 Lib/idlelib/StackViewer.py delete mode 100644 Lib/idlelib/TODO.txt delete mode 100644 Lib/idlelib/ToolTip.py delete mode 100644 Lib/idlelib/TreeWidget.py delete mode 100644 Lib/idlelib/UndoDelegator.py delete mode 100644 Lib/idlelib/WidgetRedirector.py delete mode 100644 Lib/idlelib/WindowList.py delete mode 100644 Lib/idlelib/ZoomHeight.py delete mode 100644 Lib/idlelib/__init__.py delete mode 100644 Lib/idlelib/config-unix.txt delete mode 100644 Lib/idlelib/config-win.txt delete mode 100644 Lib/idlelib/config.txt delete mode 100644 Lib/idlelib/eventparse.py delete mode 100644 Lib/idlelib/extend.txt delete mode 100644 Lib/idlelib/help.txt delete mode 100755 Lib/idlelib/idle.bat delete mode 100644 Lib/idlelib/idle.py delete mode 100644 Lib/idlelib/idle.pyw delete mode 100644 Lib/idlelib/idlever.py delete mode 100644 Lib/idlelib/keydefs.py delete mode 100644 Lib/idlelib/loader.py delete mode 100644 Lib/idlelib/protocol.py delete mode 100644 Lib/idlelib/pyclbr.py delete mode 100644 Lib/idlelib/spawn.py delete mode 100644 Lib/idlelib/tabnanny.py delete mode 100644 Lib/idlelib/testcode.py delete mode 100644 Lib/ihooks.py delete mode 100644 Lib/imaplib.py delete mode 100644 Lib/imghdr.py delete mode 100644 Lib/imputil.py delete mode 100644 Lib/inspect.py delete mode 100755 Lib/keyword.py delete mode 100644 Lib/knee.py delete mode 100644 Lib/lib-old/Para.py delete mode 100644 Lib/lib-old/addpack.py delete mode 100644 Lib/lib-old/cmp.py delete mode 100644 Lib/lib-old/cmpcache.py delete mode 100644 Lib/lib-old/codehack.py delete mode 100644 Lib/lib-old/dircmp.py delete mode 100644 Lib/lib-old/dump.py delete mode 100644 Lib/lib-old/find.py delete mode 100644 Lib/lib-old/fmt.py delete mode 100644 Lib/lib-old/grep.py delete mode 100644 Lib/lib-old/lockfile.py delete mode 100644 Lib/lib-old/newdir.py delete mode 100644 Lib/lib-old/ni.py delete mode 100644 Lib/lib-old/packmail.py delete mode 100644 Lib/lib-old/poly.py delete mode 100644 Lib/lib-old/rand.py delete mode 100644 Lib/lib-old/tb.py delete mode 100644 Lib/lib-old/util.py delete mode 100644 Lib/lib-old/whatsound.py delete mode 100644 Lib/lib-old/zmod.py delete mode 100644 Lib/lib-tk/Canvas.py delete mode 100644 Lib/lib-tk/Dialog.py delete mode 100644 Lib/lib-tk/FileDialog.py delete mode 100644 Lib/lib-tk/FixTk.py delete mode 100644 Lib/lib-tk/ScrolledText.py delete mode 100644 Lib/lib-tk/SimpleDialog.py delete mode 100755 Lib/lib-tk/Tix.py delete mode 100644 Lib/lib-tk/Tkconstants.py delete mode 100644 Lib/lib-tk/Tkdnd.py delete mode 100644 Lib/lib-tk/Tkinter.py delete mode 100644 Lib/lib-tk/tkColorChooser.py delete mode 100644 Lib/lib-tk/tkCommonDialog.py delete mode 100644 Lib/lib-tk/tkFileDialog.py delete mode 100644 Lib/lib-tk/tkFont.py delete mode 100644 Lib/lib-tk/tkMessageBox.py delete mode 100644 Lib/lib-tk/tkSimpleDialog.py delete mode 100644 Lib/lib-tk/turtle.py delete mode 100644 Lib/linecache.py delete mode 100644 Lib/locale.py delete mode 100644 Lib/macpath.py delete mode 100755 Lib/macstat.py delete mode 100644 Lib/macurl2path.py delete mode 100755 Lib/mailbox.py delete mode 100644 Lib/mailcap.py delete mode 100644 Lib/mhlib.py delete mode 100644 Lib/mimetools.py delete mode 100644 Lib/mimetypes.py delete mode 100755 Lib/mimify.py delete mode 100644 Lib/multifile.py delete mode 100644 Lib/mutex.py delete mode 100644 Lib/netrc.py delete mode 100644 Lib/nntplib.py delete mode 100644 Lib/ntpath.py delete mode 100644 Lib/nturl2path.py delete mode 100644 Lib/os.py delete mode 100644 Lib/pdb.doc delete mode 100755 Lib/pdb.py delete mode 100755 Lib/persist.py delete mode 100644 Lib/pickle.py delete mode 100644 Lib/pipes.py delete mode 100644 Lib/plat-aix3/FCNTL.py delete mode 100644 Lib/plat-aix3/IN.py delete mode 100755 Lib/plat-aix3/regen delete mode 100644 Lib/plat-aix4/FCNTL.py delete mode 100644 Lib/plat-aix4/IN.py delete mode 100755 Lib/plat-aix4/regen delete mode 100644 Lib/plat-beos5/FCNTL.py delete mode 100644 Lib/plat-beos5/IN.py delete mode 100755 Lib/plat-beos5/regen delete mode 100755 Lib/plat-freebsd2/FCNTL.py delete mode 100644 Lib/plat-freebsd2/IN.py delete mode 100755 Lib/plat-freebsd2/regen delete mode 100644 Lib/plat-freebsd3/FCNTL.py delete mode 100644 Lib/plat-freebsd3/IN.py delete mode 100755 Lib/plat-freebsd3/regen delete mode 100644 Lib/plat-freebsd4/FCNTL.py delete mode 100644 Lib/plat-freebsd4/IN.py delete mode 100644 Lib/plat-freebsd4/regen delete mode 100644 Lib/plat-freebsd5/FCNTL.py delete mode 100644 Lib/plat-freebsd5/IN.py delete mode 100644 Lib/plat-freebsd5/regen delete mode 100755 Lib/plat-generic/regen delete mode 100755 Lib/plat-irix5/AL.py delete mode 100755 Lib/plat-irix5/CD.py delete mode 100755 Lib/plat-irix5/CL.py delete mode 100755 Lib/plat-irix5/CL_old.py delete mode 100755 Lib/plat-irix5/DEVICE.py delete mode 100755 Lib/plat-irix5/ERRNO.py delete mode 100755 Lib/plat-irix5/FCNTL.py delete mode 100755 Lib/plat-irix5/FILE.py delete mode 100755 Lib/plat-irix5/FL.py delete mode 100755 Lib/plat-irix5/GET.py delete mode 100755 Lib/plat-irix5/GL.py delete mode 100755 Lib/plat-irix5/GLWS.py delete mode 100755 Lib/plat-irix5/IN.py delete mode 100755 Lib/plat-irix5/IOCTL.py delete mode 100755 Lib/plat-irix5/SV.py delete mode 100755 Lib/plat-irix5/WAIT.py delete mode 100755 Lib/plat-irix5/cddb.py delete mode 100755 Lib/plat-irix5/cdplayer.py delete mode 100755 Lib/plat-irix5/flp.doc delete mode 100755 Lib/plat-irix5/flp.py delete mode 100755 Lib/plat-irix5/jpeg.py delete mode 100755 Lib/plat-irix5/panel.py delete mode 100755 Lib/plat-irix5/panelparser.py delete mode 100755 Lib/plat-irix5/readcd.doc delete mode 100755 Lib/plat-irix5/readcd.py delete mode 100755 Lib/plat-irix5/regen delete mode 100755 Lib/plat-irix5/torgb.py delete mode 100644 Lib/plat-irix6/AL.py delete mode 100644 Lib/plat-irix6/CD.py delete mode 100644 Lib/plat-irix6/CL.py delete mode 100644 Lib/plat-irix6/DEVICE.py delete mode 100644 Lib/plat-irix6/ERRNO.py delete mode 100644 Lib/plat-irix6/FCNTL.py delete mode 100644 Lib/plat-irix6/FILE.py delete mode 100644 Lib/plat-irix6/FL.py delete mode 100644 Lib/plat-irix6/GET.py delete mode 100644 Lib/plat-irix6/GL.py delete mode 100644 Lib/plat-irix6/GLWS.py delete mode 100644 Lib/plat-irix6/IN.py delete mode 100644 Lib/plat-irix6/IOCTL.py delete mode 100644 Lib/plat-irix6/SV.py delete mode 100644 Lib/plat-irix6/WAIT.py delete mode 100644 Lib/plat-irix6/cddb.py delete mode 100644 Lib/plat-irix6/cdplayer.py delete mode 100644 Lib/plat-irix6/flp.doc delete mode 100644 Lib/plat-irix6/flp.py delete mode 100644 Lib/plat-irix6/jpeg.py delete mode 100644 Lib/plat-irix6/panel.py delete mode 100644 Lib/plat-irix6/panelparser.py delete mode 100644 Lib/plat-irix6/readcd.doc delete mode 100644 Lib/plat-irix6/readcd.py delete mode 100755 Lib/plat-irix6/regen delete mode 100644 Lib/plat-irix6/torgb.py delete mode 100755 Lib/plat-linux1/FCNTL.py delete mode 100755 Lib/plat-linux1/IN.py delete mode 100755 Lib/plat-linux1/regen delete mode 100644 Lib/plat-linux2/CDROM.py delete mode 100644 Lib/plat-linux2/FCNTL.py delete mode 100644 Lib/plat-linux2/IN.py delete mode 100755 Lib/plat-linux2/regen delete mode 100644 Lib/plat-netbsd1/FCNTL.py delete mode 100644 Lib/plat-netbsd1/IN.py delete mode 100755 Lib/plat-netbsd1/regen delete mode 100755 Lib/plat-next3/regen delete mode 100644 Lib/plat-riscos/riscosenviron.py delete mode 100644 Lib/plat-riscos/riscospath.py delete mode 100644 Lib/plat-riscos/rourl2path.py delete mode 100755 Lib/plat-sunos4/FCNTL.py delete mode 100755 Lib/plat-sunos4/IN.py delete mode 100755 Lib/plat-sunos4/SUNAUDIODEV.py delete mode 100755 Lib/plat-sunos4/WAIT.py delete mode 100755 Lib/plat-sunos4/regen delete mode 100644 Lib/plat-sunos5/CDIO.py delete mode 100755 Lib/plat-sunos5/FCNTL.py delete mode 100755 Lib/plat-sunos5/IN.py delete mode 100644 Lib/plat-sunos5/STROPTS.py delete mode 100755 Lib/plat-sunos5/SUNAUDIODEV.py delete mode 100755 Lib/plat-sunos5/regen delete mode 100644 Lib/popen2.py delete mode 100644 Lib/poplib.py delete mode 100644 Lib/posixfile.py delete mode 100644 Lib/posixpath.py delete mode 100644 Lib/pprint.py delete mode 100644 Lib/pre.py delete mode 100644 Lib/profile.doc delete mode 100755 Lib/profile.py delete mode 100644 Lib/pstats.py delete mode 100644 Lib/pty.py delete mode 100644 Lib/py_compile.py delete mode 100644 Lib/pyclbr.py delete mode 100755 Lib/pydoc.py delete mode 100755 Lib/quopri.py delete mode 100644 Lib/random.py delete mode 100644 Lib/re.py delete mode 100755 Lib/reconvert.py delete mode 100644 Lib/regex_syntax.py delete mode 100644 Lib/regsub.py delete mode 100644 Lib/repr.py delete mode 100644 Lib/rexec.py delete mode 100644 Lib/rfc822.py delete mode 100644 Lib/rlcompleter.py delete mode 100644 Lib/robotparser.py delete mode 100644 Lib/sched.py delete mode 100644 Lib/sgmllib.py delete mode 100644 Lib/shelve.py delete mode 100644 Lib/shlex.py delete mode 100644 Lib/shutil.py delete mode 100644 Lib/site-packages/README delete mode 100644 Lib/site.py delete mode 100755 Lib/smtpd.py delete mode 100755 Lib/smtplib.py delete mode 100644 Lib/sndhdr.py delete mode 100644 Lib/socket.py delete mode 100644 Lib/sre.py delete mode 100644 Lib/sre_compile.py delete mode 100644 Lib/sre_constants.py delete mode 100644 Lib/sre_parse.py delete mode 100644 Lib/stat.py delete mode 100644 Lib/statcache.py delete mode 100644 Lib/statvfs.py delete mode 100644 Lib/string.py delete mode 100644 Lib/stringold.py delete mode 100644 Lib/sunau.py delete mode 100644 Lib/sunaudio.py delete mode 100755 Lib/symbol.py delete mode 100644 Lib/symtable.py delete mode 100755 Lib/tabnanny.py delete mode 100644 Lib/telnetlib.py delete mode 100644 Lib/tempfile.py delete mode 100644 Lib/test/README delete mode 100644 Lib/test/__init__.py delete mode 100644 Lib/test/audiotest.au delete mode 100644 Lib/test/autotest.py delete mode 100644 Lib/test/greyrgb.uue delete mode 100644 Lib/test/nocaret.py delete mode 100644 Lib/test/output/test_MimeWriter delete mode 100644 Lib/test/output/test_StringIO delete mode 100644 Lib/test/output/test___all__ delete mode 100644 Lib/test/output/test___future__ delete mode 100644 Lib/test/output/test_al delete mode 100644 Lib/test/output/test_array delete mode 100644 Lib/test/output/test_atexit delete mode 100644 Lib/test/output/test_audioop delete mode 100644 Lib/test/output/test_augassign delete mode 100644 Lib/test/output/test_bastion delete mode 100644 Lib/test/output/test_binascii delete mode 100644 Lib/test/output/test_binhex delete mode 100644 Lib/test/output/test_bisect delete mode 100644 Lib/test/output/test_bsddb delete mode 100644 Lib/test/output/test_bufio delete mode 100644 Lib/test/output/test_builtin delete mode 100644 Lib/test/output/test_capi delete mode 100644 Lib/test/output/test_cd delete mode 100644 Lib/test/output/test_cfgparser delete mode 100644 Lib/test/output/test_cgi delete mode 100644 Lib/test/output/test_charmapcodec delete mode 100644 Lib/test/output/test_cl delete mode 100644 Lib/test/output/test_class delete mode 100644 Lib/test/output/test_cmath delete mode 100644 Lib/test/output/test_coercion delete mode 100644 Lib/test/output/test_compare delete mode 100644 Lib/test/output/test_compile delete mode 100644 Lib/test/output/test_complex delete mode 100644 Lib/test/output/test_contains delete mode 100644 Lib/test/output/test_cookie delete mode 100644 Lib/test/output/test_copy_reg delete mode 100644 Lib/test/output/test_cpickle delete mode 100644 Lib/test/output/test_crypt delete mode 100644 Lib/test/output/test_dbm delete mode 100644 Lib/test/output/test_difflib delete mode 100644 Lib/test/output/test_dl delete mode 100644 Lib/test/output/test_doctest delete mode 100644 Lib/test/output/test_dospath delete mode 100644 Lib/test/output/test_dumbdbm delete mode 100644 Lib/test/output/test_errno delete mode 100644 Lib/test/output/test_exceptions delete mode 100644 Lib/test/output/test_extcall delete mode 100644 Lib/test/output/test_fcntl delete mode 100644 Lib/test/output/test_file delete mode 100644 Lib/test/output/test_fnmatch delete mode 100644 Lib/test/output/test_fork1 delete mode 100644 Lib/test/output/test_format delete mode 100644 Lib/test/output/test_funcattrs delete mode 100644 Lib/test/output/test_future delete mode 100644 Lib/test/output/test_gc delete mode 100644 Lib/test/output/test_gdbm delete mode 100644 Lib/test/output/test_getopt delete mode 100644 Lib/test/output/test_gettext delete mode 100644 Lib/test/output/test_gl delete mode 100644 Lib/test/output/test_global delete mode 100644 Lib/test/output/test_grammar delete mode 100644 Lib/test/output/test_grp delete mode 100644 Lib/test/output/test_gzip delete mode 100644 Lib/test/output/test_hash delete mode 100644 Lib/test/output/test_imageop delete mode 100644 Lib/test/output/test_imgfile delete mode 100644 Lib/test/output/test_import delete mode 100644 Lib/test/output/test_inspect delete mode 100644 Lib/test/output/test_largefile delete mode 100644 Lib/test/output/test_linuxaudiodev delete mode 100644 Lib/test/output/test_long delete mode 100644 Lib/test/output/test_longexp delete mode 100644 Lib/test/output/test_mailbox delete mode 100644 Lib/test/output/test_math delete mode 100644 Lib/test/output/test_md5 delete mode 100644 Lib/test/output/test_mimetools delete mode 100644 Lib/test/output/test_minidom delete mode 100644 Lib/test/output/test_mmap delete mode 100644 Lib/test/output/test_new delete mode 100644 Lib/test/output/test_nis delete mode 100644 Lib/test/output/test_ntpath delete mode 100644 Lib/test/output/test_opcodes delete mode 100644 Lib/test/output/test_openpty delete mode 100644 Lib/test/output/test_operations delete mode 100644 Lib/test/output/test_operator delete mode 100644 Lib/test/output/test_parser delete mode 100644 Lib/test/output/test_pickle delete mode 100644 Lib/test/output/test_pkg delete mode 100644 Lib/test/output/test_poll delete mode 100644 Lib/test/output/test_popen2 delete mode 100644 Lib/test/output/test_posixpath delete mode 100644 Lib/test/output/test_pow delete mode 100644 Lib/test/output/test_pty delete mode 100644 Lib/test/output/test_pwd delete mode 100644 Lib/test/output/test_pyexpat delete mode 100644 Lib/test/output/test_re delete mode 100644 Lib/test/output/test_regex delete mode 100644 Lib/test/output/test_rfc822 delete mode 100644 Lib/test/output/test_rgbimg delete mode 100644 Lib/test/output/test_richcmp delete mode 100644 Lib/test/output/test_rotor delete mode 100644 Lib/test/output/test_sax delete mode 100644 Lib/test/output/test_scope delete mode 100644 Lib/test/output/test_select delete mode 100644 Lib/test/output/test_sha delete mode 100644 Lib/test/output/test_signal delete mode 100644 Lib/test/output/test_socket delete mode 100644 Lib/test/output/test_sre delete mode 100644 Lib/test/output/test_strftime delete mode 100644 Lib/test/output/test_string delete mode 100644 Lib/test/output/test_strop delete mode 100644 Lib/test/output/test_struct delete mode 100644 Lib/test/output/test_sunaudiodev delete mode 100644 Lib/test/output/test_sundry delete mode 100644 Lib/test/output/test_symtable delete mode 100644 Lib/test/output/test_thread delete mode 100644 Lib/test/output/test_threadedtempfile delete mode 100644 Lib/test/output/test_time delete mode 100644 Lib/test/output/test_timing delete mode 100644 Lib/test/output/test_tokenize delete mode 100644 Lib/test/output/test_traceback delete mode 100644 Lib/test/output/test_types delete mode 100644 Lib/test/output/test_ucn delete mode 100644 Lib/test/output/test_unicode delete mode 100644 Lib/test/output/test_unicodedata delete mode 100644 Lib/test/output/test_unpack delete mode 100644 Lib/test/output/test_urllib delete mode 100644 Lib/test/output/test_urlparse delete mode 100644 Lib/test/output/test_userdict delete mode 100644 Lib/test/output/test_userlist delete mode 100644 Lib/test/output/test_userstring delete mode 100644 Lib/test/output/test_wave delete mode 100644 Lib/test/output/test_weakref delete mode 100644 Lib/test/output/test_winreg delete mode 100644 Lib/test/output/test_winsound delete mode 100644 Lib/test/output/test_xmllib delete mode 100644 Lib/test/output/test_xreadline delete mode 100644 Lib/test/output/test_zipfile delete mode 100644 Lib/test/output/test_zlib delete mode 100644 Lib/test/pickletester.py delete mode 100755 Lib/test/pystone.py delete mode 100755 Lib/test/re_tests.py delete mode 100644 Lib/test/regex_tests.py delete mode 100755 Lib/test/regrtest.py delete mode 100644 Lib/test/reperf.py delete mode 100644 Lib/test/sortperf.py delete mode 100644 Lib/test/string_tests.py delete mode 100644 Lib/test/test.xml delete mode 100644 Lib/test/test.xml.out delete mode 100644 Lib/test/test_MimeWriter.py delete mode 100644 Lib/test/test_StringIO.py delete mode 100644 Lib/test/test___all__.py delete mode 100644 Lib/test/test___future__.py delete mode 100755 Lib/test/test_al.py delete mode 100755 Lib/test/test_array.py delete mode 100644 Lib/test/test_atexit.py delete mode 100644 Lib/test/test_audioop.py delete mode 100644 Lib/test/test_augassign.py delete mode 100644 Lib/test/test_b1.py delete mode 100644 Lib/test/test_b2.py delete mode 100644 Lib/test/test_bastion.py delete mode 100755 Lib/test/test_binascii.py delete mode 100755 Lib/test/test_binhex.py delete mode 100644 Lib/test/test_bisect.py delete mode 100755 Lib/test/test_bsddb.py delete mode 100644 Lib/test/test_bufio.py delete mode 100644 Lib/test/test_builtin.py delete mode 100644 Lib/test/test_capi.py delete mode 100755 Lib/test/test_cd.py delete mode 100644 Lib/test/test_cfgparser.py delete mode 100644 Lib/test/test_cgi.py delete mode 100644 Lib/test/test_charmapcodec.py delete mode 100755 Lib/test/test_cl.py delete mode 100644 Lib/test/test_class.py delete mode 100755 Lib/test/test_cmath.py delete mode 100644 Lib/test/test_coercion.py delete mode 100644 Lib/test/test_compare.py delete mode 100644 Lib/test/test_compile.py delete mode 100644 Lib/test/test_complex.py delete mode 100644 Lib/test/test_contains.py delete mode 100644 Lib/test/test_cookie.py delete mode 100644 Lib/test/test_copy_reg.py delete mode 100644 Lib/test/test_cpickle.py delete mode 100755 Lib/test/test_crypt.py delete mode 100755 Lib/test/test_dbm.py delete mode 100644 Lib/test/test_difflib.py delete mode 100755 Lib/test/test_dl.py delete mode 100644 Lib/test/test_doctest.py delete mode 100644 Lib/test/test_dospath.py delete mode 100644 Lib/test/test_dumbdbm.py delete mode 100755 Lib/test/test_errno.py delete mode 100644 Lib/test/test_exceptions.py delete mode 100644 Lib/test/test_extcall.py delete mode 100755 Lib/test/test_fcntl.py delete mode 100644 Lib/test/test_file.py delete mode 100644 Lib/test/test_fnmatch.py delete mode 100644 Lib/test/test_fork1.py delete mode 100644 Lib/test/test_format.py delete mode 100644 Lib/test/test_funcattrs.py delete mode 100644 Lib/test/test_future.py delete mode 100644 Lib/test/test_future1.py delete mode 100644 Lib/test/test_future2.py delete mode 100644 Lib/test/test_future3.py delete mode 100644 Lib/test/test_future4.py delete mode 100644 Lib/test/test_future5.py delete mode 100644 Lib/test/test_future6.py delete mode 100644 Lib/test/test_future7.py delete mode 100644 Lib/test/test_gc.py delete mode 100755 Lib/test/test_gdbm.py delete mode 100644 Lib/test/test_getopt.py delete mode 100644 Lib/test/test_gettext.py delete mode 100755 Lib/test/test_gl.py delete mode 100644 Lib/test/test_global.py delete mode 100644 Lib/test/test_grammar.py delete mode 100755 Lib/test/test_grp.py delete mode 100644 Lib/test/test_gzip.py delete mode 100644 Lib/test/test_hash.py delete mode 100755 Lib/test/test_imageop.py delete mode 100755 Lib/test/test_imgfile.py delete mode 100644 Lib/test/test_import.py delete mode 100644 Lib/test/test_inspect.py delete mode 100644 Lib/test/test_largefile.py delete mode 100644 Lib/test/test_linuxaudiodev.py delete mode 100644 Lib/test/test_long.py delete mode 100644 Lib/test/test_longexp.py delete mode 100644 Lib/test/test_mailbox.py delete mode 100644 Lib/test/test_math.py delete mode 100644 Lib/test/test_md5.py delete mode 100644 Lib/test/test_mimetools.py delete mode 100644 Lib/test/test_minidom.py delete mode 100644 Lib/test/test_mmap.py delete mode 100644 Lib/test/test_new.py delete mode 100644 Lib/test/test_nis.py delete mode 100644 Lib/test/test_ntpath.py delete mode 100644 Lib/test/test_opcodes.py delete mode 100644 Lib/test/test_openpty.py delete mode 100644 Lib/test/test_operations.py delete mode 100644 Lib/test/test_operator.py delete mode 100644 Lib/test/test_parser.py delete mode 100644 Lib/test/test_pickle.py delete mode 100644 Lib/test/test_pkg.py delete mode 100644 Lib/test/test_poll.py delete mode 100644 Lib/test/test_popen2.py delete mode 100644 Lib/test/test_posixpath.py delete mode 100644 Lib/test/test_pow.py delete mode 100644 Lib/test/test_pty.py delete mode 100644 Lib/test/test_pwd.py delete mode 100644 Lib/test/test_pyexpat.py delete mode 100644 Lib/test/test_re.py delete mode 100644 Lib/test/test_regex.py delete mode 100644 Lib/test/test_rfc822.py delete mode 100644 Lib/test/test_rgbimg.py delete mode 100644 Lib/test/test_richcmp.py delete mode 100644 Lib/test/test_rotor.py delete mode 100644 Lib/test/test_sax.py delete mode 100644 Lib/test/test_scope.py delete mode 100644 Lib/test/test_select.py delete mode 100644 Lib/test/test_sha.py delete mode 100644 Lib/test/test_signal.py delete mode 100644 Lib/test/test_socket.py delete mode 100644 Lib/test/test_sre.py delete mode 100755 Lib/test/test_strftime.py delete mode 100644 Lib/test/test_string.py delete mode 100644 Lib/test/test_strop.py delete mode 100644 Lib/test/test_struct.py delete mode 100644 Lib/test/test_sunaudiodev.py delete mode 100644 Lib/test/test_sundry.py delete mode 100644 Lib/test/test_support.py delete mode 100644 Lib/test/test_symtable.py delete mode 100644 Lib/test/test_thread.py delete mode 100644 Lib/test/test_threadedtempfile.py delete mode 100644 Lib/test/test_time.py delete mode 100644 Lib/test/test_timing.py delete mode 100644 Lib/test/test_tokenize.py delete mode 100644 Lib/test/test_traceback.py delete mode 100644 Lib/test/test_types.py delete mode 100644 Lib/test/test_ucn.py delete mode 100644 Lib/test/test_unicode.py delete mode 100644 Lib/test/test_unicodedata.py delete mode 100644 Lib/test/test_unpack.py delete mode 100644 Lib/test/test_urllib.py delete mode 100644 Lib/test/test_urlparse.py delete mode 100644 Lib/test/test_userdict.py delete mode 100644 Lib/test/test_userlist.py delete mode 100755 Lib/test/test_userstring.py delete mode 100644 Lib/test/test_wave.py delete mode 100644 Lib/test/test_weakref.py delete mode 100644 Lib/test/test_winreg.py delete mode 100644 Lib/test/test_winsound.py delete mode 100644 Lib/test/test_xmllib.py delete mode 100644 Lib/test/test_xreadline.py delete mode 100644 Lib/test/test_zipfile.py delete mode 100644 Lib/test/test_zlib.py delete mode 100644 Lib/test/testall.py delete mode 100644 Lib/test/testcodec.py delete mode 100644 Lib/test/testimg.uue delete mode 100644 Lib/test/testimgr.uue delete mode 100644 Lib/test/testrgb.uue delete mode 100644 Lib/test/tokenize_tests.py delete mode 100644 Lib/threading.py delete mode 100644 Lib/toaiff.py delete mode 100755 Lib/token.py delete mode 100644 Lib/tokenize.py delete mode 100644 Lib/traceback.py delete mode 100644 Lib/tty.py delete mode 100644 Lib/types.py delete mode 100644 Lib/tzparse.py delete mode 100644 Lib/unittest.py delete mode 100644 Lib/urllib.py delete mode 100644 Lib/urllib2.py delete mode 100644 Lib/urlparse.py delete mode 100644 Lib/user.py delete mode 100755 Lib/uu.py delete mode 100644 Lib/warnings.py delete mode 100644 Lib/wave.py delete mode 100644 Lib/weakref.py delete mode 100644 Lib/webbrowser.py delete mode 100644 Lib/whichdb.py delete mode 100644 Lib/whrandom.py delete mode 100644 Lib/xdrlib.py delete mode 100644 Lib/xml/__init__.py delete mode 100644 Lib/xml/dom/__init__.py delete mode 100644 Lib/xml/dom/domreg.py delete mode 100644 Lib/xml/dom/minidom.py delete mode 100644 Lib/xml/dom/pulldom.py delete mode 100644 Lib/xml/parsers/__init__.py delete mode 100644 Lib/xml/parsers/expat.py delete mode 100644 Lib/xml/sax/__init__.py delete mode 100644 Lib/xml/sax/_exceptions.py delete mode 100644 Lib/xml/sax/expatreader.py delete mode 100644 Lib/xml/sax/handler.py delete mode 100644 Lib/xml/sax/saxutils.py delete mode 100644 Lib/xml/sax/xmlreader.py delete mode 100644 Lib/xmllib.py delete mode 100644 Lib/zipfile.py delete mode 100644 Mac/MPW/buildall delete mode 100644 Mac/PlugIns/readme.txt delete mode 100644 Mac/Unsupported/mactcp/dnrglue.c delete mode 100644 Mac/errno_unix.h delete mode 100644 Mac/fopenRF.c delete mode 100644 Mac/mkapplet.py delete mode 100644 Mac/mwerks/mwerks_config.h delete mode 100644 Mac/mwerks/mwerks_shlib_config.h delete mode 100644 Mac/mwerksglue.c delete mode 100644 Makefile.pre.in delete mode 100644 Misc/ACKS delete mode 100644 Misc/AIX-NOTES delete mode 100644 Misc/BLURB delete mode 100644 Misc/BLURB.LUTZ delete mode 100644 Misc/BLURB.WINDOWS delete mode 100644 Misc/BeOS-NOTES delete mode 100644 Misc/HISTORY delete mode 100644 Misc/HPUX-NOTES delete mode 100644 Misc/HYPE delete mode 100644 Misc/Makefile.pre.in delete mode 100644 Misc/NEWS delete mode 100644 Misc/NEXT-NOTES delete mode 100644 Misc/PURIFY.README delete mode 100644 Misc/Porting delete mode 100644 Misc/README delete mode 100644 Misc/RFD delete mode 100644 Misc/RPM/BeOpen-Python-Setup.patch delete mode 100644 Misc/RPM/README delete mode 100644 Misc/RPM/Tkinter/setup.cfg delete mode 100644 Misc/RPM/Tkinter/setup.py delete mode 100644 Misc/RPM/beopen-python.spec delete mode 100755 Misc/RPM/make-spec.sh delete mode 100644 Misc/cheatsheet delete mode 100644 Misc/comparisons delete mode 100644 Misc/editline-fix delete mode 100755 Misc/faq2html.py delete mode 100644 Misc/find_recursionlimit.py delete mode 100755 Misc/fixfuncptrs.sh delete mode 100644 Misc/gdbinit delete mode 100644 Misc/indent.pro delete mode 100644 Misc/python-mode.el delete mode 100644 Misc/python.man delete mode 100755 Misc/renumber.py delete mode 100644 Misc/setuid-prog.c delete mode 100644 Misc/unicode.txt delete mode 100644 Misc/vgrindefs delete mode 100644 Modules/.cvsignore delete mode 100644 Modules/Setup.config.in delete mode 100644 Modules/Setup.dist delete mode 100644 Modules/_codecsmodule.c delete mode 100644 Modules/_curses_panel.c delete mode 100644 Modules/_cursesmodule.c delete mode 100644 Modules/_localemodule.c delete mode 100644 Modules/_sre.c delete mode 100644 Modules/_testcapimodule.c delete mode 100644 Modules/_tkinter.c delete mode 100644 Modules/_weakref.c delete mode 100644 Modules/almodule.c delete mode 100755 Modules/ar_beos delete mode 100644 Modules/arraymodule.c delete mode 100644 Modules/audioop.c delete mode 100644 Modules/binascii.c delete mode 100644 Modules/bsddbmodule.c delete mode 100644 Modules/cPickle.c delete mode 100644 Modules/cStringIO.c delete mode 100644 Modules/ccpython.cc delete mode 100644 Modules/cdmodule.c delete mode 100644 Modules/cgen.py delete mode 100644 Modules/cgensupport.c delete mode 100644 Modules/cgensupport.h delete mode 100644 Modules/clmodule.c delete mode 100644 Modules/cmathmodule.c delete mode 100644 Modules/config.c.in delete mode 100644 Modules/cryptmodule.c delete mode 100644 Modules/cstubs delete mode 100644 Modules/dbmmodule.c delete mode 100644 Modules/dlmodule.c delete mode 100644 Modules/errnomodule.c delete mode 100644 Modules/fcntlmodule.c delete mode 100644 Modules/flmodule.c delete mode 100644 Modules/fmmodule.c delete mode 100644 Modules/fpectlmodule.c delete mode 100644 Modules/fpetestmodule.c delete mode 100644 Modules/gcmodule.c delete mode 100644 Modules/gdbmmodule.c delete mode 100644 Modules/getbuildinfo.c delete mode 100644 Modules/getpath.c delete mode 100644 Modules/glmodule.c delete mode 100644 Modules/grpmodule.c delete mode 100644 Modules/imageop.c delete mode 100644 Modules/imgfile.c delete mode 100755 Modules/ld_so_aix delete mode 100755 Modules/ld_so_beos delete mode 100644 Modules/license.terms delete mode 100644 Modules/linuxaudiodev.c delete mode 100644 Modules/main.c delete mode 100755 Modules/makesetup delete mode 100755 Modules/makexp_aix delete mode 100644 Modules/mathmodule.c delete mode 100644 Modules/md5.h delete mode 100644 Modules/md5c.c delete mode 100644 Modules/md5module.c delete mode 100644 Modules/mmapmodule.c delete mode 100644 Modules/mpzmodule.c delete mode 100644 Modules/newmodule.c delete mode 100644 Modules/nismodule.c delete mode 100644 Modules/operator.c delete mode 100644 Modules/parsermodule.c delete mode 100644 Modules/pcre-int.h delete mode 100644 Modules/pcre.h delete mode 100644 Modules/pcremodule.c delete mode 100644 Modules/posixmodule.c delete mode 100644 Modules/puremodule.c delete mode 100644 Modules/pwdmodule.c delete mode 100644 Modules/pyexpat.c delete mode 100644 Modules/pypcre.c delete mode 100644 Modules/python.c delete mode 100644 Modules/readline.c delete mode 100644 Modules/regexmodule.c delete mode 100644 Modules/regexpr.c delete mode 100644 Modules/regexpr.h delete mode 100644 Modules/resource.c delete mode 100644 Modules/rgbimgmodule.c delete mode 100644 Modules/rotormodule.c delete mode 100644 Modules/selectmodule.c delete mode 100644 Modules/sgimodule.c delete mode 100644 Modules/shamodule.c delete mode 100644 Modules/signalmodule.c delete mode 100644 Modules/socketmodule.c delete mode 100644 Modules/sre.h delete mode 100644 Modules/sre_constants.h delete mode 100644 Modules/stropmodule.c delete mode 100644 Modules/structmodule.c delete mode 100644 Modules/sunaudiodev.c delete mode 100644 Modules/svmodule.c delete mode 100644 Modules/symtablemodule.c delete mode 100644 Modules/syslogmodule.c delete mode 100644 Modules/tclNotify.c delete mode 100644 Modules/termios.c delete mode 100644 Modules/threadmodule.c delete mode 100644 Modules/timemodule.c delete mode 100644 Modules/timing.h delete mode 100644 Modules/timingmodule.c delete mode 100644 Modules/tkappinit.c delete mode 100644 Modules/unicodedata.c delete mode 100644 Modules/unicodedata_db.h delete mode 100644 Modules/unicodename_db.h delete mode 100644 Modules/xreadlinesmodule.c delete mode 100644 Modules/xxmodule.c delete mode 100644 Modules/yuv.h delete mode 100644 Modules/yuvconvert.c delete mode 100644 Modules/zlibmodule.c delete mode 100644 Objects/.cvsignore delete mode 100644 Objects/abstract.c delete mode 100644 Objects/bufferobject.c delete mode 100644 Objects/cellobject.c delete mode 100644 Objects/classobject.c delete mode 100644 Objects/cobject.c delete mode 100644 Objects/complexobject.c delete mode 100644 Objects/dictobject.c delete mode 100644 Objects/fileobject.c delete mode 100644 Objects/floatobject.c delete mode 100644 Objects/frameobject.c delete mode 100644 Objects/funcobject.c delete mode 100644 Objects/intobject.c delete mode 100644 Objects/listobject.c delete mode 100644 Objects/longobject.c delete mode 100644 Objects/methodobject.c delete mode 100644 Objects/moduleobject.c delete mode 100644 Objects/object.c delete mode 100644 Objects/obmalloc.c delete mode 100644 Objects/rangeobject.c delete mode 100644 Objects/sliceobject.c delete mode 100644 Objects/stringobject.c delete mode 100644 Objects/tupleobject.c delete mode 100644 Objects/typeobject.c delete mode 100644 Objects/unicodectype.c delete mode 100644 Objects/unicodeobject.c delete mode 100644 Objects/unicodetype_db.h delete mode 100644 Objects/xxobject.c delete mode 100644 PC/WinMain.c delete mode 100644 PC/_winreg.c delete mode 100644 PC/config.c delete mode 100644 PC/config.h delete mode 100644 PC/dl_nt.c delete mode 100644 PC/dllbase_nt.txt delete mode 100644 PC/example_nt/.cvsignore delete mode 100644 PC/example_nt/example.c delete mode 100644 PC/example_nt/example.def delete mode 100644 PC/example_nt/example.dsp delete mode 100644 PC/example_nt/example.dsw delete mode 100644 PC/example_nt/readme.txt delete mode 100644 PC/frozen_dllmain.c delete mode 100644 PC/getpathp.c delete mode 100644 PC/import_nt.c delete mode 100755 PC/msvcrtmodule.c delete mode 100644 PC/os2vacpp/_tkinter.def delete mode 100644 PC/os2vacpp/config.c delete mode 100644 PC/os2vacpp/config.h delete mode 100644 PC/os2vacpp/getpathp.c delete mode 100644 PC/os2vacpp/makefile delete mode 100644 PC/os2vacpp/makefile.omk delete mode 100644 PC/os2vacpp/python.def delete mode 100644 PC/os2vacpp/readme.txt delete mode 100644 PC/py.ico delete mode 100644 PC/pyc.ico delete mode 100644 PC/pycon.ico delete mode 100644 PC/python.mk delete mode 100644 PC/python_exe.rc delete mode 100644 PC/python_nt.rc delete mode 100644 PC/readme.txt delete mode 100644 PC/testpy.py delete mode 100644 PC/w9xpopen.c delete mode 100644 PC/winsound.c delete mode 100644 PCbuild/.cvsignore delete mode 100644 PCbuild/BUILDno.txt delete mode 100755 PCbuild/_socket.dsp delete mode 100755 PCbuild/_sre.dsp delete mode 100644 PCbuild/_symtable.dsp delete mode 100644 PCbuild/_testcapi.dsp delete mode 100644 PCbuild/_tkinter.dsp delete mode 100644 PCbuild/bsddb.dsp delete mode 100644 PCbuild/mmap.dsp delete mode 100644 PCbuild/parser.dsp delete mode 100644 PCbuild/pcbuild.dsw delete mode 100755 PCbuild/pyexpat.dsp delete mode 100644 PCbuild/python.dsp delete mode 100644 PCbuild/python20.wse delete mode 100644 PCbuild/pythoncore.dsp delete mode 100644 PCbuild/pythonw.dsp delete mode 100644 PCbuild/readme.txt delete mode 100644 PCbuild/rmpyc.py delete mode 100755 PCbuild/rt.bat delete mode 100755 PCbuild/select.dsp delete mode 100755 PCbuild/unicodedata.dsp delete mode 100644 PCbuild/w9xpopen.dsp delete mode 100644 PCbuild/winreg.dsp delete mode 100644 PCbuild/winsound.dsp delete mode 100644 PCbuild/zlib.dsp delete mode 100644 Parser/.cvsignore delete mode 100644 Parser/acceler.c delete mode 100644 Parser/assert.h delete mode 100644 Parser/bitset.c delete mode 100644 Parser/firstsets.c delete mode 100644 Parser/grammar.c delete mode 100644 Parser/grammar1.c delete mode 100644 Parser/intrcheck.c delete mode 100644 Parser/listnode.c delete mode 100644 Parser/metagrammar.c delete mode 100644 Parser/myreadline.c delete mode 100644 Parser/node.c delete mode 100644 Parser/parser.c delete mode 100644 Parser/parser.h delete mode 100644 Parser/parsetok.c delete mode 100644 Parser/pgen.c delete mode 100644 Parser/pgen.h delete mode 100644 Parser/pgenmain.c delete mode 100644 Parser/printgrammar.c delete mode 100644 Parser/tokenizer.c delete mode 100644 Parser/tokenizer.h delete mode 100644 Python/.cvsignore delete mode 100644 Python/atof.c delete mode 100644 Python/bltinmodule.c delete mode 100644 Python/ceval.c delete mode 100644 Python/codecs.c delete mode 100644 Python/compile.c delete mode 100644 Python/dup2.c delete mode 100644 Python/dynload_aix.c delete mode 100644 Python/dynload_beos.c delete mode 100644 Python/dynload_dl.c delete mode 100644 Python/dynload_hpux.c delete mode 100644 Python/dynload_mac.c delete mode 100644 Python/dynload_next.c delete mode 100644 Python/dynload_os2.c delete mode 100644 Python/dynload_shlib.c delete mode 100644 Python/dynload_stub.c delete mode 100644 Python/dynload_win.c delete mode 100644 Python/errors.c delete mode 100644 Python/exceptions.c delete mode 100644 Python/fmod.c delete mode 100644 Python/frozen.c delete mode 100644 Python/frozenmain.c delete mode 100644 Python/future.c delete mode 100644 Python/getargs.c delete mode 100644 Python/getcompiler.c delete mode 100644 Python/getcopyright.c delete mode 100644 Python/getcwd.c delete mode 100644 Python/getmtime.c delete mode 100644 Python/getopt.c delete mode 100644 Python/getplatform.c delete mode 100644 Python/getversion.c delete mode 100644 Python/graminit.c delete mode 100644 Python/hypot.c delete mode 100644 Python/import.c delete mode 100644 Python/importdl.c delete mode 100644 Python/importdl.h delete mode 100644 Python/marshal.c delete mode 100644 Python/memmove.c delete mode 100644 Python/modsupport.c delete mode 100644 Python/mystrtoul.c delete mode 100644 Python/pyfpe.c delete mode 100644 Python/pystate.c delete mode 100644 Python/pythonmain.c delete mode 100644 Python/pythonrun.c delete mode 100644 Python/sigcheck.c delete mode 100644 Python/strdup.c delete mode 100644 Python/strerror.c delete mode 100644 Python/strtod.c delete mode 100644 Python/structmember.c delete mode 100644 Python/symtable.c delete mode 100644 Python/sysmodule.c delete mode 100644 Python/thread.c delete mode 100644 Python/thread_beos.h delete mode 100644 Python/thread_cthread.h delete mode 100644 Python/thread_foobar.h delete mode 100644 Python/thread_lwp.h delete mode 100644 Python/thread_nt.h delete mode 100644 Python/thread_os2.h delete mode 100644 Python/thread_pth.h delete mode 100644 Python/thread_pthread.h delete mode 100644 Python/thread_sgi.h delete mode 100644 Python/thread_solaris.h delete mode 100644 Python/thread_wince.h delete mode 100644 Python/traceback.c delete mode 100644 README delete mode 100644 RISCOS/Makefile delete mode 100644 RISCOS/Modules/config.c delete mode 100644 RISCOS/Modules/drawfmodule.c delete mode 100644 RISCOS/Modules/getpath_riscos.c delete mode 100644 RISCOS/Modules/riscosmodule.c delete mode 100644 RISCOS/Modules/swimodule.c delete mode 100644 RISCOS/Python/dynload_riscos.c delete mode 100644 RISCOS/Python/getcwd_riscos.c delete mode 100644 RISCOS/Python/getmtime_riscos.c delete mode 100644 RISCOS/README delete mode 100644 RISCOS/config.h delete mode 100644 RISCOS/unixstuff.c delete mode 100644 RISCOS/unixstuff.h delete mode 100644 Tools/README delete mode 100644 Tools/audiopy/README delete mode 100755 Tools/audiopy/audiopy delete mode 100644 Tools/bgen/README delete mode 100644 Tools/bgen/bgen/bgen.py delete mode 100644 Tools/bgen/bgen/bgenBuffer.py delete mode 100644 Tools/bgen/bgen/bgenGenerator.py delete mode 100644 Tools/bgen/bgen/bgenGeneratorGroup.py delete mode 100644 Tools/bgen/bgen/bgenHeapBuffer.py delete mode 100644 Tools/bgen/bgen/bgenModule.py delete mode 100644 Tools/bgen/bgen/bgenObjectDefinition.py delete mode 100644 Tools/bgen/bgen/bgenOutput.py delete mode 100644 Tools/bgen/bgen/bgenStackBuffer.py delete mode 100644 Tools/bgen/bgen/bgenStringBuffer.py delete mode 100644 Tools/bgen/bgen/bgenType.py delete mode 100644 Tools/bgen/bgen/bgenVariable.py delete mode 100644 Tools/bgen/bgen/bgenlocations.py delete mode 100644 Tools/bgen/bgen/macsupport.py delete mode 100644 Tools/bgen/bgen/scantools.py delete mode 100644 Tools/compiler/ast.txt delete mode 100644 Tools/compiler/astgen.py delete mode 100644 Tools/compiler/compile.py delete mode 100644 Tools/compiler/compiler/__init__.py delete mode 100644 Tools/compiler/compiler/ast.py delete mode 100644 Tools/compiler/compiler/ast.txt delete mode 100644 Tools/compiler/compiler/astgen.py delete mode 100644 Tools/compiler/compiler/consts.py delete mode 100644 Tools/compiler/compiler/misc.py delete mode 100644 Tools/compiler/compiler/pyassem.py delete mode 100644 Tools/compiler/compiler/pycodegen.py delete mode 100644 Tools/compiler/compiler/transformer.py delete mode 100644 Tools/compiler/compiler/visitor.py delete mode 100755 Tools/compiler/demo.py delete mode 100755 Tools/compiler/dumppyc.py delete mode 100644 Tools/compiler/regrtest.py delete mode 100644 Tools/compiler/setup.py delete mode 100644 Tools/faqwiz/README delete mode 100644 Tools/faqwiz/faqconf.py delete mode 100644 Tools/faqwiz/faqcust.py delete mode 100755 Tools/faqwiz/faqw.py delete mode 100644 Tools/faqwiz/faqwiz.py delete mode 100644 Tools/freeze/.cvsignore delete mode 100644 Tools/freeze/README delete mode 100644 Tools/freeze/bkfile.py delete mode 100644 Tools/freeze/checkextensions.py delete mode 100644 Tools/freeze/checkextensions_win32.py delete mode 100644 Tools/freeze/extensions_win32.ini delete mode 100755 Tools/freeze/freeze.py delete mode 100644 Tools/freeze/hello.py delete mode 100644 Tools/freeze/makeconfig.py delete mode 100644 Tools/freeze/makefreeze.py delete mode 100644 Tools/freeze/makemakefile.py delete mode 100644 Tools/freeze/modulefinder.py delete mode 100644 Tools/freeze/parsesetup.py delete mode 100644 Tools/freeze/win32.html delete mode 100644 Tools/freeze/winmakemakefile.py delete mode 100755 Tools/i18n/msgfmt.py delete mode 100755 Tools/i18n/pygettext.py delete mode 100644 Tools/idle/AutoExpand.py delete mode 100644 Tools/idle/AutoIndent.py delete mode 100644 Tools/idle/Bindings.py delete mode 100755 Tools/idle/BrowserControl.py delete mode 100644 Tools/idle/CallTipWindow.py delete mode 100644 Tools/idle/CallTips.py delete mode 100644 Tools/idle/ChangeLog delete mode 100644 Tools/idle/ClassBrowser.py delete mode 100644 Tools/idle/ColorDelegator.py delete mode 100644 Tools/idle/Debugger.py delete mode 100644 Tools/idle/Delegator.py delete mode 100644 Tools/idle/EditorWindow.py delete mode 100644 Tools/idle/FileList.py delete mode 100644 Tools/idle/FormatParagraph.py delete mode 100644 Tools/idle/FrameViewer.py delete mode 100644 Tools/idle/GrepDialog.py delete mode 100644 Tools/idle/IOBinding.py delete mode 100644 Tools/idle/Icons/folder.gif delete mode 100644 Tools/idle/Icons/minusnode.gif delete mode 100644 Tools/idle/Icons/openfolder.gif delete mode 100644 Tools/idle/Icons/plusnode.gif delete mode 100644 Tools/idle/Icons/python.gif delete mode 100644 Tools/idle/Icons/tk.gif delete mode 100644 Tools/idle/IdleConf.py delete mode 100644 Tools/idle/IdleHistory.py delete mode 100644 Tools/idle/MultiScrolledLists.py delete mode 100644 Tools/idle/MultiStatusBar.py delete mode 100644 Tools/idle/NEWS.txt delete mode 100644 Tools/idle/ObjectBrowser.py delete mode 100644 Tools/idle/OldStackViewer.py delete mode 100644 Tools/idle/OutputWindow.py delete mode 100644 Tools/idle/ParenMatch.py delete mode 100644 Tools/idle/PathBrowser.py delete mode 100644 Tools/idle/Percolator.py delete mode 100644 Tools/idle/PyParse.py delete mode 100644 Tools/idle/PyShell.py delete mode 100644 Tools/idle/README.txt delete mode 100644 Tools/idle/RemoteInterp.py delete mode 100644 Tools/idle/ReplaceDialog.py delete mode 100644 Tools/idle/ScriptBinding.py delete mode 100644 Tools/idle/ScrolledList.py delete mode 100644 Tools/idle/SearchBinding.py delete mode 100644 Tools/idle/SearchDialog.py delete mode 100644 Tools/idle/SearchDialogBase.py delete mode 100644 Tools/idle/SearchEngine.py delete mode 100644 Tools/idle/Separator.py delete mode 100644 Tools/idle/StackViewer.py delete mode 100644 Tools/idle/TODO.txt delete mode 100644 Tools/idle/ToolTip.py delete mode 100644 Tools/idle/TreeWidget.py delete mode 100644 Tools/idle/UndoDelegator.py delete mode 100644 Tools/idle/WidgetRedirector.py delete mode 100644 Tools/idle/WindowList.py delete mode 100644 Tools/idle/ZoomHeight.py delete mode 100644 Tools/idle/__init__.py delete mode 100644 Tools/idle/config-unix.txt delete mode 100644 Tools/idle/config-win.txt delete mode 100644 Tools/idle/config.txt delete mode 100644 Tools/idle/eventparse.py delete mode 100644 Tools/idle/extend.txt delete mode 100644 Tools/idle/help.txt delete mode 100755 Tools/idle/idle delete mode 100644 Tools/idle/idle.bat delete mode 100755 Tools/idle/idle.py delete mode 100644 Tools/idle/idle.pyw delete mode 100644 Tools/idle/idlever.py delete mode 100644 Tools/idle/keydefs.py delete mode 100644 Tools/idle/setup.py delete mode 100644 Tools/idle/testcode.py delete mode 100644 Tools/modulator/EXAMPLE.py delete mode 100644 Tools/modulator/README delete mode 100644 Tools/modulator/ScrolledListbox.py delete mode 100644 Tools/modulator/Templates/copyright delete mode 100644 Tools/modulator/Templates/module_head delete mode 100644 Tools/modulator/Templates/module_method delete mode 100644 Tools/modulator/Templates/module_tail delete mode 100644 Tools/modulator/Templates/object_head delete mode 100644 Tools/modulator/Templates/object_method delete mode 100644 Tools/modulator/Templates/object_mlist delete mode 100644 Tools/modulator/Templates/object_new delete mode 100644 Tools/modulator/Templates/object_structure delete mode 100644 Tools/modulator/Templates/object_tail delete mode 100644 Tools/modulator/Templates/object_tp_as_mapping delete mode 100644 Tools/modulator/Templates/object_tp_as_number delete mode 100644 Tools/modulator/Templates/object_tp_as_sequence delete mode 100644 Tools/modulator/Templates/object_tp_call delete mode 100644 Tools/modulator/Templates/object_tp_compare delete mode 100644 Tools/modulator/Templates/object_tp_dealloc delete mode 100644 Tools/modulator/Templates/object_tp_getattr delete mode 100644 Tools/modulator/Templates/object_tp_hash delete mode 100644 Tools/modulator/Templates/object_tp_print delete mode 100644 Tools/modulator/Templates/object_tp_repr delete mode 100644 Tools/modulator/Templates/object_tp_setattr delete mode 100644 Tools/modulator/Templates/object_tp_str delete mode 100755 Tools/modulator/Tkextra.py delete mode 100755 Tools/modulator/genmodule.py delete mode 100755 Tools/modulator/modulator.py delete mode 100644 Tools/modulator/varsubst.py delete mode 100644 Tools/pynche/ChipViewer.py delete mode 100644 Tools/pynche/ColorDB.py delete mode 100644 Tools/pynche/DetailsViewer.py delete mode 100644 Tools/pynche/ListViewer.py delete mode 100644 Tools/pynche/Main.py delete mode 100644 Tools/pynche/PyncheWidget.py delete mode 100644 Tools/pynche/README delete mode 100644 Tools/pynche/StripViewer.py delete mode 100644 Tools/pynche/Switchboard.py delete mode 100644 Tools/pynche/TextViewer.py delete mode 100644 Tools/pynche/TypeinViewer.py delete mode 100644 Tools/pynche/X/rgb.txt delete mode 100644 Tools/pynche/X/xlicense.txt delete mode 100644 Tools/pynche/__init__.py delete mode 100644 Tools/pynche/html40colors.txt delete mode 100644 Tools/pynche/namedcolors.txt delete mode 100644 Tools/pynche/pyColorChooser.py delete mode 100755 Tools/pynche/pynche delete mode 100755 Tools/pynche/pynche.pyw delete mode 100644 Tools/pynche/webcolors.txt delete mode 100644 Tools/pynche/websafe.txt delete mode 100644 Tools/scripts/README delete mode 100755 Tools/scripts/byteyears.py delete mode 100755 Tools/scripts/checkappend.py delete mode 100755 Tools/scripts/checkpyc.py delete mode 100755 Tools/scripts/classfix.py delete mode 100755 Tools/scripts/copytime.py delete mode 100755 Tools/scripts/crlf.py delete mode 100755 Tools/scripts/cvsfiles.py delete mode 100644 Tools/scripts/dutree.doc delete mode 100755 Tools/scripts/dutree.py delete mode 100755 Tools/scripts/eptags.py delete mode 100755 Tools/scripts/findlinksto.py delete mode 100755 Tools/scripts/fixcid.py delete mode 100755 Tools/scripts/fixheader.py delete mode 100755 Tools/scripts/fixnotice.py delete mode 100755 Tools/scripts/fixps.py delete mode 100755 Tools/scripts/ftpmirror.py delete mode 100644 Tools/scripts/gencodec.py delete mode 100755 Tools/scripts/h2py.py delete mode 100755 Tools/scripts/ifdef.py delete mode 100755 Tools/scripts/lfcr.py delete mode 100755 Tools/scripts/linktree.py delete mode 100755 Tools/scripts/lll.py delete mode 100755 Tools/scripts/logmerge.py delete mode 100755 Tools/scripts/mailerdaemon.py delete mode 100755 Tools/scripts/methfix.py delete mode 100755 Tools/scripts/mkreal.py delete mode 100755 Tools/scripts/ndiff.py delete mode 100755 Tools/scripts/nm2def.py delete mode 100755 Tools/scripts/objgraph.py delete mode 100755 Tools/scripts/parseentities.py delete mode 100755 Tools/scripts/pathfix.py delete mode 100755 Tools/scripts/pdeps.py delete mode 100755 Tools/scripts/pindent.py delete mode 100755 Tools/scripts/ptags.py delete mode 100755 Tools/scripts/pydoc delete mode 100755 Tools/scripts/pydoc.pyw delete mode 100644 Tools/scripts/redemo.py delete mode 100644 Tools/scripts/reindent.py delete mode 100755 Tools/scripts/rgrep.py delete mode 100755 Tools/scripts/suff.py delete mode 100755 Tools/scripts/sum5.py delete mode 100755 Tools/scripts/texi2html.py delete mode 100644 Tools/scripts/trace.py delete mode 100755 Tools/scripts/treesync.py delete mode 100755 Tools/scripts/untabify.py delete mode 100755 Tools/scripts/which.py delete mode 100755 Tools/scripts/xxci.py delete mode 100644 Tools/unicode/makeunicodedata.py delete mode 100644 Tools/versioncheck/README delete mode 100644 Tools/versioncheck/_checkversion.py delete mode 100644 Tools/versioncheck/checkversions.py delete mode 100644 Tools/versioncheck/pyversioncheck.py delete mode 100644 Tools/webchecker/README delete mode 100644 Tools/webchecker/tktools.py delete mode 100755 Tools/webchecker/wcgui.py delete mode 100644 Tools/webchecker/wcmac.py delete mode 100755 Tools/webchecker/webchecker.py delete mode 100755 Tools/webchecker/websucker.py delete mode 100755 Tools/webchecker/wsgui.py delete mode 100644 Tools/world/README delete mode 100755 Tools/world/world delete mode 100644 acconfig.h delete mode 100644 config.h.in delete mode 100755 configure delete mode 100644 configure.in delete mode 100755 install-sh delete mode 100644 setup.py diff --git a/.cvsignore b/.cvsignore deleted file mode 100644 index 04a4a99e4d..0000000000 --- a/.cvsignore +++ /dev/null @@ -1,8 +0,0 @@ -.purify -config.log -config.h -config.cache -config.status -Makefile -buildno -python diff --git a/Demo/README b/Demo/README deleted file mode 100644 index ac39f39b04..0000000000 --- a/Demo/README +++ /dev/null @@ -1,50 +0,0 @@ -This directory contains various demonstrations of what you can do with -Python. They were all written by me except where explicitly stated -otherwise -- in general, demos contributed by others ends up in the -../Contrib directory, unless I think they're of utmost general -importance (like Matt Conway's Tk demos). - -A fair number of utilities that are useful when while developing -Python code can be found in the ../Tools directory -- some of these -can also be considered good examples of how to write Python code. - -Finally, in order to save disk space and net bandwidth, not all -subdirectories listed here are distributed. They are listed just -in case I change my mind about them. - - -classes Some examples of how to use classes. - -embed An example of embedding Python in another application - (see also pysvr). - -extend An example of using the generic Makefile.pre.in from - the Misc directory to build a statically linked or - shared extension module. - -md5test Test program for the optional md5 module. - -pysvr An example of embedding Python in a threaded - application. - -rpc A set of classes for building clients and servers for - Sun RPC. - -scripts Some useful Python scripts that I put in my bin - directory. No optional built-in modules needed. - -sockets Examples for the new built-in module 'socket'. - -sgi Demos that only run on Silicon Graphics machines. - These require at least one of the optional built-in - modules that only make sense for the SGI, such as - 'gl', 'al', and 'sv'. Split in subdirectories - per subject. - -threads Demos that use the 'thread' module. (Currently these - only run on SGIs, but this may change in the future.) - -tkinter Demos using the Tk interface (including Matt Conway's - excellent set of demos). - -tix Demos using the Tix widget set addition to Tkinter. diff --git a/Demo/classes/Complex.py b/Demo/classes/Complex.py deleted file mode 100755 index bfb0d95ea9..0000000000 --- a/Demo/classes/Complex.py +++ /dev/null @@ -1,298 +0,0 @@ -# Complex numbers -# --------------- - -# [Now that Python has a complex data type built-in, this is not very -# useful, but it's still a nice example class] - -# This module represents complex numbers as instances of the class Complex. -# A Complex instance z has two data attribues, z.re (the real part) and z.im -# (the imaginary part). In fact, z.re and z.im can have any value -- all -# arithmetic operators work regardless of the type of z.re and z.im (as long -# as they support numerical operations). -# -# The following functions exist (Complex is actually a class): -# Complex([re [,im]) -> creates a complex number from a real and an imaginary part -# IsComplex(z) -> true iff z is a complex number (== has .re and .im attributes) -# ToComplex(z) -> a complex number equal to z; z itself if IsComplex(z) is true -# if z is a tuple(re, im) it will also be converted -# PolarToComplex([r [,phi [,fullcircle]]]) -> -# the complex number z for which r == z.radius() and phi == z.angle(fullcircle) -# (r and phi default to 0) -# exp(z) -> returns the complex exponential of z. Equivalent to pow(math.e,z). -# -# Complex numbers have the following methods: -# z.abs() -> absolute value of z -# z.radius() == z.abs() -# z.angle([fullcircle]) -> angle from positive X axis; fullcircle gives units -# z.phi([fullcircle]) == z.angle(fullcircle) -# -# These standard functions and unary operators accept complex arguments: -# abs(z) -# -z -# +z -# not z -# repr(z) == `z` -# str(z) -# hash(z) -> a combination of hash(z.re) and hash(z.im) such that if z.im is zero -# the result equals hash(z.re) -# Note that hex(z) and oct(z) are not defined. -# -# These conversions accept complex arguments only if their imaginary part is zero: -# int(z) -# long(z) -# float(z) -# -# The following operators accept two complex numbers, or one complex number -# and one real number (int, long or float): -# z1 + z2 -# z1 - z2 -# z1 * z2 -# z1 / z2 -# pow(z1, z2) -# cmp(z1, z2) -# Note that z1 % z2 and divmod(z1, z2) are not defined, -# nor are shift and mask operations. -# -# The standard module math does not support complex numbers. -# (I suppose it would be easy to implement a cmath module.) -# -# Idea: -# add a class Polar(r, phi) and mixed-mode arithmetic which -# chooses the most appropriate type for the result: -# Complex for +,-,cmp -# Polar for *,/,pow - - -import types, math - -twopi = math.pi*2.0 -halfpi = math.pi/2.0 - -def IsComplex(obj): - return hasattr(obj, 're') and hasattr(obj, 'im') - -def ToComplex(obj): - if IsComplex(obj): - return obj - elif type(obj) == types.TupleType: - return apply(Complex, obj) - else: - return Complex(obj) - -def PolarToComplex(r = 0, phi = 0, fullcircle = twopi): - phi = phi * (twopi / fullcircle) - return Complex(math.cos(phi)*r, math.sin(phi)*r) - -def Re(obj): - if IsComplex(obj): - return obj.re - else: - return obj - -def Im(obj): - if IsComplex(obj): - return obj.im - else: - return obj - -class Complex: - - def __init__(self, re=0, im=0): - if IsComplex(re): - im = i + Complex(0, re.im) - re = re.re - if IsComplex(im): - re = re - im.im - im = im.re - self.__dict__['re'] = re - self.__dict__['im'] = im - - def __setattr__(self, name, value): - raise TypeError, 'Complex numbers are immutable' - - def __hash__(self): - if not self.im: return hash(self.re) - mod = sys.maxint + 1L - return int((hash(self.re) + 2L*hash(self.im) + mod) % (2L*mod) - mod) - - def __repr__(self): - if not self.im: - return 'Complex(%s)' % `self.re` - else: - return 'Complex(%s, %s)' % (`self.re`, `self.im`) - - def __str__(self): - if not self.im: - return `self.re` - else: - return 'Complex(%s, %s)' % (`self.re`, `self.im`) - - def __neg__(self): - return Complex(-self.re, -self.im) - - def __pos__(self): - return self - - def __abs__(self): - # XXX could be done differently to avoid overflow! - return math.sqrt(self.re*self.re + self.im*self.im) - - def __int__(self): - if self.im: - raise ValueError, "can't convert Complex with nonzero im to int" - return int(self.re) - - def __long__(self): - if self.im: - raise ValueError, "can't convert Complex with nonzero im to long" - return long(self.re) - - def __float__(self): - if self.im: - raise ValueError, "can't convert Complex with nonzero im to float" - return float(self.re) - - def __cmp__(self, other): - other = ToComplex(other) - return cmp((self.re, self.im), (other.re, other.im)) - - def __rcmp__(self, other): - other = ToComplex(other) - return cmp(other, self) - - def __nonzero__(self): - return not (self.re == self.im == 0) - - abs = radius = __abs__ - - def angle(self, fullcircle = twopi): - return (fullcircle/twopi) * ((halfpi - math.atan2(self.re, self.im)) % twopi) - - phi = angle - - def __add__(self, other): - other = ToComplex(other) - return Complex(self.re + other.re, self.im + other.im) - - __radd__ = __add__ - - def __sub__(self, other): - other = ToComplex(other) - return Complex(self.re - other.re, self.im - other.im) - - def __rsub__(self, other): - other = ToComplex(other) - return other - self - - def __mul__(self, other): - other = ToComplex(other) - return Complex(self.re*other.re - self.im*other.im, - self.re*other.im + self.im*other.re) - - __rmul__ = __mul__ - - def __div__(self, other): - other = ToComplex(other) - d = float(other.re*other.re + other.im*other.im) - if not d: raise ZeroDivisionError, 'Complex division' - return Complex((self.re*other.re + self.im*other.im) / d, - (self.im*other.re - self.re*other.im) / d) - - def __rdiv__(self, other): - other = ToComplex(other) - return other / self - - def __pow__(self, n, z=None): - if z is not None: - raise TypeError, 'Complex does not support ternary pow()' - if IsComplex(n): - if n.im: - if self.im: raise TypeError, 'Complex to the Complex power' - else: return exp(math.log(self.re)*n) - n = n.re - r = pow(self.abs(), n) - phi = n*self.angle() - return Complex(math.cos(phi)*r, math.sin(phi)*r) - - def __rpow__(self, base): - base = ToComplex(base) - return pow(base, self) - -def exp(z): - r = math.exp(z.re) - return Complex(math.cos(z.im)*r,math.sin(z.im)*r) - - -def checkop(expr, a, b, value, fuzz = 1e-6): - import sys - print ' ', a, 'and', b, - try: - result = eval(expr) - except: - result = sys.exc_type - print '->', result - if (type(result) == type('') or type(value) == type('')): - ok = result == value - else: - ok = abs(result - value) <= fuzz - if not ok: - print '!!\t!!\t!! should be', value, 'diff', abs(result - value) - - -def test(): - testsuite = { - 'a+b': [ - (1, 10, 11), - (1, Complex(0,10), Complex(1,10)), - (Complex(0,10), 1, Complex(1,10)), - (Complex(0,10), Complex(1), Complex(1,10)), - (Complex(1), Complex(0,10), Complex(1,10)), - ], - 'a-b': [ - (1, 10, -9), - (1, Complex(0,10), Complex(1,-10)), - (Complex(0,10), 1, Complex(-1,10)), - (Complex(0,10), Complex(1), Complex(-1,10)), - (Complex(1), Complex(0,10), Complex(1,-10)), - ], - 'a*b': [ - (1, 10, 10), - (1, Complex(0,10), Complex(0, 10)), - (Complex(0,10), 1, Complex(0,10)), - (Complex(0,10), Complex(1), Complex(0,10)), - (Complex(1), Complex(0,10), Complex(0,10)), - ], - 'a/b': [ - (1., 10, 0.1), - (1, Complex(0,10), Complex(0, -0.1)), - (Complex(0, 10), 1, Complex(0, 10)), - (Complex(0, 10), Complex(1), Complex(0, 10)), - (Complex(1), Complex(0,10), Complex(0, -0.1)), - ], - 'pow(a,b)': [ - (1, 10, 1), - (1, Complex(0,10), 1), - (Complex(0,10), 1, Complex(0,10)), - (Complex(0,10), Complex(1), Complex(0,10)), - (Complex(1), Complex(0,10), 1), - (2, Complex(4,0), 16), - ], - 'cmp(a,b)': [ - (1, 10, -1), - (1, Complex(0,10), 1), - (Complex(0,10), 1, -1), - (Complex(0,10), Complex(1), -1), - (Complex(1), Complex(0,10), 1), - ], - } - exprs = testsuite.keys() - exprs.sort() - for expr in exprs: - print expr + ':' - t = (expr,) - for item in testsuite[expr]: - apply(checkop, t+item) - - -if __name__ == '__main__': - test() diff --git a/Demo/classes/Dates.py b/Demo/classes/Dates.py deleted file mode 100755 index 2c37a4e3bf..0000000000 --- a/Demo/classes/Dates.py +++ /dev/null @@ -1,218 +0,0 @@ -# Class Date supplies date objects that support date arithmetic. -# -# Date(month,day,year) returns a Date object. An instance prints as, -# e.g., 'Mon 16 Aug 1993'. -# -# Addition, subtraction, comparison operators, min, max, and sorting -# all work as expected for date objects: int+date or date+int returns -# the date `int' days from `date'; date+date raises an exception; -# date-int returns the date `int' days before `date'; date2-date1 returns -# an integer, the number of days from date1 to date2; int-date raises an -# exception; date1 < date2 is true iff date1 occurs before date2 (& -# similarly for other comparisons); min(date1,date2) is the earlier of -# the two dates and max(date1,date2) the later; and date objects can be -# used as dictionary keys. -# -# Date objects support one visible method, date.weekday(). This returns -# the day of the week the date falls on, as a string. -# -# Date objects also have 4 read-only data attributes: -# .month in 1..12 -# .day in 1..31 -# .year int or long int -# .ord the ordinal of the date relative to an arbitrary staring point -# -# The Dates module also supplies function today(), which returns the -# current date as a date object. -# -# Those entranced by calendar trivia will be disappointed, as no attempt -# has been made to accommodate the Julian (etc) system. On the other -# hand, at least this package knows that 2000 is a leap year but 2100 -# isn't, and works fine for years with a hundred decimal digits . - -# Tim Peters tim@ksr.com -# not speaking for Kendall Square Research Corp - -# Adapted to Python 1.1 (where some hacks to overcome coercion are unnecessary) -# by Guido van Rossum - -# vi:set tabsize=8: - -_MONTH_NAMES = [ 'January', 'February', 'March', 'April', 'May', - 'June', 'July', 'August', 'September', 'October', - 'November', 'December' ] - -_DAY_NAMES = [ 'Friday', 'Saturday', 'Sunday', 'Monday', - 'Tuesday', 'Wednesday', 'Thursday' ] - -_DAYS_IN_MONTH = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] - -_DAYS_BEFORE_MONTH = [] -dbm = 0 -for dim in _DAYS_IN_MONTH: - _DAYS_BEFORE_MONTH.append(dbm) - dbm = dbm + dim -del dbm, dim - -_INT_TYPES = type(1), type(1L) - -def _is_leap( year ): # 1 if leap year, else 0 - if year % 4 != 0: return 0 - if year % 400 == 0: return 1 - return year % 100 != 0 - -def _days_in_year( year ): # number of days in year - return 365 + _is_leap(year) - -def _days_before_year( year ): # number of days before year - return year*365L + (year+3)/4 - (year+99)/100 + (year+399)/400 - -def _days_in_month( month, year ): # number of days in month of year - if month == 2 and _is_leap(year): return 29 - return _DAYS_IN_MONTH[month-1] - -def _days_before_month( month, year ): # number of days in year before month - return _DAYS_BEFORE_MONTH[month-1] + (month > 2 and _is_leap(year)) - -def _date2num( date ): # compute ordinal of date.month,day,year - return _days_before_year( date.year ) + \ - _days_before_month( date.month, date.year ) + \ - date.day - -_DI400Y = _days_before_year( 400 ) # number of days in 400 years - -def _num2date( n ): # return date with ordinal n - if type(n) not in _INT_TYPES: - raise TypeError, 'argument must be integer: ' + `type(n)` - - ans = Date(1,1,1) # arguments irrelevant; just getting a Date obj - del ans.ord, ans.month, ans.day, ans.year # un-initialize it - ans.ord = n - - n400 = (n-1)/_DI400Y # # of 400-year blocks preceding - year, n = 400 * n400, n - _DI400Y * n400 - more = n / 365 - dby = _days_before_year( more ) - if dby >= n: - more = more - 1 - dby = dby - _days_in_year( more ) - year, n = year + more, int(n - dby) - - try: year = int(year) # chop to int, if it fits - except (ValueError, OverflowError): pass - - month = min( n/29 + 1, 12 ) - dbm = _days_before_month( month, year ) - if dbm >= n: - month = month - 1 - dbm = dbm - _days_in_month( month, year ) - - ans.month, ans.day, ans.year = month, n-dbm, year - return ans - -def _num2day( n ): # return weekday name of day with ordinal n - return _DAY_NAMES[ int(n % 7) ] - - -class Date: - def __init__( self, month, day, year ): - if not 1 <= month <= 12: - raise ValueError, 'month must be in 1..12: ' + `month` - dim = _days_in_month( month, year ) - if not 1 <= day <= dim: - raise ValueError, 'day must be in 1..' + `dim` + ': ' + `day` - self.month, self.day, self.year = month, day, year - self.ord = _date2num( self ) - - # don't allow setting existing attributes - def __setattr__( self, name, value ): - if self.__dict__.has_key(name): - raise AttributeError, 'read-only attribute ' + name - self.__dict__[name] = value - - def __cmp__( self, other ): - return cmp( self.ord, other.ord ) - - # define a hash function so dates can be used as dictionary keys - def __hash__( self ): - return hash( self.ord ) - - # print as, e.g., Mon 16 Aug 1993 - def __repr__( self ): - return '%.3s %2d %.3s ' % ( - self.weekday(), - self.day, - _MONTH_NAMES[self.month-1] ) + `self.year` - - # Python 1.1 coerces neither int+date nor date+int - def __add__( self, n ): - if type(n) not in _INT_TYPES: - raise TypeError, 'can\'t add ' + `type(n)` + ' to date' - return _num2date( self.ord + n ) - __radd__ = __add__ # handle int+date - - # Python 1.1 coerces neither date-int nor date-date - def __sub__( self, other ): - if type(other) in _INT_TYPES: # date-int - return _num2date( self.ord - other ) - else: - return self.ord - other.ord # date-date - - # complain about int-date - def __rsub__( self, other ): - raise TypeError, 'Can\'t subtract date from integer' - - def weekday( self ): - return _num2day( self.ord ) - -def today(): - import time - local = time.localtime(time.time()) - return Date( local[1], local[2], local[0] ) - -DateTestError = 'DateTestError' -def test( firstyear, lastyear ): - a = Date(9,30,1913) - b = Date(9,30,1914) - if `a` != 'Tue 30 Sep 1913': - raise DateTestError, '__repr__ failure' - if (not a < b) or a == b or a > b or b != b: - raise DateTestError, '__cmp__ failure' - if a+365 != b or 365+a != b: - raise DateTestError, '__add__ failure' - if b-a != 365 or b-365 != a: - raise DateTestError, '__sub__ failure' - try: - x = 1 - a - raise DateTestError, 'int-date should have failed' - except TypeError: - pass - try: - x = a + b - raise DateTestError, 'date+date should have failed' - except TypeError: - pass - if a.weekday() != 'Tuesday': - raise DateTestError, 'weekday() failure' - if max(a,b) is not b or min(a,b) is not a: - raise DateTestError, 'min/max failure' - d = {a-1:b, b:a+1} - if d[b-366] != b or d[a+(b-a)] != Date(10,1,1913): - raise DateTestError, 'dictionary failure' - - # verify date<->number conversions for first and last days for - # all years in firstyear .. lastyear - - lord = _days_before_year( firstyear ) - y = firstyear - while y <= lastyear: - ford = lord + 1 - lord = ford + _days_in_year(y) - 1 - fd, ld = Date(1,1,y), Date(12,31,y) - if (fd.ord,ld.ord) != (ford,lord): - raise DateTestError, ('date->num failed', y) - fd, ld = _num2date(ford), _num2date(lord) - if (1,1,y,12,31,y) != \ - (fd.month,fd.day,fd.year,ld.month,ld.day,ld.year): - raise DateTestError, ('num->date failed', y) - y = y + 1 diff --git a/Demo/classes/Dbm.py b/Demo/classes/Dbm.py deleted file mode 100755 index 8d7fe0f8f4..0000000000 --- a/Demo/classes/Dbm.py +++ /dev/null @@ -1,66 +0,0 @@ -# A wrapper around the (optional) built-in class dbm, supporting keys -# and values of almost any type instead of just string. -# (Actually, this works only for keys and values that can be read back -# correctly after being converted to a string.) - - -class Dbm: - - def __init__(self, filename, mode, perm): - import dbm - self.db = dbm.open(filename, mode, perm) - - def __repr__(self): - s = '' - for key in self.keys(): - t = `key` + ': ' + `self[key]` - if s: t = ', ' + t - s = s + t - return '{' + s + '}' - - def __len__(self): - return len(self.db) - - def __getitem__(self, key): - return eval(self.db[`key`]) - - def __setitem__(self, key, value): - self.db[`key`] = `value` - - def __delitem__(self, key): - del self.db[`key`] - - def keys(self): - res = [] - for key in self.db.keys(): - res.append(eval(key)) - return res - - def has_key(self, key): - return self.db.has_key(`key`) - - -def test(): - d = Dbm('@dbm', 'rw', 0600) - print d - while 1: - try: - key = input('key: ') - if d.has_key(key): - value = d[key] - print 'currently:', value - value = input('value: ') - if value == None: - del d[key] - else: - d[key] = value - except KeyboardInterrupt: - print '' - print d - except EOFError: - print '[eof]' - break - print d - - -test() diff --git a/Demo/classes/README b/Demo/classes/README deleted file mode 100644 index cca7524891..0000000000 --- a/Demo/classes/README +++ /dev/null @@ -1,14 +0,0 @@ -Examples of classes that implement special operators (see reference manual): - -Complex.py Complex numbers -Dates.py Date manipulation package by Tim Peters -Dbm.py Wrapper around built-in dbm, supporting arbitrary values -Range.py Example of a generator: re-implement built-in range() -Rat.py Rational numbers -Rev.py Yield the reverse of a sequence -Vec.py A simple vector class -bitvec.py A bit-vector class by Jan-Hein B\"uhrman - -(For straightforward examples of basic class features, such as use of -methods and inheritance, see the library code -- especially the window -modules are full of them.) diff --git a/Demo/classes/Range.py b/Demo/classes/Range.py deleted file mode 100755 index 18f626f458..0000000000 --- a/Demo/classes/Range.py +++ /dev/null @@ -1,71 +0,0 @@ -# Example of a generator: re-implement the built-in range function -# without actually constructing the list of values. (It turns out -# that the built-in function is about 20 times faster -- that's why -# it's built-in. :-) - - -# Wrapper function to emulate the complicated range() arguments - -def range(*a): - if len(a) == 1: - start, stop, step = 0, a[0], 1 - elif len(a) == 2: - start, stop = a - step = 1 - elif len(a) == 3: - start, stop, step = a - else: - raise TypeError, 'range() needs 1-3 arguments' - return Range(start, stop, step) - - -# Class implementing a range object. -# To the user the instances feel like immutable sequences -# (and you can't concatenate or slice them) - -class Range: - - # initialization -- should be called only by range() above - def __init__(self, start, stop, step): - if step == 0: - raise ValueError, 'range() called with zero step' - self.start = start - self.stop = stop - self.step = step - self.len = max(0, int((self.stop - self.start) / self.step)) - - # implement `x` and is also used by print x - def __repr__(self): - return 'range' + `self.start, self.stop, self.step` - - # implement len(x) - def __len__(self): - return self.len - - # implement x[i] - def __getitem__(self, i): - if 0 <= i < self.len: - return self.start + self.step * i - else: - raise IndexError, 'range[i] index out of range' - - -# Small test program - -def test(): - import time, __builtin__ - print range(10), range(-10, 10), range(0, 10, 2) - for i in range(100, -100, -10): print i, - print - t1 = time.time() - for i in range(1000): - pass - t2 = time.time() - for i in __builtin__.range(1000): - pass - t3 = time.time() - print t2-t1, 'sec (class)' - print t3-t2, 'sec (built-in)' - - -test() diff --git a/Demo/classes/Rat.py b/Demo/classes/Rat.py deleted file mode 100755 index 4fc4a1786f..0000000000 --- a/Demo/classes/Rat.py +++ /dev/null @@ -1,307 +0,0 @@ -'''\ -This module implements rational numbers. - -The entry point of this module is the function - rat(numerator, denominator) -If either numerator or denominator is of an integral or rational type, -the result is a rational number, else, the result is the simplest of -the types float and complex which can hold numerator/denominator. -If denominator is omitted, it defaults to 1. -Rational numbers can be used in calculations with any other numeric -type. The result of the calculation will be rational if possible. - -There is also a test function with calling sequence - test() -The documentation string of the test function contains the expected -output. -''' - -# Contributed by Sjoerd Mullender - -from types import * - -def gcd(a, b): - '''Calculate the Greatest Common Divisor.''' - while b: - a, b = b, a%b - return a - -def rat(num, den = 1): - # must check complex before float - if type(num) is ComplexType or type(den) is ComplexType: - # numerator or denominator is complex: return a complex - return complex(num) / complex(den) - if type(num) is FloatType or type(den) is FloatType: - # numerator or denominator is float: return a float - return float(num) / float(den) - # otherwise return a rational - return Rat(num, den) - -class Rat: - '''This class implements rational numbers.''' - - def __init__(self, num, den = 1): - if den == 0: - raise ZeroDivisionError, 'rat(x, 0)' - - # normalize - - # must check complex before float - if type(num) is ComplexType or type(den) is ComplexType: - # numerator or denominator is complex: - # normalized form has denominator == 1+0j - self.__num = complex(num) / complex(den) - self.__den = complex(1) - return - if type(num) is FloatType or type(den) is FloatType: - # numerator or denominator is float: - # normalized form has denominator == 1.0 - self.__num = float(num) / float(den) - self.__den = 1.0 - return - if (type(num) is InstanceType and - num.__class__ is self.__class__) or \ - (type(den) is InstanceType and - den.__class__ is self.__class__): - # numerator or denominator is rational - new = num / den - if type(new) is not InstanceType or \ - new.__class__ is not self.__class__: - self.__num = new - if type(new) is ComplexType: - self.__den = complex(1) - else: - self.__den = 1.0 - else: - self.__num = new.__num - self.__den = new.__den - else: - # make sure numerator and denominator don't - # have common factors - # this also makes sure that denominator > 0 - g = gcd(num, den) - self.__num = num / g - self.__den = den / g - # try making numerator and denominator of IntType if they fit - try: - numi = int(self.__num) - deni = int(self.__den) - except (OverflowError, TypeError): - pass - else: - if self.__num == numi and self.__den == deni: - self.__num = numi - self.__den = deni - - def __repr__(self): - return 'Rat(%s,%s)' % (self.__num, self.__den) - - def __str__(self): - if self.__den == 1: - return str(self.__num) - else: - return '(%s/%s)' % (str(self.__num), str(self.__den)) - - # a + b - def __add__(a, b): - try: - return rat(a.__num * b.__den + b.__num * a.__den, - a.__den * b.__den) - except OverflowError: - return rat(long(a.__num) * long(b.__den) + - long(b.__num) * long(a.__den), - long(a.__den) * long(b.__den)) - - def __radd__(b, a): - return Rat(a) + b - - # a - b - def __sub__(a, b): - try: - return rat(a.__num * b.__den - b.__num * a.__den, - a.__den * b.__den) - except OverflowError: - return rat(long(a.__num) * long(b.__den) - - long(b.__num) * long(a.__den), - long(a.__den) * long(b.__den)) - - def __rsub__(b, a): - return Rat(a) - b - - # a * b - def __mul__(a, b): - try: - return rat(a.__num * b.__num, a.__den * b.__den) - except OverflowError: - return rat(long(a.__num) * long(b.__num), - long(a.__den) * long(b.__den)) - - def __rmul__(b, a): - return Rat(a) * b - - # a / b - def __div__(a, b): - try: - return rat(a.__num * b.__den, a.__den * b.__num) - except OverflowError: - return rat(long(a.__num) * long(b.__den), - long(a.__den) * long(b.__num)) - - def __rdiv__(b, a): - return Rat(a) / b - - # a % b - def __mod__(a, b): - div = a / b - try: - div = int(div) - except OverflowError: - div = long(div) - return a - b * div - - def __rmod__(b, a): - return Rat(a) % b - - # a ** b - def __pow__(a, b): - if b.__den != 1: - if type(a.__num) is ComplexType: - a = complex(a) - else: - a = float(a) - if type(b.__num) is ComplexType: - b = complex(b) - else: - b = float(b) - return a ** b - try: - return rat(a.__num ** b.__num, a.__den ** b.__num) - except OverflowError: - return rat(long(a.__num) ** b.__num, - long(a.__den) ** b.__num) - - def __rpow__(b, a): - return Rat(a) ** b - - # -a - def __neg__(a): - try: - return rat(-a.__num, a.__den) - except OverflowError: - # a.__num == sys.maxint - return rat(-long(a.__num), a.__den) - - # abs(a) - def __abs__(a): - return rat(abs(a.__num), a.__den) - - # int(a) - def __int__(a): - return int(a.__num / a.__den) - - # long(a) - def __long__(a): - return long(a.__num) / long(a.__den) - - # float(a) - def __float__(a): - return float(a.__num) / float(a.__den) - - # complex(a) - def __complex__(a): - return complex(a.__num) / complex(a.__den) - - # cmp(a,b) - def __cmp__(a, b): - diff = Rat(a - b) - if diff.__num < 0: - return -1 - elif diff.__num > 0: - return 1 - else: - return 0 - - def __rcmp__(b, a): - return cmp(Rat(a), b) - - # a != 0 - def __nonzero__(a): - return a.__num != 0 - - # coercion - def __coerce__(a, b): - return a, Rat(b) - -def test(): - '''\ - Test function for rat module. - - The expected output is (module some differences in floating - precission): - -1 - -1 - 0 0L 0.1 (0.1+0j) - [Rat(1,2), Rat(-3,10), Rat(1,25), Rat(1,4)] - [Rat(-3,10), Rat(1,25), Rat(1,4), Rat(1,2)] - 0 - (11/10) - (11/10) - 1.1 - OK - 2 1.5 (3/2) (1.5+1.5j) (15707963/5000000) - 2 2 2.0 (2+0j) - - 4 0 4 1 4 0 - 3.5 0.5 3.0 1.33333333333 2.82842712475 1 - (7/2) (1/2) 3 (4/3) 2.82842712475 1 - (3.5+1.5j) (0.5-1.5j) (3+3j) (0.666666666667-0.666666666667j) (1.43248815986+2.43884761145j) 1 - 1.5 1 1.5 (1.5+0j) - - 3.5 -0.5 3.0 0.75 2.25 -1 - 3.0 0.0 2.25 1.0 1.83711730709 0 - 3.0 0.0 2.25 1.0 1.83711730709 1 - (3+1.5j) -1.5j (2.25+2.25j) (0.5-0.5j) (1.50768393746+1.04970907623j) -1 - (3/2) 1 1.5 (1.5+0j) - - (7/2) (-1/2) 3 (3/4) (9/4) -1 - 3.0 0.0 2.25 1.0 1.83711730709 -1 - 3 0 (9/4) 1 1.83711730709 0 - (3+1.5j) -1.5j (2.25+2.25j) (0.5-0.5j) (1.50768393746+1.04970907623j) -1 - (1.5+1.5j) (1.5+1.5j) - - (3.5+1.5j) (-0.5+1.5j) (3+3j) (0.75+0.75j) 4.5j -1 - (3+1.5j) 1.5j (2.25+2.25j) (1+1j) (1.18235814075+2.85446505899j) 1 - (3+1.5j) 1.5j (2.25+2.25j) (1+1j) (1.18235814075+2.85446505899j) 1 - (3+3j) 0j 4.5j (1+0j) (-0.638110484918+0.705394566962j) 0 - ''' - print rat(-1L, 1) - print rat(1, -1) - a = rat(1, 10) - print int(a), long(a), float(a), complex(a) - b = rat(2, 5) - l = [a+b, a-b, a*b, a/b] - print l - l.sort() - print l - print rat(0, 1) - print a+1 - print a+1L - print a+1.0 - try: - print rat(1, 0) - raise SystemError, 'should have been ZeroDivisionError' - except ZeroDivisionError: - print 'OK' - print rat(2), rat(1.5), rat(3, 2), rat(1.5+1.5j), rat(31415926,10000000) - list = [2, 1.5, rat(3,2), 1.5+1.5j] - for i in list: - print i, - if type(i) is not ComplexType: - print int(i), float(i), - print complex(i) - print - for j in list: - print i + j, i - j, i * j, i / j, i ** j, cmp(i, j) - -if __name__ == '__main__': - test() diff --git a/Demo/classes/Rev.py b/Demo/classes/Rev.py deleted file mode 100755 index c1874c65c5..0000000000 --- a/Demo/classes/Rev.py +++ /dev/null @@ -1,89 +0,0 @@ -# A class which presents the reverse of a sequence without duplicating it. -# From: "Steven D. Majewski" - -# It works on mutable or inmutable sequences. -# -# >>> for c in Rev( 'Hello World!' ) : sys.stdout.write( c ) -# ... else: sys.stdout.write( '\n' ) -# ... -# !dlroW olleH -# -# The .forw is so you can use anonymous sequences in __init__, and still -# keep a reference the forward sequence. ) -# If you give it a non-anonymous mutable sequence, the reverse sequence -# will track the updated values. ( but not reassignment! - another -# good reason to use anonymous values in creating the sequence to avoid -# confusion. Maybe it should be change to copy input sequence to break -# the connection completely ? ) -# -# >>> nnn = range( 0, 3 ) -# >>> rnn = Rev( nnn ) -# >>> for n in rnn: print n -# ... -# 2 -# 1 -# 0 -# >>> for n in range( 4, 6 ): nnn.append( n ) # update nnn -# ... -# >>> for n in rnn: print n # prints reversed updated values -# ... -# 5 -# 4 -# 2 -# 1 -# 0 -# >>> nnn = nnn[1:-1] -# >>> nnn -# [1, 2, 4] -# >>> for n in rnn: print n # prints reversed values of old nnn -# ... -# 5 -# 4 -# 2 -# 1 -# 0 -# >>> -# -# WH = Rev( 'Hello World!' ) -# print WH.forw, WH.back -# nnn = Rev( range( 1, 10 ) ) -# print nnn.forw -# print nnn -# -# produces output: -# -# Hello World! !dlroW olleH -# [1, 2, 3, 4, 5, 6, 7, 8, 9] -# [9, 8, 7, 6, 5, 4, 3, 2, 1] -# -# >>>rrr = Rev( nnn ) -# >>>rrr -# <1, 2, 3, 4, 5, 6, 7, 8, 9> - -from string import joinfields -class Rev: - def __init__( self, seq ): - self.forw = seq - self.back = self - def __len__( self ): - return len( self.forw ) - def __getitem__( self, j ): - return self.forw[ -( j + 1 ) ] - def __repr__( self ): - seq = self.forw - if type(seq) == type( [] ) : - wrap = '[]' - sep = ', ' - elif type(seq) == type( () ) : - wrap = '()' - sep = ', ' - elif type(seq) == type( '' ) : - wrap = '' - sep = '' - else: - wrap = '<>' - sep = ', ' - outstrs = [] - for item in self.back : - outstrs.append( str( item ) ) - return wrap[:1] + joinfields( outstrs, sep ) + wrap[-1:] diff --git a/Demo/classes/Vec.py b/Demo/classes/Vec.py deleted file mode 100755 index 8289bc847e..0000000000 --- a/Demo/classes/Vec.py +++ /dev/null @@ -1,64 +0,0 @@ -# A simple vector class - - -def vec(*v): - return apply(Vec, v) - - -class Vec: - - def __init__(self, *v): - self.v = [] - for x in v: - self.v.append(x) - - - def fromlist(self, v): - self.v = [] - if type(v) <> type([]): - raise TypeError - self.v = v[:] - return self - - - def __repr__(self): - return 'vec(' + `self.v`[1:-1] + ')' - - def __len__(self): - return len(self.v) - - def __getitem__(self, i): - return self.v[i] - - def __add__(a, b): - # Element-wise addition - v = [] - for i in range(len(a)): - v.append(a[i] + b[i]) - return Vec().fromlist(v) - - def __sub__(a, b): - # Element-wise subtraction - v = [] - for i in range(len(a)): - v.append(a[i] - b[i]) - return Vec().fromlist(v) - - def __mul__(self, scalar): - # Multiply by scalar - v = [] - for i in range(len(self.v)): - v.append(self.v[i]*scalar) - return Vec().fromlist(v) - - - -def test(): - a = vec(1, 2, 3) - b = vec(3, 2, 1) - print a - print b - print a+b - print a*3.0 - -test() diff --git a/Demo/classes/bitvec.py b/Demo/classes/bitvec.py deleted file mode 100755 index b3469975a5..0000000000 --- a/Demo/classes/bitvec.py +++ /dev/null @@ -1,332 +0,0 @@ -# -# this is a rather strict implementation of a bit vector class -# it is accessed the same way as an array of python-ints, except -# the value must be 0 or 1 -# - -import sys; rprt = sys.stderr.write #for debugging - -error = 'bitvec.error' - - -def _check_value(value): - if type(value) != type(0) or not 0 <= value < 2: - raise error, 'bitvec() items must have int value 0 or 1' - - -import math - -def _compute_len(param): - mant, l = math.frexp(float(param)) - bitmask = 1L << l - if bitmask <= param: - raise 'FATAL', '(param, l) = ' + `param, l` - while l: - bitmask = bitmask >> 1 - if param & bitmask: - break - l = l - 1 - return l - - -def _check_key(len, key): - if type(key) != type(0): - raise TypeError, 'sequence subscript not int' - if key < 0: - key = key + len - if not 0 <= key < len: - raise IndexError, 'list index out of range' - return key - -def _check_slice(len, i, j): - #the type is ok, Python already checked that - i, j = max(i, 0), min(len, j) - if i > j: - i = j - return i, j - - -class BitVec: - - def __init__(self, *params): - self._data = 0L - self._len = 0 - if not len(params): - pass - elif len(params) == 1: - param, = params - if type(param) == type([]): - value = 0L - bit_mask = 1L - for item in param: - # strict check - #_check_value(item) - if item: - value = value | bit_mask - bit_mask = bit_mask << 1 - self._data = value - self._len = len(param) - elif type(param) == type(0L): - if param < 0: - raise error, 'bitvec() can\'t handle negative longs' - self._data = param - self._len = _compute_len(param) - else: - raise error, 'bitvec() requires array or long parameter' - elif len(params) == 2: - param, length = params - if type(param) == type(0L): - if param < 0: - raise error, \ - 'can\'t handle negative longs' - self._data = param - if type(length) != type(0): - raise error, 'bitvec()\'s 2nd parameter must be int' - computed_length = _compute_len(param) - if computed_length > length: - print 'warning: bitvec() value is longer than the length indicates, truncating value' - self._data = self._data & \ - ((1L << length) - 1) - self._len = length - else: - raise error, 'bitvec() requires array or long parameter' - else: - raise error, 'bitvec() requires 0 -- 2 parameter(s)' - - - def append(self, item): - #_check_value(item) - #self[self._len:self._len] = [item] - self[self._len:self._len] = \ - BitVec(long(not not item), 1) - - - def count(self, value): - #_check_value(value) - if value: - data = self._data - else: - data = (~self)._data - count = 0 - while data: - data, count = data >> 1, count + (data & 1 != 0) - return count - - - def index(self, value): - #_check_value(value): - if value: - data = self._data - else: - data = (~self)._data - index = 0 - if not data: - raise ValueError, 'list.index(x): x not in list' - while not (data & 1): - data, index = data >> 1, index + 1 - return index - - - def insert(self, index, item): - #_check_value(item) - #self[index:index] = [item] - self[index:index] = BitVec(long(not not item), 1) - - - def remove(self, value): - del self[self.index(value)] - - - def reverse(self): - #ouch, this one is expensive! - #for i in self._len>>1: self[i], self[l-i] = self[l-i], self[i] - data, result = self._data, 0L - for i in range(self._len): - if not data: - result = result << (self._len - i) - break - result, data = (result << 1) | (data & 1), data >> 1 - self._data = result - - - def sort(self): - c = self.count(1) - self._data = ((1L << c) - 1) << (self._len - c) - - - def copy(self): - return BitVec(self._data, self._len) - - - def seq(self): - result = [] - for i in self: - result.append(i) - return result - - - def __repr__(self): - ##rprt('.' + '__repr__()\n') - return 'bitvec' + `self._data, self._len` - - def __cmp__(self, other, *rest): - #rprt(`self`+'.__cmp__'+`(other, ) + rest`+'\n') - if type(other) != type(self): - other = apply(bitvec, (other, ) + rest) - #expensive solution... recursive binary, with slicing - length = self._len - if length == 0 or other._len == 0: - return cmp(length, other._len) - if length != other._len: - min_length = min(length, other._len) - return cmp(self[:min_length], other[:min_length]) or \ - cmp(self[min_length:], other[min_length:]) - #the lengths are the same now... - if self._data == other._data: - return 0 - if length == 1: - return cmp(self[0], other[0]) - else: - length = length >> 1 - return cmp(self[:length], other[:length]) or \ - cmp(self[length:], other[length:]) - - - def __len__(self): - #rprt(`self`+'.__len__()\n') - return self._len - - def __getitem__(self, key): - #rprt(`self`+'.__getitem__('+`key`+')\n') - key = _check_key(self._len, key) - return self._data & (1L << key) != 0 - - def __setitem__(self, key, value): - #rprt(`self`+'.__setitem__'+`key, value`+'\n') - key = _check_key(self._len, key) - #_check_value(value) - if value: - self._data = self._data | (1L << key) - else: - self._data = self._data & ~(1L << key) - - def __delitem__(self, key): - #rprt(`self`+'.__delitem__('+`key`+')\n') - key = _check_key(self._len, key) - #el cheapo solution... - self._data = self[:key]._data | self[key+1:]._data >> key - self._len = self._len - 1 - - def __getslice__(self, i, j): - #rprt(`self`+'.__getslice__'+`i, j`+'\n') - i, j = _check_slice(self._len, i, j) - if i >= j: - return BitVec(0L, 0) - if i: - ndata = self._data >> i - else: - ndata = self._data - nlength = j - i - if j != self._len: - #we'll have to invent faster variants here - #e.g. mod_2exp - ndata = ndata & ((1L << nlength) - 1) - return BitVec(ndata, nlength) - - def __setslice__(self, i, j, sequence, *rest): - #rprt(`self`+'.__setslice__'+`(i, j, sequence) + rest`+'\n') - i, j = _check_slice(self._len, i, j) - if type(sequence) != type(self): - sequence = apply(bitvec, (sequence, ) + rest) - #sequence is now of our own type - ls_part = self[:i] - ms_part = self[j:] - self._data = ls_part._data | \ - ((sequence._data | \ - (ms_part._data << sequence._len)) << ls_part._len) - self._len = self._len - j + i + sequence._len - - def __delslice__(self, i, j): - #rprt(`self`+'.__delslice__'+`i, j`+'\n') - i, j = _check_slice(self._len, i, j) - if i == 0 and j == self._len: - self._data, self._len = 0L, 0 - elif i < j: - self._data = self[:i]._data | (self[j:]._data >> i) - self._len = self._len - j + i - - def __add__(self, other): - #rprt(`self`+'.__add__('+`other`+')\n') - retval = self.copy() - retval[self._len:self._len] = other - return retval - - def __mul__(self, multiplier): - #rprt(`self`+'.__mul__('+`multiplier`+')\n') - if type(multiplier) != type(0): - raise TypeError, 'sequence subscript not int' - if multiplier <= 0: - return BitVec(0L, 0) - elif multiplier == 1: - return self.copy() - #handle special cases all 0 or all 1... - if self._data == 0L: - return BitVec(0L, self._len * multiplier) - elif (~self)._data == 0L: - return ~BitVec(0L, self._len * multiplier) - #otherwise el cheapo again... - retval = BitVec(0L, 0) - while multiplier: - retval, multiplier = retval + self, multiplier - 1 - return retval - - def __and__(self, otherseq, *rest): - #rprt(`self`+'.__and__'+`(otherseq, ) + rest`+'\n') - if type(otherseq) != type(self): - otherseq = apply(bitvec, (otherseq, ) + rest) - #sequence is now of our own type - return BitVec(self._data & otherseq._data, \ - min(self._len, otherseq._len)) - - - def __xor__(self, otherseq, *rest): - #rprt(`self`+'.__xor__'+`(otherseq, ) + rest`+'\n') - if type(otherseq) != type(self): - otherseq = apply(bitvec, (otherseq, ) + rest) - #sequence is now of our own type - return BitVec(self._data ^ otherseq._data, \ - max(self._len, otherseq._len)) - - - def __or__(self, otherseq, *rest): - #rprt(`self`+'.__or__'+`(otherseq, ) + rest`+'\n') - if type(otherseq) != type(self): - otherseq = apply(bitvec, (otherseq, ) + rest) - #sequence is now of our own type - return BitVec(self._data | otherseq._data, \ - max(self._len, otherseq._len)) - - - def __invert__(self): - #rprt(`self`+'.__invert__()\n') - return BitVec(~self._data & ((1L << self._len) - 1), \ - self._len) - - def __coerce__(self, otherseq, *rest): - #needed for *some* of the arithmetic operations - #rprt(`self`+'.__coerce__'+`(otherseq, ) + rest`+'\n') - if type(otherseq) != type(self): - otherseq = apply(bitvec, (otherseq, ) + rest) - return self, otherseq - - def __int__(self): - return int(self._data) - - def __long__(self): - return long(self._data) - - def __float__(self): - return float(self._data) - - -bitvec = BitVec diff --git a/Demo/classes/class.doc b/Demo/classes/class.doc deleted file mode 100755 index fddc60bf7b..0000000000 --- a/Demo/classes/class.doc +++ /dev/null @@ -1,110 +0,0 @@ -New features of classes -======================= - -A class can implement certain operations that are invoked by special -syntax (such as subscription or arithmetic operations) by defining -methods with special names. - - -Special methods for any type ----------------------------- - -__repr__(self) --> string - -Used by the print statement and conversions (reverse quotes) to -compute the string representation of an object. - -__cmp__(self, other) --> int - -Used by all comparison operations. Should return -1 if selfother. Due to limitations in the -interpreter, exceptions raised by comparisons are ignored, and the -objects will be considered equal in this case. - - -Special methods for sequence and mapping types ----------------------------------------------- - -__len__(self) --> int - -Used by the built-in function len(). Should return the length of the -object, which should be >= 0. Also, an object whose __len__() method -returns 0 - -__getitem__(self, key) --> value - -Used to implement value = self[key]. Note that the special -interpretation of negative keys (if the class wishes to emulate a -sequence type) is up to the __getitem__ method. - -__setitem__(self, key, value) - -Used to implement self[key] = value. Same note as for __getitem__. - -__delitem__(self, key) - -Used to implement del self[key]. Same note as for __getitem__. - - -Special methods for sequence types ----------------------------------- - -__getslice__(self, i, j) --> sequence - -Used to implement self[i:j]. Note that missing i or j are replaced by -0 or len(self), respectively, and len(self) has been added to negative -i or j. - -__setslice__(self, i, j, sequence) - -Used to implement self[i:j] = value. Same note as for __getslice__. - -__delslice__(self, i, j) - -Used to implement del self[i:j]. Same note as for __getslice__. - - -Special methods for numeric types ---------------------------------- - -__add__, __sub__, __mul__, __div__, __mod__, __divmod__, __pow__, -__lshift__, __rshift__, __and__, __xor__, __or__ - -Used to implement the binary arithmetic operations (divmod and pow are -called by built-in functions). All have the call pattern -func(self, other) --> number. - -__neg__, __pos__, __abs__, __invert__ - -Used to implement the unary arithmetic operations (-, +, abs and ~). -All have the call pattern func(self) --> number. - -__nonzero__(self) --> int - -Used to implement boolean testing. An alternative name for this -method is __len__. - -__coerce__(self, other) --> (self1, other1) or None - -Used to implement "mixed-mode" numeric arithmetic. Either return a -tuple containing self and other converted to some common type, or None -if no way of conversion is known. When the common type would be the -type of other, it is sufficient to return None, since the interpreter -will also ask the other object to attempt a coercion (but sometimes, -if the implementation of the other type cannot be changed, it is -useful to do the conversion to the other type here). - -__int__(self) --> int -__long__(self) --> long -__float__(self) --> float - -Used to implement the built-in functions int(), long() and float(). - - -Notes ------ - -Except for __repr__ and __cmp__, when no appropriate method is -defined, attempts to execute the operation raise an exception. For -__repr__ and __cmp__, the traditional interpretations are used -in this case. diff --git a/Demo/comparisons/README b/Demo/comparisons/README deleted file mode 100644 index 111667c264..0000000000 --- a/Demo/comparisons/README +++ /dev/null @@ -1,60 +0,0 @@ -Subject: Re: What language would you use? -From: Tom Christiansen -Date: 6 Nov 1994 15:14:51 GMT -Newsgroups: comp.lang.python,comp.lang.tcl,comp.lang.scheme,comp.lang.misc,comp.lang.perl -Message-Id: <39irtb$3t4@csnews.cs.Colorado.EDU> -References: <39b7ha$j9v@zeno.nscf.org> <39hhjp$lgn@csnews.cs.Colorado.EDU> <39hvsu$dus@mathserv.mps.ohio-state.edu> - -[...] -If you're really into benchmarks, I'd love it if someone were to code up -the following problems in tcl, python, and scheme (and whatever else you'd -like). Separate versions (one optimized for speed, one for beauty :-) are -ok. Post your code so we can time it on our own systems. - -0) Factorial Test (numerics and function calls) - - (we did this already) - -1) Regular Expressions Test - - Read a file of (extended per egrep) regular expressions (one per line), - and apply those to all files whose names are listed on the command line. - Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns - against a five /etc/termcap files. Tests using more elaborate patters - would also be interesting. Your code should not break if given hundreds - of regular expressions or binary files to scan. - -2) Sorting Test - - Sort an input file that consists of lines like this - - var1=23 other=14 ditto=23 fred=2 - - such that each output line is sorted WRT to the number. Order - of output lines does not change. Resolve collisions using the - variable name. e.g. - - fred=2 other=14 ditto=23 var1=23 - - Lines may be up to several kilobytes in length and contain - zillions of variables. - -3) System Test - - Given a list of directories, report any bogus symbolic links contained - anywhere in those subtrees. A bogus symbolic link is one that cannot - be resolved because it points to a nonexistent or otherwise - unresolvable file. Do *not* use an external find executable. - Directories may be very very deep. Print a warning immediately if the - system you're running on doesn't support symbolic links. - - -I'll post perl solutions if people post the others. - - ---tom --- -Tom Christiansen Perl Consultant, Gamer, Hiker tchrist@mox.perl.com - - "But Billy! A *small* allowance prepares you for a lifetime of small - salaries and for your Social Security payments." --Family Circus diff --git a/Demo/comparisons/patterns b/Demo/comparisons/patterns deleted file mode 100755 index f4da846af6..0000000000 --- a/Demo/comparisons/patterns +++ /dev/null @@ -1,4 +0,0 @@ -^def -^class -^import -^from diff --git a/Demo/comparisons/regextest.py b/Demo/comparisons/regextest.py deleted file mode 100755 index 97564b7939..0000000000 --- a/Demo/comparisons/regextest.py +++ /dev/null @@ -1,50 +0,0 @@ -#! /usr/bin/env python - -# 1) Regular Expressions Test -# -# Read a file of (extended per egrep) regular expressions (one per line), -# and apply those to all files whose names are listed on the command line. -# Basically, an 'egrep -f' simulator. Test it with 20 "vt100" patterns -# against a five /etc/termcap files. Tests using more elaborate patters -# would also be interesting. Your code should not break if given hundreds -# of regular expressions or binary files to scan. - -# This implementation: -# - combines all patterns into a single one using ( ... | ... | ... ) -# - reads patterns from stdin, scans files given as command line arguments -# - produces output in the format :: -# - is only about 2.5 times as slow as egrep (though I couldn't run -# Tom's test -- this system, a vanilla SGI, only has /etc/terminfo) - -import string -import sys -import regex -from regex_syntax import * - -regex.set_syntax(RE_SYNTAX_EGREP) - -def main(): - pats = map(chomp, sys.stdin.readlines()) - bigpat = '(' + string.joinfields(pats, '|') + ')' - prog = regex.compile(bigpat) - - for file in sys.argv[1:]: - try: - fp = open(file, 'r') - except IOError, msg: - print "%s: %s" % (file, msg) - continue - lineno = 0 - while 1: - line = fp.readline() - if not line: - break - lineno = lineno + 1 - if prog.search(line) >= 0: - print "%s:%s:%s" % (file, lineno, line), - -def chomp(s): - if s[-1:] == '\n': return s[:-1] - else: return s - -main() diff --git a/Demo/comparisons/sortingtest.py b/Demo/comparisons/sortingtest.py deleted file mode 100755 index d6c213ca75..0000000000 --- a/Demo/comparisons/sortingtest.py +++ /dev/null @@ -1,50 +0,0 @@ -#! /usr/bin/env python - -# 2) Sorting Test -# -# Sort an input file that consists of lines like this -# -# var1=23 other=14 ditto=23 fred=2 -# -# such that each output line is sorted WRT to the number. Order -# of output lines does not change. Resolve collisions using the -# variable name. e.g. -# -# fred=2 other=14 ditto=23 var1=23 -# -# Lines may be up to several kilobytes in length and contain -# zillions of variables. - -# This implementation: -# - Reads stdin, writes stdout -# - Uses any amount of whitespace to separate fields -# - Allows signed numbers -# - Treats illegally formatted fields as field=0 -# - Outputs the sorted fields with exactly one space between them -# - Handles blank input lines correctly - -import regex -import string -import sys - -def main(): - prog = regex.compile('^\(.*\)=\([-+]?[0-9]+\)') - def makekey(item, prog=prog): - if prog.match(item) >= 0: - var, num = prog.group(1, 2) - return string.atoi(num), var - else: - # Bad input -- pretend it's a var with value 0 - return 0, item - while 1: - line = sys.stdin.readline() - if not line: - break - items = string.split(line) - items = map(makekey, items) - items.sort() - for num, var in items: - print "%s=%s" % (var, num), - print - -main() diff --git a/Demo/comparisons/systemtest.py b/Demo/comparisons/systemtest.py deleted file mode 100755 index f2533b1c0c..0000000000 --- a/Demo/comparisons/systemtest.py +++ /dev/null @@ -1,74 +0,0 @@ -#! /usr/bin/env python - -# 3) System Test -# -# Given a list of directories, report any bogus symbolic links contained -# anywhere in those subtrees. A bogus symbolic link is one that cannot -# be resolved because it points to a nonexistent or otherwise -# unresolvable file. Do *not* use an external find executable. -# Directories may be very very deep. Print a warning immediately if the -# system you're running on doesn't support symbolic links. - -# This implementation: -# - takes one optional argument, using the current directory as default -# - uses chdir to increase performance -# - sorts the names per directory -# - prints output lines of the form "path1 -> path2" as it goes -# - prints error messages about directories it can't list or chdir into - -import os -import sys -from stat import * - -def main(): - try: - # Note: can't test for presence of lstat -- it's always there - dummy = os.readlink - except AttributeError: - print "This system doesn't have symbolic links" - sys.exit(0) - if sys.argv[1:]: - prefix = sys.argv[1] - else: - prefix = '' - if prefix: - os.chdir(prefix) - if prefix[-1:] != '/': prefix = prefix + '/' - reportboguslinks(prefix) - else: - reportboguslinks('') - -def reportboguslinks(prefix): - try: - names = os.listdir('.') - except os.error, msg: - print "%s%s: can't list: %s" % (prefix, '.', msg) - return - names.sort() - for name in names: - if name == os.curdir or name == os.pardir: - continue - try: - mode = os.lstat(name)[ST_MODE] - except os.error: - print "%s%s: can't stat: %s" % (prefix, name, msg) - continue - if S_ISLNK(mode): - try: - os.stat(name) - except os.error: - print "%s%s -> %s" % \ - (prefix, name, os.readlink(name)) - elif S_ISDIR(mode): - try: - os.chdir(name) - except os.error, msg: - print "%s%s: can't chdir: %s" % \ - (prefix, name, msg) - continue - try: - reportboguslinks(prefix + name + '/') - finally: - os.chdir('..') - -main() diff --git a/Demo/curses/README b/Demo/curses/README deleted file mode 100644 index f2a3b74499..0000000000 --- a/Demo/curses/README +++ /dev/null @@ -1,28 +0,0 @@ -This is a collection of demos and tests for the curses module. - -ncurses demos -============= - -These demos are converted from the C versions in the ncurses -distribution, and were contributed by Thomas Gellekum -I didn't strive for a `pythonic' style, but bluntly copied the -originals. I won't attempt to `beautify' the program anytime soon, but -I wouldn't mind someone else making an effort in that direction, of -course. - -ncurses.py -- currently only a panels demo - XXX this won't work until panel support is checked in -rain.py -- raindrops keep falling on my desktop -tclock.py -- ASCII clock, by Howard Jones -xmas.py -- I'm dreaming of an ASCII christmas - -Please send bugfixes and new contributions to me or, even better, -submit them to the Python Bug Tracker on SourceForge -(). - - -Other demos -=========== - -life.py -- Simple game of Life -repeat.py -- Repeatedly execute a shell command (like watch(1)) diff --git a/Demo/curses/life.py b/Demo/curses/life.py deleted file mode 100755 index b4797bf0af..0000000000 --- a/Demo/curses/life.py +++ /dev/null @@ -1,223 +0,0 @@ -#!/usr/bin/env python -# life.py -- A curses-based version of Conway's Game of Life. -# Contributed by A.M. Kuchling -# -# An empty board will be displayed, and the following commands are available: -# E : Erase the board -# R : Fill the board randomly -# S : Step for a single generation -# C : Update continuously until a key is struck -# Q : Quit -# Cursor keys : Move the cursor around the board -# Space or Enter : Toggle the contents of the cursor's position -# -# TODO : -# Support the mouse -# Use colour if available -# Make board updates faster -# - -class LifeBoard: - """Encapsulates a Life board - - Attributes: - X,Y : horizontal and vertical size of the board - state : dictionary mapping (x,y) to 0 or 1 - - Methods: - display(update_board) -- If update_board is true, compute the - next generation. Then display the state - of the board and refresh the screen. - erase() -- clear the entire board - makeRandom() -- fill the board randomly - set(y,x) -- set the given cell to Live; doesn't refresh the screen - toggle(y,x) -- change the given cell from live to dead, or vice - versa, and refresh the screen display - - """ - def __init__(self, scr, char=ord('*')): - """Create a new LifeBoard instance. - - scr -- curses screen object to use for display - char -- character used to render live cells (default: '*') - """ - self.state={} ; self.scr=scr - Y, X = self.scr.getmaxyx() - self.X, self.Y = X-2, Y-2-1 - self.char = char - self.scr.clear() - - # Draw a border around the board - border_line='+'+(self.X*'-')+'+' - self.scr.addstr(0, 0, border_line) - self.scr.addstr(self.Y+1,0, border_line) - for y in range(0, self.Y): - self.scr.addstr(1+y, 0, '|') - self.scr.addstr(1+y, self.X+1, '|') - self.scr.refresh() - - def set(self, y, x): - """Set a cell to the live state""" - if x<0 or self.X<=x or y<0 or self.Y<=y: - raise ValueError, "Coordinates out of range %i,%i"% (y,x) - self.state[x,y] = 1 - - def toggle(self, y, x): - """Toggle a cell's state between live and dead""" - if x<0 or self.X<=x or y<0 or self.Y<=y: - raise ValueError, "Coordinates out of range %i,%i"% (y,x) - if self.state.has_key( (x,y) ): - del self.state[x,y] - self.scr.addch(y+1, x+1, ' ') - else: - self.state[x,y]=1 - self.scr.addch(y+1, x+1, self.char) - self.scr.refresh() - - def erase(self): - """Clear the entire board and update the board display""" - self.state={} - self.display(update_board=0) - - def display(self, update_board=1): - """Display the whole board, optionally computing one generation""" - M,N = self.X, self.Y - if not update_board: - for i in range(0, M): - for j in range(0, N): - if self.state.has_key( (i,j) ): - self.scr.addch(j+1, i+1, self.char) - else: - self.scr.addch(j+1, i+1, ' ') - self.scr.refresh() - return - - d={} ; self.boring=1 - for i in range(0, M): - L=range( max(0, i-1), min(M, i+2) ) - for j in range(0, N): - s=0 - live=self.state.has_key( (i,j) ) - for k in range( max(0, j-1), min(N, j+2) ): - for l in L: - if self.state.has_key( (l,k) ): - s=s+1 - s=s-live - if s==3: - # Birth - d[i,j]=1 - self.scr.addch(j+1, i+1, self.char) - if not live: self.boring=0 - elif s==2 and live: d[i,j]=1 # Survival - elif live: - # Death - self.scr.addch(j+1, i+1, ' ') - self.boring=0 - self.state=d - self.scr.refresh() - - def makeRandom(self): - "Fill the board with a random pattern" - import whrandom - self.state={} - for i in range(0, self.X): - for j in range(0, self.Y): - if whrandom.random()*10>5.0: self.set(j,i) - - -def erase_menu(stdscr, menu_y): - "Clear the space where the menu resides" - stdscr.move(menu_y, 0) ; stdscr.clrtoeol() - stdscr.move(menu_y+1, 0) ; stdscr.clrtoeol() - -def display_menu(stdscr, menu_y): - "Display the menu of possible keystroke commands" - erase_menu(stdscr, menu_y) - stdscr.addstr(menu_y, 4, - 'Use the cursor keys to move, and space or Enter to toggle a cell.') - stdscr.addstr(menu_y+1, 4, - 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit') - -def main(stdscr): - import string, curses - - # Clear the screen and display the menu of keys - stdscr.clear() - stdscr_y, stdscr_x = stdscr.getmaxyx() - menu_y=(stdscr_y-3)-1 - display_menu(stdscr, menu_y) - - # Allocate a subwindow for the Life board and create the board object - subwin=stdscr.subwin(stdscr_y-3, stdscr_x, 0, 0) - board=LifeBoard(subwin, char=ord('*')) - board.display(update_board=0) - - # xpos, ypos are the cursor's position - xpos, ypos = board.X/2, board.Y/2 - - # Main loop: - while (1): - stdscr.move(1+ypos, 1+xpos) # Move the cursor - c=stdscr.getch() # Get a keystroke - if 00: ypos=ypos-1 - elif c==curses.KEY_DOWN and ypos0: xpos=xpos-1 - elif c==curses.KEY_RIGHT and xpos", "LAST"] - - stdscr.refresh() - - for y in range(0, curses.LINES - 1): - for x in range(0, curses.COLS): - stdscr.addstr("%d" % ((y + x) % 10)) - for y in range(0, 1): - p1 = mkpanel(curses.COLOR_RED, - curses.LINES / 2 - 2, - curses.COLS / 8 + 1, - 0, - 0) - p1.set_userptr("p1") - - p2 = mkpanel(curses.COLOR_GREEN, - curses.LINES / 2 + 1, - curses.COLS / 7, - curses.LINES / 4, - curses.COLS / 10) - p2.set_userptr("p2") - - p3 = mkpanel(curses.COLOR_YELLOW, - curses.LINES / 4, - curses.COLS / 10, - curses.LINES / 2, - curses.COLS / 9) - p3.set_userptr("p3") - - p4 = mkpanel(curses.COLOR_BLUE, - curses.LINES / 2 - 2, - curses.COLS / 8, - curses.LINES / 2 - 2, - curses.COLS / 3) - p4.set_userptr("p4") - - p5 = mkpanel(curses.COLOR_MAGENTA, - curses.LINES / 2 - 2, - curses.COLS / 8, - curses.LINES / 2, - curses.COLS / 2 - 2) - p5.set_userptr("p5") - - fill_panel(p1) - fill_panel(p2) - fill_panel(p3) - fill_panel(p4) - fill_panel(p5) - p4.hide() - p5.hide() - pflush() - saywhat("press any key to continue") - wait_a_while() - - saywhat("h3 s1 s2 s4 s5;press any key to continue") - p1.move(0, 0) - p3.hide() - p1.show() - p2.show() - p4.show() - p5.show() - pflush() - wait_a_while() - - saywhat("s1; press any key to continue") - p1.show() - pflush() - wait_a_while() - - saywhat("s2; press any key to continue") - p2.show() - pflush() - wait_a_while() - - saywhat("m2; press any key to continue") - p2.move(curses.LINES / 3 + 1, curses.COLS / 8) - pflush() - wait_a_while() - - saywhat("s3; press any key to continue") - p3.show() - pflush() - wait_a_while() - - saywhat("m3; press any key to continue") - p3.move(curses.LINES / 4 + 1, curses.COLS / 15) - pflush() - wait_a_while() - - saywhat("b3; press any key to continue") - p3.bottom() - pflush() - wait_a_while() - - saywhat("s4; press any key to continue") - p4.show() - pflush() - wait_a_while() - - saywhat("s5; press any key to continue") - p5.show() - pflush() - wait_a_while() - - saywhat("t3; press any key to continue") - p3.top() - pflush() - wait_a_while() - - saywhat("t1; press any key to continue") - p1.show() - pflush() - wait_a_while() - - saywhat("t2; press any key to continue") - p2.show() - pflush() - wait_a_while() - - saywhat("t3; press any key to continue") - p3.show() - pflush() - wait_a_while() - - saywhat("t4; press any key to continue") - p4.show() - pflush() - wait_a_while() - - for itmp in range(0, 6): - w4 = p4.window() - w5 = p5.window() - - saywhat("m4; press any key to continue") - w4.move(curses.LINES / 8, 1) - w4.addstr(mod[itmp]) - p4.move(curses.LINES / 6, itmp * curses.COLS / 8) - w5.move(curses.LINES / 6, 1) - w5.addstr(mod[itmp]) - pflush() - wait_a_while() - - saywhat("m5; press any key to continue") - w4.move(curses.LINES / 6, 1) - w4.addstr(mod[itmp]) - p5.move(curses.LINES / 3 - 1, itmp * 10 + 6) - w5.move(curses.LINES / 8, 1) - w5.addstr(mod[itmp]) - pflush() - wait_a_while() - - saywhat("m4; press any key to continue") - p4.move(curses.LINES / 6, (itmp + 1) * curses.COLS / 8) - pflush() - wait_a_while() - - saywhat("t5; press any key to continue") - p5.top() - pflush() - wait_a_while() - - saywhat("t2; press any key to continue") - p2.top() - pflush() - wait_a_while() - - saywhat("t1; press any key to continue") - p1.top() - pflush() - wait_a_while() - - saywhat("d2; press any key to continue") - del p2 - pflush() - wait_a_while() - - saywhat("h3; press any key to continue") - p3.hide() - pflush() - wait_a_while() - - saywhat("d1; press any key to continue") - del p1 - pflush() - wait_a_while() - - saywhat("d4; press any key to continue") - del p4 - pflush() - wait_a_while() - - saywhat("d5; press any key to continue") - del p5 - pflush() - wait_a_while() - if nap_msec == 1: - break - nap_msec = 100 - -# -# one fine day there'll be the menu at this place -# -curses.wrapper(demo_panels) diff --git a/Demo/curses/rain.py b/Demo/curses/rain.py deleted file mode 100644 index 2399d7f438..0000000000 --- a/Demo/curses/rain.py +++ /dev/null @@ -1,94 +0,0 @@ -#!/usr/bin/env python -# -# $Id$ -# -# somebody should probably check the randrange()s... - -import curses -from random import randrange - -def next_j(j): - if j == 0: - j = 4 - else: - j -= 1 - - if curses.has_colors(): - z = randrange(0, 3) - color = curses.color_pair(z) - if z: - color = color | curses.A_BOLD - stdscr.attrset(color) - - return j - -def main(win): - # we know that the first argument from curses.wrapper() is stdscr. - # Initialize it globally for convenience. - global stdscr - stdscr = win - - if curses.has_colors(): - bg = curses.COLOR_BLACK - curses.init_pair(1, curses.COLOR_BLUE, bg) - curses.init_pair(2, curses.COLOR_CYAN, bg) - - curses.nl() - curses.noecho() - # XXX curs_set() always returns ERR - # curses.curs_set(0) - stdscr.timeout(0) - - c = curses.COLS - 4 - r = curses.LINES - 4 - xpos = [0] * c - ypos = [0] * r - for j in range(4, -1, -1): - xpos[j] = randrange(0, c) + 2 - ypos[j] = randrange(0, r) + 2 - - j = 0 - while 1: - x = randrange(0, c) + 2 - y = randrange(0, r) + 2 - - stdscr.addch(y, x, ord('.')) - - stdscr.addch(ypos[j], xpos[j], ord('o')) - - j = next_j(j) - stdscr.addch(ypos[j], xpos[j], ord('O')) - - j = next_j(j) - stdscr.addch( ypos[j] - 1, xpos[j], ord('-')) - stdscr.addstr(ypos[j], xpos[j] - 1, "|.|") - stdscr.addch( ypos[j] + 1, xpos[j], ord('-')) - - j = next_j(j) - stdscr.addch( ypos[j] - 2, xpos[j], ord('-')) - stdscr.addstr(ypos[j] - 1, xpos[j] - 1, "/ \\") - stdscr.addstr(ypos[j], xpos[j] - 2, "| O |") - stdscr.addstr(ypos[j] + 1, xpos[j] - 1, "\\ /") - stdscr.addch( ypos[j] + 2, xpos[j], ord('-')) - - j = next_j(j) - stdscr.addch( ypos[j] - 2, xpos[j], ord(' ')) - stdscr.addstr(ypos[j] - 1, xpos[j] - 1, " ") - stdscr.addstr(ypos[j], xpos[j] - 2, " ") - stdscr.addstr(ypos[j] + 1, xpos[j] - 1, " ") - stdscr.addch( ypos[j] + 2, xpos[j], ord(' ')) - - xpos[j] = x - ypos[j] = y - - ch = stdscr.getch() - if ch == ord('q') or ch == ord('Q'): - return 0 - elif ch == ord('s'): - stdscr.nodelay(0) - elif ch == ord(' '): - stdscr.nodelay(1) - - curses.napms(50) - -curses.wrapper(main) diff --git a/Demo/curses/repeat.py b/Demo/curses/repeat.py deleted file mode 100755 index 158264cf6b..0000000000 --- a/Demo/curses/repeat.py +++ /dev/null @@ -1,58 +0,0 @@ -#! /usr/bin/env python - -"""repeat - -This simple program repeatedly (with 1-second intervals) executes the -shell command given on the command line and displays the output (or as -much of it as fits on the screen). It uses curses to paint each new -output on top of the old output, so that if nothing changes, the -screen doesn't change. This is handy to watch for changes in e.g. a -directory or process listing. - -To end, hit Control-C. -""" - -# Author: Guido van Rossum - -# Disclaimer: there's a Linux program named 'watch' that does the same -# thing. Honestly, I didn't know of its existence when I wrote this! - -# To do: add features until it has the same functionality as watch(1); -# then compare code size and development time. - -import os -import sys -import time -import curses - -def main(): - if not sys.argv[1:]: - print __doc__ - sys.exit(0) - cmd = " ".join(sys.argv[1:]) - p = os.popen(cmd, "r") - text = p.read() - sts = p.close() - if sts: - print >>sys.stderr, "Exit code:", sts - sys.exit(sts) - w = curses.initscr() - try: - while 1: - w.erase() - try: - w.addstr(text) - except curses.error: - pass - w.refresh() - time.sleep(1) - p = os.popen(cmd, "r") - text = p.read() - sts = p.close() - if sts: - print >>sys.stderr, "Exit code:", sts - sys.exit(sts) - finally: - curses.endwin() - -main() diff --git a/Demo/curses/tclock.py b/Demo/curses/tclock.py deleted file mode 100644 index f423e9a54b..0000000000 --- a/Demo/curses/tclock.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python -# -# $Id$ -# -# From tclock.c, Copyright Howard Jones , September 1994. - -from math import * -import curses, time - -ASPECT = 2.2 - -def sign(_x): - if _x < 0: return -1 - return 1 - -def A2XY(angle, radius): - return int(round(ASPECT * radius * sin(angle))), int(round(radius * cos(angle))) - -def plot(x, y, col): - stdscr.addch(y, x, col) - -# draw a diagonal line using Bresenham's algorithm -def dline(pair, from_x, from_y, x2, y2, ch): - if curses.has_colors(): - stdscr.attrset(curses.color_pair(pair)) - - dx = x2 - from_x - dy = y2 - from_y - - ax = abs(dx * 2) - ay = abs(dy * 2) - - sx = sign(dx) - sy = sign(dy) - - x = from_x - y = from_y - - if ax > ay: - d = ay - ax / 2 - - while 1: - plot(x, y, ch) - if x == x2: - return - - if d >= 0: - y += sy - d -= ax - x += sx - d += ay - else: - d = ax - ay / 2 - - while 1: - plot(x, y, ch) - if y == y2: - return - - if d >= 0: - x += sx - d -= ay - y += sy - d += ax - -def main(win): - global stdscr - stdscr = win - - lastbeep = -1 - my_bg = curses.COLOR_BLACK - - stdscr.nodelay(1) - stdscr.timeout(0) -# curses.curs_set(0) - if curses.has_colors(): - curses.init_pair(1, curses.COLOR_RED, my_bg) - curses.init_pair(2, curses.COLOR_MAGENTA, my_bg) - curses.init_pair(3, curses.COLOR_GREEN, my_bg) - - cx = (curses.COLS - 1) / 2 - cy = curses.LINES / 2 - ch = min( cy-1, int(cx / ASPECT) - 1) - mradius = (3 * ch) / 4 - hradius = ch / 2 - sradius = 5 * ch / 6 - - for i in range(0, 12): - sangle = (i + 1) * 2.0 * pi / 12.0 - sdx, sdy = A2XY(sangle, sradius) - - stdscr.addstr(cy - sdy, cx + sdx, "%d" % (i + 1)) - - stdscr.addstr(0, 0, - "ASCII Clock by Howard Jones , 1994") - - sradius = max(sradius-4, 8) - - while 1: - curses.napms(1000) - - tim = time.time() - t = time.localtime(tim) - - hours = t[3] + t[4] / 60.0 - if hours > 12.0: - hours -= 12.0 - - mangle = t[4] * 2 * pi / 60.0 - mdx, mdy = A2XY(mangle, mradius) - - hangle = hours * 2 * pi / 12.0 - hdx, hdy = A2XY(hangle, hradius) - - sangle = t[5] * 2 * pi / 60.0 - sdx, sdy = A2XY(sangle, sradius) - - dline(3, cx, cy, cx + mdx, cy - mdy, ord('#')) - - stdscr.attrset(curses.A_REVERSE) - dline(2, cx, cy, cx + hdx, cy - hdy, ord('.')) - stdscr.attroff(curses.A_REVERSE) - - if curses.has_colors(): - stdscr.attrset(curses.color_pair(1)) - - plot(cx + sdx, cy - sdy, ord('O')) - - if curses.has_colors(): - stdscr.attrset(curses.color_pair(0)) - - stdscr.addstr(curses.LINES - 2, 0, time.ctime(tim)) - stdscr.refresh() - if (t[5] % 5) == 0 and t[5] != lastbeep: - lastbeep = t[5] - curses.beep() - - ch = stdscr.getch() - if ch == ord('q'): - return 0 - - plot(cx + sdx, cy - sdy, ord(' ')) - dline(0, cx, cy, cx + hdx, cy - hdy, ord(' ')) - dline(0, cx, cy, cx + mdx, cy - mdy, ord(' ')) - -curses.wrapper(main) diff --git a/Demo/curses/xmas.py b/Demo/curses/xmas.py deleted file mode 100644 index 99c708730d..0000000000 --- a/Demo/curses/xmas.py +++ /dev/null @@ -1,906 +0,0 @@ -# asciixmas -# December 1989 Larry Bartz Indianapolis, IN -# -# $Id$ -# -# I'm dreaming of an ascii character-based monochrome Christmas, -# Just like the one's I used to know! -# Via a full duplex communications channel, -# At 9600 bits per second, -# Even though it's kinda slow. -# -# I'm dreaming of an ascii character-based monochrome Christmas, -# With ev'ry C program I write! -# May your screen be merry and bright! -# And may all your Christmases be amber or green, -# (for reduced eyestrain and improved visibility)! -# -# -# Notes on the Python version: -# I used a couple of `try...except curses.error' to get around some functions -# returning ERR. The errors come from using wrapping functions to fill -# windows to the last character cell. The C version doesn't have this problem, -# it simply ignores any return values. -# - -import curses -import sys - -FROMWHO = "Thomas Gellekum " - -def set_color(win, color): - if curses.has_colors(): - n = color + 1 - curses.init_pair(n, color, my_bg) - win.attroff(curses.A_COLOR) - win.attron(curses.color_pair(n)) - -def unset_color(win): - if curses.has_colors(): - win.attrset(curses.color_pair(0)) - -def look_out(msecs): - curses.napms(msecs) - if stdscr.getch() != -1: - curses.beep() - sys.exit(0) - -def boxit(): - for y in range(0, 20): - stdscr.addch(y, 7, ord('|')) - - for x in range(8, 80): - stdscr.addch(19, x, ord('_')) - - for x in range(0, 80): - stdscr.addch(22, x, ord('_')) - - return - -def seas(): - stdscr.addch(4, 1, ord('S')) - stdscr.addch(6, 1, ord('E')) - stdscr.addch(8, 1, ord('A')) - stdscr.addch(10, 1, ord('S')) - stdscr.addch(12, 1, ord('O')) - stdscr.addch(14, 1, ord('N')) - stdscr.addch(16, 1, ord("'")) - stdscr.addch(18, 1, ord('S')) - - return - -def greet(): - stdscr.addch(3, 5, ord('G')) - stdscr.addch(5, 5, ord('R')) - stdscr.addch(7, 5, ord('E')) - stdscr.addch(9, 5, ord('E')) - stdscr.addch(11, 5, ord('T')) - stdscr.addch(13, 5, ord('I')) - stdscr.addch(15, 5, ord('N')) - stdscr.addch(17, 5, ord('G')) - stdscr.addch(19, 5, ord('S')) - - return - -def fromwho(): - stdscr.addstr(21, 13, FROMWHO) - return - -def tree(): - set_color(treescrn, curses.COLOR_GREEN) - treescrn.addch(1, 11, ord('/')) - treescrn.addch(2, 11, ord('/')) - treescrn.addch(3, 10, ord('/')) - treescrn.addch(4, 9, ord('/')) - treescrn.addch(5, 9, ord('/')) - treescrn.addch(6, 8, ord('/')) - treescrn.addch(7, 7, ord('/')) - treescrn.addch(8, 6, ord('/')) - treescrn.addch(9, 6, ord('/')) - treescrn.addch(10, 5, ord('/')) - treescrn.addch(11, 3, ord('/')) - treescrn.addch(12, 2, ord('/')) - - treescrn.addch(1, 13, ord('\\')) - treescrn.addch(2, 13, ord('\\')) - treescrn.addch(3, 14, ord('\\')) - treescrn.addch(4, 15, ord('\\')) - treescrn.addch(5, 15, ord('\\')) - treescrn.addch(6, 16, ord('\\')) - treescrn.addch(7, 17, ord('\\')) - treescrn.addch(8, 18, ord('\\')) - treescrn.addch(9, 18, ord('\\')) - treescrn.addch(10, 19, ord('\\')) - treescrn.addch(11, 21, ord('\\')) - treescrn.addch(12, 22, ord('\\')) - - treescrn.addch(4, 10, ord('_')) - treescrn.addch(4, 14, ord('_')) - treescrn.addch(8, 7, ord('_')) - treescrn.addch(8, 17, ord('_')) - - treescrn.addstr(13, 0, "//////////// \\\\\\\\\\\\\\\\\\\\\\\\") - - treescrn.addstr(14, 11, "| |") - treescrn.addstr(15, 11, "|_|") - - unset_color(treescrn) - treescrn.refresh() - w_del_msg.refresh() - - return - -def balls(): - treescrn.overlay(treescrn2) - - set_color(treescrn2, curses.COLOR_BLUE) - treescrn2.addch(3, 9, ord('@')) - treescrn2.addch(3, 15, ord('@')) - treescrn2.addch(4, 8, ord('@')) - treescrn2.addch(4, 16, ord('@')) - treescrn2.addch(5, 7, ord('@')) - treescrn2.addch(5, 17, ord('@')) - treescrn2.addch(7, 6, ord('@')) - treescrn2.addch(7, 18, ord('@')) - treescrn2.addch(8, 5, ord('@')) - treescrn2.addch(8, 19, ord('@')) - treescrn2.addch(10, 4, ord('@')) - treescrn2.addch(10, 20, ord('@')) - treescrn2.addch(11, 2, ord('@')) - treescrn2.addch(11, 22, ord('@')) - treescrn2.addch(12, 1, ord('@')) - treescrn2.addch(12, 23, ord('@')) - - unset_color(treescrn2) - treescrn2.refresh() - w_del_msg.refresh() - return - -def star(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_YELLOW) - - treescrn2.addch(0, 12, ord('*')) - treescrn2.standend() - - unset_color(treescrn2) - treescrn2.refresh() - w_del_msg.refresh() - return - -def strng1(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_WHITE) - - treescrn2.addch(3, 13, ord('\'')) - treescrn2.addch(3, 12, ord(':')) - treescrn2.addch(3, 11, ord('.')) - - treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) - unset_color(treescrn2) - - treescrn2.refresh() - w_del_msg.refresh() - return - -def strng2(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_WHITE) - - treescrn2.addch(5, 14, ord('\'')) - treescrn2.addch(5, 13, ord(':')) - treescrn2.addch(5, 12, ord('.')) - treescrn2.addch(5, 11, ord(',')) - treescrn2.addch(6, 10, ord('\'')) - treescrn2.addch(6, 9, ord(':')) - - treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) - unset_color(treescrn2) - - treescrn2.refresh() - w_del_msg.refresh() - return - -def strng3(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_WHITE) - - treescrn2.addch(7, 16, ord('\'')) - treescrn2.addch(7, 15, ord(':')) - treescrn2.addch(7, 14, ord('.')) - treescrn2.addch(7, 13, ord(',')) - treescrn2.addch(8, 12, ord('\'')) - treescrn2.addch(8, 11, ord(':')) - treescrn2.addch(8, 10, ord('.')) - treescrn2.addch(8, 9, ord(',')) - - treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) - unset_color(treescrn2) - - treescrn2.refresh() - w_del_msg.refresh() - return - -def strng4(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_WHITE) - - treescrn2.addch(9, 17, ord('\'')) - treescrn2.addch(9, 16, ord(':')) - treescrn2.addch(9, 15, ord('.')) - treescrn2.addch(9, 14, ord(',')) - treescrn2.addch(10, 13, ord('\'')) - treescrn2.addch(10, 12, ord(':')) - treescrn2.addch(10, 11, ord('.')) - treescrn2.addch(10, 10, ord(',')) - treescrn2.addch(11, 9, ord('\'')) - treescrn2.addch(11, 8, ord(':')) - treescrn2.addch(11, 7, ord('.')) - treescrn2.addch(11, 6, ord(',')) - treescrn2.addch(12, 5, ord('\'')) - - treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) - unset_color(treescrn2) - - treescrn2.refresh() - w_del_msg.refresh() - return - -def strng5(): - treescrn2.attrset(curses.A_BOLD | curses.A_BLINK) - set_color(treescrn2, curses.COLOR_WHITE) - - treescrn2.addch(11, 19, ord('\'')) - treescrn2.addch(11, 18, ord(':')) - treescrn2.addch(11, 17, ord('.')) - treescrn2.addch(11, 16, ord(',')) - treescrn2.addch(12, 15, ord('\'')) - treescrn2.addch(12, 14, ord(':')) - treescrn2.addch(12, 13, ord('.')) - treescrn2.addch(12, 12, ord(',')) - - treescrn2.attroff(curses.A_BOLD | curses.A_BLINK) - unset_color(treescrn2) - - # save a fully lit tree - treescrn2.overlay(treescrn) - - treescrn2.refresh() - w_del_msg.refresh() - return - -def blinkit(): - treescrn8.touchwin() - - for cycle in range(0, 5): - if cycle == 0: - treescrn3.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - break - elif cycle == 1: - treescrn4.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - break - elif cycle == 2: - treescrn5.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - break - elif cycle == 3: - treescrn6.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - break - elif cycle == 4: - treescrn7.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - break - - treescrn8.touchwin() - - # ALL ON - treescrn.overlay(treescrn8) - treescrn8.refresh() - w_del_msg.refresh() - - return - -def deer_step(win, y, x): - win.mvwin(y, x) - win.refresh() - w_del_msg.refresh() - look_out(5) - -def reindeer(): - y_pos = 0 - - for x_pos in range(70, 62, -1): - if x_pos < 66: y_pos = 1 - for looper in range(0, 4): - dotdeer0.addch(y_pos, x_pos, ord('.')) - dotdeer0.refresh() - w_del_msg.refresh() - dotdeer0.erase() - dotdeer0.refresh() - w_del_msg.refresh() - look_out(50) - - y_pos = 2 - - for x_pos in range(x_pos - 1, 50, -1): - for looper in range(0, 4): - if x_pos < 56: - y_pos = 3 - - try: - stardeer0.addch(y_pos, x_pos, ord('*')) - except curses.error: - pass - stardeer0.refresh() - w_del_msg.refresh() - stardeer0.erase() - stardeer0.refresh() - w_del_msg.refresh() - else: - dotdeer0.addch(y_pos, x_pos, ord('*')) - dotdeer0.refresh() - w_del_msg.refresh() - dotdeer0.erase() - dotdeer0.refresh() - w_del_msg.refresh() - - x_pos = 58 - - for y_pos in range(2, 5): - lildeer0.touchwin() - lildeer0.refresh() - w_del_msg.refresh() - - for looper in range(0, 4): - deer_step(lildeer3, y_pos, x_pos) - deer_step(lildeer2, y_pos, x_pos) - deer_step(lildeer1, y_pos, x_pos) - deer_step(lildeer2, y_pos, x_pos) - deer_step(lildeer3, y_pos, x_pos) - - lildeer0.touchwin() - lildeer0.refresh() - w_del_msg.refresh() - - x_pos -= 2 - - x_pos = 35 - - for y_pos in range(5, 10): - - middeer0.touchwin() - middeer0.refresh() - w_del_msg.refresh() - - for looper in range(0, 2): - deer_step(middeer3, y_pos, x_pos) - deer_step(middeer2, y_pos, x_pos) - deer_step(middeer1, y_pos, x_pos) - deer_step(middeer2, y_pos, x_pos) - deer_step(middeer3, y_pos, x_pos) - - middeer0.touchwin() - middeer0.refresh() - w_del_msg.refresh() - - x_pos -= 3 - - look_out(300) - - y_pos = 1 - - for x_pos in range(8, 16): - deer_step(bigdeer4, y_pos, x_pos) - deer_step(bigdeer3, y_pos, x_pos) - deer_step(bigdeer2, y_pos, x_pos) - deer_step(bigdeer1, y_pos, x_pos) - deer_step(bigdeer2, y_pos, x_pos) - deer_step(bigdeer3, y_pos, x_pos) - deer_step(bigdeer4, y_pos, x_pos) - deer_step(bigdeer0, y_pos, x_pos) - - x_pos -= 1 - - for looper in range(0, 6): - deer_step(lookdeer4, y_pos, x_pos) - deer_step(lookdeer3, y_pos, x_pos) - deer_step(lookdeer2, y_pos, x_pos) - deer_step(lookdeer1, y_pos, x_pos) - deer_step(lookdeer2, y_pos, x_pos) - deer_step(lookdeer3, y_pos, x_pos) - deer_step(lookdeer4, y_pos, x_pos) - - deer_step(lookdeer0, y_pos, x_pos) - - for y_pos in range(y_pos, 10): - for looper in range(0, 2): - deer_step(bigdeer4, y_pos, x_pos) - deer_step(bigdeer3, y_pos, x_pos) - deer_step(bigdeer2, y_pos, x_pos) - deer_step(bigdeer1, y_pos, x_pos) - deer_step(bigdeer2, y_pos, x_pos) - deer_step(bigdeer3, y_pos, x_pos) - deer_step(bigdeer4, y_pos, x_pos) - deer_step(bigdeer0, y_pos, x_pos) - - y_pos -= 1 - - deer_step(lookdeer3, y_pos, x_pos) - return - -def main(win): - global stdscr - stdscr = win - - global my_bg, y_pos, x_pos - global treescrn, treescrn2, treescrn3, treescrn4 - global treescrn5, treescrn6, treescrn7, treescrn8 - global dotdeer0, stardeer0 - global lildeer0, lildeer1, lildeer2, lildeer3 - global middeer0, middeer1, middeer2, middeer3 - global bigdeer0, bigdeer1, bigdeer2, bigdeer3, bigdeer4 - global lookdeer0, lookdeer1, lookdeer2, lookdeer3, lookdeer4 - global w_holiday, w_del_msg - - my_bg = curses.COLOR_BLACK - # curses.curs_set(0) - - treescrn = curses.newwin(16, 27, 3, 53) - treescrn2 = curses.newwin(16, 27, 3, 53) - treescrn3 = curses.newwin(16, 27, 3, 53) - treescrn4 = curses.newwin(16, 27, 3, 53) - treescrn5 = curses.newwin(16, 27, 3, 53) - treescrn6 = curses.newwin(16, 27, 3, 53) - treescrn7 = curses.newwin(16, 27, 3, 53) - treescrn8 = curses.newwin(16, 27, 3, 53) - - dotdeer0 = curses.newwin(3, 71, 0, 8) - - stardeer0 = curses.newwin(4, 56, 0, 8) - - lildeer0 = curses.newwin(7, 53, 0, 8) - lildeer1 = curses.newwin(2, 4, 0, 0) - lildeer2 = curses.newwin(2, 4, 0, 0) - lildeer3 = curses.newwin(2, 4, 0, 0) - - middeer0 = curses.newwin(15, 42, 0, 8) - middeer1 = curses.newwin(3, 7, 0, 0) - middeer2 = curses.newwin(3, 7, 0, 0) - middeer3 = curses.newwin(3, 7, 0, 0) - - bigdeer0 = curses.newwin(10, 23, 0, 0) - bigdeer1 = curses.newwin(10, 23, 0, 0) - bigdeer2 = curses.newwin(10, 23, 0, 0) - bigdeer3 = curses.newwin(10, 23, 0, 0) - bigdeer4 = curses.newwin(10, 23, 0, 0) - - lookdeer0 = curses.newwin(10, 25, 0, 0) - lookdeer1 = curses.newwin(10, 25, 0, 0) - lookdeer2 = curses.newwin(10, 25, 0, 0) - lookdeer3 = curses.newwin(10, 25, 0, 0) - lookdeer4 = curses.newwin(10, 25, 0, 0) - - w_holiday = curses.newwin(1, 27, 3, 27) - - w_del_msg = curses.newwin(1, 20, 23, 60) - - try: - w_del_msg.addstr(0, 0, "Hit any key to quit") - except curses.error: - pass - - try: - w_holiday.addstr(0, 0, "H A P P Y H O L I D A Y S") - except curses.error: - pass - - # set up the windows for our various reindeer - lildeer1.addch(0, 0, ord('V')) - lildeer1.addch(1, 0, ord('@')) - lildeer1.addch(1, 1, ord('<')) - lildeer1.addch(1, 2, ord('>')) - try: - lildeer1.addch(1, 3, ord('~')) - except curses.error: - pass - - lildeer2.addch(0, 0, ord('V')) - lildeer2.addch(1, 0, ord('@')) - lildeer2.addch(1, 1, ord('|')) - lildeer2.addch(1, 2, ord('|')) - try: - lildeer2.addch(1, 3, ord('~')) - except curses.error: - pass - - lildeer3.addch(0, 0, ord('V')) - lildeer3.addch(1, 0, ord('@')) - lildeer3.addch(1, 1, ord('>')) - lildeer3.addch(1, 2, ord('<')) - try: - lildeer2.addch(1, 3, ord('~')) # XXX - except curses.error: - pass - - middeer1.addch(0, 2, ord('y')) - middeer1.addch(0, 3, ord('y')) - middeer1.addch(1, 2, ord('0')) - middeer1.addch(1, 3, ord('(')) - middeer1.addch(1, 4, ord('=')) - middeer1.addch(1, 5, ord(')')) - middeer1.addch(1, 6, ord('~')) - middeer1.addch(2, 3, ord('\\')) - middeer1.addch(2, 5, ord('/')) - - middeer2.addch(0, 2, ord('y')) - middeer2.addch(0, 3, ord('y')) - middeer2.addch(1, 2, ord('0')) - middeer2.addch(1, 3, ord('(')) - middeer2.addch(1, 4, ord('=')) - middeer2.addch(1, 5, ord(')')) - middeer2.addch(1, 6, ord('~')) - middeer2.addch(2, 3, ord('|')) - middeer2.addch(2, 5, ord('|')) - - middeer3.addch(0, 2, ord('y')) - middeer3.addch(0, 3, ord('y')) - middeer3.addch(1, 2, ord('0')) - middeer3.addch(1, 3, ord('(')) - middeer3.addch(1, 4, ord('=')) - middeer3.addch(1, 5, ord(')')) - middeer3.addch(1, 6, ord('~')) - middeer3.addch(2, 3, ord('/')) - middeer3.addch(2, 5, ord('\\')) - - bigdeer1.addch(0, 17, ord('\\')) - bigdeer1.addch(0, 18, ord('/')) - bigdeer1.addch(0, 19, ord('\\')) - bigdeer1.addch(0, 20, ord('/')) - bigdeer1.addch(1, 18, ord('\\')) - bigdeer1.addch(1, 20, ord('/')) - bigdeer1.addch(2, 19, ord('|')) - bigdeer1.addch(2, 20, ord('_')) - bigdeer1.addch(3, 18, ord('/')) - bigdeer1.addch(3, 19, ord('^')) - bigdeer1.addch(3, 20, ord('0')) - bigdeer1.addch(3, 21, ord('\\')) - bigdeer1.addch(4, 17, ord('/')) - bigdeer1.addch(4, 18, ord('/')) - bigdeer1.addch(4, 19, ord('\\')) - bigdeer1.addch(4, 22, ord('\\')) - bigdeer1.addstr(5, 7, "^~~~~~~~~// ~~U") - bigdeer1.addstr(6, 7, "( \\_____( /") # )) - bigdeer1.addstr(7, 8, "( ) /") - bigdeer1.addstr(8, 9, "\\\\ /") - bigdeer1.addstr(9, 11, "\\>/>") - - bigdeer2.addch(0, 17, ord('\\')) - bigdeer2.addch(0, 18, ord('/')) - bigdeer2.addch(0, 19, ord('\\')) - bigdeer2.addch(0, 20, ord('/')) - bigdeer2.addch(1, 18, ord('\\')) - bigdeer2.addch(1, 20, ord('/')) - bigdeer2.addch(2, 19, ord('|')) - bigdeer2.addch(2, 20, ord('_')) - bigdeer2.addch(3, 18, ord('/')) - bigdeer2.addch(3, 19, ord('^')) - bigdeer2.addch(3, 20, ord('0')) - bigdeer2.addch(3, 21, ord('\\')) - bigdeer2.addch(4, 17, ord('/')) - bigdeer2.addch(4, 18, ord('/')) - bigdeer2.addch(4, 19, ord('\\')) - bigdeer2.addch(4, 22, ord('\\')) - bigdeer2.addstr(5, 7, "^~~~~~~~~// ~~U") - bigdeer2.addstr(6, 7, "(( )____( /") # )) - bigdeer2.addstr(7, 7, "( / |") - bigdeer2.addstr(8, 8, "\\/ |") - bigdeer2.addstr(9, 9, "|> |>") - - bigdeer3.addch(0, 17, ord('\\')) - bigdeer3.addch(0, 18, ord('/')) - bigdeer3.addch(0, 19, ord('\\')) - bigdeer3.addch(0, 20, ord('/')) - bigdeer3.addch(1, 18, ord('\\')) - bigdeer3.addch(1, 20, ord('/')) - bigdeer3.addch(2, 19, ord('|')) - bigdeer3.addch(2, 20, ord('_')) - bigdeer3.addch(3, 18, ord('/')) - bigdeer3.addch(3, 19, ord('^')) - bigdeer3.addch(3, 20, ord('0')) - bigdeer3.addch(3, 21, ord('\\')) - bigdeer3.addch(4, 17, ord('/')) - bigdeer3.addch(4, 18, ord('/')) - bigdeer3.addch(4, 19, ord('\\')) - bigdeer3.addch(4, 22, ord('\\')) - bigdeer3.addstr(5, 7, "^~~~~~~~~// ~~U") - bigdeer3.addstr(6, 6, "( ()_____( /") # )) - bigdeer3.addstr(7, 6, "/ / /") - bigdeer3.addstr(8, 5, "|/ \\") - bigdeer3.addstr(9, 5, "/> \\>") - - bigdeer4.addch(0, 17, ord('\\')) - bigdeer4.addch(0, 18, ord('/')) - bigdeer4.addch(0, 19, ord('\\')) - bigdeer4.addch(0, 20, ord('/')) - bigdeer4.addch(1, 18, ord('\\')) - bigdeer4.addch(1, 20, ord('/')) - bigdeer4.addch(2, 19, ord('|')) - bigdeer4.addch(2, 20, ord('_')) - bigdeer4.addch(3, 18, ord('/')) - bigdeer4.addch(3, 19, ord('^')) - bigdeer4.addch(3, 20, ord('0')) - bigdeer4.addch(3, 21, ord('\\')) - bigdeer4.addch(4, 17, ord('/')) - bigdeer4.addch(4, 18, ord('/')) - bigdeer4.addch(4, 19, ord('\\')) - bigdeer4.addch(4, 22, ord('\\')) - bigdeer4.addstr(5, 7, "^~~~~~~~~// ~~U") - bigdeer4.addstr(6, 6, "( )______( /") # ) - bigdeer4.addstr(7, 5, "(/ \\") # ) - bigdeer4.addstr(8, 0, "v___= ----^") - - lookdeer1.addstr(0, 16, "\\/ \\/") - lookdeer1.addstr(1, 17, "\\Y/ \\Y/") - lookdeer1.addstr(2, 19, "\\=/") - lookdeer1.addstr(3, 17, "^\\o o/^") - lookdeer1.addstr(4, 17, "//( )") - lookdeer1.addstr(5, 7, "^~~~~~~~~// \\O/") - lookdeer1.addstr(6, 7, "( \\_____( /") # )) - lookdeer1.addstr(7, 8, "( ) /") - lookdeer1.addstr(8, 9, "\\\\ /") - lookdeer1.addstr(9, 11, "\\>/>") - - lookdeer2.addstr(0, 16, "\\/ \\/") - lookdeer2.addstr(1, 17, "\\Y/ \\Y/") - lookdeer2.addstr(2, 19, "\\=/") - lookdeer2.addstr(3, 17, "^\\o o/^") - lookdeer2.addstr(4, 17, "//( )") - lookdeer2.addstr(5, 7, "^~~~~~~~~// \\O/") - lookdeer2.addstr(6, 7, "(( )____( /") # )) - lookdeer2.addstr(7, 7, "( / |") - lookdeer2.addstr(8, 8, "\\/ |") - lookdeer2.addstr(9, 9, "|> |>") - - lookdeer3.addstr(0, 16, "\\/ \\/") - lookdeer3.addstr(1, 17, "\\Y/ \\Y/") - lookdeer3.addstr(2, 19, "\\=/") - lookdeer3.addstr(3, 17, "^\\o o/^") - lookdeer3.addstr(4, 17, "//( )") - lookdeer3.addstr(5, 7, "^~~~~~~~~// \\O/") - lookdeer3.addstr(6, 6, "( ()_____( /") # )) - lookdeer3.addstr(7, 6, "/ / /") - lookdeer3.addstr(8, 5, "|/ \\") - lookdeer3.addstr(9, 5, "/> \\>") - - lookdeer4.addstr(0, 16, "\\/ \\/") - lookdeer4.addstr(1, 17, "\\Y/ \\Y/") - lookdeer4.addstr(2, 19, "\\=/") - lookdeer4.addstr(3, 17, "^\\o o/^") - lookdeer4.addstr(4, 17, "//( )") - lookdeer4.addstr(5, 7, "^~~~~~~~~// \\O/") - lookdeer4.addstr(6, 6, "( )______( /") # ) - lookdeer4.addstr(7, 5, "(/ \\") # ) - lookdeer4.addstr(8, 0, "v___= ----^") - - ############################################### - curses.cbreak() - stdscr.nodelay(1) - - while 1: - stdscr.clear() - treescrn.erase() - w_del_msg.touchwin() - treescrn.touchwin() - treescrn2.erase() - treescrn2.touchwin() - treescrn8.erase() - treescrn8.touchwin() - stdscr.refresh() - look_out(150) - boxit() - stdscr.refresh() - look_out(150) - seas() - stdscr.refresh() - greet() - stdscr.refresh() - look_out(150) - fromwho() - stdscr.refresh() - look_out(150) - tree() - look_out(150) - balls() - look_out(150) - star() - look_out(150) - strng1() - strng2() - strng3() - strng4() - strng5() - - # set up the windows for our blinking trees - # - # treescrn3 - treescrn.overlay(treescrn3) - - # balls - treescrn3.addch(4, 18, ord(' ')) - treescrn3.addch(7, 6, ord(' ')) - treescrn3.addch(8, 19, ord(' ')) - treescrn3.addch(11, 22, ord(' ')) - - # star - treescrn3.addch(0, 12, ord('*')) - - # strng1 - treescrn3.addch(3, 11, ord(' ')) - - # strng2 - treescrn3.addch(5, 13, ord(' ')) - treescrn3.addch(6, 10, ord(' ')) - - # strng3 - treescrn3.addch(7, 16, ord(' ')) - treescrn3.addch(7, 14, ord(' ')) - - # strng4 - treescrn3.addch(10, 13, ord(' ')) - treescrn3.addch(10, 10, ord(' ')) - treescrn3.addch(11, 8, ord(' ')) - - # strng5 - treescrn3.addch(11, 18, ord(' ')) - treescrn3.addch(12, 13, ord(' ')) - - # treescrn4 - treescrn.overlay(treescrn4) - - # balls - treescrn4.addch(3, 9, ord(' ')) - treescrn4.addch(4, 16, ord(' ')) - treescrn4.addch(7, 6, ord(' ')) - treescrn4.addch(8, 19, ord(' ')) - treescrn4.addch(11, 2, ord(' ')) - treescrn4.addch(12, 23, ord(' ')) - - # star - treescrn4.standout() - treescrn4.addch(0, 12, ord('*')) - treescrn4.standend() - - # strng1 - treescrn4.addch(3, 13, ord(' ')) - - # strng2 - - # strng3 - treescrn4.addch(7, 15, ord(' ')) - treescrn4.addch(8, 11, ord(' ')) - - # strng4 - treescrn4.addch(9, 16, ord(' ')) - treescrn4.addch(10, 12, ord(' ')) - treescrn4.addch(11, 8, ord(' ')) - - # strng5 - treescrn4.addch(11, 18, ord(' ')) - treescrn4.addch(12, 14, ord(' ')) - - # treescrn5 - treescrn.overlay(treescrn5) - - # balls - treescrn5.addch(3, 15, ord(' ')) - treescrn5.addch(10, 20, ord(' ')) - treescrn5.addch(12, 1, ord(' ')) - - # star - treescrn5.addch(0, 12, ord(' ')) - - # strng1 - treescrn5.addch(3, 11, ord(' ')) - - # strng2 - treescrn5.addch(5, 12, ord(' ')) - - # strng3 - treescrn5.addch(7, 14, ord(' ')) - treescrn5.addch(8, 10, ord(' ')) - - # strng4 - treescrn5.addch(9, 15, ord(' ')) - treescrn5.addch(10, 11, ord(' ')) - treescrn5.addch(11, 7, ord(' ')) - - # strng5 - treescrn5.addch(11, 17, ord(' ')) - treescrn5.addch(12, 13, ord(' ')) - - # treescrn6 - treescrn.overlay(treescrn6) - - # balls - treescrn6.addch(6, 7, ord(' ')) - treescrn6.addch(7, 18, ord(' ')) - treescrn6.addch(10, 4, ord(' ')) - treescrn6.addch(11, 23, ord(' ')) - - # star - treescrn6.standout() - treescrn6.addch(0, 12, ord('*')) - treescrn6.standend() - - # strng1 - - # strng2 - treescrn6.addch(5, 11, ord(' ')) - - # strng3 - treescrn6.addch(7, 13, ord(' ')) - treescrn6.addch(8, 9, ord(' ')) - - # strng4 - treescrn6.addch(9, 14, ord(' ')) - treescrn6.addch(10, 10, ord(' ')) - treescrn6.addch(11, 6, ord(' ')) - - # strng5 - treescrn6.addch(11, 16, ord(' ')) - treescrn6.addch(12, 12, ord(' ')) - - # treescrn7 - - treescrn.overlay(treescrn7) - - # balls - treescrn7.addch(3, 15, ord(' ')) - treescrn7.addch(6, 7, ord(' ')) - treescrn7.addch(7, 18, ord(' ')) - treescrn7.addch(10, 4, ord(' ')) - treescrn7.addch(11, 22, ord(' ')) - - # star - treescrn7.addch(0, 12, ord('*')) - - # strng1 - treescrn7.addch(3, 12, ord(' ')) - - # strng2 - treescrn7.addch(5, 13, ord(' ')) - treescrn7.addch(6, 9, ord(' ')) - - # strng3 - treescrn7.addch(7, 15, ord(' ')) - treescrn7.addch(8, 11, ord(' ')) - - # strng4 - treescrn7.addch(9, 16, ord(' ')) - treescrn7.addch(10, 12, ord(' ')) - treescrn7.addch(11, 8, ord(' ')) - - # strng5 - treescrn7.addch(11, 18, ord(' ')) - treescrn7.addch(12, 14, ord(' ')) - - look_out(150) - reindeer() - - w_holiday.touchwin() - w_holiday.refresh() - w_del_msg.refresh() - - look_out(500) - for i in range(0, 20): - blinkit() - -curses.wrapper(main) diff --git a/Demo/dns/README b/Demo/dns/README deleted file mode 100644 index 2f6d751f9d..0000000000 --- a/Demo/dns/README +++ /dev/null @@ -1,16 +0,0 @@ -This directory contains a module (dnslib) that implements a DNS -(Domain Name Server) client, plus additional modules that define some -symbolic constants used by DNS (dnstype, dnsclass, dnsopcode). - -Type "python dnslib.py -/" for a usage message. - -You can also import dnslib and write your own, more sophisticated -client code; use the test program as an example (there is currently no -documentation :-). - -Anthony Baxter maintains an enhanced version of this code at - - http://alumni.dgs.monash.edu.au/~anthony/python/ - ---Guido van Rossum, CWI, Amsterdam -URL: diff --git a/Demo/dns/asgethost.py b/Demo/dns/asgethost.py deleted file mode 100755 index 2e9185a13e..0000000000 --- a/Demo/dns/asgethost.py +++ /dev/null @@ -1,35 +0,0 @@ -import sys -import dnslib -import dnstype -import dnsopcode -import dnsclass -import socket -import select - -def main(): - server = 'cnri.reston.va.us' # How? - port = 53 - opcode = dnsopcode.QUERY - rd = 0 - qtype = dnstype.MX - qname = sys.argv[1:] and sys.argv[1] or 'www.python.org' - m = dnslib.Mpacker() - m.addHeader(0, - 0, opcode, 0, 0, rd, 0, 0, 0, - 1, 0, 0, 0) - m.addQuestion(qname, qtype, dnsclass.IN) - request = m.getbuf() - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.connect((server, port)) - s.send(request) - while 1: - r, w, x = [s], [], [] - r, w, x = select.select(r, w, x, 0.333) - print r, w, x - if r: - reply = s.recv(1024) - u = dnslib.Munpacker(reply) - dnslib.dumpM(u) - break - -main() diff --git a/Demo/dns/dnsclass.py b/Demo/dns/dnsclass.py deleted file mode 100755 index f90b9e8460..0000000000 --- a/Demo/dns/dnsclass.py +++ /dev/null @@ -1,23 +0,0 @@ -# CLASS values (section 3.2.4) - -IN = 1 # the Internet -CS = 2 # the CSNET class (Obsolete - used only for examples in - # some obsolete RFCs) -CH = 3 # the CHAOS class -HS = 4 # Hesiod [Dyer 87] - -# QCLASS values (section 3.2.5) - -ANY = 255 # any class - - -# Construct reverse mapping dictionary - -_names = dir() -classmap = {} -for _name in _names: - if _name[0] != '_': classmap[eval(_name)] = _name - -def classstr(klass): - if classmap.has_key(klass): return classmap[klass] - else: return `klass` diff --git a/Demo/dns/dnslib.py b/Demo/dns/dnslib.py deleted file mode 100755 index 4e1fb87b2c..0000000000 --- a/Demo/dns/dnslib.py +++ /dev/null @@ -1,588 +0,0 @@ -# Domain Name Server (DNS) interface -# -# See RFC 1035: -# ------------------------------------------------------------------------ -# Network Working Group P. Mockapetris -# Request for Comments: 1035 ISI -# November 1987 -# Obsoletes: RFCs 882, 883, 973 -# -# DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION -# ------------------------------------------------------------------------ - - -import string - -import dnstype -import dnsclass -import dnsopcode - - -# Low-level 16 and 32 bit integer packing and unpacking - -def pack16bit(n): - return chr((n>>8)&0xFF) + chr(n&0xFF) - -def pack32bit(n): - return chr((n>>24)&0xFF) + chr((n>>16)&0xFF) \ - + chr((n>>8)&0xFF) + chr(n&0xFF) - -def unpack16bit(s): - return (ord(s[0])<<8) | ord(s[1]) - -def unpack32bit(s): - return (ord(s[0])<<24) | (ord(s[1])<<16) \ - | (ord(s[2])<<8) | ord(s[3]) - -def addr2bin(addr): - if type(addr) == type(0): - return addr - bytes = string.splitfields(addr, '.') - if len(bytes) != 4: raise ValueError, 'bad IP address' - n = 0 - for byte in bytes: n = n<<8 | string.atoi(byte) - return n - -def bin2addr(n): - return '%d.%d.%d.%d' % ((n>>24)&0xFF, (n>>16)&0xFF, - (n>>8)&0xFF, n&0xFF) - - -# Packing class - -class Packer: - def __init__(self): - self.buf = '' - self.index = {} - def getbuf(self): - return self.buf - def addbyte(self, c): - if len(c) != 1: raise TypeError, 'one character expected' - self.buf = self.buf + c - def addbytes(self, bytes): - self.buf = self.buf + bytes - def add16bit(self, n): - self.buf = self.buf + pack16bit(n) - def add32bit(self, n): - self.buf = self.buf + pack32bit(n) - def addaddr(self, addr): - n = addr2bin(addr) - self.buf = self.buf + pack32bit(n) - def addstring(self, s): - self.addbyte(chr(len(s))) - self.addbytes(s) - def addname(self, name): - # Domain name packing (section 4.1.4) - # Add a domain name to the buffer, possibly using pointers. - # The case of the first occurrence of a name is preserved. - # Redundant dots are ignored. - list = [] - for label in string.splitfields(name, '.'): - if label: - if len(label) > 63: - raise PackError, 'label too long' - list.append(label) - keys = [] - for i in range(len(list)): - key = string.upper(string.joinfields(list[i:], '.')) - keys.append(key) - if self.index.has_key(key): - pointer = self.index[key] - break - else: - i = len(list) - pointer = None - # Do it into temporaries first so exceptions don't - # mess up self.index and self.buf - buf = '' - offset = len(self.buf) - index = [] - for j in range(i): - label = list[j] - n = len(label) - if offset + len(buf) < 0x3FFF: - index.append( (keys[j], offset + len(buf)) ) - else: - print 'dnslib.Packer.addname:', - print 'warning: pointer too big' - buf = buf + (chr(n) + label) - if pointer: - buf = buf + pack16bit(pointer | 0xC000) - else: - buf = buf + '\0' - self.buf = self.buf + buf - for key, value in index: - self.index[key] = value - def dump(self): - keys = self.index.keys() - keys.sort() - print '-'*40 - for key in keys: - print '%20s %3d' % (key, self.index[key]) - print '-'*40 - space = 1 - for i in range(0, len(self.buf)+1, 2): - if self.buf[i:i+2] == '**': - if not space: print - space = 1 - continue - space = 0 - print '%4d' % i, - for c in self.buf[i:i+2]: - if ' ' < c < '\177': - print ' %c' % c, - else: - print '%2d' % ord(c), - print - print '-'*40 - - -# Unpacking class - -UnpackError = 'dnslib.UnpackError' # Exception - -class Unpacker: - def __init__(self, buf): - self.buf = buf - self.offset = 0 - def getbyte(self): - c = self.buf[self.offset] - self.offset = self.offset + 1 - return c - def getbytes(self, n): - s = self.buf[self.offset : self.offset + n] - if len(s) != n: raise UnpackError, 'not enough data left' - self.offset = self.offset + n - return s - def get16bit(self): - return unpack16bit(self.getbytes(2)) - def get32bit(self): - return unpack32bit(self.getbytes(4)) - def getaddr(self): - return bin2addr(self.get32bit()) - def getstring(self): - return self.getbytes(ord(self.getbyte())) - def getname(self): - # Domain name unpacking (section 4.1.4) - c = self.getbyte() - i = ord(c) - if i & 0xC0 == 0xC0: - d = self.getbyte() - j = ord(d) - pointer = ((i<<8) | j) & ~0xC000 - save_offset = self.offset - try: - self.offset = pointer - domain = self.getname() - finally: - self.offset = save_offset - return domain - if i == 0: - return '' - domain = self.getbytes(i) - remains = self.getname() - if not remains: - return domain - else: - return domain + '.' + remains - - -# Test program for packin/unpacking (section 4.1.4) - -def testpacker(): - N = 25 - R = range(N) - import timing - # See section 4.1.4 of RFC 1035 - timing.start() - for i in R: - p = Packer() - p.addbytes('*' * 20) - p.addname('f.ISI.ARPA') - p.addbytes('*' * 8) - p.addname('Foo.F.isi.arpa') - p.addbytes('*' * 18) - p.addname('arpa') - p.addbytes('*' * 26) - p.addname('') - timing.finish() - print round(timing.milli() * 0.001 / N, 3), 'seconds per packing' - p.dump() - u = Unpacker(p.buf) - u.getbytes(20) - u.getname() - u.getbytes(8) - u.getname() - u.getbytes(18) - u.getname() - u.getbytes(26) - u.getname() - timing.start() - for i in R: - u = Unpacker(p.buf) - res = (u.getbytes(20), - u.getname(), - u.getbytes(8), - u.getname(), - u.getbytes(18), - u.getname(), - u.getbytes(26), - u.getname()) - timing.finish() - print round(timing.milli() * 0.001 / N, 3), 'seconds per unpacking' - for item in res: print item - - -# Pack/unpack RR toplevel format (section 3.2.1) - -class RRpacker(Packer): - def __init__(self): - Packer.__init__(self) - self.rdstart = None - def addRRheader(self, name, type, klass, ttl, *rest): - self.addname(name) - self.add16bit(type) - self.add16bit(klass) - self.add32bit(ttl) - if rest: - if res[1:]: raise TypeError, 'too many args' - rdlength = rest[0] - else: - rdlength = 0 - self.add16bit(rdlength) - self.rdstart = len(self.buf) - def patchrdlength(self): - rdlength = unpack16bit(self.buf[self.rdstart-2:self.rdstart]) - if rdlength == len(self.buf) - self.rdstart: - return - rdata = self.buf[self.rdstart:] - save_buf = self.buf - ok = 0 - try: - self.buf = self.buf[:self.rdstart-2] - self.add16bit(len(rdata)) - self.buf = self.buf + rdata - ok = 1 - finally: - if not ok: self.buf = save_buf - def endRR(self): - if self.rdstart is not None: - self.patchrdlength() - self.rdstart = None - def getbuf(self): - if self.rdstart is not None: self.patchrdlenth() - return Packer.getbuf(self) - # Standard RRs (section 3.3) - def addCNAME(self, name, klass, ttl, cname): - self.addRRheader(name, dnstype.CNAME, klass, ttl) - self.addname(cname) - self.endRR() - def addHINFO(self, name, klass, ttl, cpu, os): - self.addRRheader(name, dnstype.HINFO, klass, ttl) - self.addstring(cpu) - self.addstring(os) - self.endRR() - def addMX(self, name, klass, ttl, preference, exchange): - self.addRRheader(name, dnstype.MX, klass, ttl) - self.add16bit(preference) - self.addname(exchange) - self.endRR() - def addNS(self, name, klass, ttl, nsdname): - self.addRRheader(name, dnstype.NS, klass, ttl) - self.addname(nsdname) - self.endRR() - def addPTR(self, name, klass, ttl, ptrdname): - self.addRRheader(name, dnstype.PTR, klass, ttl) - self.addname(ptrdname) - self.endRR() - def addSOA(self, name, klass, ttl, - mname, rname, serial, refresh, retry, expire, minimum): - self.addRRheader(name, dnstype.SOA, klass, ttl) - self.addname(mname) - self.addname(rname) - self.add32bit(serial) - self.add32bit(refresh) - self.add32bit(retry) - self.add32bit(expire) - self.add32bit(minimum) - self.endRR() - def addTXT(self, name, klass, ttl, list): - self.addRRheader(name, dnstype.TXT, klass, ttl) - for txtdata in list: - self.addstring(txtdata) - self.endRR() - # Internet specific RRs (section 3.4) -- class = IN - def addA(self, name, ttl, address): - self.addRRheader(name, dnstype.A, dnsclass.IN, ttl) - self.addaddr(address) - self.endRR() - def addWKS(self, name, ttl, address, protocol, bitmap): - self.addRRheader(name, dnstype.WKS, dnsclass.IN, ttl) - self.addaddr(address) - self.addbyte(chr(protocol)) - self.addbytes(bitmap) - self.endRR() - - -class RRunpacker(Unpacker): - def __init__(self, buf): - Unpacker.__init__(self, buf) - self.rdend = None - def getRRheader(self): - name = self.getname() - type = self.get16bit() - klass = self.get16bit() - ttl = self.get32bit() - rdlength = self.get16bit() - self.rdend = self.offset + rdlength - return (name, type, klass, ttl, rdlength) - def endRR(self): - if self.offset != self.rdend: - raise UnpackError, 'end of RR not reached' - def getCNAMEdata(self): - return self.getname() - def getHINFOdata(self): - return self.getstring(), self.getstring() - def getMXdata(self): - return self.get16bit(), self.getname() - def getNSdata(self): - return self.getname() - def getPTRdata(self): - return self.getname() - def getSOAdata(self): - return self.getname(), \ - self.getname(), \ - self.get32bit(), \ - self.get32bit(), \ - self.get32bit(), \ - self.get32bit(), \ - self.get32bit() - def getTXTdata(self): - list = [] - while self.offset != self.rdend: - list.append(self.getstring()) - return list - def getAdata(self): - return self.getaddr() - def getWKSdata(self): - address = self.getaddr() - protocol = ord(self.getbyte()) - bitmap = self.getbytes(self.rdend - self.offset) - return address, protocol, bitmap - - -# Pack/unpack Message Header (section 4.1) - -class Hpacker(Packer): - def addHeader(self, id, qr, opcode, aa, tc, rd, ra, z, rcode, - qdcount, ancount, nscount, arcount): - self.add16bit(id) - self.add16bit((qr&1)<<15 | (opcode*0xF)<<11 | (aa&1)<<10 - | (tc&1)<<9 | (rd&1)<<8 | (ra&1)<<7 - | (z&7)<<4 | (rcode&0xF)) - self.add16bit(qdcount) - self.add16bit(ancount) - self.add16bit(nscount) - self.add16bit(arcount) - -class Hunpacker(Unpacker): - def getHeader(self): - id = self.get16bit() - flags = self.get16bit() - qr, opcode, aa, tc, rd, ra, z, rcode = ( - (flags>>15)&1, - (flags>>11)&0xF, - (flags>>10)&1, - (flags>>9)&1, - (flags>>8)&1, - (flags>>7)&1, - (flags>>4)&7, - (flags>>0)&0xF) - qdcount = self.get16bit() - ancount = self.get16bit() - nscount = self.get16bit() - arcount = self.get16bit() - return (id, qr, opcode, aa, tc, rd, ra, z, rcode, - qdcount, ancount, nscount, arcount) - - -# Pack/unpack Question (section 4.1.2) - -class Qpacker(Packer): - def addQuestion(self, qname, qtype, qclass): - self.addname(qname) - self.add16bit(qtype) - self.add16bit(qclass) - -class Qunpacker(Unpacker): - def getQuestion(self): - return self.getname(), self.get16bit(), self.get16bit() - - -# Pack/unpack Message(section 4) -# NB the order of the base classes is important for __init__()! - -class Mpacker(RRpacker, Qpacker, Hpacker): - pass - -class Munpacker(RRunpacker, Qunpacker, Hunpacker): - pass - - -# Routines to print an unpacker to stdout, for debugging. -# These affect the unpacker's current position! - -def dumpM(u): - print 'HEADER:', - (id, qr, opcode, aa, tc, rd, ra, z, rcode, - qdcount, ancount, nscount, arcount) = u.getHeader() - print 'id=%d,' % id, - print 'qr=%d, opcode=%d, aa=%d, tc=%d, rd=%d, ra=%d, z=%d, rcode=%d,' \ - % (qr, opcode, aa, tc, rd, ra, z, rcode) - if tc: print '*** response truncated! ***' - if rcode: print '*** nonzero error code! (%d) ***' % rcode - print ' qdcount=%d, ancount=%d, nscount=%d, arcount=%d' \ - % (qdcount, ancount, nscount, arcount) - for i in range(qdcount): - print 'QUESTION %d:' % i, - dumpQ(u) - for i in range(ancount): - print 'ANSWER %d:' % i, - dumpRR(u) - for i in range(nscount): - print 'AUTHORITY RECORD %d:' % i, - dumpRR(u) - for i in range(arcount): - print 'ADDITIONAL RECORD %d:' % i, - dumpRR(u) - -def dumpQ(u): - qname, qtype, qclass = u.getQuestion() - print 'qname=%s, qtype=%d(%s), qclass=%d(%s)' \ - % (qname, - qtype, dnstype.typestr(qtype), - qclass, dnsclass.classstr(qclass)) - -def dumpRR(u): - name, type, klass, ttl, rdlength = u.getRRheader() - typename = dnstype.typestr(type) - print 'name=%s, type=%d(%s), class=%d(%s), ttl=%d' \ - % (name, - type, typename, - klass, dnsclass.classstr(klass), - ttl) - mname = 'get%sdata' % typename - if hasattr(u, mname): - print ' formatted rdata:', getattr(u, mname)() - else: - print ' binary rdata:', u.getbytes(rdlength) - - -# Test program - -def test(): - import sys - import getopt - import socket - protocol = 'udp' - server = 'cnri.reston.va.us' # XXX adapt this to your local - port = 53 - opcode = dnsopcode.QUERY - rd = 0 - qtype = dnstype.MX - qname = 'cwi.nl' - try: - opts, args = getopt.getopt(sys.argv[1:], 'Trs:tu') - if len(args) > 2: raise getopt.error, 'too many arguments' - except getopt.error, msg: - print msg - print 'Usage: python dnslib.py', - print '[-T] [-r] [-s server] [-t] [-u]', - print '[qtype [qname]]' - print '-T: run testpacker() and exit' - print '-r: recursion desired (default not)' - print '-s server: use server (default %s)' % server - print '-t: use TCP protocol' - print '-u: use UDP protocol (default)' - print 'qtype: query type (default %s)' % \ - dnstype.typestr(qtype) - print 'qname: query name (default %s)' % qname - print 'Recognized qtype values:' - qtypes = dnstype.typemap.keys() - qtypes.sort() - n = 0 - for qtype in qtypes: - n = n+1 - if n >= 8: n = 1; print - print '%s = %d' % (dnstype.typemap[qtype], qtype), - print - sys.exit(2) - for o, a in opts: - if o == '-T': testpacker(); return - if o == '-t': protocol = 'tcp' - if o == '-u': protocol = 'udp' - if o == '-s': server = a - if o == '-r': rd = 1 - if args[0:]: - try: - qtype = eval(string.upper(args[0]), dnstype.__dict__) - except (NameError, SyntaxError): - print 'bad query type:', `args[0]` - sys.exit(2) - if args[1:]: - qname = args[1] - if qtype == dnstype.AXFR: - print 'Query type AXFR, protocol forced to TCP' - protocol = 'tcp' - print 'QTYPE %d(%s)' % (qtype, dnstype.typestr(qtype)) - m = Mpacker() - m.addHeader(0, - 0, opcode, 0, 0, rd, 0, 0, 0, - 1, 0, 0, 0) - m.addQuestion(qname, qtype, dnsclass.IN) - request = m.getbuf() - if protocol == 'udp': - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.connect((server, port)) - s.send(request) - reply = s.recv(1024) - else: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.connect((server, port)) - s.send(pack16bit(len(request)) + request) - s.shutdown(1) - f = s.makefile('r') - header = f.read(2) - if len(header) < 2: - print '*** EOF ***' - return - count = unpack16bit(header) - reply = f.read(count) - if len(reply) != count: - print '*** Incomplete reply ***' - return - u = Munpacker(reply) - dumpM(u) - if protocol == 'tcp' and qtype == dnstype.AXFR: - while 1: - header = f.read(2) - if len(header) < 2: - print '========== EOF ==========' - break - count = unpack16bit(header) - if not count: - print '========== ZERO COUNT ==========' - break - print '========== NEXT ==========' - reply = f.read(count) - if len(reply) != count: - print '*** Incomplete reply ***' - break - u = Munpacker(reply) - dumpM(u) - - -# Run test program when called as a script - -if __name__ == '__main__': - test() diff --git a/Demo/dns/dnsopcode.py b/Demo/dns/dnsopcode.py deleted file mode 100755 index f2e7cd5b0a..0000000000 --- a/Demo/dns/dnsopcode.py +++ /dev/null @@ -1,16 +0,0 @@ -# Opcode values in message header (section 4.1.1) - -QUERY = 0 -IQUERY = 1 -STATUS = 2 - -# Construct reverse mapping dictionary - -_names = dir() -opcodemap = {} -for _name in _names: - if _name[0] != '_': opcodemap[eval(_name)] = _name - -def opcodestr(opcode): - if opcodemap.has_key(opcode): return opcodemap[opcode] - else: return `opcode` diff --git a/Demo/dns/dnstype.py b/Demo/dns/dnstype.py deleted file mode 100755 index 80c2b76c45..0000000000 --- a/Demo/dns/dnstype.py +++ /dev/null @@ -1,41 +0,0 @@ -# TYPE values (section 3.2.2) - -A = 1 # a host address -NS = 2 # an authoritative name server -MD = 3 # a mail destination (Obsolete - use MX) -MF = 4 # a mail forwarder (Obsolete - use MX) -CNAME = 5 # the canonical name for an alias -SOA = 6 # marks the start of a zone of authority -MB = 7 # a mailbox domain name (EXPERIMENTAL) -MG = 8 # a mail group member (EXPERIMENTAL) -MR = 9 # a mail rename domain name (EXPERIMENTAL) -NULL = 10 # a null RR (EXPERIMENTAL) -WKS = 11 # a well known service description -PTR = 12 # a domain name pointer -HINFO = 13 # host information -MINFO = 14 # mailbox or mail list information -MX = 15 # mail exchange -TXT = 16 # text strings - -# Additional TYPE values from host.c source - -UNAME = 110 -MP = 240 - -# QTYPE values (section 3.2.3) - -AXFR = 252 # A request for a transfer of an entire zone -MAILB = 253 # A request for mailbox-related records (MB, MG or MR) -MAILA = 254 # A request for mail agent RRs (Obsolete - see MX) -ANY = 255 # A request for all records - -# Construct reverse mapping dictionary - -_names = dir() -typemap = {} -for _name in _names: - if _name[0] != '_': typemap[eval(_name)] = _name - -def typestr(type): - if typemap.has_key(type): return typemap[type] - else: return `type` diff --git a/Demo/embed/.cvsignore b/Demo/embed/.cvsignore deleted file mode 100644 index fb98617eb9..0000000000 --- a/Demo/embed/.cvsignore +++ /dev/null @@ -1,3 +0,0 @@ -demo -loop -importexc diff --git a/Demo/embed/Makefile b/Demo/embed/Makefile deleted file mode 100644 index ebc274fa7b..0000000000 --- a/Demo/embed/Makefile +++ /dev/null @@ -1,56 +0,0 @@ -# Makefile for embedded Python use demo. -# (This version tailored for my Red Hat Linux 6.1 setup; -# edit lines marked with XXX.) - -# XXX The compiler you are using -CC= gcc - -# XXX Top of the build tree and source tree -blddir= ../.. -srcdir= ../.. - -# Python version -VERSION= 2.1 - -# Compiler flags -OPT= -g -INCLUDES= -I$(srcdir)/Include -I$(blddir) -CFLAGS= $(OPT) $(INCLUDES) - -# The Python library -LIBPYTHON= $(blddir)/libpython$(VERSION).a - -# XXX edit LIBS (in particular) to match $(blddir)/Modules/Makefile -LIBS= -lnsl -ldl -lreadline -ltermcap -lieee -lpthread -lutil -LDFLAGS= -Xlinker -export-dynamic -SYSLIBS= -lm -MODLIBS= -ALLLIBS= $(LIBPYTHON) $(MODLIBS) $(LIBS) $(SYSLIBS) - -# Build the demo application -all: demo loop importexc -demo: demo.o - $(CC) $(LDFLAGS) demo.o $(ALLLIBS) -o demo - -loop: loop.o - $(CC) $(LDFLAGS) loop.o $(ALLLIBS) -o loop - -importexc: importexc.o - $(CC) $(LDFLAGS) importexc.o $(ALLLIBS) -o importexc - -# Administrative targets - -test: demo - ./demo - -COMMAND="print 'hello world'" -looptest: loop - ./loop $(COMMAND) - -clean: - -rm -f *.o core - -clobber: clean - -rm -f *~ @* '#'* demo loop importexc - -realclean: clobber diff --git a/Demo/embed/README b/Demo/embed/README deleted file mode 100644 index a0f7af8439..0000000000 --- a/Demo/embed/README +++ /dev/null @@ -1,19 +0,0 @@ -This directory show how to embed the Python interpreter in your own -application. The file demo.c shows you all that is needed in your C -code. - -To build it, you may have to edit the Makefile: - -1) set blddir to the directory where you built Python, if it isn't in -the source directory (../..) - -2) change the variables that together define the list of libraries -(MODLIBS, LIBS, SYSLIBS) to link with, to match their definitions in -$(blddir)/Modules/Makefile - -An additional test program, loop.c, is used to experiment with memory -leakage caused by repeated initialization and finalization of the -interpreter. It can be build by saying "make loop" and tested with -"make looptest". Command line usage is "./loop ", -e.g. "./loop 'print 2+2'" should spit out an endless number of lines -containing the number 4. diff --git a/Demo/embed/demo.c b/Demo/embed/demo.c deleted file mode 100644 index 581365f36e..0000000000 --- a/Demo/embed/demo.c +++ /dev/null @@ -1,66 +0,0 @@ -/* Example of embedding Python in another program */ - -#include "Python.h" - -void initxyzzy(void); /* Forward */ - -main(int argc, char **argv) -{ - /* Pass argv[0] to the Python interpreter */ - Py_SetProgramName(argv[0]); - - /* Initialize the Python interpreter. Required. */ - Py_Initialize(); - - /* Add a static module */ - initxyzzy(); - - /* Define sys.argv. It is up to the application if you - want this; you can also let it undefined (since the Python - code is generally not a main program it has no business - touching sys.argv...) */ - PySys_SetArgv(argc, argv); - - /* Do some application specific code */ - printf("Hello, brave new world\n\n"); - - /* Execute some Python statements (in module __main__) */ - PyRun_SimpleString("import sys\n"); - PyRun_SimpleString("print sys.builtin_module_names\n"); - PyRun_SimpleString("print sys.modules.keys()\n"); - PyRun_SimpleString("print sys.executable\n"); - PyRun_SimpleString("print sys.argv\n"); - - /* Note that you can call any public function of the Python - interpreter here, e.g. call_object(). */ - - /* Some more application specific code */ - printf("\nGoodbye, cruel world\n"); - - /* Exit, cleaning up the interpreter */ - Py_Exit(0); - /*NOTREACHED*/ -} - -/* A static module */ - -/* 'self' is not used */ -static PyObject * -xyzzy_foo(PyObject *self, PyObject* args) -{ - if (!PyArg_ParseTuple(args, "")) - return NULL; - return PyInt_FromLong(42L); -} - -static PyMethodDef xyzzy_methods[] = { - {"foo", xyzzy_foo, 1}, - {NULL, NULL} /* sentinel */ -}; - -void -initxyzzy(void) -{ - PyImport_AddModule("xyzzy"); - Py_InitModule("xyzzy", xyzzy_methods); -} diff --git a/Demo/embed/importexc.c b/Demo/embed/importexc.c deleted file mode 100644 index 375ce1b686..0000000000 --- a/Demo/embed/importexc.c +++ /dev/null @@ -1,17 +0,0 @@ -#include - -char* cmd = "import exceptions"; - -int main() -{ - Py_Initialize(); - PyEval_InitThreads(); - PyRun_SimpleString(cmd); - Py_EndInterpreter(PyThreadState_Get()); - - Py_NewInterpreter(); - PyRun_SimpleString(cmd); - Py_Finalize(); - - return 0; -} diff --git a/Demo/embed/loop.c b/Demo/embed/loop.c deleted file mode 100644 index d5af82986d..0000000000 --- a/Demo/embed/loop.c +++ /dev/null @@ -1,33 +0,0 @@ -/* Simple program that repeatedly calls Py_Initialize(), does something, and - then calls Py_Finalize(). This should help finding leaks related to - initialization. */ - -#include "Python.h" - -main(int argc, char **argv) -{ - int count = -1; - char *command; - - if (argc < 2 || argc > 3) { - fprintf(stderr, "usage: loop [count]\n"); - exit(2); - } - command = argv[1]; - - if (argc == 3) { - count = atoi(argv[2]); - } - - Py_SetProgramName(argv[0]); - - /* uncomment this if you don't want to load site.py */ - /* Py_NoSiteFlag = 1; */ - - while (count == -1 || --count >= 0 ) { - Py_Initialize(); - PyRun_SimpleString(command); - Py_Finalize(); - } - return 0; -} diff --git a/Demo/extend/README b/Demo/extend/README deleted file mode 100644 index 26daf14548..0000000000 --- a/Demo/extend/README +++ /dev/null @@ -1,16 +0,0 @@ -This directory contains a test and demonstration of the power of the -generic Makefile.pre.in from the Misc directory. There are three -shell scripts. Study the source of the scripts to find out how they -work (it's really easy). - -./make_static Make a static python binary with the xx module - linked in. To test this, run ./python and try to - import xx. - -./make_shared Make a shared module xx. To test this, run the - standard python interpreter in this directory and try - to import xx. - -./make_clean Clean up after either of the above. Note that each - scripts starts by calling this script, to begin with a - clean slate. diff --git a/Demo/extend/make_clean b/Demo/extend/make_clean deleted file mode 100755 index 13203cd186..0000000000 --- a/Demo/extend/make_clean +++ /dev/null @@ -1,5 +0,0 @@ -#! /bin/sh - -# Reset the directory contents. - -rm -f Setup* Makefile* *.c *.o *.a *.so *~ python sedscript diff --git a/Demo/extend/make_shared b/Demo/extend/make_shared deleted file mode 100755 index b5fbe24300..0000000000 --- a/Demo/extend/make_shared +++ /dev/null @@ -1,16 +0,0 @@ -#! /bin/sh - -# This script tests and demonstrates the mechanism for building a -# shared library for an additional extension module using the -# generic Makefile.pre.in from the Misc directory. - -./make_clean - -cp ../../Misc/Makefile.pre.in . -cp ../../Modules/xxmodule.c . -echo '*shared*' >Setup.in -echo xx xxmodule.c >>Setup.in - -make -f Makefile.pre.in boot -make Makefile -make diff --git a/Demo/extend/make_static b/Demo/extend/make_static deleted file mode 100755 index cfa48feafd..0000000000 --- a/Demo/extend/make_static +++ /dev/null @@ -1,15 +0,0 @@ -#! /bin/sh - -# This script tests and demonstrates the mechanism for building a -# static Python binary with an additional extension module using the -# generic Makefile.pre.in from the Misc directory. - -./make_clean - -cp ../../Misc/Makefile.pre.in . -cp ../../Modules/xxmodule.c . -echo xx xxmodule.c >Setup.in - -make -f Makefile.pre.in boot -make Makefile -make static diff --git a/Demo/imputil/importers.py b/Demo/imputil/importers.py deleted file mode 100644 index 864ff02f52..0000000000 --- a/Demo/imputil/importers.py +++ /dev/null @@ -1,248 +0,0 @@ -# -# importers.py -# -# Demonstration subclasses of imputil.Importer -# - -# There should be consideration for the imports below if it is desirable -# to have "all" modules be imported through the imputil system. - -# these are C extensions -import sys -import imp -import struct -import marshal - -# these are .py modules -import imputil -import os - -###################################################################### - -_TupleType = type(()) -_StringType = type('') - -###################################################################### - -# byte-compiled file suffic character -_suffix_char = __debug__ and 'c' or 'o' - -# byte-compiled file suffix -_suffix = '.py' + _suffix_char - -# the C_EXTENSION suffixes -_c_suffixes = filter(lambda x: x[2] == imp.C_EXTENSION, imp.get_suffixes()) - -def _timestamp(pathname): - "Return the file modification time as a Long." - try: - s = os.stat(pathname) - except OSError: - return None - return long(s[8]) - -def _fs_import(dir, modname, fqname): - "Fetch a module from the filesystem." - - pathname = os.path.join(dir, modname) - if os.path.isdir(pathname): - values = { '__pkgdir__' : pathname, '__path__' : [ pathname ] } - ispkg = 1 - pathname = os.path.join(pathname, '__init__') - else: - values = { } - ispkg = 0 - - # look for dynload modules - for desc in _c_suffixes: - file = pathname + desc[0] - try: - fp = open(file, desc[1]) - except IOError: - pass - else: - module = imp.load_module(fqname, fp, file, desc) - values['__file__'] = file - return 0, module, values - - t_py = _timestamp(pathname + '.py') - t_pyc = _timestamp(pathname + _suffix) - if t_py is None and t_pyc is None: - return None - code = None - if t_py is None or (t_pyc is not None and t_pyc >= t_py): - file = pathname + _suffix - f = open(file, 'rb') - if f.read(4) == imp.get_magic(): - t = struct.unpack('., where - can be located using a subclass-specific mechanism and the - is found in the archive using a subclass-specific mechanism. - - This class defines two hooks for subclasses: one to locate an archive - (and possibly return some context for future subfile lookups), and one - to locate subfiles. - """ - - def get_code(self, parent, modname, fqname): - if parent: - # the Importer._finish_import logic ensures that we handle imports - # under the top level module (package / archive). - assert parent.__importer__ == self - - # if a parent "package" is provided, then we are importing a - # sub-file from the archive. - result = self.get_subfile(parent.__archive__, modname) - if result is None: - return None - if isinstance(result, _TupleType): - assert len(result) == 2 - return (0,) + result - return 0, result, {} - - # no parent was provided, so the archive should exist somewhere on the - # default "path". - archive = self.get_archive(modname) - if archive is None: - return None - return 1, "", {'__archive__':archive} - - def get_archive(self, modname): - """Get an archive of modules. - - This method should locate an archive and return a value which can be - used by get_subfile to load modules from it. The value may be a simple - pathname, an open file, or a complex object that caches information - for future imports. - - Return None if the archive was not found. - """ - raise RuntimeError, "get_archive not implemented" - - def get_subfile(self, archive, modname): - """Get code from a subfile in the specified archive. - - Given the specified archive (as returned by get_archive()), locate - and return a code object for the specified module name. - - A 2-tuple may be returned, consisting of a code object and a dict - of name/values to place into the target module. - - Return None if the subfile was not found. - """ - raise RuntimeError, "get_subfile not implemented" - - -class PackageArchive(PackageArchiveImporter): - "PackageArchiveImporter subclass that refers to a specific archive." - - def __init__(self, modname, archive_pathname): - self.__modname = modname - self.__path = archive_pathname - - def get_archive(self, modname): - if modname == self.__modname: - return self.__path - return None - - # get_subfile is passed the full pathname of the archive - - -###################################################################### -# -# Emulate the standard directory-based import mechanism -# -class DirectoryImporter(imputil.Importer): - "Importer subclass to emulate the standard importer." - - def __init__(self, dir): - self.dir = dir - - def get_code(self, parent, modname, fqname): - if parent: - dir = parent.__pkgdir__ - else: - dir = self.dir - - # Return the module (and other info) if found in the specified - # directory. Otherwise, return None. - return _fs_import(dir, modname, fqname) - - def __repr__(self): - return '<%s.%s for "%s" at 0x%x>' % (self.__class__.__module__, - self.__class__.__name__, - self.dir, - id(self)) - - -###################################################################### -# -# Emulate the standard path-style import mechanism -# -class PathImporter(imputil.Importer): - def __init__(self, path=sys.path): - self.path = path - - def get_code(self, parent, modname, fqname): - if parent: - # we are looking for a module inside of a specific package - return _fs_import(parent.__pkgdir__, modname, fqname) - - # scan sys.path, looking for the requested module - for dir in self.path: - if isinstance(dir, _StringType): - result = _fs_import(dir, modname, fqname) - if result: - return result - - # not found - return None - -###################################################################### - -def _test_dir(): - "Debug/test function to create DirectoryImporters from sys.path." - imputil.ImportManager().install() - path = sys.path[:] - path.reverse() - for d in path: - sys.path.insert(0, DirectoryImporter(d)) - sys.path.insert(0, imputil.BuiltinImporter()) - -def _test_revamp(): - "Debug/test function for the revamped import system." - imputil.ImportManager().install() - sys.path.insert(0, PathImporter()) - sys.path.insert(0, imputil.BuiltinImporter()) diff --git a/Demo/md5test/README b/Demo/md5test/README deleted file mode 100644 index be7621e464..0000000000 --- a/Demo/md5test/README +++ /dev/null @@ -1,10 +0,0 @@ -This is the Python version of the MD5 test program from the MD5 -Internet Draft (Rivest and Dusse, The MD5 Message-Digest Algorithm, 10 -July 1991). The file "foo" contains the string "abc" with no trailing -newline. - -When called without arguments, it acts as a filter. When called with -"-x", it executes a self-test, and the output should literally match -the output given in the RFC. - -Code by Jan-Hein B\"uhrman after the original in C. diff --git a/Demo/md5test/foo b/Demo/md5test/foo deleted file mode 100755 index f2ba8f84ab..0000000000 --- a/Demo/md5test/foo +++ /dev/null @@ -1 +0,0 @@ -abc \ No newline at end of file diff --git a/Demo/md5test/md5driver.py b/Demo/md5test/md5driver.py deleted file mode 100755 index 326c0cf2a2..0000000000 --- a/Demo/md5test/md5driver.py +++ /dev/null @@ -1,125 +0,0 @@ -import string - -def MDPrint(str): - outstr = '' - for i in str: - o = ord(i) - outstr = outstr \ - + string.hexdigits[(o >> 4) & 0xF] \ - + string.hexdigits[o & 0xF] - print outstr, - - -from time import time - -def makestr(start, end): - result = '' - for i in range(start, end + 1): - result = result + chr(i) - - return result - - -from md5 import md5 - -def MDTimeTrial(): - TEST_BLOCK_SIZE = 1000 - TEST_BLOCKS = 10000 - - TEST_BYTES = TEST_BLOCK_SIZE * TEST_BLOCKS - - # initialize test data, need temporary string filler - - filsiz = 1 << 8 - filler = makestr(0, filsiz-1) - data = filler * (TEST_BLOCK_SIZE / filsiz); - data = data + filler[:(TEST_BLOCK_SIZE % filsiz)] - - del filsiz, filler - - - # start timer - print 'MD5 time trial. Processing', TEST_BYTES, 'characters...' - t1 = time() - - mdContext = md5() - - for i in range(TEST_BLOCKS): - mdContext.update(data) - - str = mdContext.digest() - t2 = time() - - MDPrint(str) - print 'is digest of test input.' - print 'Seconds to process test input:', t2 - t1 - print 'Characters processed per second:', TEST_BYTES / (t2 - t1) - - -def MDString(str): - MDPrint(md5(str).digest()) - print '"' + str + '"' - - -def MDFile(filename): - f = open(filename, 'rb'); - mdContext = md5() - - while 1: - data = f.read(1024) - if not data: - break - mdContext.update(data) - - MDPrint(mdContext.digest()) - print filename - - -import sys - -def MDFilter(): - mdContext = md5() - - while 1: - data = sys.stdin.read(16) - if not data: - break - mdContext.update(data) - - MDPrint(mdContext.digest()) - print - - -def MDTestSuite(): - print 'MD5 test suite results:' - MDString('') - MDString('a') - MDString('abc') - MDString('message digest') - MDString(makestr(ord('a'), ord('z'))) - MDString(makestr(ord('A'), ord('Z')) \ - + makestr(ord('a'), ord('z')) \ - + makestr(ord('0'), ord('9'))) - MDString((makestr(ord('1'), ord('9')) + '0') * 8) - - # Contents of file foo are "abc" - MDFile('foo') - - -from sys import argv - -# I don't wanna use getopt(), since I want to use the same i/f... -def main(): - if len(argv) == 1: - MDFilter() - for arg in argv[1:]: - if arg[:2] == '-s': - MDString(arg[2:]) - elif arg == '-t': - MDTimeTrial() - elif arg == '-x': - MDTestSuite() - else: - MDFile(arg) - -main() diff --git a/Demo/metaclasses/Eiffel.py b/Demo/metaclasses/Eiffel.py deleted file mode 100644 index d9c8a9a0c7..0000000000 --- a/Demo/metaclasses/Eiffel.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Support Eiffel-style preconditions and postconditions. - -For example, - -class C: - def m1(self, arg): - require arg > 0 - return whatever - ensure Result > arg - -can be written (clumsily, I agree) as: - -class C(Eiffel): - def m1(self, arg): - return whatever - def m1_pre(self, arg): - assert arg > 0 - def m1_post(self, Result, arg): - assert Result > arg - -Pre- and post-conditions for a method, being implemented as methods -themselves, are inherited independently from the method. This gives -much of the same effect of Eiffel, where pre- and post-conditions are -inherited when a method is overridden by a derived class. However, -when a derived class in Python needs to extend a pre- or -post-condition, it must manually merge the base class' pre- or -post-condition with that defined in the derived class', for example: - -class D(C): - def m1(self, arg): - return whatever**2 - def m1_post(self, Result, arg): - C.m1_post(self, Result, arg) - assert Result < 100 - -This gives derived classes more freedom but also more responsibility -than in Eiffel, where the compiler automatically takes care of this. - -In Eiffel, pre-conditions combine using contravariance, meaning a -derived class can only make a pre-condition weaker; in Python, this is -up to the derived class. For example, a derived class that takes away -the requirement that arg > 0 could write: - - def m1_pre(self, arg): - pass - -but one could equally write a derived class that makes a stronger -requirement: - - def m1_pre(self, arg): - require arg > 50 - -It would be easy to modify the classes shown here so that pre- and -post-conditions can be disabled (separately, on a per-class basis). - -A different design would have the pre- or post-condition testing -functions return true for success and false for failure. This would -make it possible to implement automatic combination of inherited -and new pre-/post-conditions. All this is left as an exercise to the -reader. - -""" - -from Meta import MetaClass, MetaHelper, MetaMethodWrapper - -class EiffelMethodWrapper(MetaMethodWrapper): - - def __init__(self, func, inst): - MetaMethodWrapper.__init__(self, func, inst) - # Note that the following causes recursive wrappers around - # the pre-/post-condition testing methods. These are harmless - # but inefficient; to avoid them, the lookup must be done - # using the class. - try: - self.pre = getattr(inst, self.__name__ + "_pre") - except AttributeError: - self.pre = None - try: - self.post = getattr(inst, self.__name__ + "_post") - except AttributeError: - self.post = None - - def __call__(self, *args, **kw): - if self.pre: - apply(self.pre, args, kw) - Result = apply(self.func, (self.inst,) + args, kw) - if self.post: - apply(self.post, (Result,) + args, kw) - return Result - -class EiffelHelper(MetaHelper): - __methodwrapper__ = EiffelMethodWrapper - -class EiffelMetaClass(MetaClass): - __helper__ = EiffelHelper - -Eiffel = EiffelMetaClass('Eiffel', (), {}) - - -def _test(): - class C(Eiffel): - def m1(self, arg): - return arg+1 - def m1_pre(self, arg): - assert arg > 0, "precondition for m1 failed" - def m1_post(self, Result, arg): - assert Result > arg - x = C() - x.m1(12) -## x.m1(-1) - -if __name__ == '__main__': - _test() diff --git a/Demo/metaclasses/Enum.py b/Demo/metaclasses/Enum.py deleted file mode 100644 index 13a3ed7d6d..0000000000 --- a/Demo/metaclasses/Enum.py +++ /dev/null @@ -1,169 +0,0 @@ -"""Enumeration metaclass. - -XXX This is very much a work in progress. - -""" - -import string - -class EnumMetaClass: - """Metaclass for enumeration. - - To define your own enumeration, do something like - - class Color(Enum): - red = 1 - green = 2 - blue = 3 - - Now, Color.red, Color.green and Color.blue behave totally - different: they are enumerated values, not integers. - - Enumerations cannot be instantiated; however they can be - subclassed. - - """ - - def __init__(self, name, bases, dict): - """Constructor -- create an enumeration. - - Called at the end of the class statement. The arguments are - the name of the new class, a tuple containing the base - classes, and a dictionary containing everything that was - entered in the class' namespace during execution of the class - statement. In the above example, it would be {'red': 1, - 'green': 2, 'blue': 3}. - - """ - for base in bases: - if base.__class__ is not EnumMetaClass: - raise TypeError, "Enumeration base class must be enumeration" - bases = filter(lambda x: x is not Enum, bases) - self.__name__ = name - self.__bases__ = bases - self.__dict = {} - for key, value in dict.items(): - self.__dict[key] = EnumInstance(name, key, value) - - def __getattr__(self, name): - """Return an enumeration value. - - For example, Color.red returns the value corresponding to red. - - XXX Perhaps the values should be created in the constructor? - - This looks in the class dictionary and if it is not found - there asks the base classes. - - The special attribute __members__ returns the list of names - defined in this class (it does not merge in the names defined - in base classes). - - """ - if name == '__members__': - return self.__dict.keys() - - try: - return self.__dict[name] - except KeyError: - for base in self.__bases__: - try: - return getattr(base, name) - except AttributeError: - continue - - raise AttributeError, name - - def __repr__(self): - s = self.__name__ - if self.__bases__: - s = s + '(' + string.join(map(lambda x: x.__name__, - self.__bases__), ", ") + ')' - if self.__dict: - list = [] - for key, value in self.__dict.items(): - list.append("%s: %s" % (key, int(value))) - s = "%s: {%s}" % (s, string.join(list, ", ")) - return s - - -class EnumInstance: - """Class to represent an enumeration value. - - EnumInstance('Color', 'red', 12) prints as 'Color.red' and behaves - like the integer 12 when compared, but doesn't support arithmetic. - - XXX Should it record the actual enumeration rather than just its - name? - - """ - - def __init__(self, classname, enumname, value): - self.__classname = classname - self.__enumname = enumname - self.__value = value - - def __int__(self): - return self.__value - - def __repr__(self): - return "EnumInstance(%s, %s, %s)" % (`self.__classname`, - `self.__enumname`, - `self.__value`) - - def __str__(self): - return "%s.%s" % (self.__classname, self.__enumname) - - def __cmp__(self, other): - return cmp(self.__value, int(other)) - - -# Create the base class for enumerations. -# It is an empty enumeration. -Enum = EnumMetaClass("Enum", (), {}) - - -def _test(): - - class Color(Enum): - red = 1 - green = 2 - blue = 3 - - print Color.red - print dir(Color) - - print Color.red == Color.red - print Color.red == Color.blue - print Color.red == 1 - print Color.red == 2 - - class ExtendedColor(Color): - white = 0 - orange = 4 - yellow = 5 - purple = 6 - black = 7 - - print ExtendedColor.orange - print ExtendedColor.red - - print Color.red == ExtendedColor.red - - class OtherColor(Enum): - white = 4 - blue = 5 - - class MergedColor(Color, OtherColor): - pass - - print MergedColor.red - print MergedColor.white - - print Color - print ExtendedColor - print OtherColor - print MergedColor - -if __name__ == '__main__': - _test() diff --git a/Demo/metaclasses/Meta.py b/Demo/metaclasses/Meta.py deleted file mode 100644 index 39cbef6266..0000000000 --- a/Demo/metaclasses/Meta.py +++ /dev/null @@ -1,120 +0,0 @@ -"""Generic metaclass. - -XXX This is very much a work in progress. - -""" - -import types - -class MetaMethodWrapper: - - def __init__(self, func, inst): - self.func = func - self.inst = inst - self.__name__ = self.func.__name__ - - def __call__(self, *args, **kw): - return apply(self.func, (self.inst,) + args, kw) - -class MetaHelper: - - __methodwrapper__ = MetaMethodWrapper # For derived helpers to override - - def __helperinit__(self, formalclass): - self.__formalclass__ = formalclass - - def __getattr__(self, name): - # Invoked for any attr not in the instance's __dict__ - try: - raw = self.__formalclass__.__getattr__(name) - except AttributeError: - try: - ga = self.__formalclass__.__getattr__('__usergetattr__') - except (KeyError, AttributeError): - raise AttributeError, name - return ga(self, name) - if type(raw) != types.FunctionType: - return raw - return self.__methodwrapper__(raw, self) - -class MetaClass: - - """A generic metaclass. - - This can be subclassed to implement various kinds of meta-behavior. - - """ - - __helper__ = MetaHelper # For derived metaclasses to override - - __inited = 0 - - def __init__(self, name, bases, dict): - try: - ga = dict['__getattr__'] - except KeyError: - pass - else: - dict['__usergetattr__'] = ga - del dict['__getattr__'] - self.__name__ = name - self.__bases__ = bases - self.__realdict__ = dict - self.__inited = 1 - - def __getattr__(self, name): - try: - return self.__realdict__[name] - except KeyError: - for base in self.__bases__: - try: - return base.__getattr__(name) - except AttributeError: - pass - raise AttributeError, name - - def __setattr__(self, name, value): - if not self.__inited: - self.__dict__[name] = value - else: - self.__realdict__[name] = value - - def __call__(self, *args, **kw): - inst = self.__helper__() - inst.__helperinit__(self) - try: - init = inst.__getattr__('__init__') - except AttributeError: - init = lambda: None - apply(init, args, kw) - return inst - - -Meta = MetaClass('Meta', (), {}) - - -def _test(): - class C(Meta): - def __init__(self, *args): - print "__init__, args =", args - def m1(self, x): - print "m1(x=%s)" %`x` - print C - x = C() - print x - x.m1(12) - class D(C): - def __getattr__(self, name): - if name[:2] == '__': raise AttributeError, name - return "getattr:%s" % name - x = D() - print x.foo - print x._foo -## print x.__foo -## print x.__foo__ - - -if __name__ == '__main__': - _test() - - diff --git a/Demo/metaclasses/Simple.py b/Demo/metaclasses/Simple.py deleted file mode 100644 index 03ed2592ee..0000000000 --- a/Demo/metaclasses/Simple.py +++ /dev/null @@ -1,45 +0,0 @@ -import types - -class Tracing: - def __init__(self, name, bases, namespace): - """Create a new class.""" - self.__name__ = name - self.__bases__ = bases - self.__namespace__ = namespace - def __call__(self): - """Create a new instance.""" - return Instance(self) - -class Instance: - def __init__(self, klass): - self.__klass__ = klass - def __getattr__(self, name): - try: - value = self.__klass__.__namespace__[name] - except KeyError: - raise AttributeError, name - if type(value) is not types.FunctionType: - return value - return BoundMethod(value, self) - -class BoundMethod: - def __init__(self, function, instance): - self.function = function - self.instance = instance - def __call__(self, *args): - print "calling", self.function, "for", self.instance, "with", args - return apply(self.function, (self.instance,) + args) - -Trace = Tracing('Trace', (), {}) - -class MyTracedClass(Trace): - def method1(self, a): - self.a = a - def method2(self): - return self.a - -aninstance = MyTracedClass() - -aninstance.method1(10) - -print aninstance.method2() diff --git a/Demo/metaclasses/Synch.py b/Demo/metaclasses/Synch.py deleted file mode 100644 index df70337924..0000000000 --- a/Demo/metaclasses/Synch.py +++ /dev/null @@ -1,256 +0,0 @@ -"""Synchronization metaclass. - -This metaclass makes it possible to declare synchronized methods. - -""" - -import thread - -# First we need to define a reentrant lock. -# This is generally useful and should probably be in a standard Python -# library module. For now, we in-line it. - -class Lock: - - """Reentrant lock. - - This is a mutex-like object which can be acquired by the same - thread more than once. It keeps a reference count of the number - of times it has been acquired by the same thread. Each acquire() - call must be matched by a release() call and only the last - release() call actually releases the lock for acquisition by - another thread. - - The implementation uses two locks internally: - - __mutex is a short term lock used to protect the instance variables - __wait is the lock for which other threads wait - - A thread intending to acquire both locks should acquire __wait - first. - - The implementation uses two other instance variables, protected by - locking __mutex: - - __tid is the thread ID of the thread that currently has the lock - __count is the number of times the current thread has acquired it - - When the lock is released, __tid is None and __count is zero. - - """ - - def __init__(self): - """Constructor. Initialize all instance variables.""" - self.__mutex = thread.allocate_lock() - self.__wait = thread.allocate_lock() - self.__tid = None - self.__count = 0 - - def acquire(self, flag=1): - """Acquire the lock. - - If the optional flag argument is false, returns immediately - when it cannot acquire the __wait lock without blocking (it - may still block for a little while in order to acquire the - __mutex lock). - - The return value is only relevant when the flag argument is - false; it is 1 if the lock is acquired, 0 if not. - - """ - self.__mutex.acquire() - try: - if self.__tid == thread.get_ident(): - self.__count = self.__count + 1 - return 1 - finally: - self.__mutex.release() - locked = self.__wait.acquire(flag) - if not flag and not locked: - return 0 - try: - self.__mutex.acquire() - assert self.__tid == None - assert self.__count == 0 - self.__tid = thread.get_ident() - self.__count = 1 - return 1 - finally: - self.__mutex.release() - - def release(self): - """Release the lock. - - If this thread doesn't currently have the lock, an assertion - error is raised. - - Only allow another thread to acquire the lock when the count - reaches zero after decrementing it. - - """ - self.__mutex.acquire() - try: - assert self.__tid == thread.get_ident() - assert self.__count > 0 - self.__count = self.__count - 1 - if self.__count == 0: - self.__tid = None - self.__wait.release() - finally: - self.__mutex.release() - - -def _testLock(): - - done = [] - - def f2(lock, done=done): - lock.acquire() - print "f2 running in thread %d\n" % thread.get_ident(), - lock.release() - done.append(1) - - def f1(lock, f2=f2, done=done): - lock.acquire() - print "f1 running in thread %d\n" % thread.get_ident(), - try: - f2(lock) - finally: - lock.release() - done.append(1) - - lock = Lock() - lock.acquire() - f1(lock) # Adds 2 to done - lock.release() - - lock.acquire() - - thread.start_new_thread(f1, (lock,)) # Adds 2 - thread.start_new_thread(f1, (lock, f1)) # Adds 3 - thread.start_new_thread(f2, (lock,)) # Adds 1 - thread.start_new_thread(f2, (lock,)) # Adds 1 - - lock.release() - import time - while len(done) < 9: - print len(done) - time.sleep(0.001) - print len(done) - - -# Now, the Locking metaclass is a piece of cake. -# As an example feature, methods whose name begins with exactly one -# underscore are not synchronized. - -from Meta import MetaClass, MetaHelper, MetaMethodWrapper - -class LockingMethodWrapper(MetaMethodWrapper): - def __call__(self, *args, **kw): - if self.__name__[:1] == '_' and self.__name__[1:] != '_': - return apply(self.func, (self.inst,) + args, kw) - self.inst.__lock__.acquire() - try: - return apply(self.func, (self.inst,) + args, kw) - finally: - self.inst.__lock__.release() - -class LockingHelper(MetaHelper): - __methodwrapper__ = LockingMethodWrapper - def __helperinit__(self, formalclass): - MetaHelper.__helperinit__(self, formalclass) - self.__lock__ = Lock() - -class LockingMetaClass(MetaClass): - __helper__ = LockingHelper - -Locking = LockingMetaClass('Locking', (), {}) - -def _test(): - # For kicks, take away the Locking base class and see it die - class Buffer(Locking): - def __init__(self, initialsize): - assert initialsize > 0 - self.size = initialsize - self.buffer = [None]*self.size - self.first = self.last = 0 - def put(self, item): - # Do we need to grow the buffer? - if (self.last+1) % self.size != self.first: - # Insert the new item - self.buffer[self.last] = item - self.last = (self.last+1) % self.size - return - # Double the buffer size - # First normalize it so that first==0 and last==size-1 - print "buffer =", self.buffer - print "first = %d, last = %d, size = %d" % ( - self.first, self.last, self.size) - if self.first <= self.last: - temp = self.buffer[self.first:self.last] - else: - temp = self.buffer[self.first:] + self.buffer[:self.last] - print "temp =", temp - self.buffer = temp + [None]*(self.size+1) - self.first = 0 - self.last = self.size-1 - self.size = self.size*2 - print "Buffer size doubled to", self.size - print "new buffer =", self.buffer - print "first = %d, last = %d, size = %d" % ( - self.first, self.last, self.size) - self.put(item) # Recursive call to test the locking - def get(self): - # Is the buffer empty? - if self.first == self.last: - raise EOFError # Avoid defining a new exception - item = self.buffer[self.first] - self.first = (self.first+1) % self.size - return item - - def producer(buffer, wait, n=1000): - import time - i = 0 - while i < n: - print "put", i - buffer.put(i) - i = i+1 - print "Producer: done producing", n, "items" - wait.release() - - def consumer(buffer, wait, n=1000): - import time - i = 0 - tout = 0.001 - while i < n: - try: - x = buffer.get() - if x != i: - raise AssertionError, \ - "get() returned %s, expected %s" % (x, i) - print "got", i - i = i+1 - tout = 0.001 - except EOFError: - time.sleep(tout) - tout = tout*2 - print "Consumer: done consuming", n, "items" - wait.release() - - pwait = thread.allocate_lock() - pwait.acquire() - cwait = thread.allocate_lock() - cwait.acquire() - buffer = Buffer(1) - n = 1000 - thread.start_new_thread(consumer, (buffer, cwait, n)) - thread.start_new_thread(producer, (buffer, pwait, n)) - pwait.acquire() - print "Producer done" - cwait.acquire() - print "All done" - print "buffer size ==", len(buffer.buffer) - -if __name__ == '__main__': - _testLock() - _test() diff --git a/Demo/metaclasses/Trace.py b/Demo/metaclasses/Trace.py deleted file mode 100644 index 86e199d602..0000000000 --- a/Demo/metaclasses/Trace.py +++ /dev/null @@ -1,145 +0,0 @@ -"""Tracing metaclass. - -XXX This is very much a work in progress. - -""" - -import types, sys - -class TraceMetaClass: - """Metaclass for tracing. - - Classes defined using this metaclass have an automatic tracing - feature -- by setting the __trace_output__ instance (or class) - variable to a file object, trace messages about all calls are - written to the file. The trace formatting can be changed by - defining a suitable __trace_call__ method. - - """ - - __inited = 0 - - def __init__(self, name, bases, dict): - self.__name__ = name - self.__bases__ = bases - self.__dict = dict - # XXX Can't define __dict__, alas - self.__inited = 1 - - def __getattr__(self, name): - try: - return self.__dict[name] - except KeyError: - for base in self.__bases__: - try: - return base.__getattr__(name) - except AttributeError: - pass - raise AttributeError, name - - def __setattr__(self, name, value): - if not self.__inited: - self.__dict__[name] = value - else: - self.__dict[name] = value - - def __call__(self, *args, **kw): - inst = TracingInstance() - inst.__meta_init__(self) - try: - init = inst.__getattr__('__init__') - except AttributeError: - init = lambda: None - apply(init, args, kw) - return inst - - __trace_output__ = None - -class TracingInstance: - """Helper class to represent an instance of a tracing class.""" - - def __trace_call__(self, fp, fmt, *args): - fp.write((fmt+'\n') % args) - - def __meta_init__(self, klass): - self.__class = klass - - def __getattr__(self, name): - # Invoked for any attr not in the instance's __dict__ - try: - raw = self.__class.__getattr__(name) - except AttributeError: - raise AttributeError, name - if type(raw) != types.FunctionType: - return raw - # It's a function - fullname = self.__class.__name__ + "." + name - if not self.__trace_output__ or name == '__trace_call__': - return NotTracingWrapper(fullname, raw, self) - else: - return TracingWrapper(fullname, raw, self) - -class NotTracingWrapper: - def __init__(self, name, func, inst): - self.__name__ = name - self.func = func - self.inst = inst - def __call__(self, *args, **kw): - return apply(self.func, (self.inst,) + args, kw) - -class TracingWrapper(NotTracingWrapper): - def __call__(self, *args, **kw): - self.inst.__trace_call__(self.inst.__trace_output__, - "calling %s, inst=%s, args=%s, kw=%s", - self.__name__, self.inst, args, kw) - try: - rv = apply(self.func, (self.inst,) + args, kw) - except: - t, v, tb = sys.exc_info() - self.inst.__trace_call__(self.inst.__trace_output__, - "returning from %s with exception %s: %s", - self.__name__, t, v) - raise t, v, tb - else: - self.inst.__trace_call__(self.inst.__trace_output__, - "returning from %s with value %s", - self.__name__, rv) - return rv - -Traced = TraceMetaClass('Traced', (), {'__trace_output__': None}) - - -def _test(): - global C, D - class C(Traced): - def __init__(self, x=0): self.x = x - def m1(self, x): self.x = x - def m2(self, y): return self.x + y - __trace_output__ = sys.stdout - class D(C): - def m2(self, y): print "D.m2(%s)" % `y`; return C.m2(self, y) - __trace_output__ = None - x = C(4321) - print x - print x.x - print x.m1(100) - print x.m1(10) - print x.m2(33) - print x.m1(5) - print x.m2(4000) - print x.x - - print C.__init__ - print C.m2 - print D.__init__ - print D.m2 - - y = D() - print y - print y.m1(10) - print y.m2(100) - print y.x - -if __name__ == '__main__': - _test() - diff --git a/Demo/metaclasses/index.html b/Demo/metaclasses/index.html deleted file mode 100644 index af9caa9f58..0000000000 --- a/Demo/metaclasses/index.html +++ /dev/null @@ -1,605 +0,0 @@ - - - -Metaclasses in Python 1.5 - - - - -

Metaclasses in Python 1.5

-

(A.k.a. The Killer Joke :-)

- -
- -(Postscript: reading this essay is probably not the best way to -understand the metaclass hook described here. See a message posted by Vladimir Marangozov -which may give a gentler introduction to the matter. You may also -want to search Deja News for messages with "metaclass" in the subject -posted to comp.lang.python in July and August 1998.) - -
- -

In previous Python releases (and still in 1.5), there is something -called the ``Don Beaudry hook'', after its inventor and champion. -This allows C extensions to provide alternate class behavior, thereby -allowing the Python class syntax to be used to define other class-like -entities. Don Beaudry has used this in his infamous MESS package; Jim -Fulton has used it in his Extension -Classes package. (It has also been referred to as the ``Don -Beaudry hack,'' but that's a misnomer. There's nothing hackish -about it -- in fact, it is rather elegant and deep, even though -there's something dark to it.) - -

(On first reading, you may want to skip directly to the examples in -the section "Writing Metaclasses in Python" below, unless you want -your head to explode.) - -

- -


- -

Documentation of the Don Beaudry hook has purposefully been kept -minimal, since it is a feature of incredible power, and is easily -abused. Basically, it checks whether the type of the base -class is callable, and if so, it is called to create the new -class. - -

Note the two indirection levels. Take a simple example: - -

-class B:
-    pass
-
-class C(B):
-    pass
-
- -Take a look at the second class definition, and try to fathom ``the -type of the base class is callable.'' - -

(Types are not classes, by the way. See questions 4.2, 4.19 and in -particular 6.22 in the Python FAQ -for more on this topic.) - -

- -

    - -
  • The base class is B; this one's easy.

    - -

  • Since B is a class, its type is ``class''; so the type of the -base class is the type ``class''. This is also known as -types.ClassType, assuming the standard module types has -been imported.

    - -

  • Now is the type ``class'' callable? No, because types (in -core Python) are never callable. Classes are callable (calling a -class creates a new instance) but types aren't.

    - -

- -

So our conclusion is that in our example, the type of the base -class (of C) is not callable. So the Don Beaudry hook does not apply, -and the default class creation mechanism is used (which is also used -when there is no base class). In fact, the Don Beaudry hook never -applies when using only core Python, since the type of a core object -is never callable. - -

So what do Don and Jim do in order to use Don's hook? Write an -extension that defines at least two new Python object types. The -first would be the type for ``class-like'' objects usable as a base -class, to trigger Don's hook. This type must be made callable. -That's why we need a second type. Whether an object is callable -depends on its type. So whether a type object is callable depends on -its type, which is a meta-type. (In core Python there -is only one meta-type, the type ``type'' (types.TypeType), which is -the type of all type objects, even itself.) A new meta-type must -be defined that makes the type of the class-like objects callable. -(Normally, a third type would also be needed, the new ``instance'' -type, but this is not an absolute requirement -- the new class type -could return an object of some existing type when invoked to create an -instance.) - -

Still confused? Here's a simple device due to Don himself to -explain metaclasses. Take a simple class definition; assume B is a -special class that triggers Don's hook: - -

-class C(B):
-    a = 1
-    b = 2
-
- -This can be though of as equivalent to: - -
-C = type(B)('C', (B,), {'a': 1, 'b': 2})
-
- -If that's too dense for you, here's the same thing written out using -temporary variables: - -
-creator = type(B)               # The type of the base class
-name = 'C'                      # The name of the new class
-bases = (B,)                    # A tuple containing the base class(es)
-namespace = {'a': 1, 'b': 2}    # The namespace of the class statement
-C = creator(name, bases, namespace)
-
- -This is analogous to what happens without the Don Beaudry hook, except -that in that case the creator function is set to the default class -creator. - -

In either case, the creator is called with three arguments. The -first one, name, is the name of the new class (as given at the -top of the class statement). The bases argument is a tuple of -base classes (a singleton tuple if there's only one base class, like -the example). Finally, namespace is a dictionary containing -the local variables collected during execution of the class statement. - -

Note that the contents of the namespace dictionary is simply -whatever names were defined in the class statement. A little-known -fact is that when Python executes a class statement, it enters a new -local namespace, and all assignments and function definitions take -place in this namespace. Thus, after executing the following class -statement: - -

-class C:
-    a = 1
-    def f(s): pass
-
- -the class namespace's contents would be {'a': 1, 'f': <function f -...>}. - -

But enough already about writing Python metaclasses in C; read the -documentation of MESS or Extension -Classes for more information. - -

- -


- -

Writing Metaclasses in Python

- -

In Python 1.5, the requirement to write a C extension in order to -write metaclasses has been dropped (though you can still do -it, of course). In addition to the check ``is the type of the base -class callable,'' there's a check ``does the base class have a -__class__ attribute.'' If so, it is assumed that the __class__ -attribute refers to a class. - -

Let's repeat our simple example from above: - -

-class C(B):
-    a = 1
-    b = 2
-
- -Assuming B has a __class__ attribute, this translates into: - -
-C = B.__class__('C', (B,), {'a': 1, 'b': 2})
-
- -This is exactly the same as before except that instead of type(B), -B.__class__ is invoked. If you have read FAQ question 6.22 you will understand that while there is a big -technical difference between type(B) and B.__class__, they play the -same role at different abstraction levels. And perhaps at some point -in the future they will really be the same thing (at which point you -would be able to derive subclasses from built-in types). - -

At this point it may be worth mentioning that C.__class__ is the -same object as B.__class__, i.e., C's metaclass is the same as B's -metaclass. In other words, subclassing an existing class creates a -new (meta)inststance of the base class's metaclass. - -

Going back to the example, the class B.__class__ is instantiated, -passing its constructor the same three arguments that are passed to -the default class constructor or to an extension's metaclass: -name, bases, and namespace. - -

It is easy to be confused by what exactly happens when using a -metaclass, because we lose the absolute distinction between classes -and instances: a class is an instance of a metaclass (a -``metainstance''), but technically (i.e. in the eyes of the python -runtime system), the metaclass is just a class, and the metainstance -is just an instance. At the end of the class statement, the metaclass -whose metainstance is used as a base class is instantiated, yielding a -second metainstance (of the same metaclass). This metainstance is -then used as a (normal, non-meta) class; instantiation of the class -means calling the metainstance, and this will return a real instance. -And what class is that an instance of? Conceptually, it is of course -an instance of our metainstance; but in most cases the Python runtime -system will see it as an instance of a a helper class used by the -metaclass to implement its (non-meta) instances... - -

Hopefully an example will make things clearer. Let's presume we -have a metaclass MetaClass1. It's helper class (for non-meta -instances) is callled HelperClass1. We now (manually) instantiate -MetaClass1 once to get an empty special base class: - -

-BaseClass1 = MetaClass1("BaseClass1", (), {})
-
- -We can now use BaseClass1 as a base class in a class statement: - -
-class MySpecialClass(BaseClass1):
-    i = 1
-    def f(s): pass
-
- -At this point, MySpecialClass is defined; it is a metainstance of -MetaClass1 just like BaseClass1, and in fact the expression -``BaseClass1.__class__ == MySpecialClass.__class__ == MetaClass1'' -yields true. - -

We are now ready to create instances of MySpecialClass. Let's -assume that no constructor arguments are required: - -

-x = MySpecialClass()
-y = MySpecialClass()
-print x.__class__, y.__class__
-
- -The print statement shows that x and y are instances of HelperClass1. -How did this happen? MySpecialClass is an instance of MetaClass1 -(``meta'' is irrelevant here); when an instance is called, its -__call__ method is invoked, and presumably the __call__ method defined -by MetaClass1 returns an instance of HelperClass1. - -

Now let's see how we could use metaclasses -- what can we do -with metaclasses that we can't easily do without them? Here's one -idea: a metaclass could automatically insert trace calls for all -method calls. Let's first develop a simplified example, without -support for inheritance or other ``advanced'' Python features (we'll -add those later). - -

-import types
-
-class Tracing:
-    def __init__(self, name, bases, namespace):
-        """Create a new class."""
-        self.__name__ = name
-        self.__bases__ = bases
-        self.__namespace__ = namespace
-    def __call__(self):
-        """Create a new instance."""
-        return Instance(self)
-
-class Instance:
-    def __init__(self, klass):
-        self.__klass__ = klass
-    def __getattr__(self, name):
-        try:
-            value = self.__klass__.__namespace__[name]
-        except KeyError:
-            raise AttributeError, name
-        if type(value) is not types.FunctionType:
-            return value
-        return BoundMethod(value, self)
-
-class BoundMethod:
-    def __init__(self, function, instance):
-        self.function = function
-        self.instance = instance
-    def __call__(self, *args):
-        print "calling", self.function, "for", self.instance, "with", args
-        return apply(self.function, (self.instance,) + args)
-
-Trace = Tracing('Trace', (), {})
-
-class MyTracedClass(Trace):
-    def method1(self, a):
-        self.a = a
-    def method2(self):
-        return self.a
-
-aninstance = MyTracedClass()
-
-aninstance.method1(10)
-
-print "the answer is %d" % aninstance.method2()
-
- -Confused already? The intention is to read this from top down. The -Tracing class is the metaclass we're defining. Its structure is -really simple. - -

- -

    - -
  • The __init__ method is invoked when a new Tracing instance is -created, e.g. the definition of class MyTracedClass later in the -example. It simply saves the class name, base classes and namespace -as instance variables.

    - -

  • The __call__ method is invoked when a Tracing instance is called, -e.g. the creation of aninstance later in the example. It returns an -instance of the class Instance, which is defined next.

    - -

- -

The class Instance is the class used for all instances of classes -built using the Tracing metaclass, e.g. aninstance. It has two -methods: - -

- -

    - -
  • The __init__ method is invoked from the Tracing.__call__ method -above to initialize a new instance. It saves the class reference as -an instance variable. It uses a funny name because the user's -instance variables (e.g. self.a later in the example) live in the same -namespace.

    - -

  • The __getattr__ method is invoked whenever the user code -references an attribute of the instance that is not an instance -variable (nor a class variable; but except for __init__ and -__getattr__ there are no class variables). It will be called, for -example, when aninstance.method1 is referenced in the example, with -self set to aninstance and name set to the string "method1".

    - -

- -

The __getattr__ method looks the name up in the __namespace__ -dictionary. If it isn't found, it raises an AttributeError exception. -(In a more realistic example, it would first have to look through the -base classes as well.) If it is found, there are two possibilities: -it's either a function or it isn't. If it's not a function, it is -assumed to be a class variable, and its value is returned. If it's a -function, we have to ``wrap'' it in instance of yet another helper -class, BoundMethod. - -

The BoundMethod class is needed to implement a familiar feature: -when a method is defined, it has an initial argument, self, which is -automatically bound to the relevant instance when it is called. For -example, aninstance.method1(10) is equivalent to method1(aninstance, -10). In the example if this call, first a temporary BoundMethod -instance is created with the following constructor call: temp = -BoundMethod(method1, aninstance); then this instance is called as -temp(10). After the call, the temporary instance is discarded. - -

- -

    - -
  • The __init__ method is invoked for the constructor call -BoundMethod(method1, aninstance). It simply saves away its -arguments.

    - -

  • The __call__ method is invoked when the bound method instance is -called, as in temp(10). It needs to call method1(aninstance, 10). -However, even though self.function is now method1 and self.instance is -aninstance, it can't call self.function(self.instance, args) directly, -because it should work regardless of the number of arguments passed. -(For simplicity, support for keyword arguments has been omitted.)

    - -

- -

In order to be able to support arbitrary argument lists, the -__call__ method first constructs a new argument tuple. Conveniently, -because of the notation *args in __call__'s own argument list, the -arguments to __call__ (except for self) are placed in the tuple args. -To construct the desired argument list, we concatenate a singleton -tuple containing the instance with the args tuple: (self.instance,) + -args. (Note the trailing comma used to construct the singleton -tuple.) In our example, the resulting argument tuple is (aninstance, -10). - -

The intrinsic function apply() takes a function and an argument -tuple and calls the function for it. In our example, we are calling -apply(method1, (aninstance, 10)) which is equivalent to calling -method(aninstance, 10). - -

From here on, things should come together quite easily. The output -of the example code is something like this: - -

-calling <function method1 at ae8d8> for <Instance instance at 95ab0> with (10,)
-calling <function method2 at ae900> for <Instance instance at 95ab0> with ()
-the answer is 10
-
- -

That was about the shortest meaningful example that I could come up -with. A real tracing metaclass (for example, Trace.py discussed below) needs to be more -complicated in two dimensions. - -

First, it needs to support more advanced Python features such as -class variables, inheritance, __init__ methods, and keyword arguments. - -

Second, it needs to provide a more flexible way to handle the -actual tracing information; perhaps it should be possible to write -your own tracing function that gets called, perhaps it should be -possible to enable and disable tracing on a per-class or per-instance -basis, and perhaps a filter so that only interesting calls are traced; -it should also be able to trace the return value of the call (or the -exception it raised if an error occurs). Even the Trace.py example -doesn't support all these features yet. - -

- -


- -

Real-life Examples

- -

Have a look at some very preliminary examples that I coded up to -teach myself how to write metaclasses: - -

- -
Enum.py - -
This (ab)uses the class syntax as an elegant way to define -enumerated types. The resulting classes are never instantiated -- -rather, their class attributes are the enumerated values. For -example: - -
-class Color(Enum):
-    red = 1
-    green = 2
-    blue = 3
-print Color.red
-
- -will print the string ``Color.red'', while ``Color.red==1'' is true, -and ``Color.red + 1'' raise a TypeError exception. - -

- -

Trace.py - -
The resulting classes work much like standard -classes, but by setting a special class or instance attribute -__trace_output__ to point to a file, all calls to the class's methods -are traced. It was a bit of a struggle to get this right. This -should probably redone using the generic metaclass below. - -

- -

Meta.py - -
A generic metaclass. This is an attempt at finding out how much -standard class behavior can be mimicked by a metaclass. The -preliminary answer appears to be that everything's fine as long as the -class (or its clients) don't look at the instance's __class__ -attribute, nor at the class's __dict__ attribute. The use of -__getattr__ internally makes the classic implementation of __getattr__ -hooks tough; we provide a similar hook _getattr_ instead. -(__setattr__ and __delattr__ are not affected.) -(XXX Hm. Could detect presence of __getattr__ and rename it.) - -

- -

Eiffel.py - -
Uses the above generic metaclass to implement Eiffel style -pre-conditions and post-conditions. - -

- -

Synch.py - -
Uses the above generic metaclass to implement synchronized -methods. - -

- -

Simple.py - -
The example module used above. - -

- -

- -

A pattern seems to be emerging: almost all these uses of -metaclasses (except for Enum, which is probably more cute than useful) -mostly work by placing wrappers around method calls. An obvious -problem with that is that it's not easy to combine the features of -different metaclasses, while this would actually be quite useful: for -example, I wouldn't mind getting a trace from the test run of the -Synch module, and it would be interesting to add preconditions to it -as well. This needs more research. Perhaps a metaclass could be -provided that allows stackable wrappers... - -

- -


- -

Things You Could Do With Metaclasses

- -

There are lots of things you could do with metaclasses. Most of -these can also be done with creative use of __getattr__, but -metaclasses make it easier to modify the attribute lookup behavior of -classes. Here's a partial list. - -

- -

    - -
  • Enforce different inheritance semantics, e.g. automatically call -base class methods when a derived class overrides

    - -

  • Implement class methods (e.g. if the first argument is not named -'self')

    - -

  • Implement that each instance is initialized with copies of -all class variables

    - -

  • Implement a different way to store instance variables (e.g. in a -list kept outside the the instance but indexed by the instance's id())

    - -

  • Automatically wrap or trap all or certain methods - -
      - -
    • for tracing - -
    • for precondition and postcondition checking - -
    • for synchronized methods - -
    • for automatic value caching - -
    -

    - -

  • When an attribute is a parameterless function, call it on -reference (to mimic it being an instance variable); same on assignment

    - -

  • Instrumentation: see how many times various attributes are used

    - -

  • Different semantics for __setattr__ and __getattr__ (e.g. disable -them when they are being used recursively)

    - -

  • Abuse class syntax for other things

    - -

  • Experiment with automatic type checking

    - -

  • Delegation (or acquisition)

    - -

  • Dynamic inheritance patterns

    - -

  • Automatic caching of methods

    - -

- -

- -


- -

Credits

- -

Many thanks to David Ascher and Donald Beaudry for their comments -on earlier draft of this paper. Also thanks to Matt Conway and Tommy -Burnette for putting a seed for the idea of metaclasses in my -mind, nearly three years ago, even though at the time my response was -``you can do that with __getattr__ hooks...'' :-) - -

- -


- - - - diff --git a/Demo/metaclasses/meta-vladimir.txt b/Demo/metaclasses/meta-vladimir.txt deleted file mode 100644 index 36406bb465..0000000000 --- a/Demo/metaclasses/meta-vladimir.txt +++ /dev/null @@ -1,256 +0,0 @@ -Subject: Re: The metaclass saga using Python -From: Vladimir Marangozov -To: tim_one@email.msn.com (Tim Peters) -Cc: python-list@cwi.nl -Date: Wed, 5 Aug 1998 15:59:06 +0200 (DFT) - -[Tim] -> -> building-on-examples-tends-to-prevent-abstract-thrashing-ly y'rs - tim -> - -OK, I stand corrected. I understand that anybody's interpretation of -the meta-class concept is likely to be difficult to digest by others. - -Here's another try, expressing the same thing, but using the Python -programming model, examples and, perhaps, more popular terms. - -1. Classes. - - This is pure Python of today. Sorry about the tutorial, but it is - meant to illustrate the second part, which is the one we're - interested in and which will follow the same development scenario. - Besides, newbies are likely to understand that the discussion is - affordable even for them :-) - - a) Class definition - - A class is meant to define the common properties of a set of objects. - A class is a "package" of properties. The assembly of properties - in a class package is sometimes called a class structure (which isn't - always appropriate). - - >>> class A: - attr1 = "Hello" # an attribute of A - def method1(self, *args): pass # method1 of A - def method2(self, *args): pass # method2 of A - >>> - - So far, we defined the structure of the class A. The class A is - of type . We can check this by asking Python: "what is A?" - - >>> A # What is A? - - - b) Class instantiation - - Creating an object with the properties defined in the class A is - called instantiation of the class A. After an instantiation of A, we - obtain a new object, called an instance, which has the properties - packaged in the class A. - - >>> a = A() # 'a' is the 1st instance of A - >>> a # What is 'a'? - <__main__.A instance at 2022b9d0> - - >>> b = A() # 'b' is another instance of A - >>> b # What is 'b'? - <__main__.A instance at 2022b9c0> - - The objects, 'a' and 'b', are of type and they both have - the same properties. Note, that 'a' and 'b' are different objects. - (their adresses differ). This is a bit hard to see, so let's ask Python: - - >>> a == b # Is 'a' the same object as 'b'? - 0 # No. - - Instance objects have one more special property, indicating the class - they are an instance of. This property is named __class__. - - >>> a.__class__ # What is the class of 'a'? - # 'a' is an instance of A - >>> b.__class__ # What is the class of 'b'? - # 'b' is an instance of A - >>> a.__class__ == b.__class__ # Is it really the same class A? - 1 # Yes. - - c) Class inheritance (class composition and specialization) - - Classes can be defined in terms of other existing classes (and only - classes! -- don't bug me on this now). Thus, we can compose property - packages and create new ones. We reuse the property set defined - in a class by defining a new class, which "inherits" from the former. - In other words, a class B which inherits from the class A, inherits - the properties defined in A, or, B inherits the structure of A. - - In the same time, at the definition of the new class B, we can enrich - the inherited set of properties by adding new ones and/or modify some - of the inherited properties. - - >>> class B(A): # B inherits A's properties - attr2 = "World" # additional attr2 - def method2(self, arg1): pass # method2 is redefined - def method3(self, *args): pass # additional method3 - - >>> B # What is B? - - >>> B == A # Is B the same class as A? - 0 # No. - - Classes define one special property, indicating whether a class - inherits the properties of another class. This property is called - __bases__ and it contains a list (a tuple) of the classes the new - class inherits from. The classes from which a class is inheriting the - properties are called superclasses (in Python, we call them also -- - base classes). - - >>> A.__bases__ # Does A have any superclasses? - () # No. - >>> B.__bases__ # Does B have any superclasses? - (,) # Yes. It has one superclass. - >>> B.__bases__[0] == A # Is it really the class A? - 1 # Yes, it is. - --------- - - Congratulations on getting this far! This was the hard part. - Now, let's continue with the easy one. - --------- - -2. Meta-classes - - You have to admit, that an anonymous group of Python wizards are - not satisfied with the property packaging facilities presented above. - They say, that the Real-World bugs them with problems that cannot be - modelled successfully with classes. Or, that the way classes are - implemented in Python and the way classes and instances behave at - runtime isn't always appropriate for reproducing the Real-World's - behavior in a way that satisfies them. - - Hence, what they want is the following: - - a) leave objects as they are (instances of classes) - b) leave classes as they are (property packages and object creators) - - BUT, at the same time: - - c) consider classes as being instances of mysterious objects. - d) label mysterious objects "meta-classes". - - Easy, eh? - - You may ask: "Why on earth do they want to do that?". - They answer: "Poor soul... Go and see how cruel the Real-World is!". - You - fuzzy: "OK, will do!" - - And here we go for another round of what I said in section 1 -- Classes. - - However, be warned! The features we're going to talk about aren't fully - implemented yet, because the Real-World don't let wizards to evaluate - precisely how cruel it is, so the features are still highly-experimental. - - a) Meta-class definition - - A meta-class is meant to define the common properties of a set of - classes. A meta-class is a "package" of properties. The assembly - of properties in a meta-class package is sometimes called a meta-class - structure (which isn't always appropriate). - - In Python, a meta-class definition would have looked like this: - - >>> metaclass M: - attr1 = "Hello" # an attribute of M - def method1(self, *args): pass # method1 of M - def method2(self, *args): pass # method2 of M - >>> - - So far, we defined the structure of the meta-class M. The meta-class - M is of type . We cannot check this by asking Python, but - if we could, it would have answered: - - >>> M # What is M? - - - b) Meta-class instantiation - - Creating an object with the properties defined in the meta-class M is - called instantiation of the meta-class M. After an instantiation of M, - we obtain a new object, called an class, but now it is called also - a meta-instance, which has the properties packaged in the meta-class M. - - In Python, instantiating a meta-class would have looked like this: - - >>> A = M() # 'A' is the 1st instance of M - >>> A # What is 'A'? - - - >>> B = M() # 'B' is another instance of M - >>> B # What is 'B'? - - - The metaclass-instances, A and B, are of type and they both - have the same properties. Note, that A and B are different objects. - (their adresses differ). This is a bit hard to see, but if it was - possible to ask Python, it would have answered: - - >>> A == B # Is A the same class as B? - 0 # No. - - Class objects have one more special property, indicating the meta-class - they are an instance of. This property is named __metaclass__. - - >>> A.__metaclass__ # What is the meta-class of A? - # A is an instance of M - >>> A.__metaclass__ # What is the meta-class of B? - # B is an instance of M - >>> A.__metaclass__ == B.__metaclass__ # Is it the same meta-class M? - 1 # Yes. - - c) Meta-class inheritance (meta-class composition and specialization) - - Meta-classes can be defined in terms of other existing meta-classes - (and only meta-classes!). Thus, we can compose property packages and - create new ones. We reuse the property set defined in a meta-class by - defining a new meta-class, which "inherits" from the former. - In other words, a meta-class N which inherits from the meta-class M, - inherits the properties defined in M, or, N inherits the structure of M. - - In the same time, at the definition of the new meta-class N, we can - enrich the inherited set of properties by adding new ones and/or modify - some of the inherited properties. - - >>> metaclass N(M): # N inherits M's properties - attr2 = "World" # additional attr2 - def method2(self, arg1): pass # method2 is redefined - def method3(self, *args): pass # additional method3 - - >>> N # What is N? - - >>> N == M # Is N the same meta-class as M? - 0 # No. - - Meta-classes define one special property, indicating whether a - meta-class inherits the properties of another meta-class. This property - is called __metabases__ and it contains a list (a tuple) of the - meta-classes the new meta-class inherits from. The meta-classes from - which a meta-class is inheriting the properties are called - super-meta-classes (in Python, we call them also -- super meta-bases). - - >>> M.__metabases__ # Does M have any supermetaclasses? - () # No. - >>> N.__metabases__ # Does N have any supermetaclasses? - (,) # Yes. It has a supermetaclass. - >>> N.__metabases__[0] == M # Is it really the meta-class M? - 1 # Yes, it is. - --------- - - Triple congratulations on getting this far! - Now you know everything about meta-classes and the Real-World! - - - --- - Vladimir MARANGOZOV | Vladimir.Marangozov@inrialpes.fr -http://sirac.inrialpes.fr/~marangoz | tel:(+33-4)76615277 fax:76615252 diff --git a/Demo/parser/FILES b/Demo/parser/FILES deleted file mode 100644 index 1ff59a31a2..0000000000 --- a/Demo/parser/FILES +++ /dev/null @@ -1,6 +0,0 @@ -Demo/parser -Doc/libparser.tex -Lib/AST.py -Lib/symbol.py -Lib/token.py -Modules/parsermodule.c diff --git a/Demo/parser/README b/Demo/parser/README deleted file mode 100644 index f2f18cade5..0000000000 --- a/Demo/parser/README +++ /dev/null @@ -1,25 +0,0 @@ -These files are from the large example of using the `parser' module. Refer -to the Python Library Reference for more information. - -Files: ------- - - FILES -- list of files associated with the parser module. - - README -- this file. - - example.py -- module that uses the `parser' module to extract - information from the parse tree of Python source - code. - - docstring.py -- sample source file containing only a module docstring. - - simple.py -- sample source containing a "short form" definition. - - source.py -- sample source code used to demonstrate ability to - handle nested constructs easily using the functions - and classes in example.py. - - test_parser.py program to put the parser module through it's paces. - -Enjoy! diff --git a/Demo/parser/docstring.py b/Demo/parser/docstring.py deleted file mode 100644 index 45a261b61c..0000000000 --- a/Demo/parser/docstring.py +++ /dev/null @@ -1,2 +0,0 @@ -"""Some documentation. -""" diff --git a/Demo/parser/example.py b/Demo/parser/example.py deleted file mode 100644 index 2aa9ec2857..0000000000 --- a/Demo/parser/example.py +++ /dev/null @@ -1,190 +0,0 @@ -"""Simple code to extract class & function docstrings from a module. - -This code is used as an example in the library reference manual in the -section on using the parser module. Refer to the manual for a thorough -discussion of the operation of this code. -""" - -import os -import parser -import symbol -import token -import types - -from types import ListType, TupleType - - -def get_docs(fileName): - """Retrieve information from the parse tree of a source file. - - fileName - Name of the file to read Python source code from. - """ - source = open(fileName).read() - basename = os.path.basename(os.path.splitext(fileName)[0]) - ast = parser.suite(source) - return ModuleInfo(ast.totuple(), basename) - - -class SuiteInfoBase: - _docstring = '' - _name = '' - - def __init__(self, tree = None): - self._class_info = {} - self._function_info = {} - if tree: - self._extract_info(tree) - - def _extract_info(self, tree): - # extract docstring - if len(tree) == 2: - found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1]) - else: - found, vars = match(DOCSTRING_STMT_PATTERN, tree[3]) - if found: - self._docstring = eval(vars['docstring']) - # discover inner definitions - for node in tree[1:]: - found, vars = match(COMPOUND_STMT_PATTERN, node) - if found: - cstmt = vars['compound'] - if cstmt[0] == symbol.funcdef: - name = cstmt[2][1] - self._function_info[name] = FunctionInfo(cstmt) - elif cstmt[0] == symbol.classdef: - name = cstmt[2][1] - self._class_info[name] = ClassInfo(cstmt) - - def get_docstring(self): - return self._docstring - - def get_name(self): - return self._name - - def get_class_names(self): - return self._class_info.keys() - - def get_class_info(self, name): - return self._class_info[name] - - def __getitem__(self, name): - try: - return self._class_info[name] - except KeyError: - return self._function_info[name] - - -class SuiteFuncInfo: - # Mixin class providing access to function names and info. - - def get_function_names(self): - return self._function_info.keys() - - def get_function_info(self, name): - return self._function_info[name] - - -class FunctionInfo(SuiteInfoBase, SuiteFuncInfo): - def __init__(self, tree = None): - self._name = tree[2][1] - SuiteInfoBase.__init__(self, tree and tree[-1] or None) - - -class ClassInfo(SuiteInfoBase): - def __init__(self, tree = None): - self._name = tree[2][1] - SuiteInfoBase.__init__(self, tree and tree[-1] or None) - - def get_method_names(self): - return self._function_info.keys() - - def get_method_info(self, name): - return self._function_info[name] - - -class ModuleInfo(SuiteInfoBase, SuiteFuncInfo): - def __init__(self, tree = None, name = ""): - self._name = name - SuiteInfoBase.__init__(self, tree) - if tree: - found, vars = match(DOCSTRING_STMT_PATTERN, tree[1]) - if found: - self._docstring = vars["docstring"] - - -def match(pattern, data, vars=None): - """Match `data' to `pattern', with variable extraction. - - pattern - Pattern to match against, possibly containing variables. - - data - Data to be checked and against which variables are extracted. - - vars - Dictionary of variables which have already been found. If not - provided, an empty dictionary is created. - - The `pattern' value may contain variables of the form ['varname'] which - are allowed to match anything. The value that is matched is returned as - part of a dictionary which maps 'varname' to the matched value. 'varname' - is not required to be a string object, but using strings makes patterns - and the code which uses them more readable. - - This function returns two values: a boolean indicating whether a match - was found and a dictionary mapping variable names to their associated - values. - """ - if vars is None: - vars = {} - if type(pattern) is ListType: # 'variables' are ['varname'] - vars[pattern[0]] = data - return 1, vars - if type(pattern) is not TupleType: - return (pattern == data), vars - if len(data) != len(pattern): - return 0, vars - for pattern, data in map(None, pattern, data): - same, vars = match(pattern, data, vars) - if not same: - break - return same, vars - - -# This pattern identifies compound statements, allowing them to be readily -# differentiated from simple statements. -# -COMPOUND_STMT_PATTERN = ( - symbol.stmt, - (symbol.compound_stmt, ['compound']) - ) - - -# This pattern will match a 'stmt' node which *might* represent a docstring; -# docstrings require that the statement which provides the docstring be the -# first statement in the class or function, which this pattern does not check. -# -DOCSTRING_STMT_PATTERN = ( - symbol.stmt, - (symbol.simple_stmt, - (symbol.small_stmt, - (symbol.expr_stmt, - (symbol.testlist, - (symbol.test, - (symbol.and_test, - (symbol.not_test, - (symbol.comparison, - (symbol.expr, - (symbol.xor_expr, - (symbol.and_expr, - (symbol.shift_expr, - (symbol.arith_expr, - (symbol.term, - (symbol.factor, - (symbol.power, - (symbol.atom, - (token.STRING, ['docstring']) - )))))))))))))))), - (token.NEWLINE, '') - )) diff --git a/Demo/parser/simple.py b/Demo/parser/simple.py deleted file mode 100644 index 184e2fe5d0..0000000000 --- a/Demo/parser/simple.py +++ /dev/null @@ -1 +0,0 @@ -def f(): "maybe a docstring" diff --git a/Demo/parser/source.py b/Demo/parser/source.py deleted file mode 100644 index b90062851f..0000000000 --- a/Demo/parser/source.py +++ /dev/null @@ -1,27 +0,0 @@ -"""Exmaple file to be parsed for the parsermodule example. - -The classes and functions in this module exist only to exhibit the ability -of the handling information extraction from nested definitions using parse -trees. They shouldn't interest you otherwise! -""" - -class Simple: - "This class does very little." - - def method(self): - "This method does almost nothing." - return 1 - - class Nested: - "This is a nested class." - - def nested_method(self): - "Method of Nested class." - def nested_function(): - "Function in method of Nested class." - pass - return nested_function - -def function(): - "This function lives at the module level." - return 0 diff --git a/Demo/parser/test_parser.py b/Demo/parser/test_parser.py deleted file mode 100755 index be39bca7f0..0000000000 --- a/Demo/parser/test_parser.py +++ /dev/null @@ -1,48 +0,0 @@ -#! /usr/bin/env python -# (Force the script to use the latest build.) -# -# test_parser.py - -import parser, traceback - -_numFailed = 0 - -def testChunk(t, fileName): - global _numFailed - print '----', fileName, - try: - ast = parser.suite(t) - tup = parser.ast2tuple(ast) - # this discards the first AST; a huge memory savings when running - # against a large source file like Tkinter.py. - ast = None - new = parser.tuple2ast(tup) - except parser.ParserError, err: - print - print 'parser module raised exception on input file', fileName + ':' - traceback.print_exc() - _numFailed = _numFailed + 1 - else: - if tup != parser.ast2tuple(new): - print - print 'parser module failed on input file', fileName - _numFailed = _numFailed + 1 - else: - print 'o.k.' - -def testFile(fileName): - t = open(fileName).read() - testChunk(t, fileName) - -def test(): - import sys - args = sys.argv[1:] - if not args: - import glob - args = glob.glob("*.py") - args.sort() - map(testFile, args) - sys.exit(_numFailed != 0) - -if __name__ == '__main__': - test() diff --git a/Demo/parser/texipre.dat b/Demo/parser/texipre.dat deleted file mode 100644 index 8ad03a6175..0000000000 --- a/Demo/parser/texipre.dat +++ /dev/null @@ -1,100 +0,0 @@ -\input texinfo @c -*-texinfo-*- -@c %**start of header -@setfilename parser.info -@settitle Python Parser Module Reference -@setchapternewpage odd -@footnotestyle end -@c %**end of header - -@ifinfo -This file describes the interfaces -published by the optional @code{parser} module and gives examples of -how they may be used. It contains the same text as the chapter on the -@code{parser} module in the @cite{Python Library Reference}, but is -presented as a separate document. - -Copyright 1995-1996 by Fred L. Drake, Jr., Reston, Virginia, USA, and -Virginia Polytechnic Institute and State University, Blacksburg, -Virginia, USA. Portions of the software copyright 1991-1995 by -Stichting Mathematisch Centrum, Amsterdam, The Netherlands. Copying is -permitted under the terms associated with the main Python distribution, -with the additional restriction that this additional notice be included -and maintained on all distributed copies. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, -provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in -supporting documentation, and that the names of Fred L. Drake, Jr. and -Virginia Polytechnic Institute and State University not be used in -advertising or publicity pertaining to distribution of the software -without specific, written prior permission. - -FRED L. DRAKE, JR. AND VIRGINIA POLYTECHNIC INSTITUTE AND STATE -UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO -EVENT SHALL FRED L. DRAKE, JR. OR VIRGINIA POLYTECHNIC INSTITUTE AND -STATE UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL -DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR -PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -@end ifinfo - -@titlepage -@title Python Parser Module Reference -@author Fred L. Drake, Jr. - -@c The following two commands start the copyright page. -@page -@vskip 0pt plus 1filll -Copyright 1995-1996 by Fred L. Drake, Jr., Reston, Virginia, USA, and -Virginia Polytechnic Institute and State University, Blacksburg, -Virginia, USA. Portions of the software copyright 1991-1995 by -Stichting Mathematisch Centrum, Amsterdam, The Netherlands. Copying is -permitted under the terms associated with the main Python distribution, -with the additional restriction that this additional notice be included -and maintained on all distributed copies. - -@center All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, -provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in -supporting documentation, and that the names of Fred L. Drake, Jr. and -Virginia Polytechnic Institute and State University not be used in -advertising or publicity pertaining to distribution of the software -without specific, written prior permission. - -FRED L. DRAKE, JR. AND VIRGINIA POLYTECHNIC INSTITUTE AND STATE -UNIVERSITY DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, -INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO -EVENT SHALL FRED L. DRAKE, JR. OR VIRGINIA POLYTECHNIC INSTITUTE AND -STATE UNIVERSITY BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL -DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR -PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -@end titlepage - - -@node Top, Overview, (dir), (dir) -@top The Python Parser Module - -@ifinfo -This file describes the interfaces -published by the optional @code{parser} module and gives examples of -how they may be used. It contains the same text as the chapter on the -@code{parser} module in the @cite{Python Library Reference}, but is -presented as a separate document. - -This version corresponds to Python version 1.4 (1 Sept. 1996). - -@end ifinfo - -@c placeholder for the master menu -- patched by texinfo-all-menus-update -@menu -@end menu diff --git a/Demo/pdist/FSProxy.py b/Demo/pdist/FSProxy.py deleted file mode 100755 index 7510d1e6fd..0000000000 --- a/Demo/pdist/FSProxy.py +++ /dev/null @@ -1,322 +0,0 @@ -"""File System Proxy. - -Provide an OS-neutral view on a file system, locally or remotely. -The functionality is geared towards implementing some sort of -rdist-like utility between a Mac and a UNIX system. - -The module defines three classes: - -FSProxyLocal -- used for local access -FSProxyServer -- used on the server side of remote access -FSProxyClient -- used on the client side of remote access - -The remote classes are instantiated with an IP address and an optional -verbosity flag. -""" - -import server -import client -import md5 -import os -import fnmatch -from stat import * -import time -import fnmatch - -if os.name == 'mac': - import macfs - maxnamelen = 31 -else: - macfs = None - maxnamelen = 255 - -skipnames = (os.curdir, os.pardir) - - -class FSProxyLocal: - - def __init__(self): - self._dirstack = [] - self._ignore = ['*.pyc'] + self._readignore() - - def _close(self): - while self._dirstack: - self.back() - - def _readignore(self): - file = self._hide('ignore') - try: - f = open(file) - except IOError: - file = self._hide('synctree.ignorefiles') - try: - f = open(file) - except IOError: - return [] - ignore = [] - while 1: - line = f.readline() - if not line: break - if line[-1] == '\n': line = line[:-1] - ignore.append(line) - f.close() - return ignore - - def _hidden(self, name): - if os.name == 'mac': - return name[0] == '(' and name[-1] == ')' - else: - return name[0] == '.' - - def _hide(self, name): - if os.name == 'mac': - return '(%s)' % name - else: - return '.%s' % name - - def visible(self, name): - if len(name) > maxnamelen: return 0 - if name[-1] == '~': return 0 - if name in skipnames: return 0 - if self._hidden(name): return 0 - head, tail = os.path.split(name) - if head or not tail: return 0 - if macfs: - if os.path.exists(name) and not os.path.isdir(name): - try: - fs = macfs.FSSpec(name) - c, t = fs.GetCreatorType() - if t != 'TEXT': return 0 - except macfs.error, msg: - print "***", name, msg - return 0 - else: - if os.path.islink(name): return 0 - if '\0' in open(name, 'rb').read(512): return 0 - for ign in self._ignore: - if fnmatch.fnmatch(name, ign): return 0 - return 1 - - def check(self, name): - if not self.visible(name): - raise os.error, "protected name %s" % repr(name) - - def checkfile(self, name): - self.check(name) - if not os.path.isfile(name): - raise os.error, "not a plain file %s" % repr(name) - - def pwd(self): - return os.getcwd() - - def cd(self, name): - self.check(name) - save = os.getcwd(), self._ignore - os.chdir(name) - self._dirstack.append(save) - self._ignore = self._ignore + self._readignore() - - def back(self): - if not self._dirstack: - raise os.error, "empty directory stack" - dir, ignore = self._dirstack[-1] - os.chdir(dir) - del self._dirstack[-1] - self._ignore = ignore - - def _filter(self, files, pat = None): - if pat: - def keep(name, pat = pat): - return fnmatch.fnmatch(name, pat) - files = filter(keep, files) - files = filter(self.visible, files) - files.sort() - return files - - def list(self, pat = None): - files = os.listdir(os.curdir) - return self._filter(files, pat) - - def listfiles(self, pat = None): - files = os.listdir(os.curdir) - files = filter(os.path.isfile, files) - return self._filter(files, pat) - - def listsubdirs(self, pat = None): - files = os.listdir(os.curdir) - files = filter(os.path.isdir, files) - return self._filter(files, pat) - - def exists(self, name): - return self.visible(name) and os.path.exists(name) - - def isdir(self, name): - return self.visible(name) and os.path.isdir(name) - - def islink(self, name): - return self.visible(name) and os.path.islink(name) - - def isfile(self, name): - return self.visible(name) and os.path.isfile(name) - - def sum(self, name): - self.checkfile(name) - BUFFERSIZE = 1024*8 - f = open(name) - sum = md5.new() - while 1: - buffer = f.read(BUFFERSIZE) - if not buffer: - break - sum.update(buffer) - return sum.digest() - - def size(self, name): - self.checkfile(name) - return os.stat(name)[ST_SIZE] - - def mtime(self, name): - self.checkfile(name) - return time.localtime(os.stat(name)[ST_MTIME]) - - def stat(self, name): - self.checkfile(name) - size = os.stat(name)[ST_SIZE] - mtime = time.localtime(os.stat(name)[ST_MTIME]) - return size, mtime - - def info(self, name): - sum = self.sum(name) - size = os.stat(name)[ST_SIZE] - mtime = time.localtime(os.stat(name)[ST_MTIME]) - return sum, size, mtime - - def _list(self, function, list): - if list is None: - list = self.listfiles() - res = [] - for name in list: - try: - res.append((name, function(name))) - except (os.error, IOError): - res.append((name, None)) - return res - - def sumlist(self, list = None): - return self._list(self.sum, list) - - def statlist(self, list = None): - return self._list(self.stat, list) - - def mtimelist(self, list = None): - return self._list(self.mtime, list) - - def sizelist(self, list = None): - return self._list(self.size, list) - - def infolist(self, list = None): - return self._list(self.info, list) - - def _dict(self, function, list): - if list is None: - list = self.listfiles() - dict = {} - for name in list: - try: - dict[name] = function(name) - except (os.error, IOError): - pass - return dict - - def sumdict(self, list = None): - return self.dict(self.sum, list) - - def sizedict(self, list = None): - return self.dict(self.size, list) - - def mtimedict(self, list = None): - return self.dict(self.mtime, list) - - def statdict(self, list = None): - return self.dict(self.stat, list) - - def infodict(self, list = None): - return self._dict(self.info, list) - - def read(self, name, offset = 0, length = -1): - self.checkfile(name) - f = open(name) - f.seek(offset) - if length == 0: - data = '' - elif length < 0: - data = f.read() - else: - data = f.read(length) - f.close() - return data - - def create(self, name): - self.check(name) - if os.path.exists(name): - self.checkfile(name) - bname = name + '~' - try: - os.unlink(bname) - except os.error: - pass - os.rename(name, bname) - f = open(name, 'w') - f.close() - - def write(self, name, data, offset = 0): - self.checkfile(name) - f = open(name, 'r+') - f.seek(offset) - f.write(data) - f.close() - - def mkdir(self, name): - self.check(name) - os.mkdir(name, 0777) - - def rmdir(self, name): - self.check(name) - os.rmdir(name) - - -class FSProxyServer(FSProxyLocal, server.Server): - - def __init__(self, address, verbose = server.VERBOSE): - FSProxyLocal.__init__(self) - server.Server.__init__(self, address, verbose) - - def _close(self): - server.Server._close(self) - FSProxyLocal._close(self) - - def _serve(self): - server.Server._serve(self) - # Retreat into start directory - while self._dirstack: self.back() - - -class FSProxyClient(client.Client): - - def __init__(self, address, verbose = client.VERBOSE): - client.Client.__init__(self, address, verbose) - - -def test(): - import string - import sys - if sys.argv[1:]: - port = string.atoi(sys.argv[1]) - else: - port = 4127 - proxy = FSProxyServer(('', port)) - proxy._serverloop() - - -if __name__ == '__main__': - test() diff --git a/Demo/pdist/RCSProxy.py b/Demo/pdist/RCSProxy.py deleted file mode 100755 index 7212ca6224..0000000000 --- a/Demo/pdist/RCSProxy.py +++ /dev/null @@ -1,198 +0,0 @@ -#! /usr/bin/env python - -"""RCS Proxy. - -Provide a simplified interface on RCS files, locally or remotely. -The functionality is geared towards implementing some sort of -remote CVS like utility. It is modeled after the similar module -FSProxy. - -The module defines two classes: - -RCSProxyLocal -- used for local access -RCSProxyServer -- used on the server side of remote access - -The corresponding client class, RCSProxyClient, is defined in module -rcsclient. - -The remote classes are instantiated with an IP address and an optional -verbosity flag. -""" - -import server -import md5 -import os -import fnmatch -import string -import tempfile -import rcslib - - -class DirSupport: - - def __init__(self): - self._dirstack = [] - - def __del__(self): - self._close() - - def _close(self): - while self._dirstack: - self.back() - - def pwd(self): - return os.getcwd() - - def cd(self, name): - save = os.getcwd() - os.chdir(name) - self._dirstack.append(save) - - def back(self): - if not self._dirstack: - raise os.error, "empty directory stack" - dir = self._dirstack[-1] - os.chdir(dir) - del self._dirstack[-1] - - def listsubdirs(self, pat = None): - files = os.listdir(os.curdir) - files = filter(os.path.isdir, files) - return self._filter(files, pat) - - def isdir(self, name): - return os.path.isdir(name) - - def mkdir(self, name): - os.mkdir(name, 0777) - - def rmdir(self, name): - os.rmdir(name) - - -class RCSProxyLocal(rcslib.RCS, DirSupport): - - def __init__(self): - rcslib.RCS.__init__(self) - DirSupport.__init__(self) - - def __del__(self): - DirSupport.__del__(self) - rcslib.RCS.__del__(self) - - def sumlist(self, list = None): - return self._list(self.sum, list) - - def sumdict(self, list = None): - return self._dict(self.sum, list) - - def sum(self, name_rev): - f = self._open(name_rev) - BUFFERSIZE = 1024*8 - sum = md5.new() - while 1: - buffer = f.read(BUFFERSIZE) - if not buffer: - break - sum.update(buffer) - self._closepipe(f) - return sum.digest() - - def get(self, name_rev): - f = self._open(name_rev) - data = f.read() - self._closepipe(f) - return data - - def put(self, name_rev, data, message=None): - name, rev = self._unmangle(name_rev) - f = open(name, 'w') - f.write(data) - f.close() - self.checkin(name_rev, message) - self._remove(name) - - def _list(self, function, list = None): - """INTERNAL: apply FUNCTION to all files in LIST. - - Return a list of the results. - - The list defaults to all files in the directory if None. - - """ - if list is None: - list = self.listfiles() - res = [] - for name in list: - try: - res.append((name, function(name))) - except (os.error, IOError): - res.append((name, None)) - return res - - def _dict(self, function, list = None): - """INTERNAL: apply FUNCTION to all files in LIST. - - Return a dictionary mapping files to results. - - The list defaults to all files in the directory if None. - - """ - if list is None: - list = self.listfiles() - dict = {} - for name in list: - try: - dict[name] = function(name) - except (os.error, IOError): - pass - return dict - - -class RCSProxyServer(RCSProxyLocal, server.SecureServer): - - def __init__(self, address, verbose = server.VERBOSE): - RCSProxyLocal.__init__(self) - server.SecureServer.__init__(self, address, verbose) - - def _close(self): - server.SecureServer._close(self) - RCSProxyLocal._close(self) - - def _serve(self): - server.SecureServer._serve(self) - # Retreat into start directory - while self._dirstack: self.back() - - -def test_server(): - import string - import sys - if sys.argv[1:]: - port = string.atoi(sys.argv[1]) - else: - port = 4127 - proxy = RCSProxyServer(('', port)) - proxy._serverloop() - - -def test(): - import sys - if not sys.argv[1:] or sys.argv[1] and sys.argv[1][0] in '0123456789': - test_server() - sys.exit(0) - proxy = RCSProxyLocal() - what = sys.argv[1] - if hasattr(proxy, what): - attr = getattr(proxy, what) - if callable(attr): - print apply(attr, tuple(sys.argv[2:])) - else: - print `attr` - else: - print "%s: no such attribute" % what - sys.exit(2) - - -if __name__ == '__main__': - test() diff --git a/Demo/pdist/README b/Demo/pdist/README deleted file mode 100644 index b3fac24127..0000000000 --- a/Demo/pdist/README +++ /dev/null @@ -1,121 +0,0 @@ -Filesystem, RCS and CVS client and server classes -================================================= - -*** See the security warning at the end of this file! *** - -This directory contains various modules and classes that support -remote file system operations. - -CVS stuff ---------- - -rcvs Script to put in your bin directory -rcvs.py Remote CVS client command line interface - -cvslib.py CVS admin files classes (used by rrcs) -cvslock.py CVS locking algorithms - -RCS stuff ---------- - -rrcs Script to put in your bin directory -rrcs.py Remote RCS client command line interface - -rcsclient.py Return an RCSProxyClient instance - (has reasonable default server/port/directory) - -RCSProxy.py RCS proxy and server classes (on top of rcslib.py) - -rcslib.py Local-only RCS base class (affects stdout & - local work files) - -FSProxy stuff -------------- - -sumtree.py Old demo for FSProxy -cmptree.py First FSProxy client (used to sync from the Mac) -FSProxy.py Filesystem interface classes - -Generic client/server stuff ---------------------------- - -client.py Client class -server.py Server class - -security.py Security mix-in class (not very secure I think) - -Other generic stuff -------------------- - -cmdfw.py CommandFrameWork class - (used by rcvs, should be used by rrcs as well) - - -Client/Server operation ------------------------ - -The Client and Server classes implement a simple-minded RPC protocol, -using Python's pickle module to transfer arguments, return values and -exceptions with the most generality. The Server class is instantiated -with a port number on which it should listen for requests; the Client -class is instantiated with a host name and a port number where it -should connect to. Once a client is connected, a TCP connection is -maintained between client and server. - -The Server class currently handles only one connection at a time; -however it could be rewritten to allow various modes of operations, -using multiple threads or processes or the select() system call as -desired to serve multiple clients simultaneously (when using select(), -still handling one request at a time). This would not require -rewriting of the Client class. It may also be possible to adapt the -code to use UDP instead of TCP, but then both classes will have to be -rewritten (and unless extensive acknowlegements and request serial -numbers are used, the server should handle duplicate requests, so its -semantics should be idempotent -- shrudder). - -Even though the FSProxy and RCSProxy modules define client classes, -the client class is fully generic -- what methods it supports is -determined entirely by the server. The server class, however, must be -derived from. This is generally done as follows: - - from server import Server - from client import Client - - # Define a class that performs the operations locally - class MyClassLocal: - def __init__(self): ... - def _close(self): ... - - # Derive a server class using multiple inheritance - class MyClassServer(MyClassLocal, Server): - def __init__(self, address): - # Must initialize MyClassLocal as well as Server - MyClassLocal.__init__(self) - Server.__init__(self, address) - def _close(self): - Server._close() - MyClassLocal._close() - - # A dummy client class - class MyClassClient(Client): pass - -Note that because MyClassLocal isn't used in the definition of -MyClassClient, it would actually be better to place it in a separate -module so the definition of MyClassLocal isn't executed when we only -instantiate a client. - -The modules client and server should probably be renamed to Client and -Server in order to match the class names. - - -*** Security warning: this version requires that you have a file -$HOME/.python_keyfile at the server and client side containing two -comma- separated numbers. The security system at the moment makes no -guarantees of actuallng being secure -- however it requires that the -key file exists and contains the same numbers at both ends for this to -work. (You can specify an alternative keyfile in $PYTHON_KEYFILE). -Have a look at the Security class in security.py for details; -basically, if the key file contains (x, y), then the security server -class chooses a random number z (the challenge) in the range -10..100000 and the client must be able to produce pow(z, x, y) -(i.e. z**x mod y). diff --git a/Demo/pdist/client.py b/Demo/pdist/client.py deleted file mode 100755 index 3e93f1ce8e..0000000000 --- a/Demo/pdist/client.py +++ /dev/null @@ -1,158 +0,0 @@ -"""RPC Client module.""" - -import sys -import socket -import pickle -import __builtin__ -import os - - -# Default verbosity (0 = silent, 1 = print connections, 2 = print requests too) -VERBOSE = 1 - - -class Client: - - """RPC Client class. No need to derive a class -- it's fully generic.""" - - def __init__(self, address, verbose = VERBOSE): - self._pre_init(address, verbose) - self._post_init() - - def _pre_init(self, address, verbose = VERBOSE): - if type(address) == type(0): - address = ('', address) - self._address = address - self._verbose = verbose - if self._verbose: print "Connecting to %s ..." % repr(address) - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.connect(address) - if self._verbose: print "Connected." - self._lastid = 0 # Last id for which a reply has been received - self._nextid = 1 # Id of next request - self._replies = {} # Unprocessed replies - self._rf = self._socket.makefile('r') - self._wf = self._socket.makefile('w') - - def _post_init(self): - self._methods = self._call('.methods') - - def __del__(self): - self._close() - - def _close(self): - if self._rf: self._rf.close() - self._rf = None - if self._wf: self._wf.close() - self._wf = None - if self._socket: self._socket.close() - self._socket = None - - def __getattr__(self, name): - if name in self._methods: - method = _stub(self, name) - setattr(self, name, method) # XXX circular reference - return method - raise AttributeError, name - - def _setverbose(self, verbose): - self._verbose = verbose - - def _call(self, name, *args): - return self._vcall(name, args) - - def _vcall(self, name, args): - return self._recv(self._vsend(name, args)) - - def _send(self, name, *args): - return self._vsend(name, args) - - def _send_noreply(self, name, *args): - return self._vsend(name, args, 0) - - def _vsend_noreply(self, name, args): - return self._vsend(name, args, 0) - - def _vsend(self, name, args, wantreply = 1): - id = self._nextid - self._nextid = id+1 - if not wantreply: id = -id - request = (name, args, id) - if self._verbose > 1: print "sending request: %s" % repr(request) - wp = pickle.Pickler(self._wf) - wp.dump(request) - return id - - def _recv(self, id): - exception, value, rid = self._vrecv(id) - if rid != id: - raise RuntimeError, "request/reply id mismatch: %d/%d" % (id, rid) - if exception is None: - return value - x = exception - if hasattr(__builtin__, exception): - x = getattr(__builtin__, exception) - elif exception in ('posix.error', 'mac.error'): - x = os.error - if x == exception: - exception = x - raise exception, value - - def _vrecv(self, id): - self._flush() - if self._replies.has_key(id): - if self._verbose > 1: print "retrieving previous reply, id = %d" % id - reply = self._replies[id] - del self._replies[id] - return reply - aid = abs(id) - while 1: - if self._verbose > 1: print "waiting for reply, id = %d" % id - rp = pickle.Unpickler(self._rf) - reply = rp.load() - del rp - if self._verbose > 1: print "got reply: %s" % repr(reply) - rid = reply[2] - arid = abs(rid) - if arid == aid: - if self._verbose > 1: print "got it" - return reply - self._replies[rid] = reply - if arid > aid: - if self._verbose > 1: print "got higher id, assume all ok" - return (None, None, id) - - def _flush(self): - self._wf.flush() - - -from security import Security - - -class SecureClient(Client, Security): - - def __init__(self, *args): - import string - apply(self._pre_init, args) - Security.__init__(self) - self._wf.flush() - line = self._rf.readline() - challenge = string.atoi(string.strip(line)) - response = self._encode_challenge(challenge) - line = `long(response)` - if line[-1] in 'Ll': line = line[:-1] - self._wf.write(line + '\n') - self._wf.flush() - self._post_init() - -class _stub: - - """Helper class for Client -- each instance serves as a method of the client.""" - - def __init__(self, client, name): - self._client = client - self._name = name - - def __call__(self, *args): - return self._client._vcall(self._name, args) - diff --git a/Demo/pdist/cmdfw.py b/Demo/pdist/cmdfw.py deleted file mode 100755 index a0c6f5d8ec..0000000000 --- a/Demo/pdist/cmdfw.py +++ /dev/null @@ -1,144 +0,0 @@ -"Framework for command line interfaces like CVS. See class CmdFrameWork." - - -class CommandFrameWork: - - """Framework class for command line interfaces like CVS. - - The general command line structure is - - command [flags] subcommand [subflags] [argument] ... - - There's a class variable GlobalFlags which specifies the - global flags options. Subcommands are defined by defining - methods named do_. Flags for the subcommand are - defined by defining class or instance variables named - flags_. If there's no command, method default() - is called. The __doc__ strings for the do_ methods are used - for the usage message, printed after the general usage message - which is the class variable UsageMessage. The class variable - PostUsageMessage is printed after all the do_ methods' __doc__ - strings. The method's return value can be a suggested exit - status. [XXX Need to rewrite this to clarify it.] - - Common usage is to derive a class, instantiate it, and then call its - run() method; by default this takes its arguments from sys.argv[1:]. - """ - - UsageMessage = \ - "usage: (name)s [flags] subcommand [subflags] [argument] ..." - - PostUsageMessage = None - - GlobalFlags = '' - - def __init__(self): - """Constructor, present for completeness.""" - pass - - def run(self, args = None): - """Process flags, subcommand and options, then run it.""" - import getopt, sys - if args is None: args = sys.argv[1:] - try: - opts, args = getopt.getopt(args, self.GlobalFlags) - except getopt.error, msg: - return self.usage(msg) - self.options(opts) - if not args: - self.ready() - return self.default() - else: - cmd = args[0] - mname = 'do_' + cmd - fname = 'flags_' + cmd - try: - method = getattr(self, mname) - except AttributeError: - return self.usage("command %s unknown" % `cmd`) - try: - flags = getattr(self, fname) - except AttributeError: - flags = '' - try: - opts, args = getopt.getopt(args[1:], flags) - except getopt.error, msg: - return self.usage( - "subcommand %s: " % cmd + str(msg)) - self.ready() - return method(opts, args) - - def options(self, opts): - """Process the options retrieved by getopt. - Override this if you have any options.""" - if opts: - print "-"*40 - print "Options:" - for o, a in opts: - print 'option', o, 'value', `a` - print "-"*40 - - def ready(self): - """Called just before calling the subcommand.""" - pass - - def usage(self, msg = None): - """Print usage message. Return suitable exit code (2).""" - if msg: print msg - print self.UsageMessage % {'name': self.__class__.__name__} - docstrings = {} - c = self.__class__ - while 1: - for name in dir(c): - if name[:3] == 'do_': - if docstrings.has_key(name): - continue - try: - doc = getattr(c, name).__doc__ - except: - doc = None - if doc: - docstrings[name] = doc - if not c.__bases__: - break - c = c.__bases__[0] - if docstrings: - print "where subcommand can be:" - names = docstrings.keys() - names.sort() - for name in names: - print docstrings[name] - if self.PostUsageMessage: - print self.PostUsageMessage - return 2 - - def default(self): - """Default method, called when no subcommand is given. - You should always override this.""" - print "Nobody expects the Spanish Inquisition!" - - -def test(): - """Test script -- called when this module is run as a script.""" - import sys - class Hello(CommandFrameWork): - def do_hello(self, opts, args): - "hello -- print 'hello world', needs no arguments" - print "Hello, world" - x = Hello() - tests = [ - [], - ['hello'], - ['spam'], - ['-x'], - ['hello', '-x'], - None, - ] - for t in tests: - print '-'*10, t, '-'*10 - sts = x.run(t) - print "Exit status:", `sts` - - -if __name__ == '__main__': - test() diff --git a/Demo/pdist/cmptree.py b/Demo/pdist/cmptree.py deleted file mode 100755 index 7eaa6c3697..0000000000 --- a/Demo/pdist/cmptree.py +++ /dev/null @@ -1,208 +0,0 @@ -"""Compare local and remote dictionaries and transfer differing files -- like rdist.""" - -import sys -from repr import repr -import FSProxy -import time -import os - -def main(): - pwd = os.getcwd() - s = raw_input("chdir [%s] " % pwd) - if s: - os.chdir(s) - pwd = os.getcwd() - host = ask("host", 'voorn.cwi.nl') - port = 4127 - verbose = 1 - mode = '' - print """\ -Mode should be a string of characters, indicating what to do with differences. -r - read different files to local file system -w - write different files to remote file system -c - create new files, either remote or local -d - delete disappearing files, either remote or local -""" - s = raw_input("mode [%s] " % mode) - if s: mode = s - address = (host, port) - t1 = time.time() - local = FSProxy.FSProxyLocal() - remote = FSProxy.FSProxyClient(address, verbose) - compare(local, remote, mode) - remote._close() - local._close() - t2 = time.time() - dt = t2-t1 - mins, secs = divmod(dt, 60) - print mins, "minutes and", round(secs), "seconds" - raw_input("[Return to exit] ") - -def ask(prompt, default): - s = raw_input("%s [%s] " % (prompt, default)) - return s or default - -def askint(prompt, default): - s = raw_input("%s [%s] " % (prompt, str(default))) - if s: return string.atoi(s) - return default - -def compare(local, remote, mode): - print - print "PWD =", `os.getcwd()` - sums_id = remote._send('sumlist') - subdirs_id = remote._send('listsubdirs') - remote._flush() - print "calculating local sums ..." - lsumdict = {} - for name, info in local.sumlist(): - lsumdict[name] = info - print "getting remote sums ..." - sums = remote._recv(sums_id) - print "got", len(sums) - rsumdict = {} - for name, rsum in sums: - rsumdict[name] = rsum - if not lsumdict.has_key(name): - print `name`, "only remote" - if 'r' in mode and 'c' in mode: - recvfile(local, remote, name) - else: - lsum = lsumdict[name] - if lsum != rsum: - print `name`, - rmtime = remote.mtime(name) - lmtime = local.mtime(name) - if rmtime > lmtime: - print "remote newer", - if 'r' in mode: - recvfile(local, remote, name) - elif lmtime > rmtime: - print "local newer", - if 'w' in mode: - sendfile(local, remote, name) - else: - print "same mtime but different sum?!?!", - print - for name in lsumdict.keys(): - if not rsumdict.keys(): - print `name`, "only locally", - fl() - if 'w' in mode and 'c' in mode: - sendfile(local, remote, name) - elif 'r' in mode and 'd' in mode: - os.unlink(name) - print "removed." - print - print "gettin subdirs ..." - subdirs = remote._recv(subdirs_id) - common = [] - for name in subdirs: - if local.isdir(name): - print "Common subdirectory", repr(name) - common.append(name) - else: - print "Remote subdirectory", repr(name), "not found locally" - if 'r' in mode and 'c' in mode: - pr = "Create local subdirectory %s? [y] " % \ - repr(name) - if 'y' in mode: - ok = 'y' - else: - ok = ask(pr, "y") - if ok[:1] in ('y', 'Y'): - local.mkdir(name) - print "Subdirectory %s made" % \ - repr(name) - common.append(name) - lsubdirs = local.listsubdirs() - for name in lsubdirs: - if name not in subdirs: - print "Local subdirectory", repr(name), "not found remotely" - for name in common: - print "Entering subdirectory", repr(name) - local.cd(name) - remote.cd(name) - compare(local, remote, mode) - remote.back() - local.back() - -def sendfile(local, remote, name): - try: - remote.create(name) - except (IOError, os.error), msg: - print "cannot create:", msg - return - - print "sending ...", - fl() - - data = open(name).read() - - t1 = time.time() - - remote._send_noreply('write', name, data) - remote._flush() - - t2 = time.time() - - dt = t2-t1 - print len(data), "bytes in", round(dt), "seconds", - if dt: - print "i.e.", round(len(data)/dt), "bytes/sec", - print - -def recvfile(local, remote, name): - ok = 0 - try: - rv = recvfile_real(local, remote, name) - ok = 1 - return rv - finally: - if not ok: - print "*** recvfile of %s failed, deleting" % `name` - local.delete(name) - -def recvfile_real(local, remote, name): - try: - local.create(name) - except (IOError, os.error), msg: - print "cannot create:", msg - return - - print "receiving ...", - fl() - - f = open(name, 'w') - t1 = time.time() - - length = 4*1024 - offset = 0 - id = remote._send('read', name, offset, length) - remote._flush() - while 1: - newoffset = offset + length - newid = remote._send('read', name, newoffset, length) - data = remote._recv(id) - id = newid - if not data: break - f.seek(offset) - f.write(data) - offset = newoffset - size = f.tell() - - t2 = time.time() - f.close() - - dt = t2-t1 - print size, "bytes in", round(dt), "seconds", - if dt: - print "i.e.", int(size/dt), "bytes/sec", - print - remote._recv(id) # ignored - -def fl(): - sys.stdout.flush() - -if __name__ == '__main__': - main() diff --git a/Demo/pdist/cvslib.py b/Demo/pdist/cvslib.py deleted file mode 100755 index cf305c9798..0000000000 --- a/Demo/pdist/cvslib.py +++ /dev/null @@ -1,364 +0,0 @@ -"""Utilities for CVS administration.""" - -import string -import os -import time -import md5 -import fnmatch - -if not hasattr(time, 'timezone'): - time.timezone = 0 - -class File: - - """Represent a file's status. - - Instance variables: - - file -- the filename (no slashes), None if uninitialized - lseen -- true if the data for the local file is up to date - eseen -- true if the data from the CVS/Entries entry is up to date - (this implies that the entry must be written back) - rseen -- true if the data for the remote file is up to date - proxy -- RCSProxy instance used to contact the server, or None - - Note that lseen and rseen don't necessary mean that a local - or remote file *exists* -- they indicate that we've checked it. - However, eseen means that this instance corresponds to an - entry in the CVS/Entries file. - - If lseen is true: - - lsum -- checksum of the local file, None if no local file - lctime -- ctime of the local file, None if no local file - lmtime -- mtime of the local file, None if no local file - - If eseen is true: - - erev -- revision, None if this is a no revision (not '0') - enew -- true if this is an uncommitted added file - edeleted -- true if this is an uncommitted removed file - ectime -- ctime of last local file corresponding to erev - emtime -- mtime of last local file corresponding to erev - extra -- 5th string from CVS/Entries file - - If rseen is true: - - rrev -- revision of head, None if non-existent - rsum -- checksum of that revision, Non if non-existent - - If eseen and rseen are both true: - - esum -- checksum of revision erev, None if no revision - - Note - """ - - def __init__(self, file = None): - if file and '/' in file: - raise ValueError, "no slash allowed in file" - self.file = file - self.lseen = self.eseen = self.rseen = 0 - self.proxy = None - - def __cmp__(self, other): - return cmp(self.file, other.file) - - def getlocal(self): - try: - self.lmtime, self.lctime = os.stat(self.file)[-2:] - except os.error: - self.lmtime = self.lctime = self.lsum = None - else: - self.lsum = md5.md5(open(self.file).read()).digest() - self.lseen = 1 - - def getentry(self, line): - words = string.splitfields(line, '/') - if self.file and words[1] != self.file: - raise ValueError, "file name mismatch" - self.file = words[1] - self.erev = words[2] - self.edeleted = 0 - self.enew = 0 - self.ectime = self.emtime = None - if self.erev[:1] == '-': - self.edeleted = 1 - self.erev = self.erev[1:] - if self.erev == '0': - self.erev = None - self.enew = 1 - else: - dates = words[3] - self.ectime = unctime(dates[:24]) - self.emtime = unctime(dates[25:]) - self.extra = words[4] - if self.rseen: - self.getesum() - self.eseen = 1 - - def getremote(self, proxy = None): - if proxy: - self.proxy = proxy - try: - self.rrev = self.proxy.head(self.file) - except (os.error, IOError): - self.rrev = None - if self.rrev: - self.rsum = self.proxy.sum(self.file) - else: - self.rsum = None - if self.eseen: - self.getesum() - self.rseen = 1 - - def getesum(self): - if self.erev == self.rrev: - self.esum = self.rsum - elif self.erev: - name = (self.file, self.erev) - self.esum = self.proxy.sum(name) - else: - self.esum = None - - def putentry(self): - """Return a line suitable for inclusion in CVS/Entries. - - The returned line is terminated by a newline. - If no entry should be written for this file, - return "". - """ - if not self.eseen: - return "" - - rev = self.erev or '0' - if self.edeleted: - rev = '-' + rev - if self.enew: - dates = 'Initial ' + self.file - else: - dates = gmctime(self.ectime) + ' ' + \ - gmctime(self.emtime) - return "/%s/%s/%s/%s/\n" % ( - self.file, - rev, - dates, - self.extra) - - def report(self): - print '-'*50 - def r(key, repr=repr, self=self): - try: - value = repr(getattr(self, key)) - except AttributeError: - value = "?" - print "%-15s:" % key, value - r("file") - if self.lseen: - r("lsum", hexify) - r("lctime", gmctime) - r("lmtime", gmctime) - if self.eseen: - r("erev") - r("enew") - r("edeleted") - r("ectime", gmctime) - r("emtime", gmctime) - if self.rseen: - r("rrev") - r("rsum", hexify) - if self.eseen: - r("esum", hexify) - - -class CVS: - - """Represent the contents of a CVS admin file (and more). - - Class variables: - - FileClass -- the class to be instantiated for entries - (this should be derived from class File above) - IgnoreList -- shell patterns for local files to be ignored - - Instance variables: - - entries -- a dictionary containing File instances keyed by - their file name - proxy -- an RCSProxy instance, or None - """ - - FileClass = File - - IgnoreList = ['.*', '@*', ',*', '*~', '*.o', '*.a', '*.so', '*.pyc'] - - def __init__(self): - self.entries = {} - self.proxy = None - - def setproxy(self, proxy): - if proxy is self.proxy: - return - self.proxy = proxy - for e in self.entries.values(): - e.rseen = 0 - - def getentries(self): - """Read the contents of CVS/Entries""" - self.entries = {} - f = self.cvsopen("Entries") - while 1: - line = f.readline() - if not line: break - e = self.FileClass() - e.getentry(line) - self.entries[e.file] = e - f.close() - - def putentries(self): - """Write CVS/Entries back""" - f = self.cvsopen("Entries", 'w') - for e in self.values(): - f.write(e.putentry()) - f.close() - - def getlocalfiles(self): - list = self.entries.keys() - addlist = os.listdir(os.curdir) - for name in addlist: - if name in list: - continue - if not self.ignored(name): - list.append(name) - list.sort() - for file in list: - try: - e = self.entries[file] - except KeyError: - e = self.entries[file] = self.FileClass(file) - e.getlocal() - - def getremotefiles(self, proxy = None): - if proxy: - self.proxy = proxy - if not self.proxy: - raise RuntimeError, "no RCS proxy" - addlist = self.proxy.listfiles() - for file in addlist: - try: - e = self.entries[file] - except KeyError: - e = self.entries[file] = self.FileClass(file) - e.getremote(self.proxy) - - def report(self): - for e in self.values(): - e.report() - print '-'*50 - - def keys(self): - keys = self.entries.keys() - keys.sort() - return keys - - def values(self): - def value(key, self=self): - return self.entries[key] - return map(value, self.keys()) - - def items(self): - def item(key, self=self): - return (key, self.entries[key]) - return map(item, self.keys()) - - def cvsexists(self, file): - file = os.path.join("CVS", file) - return os.path.exists(file) - - def cvsopen(self, file, mode = 'r'): - file = os.path.join("CVS", file) - if 'r' not in mode: - self.backup(file) - return open(file, mode) - - def backup(self, file): - if os.path.isfile(file): - bfile = file + '~' - try: os.unlink(bfile) - except os.error: pass - os.rename(file, bfile) - - def ignored(self, file): - if os.path.isdir(file): return 1 - for pat in self.IgnoreList: - if fnmatch.fnmatch(file, pat): return 1 - return 0 - - -# hexify and unhexify are useful to print MD5 checksums in hex format - -hexify_format = '%02x' * 16 -def hexify(sum): - "Return a hex representation of a 16-byte string (e.g. an MD5 digest)" - if sum is None: - return "None" - return hexify_format % tuple(map(ord, sum)) - -def unhexify(hexsum): - "Return the original from a hexified string" - if hexsum == "None": - return None - sum = '' - for i in range(0, len(hexsum), 2): - sum = sum + chr(string.atoi(hexsum[i:i+2], 16)) - return sum - - -unctime_monthmap = {} -def unctime(date): - if date == "None": return None - if not unctime_monthmap: - months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] - i = 0 - for m in months: - i = i+1 - unctime_monthmap[m] = i - words = string.split(date) # Day Mon DD HH:MM:SS YEAR - year = string.atoi(words[4]) - month = unctime_monthmap[words[1]] - day = string.atoi(words[2]) - [hh, mm, ss] = map(string.atoi, string.splitfields(words[3], ':')) - ss = ss - time.timezone - return time.mktime((year, month, day, hh, mm, ss, 0, 0, 0)) - -def gmctime(t): - if t is None: return "None" - return time.asctime(time.gmtime(t)) - -def test_unctime(): - now = int(time.time()) - t = time.gmtime(now) - at = time.asctime(t) - print 'GMT', now, at - print 'timezone', time.timezone - print 'local', time.ctime(now) - u = unctime(at) - print 'unctime()', u - gu = time.gmtime(u) - print '->', gu - print time.asctime(gu) - -def test(): - x = CVS() - x.getentries() - x.getlocalfiles() -## x.report() - import rcsclient - proxy = rcsclient.openrcsclient() - x.getremotefiles(proxy) - x.report() - - -if __name__ == "__main__": - test() diff --git a/Demo/pdist/cvslock.py b/Demo/pdist/cvslock.py deleted file mode 100755 index a421e1a943..0000000000 --- a/Demo/pdist/cvslock.py +++ /dev/null @@ -1,280 +0,0 @@ -"""CVS locking algorithm. - -CVS locking strategy -==================== - -As reverse engineered from the CVS 1.3 sources (file lock.c): - -- Locking is done on a per repository basis (but a process can hold -write locks for multiple directories); all lock files are placed in -the repository and have names beginning with "#cvs.". - -- Before even attempting to lock, a file "#cvs.tfl." is created -(and removed again), to test that we can write the repository. [The -algorithm can still be fooled (1) if the repository's mode is changed -while attempting to lock; (2) if this file exists and is writable but -the directory is not.] - -- While creating the actual read/write lock files (which may exist for -a long time), a "meta-lock" is held. The meta-lock is a directory -named "#cvs.lock" in the repository. The meta-lock is also held while -a write lock is held. - -- To set a read lock: - - - acquire the meta-lock - - create the file "#cvs.rfl." - - release the meta-lock - -- To set a write lock: - - - acquire the meta-lock - - check that there are no files called "#cvs.rfl.*" - - if there are, release the meta-lock, sleep, try again - - create the file "#cvs.wfl." - -- To release a write lock: - - - remove the file "#cvs.wfl." - - rmdir the meta-lock - -- To release a read lock: - - - remove the file "#cvs.rfl." - - -Additional notes ----------------- - -- A process should read-lock at most one repository at a time. - -- A process may write-lock as many repositories as it wishes (to avoid -deadlocks, I presume it should always lock them top-down in the -directory hierarchy). - -- A process should make sure it removes all its lock files and -directories when it crashes. - -- Limitation: one user id should not be committing files into the same -repository at the same time. - - -Turn this into Python code --------------------------- - -rl = ReadLock(repository, waittime) - -wl = WriteLock(repository, waittime) - -list = MultipleWriteLock([repository1, repository2, ...], waittime) - -""" - - -import os -import time -import stat -import pwd - - -# Default wait time -DELAY = 10 - - -# XXX This should be the same on all Unix versions -EEXIST = 17 - - -# Files used for locking (must match cvs.h in the CVS sources) -CVSLCK = "#cvs.lck" -CVSRFL = "#cvs.rfl." -CVSWFL = "#cvs.wfl." - - -class Error: - - def __init__(self, msg): - self.msg = msg - - def __repr__(self): - return repr(self.msg) - - def __str__(self): - return str(self.msg) - - -class Locked(Error): - pass - - -class Lock: - - def __init__(self, repository = ".", delay = DELAY): - self.repository = repository - self.delay = delay - self.lockdir = None - self.lockfile = None - pid = `os.getpid()` - self.cvslck = self.join(CVSLCK) - self.cvsrfl = self.join(CVSRFL + pid) - self.cvswfl = self.join(CVSWFL + pid) - - def __del__(self): - print "__del__" - self.unlock() - - def setlockdir(self): - while 1: - try: - self.lockdir = self.cvslck - os.mkdir(self.cvslck, 0777) - return - except os.error, msg: - self.lockdir = None - if msg[0] == EEXIST: - try: - st = os.stat(self.cvslck) - except os.error: - continue - self.sleep(st) - continue - raise Error("failed to lock %s: %s" % ( - self.repository, msg)) - - def unlock(self): - self.unlockfile() - self.unlockdir() - - def unlockfile(self): - if self.lockfile: - print "unlink", self.lockfile - try: - os.unlink(self.lockfile) - except os.error: - pass - self.lockfile = None - - def unlockdir(self): - if self.lockdir: - print "rmdir", self.lockdir - try: - os.rmdir(self.lockdir) - except os.error: - pass - self.lockdir = None - - def sleep(self, st): - sleep(st, self.repository, self.delay) - - def join(self, name): - return os.path.join(self.repository, name) - - -def sleep(st, repository, delay): - if delay <= 0: - raise Locked(st) - uid = st[stat.ST_UID] - try: - pwent = pwd.getpwuid(uid) - user = pwent[0] - except KeyError: - user = "uid %d" % uid - print "[%s]" % time.ctime(time.time())[11:19], - print "Waiting for %s's lock in" % user, repository - time.sleep(delay) - - -class ReadLock(Lock): - - def __init__(self, repository, delay = DELAY): - Lock.__init__(self, repository, delay) - ok = 0 - try: - self.setlockdir() - self.lockfile = self.cvsrfl - fp = open(self.lockfile, 'w') - fp.close() - ok = 1 - finally: - if not ok: - self.unlockfile() - self.unlockdir() - - -class WriteLock(Lock): - - def __init__(self, repository, delay = DELAY): - Lock.__init__(self, repository, delay) - self.setlockdir() - while 1: - uid = self.readers_exist() - if not uid: - break - self.unlockdir() - self.sleep(uid) - self.lockfile = self.cvswfl - fp = open(self.lockfile, 'w') - fp.close() - - def readers_exist(self): - n = len(CVSRFL) - for name in os.listdir(self.repository): - if name[:n] == CVSRFL: - try: - st = os.stat(self.join(name)) - except os.error: - continue - return st - return None - - -def MultipleWriteLock(repositories, delay = DELAY): - while 1: - locks = [] - for r in repositories: - try: - locks.append(WriteLock(r, 0)) - except Locked, instance: - del locks - break - else: - break - sleep(instance.msg, r, delay) - return list - - -def test(): - import sys - if sys.argv[1:]: - repository = sys.argv[1] - else: - repository = "." - rl = None - wl = None - try: - print "attempting write lock ..." - wl = WriteLock(repository) - print "got it." - wl.unlock() - print "attempting read lock ..." - rl = ReadLock(repository) - print "got it." - rl.unlock() - finally: - print [1] - sys.exc_traceback = None - print [2] - if rl: - rl.unlock() - print [3] - if wl: - wl.unlock() - print [4] - rl = None - print [5] - wl = None - print [6] - - -if __name__ == '__main__': - test() diff --git a/Demo/pdist/mac.py b/Demo/pdist/mac.py deleted file mode 100755 index 516ee153e4..0000000000 --- a/Demo/pdist/mac.py +++ /dev/null @@ -1,19 +0,0 @@ -import sys -import string -import rcvs - -def main(): - while 1: - try: - line = raw_input('$ ') - except EOFError: - break - words = string.split(line) - if not words: - continue - if words[0] != 'rcvs': - words.insert(0, 'rcvs') - sys.argv = words - rcvs.main() - -main() diff --git a/Demo/pdist/makechangelog.py b/Demo/pdist/makechangelog.py deleted file mode 100755 index b26f30b3a0..0000000000 --- a/Demo/pdist/makechangelog.py +++ /dev/null @@ -1,109 +0,0 @@ -#! /usr/bin/env python - -"""Turn a pile of RCS log output into ChangeLog file entries. - -""" - -import sys -import string -import regex -import getopt -import time - -def main(): - args = sys.argv[1:] - opts, args = getopt.getopt(args, 'p:') - prefix = '' - for o, a in opts: - if p == '-p': prefix = a - - f = sys.stdin - allrevs = [] - while 1: - file = getnextfile(f) - if not file: break - revs = [] - while 1: - rev = getnextrev(f, file) - if not rev: - break - revs.append(rev) - if revs: - allrevs[len(allrevs):] = revs - allrevs.sort() - allrevs.reverse() - for rev in allrevs: - formatrev(rev, prefix) - -parsedateprog = regex.compile( - '^date: \([0-9]+\)/\([0-9]+\)/\([0-9]+\) ' + - '\([0-9]+\):\([0-9]+\):\([0-9]+\); author: \([^ ;]+\)') - -authormap = { - 'guido': 'Guido van Rossum ', - 'jack': 'Jack Jansen ', - 'sjoerd': 'Sjoerd Mullender ', - } - -def formatrev(rev, prefix): - dateline, file, revline, log = rev - if parsedateprog.match(dateline) >= 0: - fields = parsedateprog.group(1, 2, 3, 4, 5, 6) - author = parsedateprog.group(7) - if authormap.has_key(author): author = authormap[author] - tfields = map(string.atoi, fields) + [0, 0, 0] - tfields[5] = tfields[5] - time.timezone - t = time.mktime(tuple(tfields)) - print time.ctime(t), '', author - words = string.split(log) - words[:0] = ['*', prefix + file + ':'] - maxcol = 72-8 - col = maxcol - for word in words: - if col > 0 and col + len(word) >= maxcol: - print - print '\t' + word, - col = -1 - else: - print word, - col = col + 1 + len(word) - print - print - -startprog = regex.compile("^Working file: \(.*\)$") - -def getnextfile(f): - while 1: - line = f.readline() - if not line: return None - if startprog.match(line) >= 0: - file = startprog.group(1) - # Skip until first revision - while 1: - line = f.readline() - if not line: return None - if line[:10] == '='*10: return None - if line[:10] == '-'*10: break -## print "Skipped", line, - return file -## else: -## print "Ignored", line, - -def getnextrev(f, file): - # This is called when we are positioned just after a '---' separator - revline = f.readline() - dateline = f.readline() - log = '' - while 1: - line = f.readline() - if not line: break - if line[:10] == '='*10: - # Ignore the *last* log entry for each file since it - # is the revision since which we are logging. - return None - if line[:10] == '-'*10: break - log = log + line - return dateline, file, revline, log - -if __name__ == '__main__': - main() diff --git a/Demo/pdist/new b/Demo/pdist/new deleted file mode 100755 index 9daeafb986..0000000000 --- a/Demo/pdist/new +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/Demo/pdist/rcsbump b/Demo/pdist/rcsbump deleted file mode 100755 index e4e9ed558d..0000000000 --- a/Demo/pdist/rcsbump +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env python -# -*- python -*- -# -# guido's version, from rcsbump,v 1.2 1995/06/22 21:27:27 bwarsaw Exp -# -# Python script for bumping up an RCS major revision number. - -import sys -import regex -import rcslib -import string - -WITHLOCK = 1 -majorrev_re = regex.compile('^[0-9]+') - -dir = rcslib.RCS() - -if sys.argv[1:]: - files = sys.argv[1:] -else: - files = dir.listfiles() - -for file in files: - # get the major revnumber of the file - headbranch = dir.info(file)['head'] - majorrev_re.match(headbranch) - majorrev = string.atoi(majorrev_re.group(0)) + 1 - - if not dir.islocked(file): - dir.checkout(file, WITHLOCK) - - msg = "Bumping major revision number (to %d)" % majorrev - dir.checkin((file, "%s.0" % majorrev), msg, "-f") diff --git a/Demo/pdist/rcsclient.py b/Demo/pdist/rcsclient.py deleted file mode 100755 index 5d88a57981..0000000000 --- a/Demo/pdist/rcsclient.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Customize this file to change the default client etc. - -(In general, it is probably be better to make local operation the -default and to require something like an RCSSERVER environment -variable to enable remote operation.) - -""" - -import string -import os - -# These defaults don't belong here -- they should be taken from the -# environment or from a hidden file in the current directory - -HOST = 'voorn.cwi.nl' -PORT = 4127 -VERBOSE = 1 -LOCAL = 0 - -import client - - -class RCSProxyClient(client.SecureClient): - - def __init__(self, address, verbose = client.VERBOSE): - client.SecureClient.__init__(self, address, verbose) - - -def openrcsclient(opts = []): - "open an RCSProxy client based on a list of options returned by getopt" - import RCSProxy - host = HOST - port = PORT - verbose = VERBOSE - local = LOCAL - directory = None - for o, a in opts: - if o == '-h': - host = a - if ':' in host: - i = string.find(host, ':') - host, p = host[:i], host[i+1:] - if p: - port = string.atoi(p) - if o == '-p': - port = string.atoi(a) - if o == '-d': - directory = a - if o == '-v': - verbose = verbose + 1 - if o == '-q': - verbose = 0 - if o == '-L': - local = 1 - if local: - import RCSProxy - x = RCSProxy.RCSProxyLocal() - else: - address = (host, port) - x = RCSProxyClient(address, verbose) - if not directory: - try: - directory = open(os.path.join("CVS", "Repository")).readline() - except IOError: - pass - else: - if directory[-1] == '\n': - directory = directory[:-1] - if directory: - x.cd(directory) - return x diff --git a/Demo/pdist/rcslib.py b/Demo/pdist/rcslib.py deleted file mode 100755 index 5e79247cb3..0000000000 --- a/Demo/pdist/rcslib.py +++ /dev/null @@ -1,339 +0,0 @@ -"""RCS interface module. - -Defines the class RCS, which represents a directory with rcs version -files and (possibly) corresponding work files. - -""" - - -import fnmatch -import os -import regsub -import string -import tempfile - - -class RCS: - - """RCS interface class (local filesystem version). - - An instance of this class represents a directory with rcs version - files and (possible) corresponding work files. - - Methods provide access to most rcs operations such as - checkin/checkout, access to the rcs metadata (revisions, logs, - branches etc.) as well as some filesystem operations such as - listing all rcs version files. - - XXX BUGS / PROBLEMS - - - The instance always represents the current directory so it's not - very useful to have more than one instance around simultaneously - - """ - - # Characters allowed in work file names - okchars = string.letters + string.digits + '-_=+.' - - def __init__(self): - """Constructor.""" - pass - - def __del__(self): - """Destructor.""" - pass - - # --- Informational methods about a single file/revision --- - - def log(self, name_rev, otherflags = ''): - """Return the full log text for NAME_REV as a string. - - Optional OTHERFLAGS are passed to rlog. - - """ - f = self._open(name_rev, 'rlog ' + otherflags) - data = f.read() - status = self._closepipe(f) - if status: - data = data + "%s: %s" % status - elif data[-1] == '\n': - data = data[:-1] - return data - - def head(self, name_rev): - """Return the head revision for NAME_REV""" - dict = self.info(name_rev) - return dict['head'] - - def info(self, name_rev): - """Return a dictionary of info (from rlog -h) for NAME_REV - - The dictionary's keys are the keywords that rlog prints - (e.g. 'head' and its values are the corresponding data - (e.g. '1.3'). - - XXX symbolic names and locks are not returned - - """ - f = self._open(name_rev, 'rlog -h') - dict = {} - while 1: - line = f.readline() - if not line: break - if line[0] == '\t': - # XXX could be a lock or symbolic name - # Anything else? - continue - i = string.find(line, ':') - if i > 0: - key, value = line[:i], string.strip(line[i+1:]) - dict[key] = value - status = self._closepipe(f) - if status: - raise IOError, status - return dict - - # --- Methods that change files --- - - def lock(self, name_rev): - """Set an rcs lock on NAME_REV.""" - name, rev = self.checkfile(name_rev) - cmd = "rcs -l%s %s" % (rev, name) - return self._system(cmd) - - def unlock(self, name_rev): - """Clear an rcs lock on NAME_REV.""" - name, rev = self.checkfile(name_rev) - cmd = "rcs -u%s %s" % (rev, name) - return self._system(cmd) - - def checkout(self, name_rev, withlock=0, otherflags=""): - """Check out NAME_REV to its work file. - - If optional WITHLOCK is set, check out locked, else unlocked. - - The optional OTHERFLAGS is passed to co without - interpretation. - - Any output from co goes to directly to stdout. - - """ - name, rev = self.checkfile(name_rev) - if withlock: lockflag = "-l" - else: lockflag = "-u" - cmd = 'co %s%s %s %s' % (lockflag, rev, otherflags, name) - return self._system(cmd) - - def checkin(self, name_rev, message=None, otherflags=""): - """Check in NAME_REV from its work file. - - The optional MESSAGE argument becomes the checkin message - (default "" if None); or the file description if this is - a new file. - - The optional OTHERFLAGS argument is passed to ci without - interpretation. - - Any output from ci goes to directly to stdout. - - """ - name, rev = self._unmangle(name_rev) - new = not self.isvalid(name) - if not message: message = "" - if message and message[-1] != '\n': - message = message + '\n' - lockflag = "-u" - textfile = None - try: - if new: - textfile = tempfile.mktemp() - f = open(textfile, 'w') - f.write(message) - f.close() - cmd = 'ci %s%s -t%s %s %s' % \ - (lockflag, rev, textfile, otherflags, name) - else: - message = regsub.gsub('\([\\"$`]\)', '\\\\\\1', message) - cmd = 'ci %s%s -m"%s" %s %s' % \ - (lockflag, rev, message, otherflags, name) - return self._system(cmd) - finally: - if textfile: self._remove(textfile) - - # --- Exported support methods --- - - def listfiles(self, pat = None): - """Return a list of all version files matching optional PATTERN.""" - files = os.listdir(os.curdir) - files = filter(self._isrcs, files) - if os.path.isdir('RCS'): - files2 = os.listdir('RCS') - files2 = filter(self._isrcs, files2) - files = files + files2 - files = map(self.realname, files) - return self._filter(files, pat) - - def isvalid(self, name): - """Test whether NAME has a version file associated.""" - namev = self.rcsname(name) - return (os.path.isfile(namev) or - os.path.isfile(os.path.join('RCS', namev))) - - def rcsname(self, name): - """Return the pathname of the version file for NAME. - - The argument can be a work file name or a version file name. - If the version file does not exist, the name of the version - file that would be created by "ci" is returned. - - """ - if self._isrcs(name): namev = name - else: namev = name + ',v' - if os.path.isfile(namev): return namev - namev = os.path.join('RCS', os.path.basename(namev)) - if os.path.isfile(namev): return namev - if os.path.isdir('RCS'): - return os.path.join('RCS', namev) - else: - return namev - - def realname(self, namev): - """Return the pathname of the work file for NAME. - - The argument can be a work file name or a version file name. - If the work file does not exist, the name of the work file - that would be created by "co" is returned. - - """ - if self._isrcs(namev): name = namev[:-2] - else: name = namev - if os.path.isfile(name): return name - name = os.path.basename(name) - return name - - def islocked(self, name_rev): - """Test whether FILE (which must have a version file) is locked. - - XXX This does not tell you which revision number is locked and - ignores any revision you may pass in (by virtue of using rlog - -L -R). - - """ - f = self._open(name_rev, 'rlog -L -R') - line = f.readline() - status = self._closepipe(f) - if status: - raise IOError, status - if not line: return None - if line[-1] == '\n': - line = line[:-1] - return self.realname(name_rev) == self.realname(line) - - def checkfile(self, name_rev): - """Normalize NAME_REV into a (NAME, REV) tuple. - - Raise an exception if there is no corresponding version file. - - """ - name, rev = self._unmangle(name_rev) - if not self.isvalid(name): - raise os.error, 'not an rcs file %s' % `name` - return name, rev - - # --- Internal methods --- - - def _open(self, name_rev, cmd = 'co -p', rflag = '-r'): - """INTERNAL: open a read pipe to NAME_REV using optional COMMAND. - - Optional FLAG is used to indicate the revision (default -r). - - Default COMMAND is "co -p". - - Return a file object connected by a pipe to the command's - output. - - """ - name, rev = self.checkfile(name_rev) - namev = self.rcsname(name) - if rev: - cmd = cmd + ' ' + rflag + rev - return os.popen("%s %s" % (cmd, `namev`)) - - def _unmangle(self, name_rev): - """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple. - - Raise an exception if NAME contains invalid characters. - - A NAME_REV argument is either NAME string (implying REV='') or - a tuple of the form (NAME, REV). - - """ - if type(name_rev) == type(''): - name_rev = name, rev = name_rev, '' - else: - name, rev = name_rev - for c in rev: - if c not in self.okchars: - raise ValueError, "bad char in rev" - return name_rev - - def _closepipe(self, f): - """INTERNAL: Close PIPE and print its exit status if nonzero.""" - sts = f.close() - if not sts: return None - detail, reason = divmod(sts, 256) - if reason == 0: return 'exit', detail # Exit status - signal = reason&0x7F - if signal == 0x7F: - code = 'stopped' - signal = detail - else: - code = 'killed' - if reason&0x80: - code = code + '(coredump)' - return code, signal - - def _system(self, cmd): - """INTERNAL: run COMMAND in a subshell. - - Standard input for the command is taken from /dev/null. - - Raise IOError when the exit status is not zero. - - Return whatever the calling method should return; normally - None. - - A derived class may override this method and redefine it to - capture stdout/stderr of the command and return it. - - """ - cmd = cmd + " > ") - sys.stderr.flush() - line = sys.stdin.readline() - if not line or line == '.\n': break - message = message + line - return message - -def remove(fn): - try: - os.unlink(fn) - except os.error: - pass - -commands = { - 'ci': ('', checkin), - 'put': ('', checkin), - 'co': ('', checkout), - 'get': ('', checkout), - 'info': ('', info), - 'head': ('', head), - 'list': ('', list), - 'lock': ('', lock), - 'unlock': ('', unlock), - 'log': ('bhLRtd:l:r:s:w:V:', log), - 'diff': ('c', diff), - } - -if __name__ == '__main__': - main() diff --git a/Demo/pdist/security.py b/Demo/pdist/security.py deleted file mode 100755 index 0ffd511a07..0000000000 --- a/Demo/pdist/security.py +++ /dev/null @@ -1,33 +0,0 @@ -class Security: - - def __init__(self): - import os - env = os.environ - if env.has_key('PYTHON_KEYFILE'): - keyfile = env['PYTHON_KEYFILE'] - else: - keyfile = '.python_keyfile' - if env.has_key('HOME'): - keyfile = os.path.join(env['HOME'], keyfile) - if not os.path.exists(keyfile): - import sys - for dir in sys.path: - kf = os.path.join(dir, keyfile) - if os.path.exists(kf): - keyfile = kf - break - try: - self._key = eval(open(keyfile).readline()) - except IOError: - raise IOError, "python keyfile %s: cannot open" % keyfile - - def _generate_challenge(self): - import random - return random.randint(100, 100000) - - def _compare_challenge_response(self, challenge, response): - return self._encode_challenge(challenge) == response - - def _encode_challenge(self, challenge): - p, m = self._key - return pow(long(challenge), p, m) diff --git a/Demo/pdist/server.py b/Demo/pdist/server.py deleted file mode 100755 index 423d583007..0000000000 --- a/Demo/pdist/server.py +++ /dev/null @@ -1,145 +0,0 @@ -"""RPC Server module.""" - -import sys -import socket -import pickle -from fnmatch import fnmatch -from repr import repr - - -# Default verbosity (0 = silent, 1 = print connections, 2 = print requests too) -VERBOSE = 1 - - -class Server: - - """RPC Server class. Derive a class to implement a particular service.""" - - def __init__(self, address, verbose = VERBOSE): - if type(address) == type(0): - address = ('', address) - self._address = address - self._verbose = verbose - self._socket = None - self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self._socket.bind(address) - self._socket.listen(1) - self._listening = 1 - - def _setverbose(self, verbose): - self._verbose = verbose - - def __del__(self): - self._close() - - def _close(self): - self._listening = 0 - if self._socket: - self._socket.close() - self._socket = None - - def _serverloop(self): - while self._listening: - self._serve() - - def _serve(self): - if self._verbose: print "Wait for connection ..." - conn, address = self._socket.accept() - if self._verbose: print "Accepted connection from %s" % repr(address) - if not self._verify(conn, address): - print "*** Connection from %s refused" % repr(address) - conn.close() - return - rf = conn.makefile('r') - wf = conn.makefile('w') - ok = 1 - while ok: - wf.flush() - if self._verbose > 1: print "Wait for next request ..." - ok = self._dorequest(rf, wf) - - _valid = ['192.16.201.*', '192.16.197.*', '132.151.1.*', '129.6.64.*'] - - def _verify(self, conn, address): - host, port = address - for pat in self._valid: - if fnmatch(host, pat): return 1 - return 0 - - def _dorequest(self, rf, wf): - rp = pickle.Unpickler(rf) - try: - request = rp.load() - except EOFError: - return 0 - if self._verbose > 1: print "Got request: %s" % repr(request) - try: - methodname, args, id = request - if '.' in methodname: - reply = (None, self._special(methodname, args), id) - elif methodname[0] == '_': - raise NameError, "illegal method name %s" % repr(methodname) - else: - method = getattr(self, methodname) - reply = (None, apply(method, args), id) - except: - reply = (sys.exc_type, sys.exc_value, id) - if id < 0 and reply[:2] == (None, None): - if self._verbose > 1: print "Suppress reply" - return 1 - if self._verbose > 1: print "Send reply: %s" % repr(reply) - wp = pickle.Pickler(wf) - wp.dump(reply) - return 1 - - def _special(self, methodname, args): - if methodname == '.methods': - if not hasattr(self, '_methods'): - self._methods = tuple(self._listmethods()) - return self._methods - raise NameError, "unrecognized special method name %s" % repr(methodname) - - def _listmethods(self, cl=None): - if not cl: cl = self.__class__ - names = cl.__dict__.keys() - names = filter(lambda x: x[0] != '_', names) - names.sort() - for base in cl.__bases__: - basenames = self._listmethods(base) - basenames = filter(lambda x, names=names: x not in names, basenames) - names[len(names):] = basenames - return names - - -from security import Security - - -class SecureServer(Server, Security): - - def __init__(self, *args): - apply(Server.__init__, (self,) + args) - Security.__init__(self) - - def _verify(self, conn, address): - import string - challenge = self._generate_challenge() - conn.send("%d\n" % challenge) - response = "" - while "\n" not in response and len(response) < 100: - data = conn.recv(100) - if not data: - break - response = response + data - try: - response = string.atol(string.strip(response)) - except string.atol_error: - if self._verbose > 0: - print "Invalid response syntax", `response` - return 0 - if not self._compare_challenge_response(challenge, response): - if self._verbose > 0: - print "Invalid response value", `response` - return 0 - if self._verbose > 1: - print "Response matches challenge. Go ahead!" - return 1 diff --git a/Demo/pdist/sumtree.py b/Demo/pdist/sumtree.py deleted file mode 100755 index 92c1fd0552..0000000000 --- a/Demo/pdist/sumtree.py +++ /dev/null @@ -1,24 +0,0 @@ -import time -import FSProxy - -def main(): - t1 = time.time() - #proxy = FSProxy.FSProxyClient(('voorn.cwi.nl', 4127)) - proxy = FSProxy.FSProxyLocal() - sumtree(proxy) - proxy._close() - t2 = time.time() - print t2-t1, "seconds" - raw_input("[Return to exit] ") - -def sumtree(proxy): - print "PWD =", proxy.pwd() - files = proxy.listfiles() - proxy.infolist(files) - subdirs = proxy.listsubdirs() - for name in subdirs: - proxy.cd(name) - sumtree(proxy) - proxy.back() - -main() diff --git a/Demo/pysvr/Makefile b/Demo/pysvr/Makefile deleted file mode 100644 index 7e3655354e..0000000000 --- a/Demo/pysvr/Makefile +++ /dev/null @@ -1,53 +0,0 @@ -# Makefile for 'pysvr' application embedding Python. -# Tailored for Python 1.5a3 or later. -# Some details are specific for Solaris or CNRI. -# Also see ## comments for tailoring. - -# Which C compiler -CC=gcc -##PURIFY=/usr/local/pure/purify -LINKCC=$(PURIFY) $(CC) - -# Optimization preferences -OPT=-g - -# Where Python is installed, and which version -INST=/usr/local -VER=2.0 - -# Expressions using the above definitions -- no need to change -PYVER=python$(VER) -# Use these defs when compiling against installed Python -PYC=$(INST)/lib/$(PYVER)/config -PYINCL=-I$(INST)/include/$(PYVER) -I$(PYC) -PYLIBS=$(PYC)/lib$(PYVER).a -# Use these defs when compiling against built Python -##PYINCL=-I../../Include -I../../sparc -##PYLIBS=../../sparc/lib$(PYVER).a - -# Libraries to link with -- very installation dependent -# (See LIBS= in Modules/Makefile in build tree) -RLLIBS=-lreadline -ltermcap -OTHERLIBS=-lnsl -lpthread -ldl -lm -ldb -lutil - -# Compilation and link flags -- no need to change normally -CFLAGS=$(PYINCL) $(OPT) -LIBS=$(PYLIBS) $(RLLIBS) $(OTHERLIBS) - -# Default port for the pysvr application -PORT=4000 - -# Default target -all: pysvr - -# Target to build pysvr -pysvr: pysvr.o $(PYOBJS) $(PYLIBS) - $(LINKCC) pysvr.o $(LIBS) -o pysvr - -# Target to build and run pysvr -run: pysvr - pysvr $(PORT) - -# Target to clean up the directory -clean: - -rm -f pysvr *.o *~ core diff --git a/Demo/pysvr/README b/Demo/pysvr/README deleted file mode 100644 index 5e64e38bb4..0000000000 --- a/Demo/pysvr/README +++ /dev/null @@ -1,9 +0,0 @@ -This is an example of a multi-threaded C application embedding a -Python interpreter. - -The particular application is a multi-threaded telnet-like server that -provides you with a Python prompt (instead of a shell prompt). - -The file pysvr.py is a prototype in Python. - -THIS APPLICATION IS NOT SECURE -- ONLY USE IT FOR TESTING! diff --git a/Demo/pysvr/pysvr.c b/Demo/pysvr/pysvr.c deleted file mode 100644 index 99d7b07818..0000000000 --- a/Demo/pysvr/pysvr.c +++ /dev/null @@ -1,369 +0,0 @@ -/* A multi-threaded telnet-like server that gives a Python prompt. - -Usage: pysvr [port] - -For security reasons, it only accepts requests from the current host. -This can still be insecure, but restricts violations from people who -can log in on your machine. Use with caution! - -*/ - -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include - -/* XXX Umpfh. - Python.h defines a typedef destructor, which conflicts with pthread.h. - So Python.h must be included after pthread.h. */ - -#include - -extern int Py_VerboseFlag; - -#ifndef PORT -#define PORT 4000 -#endif - -struct workorder { - int conn; - struct sockaddr_in addr; -}; - -/* Forward */ -static void init_python(void); -static void usage(void); -static void oprogname(void); -static void main_thread(int); -static void create_thread(int, struct sockaddr_in *); -static void *service_thread(struct workorder *); -static void run_interpreter(FILE *, FILE *); -static int run_command(char *, PyObject *); -static void ps(void); - -static char *progname = "pysvr"; - -static PyThreadState *gtstate; - -main(int argc, char **argv) -{ - int port = PORT; - int c; - - if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0') - progname = argv[0]; - - while ((c = getopt(argc, argv, "v")) != EOF) { - switch (c) { - case 'v': - Py_VerboseFlag++; - break; - default: - usage(); - } - } - - if (optind < argc) { - if (optind+1 < argc) { - oprogname(); - fprintf(stderr, "too many arguments\n"); - usage(); - } - port = atoi(argv[optind]); - if (port <= 0) { - fprintf(stderr, "bad port (%s)\n", argv[optind]); - usage(); - } - } - - main_thread(port); - - fprintf(stderr, "Bye.\n"); - - exit(0); -} - -static char usage_line[] = "usage: %s [port]\n"; - -static void -usage(void) -{ - fprintf(stderr, usage_line, progname); - exit(2); -} - -static void -main_thread(int port) -{ - int sock, conn, size, i; - struct sockaddr_in addr, clientaddr; - - sock = socket(PF_INET, SOCK_STREAM, 0); - if (sock < 0) { - oprogname(); - perror("can't create socket"); - exit(1); - } - -#ifdef SO_REUSEADDR - i = 1; - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i); -#endif - - memset((char *)&addr, '\0', sizeof addr); - addr.sin_family = AF_INET; - addr.sin_port = htons(port); - addr.sin_addr.s_addr = 0L; - if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) { - oprogname(); - perror("can't bind socket to address"); - exit(1); - } - - if (listen(sock, 5) < 0) { - oprogname(); - perror("can't listen on socket"); - exit(1); - } - - fprintf(stderr, "Listening on port %d...\n", port); - - for (i = 0; ; i++) { - size = sizeof clientaddr; - memset((char *) &clientaddr, '\0', size); - conn = accept(sock, (struct sockaddr *) &clientaddr, &size); - if (conn < 0) { - oprogname(); - perror("can't accept connection from socket"); - exit(1); - } - - size = sizeof addr; - memset((char *) &addr, '\0', size); - if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { - oprogname(); - perror("can't get socket name of connection"); - exit(1); - } - if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { - oprogname(); - perror("connection from non-local host refused"); - fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", - ntohl(addr.sin_addr.s_addr), - ntohl(clientaddr.sin_addr.s_addr)); - close(conn); - continue; - } - if (i == 4) { - close(conn); - break; - } - create_thread(conn, &clientaddr); - } - - close(sock); - - if (gtstate) { - PyEval_AcquireThread(gtstate); - gtstate = NULL; - Py_Finalize(); - /* And a second time, just because we can. */ - Py_Finalize(); /* This should be harmless. */ - } - exit(0); -} - -static void -create_thread(int conn, struct sockaddr_in *addr) -{ - struct workorder *work; - pthread_t tdata; - - work = malloc(sizeof(struct workorder)); - if (work == NULL) { - oprogname(); - fprintf(stderr, "out of memory for thread.\n"); - close(conn); - return; - } - work->conn = conn; - work->addr = *addr; - - init_python(); - - if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) { - oprogname(); - perror("can't create new thread"); - close(conn); - return; - } - - if (pthread_detach(tdata) < 0) { - oprogname(); - perror("can't detach from thread"); - } -} - -static PyThreadState *the_tstate; -static PyInterpreterState *the_interp; -static PyObject *the_builtins; - -static void -init_python(void) -{ - if (gtstate) - return; - Py_Initialize(); /* Initialize the interpreter */ - PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ - gtstate = PyEval_SaveThread(); /* Release the thread state */ -} - -static void * -service_thread(struct workorder *work) -{ - FILE *input, *output; - - fprintf(stderr, "Start thread for connection %d.\n", work->conn); - - ps(); - - input = fdopen(work->conn, "r"); - if (input == NULL) { - oprogname(); - perror("can't create input stream"); - goto done; - } - - output = fdopen(work->conn, "w"); - if (output == NULL) { - oprogname(); - perror("can't create output stream"); - fclose(input); - goto done; - } - - setvbuf(input, NULL, _IONBF, 0); - setvbuf(output, NULL, _IONBF, 0); - - run_interpreter(input, output); - - fclose(input); - fclose(output); - - done: - fprintf(stderr, "End thread for connection %d.\n", work->conn); - close(work->conn); - free(work); -} - -static void -oprogname(void) -{ - int save = errno; - fprintf(stderr, "%s: ", progname); - errno = save; -} - -static void -run_interpreter(FILE *input, FILE *output) -{ - PyThreadState *tstate; - PyObject *new_stdin, *new_stdout; - PyObject *mainmod, *globals; - char buffer[1000]; - char *p, *q; - int n, end; - - PyEval_AcquireLock(); - tstate = Py_NewInterpreter(); - if (tstate == NULL) { - fprintf(output, "Sorry -- can't create an interpreter\n"); - return; - } - - mainmod = PyImport_AddModule("__main__"); - globals = PyModule_GetDict(mainmod); - Py_INCREF(globals); - - new_stdin = PyFile_FromFile(input, "", "r", NULL); - new_stdout = PyFile_FromFile(output, "", "w", NULL); - - PySys_SetObject("stdin", new_stdin); - PySys_SetObject("stdout", new_stdout); - PySys_SetObject("stderr", new_stdout); - - for (n = 1; !PyErr_Occurred(); n++) { - Py_BEGIN_ALLOW_THREADS - fprintf(output, "%d> ", n); - p = fgets(buffer, sizeof buffer, input); - Py_END_ALLOW_THREADS - - if (p == NULL) - break; - if (p[0] == '\377' && p[1] == '\354') - break; - - q = strrchr(p, '\r'); - if (q && q[1] == '\n' && q[2] == '\0') { - *q++ = '\n'; - *q++ = '\0'; - } - - while (*p && isspace(*p)) - p++; - if (p[0] == '#' || p[0] == '\0') - continue; - - end = run_command(buffer, globals); - if (end < 0) - PyErr_Print(); - - if (end) - break; - } - - Py_XDECREF(globals); - Py_XDECREF(new_stdin); - Py_XDECREF(new_stdout); - - Py_EndInterpreter(tstate); - PyEval_ReleaseLock(); - - fprintf(output, "Goodbye!\n"); -} - -static int -run_command(char *buffer, PyObject *globals) -{ - PyObject *m, *d, *v; - fprintf(stderr, "run_command: %s", buffer); - if (strchr(buffer, '\n') == NULL) - fprintf(stderr, "\n"); - v = PyRun_String(buffer, Py_single_input, globals, globals); - if (v == NULL) { - if (PyErr_Occurred() == PyExc_SystemExit) { - PyErr_Clear(); - return 1; - } - PyErr_Print(); - return 0; - } - Py_DECREF(v); - return 0; -} - -static void -ps(void) -{ - char buffer[100]; - sprintf(buffer, "ps -l -p %d 1: - raise getopt.error, "Too many arguments." - except getopt.error, msg: - usage(msg) - for o, a in opts: - pass - if args: - try: - port = string.atoi(args[0]) - except ValueError, msg: - usage(msg) - else: - port = PORT - main_thread(port) - -def usage(msg=None): - sys.stdout = sys.stderr - if msg: - print msg - print "\n", __doc__, - sys.exit(2) - -def main_thread(port): - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.bind(("", port)) - sock.listen(5) - print "Listening on port", port, "..." - while 1: - (conn, addr) = sock.accept() - if addr[0] != conn.getsockname()[0]: - conn.close() - print "Refusing connection from non-local host", addr[0], "." - continue - thread.start_new_thread(service_thread, (conn, addr)) - del conn, addr - -def service_thread(conn, addr): - (caddr, cport) = addr - print "Thread %s has connection from %s.\n" % (str(thread.get_ident()), - caddr), - stdin = conn.makefile("r") - stdout = conn.makefile("w", 0) - run_interpreter(stdin, stdout) - print "Thread %s is done.\n" % str(thread.get_ident()), - -def run_interpreter(stdin, stdout): - globals = {} - try: - str(sys.ps1) - except: - sys.ps1 = ">>> " - source = "" - while 1: - stdout.write(sys.ps1) - line = stdin.readline() - if line[:2] == '\377\354': - line = "" - if not line and not source: - break - if line[-2:] == '\r\n': - line = line[:-2] + '\n' - source = source + line - try: - code = compile_command(source) - except SyntaxError, err: - source = "" - traceback.print_exception(SyntaxError, err, None, file=stdout) - continue - if not code: - continue - source = "" - try: - run_command(code, stdin, stdout, globals) - except SystemExit, how: - if how: - try: - how = str(how) - except: - how = "" - stdout.write("Exit %s\n" % how) - break - stdout.write("\nGoodbye.\n") - -def run_command(code, stdin, stdout, globals): - save = sys.stdin, sys.stdout, sys.stderr - try: - sys.stdout = sys.stderr = stdout - sys.stdin = stdin - try: - exec code in globals - except SystemExit, how: - raise SystemExit, how, sys.exc_info()[2] - except: - type, value, tb = sys.exc_info() - if tb: tb = tb.tb_next - traceback.print_exception(type, value, tb) - del tb - finally: - sys.stdin, sys.stdout, sys.stderr = save - -from code import compile_command - -main() diff --git a/Demo/rpc/MANIFEST b/Demo/rpc/MANIFEST deleted file mode 100644 index e65f3ebee8..0000000000 --- a/Demo/rpc/MANIFEST +++ /dev/null @@ -1,10 +0,0 @@ - File Name Archive # Description ------------------------------------------------------------ - MANIFEST 1 This shipping list - README 1 - T.py 1 - mountclient.py 1 - nfsclient.py 1 - rpc.py 1 - test 1 - xdr.py 1 diff --git a/Demo/rpc/README b/Demo/rpc/README deleted file mode 100644 index 8165ce020d..0000000000 --- a/Demo/rpc/README +++ /dev/null @@ -1,25 +0,0 @@ -This is a Python interface to Sun RPC, designed and implemented mostly -by reading the Internet RFCs about the subject. - -*** NOTE: xdr.py has evolved into the standard module xdrlib.py *** - -There are two library modules, xdr.py and rpc.py, and several example -clients: mountclient.py, nfsclient.py, and rnusersclient.py, -implementing the NFS Mount protocol, (part of) the NFS protocol, and -the "rnusers" protocol (used by rusers(1)), respectively. The latter -demonstrates the use of broadcast via the Port mapper's CALLIT -procedure. - -There is also a way to create servers in Python. - -To test the nfs client, run it from the shell with something like this: - - python -c 'import nfsclient; nfsclient.test()' [hostname [filesystemname]] - -When called without a filesystemname, it lists the filesystems at the -host; default host is the local machine. - -Other clients are tested similarly. - -For hostname, use e.g. wuarchive.wustl.edu or gatekeeper.dec.com (two -hosts that are known to export NFS filesystems with little restrictions). diff --git a/Demo/rpc/T.py b/Demo/rpc/T.py deleted file mode 100644 index abf3a06d05..0000000000 --- a/Demo/rpc/T.py +++ /dev/null @@ -1,22 +0,0 @@ -# Simple interface to report execution times of program fragments. -# Call TSTART() to reset the timer, TSTOP(...) to report times. - -import sys, os, time - -def TSTART(): - global t0, t1 - u, s, cu, cs = os.times() - t0 = u+cu, s+cs, time.time() - -def TSTOP(*label): - global t0, t1 - u, s, cu, cs = os.times() - t1 = u+cu, s+cs, time.time() - tt = [] - for i in range(3): - tt.append(t1[i] - t0[i]) - [u, s, r] = tt - msg = '' - for x in label: msg = msg + (x + ' ') - msg = msg + `u` + ' user, ' + `s` + ' sys, ' + `r` + ' real\n' - sys.stderr.write(msg) diff --git a/Demo/rpc/mountclient.py b/Demo/rpc/mountclient.py deleted file mode 100644 index ff66b3d6cc..0000000000 --- a/Demo/rpc/mountclient.py +++ /dev/null @@ -1,201 +0,0 @@ -# Mount RPC client -- RFC 1094 (NFS), Appendix A - -# This module demonstrates how to write your own RPC client in Python. -# Since there is no RPC compiler for Python (yet), you must first -# create classes derived from Packer and Unpacker to handle the data -# types for the server you want to interface to. You then write the -# client class. If you want to support both the TCP and the UDP -# version of a protocol, use multiple inheritance as shown below. - - -import rpc -from rpc import Packer, Unpacker, TCPClient, UDPClient - - -# Program number and version for the mount protocol -MOUNTPROG = 100005 -MOUNTVERS = 1 - -# Size of the 'fhandle' opaque structure -FHSIZE = 32 - - -# Packer derived class for Mount protocol clients. -# The only thing we need to pack beyond basic types is an 'fhandle' - -class MountPacker(Packer): - - def pack_fhandle(self, fhandle): - self.pack_fopaque(FHSIZE, fhandle) - - -# Unpacker derived class for Mount protocol clients. -# The important types we need to unpack are fhandle, fhstatus, -# mountlist and exportlist; mountstruct, exportstruct and groups are -# used to unpack components of mountlist and exportlist and the -# corresponding functions are passed as function argument to the -# generic unpack_list function. - -class MountUnpacker(Unpacker): - - def unpack_fhandle(self): - return self.unpack_fopaque(FHSIZE) - - def unpack_fhstatus(self): - status = self.unpack_uint() - if status == 0: - fh = self.unpack_fhandle() - else: - fh = None - return status, fh - - def unpack_mountlist(self): - return self.unpack_list(self.unpack_mountstruct) - - def unpack_mountstruct(self): - hostname = self.unpack_string() - directory = self.unpack_string() - return (hostname, directory) - - def unpack_exportlist(self): - return self.unpack_list(self.unpack_exportstruct) - - def unpack_exportstruct(self): - filesys = self.unpack_string() - groups = self.unpack_groups() - return (filesys, groups) - - def unpack_groups(self): - return self.unpack_list(self.unpack_string) - - -# These are the procedures specific to the Mount client class. -# Think of this as a derived class of either TCPClient or UDPClient. - -class PartialMountClient: - - # This method is called by Client.__init__ to initialize - # self.packer and self.unpacker - def addpackers(self): - self.packer = MountPacker() - self.unpacker = MountUnpacker('') - - # This method is called by Client.__init__ to bind the socket - # to a particular network interface and port. We use the - # default network interface, but if we're running as root, - # we want to bind to a reserved port - def bindsocket(self): - import os - try: - uid = os.getuid() - except AttributeError: - uid = 1 - if uid == 0: - port = rpc.bindresvport(self.sock, '') - # 'port' is not used - else: - self.sock.bind(('', 0)) - - # This function is called to cough up a suitable - # authentication object for a call to procedure 'proc'. - def mkcred(self): - if self.cred == None: - self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() - return self.cred - - # The methods Mnt, Dump etc. each implement one Remote - # Procedure Call. This is done by calling self.make_call() - # with as arguments: - # - # - the procedure number - # - the arguments (or None) - # - the "packer" function for the arguments (or None) - # - the "unpacker" function for the return value (or None) - # - # The packer and unpacker function, if not None, *must* be - # methods of self.packer and self.unpacker, respectively. - # A value of None means that there are no arguments or is no - # return value, respectively. - # - # The return value from make_call() is the return value from - # the remote procedure call, as unpacked by the "unpacker" - # function, or None if the unpacker function is None. - # - # (Even if you expect a result of None, you should still - # return the return value from make_call(), since this may be - # needed by a broadcasting version of the class.) - # - # If the call fails, make_call() raises an exception - # (this includes time-outs and invalid results). - # - # Note that (at least with the UDP protocol) there is no - # guarantee that a call is executed at most once. When you do - # get a reply, you know it has been executed at least once; - # when you don't get a reply, you know nothing. - - def Mnt(self, directory): - return self.make_call(1, directory, \ - self.packer.pack_string, \ - self.unpacker.unpack_fhstatus) - - def Dump(self): - return self.make_call(2, None, \ - None, self.unpacker.unpack_mountlist) - - def Umnt(self, directory): - return self.make_call(3, directory, \ - self.packer.pack_string, None) - - def Umntall(self): - return self.make_call(4, None, None, None) - - def Export(self): - return self.make_call(5, None, \ - None, self.unpacker.unpack_exportlist) - - -# We turn the partial Mount client into a full one for either protocol -# by use of multiple inheritance. (In general, when class C has base -# classes B1...Bn, if x is an instance of class C, methods of x are -# searched first in C, then in B1, then in B2, ..., finally in Bn.) - -class TCPMountClient(PartialMountClient, TCPClient): - - def __init__(self, host): - TCPClient.__init__(self, host, MOUNTPROG, MOUNTVERS) - - -class UDPMountClient(PartialMountClient, UDPClient): - - def __init__(self, host): - UDPClient.__init__(self, host, MOUNTPROG, MOUNTVERS) - - -# A little test program for the Mount client. This takes a host as -# command line argument (default the local machine), prints its export -# list, and attempts to mount and unmount each exported files system. -# An optional first argument of -t or -u specifies the protocol to use -# (TCP or UDP), default is UDP. - -def test(): - import sys - if sys.argv[1:] and sys.argv[1] == '-t': - C = TCPMountClient - del sys.argv[1] - elif sys.argv[1:] and sys.argv[1] == '-u': - C = UDPMountClient - del sys.argv[1] - else: - C = UDPMountClient - if sys.argv[1:]: host = sys.argv[1] - else: host = '' - mcl = C(host) - list = mcl.Export() - for item in list: - print item - try: - mcl.Mnt(item[0]) - except: - print 'Sorry' - continue - mcl.Umnt(item[0]) diff --git a/Demo/rpc/nfsclient.py b/Demo/rpc/nfsclient.py deleted file mode 100644 index 37ec46c047..0000000000 --- a/Demo/rpc/nfsclient.py +++ /dev/null @@ -1,201 +0,0 @@ -# NFS RPC client -- RFC 1094 - -# XXX This is not yet complete. -# XXX Only GETATTR, SETTTR, LOOKUP and READDIR are supported. - -# (See mountclient.py for some hints on how to write RPC clients in -# Python in general) - -import rpc -from rpc import UDPClient, TCPClient -from mountclient import FHSIZE, MountPacker, MountUnpacker - -NFS_PROGRAM = 100003 -NFS_VERSION = 2 - -# enum stat -NFS_OK = 0 -# (...many error values...) - -# enum ftype -NFNON = 0 -NFREG = 1 -NFDIR = 2 -NFBLK = 3 -NFCHR = 4 -NFLNK = 5 - - -class NFSPacker(MountPacker): - - def pack_sattrargs(self, sa): - file, attributes = sa - self.pack_fhandle(file) - self.pack_sattr(attributes) - - def pack_sattr(self, sa): - mode, uid, gid, size, atime, mtime = sa - self.pack_uint(mode) - self.pack_uint(uid) - self.pack_uint(gid) - self.pack_uint(size) - self.pack_timeval(atime) - self.pack_timeval(mtime) - - def pack_diropargs(self, da): - dir, name = da - self.pack_fhandle(dir) - self.pack_string(name) - - def pack_readdirargs(self, ra): - dir, cookie, count = ra - self.pack_fhandle(dir) - self.pack_uint(cookie) - self.pack_uint(count) - - def pack_timeval(self, tv): - secs, usecs = tv - self.pack_uint(secs) - self.pack_uint(usecs) - - -class NFSUnpacker(MountUnpacker): - - def unpack_readdirres(self): - status = self.unpack_enum() - if status == NFS_OK: - entries = self.unpack_list(self.unpack_entry) - eof = self.unpack_bool() - rest = (entries, eof) - else: - rest = None - return (status, rest) - - def unpack_entry(self): - fileid = self.unpack_uint() - name = self.unpack_string() - cookie = self.unpack_uint() - return (fileid, name, cookie) - - def unpack_diropres(self): - status = self.unpack_enum() - if status == NFS_OK: - fh = self.unpack_fhandle() - fa = self.unpack_fattr() - rest = (fh, fa) - else: - rest = None - return (status, rest) - - def unpack_attrstat(self): - status = self.unpack_enum() - if status == NFS_OK: - attributes = self.unpack_fattr() - else: - attributes = None - return status, attributes - - def unpack_fattr(self): - type = self.unpack_enum() - mode = self.unpack_uint() - nlink = self.unpack_uint() - uid = self.unpack_uint() - gid = self.unpack_uint() - size = self.unpack_uint() - blocksize = self.unpack_uint() - rdev = self.unpack_uint() - blocks = self.unpack_uint() - fsid = self.unpack_uint() - fileid = self.unpack_uint() - atime = self.unpack_timeval() - mtime = self.unpack_timeval() - ctime = self.unpack_timeval() - return (type, mode, nlink, uid, gid, size, blocksize, \ - rdev, blocks, fsid, fileid, atime, mtime, ctime) - - def unpack_timeval(self): - secs = self.unpack_uint() - usecs = self.unpack_uint() - return (secs, usecs) - - -class NFSClient(UDPClient): - - def __init__(self, host): - UDPClient.__init__(self, host, NFS_PROGRAM, NFS_VERSION) - - def addpackers(self): - self.packer = NFSPacker() - self.unpacker = NFSUnpacker('') - - def mkcred(self): - if self.cred == None: - self.cred = rpc.AUTH_UNIX, rpc.make_auth_unix_default() - return self.cred - - def Getattr(self, fh): - return self.make_call(1, fh, \ - self.packer.pack_fhandle, \ - self.unpacker.unpack_attrstat) - - def Setattr(self, sa): - return self.make_call(2, sa, \ - self.packer.pack_sattrargs, \ - self.unpacker.unpack_attrstat) - - # Root() is obsolete - - def Lookup(self, da): - return self.make_call(4, da, \ - self.packer.pack_diropargs, \ - self.unpacker.unpack_diropres) - - # ... - - def Readdir(self, ra): - return self.make_call(16, ra, \ - self.packer.pack_readdirargs, \ - self.unpacker.unpack_readdirres) - - # Shorthand to get the entire contents of a directory - def Listdir(self, dir): - list = [] - ra = (dir, 0, 2000) - while 1: - (status, rest) = self.Readdir(ra) - if status <> NFS_OK: - break - entries, eof = rest - last_cookie = None - for fileid, name, cookie in entries: - list.append((fileid, name)) - last_cookie = cookie - if eof or last_cookie == None: - break - ra = (ra[0], last_cookie, ra[2]) - return list - - -def test(): - import sys - if sys.argv[1:]: host = sys.argv[1] - else: host = '' - if sys.argv[2:]: filesys = sys.argv[2] - else: filesys = None - from mountclient import UDPMountClient, TCPMountClient - mcl = TCPMountClient(host) - if filesys == None: - list = mcl.Export() - for item in list: - print item - return - sf = mcl.Mnt(filesys) - print sf - fh = sf[1] - if fh: - ncl = NFSClient(host) - as = ncl.Getattr(fh) - print as - list = ncl.Listdir(fh) - for item in list: print item - mcl.Umnt(filesys) diff --git a/Demo/rpc/rnusersclient.py b/Demo/rpc/rnusersclient.py deleted file mode 100644 index e9cad620fd..0000000000 --- a/Demo/rpc/rnusersclient.py +++ /dev/null @@ -1,98 +0,0 @@ -# Remote nusers client interface - -import rpc -from rpc import Packer, Unpacker, UDPClient, BroadcastUDPClient - - -class RnusersPacker(Packer): - def pack_utmp(self, ui): - ut_line, ut_name, ut_host, ut_time = utmp - self.pack_string(ut_line) - self.pack_string(ut_name) - self.pack_string(ut_host) - self.pack_int(ut_time) - def pack_utmpidle(self, ui): - ui_itmp, ui_idle = ui - self.pack_utmp(ui_utmp) - self.pack_uint(ui_idle) - def pack_utmpidlearr(self, list): - self.pack_array(list, self.pack_itmpidle) - - -class RnusersUnpacker(Unpacker): - def unpack_utmp(self): - ut_line = self.unpack_string() - ut_name = self.unpack_string() - ut_host = self.unpack_string() - ut_time = self.unpack_int() - return ut_line, ut_name, ut_host, ut_time - def unpack_utmpidle(self): - ui_utmp = self.unpack_utmp() - ui_idle = self.unpack_uint() - return ui_utmp, ui_idle - def unpack_utmpidlearr(self): - return self.unpack_array(self.unpack_utmpidle) - - -class PartialRnusersClient: - - def addpackers(self): - self.packer = RnusersPacker() - self.unpacker = RnusersUnpacker('') - - def Num(self): - return self.make_call(1, None, None, self.unpacker.unpack_int) - - def Names(self): - return self.make_call(2, None, \ - None, self.unpacker.unpack_utmpidlearr) - - def Allnames(self): - return self.make_call(3, None, \ - None, self.unpacker.unpack_utmpidlearr) - - -class RnusersClient(PartialRnusersClient, UDPClient): - - def __init__(self, host): - UDPClient.__init__(self, host, 100002, 2) - - -class BroadcastRnusersClient(PartialRnusersClient, BroadcastUDPClient): - - def __init__(self, bcastaddr): - BroadcastUDPClient.__init__(self, bcastaddr, 100002, 2) - - -def test(): - import sys - if not sys.argv[1:]: - testbcast() - return - else: - host = sys.argv[1] - c = RnusersClient(host) - list = c.Names() - for (line, name, host, time), idle in list: - line = strip0(line) - name = strip0(name) - host = strip0(host) - print `name`, `host`, `line`, time, idle - -def testbcast(): - c = BroadcastRnusersClient('') - def listit(list, fromaddr): - host, port = fromaddr - print host + '\t:', - for (line, name, host, time), idle in list: - print strip0(name), - print - c.set_reply_handler(listit) - all = c.Names() - print 'Total Count:', len(all) - -def strip0(s): - while s and s[-1] == '\0': s = s[:-1] - return s - -test() diff --git a/Demo/rpc/rpc.py b/Demo/rpc/rpc.py deleted file mode 100644 index f44b3e4426..0000000000 --- a/Demo/rpc/rpc.py +++ /dev/null @@ -1,891 +0,0 @@ -# Sun RPC version 2 -- RFC1057. - -# XXX There should be separate exceptions for the various reasons why -# XXX an RPC can fail, rather than using RuntimeError for everything - -# XXX The UDP version of the protocol resends requests when it does -# XXX not receive a timely reply -- use only for idempotent calls! - -# XXX There is no provision for call timeout on TCP connections - -import xdr -import socket -import os - -RPCVERSION = 2 - -CALL = 0 -REPLY = 1 - -AUTH_NULL = 0 -AUTH_UNIX = 1 -AUTH_SHORT = 2 -AUTH_DES = 3 - -MSG_ACCEPTED = 0 -MSG_DENIED = 1 - -SUCCESS = 0 # RPC executed successfully -PROG_UNAVAIL = 1 # remote hasn't exported program -PROG_MISMATCH = 2 # remote can't support version # -PROC_UNAVAIL = 3 # program can't support procedure -GARBAGE_ARGS = 4 # procedure can't decode params - -RPC_MISMATCH = 0 # RPC version number != 2 -AUTH_ERROR = 1 # remote can't authenticate caller - -AUTH_BADCRED = 1 # bad credentials (seal broken) -AUTH_REJECTEDCRED = 2 # client must begin new session -AUTH_BADVERF = 3 # bad verifier (seal broken) -AUTH_REJECTEDVERF = 4 # verifier expired or replayed -AUTH_TOOWEAK = 5 # rejected for security reasons - - -class Packer(xdr.Packer): - - def pack_auth(self, auth): - flavor, stuff = auth - self.pack_enum(flavor) - self.pack_opaque(stuff) - - def pack_auth_unix(self, stamp, machinename, uid, gid, gids): - self.pack_uint(stamp) - self.pack_string(machinename) - self.pack_uint(uid) - self.pack_uint(gid) - self.pack_uint(len(gids)) - for i in gids: - self.pack_uint(i) - - def pack_callheader(self, xid, prog, vers, proc, cred, verf): - self.pack_uint(xid) - self.pack_enum(CALL) - self.pack_uint(RPCVERSION) - self.pack_uint(prog) - self.pack_uint(vers) - self.pack_uint(proc) - self.pack_auth(cred) - self.pack_auth(verf) - # Caller must add procedure-specific part of call - - def pack_replyheader(self, xid, verf): - self.pack_uint(xid) - self.pack_enum(REPLY) - self.pack_uint(MSG_ACCEPTED) - self.pack_auth(verf) - self.pack_enum(SUCCESS) - # Caller must add procedure-specific part of reply - - -# Exceptions -BadRPCFormat = 'rpc.BadRPCFormat' -BadRPCVersion = 'rpc.BadRPCVersion' -GarbageArgs = 'rpc.GarbageArgs' - -class Unpacker(xdr.Unpacker): - - def unpack_auth(self): - flavor = self.unpack_enum() - stuff = self.unpack_opaque() - return (flavor, stuff) - - def unpack_callheader(self): - xid = self.unpack_uint(xid) - temp = self.unpack_enum() - if temp <> CALL: - raise BadRPCFormat, 'no CALL but ' + `temp` - temp = self.unpack_uint() - if temp <> RPCVERSION: - raise BadRPCVerspion, 'bad RPC version ' + `temp` - prog = self.unpack_uint() - vers = self.unpack_uint() - proc = self.unpack_uint() - cred = self.unpack_auth() - verf = self.unpack_auth() - return xid, prog, vers, proc, cred, verf - # Caller must add procedure-specific part of call - - def unpack_replyheader(self): - xid = self.unpack_uint() - mtype = self.unpack_enum() - if mtype <> REPLY: - raise RuntimeError, 'no REPLY but ' + `mtype` - stat = self.unpack_enum() - if stat == MSG_DENIED: - stat = self.unpack_enum() - if stat == RPC_MISMATCH: - low = self.unpack_uint() - high = self.unpack_uint() - raise RuntimeError, \ - 'MSG_DENIED: RPC_MISMATCH: ' + `low, high` - if stat == AUTH_ERROR: - stat = self.unpack_uint() - raise RuntimeError, \ - 'MSG_DENIED: AUTH_ERROR: ' + `stat` - raise RuntimeError, 'MSG_DENIED: ' + `stat` - if stat <> MSG_ACCEPTED: - raise RuntimeError, \ - 'Neither MSG_DENIED nor MSG_ACCEPTED: ' + `stat` - verf = self.unpack_auth() - stat = self.unpack_enum() - if stat == PROG_UNAVAIL: - raise RuntimeError, 'call failed: PROG_UNAVAIL' - if stat == PROG_MISMATCH: - low = self.unpack_uint() - high = self.unpack_uint() - raise RuntimeError, \ - 'call failed: PROG_MISMATCH: ' + `low, high` - if stat == PROC_UNAVAIL: - raise RuntimeError, 'call failed: PROC_UNAVAIL' - if stat == GARBAGE_ARGS: - raise RuntimeError, 'call failed: GARBAGE_ARGS' - if stat <> SUCCESS: - raise RuntimeError, 'call failed: ' + `stat` - return xid, verf - # Caller must get procedure-specific part of reply - - -# Subroutines to create opaque authentication objects - -def make_auth_null(): - return '' - -def make_auth_unix(seed, host, uid, gid, groups): - p = Packer() - p.pack_auth_unix(seed, host, uid, gid, groups) - return p.get_buf() - -def make_auth_unix_default(): - try: - from os import getuid, getgid - uid = getuid() - gid = getgid() - except ImportError: - uid = gid = 0 - import time - return make_auth_unix(int(time.time()-unix_epoch()), \ - socket.gethostname(), uid, gid, []) - -_unix_epoch = -1 -def unix_epoch(): - """Very painful calculation of when the Unix Epoch is. - - This is defined as the return value of time.time() on Jan 1st, - 1970, 00:00:00 GMT. - - On a Unix system, this should always return 0.0. On a Mac, the - calculations are needed -- and hard because of integer overflow - and other limitations. - - """ - global _unix_epoch - if _unix_epoch >= 0: return _unix_epoch - import time - now = time.time() - localt = time.localtime(now) # (y, m, d, hh, mm, ss, ..., ..., ...) - gmt = time.gmtime(now) - offset = time.mktime(localt) - time.mktime(gmt) - y, m, d, hh, mm, ss = 1970, 1, 1, 0, 0, 0 - offset, ss = divmod(ss + offset, 60) - offset, mm = divmod(mm + offset, 60) - offset, hh = divmod(hh + offset, 24) - d = d + offset - _unix_epoch = time.mktime((y, m, d, hh, mm, ss, 0, 0, 0)) - print "Unix epoch:", time.ctime(_unix_epoch) - return _unix_epoch - - -# Common base class for clients - -class Client: - - def __init__(self, host, prog, vers, port): - self.host = host - self.prog = prog - self.vers = vers - self.port = port - self.makesocket() # Assigns to self.sock - self.bindsocket() - self.connsocket() - self.lastxid = 0 # XXX should be more random? - self.addpackers() - self.cred = None - self.verf = None - - def close(self): - self.sock.close() - - def makesocket(self): - # This MUST be overridden - raise RuntimeError, 'makesocket not defined' - - def connsocket(self): - # Override this if you don't want/need a connection - self.sock.connect((self.host, self.port)) - - def bindsocket(self): - # Override this to bind to a different port (e.g. reserved) - self.sock.bind(('', 0)) - - def addpackers(self): - # Override this to use derived classes from Packer/Unpacker - self.packer = Packer() - self.unpacker = Unpacker('') - - def make_call(self, proc, args, pack_func, unpack_func): - # Don't normally override this (but see Broadcast) - if pack_func is None and args is not None: - raise TypeError, 'non-null args with null pack_func' - self.start_call(proc) - if pack_func: - pack_func(args) - self.do_call() - if unpack_func: - result = unpack_func() - else: - result = None - self.unpacker.done() - return result - - def start_call(self, proc): - # Don't override this - self.lastxid = xid = self.lastxid + 1 - cred = self.mkcred() - verf = self.mkverf() - p = self.packer - p.reset() - p.pack_callheader(xid, self.prog, self.vers, proc, cred, verf) - - def do_call(self): - # This MUST be overridden - raise RuntimeError, 'do_call not defined' - - def mkcred(self): - # Override this to use more powerful credentials - if self.cred == None: - self.cred = (AUTH_NULL, make_auth_null()) - return self.cred - - def mkverf(self): - # Override this to use a more powerful verifier - if self.verf == None: - self.verf = (AUTH_NULL, make_auth_null()) - return self.verf - - def call_0(self): # Procedure 0 is always like this - return self.make_call(0, None, None, None) - - -# Record-Marking standard support - -def sendfrag(sock, last, frag): - x = len(frag) - if last: x = x | 0x80000000L - header = (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \ - chr(int(x>>8 & 0xff)) + chr(int(x & 0xff))) - sock.send(header + frag) - -def sendrecord(sock, record): - sendfrag(sock, 1, record) - -def recvfrag(sock): - header = sock.recv(4) - if len(header) < 4: - raise EOFError - x = long(ord(header[0]))<<24 | ord(header[1])<<16 | \ - ord(header[2])<<8 | ord(header[3]) - last = ((x & 0x80000000) != 0) - n = int(x & 0x7fffffff) - frag = '' - while n > 0: - buf = sock.recv(n) - if not buf: raise EOFError - n = n - len(buf) - frag = frag + buf - return last, frag - -def recvrecord(sock): - record = '' - last = 0 - while not last: - last, frag = recvfrag(sock) - record = record + frag - return record - - -# Try to bind to a reserved port (must be root) - -last_resv_port_tried = None -def bindresvport(sock, host): - global last_resv_port_tried - FIRST, LAST = 600, 1024 # Range of ports to try - if last_resv_port_tried == None: - import os - last_resv_port_tried = FIRST + os.getpid() % (LAST-FIRST) - for i in range(last_resv_port_tried, LAST) + \ - range(FIRST, last_resv_port_tried): - last_resv_port_tried = i - try: - sock.bind((host, i)) - return last_resv_port_tried - except socket.error, (errno, msg): - if errno <> 114: - raise socket.error, (errno, msg) - raise RuntimeError, 'can\'t assign reserved port' - - -# Client using TCP to a specific port - -class RawTCPClient(Client): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - - def do_call(self): - call = self.packer.get_buf() - sendrecord(self.sock, call) - reply = recvrecord(self.sock) - u = self.unpacker - u.reset(reply) - xid, verf = u.unpack_replyheader() - if xid <> self.lastxid: - # Can't really happen since this is TCP... - raise RuntimeError, 'wrong xid in reply ' + `xid` + \ - ' instead of ' + `self.lastxid` - - -# Client using UDP to a specific port - -class RawUDPClient(Client): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - - def do_call(self): - call = self.packer.get_buf() - self.sock.send(call) - try: - from select import select - except ImportError: - print 'WARNING: select not found, RPC may hang' - select = None - BUFSIZE = 8192 # Max UDP buffer size - timeout = 1 - count = 5 - while 1: - r, w, x = [self.sock], [], [] - if select: - r, w, x = select(r, w, x, timeout) - if self.sock not in r: - count = count - 1 - if count < 0: raise RuntimeError, 'timeout' - if timeout < 25: timeout = timeout *2 -## print 'RESEND', timeout, count - self.sock.send(call) - continue - reply = self.sock.recv(BUFSIZE) - u = self.unpacker - u.reset(reply) - xid, verf = u.unpack_replyheader() - if xid <> self.lastxid: -## print 'BAD xid' - continue - break - - -# Client using UDP broadcast to a specific port - -class RawBroadcastUDPClient(RawUDPClient): - - def __init__(self, bcastaddr, prog, vers, port): - RawUDPClient.__init__(self, bcastaddr, prog, vers, port) - self.reply_handler = None - self.timeout = 30 - - def connsocket(self): - # Don't connect -- use sendto - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - - def set_reply_handler(self, reply_handler): - self.reply_handler = reply_handler - - def set_timeout(self, timeout): - self.timeout = timeout # Use None for infinite timeout - - def make_call(self, proc, args, pack_func, unpack_func): - if pack_func is None and args is not None: - raise TypeError, 'non-null args with null pack_func' - self.start_call(proc) - if pack_func: - pack_func(args) - call = self.packer.get_buf() - self.sock.sendto(call, (self.host, self.port)) - try: - from select import select - except ImportError: - print 'WARNING: select not found, broadcast will hang' - select = None - BUFSIZE = 8192 # Max UDP buffer size (for reply) - replies = [] - if unpack_func is None: - def dummy(): pass - unpack_func = dummy - while 1: - r, w, x = [self.sock], [], [] - if select: - if self.timeout is None: - r, w, x = select(r, w, x) - else: - r, w, x = select(r, w, x, self.timeout) - if self.sock not in r: - break - reply, fromaddr = self.sock.recvfrom(BUFSIZE) - u = self.unpacker - u.reset(reply) - xid, verf = u.unpack_replyheader() - if xid <> self.lastxid: -## print 'BAD xid' - continue - reply = unpack_func() - self.unpacker.done() - replies.append((reply, fromaddr)) - if self.reply_handler: - self.reply_handler(reply, fromaddr) - return replies - - -# Port mapper interface - -# Program number, version and (fixed!) port number -PMAP_PROG = 100000 -PMAP_VERS = 2 -PMAP_PORT = 111 - -# Procedure numbers -PMAPPROC_NULL = 0 # (void) -> void -PMAPPROC_SET = 1 # (mapping) -> bool -PMAPPROC_UNSET = 2 # (mapping) -> bool -PMAPPROC_GETPORT = 3 # (mapping) -> unsigned int -PMAPPROC_DUMP = 4 # (void) -> pmaplist -PMAPPROC_CALLIT = 5 # (call_args) -> call_result - -# A mapping is (prog, vers, prot, port) and prot is one of: - -IPPROTO_TCP = 6 -IPPROTO_UDP = 17 - -# A pmaplist is a variable-length list of mappings, as follows: -# either (1, mapping, pmaplist) or (0). - -# A call_args is (prog, vers, proc, args) where args is opaque; -# a call_result is (port, res) where res is opaque. - - -class PortMapperPacker(Packer): - - def pack_mapping(self, mapping): - prog, vers, prot, port = mapping - self.pack_uint(prog) - self.pack_uint(vers) - self.pack_uint(prot) - self.pack_uint(port) - - def pack_pmaplist(self, list): - self.pack_list(list, self.pack_mapping) - - def pack_call_args(self, ca): - prog, vers, proc, args = ca - self.pack_uint(prog) - self.pack_uint(vers) - self.pack_uint(proc) - self.pack_opaque(args) - - -class PortMapperUnpacker(Unpacker): - - def unpack_mapping(self): - prog = self.unpack_uint() - vers = self.unpack_uint() - prot = self.unpack_uint() - port = self.unpack_uint() - return prog, vers, prot, port - - def unpack_pmaplist(self): - return self.unpack_list(self.unpack_mapping) - - def unpack_call_result(self): - port = self.unpack_uint() - res = self.unpack_opaque() - return port, res - - -class PartialPortMapperClient: - - def addpackers(self): - self.packer = PortMapperPacker() - self.unpacker = PortMapperUnpacker('') - - def Set(self, mapping): - return self.make_call(PMAPPROC_SET, mapping, \ - self.packer.pack_mapping, \ - self.unpacker.unpack_uint) - - def Unset(self, mapping): - return self.make_call(PMAPPROC_UNSET, mapping, \ - self.packer.pack_mapping, \ - self.unpacker.unpack_uint) - - def Getport(self, mapping): - return self.make_call(PMAPPROC_GETPORT, mapping, \ - self.packer.pack_mapping, \ - self.unpacker.unpack_uint) - - def Dump(self): - return self.make_call(PMAPPROC_DUMP, None, \ - None, \ - self.unpacker.unpack_pmaplist) - - def Callit(self, ca): - return self.make_call(PMAPPROC_CALLIT, ca, \ - self.packer.pack_call_args, \ - self.unpacker.unpack_call_result) - - -class TCPPortMapperClient(PartialPortMapperClient, RawTCPClient): - - def __init__(self, host): - RawTCPClient.__init__(self, \ - host, PMAP_PROG, PMAP_VERS, PMAP_PORT) - - -class UDPPortMapperClient(PartialPortMapperClient, RawUDPClient): - - def __init__(self, host): - RawUDPClient.__init__(self, \ - host, PMAP_PROG, PMAP_VERS, PMAP_PORT) - - -class BroadcastUDPPortMapperClient(PartialPortMapperClient, \ - RawBroadcastUDPClient): - - def __init__(self, bcastaddr): - RawBroadcastUDPClient.__init__(self, \ - bcastaddr, PMAP_PROG, PMAP_VERS, PMAP_PORT) - - -# Generic clients that find their server through the Port mapper - -class TCPClient(RawTCPClient): - - def __init__(self, host, prog, vers): - pmap = TCPPortMapperClient(host) - port = pmap.Getport((prog, vers, IPPROTO_TCP, 0)) - pmap.close() - if port == 0: - raise RuntimeError, 'program not registered' - RawTCPClient.__init__(self, host, prog, vers, port) - - -class UDPClient(RawUDPClient): - - def __init__(self, host, prog, vers): - pmap = UDPPortMapperClient(host) - port = pmap.Getport((prog, vers, IPPROTO_UDP, 0)) - pmap.close() - if port == 0: - raise RuntimeError, 'program not registered' - RawUDPClient.__init__(self, host, prog, vers, port) - - -class BroadcastUDPClient(Client): - - def __init__(self, bcastaddr, prog, vers): - self.pmap = BroadcastUDPPortMapperClient(bcastaddr) - self.pmap.set_reply_handler(self.my_reply_handler) - self.prog = prog - self.vers = vers - self.user_reply_handler = None - self.addpackers() - - def close(self): - self.pmap.close() - - def set_reply_handler(self, reply_handler): - self.user_reply_handler = reply_handler - - def set_timeout(self, timeout): - self.pmap.set_timeout(timeout) - - def my_reply_handler(self, reply, fromaddr): - port, res = reply - self.unpacker.reset(res) - result = self.unpack_func() - self.unpacker.done() - self.replies.append((result, fromaddr)) - if self.user_reply_handler is not None: - self.user_reply_handler(result, fromaddr) - - def make_call(self, proc, args, pack_func, unpack_func): - self.packer.reset() - if pack_func: - pack_func(args) - if unpack_func is None: - def dummy(): pass - self.unpack_func = dummy - else: - self.unpack_func = unpack_func - self.replies = [] - packed_args = self.packer.get_buf() - dummy_replies = self.pmap.Callit( \ - (self.prog, self.vers, proc, packed_args)) - return self.replies - - -# Server classes - -# These are not symmetric to the Client classes -# XXX No attempt is made to provide authorization hooks yet - -class Server: - - def __init__(self, host, prog, vers, port): - self.host = host # Should normally be '' for default interface - self.prog = prog - self.vers = vers - self.port = port # Should normally be 0 for random port - self.makesocket() # Assigns to self.sock and self.prot - self.bindsocket() - self.host, self.port = self.sock.getsockname() - self.addpackers() - - def register(self): - mapping = self.prog, self.vers, self.prot, self.port - p = TCPPortMapperClient(self.host) - if not p.Set(mapping): - raise RuntimeError, 'register failed' - - def unregister(self): - mapping = self.prog, self.vers, self.prot, self.port - p = TCPPortMapperClient(self.host) - if not p.Unset(mapping): - raise RuntimeError, 'unregister failed' - - def handle(self, call): - # Don't use unpack_header but parse the header piecewise - # XXX I have no idea if I am using the right error responses! - self.unpacker.reset(call) - self.packer.reset() - xid = self.unpacker.unpack_uint() - self.packer.pack_uint(xid) - temp = self.unpacker.unpack_enum() - if temp <> CALL: - return None # Not worthy of a reply - self.packer.pack_uint(REPLY) - temp = self.unpacker.unpack_uint() - if temp <> RPCVERSION: - self.packer.pack_uint(MSG_DENIED) - self.packer.pack_uint(RPC_MISMATCH) - self.packer.pack_uint(RPCVERSION) - self.packer.pack_uint(RPCVERSION) - return self.packer.get_buf() - self.packer.pack_uint(MSG_ACCEPTED) - self.packer.pack_auth((AUTH_NULL, make_auth_null())) - prog = self.unpacker.unpack_uint() - if prog <> self.prog: - self.packer.pack_uint(PROG_UNAVAIL) - return self.packer.get_buf() - vers = self.unpacker.unpack_uint() - if vers <> self.vers: - self.packer.pack_uint(PROG_MISMATCH) - self.packer.pack_uint(self.vers) - self.packer.pack_uint(self.vers) - return self.packer.get_buf() - proc = self.unpacker.unpack_uint() - methname = 'handle_' + `proc` - try: - meth = getattr(self, methname) - except AttributeError: - self.packer.pack_uint(PROC_UNAVAIL) - return self.packer.get_buf() - cred = self.unpacker.unpack_auth() - verf = self.unpacker.unpack_auth() - try: - meth() # Unpack args, call turn_around(), pack reply - except (EOFError, GarbageArgs): - # Too few or too many arguments - self.packer.reset() - self.packer.pack_uint(xid) - self.packer.pack_uint(REPLY) - self.packer.pack_uint(MSG_ACCEPTED) - self.packer.pack_auth((AUTH_NULL, make_auth_null())) - self.packer.pack_uint(GARBAGE_ARGS) - return self.packer.get_buf() - - def turn_around(self): - try: - self.unpacker.done() - except RuntimeError: - raise GarbageArgs - self.packer.pack_uint(SUCCESS) - - def handle_0(self): # Handle NULL message - self.turn_around() - - def makesocket(self): - # This MUST be overridden - raise RuntimeError, 'makesocket not defined' - - def bindsocket(self): - # Override this to bind to a different port (e.g. reserved) - self.sock.bind((self.host, self.port)) - - def addpackers(self): - # Override this to use derived classes from Packer/Unpacker - self.packer = Packer() - self.unpacker = Unpacker('') - - -class TCPServer(Server): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.prot = IPPROTO_TCP - - def loop(self): - self.sock.listen(0) - while 1: - self.session(self.sock.accept()) - - def session(self, connection): - sock, (host, port) = connection - while 1: - try: - call = recvrecord(sock) - except EOFError: - break - except socket.error, msg: - print 'socket error:', msg - break - reply = self.handle(call) - if reply is not None: - sendrecord(sock, reply) - - def forkingloop(self): - # Like loop but uses forksession() - self.sock.listen(0) - while 1: - self.forksession(self.sock.accept()) - - def forksession(self, connection): - # Like session but forks off a subprocess - import os - # Wait for deceased children - try: - while 1: - pid, sts = os.waitpid(0, 1) - except os.error: - pass - pid = None - try: - pid = os.fork() - if pid: # Parent - connection[0].close() - return - # Child - self.session(connection) - finally: - # Make sure we don't fall through in the parent - if pid == 0: - os._exit(0) - - -class UDPServer(Server): - - def makesocket(self): - self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - self.prot = IPPROTO_UDP - - def loop(self): - while 1: - self.session() - - def session(self): - call, host_port = self.sock.recvfrom(8192) - reply = self.handle(call) - if reply <> None: - self.sock.sendto(reply, host_port) - - -# Simple test program -- dump local portmapper status - -def test(): - pmap = UDPPortMapperClient('') - list = pmap.Dump() - list.sort() - for prog, vers, prot, port in list: - print prog, vers, - if prot == IPPROTO_TCP: print 'tcp', - elif prot == IPPROTO_UDP: print 'udp', - else: print prot, - print port - - -# Test program for broadcast operation -- dump everybody's portmapper status - -def testbcast(): - import sys - if sys.argv[1:]: - bcastaddr = sys.argv[1] - else: - bcastaddr = '' - def rh(reply, fromaddr): - host, port = fromaddr - print host + '\t' + `reply` - pmap = BroadcastUDPPortMapperClient(bcastaddr) - pmap.set_reply_handler(rh) - pmap.set_timeout(5) - replies = pmap.Getport((100002, 1, IPPROTO_UDP, 0)) - - -# Test program for server, with corresponding client -# On machine A: python -c 'import rpc; rpc.testsvr()' -# On machine B: python -c 'import rpc; rpc.testclt()' A -# (A may be == B) - -def testsvr(): - # Simple test class -- proc 1 doubles its string argument as reply - class S(UDPServer): - def handle_1(self): - arg = self.unpacker.unpack_string() - self.turn_around() - print 'RPC function 1 called, arg', `arg` - self.packer.pack_string(arg + arg) - # - s = S('', 0x20000000, 1, 0) - try: - s.unregister() - except RuntimeError, msg: - print 'RuntimeError:', msg, '(ignored)' - s.register() - print 'Service started...' - try: - s.loop() - finally: - s.unregister() - print 'Service interrupted.' - - -def testclt(): - import sys - if sys.argv[1:]: host = sys.argv[1] - else: host = '' - # Client for above server - class C(UDPClient): - def call_1(self, arg): - return self.make_call(1, arg, \ - self.packer.pack_string, \ - self.unpacker.unpack_string) - c = C(host, 0x20000000, 1) - print 'making call...' - reply = c.call_1('hello, world, ') - print 'call returned', `reply` diff --git a/Demo/rpc/test b/Demo/rpc/test deleted file mode 100755 index ba220f24a2..0000000000 --- a/Demo/rpc/test +++ /dev/null @@ -1,24 +0,0 @@ -: ${PYTHON=python} -: ${SERVER=charon.cwi.nl} - -set -xe - -$PYTHON -c 'from rpc import test; test()' -$PYTHON -c 'from rpc import test; test()' ${SERVER} - -$PYTHON -c 'from rpc import testsvr; testsvr()' & -PID=$! -sleep 2 -$PYTHON -c 'from rpc import testclt; testclt()' -kill -2 $PID - -$PYTHON -c 'from mountclient import test; test()' -$PYTHON -c 'from mountclient import test; test()' gatekeeper.dec.com - -$PYTHON -c 'from nfsclient import test; test()' -$PYTHON -c 'from nfsclient import test; test()' gatekeeper.dec.com -$PYTHON -c 'from nfsclient import test; test()' gatekeeper.dec.com /archive - -$PYTHON -c 'from rnusersclient import test; test()' '' - -$PYTHON -c 'from rpc import testbcast; testbcast()' diff --git a/Demo/rpc/xdr.py b/Demo/rpc/xdr.py deleted file mode 100644 index 41c970ae91..0000000000 --- a/Demo/rpc/xdr.py +++ /dev/null @@ -1,201 +0,0 @@ -# Implement (a subset of) Sun XDR -- RFC1014. - - -try: - import struct -except ImportError: - struct = None - - -Long = type(0L) - - -class Packer: - - def __init__(self): - self.reset() - - def reset(self): - self.buf = '' - - def get_buf(self): - return self.buf - - def pack_uint(self, x): - self.buf = self.buf + \ - (chr(int(x>>24 & 0xff)) + chr(int(x>>16 & 0xff)) + \ - chr(int(x>>8 & 0xff)) + chr(int(x & 0xff))) - if struct and struct.pack('l', 1) == '\0\0\0\1': - def pack_uint(self, x): - if type(x) == Long: - x = int((x + 0x80000000L) % 0x100000000L \ - - 0x80000000L) - self.buf = self.buf + struct.pack('l', x) - - pack_int = pack_uint - - pack_enum = pack_int - - def pack_bool(self, x): - if x: self.buf = self.buf + '\0\0\0\1' - else: self.buf = self.buf + '\0\0\0\0' - - def pack_uhyper(self, x): - self.pack_uint(int(x>>32 & 0xffffffff)) - self.pack_uint(int(x & 0xffffffff)) - - pack_hyper = pack_uhyper - - def pack_float(self, x): - # XXX - self.buf = self.buf + struct.pack('f', x) - - def pack_double(self, x): - # XXX - self.buf = self.buf + struct.pack('d', x) - - def pack_fstring(self, n, s): - if n < 0: - raise ValueError, 'fstring size must be nonnegative' - n = ((n+3)/4)*4 - data = s[:n] - data = data + (n - len(data)) * '\0' - self.buf = self.buf + data - - pack_fopaque = pack_fstring - - def pack_string(self, s): - n = len(s) - self.pack_uint(n) - self.pack_fstring(n, s) - - pack_opaque = pack_string - - def pack_list(self, list, pack_item): - for item in list: - self.pack_uint(1) - pack_item(item) - self.pack_uint(0) - - def pack_farray(self, n, list, pack_item): - if len(list) <> n: - raise ValueError, 'wrong array size' - for item in list: - pack_item(item) - - def pack_array(self, list, pack_item): - n = len(list) - self.pack_uint(n) - self.pack_farray(n, list, pack_item) - - -class Unpacker: - - def __init__(self, data): - self.reset(data) - - def reset(self, data): - self.buf = data - self.pos = 0 - - def done(self): - if self.pos < len(self.buf): - raise RuntimeError, 'unextracted data remains' - - def unpack_uint(self): - i = self.pos - self.pos = j = i+4 - data = self.buf[i:j] - if len(data) < 4: - raise EOFError - x = long(ord(data[0]))<<24 | ord(data[1])<<16 | \ - ord(data[2])<<8 | ord(data[3]) - # Return a Python long only if the value is not representable - # as a nonnegative Python int - if x < 0x80000000L: x = int(x) - return x - if struct and struct.unpack('l', '\0\0\0\1') == 1: - def unpack_uint(self): - i = self.pos - self.pos = j = i+4 - data = self.buf[i:j] - if len(data) < 4: - raise EOFError - return struct.unpack('l', data) - - def unpack_int(self): - x = self.unpack_uint() - if x >= 0x80000000L: x = x - 0x100000000L - return int(x) - - unpack_enum = unpack_int - - unpack_bool = unpack_int - - def unpack_uhyper(self): - hi = self.unpack_uint() - lo = self.unpack_uint() - return long(hi)<<32 | lo - - def unpack_hyper(self): - x = self.unpack_uhyper() - if x >= 0x8000000000000000L: x = x - 0x10000000000000000L - return x - - def unpack_float(self): - # XXX - i = self.pos - self.pos = j = i+4 - data = self.buf[i:j] - if len(data) < 4: - raise EOFError - return struct.unpack('f', data)[0] - - def unpack_double(self): - # XXX - i = self.pos - self.pos = j = i+8 - data = self.buf[i:j] - if len(data) < 8: - raise EOFError - return struct.unpack('d', data)[0] - - def unpack_fstring(self, n): - if n < 0: - raise ValueError, 'fstring size must be nonnegative' - i = self.pos - j = i + (n+3)/4*4 - if j > len(self.buf): - raise EOFError - self.pos = j - return self.buf[i:i+n] - - unpack_fopaque = unpack_fstring - - def unpack_string(self): - n = self.unpack_uint() - return self.unpack_fstring(n) - - unpack_opaque = unpack_string - - def unpack_list(self, unpack_item): - list = [] - while 1: - x = self.unpack_uint() - if x == 0: break - if x <> 1: - raise RuntimeError, \ - '0 or 1 expected, got ' + `x` - item = unpack_item() - list.append(item) - return list - - def unpack_farray(self, n, unpack_item): - list = [] - for i in range(n): - list.append(unpack_item()) - return list - - def unpack_array(self, unpack_item): - n = self.unpack_uint() - return self.unpack_farray(n, unpack_item) diff --git a/Demo/scripts/README b/Demo/scripts/README deleted file mode 100644 index 6bc66b6eda..0000000000 --- a/Demo/scripts/README +++ /dev/null @@ -1,18 +0,0 @@ -This directory contains a collection of executable Python scripts. - -See also the Tools/scripts directory! - -fact.py Factorize numbers -from.py Summarize mailbox -ftpstats.py Summarize ftp daemon log file -lpwatch.py Watch BSD line printer queues -markov.py Markov chain simulation of words or characters -mboxconvvert.py Convert MH or MMDF mailboxes to unix mailbox format -morse.py Produce morse code (audible or on AIFF file) -mpzpi.py test mpz -- print digits of pi (compare pi.py) -pi.py Print all digits of pi -- given enough time and memory -pp.py Emulate some Perl command line options -primes.py Print prime numbers -script.py Equivalent to BSD script(1) -- by Steen Lumholt -unbirthday.py Print unbirthday count -update.py Update a bunch of files according to a script. diff --git a/Demo/scripts/beer.py b/Demo/scripts/beer.py deleted file mode 100644 index 1b9ac8bade..0000000000 --- a/Demo/scripts/beer.py +++ /dev/null @@ -1,14 +0,0 @@ -#! /usr/bin/env python -# By GvR, demystified after a version by Fredrik Lundh. -import sys -n = 100 -if sys.argv[1:]: n = int(sys.argv[1]) -def bottle(n): - if n == 0: return "no more bottles of beer" - if n == 1: return "one bottle of beer" - return str(n) + " bottles of beer" -for i in range(n): - print bottle(n-i), "on the wall," - print bottle(n-i) + "." - print "Take one down, pass it around," - print bottle(n-i-1), "on the wall." diff --git a/Demo/scripts/eqfix.py b/Demo/scripts/eqfix.py deleted file mode 100755 index 583d54e0e7..0000000000 --- a/Demo/scripts/eqfix.py +++ /dev/null @@ -1,199 +0,0 @@ -#! /usr/bin/env python - -# Fix Python source files to use the new equality test operator, i.e., -# if x = y: ... -# is changed to -# if x == y: ... -# The script correctly tokenizes the Python program to reliably -# distinguish between assignments and equality tests. -# -# Command line arguments are files or directories to be processed. -# Directories are searched recursively for files whose name looks -# like a python module. -# Symbolic links are always ignored (except as explicit directory -# arguments). Of course, the original file is kept as a back-up -# (with a "~" attached to its name). -# It complains about binaries (files containing null bytes) -# and about files that are ostensibly not Python files: if the first -# line starts with '#!' and does not contain the string 'python'. -# -# Changes made are reported to stdout in a diff-like format. -# -# Undoubtedly you can do this using find and sed or perl, but this is -# a nice example of Python code that recurses down a directory tree -# and uses regular expressions. Also note several subtleties like -# preserving the file's mode and avoiding to even write a temp file -# when no changes are needed for a file. -# -# NB: by changing only the function fixline() you can turn this -# into a program for a different change to Python programs... - -import sys -import regex -import os -from stat import * -import string - -err = sys.stderr.write -dbg = err -rep = sys.stdout.write - -def main(): - bad = 0 - if not sys.argv[1:]: # No arguments - err('usage: ' + sys.argv[0] + ' file-or-directory ...\n') - sys.exit(2) - for arg in sys.argv[1:]: - if os.path.isdir(arg): - if recursedown(arg): bad = 1 - elif os.path.islink(arg): - err(arg + ': will not process symbolic links\n') - bad = 1 - else: - if fix(arg): bad = 1 - sys.exit(bad) - -ispythonprog = regex.compile('^[a-zA-Z0-9_]+\.py$') -def ispython(name): - return ispythonprog.match(name) >= 0 - -def recursedown(dirname): - dbg('recursedown(' + `dirname` + ')\n') - bad = 0 - try: - names = os.listdir(dirname) - except os.error, msg: - err(dirname + ': cannot list directory: ' + `msg` + '\n') - return 1 - names.sort() - subdirs = [] - for name in names: - if name in (os.curdir, os.pardir): continue - fullname = os.path.join(dirname, name) - if os.path.islink(fullname): pass - elif os.path.isdir(fullname): - subdirs.append(fullname) - elif ispython(name): - if fix(fullname): bad = 1 - for fullname in subdirs: - if recursedown(fullname): bad = 1 - return bad - -def fix(filename): -## dbg('fix(' + `filename` + ')\n') - try: - f = open(filename, 'r') - except IOError, msg: - err(filename + ': cannot open: ' + `msg` + '\n') - return 1 - head, tail = os.path.split(filename) - tempname = os.path.join(head, '@' + tail) - g = None - # If we find a match, we rewind the file and start over but - # now copy everything to a temp file. - lineno = 0 - while 1: - line = f.readline() - if not line: break - lineno = lineno + 1 - if g is None and '\0' in line: - # Check for binary files - err(filename + ': contains null bytes; not fixed\n') - f.close() - return 1 - if lineno == 1 and g is None and line[:2] == '#!': - # Check for non-Python scripts - words = string.split(line[2:]) - if words and regex.search('[pP]ython', words[0]) < 0: - msg = filename + ': ' + words[0] - msg = msg + ' script; not fixed\n' - err(msg) - f.close() - return 1 - while line[-2:] == '\\\n': - nextline = f.readline() - if not nextline: break - line = line + nextline - lineno = lineno + 1 - newline = fixline(line) - if newline != line: - if g is None: - try: - g = open(tempname, 'w') - except IOError, msg: - f.close() - err(tempname+': cannot create: '+\ - `msg`+'\n') - return 1 - f.seek(0) - lineno = 0 - rep(filename + ':\n') - continue # restart from the beginning - rep(`lineno` + '\n') - rep('< ' + line) - rep('> ' + newline) - if g is not None: - g.write(newline) - - # End of file - f.close() - if not g: return 0 # No changes - - # Finishing touch -- move files - - # First copy the file's mode to the temp file - try: - statbuf = os.stat(filename) - os.chmod(tempname, statbuf[ST_MODE] & 07777) - except os.error, msg: - err(tempname + ': warning: chmod failed (' + `msg` + ')\n') - # Then make a backup of the original file as filename~ - try: - os.rename(filename, filename + '~') - except os.error, msg: - err(filename + ': warning: backup failed (' + `msg` + ')\n') - # Now move the temp file to the original file - try: - os.rename(tempname, filename) - except os.error, msg: - err(filename + ': rename failed (' + `msg` + ')\n') - return 1 - # Return succes - return 0 - - -from tokenize import tokenprog - -match = {'if':':', 'elif':':', 'while':':', 'return':'\n', \ - '(':')', '[':']', '{':'}', '`':'`'} - -def fixline(line): - # Quick check for easy case - if '=' not in line: return line - - i, n = 0, len(line) - stack = [] - while i < n: - j = tokenprog.match(line, i) - if j < 0: - # A bad token; forget about the rest of this line - print '(Syntax error:)' - print line, - return line - a, b = tokenprog.regs[3] # Location of the token proper - token = line[a:b] - i = i+j - if stack and token == stack[-1]: - del stack[-1] - elif match.has_key(token): - stack.append(match[token]) - elif token == '=' and stack: - line = line[:a] + '==' + line[b:] - i, n = a + len('=='), len(line) - elif token == '==' and not stack: - print '(Warning: \'==\' at top level:)' - print line, - return line - - -main() diff --git a/Demo/scripts/fact.py b/Demo/scripts/fact.py deleted file mode 100755 index 6cc389ea6f..0000000000 --- a/Demo/scripts/fact.py +++ /dev/null @@ -1,48 +0,0 @@ -#! /usr/bin/env python - -# Factorize numbers. -# The algorithm is not efficient, but easy to understand. -# If there are large factors, it will take forever to find them, -# because we try all odd numbers between 3 and sqrt(n)... - -import sys -from math import sqrt - -error = 'fact.error' # exception - -def fact(n): - if n < 1: raise error # fact() argument should be >= 1 - if n == 1: return [] # special case - res = [] - # Treat even factors special, so we can use i = i+2 later - while n%2 == 0: - res.append(2) - n = n/2 - # Try odd numbers up to sqrt(n) - limit = sqrt(float(n+1)) - i = 3 - while i <= limit: - if n%i == 0: - res.append(i) - n = n/i - limit = sqrt(n+1) - else: - i = i+2 - if n != 1: - res.append(n) - return res - -def main(): - if len(sys.argv) > 1: - for arg in sys.argv[1:]: - n = eval(arg) - print n, fact(n) - else: - try: - while 1: - n = input() - print n, fact(n) - except EOFError: - pass - -main() diff --git a/Demo/scripts/freeze.py b/Demo/scripts/freeze.py deleted file mode 100755 index be6d263584..0000000000 --- a/Demo/scripts/freeze.py +++ /dev/null @@ -1,480 +0,0 @@ -#! /usr/local/bin/python - -# Given a Python script, create a binary that runs the script. -# The binary is 100% independent of Python libraries and binaries. -# It will not contain any Python source code -- only "compiled" Python -# (as initialized static variables containing marshalled code objects). -# It even does the right thing for dynamically loaded modules! -# The module search path of the binary is set to the current directory. -# -# Some problems remain: -# - It's highly non-portable, since it knows about paths and libraries -# (there's a customization section though, and it knows how to -# distinguish an SGI from a Sun SPARC system -- adding knowledge -# about more systems is left as an exercise for the reader). -# - You need to have the Python source tree lying around as well as -# the "libpython.a" used to generate the Python binary. -# - For scripts that use many modules it generates absurdly large -# files (frozen.c and config.o as well as the final binary), -# and is consequently rather slow. -# -# Caveats: -# - The search for modules sometimes finds modules that are never -# actually imported since the code importing them is never executed. -# - If an imported module isn't found, you get a warning but the -# process of freezing continues. The binary will fail if it -# actually tries to import one of these modules. -# - This often happens with the module 'mac', which module 'os' tries -# to import (to determine whether it is running on a Macintosh). -# You can ignore the warning about this. -# - If the program dynamically reads or generates Python code and -# executes it, this code may reference built-in or library modules -# that aren't present in the frozen binary, and this will fail. -# - Your program may be using external data files, e.g. compiled -# forms definitions (*.fd). These aren't incorporated. Since -# sys.path in the resulting binary only contains '.', if your -# program searches its data files along sys.path (as the 'flp' -# modules does to find its forms definitions), you may need to -# change the program to extend the search path or instruct its users -# to set the environment variable PYTHONPATH to point to your data -# files. -# -# Usage hints: -# - If you have a bunch of scripts that you want to freeze, instead -# of freezing each of them separately, you might consider writing -# a tiny main script that looks at sys.argv[0] and then imports -# the corresponding module. You can then make links to the -# frozen binary named after the various scripts you support. -# Pass the additional scripts as arguments after the main script. -# A minimal script to do this is the following. -# import sys, posixpath -# exec('import ' + posixpath.basename(sys.argv[0]) + '\n') - - -import os -import sys -import regex -import getopt -import regsub -import string -import marshal - -# Function to join two pathnames with a slash in between -j = os.path.join - -################################## -# START OF CONFIGURATION SECTION # -################################## - -# Attempt to guess machine architecture -if os.path.exists('/usr/lib/libgl_s'): ARCH = 'sgi' -elif os.path.exists('/etc/issue'): ARCH = 'sequent' -else: ARCH = 'sun4' - -# Site parametrizations (change to match your site) -CC = 'cc' # C compiler -TOP = '/ufs/guido/src' # Parent of all source trees -PYTHON = j(TOP, 'python') # Top of the Python source tree -SRC = j(PYTHON, 'src') # Python source directory -BLD = j(PYTHON, 'build.' + ARCH) # Python build directory -#BLD = SRC # Use this if you build in SRC - -LIBINST = '/ufs/guido/src/python/irix4/tmp/lib/python/lib' # installed libraries -INCLINST = '/ufs/guido/src/python/irix4/tmp/include/Py' # installed include files - -# Other packages (change to match your site) -DL = j(TOP, 'dl') # Top of the dl source tree -DL_DLD = j(TOP, 'dl-dld') # The dl-dld source directory -DLD = j(TOP, 'dld-3.2.3') # The dld source directory -FORMS = j(TOP, 'forms') # Top of the FORMS source tree -STDWIN = j(TOP, 'stdwin') # Top of the STDWIN source tree -READLINE = j(TOP, 'readline.' + ARCH) # Top of the GNU Readline source tree -SUN_X11 = '/usr/local/X11R5/lib/libX11.a' - -# File names (usually no need to change) -LIBP = [ # Main Python libraries - j(LIBINST, 'libPython.a'), - j(LIBINST, 'libParser.a'), - j(LIBINST, 'libObjects.a'), - j(LIBINST, 'libModules.a') - ] -CONFIG_IN = j(LIBINST, 'config.c.in') # Configuration source file -FMAIN = j(LIBINST, 'frozenmain.c') # Special main source file - -# Libraries needed when linking. First tuple item is built-in module -# for which it is needed (or '*' for always), rest are ld arguments. -# There is a separate list per architecture. -libdeps_sgi = [ \ - ('stdwin', j(STDWIN, 'Build/' + ARCH + '/x11/lib/lib.a')), \ - ('fl', j(FORMS, 'FORMS/libforms.a'), '-lfm_s'), \ - ('*', j(READLINE, 'libreadline.a'), '-ltermcap'), \ - ('al', '-laudio'), \ - ('sv', '-lsvideo', '-lXext'), \ - ('cd', '-lcdaudio', '-lds'), \ - ('cl', '-lcl'), \ - ('imgfile', '-limage', '-lgutil', '-lm'), \ - ('mpz', '/ufs/guido/src/gmp/libgmp.a'), \ - ('*', '-lsun'), \ - ('*', j(DL, 'libdl.a'), '-lmld'), \ - ('*', '-lmpc'), \ - ('fm', '-lfm_s'), \ - ('gl', '-lgl_s', '-lX11_s'), \ - ('stdwin', '-lX11_s'), \ - ('*', '-lm'), \ - ('*', '-lc_s'), \ - ] -libdeps_sun4 = [ \ - ('*', '-Bstatic'), \ - ('stdwin', j(STDWIN, 'Build/' + ARCH + '/x11/lib/lib.a')), \ - ('*', j(READLINE, 'libreadline.a')), \ - ('*', '-lm'), \ - ('*', j(DL_DLD,'libdl.a'), j(DLD,'libdld.a')), \ - ('*', SUN_X11), \ - ('*', '-ltermcap'), \ - ('*', '-lc'), \ - ] -libdeps_sequent = [ \ - ('*', j(LIBINST, 'libreadline.a'), '-ltermcap'), \ - ('*', '-lsocket'), \ - ('*', '-linet'), \ - ('*', '-lnsl'), \ - ('*', '-lm'), \ - ('*', '-lc'), \ - ] -libdeps = eval('libdeps_' + ARCH) - -################################ -# END OF CONFIGURATION SECTION # -################################ - -# Exception used when scanfile fails -NoSuchFile = 'NoSuchFile' - -# Global options -quiet = 0 # -q -verbose = 0 # -v -noexec = 0 # -n -nowrite = 0 # -N -ofile = 'a.out' # -o file - -# Main program -- argument parsing etc. -def main(): - global quiet, verbose, noexec, nowrite, ofile - try: - opts, args = getopt.getopt(sys.argv[1:], 'nNo:qv') - except getopt.error, msg: - usage(str(msg)) - sys.exit(2) - for o, a in opts: - if o == '-n': noexec = 1 - if o == '-N': nowrite = 1 - if o == '-o': ofile = a - if o == '-q': verbose = 0; quiet = 1 - if o == '-v': verbose = verbose + 1; quiet = 0 - if len(args) < 1: - usage('please pass at least one file argument') - sys.exit(2) - process(args[0], args[1:]) - -# Print usage message to stderr -def usage(*msgs): - sys.stdout = sys.stderr - for msg in msgs: print msg - print 'Usage: freeze [options] scriptfile [modulefile ...]' - print '-n : generate the files but don\'t compile and link' - print '-N : don\'t write frozen.c (do compile unless -n given)' - print '-o file : binary output file (default a.out)' - print '-q : quiet (no messages at all except errors)' - print '-v : verbose (lots of extra messages)' - -# Process the script file -def process(filename, addmodules): - global noexec - # - if not quiet: print 'Computing needed modules ...' - todo = {} - todo['__main__'] = filename - for name in addmodules: - mod = os.path.basename(name) - if mod[-3:] == '.py': mod = mod[:-3] - todo[mod] = name - try: - dict = closure(todo) - except NoSuchFile, filename: - sys.stderr.write('Can\'t open file %s\n' % filename) - sys.exit(1) - # - mods = dict.keys() - mods.sort() - # - if verbose: - print '%-15s %s' % ('Module', 'Filename') - for mod in mods: - print '%-15s %s' % (`mod`, dict[mod]) - # - if not quiet: print 'Looking for dynamically linked modules ...' - dlmodules = [] - objs = [] - libs = [] - for mod in mods: - if dict[mod][-2:] == '.o': - if verbose: print 'Found', mod, dict[mod] - dlmodules.append(mod) - objs.append(dict[mod]) - libsname = dict[mod][:-2] + '.libs' - try: - f = open(libsname, 'r') - except IOError: - f = None - if f: - libtext = f.read() - f.close() - for lib in string.split(libtext): - if lib in libs: libs.remove(lib) - libs.append(lib) - # - if not nowrite: - if not quiet: print 'Writing frozen.c ...' - writefrozen('frozen.c', dict) - else: - if not quiet: print 'NOT writing frozen.c ...' - # -## if not dlmodules: - if 0: - config = CONFIG - if not quiet: print 'Using existing', config, '...' - else: - config = 'tmpconfig.c' - if nowrite: - if not quiet: print 'NOT writing config.c ...' - else: - if not quiet: - print 'Writing config.c with dl modules ...' - f = open(CONFIG_IN, 'r') - g = open(config, 'w') - m1 = regex.compile('-- ADDMODULE MARKER 1 --') - m2 = regex.compile('-- ADDMODULE MARKER 2 --') - builtinmodules = [] - stdmodules = ('sys', '__main__', '__builtin__', - 'marshal') - todomodules = builtinmodules + dlmodules - for mod in dict.keys(): - if dict[mod] == '' and \ - mod not in stdmodules: - builtinmodules.append(mod) - while 1: - line = f.readline() - if not line: break - g.write(line) - if m1.search(line) >= 0: - if verbose: print 'Marker 1 ...' - for mod in todomodules: - g.write('extern void init' + \ - mod + '();\n') - if m2.search(line) >= 0: - if verbose: print 'Marker 2 ...' - for mod in todomodules: - g.write('{"' + mod + \ - '", init' + mod + '},\n') - g.close() - # - if not quiet: - if noexec: print 'Generating compilation commands ...' - else: print 'Starting compilation ...' - defs = ['-DNO_MAIN', '-DUSE_FROZEN', '-DPYTHONPATH=\'"."\''] - # - incs = ['-I.', '-I' + INCLINST] - if dict.has_key('stdwin'): - incs.append('-I' + j(STDWIN, 'H')) - # - srcs = [config, FMAIN] - # - if type(LIBP) == type(''): - libs.append(LIBP) - else: - for lib in LIBP: - libs.append(lib) - for item in libdeps: - m = item[0] - if m == '*' or dict.has_key(m): - for l in item[1:]: - if l in libs: libs.remove(l) - libs.append(l) - # - sts = 0 - # - cmd = CC + ' -c' - cmd = cmd + ' ' + string.join(defs) - cmd = cmd + ' ' + string.join(incs) - cmd = cmd + ' ' + string.join(srcs) - print cmd - # - if not noexec: - sts = os.system(cmd) - if sts: - print 'Exit status', sts, '-- turning on -n' - noexec = 1 - # - for s in srcs: - s = os.path.basename(s) - if s[-2:] == '.c': s = s[:-2] - o = s + '.o' - objs.insert(0, o) - # - cmd = CC - cmd = cmd + ' ' + string.join(objs) - cmd = cmd + ' ' + string.join(libs) - cmd = cmd + ' -o ' + ofile - print cmd - # - if not noexec: - sts = os.system(cmd) - if sts: - print 'Exit status', sts - else: - print 'Done.' - # - if not quiet and not noexec and sts == 0: - print 'Note: consider this:'; print '\tstrip', ofile - # - sys.exit(sts) - - -# Generate code for a given module -def makecode(filename): - if filename[-2:] == '.o': - return None - try: - f = open(filename, 'r') - except IOError: - return None - if verbose: print 'Making code from', filename, '...' - text = f.read() - code = compile(text, filename, 'exec') - f.close() - return marshal.dumps(code) - - -# Write the C source file containing the frozen Python code -def writefrozen(filename, dict): - f = open(filename, 'w') - codelist = [] - for mod in dict.keys(): - codestring = makecode(dict[mod]) - if codestring is not None: - codelist.append((mod, codestring)) - write = sys.stdout.write - save_stdout = sys.stdout - try: - sys.stdout = f - for mod, codestring in codelist: - if verbose: - write('Writing initializer for %s\n'%mod) - print 'static unsigned char M_' + mod + '[' + \ - str(len(codestring)) + '+1] = {' - for i in range(0, len(codestring), 16): - for c in codestring[i:i+16]: - print str(ord(c)) + ',', - print - print '};' - print 'struct frozen {' - print ' char *name;' - print ' unsigned char *code;' - print ' int size;' - print '} frozen_modules[] = {' - for mod, codestring in codelist: - print ' {"' + mod + '",', - print 'M_' + mod + ',', - print str(len(codestring)) + '},' - print ' {0, 0, 0} /* sentinel */' - print '};' - finally: - sys.stdout = save_stdout - f.close() - - -# Determine the names and filenames of the modules imported by the -# script, recursively. This is done by scanning for lines containing -# import statements. (The scanning has only superficial knowledge of -# Python syntax and no knowledge of semantics, so in theory the result -# may be incorrect -- however this is quite unlikely if you don't -# intentionally obscure your Python code.) - -# Compute the closure of scanfile() -- special first file because of script -def closure(todo): - done = {} - while todo: - newtodo = {} - for modname in todo.keys(): - if not done.has_key(modname): - filename = todo[modname] - if filename is None: - filename = findmodule(modname) - done[modname] = filename - if filename in ('', ''): - continue - modules = scanfile(filename) - for m in modules: - if not done.has_key(m): - newtodo[m] = None - todo = newtodo - return done - -# Scan a file looking for import statements -importstr = '\(^\|:\)[ \t]*import[ \t]+\([a-zA-Z0-9_, \t]+\)' -fromstr = '\(^\|:\)[ \t]*from[ \t]+\([a-zA-Z0-9_]+\)[ \t]+import[ \t]+' -isimport = regex.compile(importstr) -isfrom = regex.compile(fromstr) -def scanfile(filename): - allmodules = {} - try: - f = open(filename, 'r') - except IOError, msg: - raise NoSuchFile, filename - while 1: - line = f.readline() - if not line: break # EOF - while line[-2:] == '\\\n': # Continuation line - line = line[:-2] + ' ' - line = line + f.readline() - if isimport.search(line) >= 0: - rawmodules = isimport.group(2) - modules = string.splitfields(rawmodules, ',') - for i in range(len(modules)): - modules[i] = string.strip(modules[i]) - elif isfrom.search(line) >= 0: - modules = [isfrom.group(2)] - else: - continue - for mod in modules: - allmodules[mod] = None - f.close() - return allmodules.keys() - -# Find the file containing a module, given its name; None if not found -builtins = sys.builtin_module_names + ['sys'] -def findmodule(modname): - if modname in builtins: return '' - for dirname in sys.path: - dlfullname = os.path.join(dirname, modname + 'module.o') - try: - f = open(dlfullname, 'r') - except IOError: - f = None - if f: - f.close() - return dlfullname - fullname = os.path.join(dirname, modname + '.py') - try: - f = open(fullname, 'r') - except IOError: - continue - f.close() - return fullname - if not quiet: - sys.stderr.write('Warning: module %s not found\n' % modname) - return '' - - -# Call the main program -main() diff --git a/Demo/scripts/from.py b/Demo/scripts/from.py deleted file mode 100755 index d61afde06e..0000000000 --- a/Demo/scripts/from.py +++ /dev/null @@ -1,35 +0,0 @@ -#! /usr/bin/env python - -# Print From and Subject of messages in $MAIL. -# Extension to multiple mailboxes and other bells & whistles are left -# as exercises for the reader. - -import sys, os - -# Open mailbox file. Exits with exception when this fails. - -try: - mailbox = os.environ['MAIL'] -except (AttributeError, KeyError): - sys.stderr.write('No environment variable $MAIL\n') - sys.exit(2) - -try: - mail = open(mailbox) -except IOError: - sys.exit('Cannot open mailbox file: ' + mailbox) - -while 1: - line = mail.readline() - if not line: - break # EOF - if line.startswith('From '): - # Start of message found - print line[:-1], - while 1: - line = mail.readline() - if not line or line == '\n': - break - if line.startswith('Subject: '): - print `line[9:-1]`, - print diff --git a/Demo/scripts/ftpstats.py b/Demo/scripts/ftpstats.py deleted file mode 100755 index 28b1d8bdfd..0000000000 --- a/Demo/scripts/ftpstats.py +++ /dev/null @@ -1,144 +0,0 @@ -#! /usr/bin/env python - -# Extract statistics from ftp daemon log. - -# Usage: -# ftpstats [-m maxitems] [-s search] [file] -# -m maxitems: restrict number of items in "top-N" lists, default 25. -# -s string: restrict statistics to lines containing this string. -# Default file is /usr/adm/ftpd; a "-" means read stdandard input. - -# The script must be run on the host where the ftp daemon runs. -# (At CWI this is currently buizerd.) - -import os -import sys -import regex -import string -import getopt - -pat = '^\([a-zA-Z0-9 :]*\)!\(.*\)!\(.*\)!\([<>].*\)!\([0-9]+\)!\([0-9]+\)$' -prog = regex.compile(pat) - -def main(): - maxitems = 25 - search = None - try: - opts, args = getopt.getopt(sys.argv[1:], 'm:s:') - except getopt.error, msg: - print msg - print 'usage: ftpstats [-m maxitems] [file]' - sys.exit(2) - for o, a in opts: - if o == '-m': - maxitems = string.atoi(a) - if o == '-s': - search = a - file = '/usr/adm/ftpd' - if args: file = args[0] - if file == '-': - f = sys.stdin - else: - try: - f = open(file, 'r') - except IOError, msg: - print file, ':', msg - sys.exit(1) - bydate = {} - bytime = {} - byfile = {} - bydir = {} - byhost = {} - byuser = {} - bytype = {} - lineno = 0 - try: - while 1: - line = f.readline() - if not line: break - lineno = lineno + 1 - if search and string.find(line, search) < 0: - continue - if prog.match(line) < 0: - print 'Bad line', lineno, ':', `line` - continue - items = prog.group(1, 2, 3, 4, 5, 6) - (logtime, loguser, loghost, logfile, logbytes, - logxxx2) = items -## print logtime -## print '-->', loguser -## print '--> -->', loghost -## print '--> --> -->', logfile -## print '--> --> --> -->', logbytes -## print '--> --> --> --> -->', logxxx2 -## for i in logtime, loghost, logbytes, logxxx2: -## if '!' in i: print '???', i - add(bydate, logtime[-4:] + ' ' + logtime[:6], items) - add(bytime, logtime[7:9] + ':00-59', items) - direction, logfile = logfile[0], logfile[1:] - # The real path probably starts at the last //... - while 1: - i = string.find(logfile, '//') - if i < 0: break - logfile = logfile[i+1:] - add(byfile, logfile + ' ' + direction, items) - logdir = os.path.dirname(logfile) -## logdir = os.path.normpath(logdir) + '/.' - while 1: - add(bydir, logdir + ' ' + direction, items) - dirhead = os.path.dirname(logdir) - if dirhead == logdir: break - logdir = dirhead - add(byhost, loghost, items) - add(byuser, loguser, items) - add(bytype, direction, items) - except KeyboardInterrupt: - print 'Interrupted at line', lineno - show(bytype, 'by transfer direction', maxitems) - show(bydir, 'by directory', maxitems) - show(byfile, 'by file', maxitems) - show(byhost, 'by host', maxitems) - show(byuser, 'by user', maxitems) - showbar(bydate, 'by date') - showbar(bytime, 'by time of day') - -def showbar(dict, title): - n = len(title) - print '='*((70-n)/2), title, '='*((71-n)/2) - list = [] - keys = dict.keys() - keys.sort() - for key in keys: - n = len(str(key)) - list.append((len(dict[key]), key)) - maxkeylength = 0 - maxcount = 0 - for count, key in list: - maxkeylength = max(maxkeylength, len(key)) - maxcount = max(maxcount, count) - maxbarlength = 72 - maxkeylength - 7 - for count, key in list: - barlength = int(round(maxbarlength*float(count)/maxcount)) - bar = '*'*barlength - print '%5d %-*s %s' % (count, maxkeylength, key, bar) - -def show(dict, title, maxitems): - if len(dict) > maxitems: - title = title + ' (first %d)'%maxitems - n = len(title) - print '='*((70-n)/2), title, '='*((71-n)/2) - list = [] - keys = dict.keys() - for key in keys: - list.append((-len(dict[key]), key)) - list.sort() - for count, key in list[:maxitems]: - print '%5d %s' % (-count, key) - -def add(dict, key, item): - if dict.has_key(key): - dict[key].append(item) - else: - dict[key] = [item] - -main() diff --git a/Demo/scripts/lpwatch.py b/Demo/scripts/lpwatch.py deleted file mode 100755 index 9f051ebbf3..0000000000 --- a/Demo/scripts/lpwatch.py +++ /dev/null @@ -1,109 +0,0 @@ -#! /usr/bin/env python - -# Watch line printer queue(s). -# Intended for BSD 4.3 lpq. - -import posix -import sys -import time -import string - -DEF_PRINTER = 'psc' -DEF_DELAY = 10 - -def main(): - delay = DEF_DELAY # XXX Use getopt() later - try: - thisuser = posix.environ['LOGNAME'] - except: - thisuser = posix.environ['USER'] - printers = sys.argv[1:] - if printers: - # Strip '-P' from printer names just in case - # the user specified it... - for i in range(len(printers)): - if printers[i][:2] == '-P': - printers[i] = printers[i][2:] - else: - if posix.environ.has_key('PRINTER'): - printers = [posix.environ['PRINTER']] - else: - printers = [DEF_PRINTER] - # - clearhome = posix.popen('clear', 'r').read() - # - while 1: - text = clearhome - for name in printers: - text = text + makestatus(name, thisuser) + '\n' - print text - time.sleep(delay) - -def makestatus(name, thisuser): - pipe = posix.popen('lpq -P' + name + ' 2>&1', 'r') - lines = [] - users = {} - aheadbytes = 0 - aheadjobs = 0 - userseen = 0 - totalbytes = 0 - totaljobs = 0 - while 1: - line = pipe.readline() - if not line: break - fields = string.split(line) - n = len(fields) - if len(fields) >= 6 and fields[n-1] == 'bytes': - rank = fields[0] - user = fields[1] - job = fields[2] - files = fields[3:-2] - bytes = eval(fields[n-2]) - if user == thisuser: - userseen = 1 - elif not userseen: - aheadbytes = aheadbytes + bytes - aheadjobs = aheadjobs + 1 - totalbytes = totalbytes + bytes - totaljobs = totaljobs + 1 - if users.has_key(user): - ujobs, ubytes = users[user] - else: - ujobs, ubytes = 0, 0 - ujobs = ujobs + 1 - ubytes = ubytes + bytes - users[user] = ujobs, ubytes - else: - if fields and fields[0] <> 'Rank': - line = string.strip(line) - if line == 'no entries': - line = name + ': idle' - elif line[-22:] == ' is ready and printing': - line = name - lines.append(line) - # - if totaljobs: - line = `(totalbytes+1023)/1024` + ' K' - if totaljobs <> len(users): - line = line + ' (' + `totaljobs` + ' jobs)' - if len(users) == 1: - line = line + ' for ' + users.keys()[0] - else: - line = line + ' for ' + `len(users)` + ' users' - if userseen: - if aheadjobs == 0: - line = line + ' (' + thisuser + ' first)' - else: - line = line + ' (' + `(aheadbytes+1023)/1024` - line = line + ' K before ' + thisuser + ')' - lines.append(line) - # - sts = pipe.close() - if sts: - lines.append('lpq exit status ' + `sts`) - return string.joinfields(lines, ': ') - -try: - main() -except KeyboardInterrupt: - pass diff --git a/Demo/scripts/makedir.py b/Demo/scripts/makedir.py deleted file mode 100755 index 4c00d88809..0000000000 --- a/Demo/scripts/makedir.py +++ /dev/null @@ -1,20 +0,0 @@ -#! /usr/bin/env python - -# Like mkdir, but also make intermediate directories if necessary. -# It is not an error if the given directory already exists (as long -# as it is a directory). -# Errors are not treated specially -- you just get a Python exception. - -import sys, os - -def main(): - for p in sys.argv[1:]: - makedirs(p) - -def makedirs(p): - if p and not os.path.isdir(p): - head, tail = os.path.split(p) - makedirs(head) - os.mkdir(p, 0777) - -main() diff --git a/Demo/scripts/markov.py b/Demo/scripts/markov.py deleted file mode 100755 index e1649f1e9d..0000000000 --- a/Demo/scripts/markov.py +++ /dev/null @@ -1,116 +0,0 @@ -#! /usr/bin/env python - -class Markov: - def __init__(self, histsize, choice): - self.histsize = histsize - self.choice = choice - self.trans = {} - def add(self, state, next): - if not self.trans.has_key(state): - self.trans[state] = [next] - else: - self.trans[state].append(next) - def put(self, seq): - n = self.histsize - add = self.add - add(None, seq[:0]) - for i in range(len(seq)): - add(seq[max(0, i-n):i], seq[i:i+1]) - add(seq[len(seq)-n:], None) - def get(self): - choice = self.choice - trans = self.trans - n = self.histsize - seq = choice(trans[None]) - while 1: - subseq = seq[max(0, len(seq)-n):] - options = trans[subseq] - next = choice(options) - if not next: break - seq = seq + next - return seq - -def test(): - import sys, string, random, getopt - args = sys.argv[1:] - try: - opts, args = getopt.getopt(args, '0123456789cdw') - except getopt.error: - print 'Usage: markov [-#] [-cddqw] [file] ...' - print 'Options:' - print '-#: 1-digit history size (default 2)' - print '-c: characters (default)' - print '-w: words' - print '-d: more debugging output' - print '-q: no debugging output' - print 'Input files (default stdin) are split in paragraphs' - print 'separated blank lines and each paragraph is split' - print 'in words by whitespace, then reconcatenated with' - print 'exactly one space separating words.' - print 'Output consists of paragraphs separated by blank' - print 'lines, where lines are no longer than 72 characters.' - histsize = 2 - do_words = 0 - debug = 1 - for o, a in opts: - if '-0' <= o <= '-9': histsize = eval(o[1:]) - if o == '-c': do_words = 0 - if o == '-d': debug = debug + 1 - if o == '-q': debug = 0 - if o == '-w': do_words = 1 - if not args: args = ['-'] - m = Markov(histsize, random.choice) - try: - for filename in args: - if filename == '-': - f = sys.stdin - if f.isatty(): - print 'Sorry, need stdin from file' - continue - else: - f = open(filename, 'r') - if debug: print 'processing', filename, '...' - text = f.read() - f.close() - paralist = string.splitfields(text, '\n\n') - for para in paralist: - if debug > 1: print 'feeding ...' - words = string.split(para) - if words: - if do_words: data = tuple(words) - else: data = string.joinfields(words, ' ') - m.put(data) - except KeyboardInterrupt: - print 'Interrupted -- continue with data read so far' - if not m.trans: - print 'No valid input files' - return - if debug: print 'done.' - if debug > 1: - for key in m.trans.keys(): - if key is None or len(key) < histsize: - print `key`, m.trans[key] - if histsize == 0: print `''`, m.trans[''] - print - while 1: - data = m.get() - if do_words: words = data - else: words = string.split(data) - n = 0 - limit = 72 - for w in words: - if n + len(w) > limit: - print - n = 0 - print w, - n = n + len(w) + 1 - print - print - -def tuple(list): - if len(list) == 0: return () - if len(list) == 1: return (list[0],) - i = len(list)/2 - return tuple(list[:i]) + tuple(list[i:]) - -test() diff --git a/Demo/scripts/mboxconvert.py b/Demo/scripts/mboxconvert.py deleted file mode 100755 index 08e0d0cbe5..0000000000 --- a/Demo/scripts/mboxconvert.py +++ /dev/null @@ -1,123 +0,0 @@ -#! /usr/bin/env python - -# Convert MH directories (1 message per file) or MMDF mailboxes (4x^A -# delimited) to unix mailbox (From ... delimited) on stdout. -# If -f is given, files contain one message per file (e.g. MH messages) - -import rfc822 -import sys -import time -import os -import stat -import getopt -import regex - -def main(): - dofile = mmdf - try: - opts, args = getopt.getopt(sys.argv[1:], 'f') - except getopt.error, msg: - sys.stderr.write('%s\n' % msg) - sys.exit(2) - for o, a in opts: - if o == '-f': - dofile = message - if not args: - args = ['-'] - sts = 0 - for arg in args: - if arg == '-' or arg == '': - sts = dofile(sys.stdin) or sts - elif os.path.isdir(arg): - sts = mh(arg) or sts - elif os.path.isfile(arg): - try: - f = open(arg) - except IOError, msg: - sys.stderr.write('%s: %s\n' % (arg, msg)) - sts = 1 - continue - sts = dofile(f) or sts - f.close() - else: - sys.stderr.write('%s: not found\n' % arg) - sts = 1 - if sts: - sys.exit(sts) - -numeric = regex.compile('[1-9][0-9]*') - -def mh(dir): - sts = 0 - msgs = os.listdir(dir) - for msg in msgs: - if numeric.match(msg) != len(msg): - continue - fn = os.path.join(dir, msg) - try: - f = open(fn) - except IOError, msg: - sys.stderr.write('%s: %s\n' % (fn, msg)) - sts = 1 - continue - sts = message(f) or sts - return sts - -def mmdf(f): - sts = 0 - while 1: - line = f.readline() - if not line: - break - if line == '\1\1\1\1\n': - sts = message(f, line) or sts - else: - sys.stderr.write( - 'Bad line in MMFD mailbox: %s\n' % `line`) - return sts - -counter = 0 # for generating unique Message-ID headers - -def message(f, delimiter = ''): - sts = 0 - # Parse RFC822 header - m = rfc822.Message(f) - # Write unix header line - fullname, email = m.getaddr('From') - tt = m.getdate('Date') - if tt: - t = time.mktime(tt) - else: - sys.stderr.write( - 'Unparseable date: %s\n' % `m.getheader('Date')`) - t = os.fstat(f.fileno())[stat.ST_MTIME] - print 'From', email, time.ctime(t) - # Copy RFC822 header - for line in m.headers: - print line, - # Invent Message-ID header if none is present - if not m.has_key('message-id'): - global counter - counter = counter + 1 - msgid = "<%s.%d>" % (hex(t), counter) - sys.stderr.write("Adding Message-ID %s (From %s)\n" % - (msgid, email)) - print "Message-ID:", msgid - print - # Copy body - while 1: - line = f.readline() - if line == delimiter: - break - if not line: - sys.stderr.write('Unexpected EOF in message\n') - sts = 1 - break - if line[:5] == 'From ': - line = '>' + line - print line, - # Print trailing newline - print - return sts - -main() diff --git a/Demo/scripts/mkrcs.py b/Demo/scripts/mkrcs.py deleted file mode 100755 index 36a35eace2..0000000000 --- a/Demo/scripts/mkrcs.py +++ /dev/null @@ -1,60 +0,0 @@ -#! /usr/bin/env python - -# A rather specialized script to make sure that a symbolic link named -# RCS exists pointing to a real RCS directory in a parallel tree -# referenced as RCStree in an ancestor directory. -# (I use this because I like my RCS files to reside on a physically -# different machine). - -import os - -def main(): - rcstree = 'RCStree' - rcs = 'RCS' - if os.path.islink(rcs): - print `rcs`, 'is a symlink to', `os.readlink(rcs)` - return - if os.path.isdir(rcs): - print `rcs`, 'is an ordinary directory' - return - if os.path.exists(rcs): - print `rcs`, 'is a file?!?!' - return - # - p = os.getcwd() - up = '' - down = '' - # Invariants: - # (1) join(p, down) is the current directory - # (2) up is the same directory as p - # Ergo: - # (3) join(up, down) is the current directory - #print 'p =', `p` - while not os.path.isdir(os.path.join(p, rcstree)): - head, tail = os.path.split(p) - #print 'head =', `head`, '; tail =', `tail` - if not tail: - print 'Sorry, no ancestor dir contains', `rcstree` - return - p = head - up = os.path.join(os.pardir, up) - down = os.path.join(tail, down) - #print 'p =', `p`, '; up =', `up`, '; down =', `down` - there = os.path.join(up, rcstree) - there = os.path.join(there, down) - there = os.path.join(there, rcs) - if os.path.isdir(there): - print `there`, 'already exists' - else: - print 'making', `there` - makedirs(there) - print 'making symlink', `rcs`, '->', `there` - os.symlink(there, rcs) - -def makedirs(p): - if not os.path.isdir(p): - head, tail = os.path.split(p) - makedirs(head) - os.mkdir(p, 0777) - -main() diff --git a/Demo/scripts/morse.py b/Demo/scripts/morse.py deleted file mode 100755 index 2cea83e402..0000000000 --- a/Demo/scripts/morse.py +++ /dev/null @@ -1,149 +0,0 @@ -# DAH should be three DOTs. -# Space between DOTs and DAHs should be one DOT. -# Space between two letters should be one DAH. -# Space between two words should be DOT DAH DAH. - -import sys, math, audiodev - -DOT = 30 -DAH = 3 * DOT -OCTAVE = 2 # 1 == 441 Hz, 2 == 882 Hz, ... - -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': '----.', - ',': '--..--', - '.': '.-.-.-', - '?': '..--..', - ';': '-.-.-.', - ':': '---...', - "'": '.----.', - '-': '-....-', - '/': '-..-.', - '(': '-.--.-', - ')': '-.--.-', - '_': '..--.-', - ' ': ' ' -} - -# If we play at 44.1 kHz (which we do), then if we produce one sine -# wave in 100 samples, we get a tone of 441 Hz. If we produce two -# 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 = '' - for i in range(100): - val = int(math.sin(math.pi * float(i) * octave / 50.0) * 30000) - sinewave = sinewave + chr((val >> 8) & 255) + chr(val & 255) - nowave = '\0' * 200 - -mkwave(OCTAVE) - -def main(): - import getopt, string - try: - opts, args = getopt.getopt(sys.argv[1:], '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(44100) - dev.setsampwidth(2) - dev.setnchannels(1) - if o == '-p': - mkwave(string.atoi(a)) - if not dev: - import audiodev - dev = audiodev.AudioDev() - dev.setoutrate(44100) - dev.setsampwidth(2) - dev.setnchannels(1) - dev.close = dev.stop - dev.writeframesraw = dev.writeframes - if args: - line = string.join(args) - else: - line = sys.stdin.readline() - while line: - mline = morse(line) - 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 - -# 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: # space - pause(dev, DAH + DOT) - pause(dev, DOT) - -def sine(dev, length): - for i in range(length): - dev.writeframesraw(sinewave) - -def pause(dev, length): - for i in range(length): - dev.writeframesraw(nowave) - -if __name__ == '__main__' or sys.argv[0] == __name__: - main() diff --git a/Demo/scripts/mpzpi.py b/Demo/scripts/mpzpi.py deleted file mode 100755 index 93c74aa398..0000000000 --- a/Demo/scripts/mpzpi.py +++ /dev/null @@ -1,34 +0,0 @@ -#! /usr/bin/env python -# Print digits of pi forever. -# -# The algorithm, using Python's 'long' integers ("bignums"), works -# with continued fractions, and was conceived by Lambert Meertens. -# -# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, -# published by Prentice-Hall (UK) Ltd., 1990. - -import sys -from mpz import mpz - -def main(): - mpzone, mpztwo, mpzten = mpz(1), mpz(2), mpz(10) - k, a, b, a1, b1 = mpz(2), mpz(4), mpz(1), mpz(12), mpz(4) - while 1: - # Next approximation - p, q, k = k*k, mpztwo*k+mpzone, k+mpzone - a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 - # Print common digits - d, d1 = a/b, a1/b1 - while d == d1: - output(d) - a, a1 = mpzten*(a%b), mpzten*(a1%b1) - d, d1 = a/b, a1/b1 - -def output(d): - # Use write() to avoid spaces between the digits - # Use int(d) to avoid a trailing L after each digit - sys.stdout.write(`int(d)`) - # Flush so the output is seen immediately - sys.stdout.flush() - -main() diff --git a/Demo/scripts/newslist.doc b/Demo/scripts/newslist.doc deleted file mode 100755 index 87fd9ba27a..0000000000 --- a/Demo/scripts/newslist.doc +++ /dev/null @@ -1,59 +0,0 @@ - NEWSLIST - ======== - A program to assist HTTP browsing of newsgroups - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -WWW browsers such as NCSA Mosaic allow the user to read newsgroup -articles by specifying the group name in a URL eg 'news:comp.answers'. - -To browse through many groups, though, (and there are several thousand -of them) you really need a page or pages containing links to all the -groups. There are some good ones out there, for example, - - http://info.cern.ch/hypertext/DataSources/News/Groups/Overview.html - -is the standard one at CERN, but it only shows the groups available there, -which may be rather different from those available on your machine. - -Newslist is a program which creates a hierarchy of pages for you based -on the groups available from YOUR server. It is written in python - a -splendid interpreted object-oriented language which I suggest you get -right now from the directory /pub/python at ftp.cwi.nl, if you haven't -already got it. - -You should be able to see some sample output by looking at: - http://pelican.cl.cam.ac.uk/newspage/root.html - -Descriptions of newsgroups can be added from a file with one group -per line. eg: - - alt.foo Articles about foo - comp.bar Programming in 'bar' and related languages - -A suitable list detailing most groups can be found at ftp.uu.net in -/uunet-info/newsgroups.gz. - -Make sure you read the information at the beginning of the program source and -configure the variables before running. - -In addition to python, you need: - - An NNTP-based news feed. - A directory in which to put the pages. - -The programming is not very beautiful, but it works! It comes with no -warranty, express or implied, but with the hope that some others may -find it useful. - -Comments, improvements & suggestions welcomed. -Quentin Stafford-Fraser - - ---------------------------------------------------------------------- - Quentin Stafford-Fraser - http://pelican.cl.cam.ac.uk/people/qs101/me.html - - Cambridge University Computer Lab Rank Xerox Cambridge EuroPARC - qs101@cl.cam.ac.uk fraser@europarc.xerox.com - Tel: +44 223 334411 Tel: +44 223 341521 - Fax: +44 223 334679 Fax: +44 223 341510 - ---------------------------------------------------------------------- diff --git a/Demo/scripts/newslist.py b/Demo/scripts/newslist.py deleted file mode 100755 index f78ca30271..0000000000 --- a/Demo/scripts/newslist.py +++ /dev/null @@ -1,366 +0,0 @@ -#! /usr/bin/env python -####################################################################### -# Newslist $Revision$ -# -# Syntax: -# newslist [ -a ] -# -# This is a program to create a directory full of HTML pages -# which between them contain links to all the newsgroups available -# on your server. -# -# The -a option causes a complete list of all groups to be read from -# the server rather than just the ones which have appeared since last -# execution. This recreates the local list from scratch. Use this on -# the first invocation of the program, and from time to time thereafter. -# When new groups are first created they may appear on your server as -# empty groups. By default, empty groups are ignored by the -a option. -# However, these new groups will not be created again, and so will not -# appear in the server's list of 'new groups' at a later date. Hence it -# won't appear until you do a '-a' after some articles have appeared. -# -# I should really keep a list of ignored empty groups and re-check them -# for articles on every run, but I haven't got around to it yet. -# -# This assumes an NNTP news feed. -# -# Feel free to copy, distribute and modify this code for -# non-commercial use. If you make any useful modifications, let me -# know! -# -# (c) Quentin Stafford-Fraser 1994 -# fraser@europarc.xerox.com qs101@cl.cam.ac.uk -# # -####################################################################### -import sys,nntplib, string, marshal, time, os, posix, string - -####################################################################### -# Check these variables before running! # - -# Top directory. -# Filenames which don't start with / are taken as being relative to this. -topdir='/anfs/qsbigdisc/web/html/newspage' - -# The name of your NNTP host -# eg. -# newshost = 'nntp-serv.cl.cam.ac.uk' -# or use following to get the name from the NNTPSERVER environment -# variable: -# newshost = posix.environ['NNTPSERVER'] -newshost = 'nntp-serv.cl.cam.ac.uk' - -# The filename for a local cache of the newsgroup list -treefile = 'grouptree' - -# The filename for descriptions of newsgroups -# I found a suitable one at ftp.uu.net in /uunet-info/newgroups.gz -# You can set this to '' if you don't wish to use one. -descfile = 'newsgroups' - -# The directory in which HTML pages should be created -# eg. -# pagedir = '/usr/local/lib/html/newspage' -# pagedir = 'pages' -pagedir = topdir - -# The html prefix which will refer to this directory -# eg. -# httppref = '/newspage/', -# or leave blank for relative links between pages: (Recommended) -# httppref = '' -httppref = '' - -# The name of the 'root' news page in this directory. -# A .html suffix will be added. -rootpage = 'root' - -# Set skipempty to 0 if you wish to see links to empty groups as well. -# Only affects the -a option. -skipempty = 1 - -# pagelinkicon can contain html to put an icon after links to -# further pages. This helps to make important links stand out. -# Set to '' if not wanted, or '...' is quite a good one. -pagelinkicon='... ' - -# --------------------------------------------------------------------- -# Less important personal preferences: - -# Sublistsize controls the maximum number of items the will appear as -# an indented sub-list before the whole thing is moved onto a different -# page. The smaller this is, the more pages you will have, but the -# shorter each will be. -sublistsize = 4 - -# That should be all. # -####################################################################### - -for dir in os.curdir, os.environ['HOME']: - rcfile = os.path.join(dir, '.newslistrc.py') - if os.path.exists(rcfile): - print rcfile - execfile(rcfile) - break - -from nntplib import NNTP -from stat import * - -rcsrev = '$Revision$' -rcsrev = string.join(filter(lambda s: '$' not in s, string.split(rcsrev))) -desc = {} - -# Make (possibly) relative filenames into absolute ones -treefile = os.path.join(topdir,treefile) -descfile = os.path.join(topdir,descfile) -page = os.path.join(topdir,pagedir) - -# First the bits for creating trees --------------------------- - -# Addtotree creates/augments a tree from a list of group names -def addtotree(tree, groups): - print 'Updating tree...' - for i in groups: - parts = string.splitfields(i,'.') - makeleaf(tree, parts) - -# Makeleaf makes a leaf and the branch leading to it if necessary -def makeleaf(tree,path): - j = path[0] - l = len(path) - - if not tree.has_key(j): - tree[j] = {} - if l == 1: - tree[j]['.'] = '.' - if l > 1: - makeleaf(tree[j],path[1:]) - -# Then the bits for outputting trees as pages ---------------- - -# Createpage creates an HTML file named .html containing links -# to those groups beginning with . - -def createpage(root, tree, p): - filename = os.path.join(pagedir,root+'.html') - if root == rootpage: - detail = '' - else: - detail = ' under ' + root - f = open(filename,'w') - # f.write('Content-Type: text/html\n') - f.write('Newsgroups available' + detail + '\n') - f.write('

Newsgroups available' + detail +'

\n') - f.write('Back to top level

\n') - printtree(f,tree,0,p) - f.write('This page automatically created by \'newslist\' v. '+rcsrev+'.') - f.write(time.ctime(time.time()) + '

') - f.close() - -# Printtree prints the groups as a bulleted list. Groups with -# more than subgroups will be put on a separate page. -# Other sets of subgroups are just indented. - -def printtree(f, tree, indent, p): - global desc - l = len(tree) - - if l > sublistsize and indent>0: - # Create a new page and a link to it - f.write('

  • ') - f.write(p[1:]+'.*') - f.write(''+pagelinkicon+'\n') - createpage(p[1:], tree, p) - return - - kl = tree.keys() - - if l > 1: - kl.sort() - if indent > 0: - # Create a sub-list - f.write('
  • '+p[1:]+'\n
      ') - else: - # Create a main list - f.write('
        ') - indent = indent + 1 - - for i in kl: - if i == '.': - # Output a newsgroup - f.write('
      • '+ p[1:] + ' ') - if desc.has_key(p[1:]): - f.write(' '+desc[p[1:]]+'\n') - else: - f.write('\n') - else: - # Output a hierarchy - printtree(f,tree[i], indent, p+'.'+i) - - if l > 1: - f.write('\n
      ') - -# Reading descriptions file --------------------------------------- - -# This returns an array mapping group name to its description - -def readdesc(descfile): - global desc - - desc = {} - - if descfile == '': - return - - try: - d = open(descfile, 'r') - print 'Reading descriptions...' - except (IOError): - print 'Failed to open description file ' + descfile - return - l = d.readline() - while l != '': - bits = string.split(l) - try: - grp = bits[0] - dsc = string.join(bits[1:]) - if len(dsc)>1: - desc[grp] = dsc - except (IndexError): - pass - l = d.readline() - -# Check that ouput directory exists, ------------------------------ -# and offer to create it if not - -def checkopdir(pagedir): - if not os.path.isdir(pagedir): - print 'Directory '+pagedir+' does not exist.' - print 'Shall I create it for you? (y/n)' - if sys.stdin.readline()[0] == 'y': - try: - os.mkdir(pagedir,0777) - except: - print 'Sorry - failed!' - sys.exit(1) - else: - print 'OK. Exiting.' - sys.exit(1) - -# Read and write current local tree ---------------------------------- - -def readlocallist(treefile): - print 'Reading current local group list...' - tree = {} - try: - treetime = time.localtime(os.stat(treefile)[ST_MTIME]) - except: - print '\n*** Failed to open local group cache '+treefile - print 'If this is the first time you have run newslist, then' - print 'use the -a option to create it.' - sys.exit(1) - treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2]) - try: - dump = open(treefile,'r') - tree = marshal.load(dump) - dump.close() - except (IOError): - print 'Cannot open local group list ' + treefile - return (tree, treedate) - -def writelocallist(treefile, tree): - try: - dump = open(treefile,'w') - groups = marshal.dump(tree,dump) - dump.close() - print 'Saved list to '+treefile+'\n' - except: - print 'Sorry - failed to write to local group cache '+treefile - print 'Does it (or its directory) have the correct permissions?' - sys.exit(1) - -# Return list of all groups on server ----------------------------- - -def getallgroups(server): - print 'Getting list of all groups...' - treedate='010101' - info = server.list()[1] - groups = [] - print 'Processing...' - if skipempty: - print '\nIgnoring following empty groups:' - for i in info: - grpname = string.split(i[0])[0] - if skipempty and string.atoi(i[1]) < string.atoi(i[2]): - print grpname+' ', - else: - groups.append(grpname) - print '\n' - if skipempty: - print '(End of empty groups)' - return groups - -# Return list of new groups on server ----------------------------- - -def getnewgroups(server, treedate): - print 'Getting list of new groups since start of '+treedate+'...', - info = server.newgroups(treedate,'000001')[1] - print 'got '+`len(info)`+'.' - print 'Processing...', - groups = [] - for i in info: - grpname = string.split(i)[0] - groups.append(grpname) - print 'Done' - return groups - -# Now the main program -------------------------------------------- - -def main(): - global desc - - tree={} - - # Check that the output directory exists - checkopdir(pagedir); - - try: - print 'Connecting to '+newshost+'...' - if sys.version[0] == '0': - s = NNTP.init(newshost) - else: - s = NNTP(newshost) - connected = 1 - except (nntplib.error_temp, nntplib.error_perm), x: - print 'Error connecting to host:', x - print 'I\'ll try to use just the local list.' - connected = 0 - - # If -a is specified, read the full list of groups from server - if connected and len(sys.argv) > 1 and sys.argv[1] == '-a': - - groups = getallgroups(s) - - # Otherwise just read the local file and then add - # groups created since local file last modified. - else: - - (tree, treedate) = readlocallist(treefile) - if connected: - groups = getnewgroups(s, treedate) - - if connected: - addtotree(tree, groups) - writelocallist(treefile,tree) - - # Read group descriptions - readdesc(descfile) - - print 'Creating pages...' - createpage(rootpage, tree, '') - print 'Done' - - -main() - -# That's all folks -###################################################################### diff --git a/Demo/scripts/pi.py b/Demo/scripts/pi.py deleted file mode 100755 index d6337238a8..0000000000 --- a/Demo/scripts/pi.py +++ /dev/null @@ -1,33 +0,0 @@ -#! /usr/bin/env python - -# Print digits of pi forever. -# -# The algorithm, using Python's 'long' integers ("bignums"), works -# with continued fractions, and was conceived by Lambert Meertens. -# -# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton, -# published by Prentice-Hall (UK) Ltd., 1990. - -import sys - -def main(): - k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L - while 1: - # Next approximation - p, q, k = k*k, 2L*k+1L, k+1L - a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 - # Print common digits - d, d1 = a/b, a1/b1 - while d == d1: - output(d) - a, a1 = 10L*(a%b), 10L*(a1%b1) - d, d1 = a/b, a1/b1 - -def output(d): - # Use write() to avoid spaces between the digits - # Use str() to avoid the 'L' - sys.stdout.write(str(d)) - # Flush so the output is seen immediately - sys.stdout.flush() - -main() diff --git a/Demo/scripts/pp.py b/Demo/scripts/pp.py deleted file mode 100755 index 24960466e4..0000000000 --- a/Demo/scripts/pp.py +++ /dev/null @@ -1,138 +0,0 @@ -#! /usr/bin/env python - -# Emulate some Perl command line options. -# Usage: pp [-a] [-c] [-d] [-e scriptline] [-F fieldsep] [-n] [-p] [file] ... -# Where the options mean the following: -# -a : together with -n or -p, splits each line into list F -# -c : check syntax only, do not execute any code -# -d : run the script under the debugger, pdb -# -e scriptline : gives one line of the Python script; may be repeated -# -F fieldsep : sets the field separator for the -a option [not in Perl] -# -n : runs the script for each line of input -# -p : prints the line after the script has run -# When no script lines have been passed, the first file argument -# contains the script. With -n or -p, the remaining arguments are -# read as input to the script, line by line. If a file is '-' -# or missing, standard input is read. - -# XXX To do: -# - add -i extension option (change files in place) -# - make a single loop over the files and lines (changes effect of 'break')? -# - add an option to specify the record separator -# - except for -n/-p, run directly from the file if at all possible - -import sys -import string -import getopt - -FS = '' -SCRIPT = [] -AFLAG = 0 -CFLAG = 0 -DFLAG = 0 -NFLAG = 0 -PFLAG = 0 - -try: - optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np') -except getopt.error, msg: - sys.stderr.write(sys.argv[0] + ': ' + msg + '\n') - sys.exit(2) - -for option, optarg in optlist: - if option == '-a': - AFLAG = 1 - elif option == '-c': - CFLAG = 1 - elif option == '-d': - DFLAG = 1 - elif option == '-e': - for line in string.splitfields(optarg, '\n'): - SCRIPT.append(line) - elif option == '-F': - FS = optarg - elif option == '-n': - NFLAG = 1 - PFLAG = 0 - elif option == '-p': - NFLAG = 1 - PFLAG = 1 - else: - print option, 'not recognized???' - -if not ARGS: ARGS.append('-') - -if not SCRIPT: - if ARGS[0] == '-': - fp = sys.stdin - else: - fp = open(ARGS[0], 'r') - while 1: - line = fp.readline() - if not line: break - SCRIPT.append(line[:-1]) - del fp - del ARGS[0] - if not ARGS: ARGS.append('-') - -if CFLAG: - prologue = ['if 0:'] - epilogue = [] -elif NFLAG: - # Note that it is on purpose that AFLAG and PFLAG are - # tested dynamically each time through the loop - prologue = [ \ - 'LINECOUNT = 0', \ - 'for FILE in ARGS:', \ - ' \tif FILE == \'-\':', \ - ' \t \tFP = sys.stdin', \ - ' \telse:', \ - ' \t \tFP = open(FILE, \'r\')', \ - ' \tLINENO = 0', \ - ' \twhile 1:', \ - ' \t \tLINE = FP.readline()', \ - ' \t \tif not LINE: break', \ - ' \t \tLINENO = LINENO + 1', \ - ' \t \tLINECOUNT = LINECOUNT + 1', \ - ' \t \tL = LINE[:-1]', \ - ' \t \taflag = AFLAG', \ - ' \t \tif aflag:', \ - ' \t \t \tif FS: F = string.splitfields(L, FS)', \ - ' \t \t \telse: F = string.split(L)' \ - ] - epilogue = [ \ - ' \t \tif not PFLAG: continue', \ - ' \t \tif aflag:', \ - ' \t \t \tif FS: print string.joinfields(F, FS)', \ - ' \t \t \telse: print string.join(F)', \ - ' \t \telse: print L', \ - ] -else: - prologue = ['if 1:'] - epilogue = [] - -# Note that we indent using tabs only, so that any indentation style -# used in 'command' will come out right after re-indentation. - -program = string.joinfields(prologue, '\n') + '\n' -for line in SCRIPT: - program = program + (' \t \t' + line + '\n') -program = program + (string.joinfields(epilogue, '\n') + '\n') - -import tempfile -tfn = tempfile.mktemp() -try: - fp = open(tfn, 'w') - fp.write(program) - fp.close() - if DFLAG: - import pdb - pdb.run('execfile(' + `tfn` + ')') - else: - execfile(tfn) -finally: - import os - try: - os.unlink(tfn) - except: - pass diff --git a/Demo/scripts/primes.py b/Demo/scripts/primes.py deleted file mode 100755 index 477c57bda9..0000000000 --- a/Demo/scripts/primes.py +++ /dev/null @@ -1,26 +0,0 @@ -#! /usr/bin/env python - -# Print prime numbers in a given range - -def main(): - import sys - min, max = 2, 0x7fffffff - if sys.argv[1:]: - min = int(eval(sys.argv[1])) - if sys.argv[2:]: - max = int(eval(sys.argv[2])) - primes(min, max) - -def primes(min, max): - if 2 >= min: print 2 - primes = [2] - i = 3 - while i <= max: - for p in primes: - if i%p == 0 or p*p > i: break - if i%p <> 0: - primes.append(i) - if i >= min: print i - i = i+2 - -main() diff --git a/Demo/scripts/queens.py b/Demo/scripts/queens.py deleted file mode 100755 index 74756be7d8..0000000000 --- a/Demo/scripts/queens.py +++ /dev/null @@ -1,85 +0,0 @@ -#! /usr/bin/env python - -"""N queens problem. - -The (well-known) problem is due to Niklaus Wirth. - -This solution is inspired by Dijkstra (Structured Programming). It is -a classic recursive backtracking approach. - -""" - -N = 8 # Default; command line overrides - -class Queens: - - def __init__(self, n=N): - self.n = n - self.reset() - - def reset(self): - n = self.n - self.y = [None]*n # Where is the queen in column x - self.row = [0]*n # Is row[y] safe? - self.up = [0] * (2*n-1) # Is upward diagonal[x-y] safe? - self.down = [0] * (2*n-1) # Is downward diagonal[x+y] safe? - self.nfound = 0 # Instrumentation - - def solve(self, x=0): # Recursive solver - for y in range(self.n): - if self.safe(x, y): - self.place(x, y) - if x+1 == self.n: - self.display() - else: - self.solve(x+1) - self.remove(x, y) - - def safe(self, x, y): - return not self.row[y] and not self.up[x-y] and not self.down[x+y] - - def place(self, x, y): - self.y[x] = y - self.row[y] = 1 - self.up[x-y] = 1 - self.down[x+y] = 1 - - def remove(self, x, y): - self.y[x] = None - self.row[y] = 0 - self.up[x-y] = 0 - self.down[x+y] = 0 - - silent = 0 # If set, count solutions only - - def display(self): - self.nfound = self.nfound + 1 - if self.silent: - return - print '+-' + '--'*self.n + '+' - for y in range(self.n-1, -1, -1): - print '|', - for x in range(self.n): - if self.y[x] == y: - print "Q", - else: - print ".", - print '|' - print '+-' + '--'*self.n + '+' - -def main(): - import sys - silent = 0 - n = N - if sys.argv[1:2] == ['-n']: - silent = 1 - del sys.argv[1] - if sys.argv[1:]: - n = int(sys.argv[1]) - q = Queens(n) - q.silent = silent - q.solve() - print "Found", q.nfound, "solutions." - -if __name__ == "__main__": - main() diff --git a/Demo/scripts/script.py b/Demo/scripts/script.py deleted file mode 100755 index cbad3679d1..0000000000 --- a/Demo/scripts/script.py +++ /dev/null @@ -1,33 +0,0 @@ -#! /usr/bin/env python -# script.py -- Make typescript of terminal session. -# Usage: -# -a Append to typescript. -# -p Use Python as shell. -# Author: Steen Lumholt. - - -import os, time, sys -import pty - -def read(fd): - data = os.read(fd, 1024) - file.write(data) - return data - -shell = 'sh' -filename = 'typescript' -mode = 'w' -if os.environ.has_key('SHELL'): - shell = os.environ['SHELL'] -if '-a' in sys.argv: - mode = 'a' -if '-p' in sys.argv: - shell = 'python' - -file = open(filename, mode) - -sys.stdout.write('Script started, file is %s\n' % filename) -file.write('Script started on %s\n' % time.ctime(time.time())) -pty.spawn(shell, read) -file.write('Script done on %s\n' % time.ctime(time.time())) -sys.stdout.write('Script done, file is %s\n' % filename) diff --git a/Demo/scripts/unbirthday.py b/Demo/scripts/unbirthday.py deleted file mode 100755 index e3b7be73f0..0000000000 --- a/Demo/scripts/unbirthday.py +++ /dev/null @@ -1,106 +0,0 @@ -#! /usr/bin/env python - -# Calculate your unbirthday count (see Alice in Wonderland). -# This is defined as the number of days from your birth until today -# that weren't your birthday. (The day you were born is not counted). -# Leap years make it interesting. - -import sys -import time -import calendar - -def main(): - # Note that the range checks below also check for bad types, - # e.g. 3.14 or (). However syntactically invalid replies - # will raise an exception. - if sys.argv[1:]: - year = int(sys.argv[1]) - else: - year = int(raw_input('In which year were you born? ')) - if 0<=year<100: - print "I'll assume that by", year, - year = year + 1900 - print 'you mean', year, 'and not the early Christian era' - elif not (1850<=year<=2002): - print "It's hard to believe you were born in", year - return - # - if sys.argv[2:]: - month = int(sys.argv[2]) - else: - month = int(raw_input('And in which month? (1-12) ')) - if not (1<=month<=12): - print 'There is no month numbered', month - return - # - if sys.argv[3:]: - day = int(sys.argv[3]) - else: - day = int(raw_input('And on what day of that month? (1-31) ')) - if month == 2 and calendar.isleap(year): - maxday = 29 - else: - maxday = calendar.mdays[month] - if not (1<=day<=maxday): - print 'There are no', day, 'days in that month!' - return - # - bdaytuple = (year, month, day) - bdaydate = mkdate(bdaytuple) - print 'You were born on', format(bdaytuple) - # - todaytuple = time.localtime()[:3] - todaydate = mkdate(todaytuple) - print 'Today is', format(todaytuple) - # - if bdaytuple > todaytuple: - print 'You are a time traveler. Go back to the future!' - return - # - if bdaytuple == todaytuple: - print 'You were born today. Have a nice life!' - return - # - days = todaydate - bdaydate - print 'You have lived', days, 'days' - # - age = 0 - for y in range(year, todaytuple[0] + 1): - if bdaytuple < (y, month, day) <= todaytuple: - age = age + 1 - # - print 'You are', age, 'years old' - # - if todaytuple[1:] == bdaytuple[1:]: - print 'Congratulations! Today is your', nth(age), 'birthday' - print 'Yesterday was your', - else: - print 'Today is your', - print nth(days - age), 'unbirthday' - -def format((year, month, day)): - return '%d %s %d' % (day, calendar.month_name[month], year) - -def nth(n): - if n == 1: return '1st' - if n == 2: return '2nd' - if n == 3: return '3rd' - return '%dth' % n - -def mkdate((year, month, day)): - # Januari 1st, in 0 A.D. is arbitrarily defined to be day 1, - # even though that day never actually existed and the calendar - # was different then... - days = year*365 # years, roughly - days = days + (year+3)/4 # plus leap years, roughly - days = days - (year+99)/100 # minus non-leap years every century - days = days + (year+399)/400 # plus leap years every 4 centirues - for i in range(1, month): - if i == 2 and calendar.isleap(year): - days = days + 29 - else: - days = days + calendar.mdays[i] - days = days + day - return days - -main() diff --git a/Demo/scripts/update.py b/Demo/scripts/update.py deleted file mode 100755 index 2db65dcb29..0000000000 --- a/Demo/scripts/update.py +++ /dev/null @@ -1,91 +0,0 @@ -#! /usr/bin/env python - -# Update a bunch of files according to a script. -# The input file contains lines of the form ::, -# meaning that the given line of the given file is to be replaced -# by the given text. This is useful for performing global substitutions -# on grep output: - -import os -import sys -import regex - -pat = '^\([^: \t\n]+\):\([1-9][0-9]*\):' -prog = regex.compile(pat) - -class FileObj: - def __init__(self, filename): - self.filename = filename - self.changed = 0 - try: - self.lines = open(filename, 'r').readlines() - except IOError, msg: - print '*** Can\'t open "%s":' % filename, msg - self.lines = None - return - print 'diffing', self.filename - - def finish(self): - if not self.changed: - print 'no changes to', self.filename - return - try: - os.rename(self.filename, self.filename + '~') - fp = open(self.filename, 'w') - except (os.error, IOError), msg: - print '*** Can\'t rewrite "%s":' % self.filename, msg - return - print 'writing', self.filename - for line in self.lines: - fp.write(line) - fp.close() - self.changed = 0 - - def process(self, lineno, rest): - if self.lines is None: - print '(not processed): %s:%s:%s' % ( - self.filename, lineno, rest), - return - i = eval(lineno) - 1 - if not 0 <= i < len(self.lines): - print '*** Line number out of range: %s:%s:%s' % ( - self.filename, lineno, rest), - return - if self.lines[i] == rest: - print '(no change): %s:%s:%s' % ( - self.filename, lineno, rest), - return - if not self.changed: - self.changed = 1 - print '%sc%s' % (lineno, lineno) - print '<', self.lines[i], - print '---' - self.lines[i] = rest - print '>', self.lines[i], - -def main(): - if sys.argv[1:]: - try: - fp = open(sys.argv[1], 'r') - except IOError, msg: - print 'Can\'t open "%s":' % sys.argv[1], msg - sys.exit(1) - else: - fp = sys.stdin - curfile = None - while 1: - line = fp.readline() - if not line: - if curfile: curfile.finish() - break - n = prog.match(line) - if n < 0: - print 'Funny line:', line, - continue - filename, lineno = prog.group(1, 2) - if not curfile or filename <> curfile.filename: - if curfile: curfile.finish() - curfile = FileObj(filename) - curfile.process(lineno, line[n:]) - -main() diff --git a/Demo/scripts/wh.py b/Demo/scripts/wh.py deleted file mode 100755 index b9b09efa6a..0000000000 --- a/Demo/scripts/wh.py +++ /dev/null @@ -1,2 +0,0 @@ -# This is here so I can use 'wh' instead of 'which' in '~/bin/generic_python' -import which diff --git a/Demo/sgi/README b/Demo/sgi/README deleted file mode 100644 index 3ef80d2dbd..0000000000 --- a/Demo/sgi/README +++ /dev/null @@ -1,22 +0,0 @@ -Demonstrations of Python that use various features of the Silicon -Graphics IRIS machines. - -al Demonstrations of the audio capabilities of the - Indigo. Require the built-in module 'al'. One program - also needs the build-in module 'fl' (the FORMS - library by Mark Overmars.) - -cd Demonstrations of the CD-ROM player's audio interface, - built-in module 'cd'. - -flp Demonstrations of using the 'flp' standard module, - which enables you to quickly create forms using the - 'fl' built-in module (available if you use the FORMS - library by Mark Overmars). - -gl Demonstrations of the Graphics Library (GL). - Require the built-in module 'gl'. - -sv Demonstrations of the Indigo Video module. - Requires the built-in module 'sv'. See also the - following directory. diff --git a/Demo/sgi/al/.cvsignore b/Demo/sgi/al/.cvsignore deleted file mode 100644 index 11df8b01bb..0000000000 --- a/Demo/sgi/al/.cvsignore +++ /dev/null @@ -1 +0,0 @@ -cmpaf_form.fdc diff --git a/Demo/sgi/al/README b/Demo/sgi/al/README deleted file mode 100644 index fba67b7ddf..0000000000 --- a/Demo/sgi/al/README +++ /dev/null @@ -1,15 +0,0 @@ -This directory contains programs using the "al" interface, which gives -access to the most important parts of the SGI Audio Library for the -Indigo and 4D/35. - -alwatch.py Watch changes in device settings -broadcast.py Broadcast audio using UDP packets -cmpaf.py Compare different audio compression schemes (uses fl) -intercom.py 2-way communication with another host (uses fl) -playaiff.py Play an AIFF file (as output by recordaiff) -playback.py Play raw audio data read from stdin -playold.py Play an audio file recorded by the old 4D/25 audio -radio.py Listen to UDP packets sent by broadcast.py -rec_play.py Repeatedly record and play back a sample -record.py Record raw audio data to stdout -unicast.py Like broadcast but sends to one host diff --git a/Demo/sgi/al/alwatch.py b/Demo/sgi/al/alwatch.py deleted file mode 100755 index da747d4d81..0000000000 --- a/Demo/sgi/al/alwatch.py +++ /dev/null @@ -1,33 +0,0 @@ -import time -import al, AL -import string - -dev = AL.DEFAULT_DEVICE - -source_name = ['line', 'microphone', 'digital'] - -params = al.queryparams(dev) -for i in range(1, len(params), 2): - params[i] = -1 -while 1: - time.sleep(0.1) - old = params[:] - al.getparams(dev, params) - if params <> old: - for i in range(0, len(params), 2): - if params[i+1] <> old[i+1]: - name = al.getname(dev, params[i]) - if params[i] == AL.INPUT_SOURCE: - if 0 <= old[i+1] < len(source_name): - oldval = source_name[old[i+1]] - else: - oldval = '' - newval = source_name[params[i+1]] - else: - oldval = `old[i+1]` - newval = `params[i+1]` - print string.ljust(name, 25), - print '(' + string.rjust(oldval, 10) + ')', - print '-->', - print string.rjust(newval, 10) - print diff --git a/Demo/sgi/al/broadcast.py b/Demo/sgi/al/broadcast.py deleted file mode 100755 index 9d88dac5f6..0000000000 --- a/Demo/sgi/al/broadcast.py +++ /dev/null @@ -1,27 +0,0 @@ -#! /usr/bin/env python - -# broadcast [port] -# -# Broadcast audio input on the network as UDP packets; -# they can be received on any SGI machine with "radio.py". -# This uses the input sampling rate, input source etc. set by apanel. -# It uses the default sample width and #channels (16 bit/sample stereo). -# (This is 192,000 Bytes at a sampling speed of 48 kHz, or ~137 -# packets/second -- use with caution!!!) - -import sys, al -from socket import * - -port = 5555 -if sys.argv[1:]: port = eval(sys.argv[1]) - -s = socket(AF_INET, SOCK_DGRAM) -s.allowbroadcast(1) - -p = al.openport('broadcast', 'r') - -address = '', port -while 1: - # 700 samples equals 1400 bytes, or about the max packet size! - data = p.readsamps(700) - s.sendto(data, address) diff --git a/Demo/sgi/al/cmpaf.py b/Demo/sgi/al/cmpaf.py deleted file mode 100755 index 6b91e30fd6..0000000000 --- a/Demo/sgi/al/cmpaf.py +++ /dev/null @@ -1,64 +0,0 @@ -# Compare different audio compression schemes. -# -# This copies mono audio data from the input port to the output port, -# and puts up a window with 4 toggle buttons: -# -# uLAW : convert the data to uLAW and back -# ADPCM : convert the data to ADPCM and back -# Difference : make only the difference between the converted and the -# original data audible -# Exit : quit from the program - -import fl -import FL -import flp -import al -import AL -import audioop -import sys - -class Cmpaf: - def __init__(self): - parsetree = flp.parse_form('cmpaf_form','form') - flp.create_full_form(self, parsetree) - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(1800) - self.iport = al.openport('cmpaf','r', c) - self.oport = al.openport('cmpaf','w', c) - self.do_adpcm = self.do_ulaw = self.do_diff = 0 - self.acstate = None - self.form.show_form(FL.PLACE_SIZE, 1, 'compare audio formats') - - def run(self): - while 1: - olddata = data = self.iport.readsamps(600) - if self.do_ulaw: - data = audioop.lin2ulaw(data, 2) - data = audioop.ulaw2lin(data, 2) - if self.do_adpcm: - data, nacstate = audioop.lin2adpcm(data, 2, \ - self.acstate) - data, dummy = audioop.adpcm2lin(data, 2, \ - self.acstate) - self.acstate = nacstate - if self.do_diff: - olddata = audioop.mul(olddata, 2, -1) - data = audioop.add(olddata, data, 2) - self.oport.writesamps(data) - fl.check_forms() - - def cb_exit(self, *args): - sys.exit(0) - - def cb_adpcm(self, obj, val): - self.do_adpcm = obj.get_button() - - def cb_ulaw(self, obj, val): - self.do_ulaw = obj.get_button() - - def cb_diff(self, obj, val): - self.do_diff = obj.get_button() - -cmpaf = Cmpaf() -cmpaf.run() diff --git a/Demo/sgi/al/cmpaf_form.fd b/Demo/sgi/al/cmpaf_form.fd deleted file mode 100755 index 6667405133..0000000000 --- a/Demo/sgi/al/cmpaf_form.fd +++ /dev/null @@ -1,90 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 1 - -=============== FORM =============== -Name: form -Width: 230.000000 -Height: 80.000000 -Number of Objects: 5 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 230.000000 80.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 12 -type: 1 -box: 10.000000 40.000000 100.000000 30.000000 -boxtype: 1 -colors: 39 3 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: uLAW -name: ulawbutton -callback: cb_ulaw -argument: 0 - --------------------- -class: 12 -type: 1 -box: 10.000000 10.000000 100.000000 30.000000 -boxtype: 1 -colors: 39 3 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: ADPCM -name: adpcm_button -callback: cb_adpcm -argument: 0 - --------------------- -class: 11 -type: 0 -box: 170.000000 10.000000 50.000000 20.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: EXIT -name: exit_button -callback: cb_exit -argument: 0 - --------------------- -class: 12 -type: 1 -box: 120.000000 40.000000 100.000000 30.000000 -boxtype: 1 -colors: 39 3 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Difference -name: diffbutton -callback: cb_diff -argument: 0 - -============================== -create_the_forms diff --git a/Demo/sgi/al/intercom.py b/Demo/sgi/al/intercom.py deleted file mode 100755 index fd983d39ad..0000000000 --- a/Demo/sgi/al/intercom.py +++ /dev/null @@ -1,212 +0,0 @@ -# intercom -- use mike and headset to *talk* to a person on another host. -# For SGI 4D/35 or Indigo running IRIX 4.0. -# Uses 16 bit sampling at 16000 samples/sec, or 32000 bytes/sec, -# tranmitted in 32 1000-byte UDP packets. (In each direction!) -# -# usage: -# intercom hostname - start talking to person on other host -# intercom -r hostname - called remotely to do the setup - -from names import * -import sys, time, posix, gl, fl, FL, al, AL, getopt, rand -from socket import * - -# UDP port numbers used (one for each direction!) -PORT1 = 51042 -PORT2 = PORT1+1 - -# Figure out the user name -try: - user = posix.environ['LOGNAME'] -except: - user = posix.environ['USER'] - -# Debug flags (Implemented as a list; non-empty means debugging is on) -debug = [] - -def main(): - remote = 0 - opts, args = getopt.getopt(sys.argv[1:], 'rd') - for opt, arg in opts: - if opt == '-r': remote = 1 - elif opt == '-d': debug.append(opt) - if len(args) <> 1: - msg = 'usage: intercom [-d] [-r] hostname' - msg = msg + ' (-r is for internal use only!)\n' - sys.stderr.write(msg) - sys.exit(2) - if remote: - server(args[0]) - else: - client(args[0]) - -def client(hostname): - print 'client starting' - cmd = 'rsh ' + hostname + ' "cd ' + AUDIODIR - cmd = cmd + '; DISPLAY=:0; export DISPLAY' - cmd = cmd + '; ' + PYTHON + ' intercom.py -r ' - for flag in debug: cmd = cmd + flag + ' ' - cmd = cmd + gethostname() - cmd = cmd + '"' - if debug: print cmd - pipe = posix.popen(cmd, 'r') - ack = 0 - nak = 0 - while 1: - line = pipe.readline() - if not line: break - sys.stdout.write('remote: ' + line) - if line == 'NAK\n': - nak = 1 - break - elif line == 'ACK\n': - ack = 1 - break - if nak: - print 'Remote user doesn\'t want to talk to you.' - return - if not ack: - print 'No acknowledgement (remote side crashed?).' - return - # - print 'Ready...' - # - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', PORT2) - # - otheraddr = gethostbyname(hostname), PORT1 - try: - try: - ioloop(s, otheraddr) - except KeyboardInterrupt: - log('client got intr') - except error: - log('client got error') - finally: - s.sendto('', otheraddr) - log('client finished sending empty packet to server') - # - log('client exit') - print 'Done.' - -def server(hostname): - print 'server starting' - sys.stdout.flush() - # - if not remotedialog(): - print 'NAK' - return - # - print 'ACK' - # - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', PORT1) - # - # Close std{in,out,err} so rsh will exit; reopen them as dummies - # - sys.stdin.close() - sys.stdin = open('/dev/null', 'r') - sys.stdout.close() - sys.stdout = open('/dev/null', 'w') - sys.stderr.close() - if debug: - sys.stderr = open('/tmp/intercom.err', 'a') - else: - sys.stderr = open('/dev/null', 'w') - # - ioloop(s, (gethostbyname(hostname), PORT2)) - log('server exit') - sys.exit(0) - -def remotedialog(): - gl.foreground() - gl.ringbell() - m1 = user + ' wants to talk to you over the audio channel.' - m2 = 'If it\'s OK, put on your headset and click Yes.' - m3 = 'If you\'re too busy, click No.' - return fl.show_question(m1, m2, m3) - -def ioloop(s, otheraddr): - # - dev = AL.DEFAULT_DEVICE - params = al.queryparams(dev) - al.getparams(dev, params) - time.sleep(1) - saveparams = params[:] - for i in range(0, len(params), 2): - if params[i] in (AL.INPUT_RATE, AL.OUTPUT_RATE): - params[i+1] = AL.RATE_16000 - elif params[i] == AL.INPUT_SOURCE: - params[i+1] = AL.INPUT_MIC - try: - al.setparams(dev, params) - ioloop1(s, otheraddr) - finally: - al.setparams(dev, saveparams) - -def ioloop1(s, otheraddr): - # - # Watch out! data is in bytes, but the port counts in samples, - # which are two bytes each (for 16-bit samples). - # Luckily, we use mono, else it would be worse (2 samples/frame...) - # - SAMPSPERBUF = 500 - BYTESPERSAMP = 2 # AL.SAMPLE_16 - BUFSIZE = BYTESPERSAMP*SAMPSPERBUF - QSIZE = 4*SAMPSPERBUF - # - config = al.newconfig() - config.setqueuesize(QSIZE) - config.setwidth(AL.SAMPLE_16) - config.setchannels(AL.MONO) - # - pid = posix.fork() - if pid: - # Parent -- speaker/headphones handler - log('parent started') - spkr = al.openport('spkr', 'w', config) - while 1: - data = s.recv(BUFSIZE) - if len(data) == 0: - # EOF packet - log('parent got empty packet; killing child') - posix.kill(pid, 15) - return - # Discard whole packet if we are too much behind - if spkr.getfillable() > len(data) / BYTESPERSAMP: - if len(debug) >= 2: - log('parent Q full; dropping packet') - spkr.writesamps(data) - else: - # Child -- microphone handler - log('child started') - try: - try: - mike = al.openport('mike', 'r', config) - # Sleep a while to let the other side get started - time.sleep(1) - # Drain the queue before starting to read - data = mike.readsamps(mike.getfilled()) - # Loop, sending packets from the mike to the net - while 1: - data = mike.readsamps(SAMPSPERBUF) - s.sendto(data, otheraddr) - except KeyboardInterrupt: - log('child got interrupt; exiting') - posix._exit(0) - except error: - log('child got error; exiting') - posix._exit(1) - finally: - log('child got unexpected error; leaving w/ traceback') - -def log(msg): - if not debug: return - if type(msg) <> type(''): - msg = `msg` - - f = open('/tmp/intercom.log', 'a') - f.write(`sys.argv` + ' ' + `posix.getpid()` + ': ' + msg + '\n') - f.close() - -main() diff --git a/Demo/sgi/al/listen.py b/Demo/sgi/al/listen.py deleted file mode 100755 index 83f850a657..0000000000 --- a/Demo/sgi/al/listen.py +++ /dev/null @@ -1,34 +0,0 @@ -# Listen to the input on host argv[1]. - -import sys, al, AL, posix - -BUFSIZE = 2000 -QSIZE = 4000 - -def main(): - if len(sys.argv) <> 2: - sys.stderr.write('usage: ' + sys.argv[0] + ' hostname\n') - sys.exit(2) - hostname = sys.argv[1] - cmd = 'exec rsh 'FORM': - raise aiff.Error, 'FORM chunk expected at start of file' - aiff.read_form_chunk(f) - while 1: - try: - type, size = aiff.read_chunk_header(f) - except EOFError: - break - if v: print 'header:', `type`, size - if type == 'COMM': - nchannels, nsampframes, sampwidth, samprate = \ - aiff.read_comm_chunk(f) - if v: print nchannels, nsampframes, sampwidth, samprate - elif type == 'SSND': - offset, blocksize = aiff.read_ssnd_chunk(f) - if v: print offset, blocksize - data = f.read(size-8) - if size%2: void = f.read(1) - p = makeport(nchannels, sampwidth, samprate) - play(p, data, offset, blocksize) - elif type in aiff.skiplist: - aiff.skip_chunk(f, size) - else: - raise aiff.Error, 'bad chunk type ' + type - -def makeport(nchannels, sampwidth, samprate): - c = al.newconfig() - c.setchannels(nchannels) - c.setwidth(sampwidth/8) - # can't set the rate... - p = al.openport('', 'w', c) - return p - -def play(p, data, offset, blocksize): - data = data[offset:] - p.writesamps(data) - while p.getfilled() > 0: time.sleep(0.01) - -main() diff --git a/Demo/sgi/al/playback.py b/Demo/sgi/al/playback.py deleted file mode 100755 index 967f746cf8..0000000000 --- a/Demo/sgi/al/playback.py +++ /dev/null @@ -1,23 +0,0 @@ -# Read mono 16bit samples from stdin and write them to the audio device. -# Assume the sampling rate is compatible. -# Use a small queue size to minimize delays. - -import al, sys -import AL - -BUFSIZE = 2000 -QSIZE = 4000 - -def main(): - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(QSIZE) - p = al.openport('', 'w', c) - while 1: - data = sys.stdin.read(BUFSIZE) - p.writesamps(data) - -try: - main() -except KeyboardInterrupt: - sys.exit(1) diff --git a/Demo/sgi/al/playold.py b/Demo/sgi/al/playold.py deleted file mode 100755 index 9792c168c5..0000000000 --- a/Demo/sgi/al/playold.py +++ /dev/null @@ -1,51 +0,0 @@ -# Play old style sound files (Guido's private format) - -import al, sys, time -import AL - -BUFSIZE = 8000 - -def main(): - if len(sys.argv) < 2: - f = sys.stdin - filename = sys.argv[0] - else: - if len(sys.argv) <> 2: - sys.stderr.write('usage: ' + \ - sys.argv[0] + ' filename\n') - sys.exit(2) - filename = sys.argv[1] - f = open(filename, 'r') - # - magic = f.read(4) - extra = '' - if magic == '0008': - rate = 8000 - elif magic == '0016': - rate = 16000 - elif magic == '0032': - rate = 32000 - else: - sys.stderr.write('no magic header; assuming 8k samples/sec.\n') - rate = 8000 - extra = magic - # - pv = [AL.OUTPUT_RATE, rate] - al.setparams(AL.DEFAULT_DEVICE, pv) - c = al.newconfig() - c.setchannels(AL.MONO) - c.setwidth(AL.SAMPLE_8) - port = al.openport(filename, 'w', c) - if extra: - port.writesamps(extra) - while 1: - buf = f.read(BUFSIZE) - if not buf: break - port.writesamps(buf) - while port.getfilled() > 0: - time.sleep(0.1) - -try: - main() -except KeyboardInterrupt: - sys.exit(1) diff --git a/Demo/sgi/al/radio.py b/Demo/sgi/al/radio.py deleted file mode 100755 index b9d30d2fa8..0000000000 --- a/Demo/sgi/al/radio.py +++ /dev/null @@ -1,21 +0,0 @@ -#! /usr/bin/env python - -# radio [port] -# -# Receive audio packets broadcast by "broadcast.py" on another SGI machine. -# Use apanel to set the output sampling rate to match that of the broadcast. - -import sys, al -from socket import * - -port = 5555 -if sys.argv[1:]: port = eval(sys.argv[1]) - -s = socket(AF_INET, SOCK_DGRAM) -s.bind('', port) - -p = al.openport('radio', 'w') - -while 1: - data = s.recv(1400) - p.writesamps(data) diff --git a/Demo/sgi/al/rec_play.py b/Demo/sgi/al/rec_play.py deleted file mode 100755 index 693c96e453..0000000000 --- a/Demo/sgi/al/rec_play.py +++ /dev/null @@ -1,28 +0,0 @@ -# -# records an AIFF sample and plays it -# infinity number of times. -# - -import time -import al - -def recordit () : - p = al.openport('hello', 'r') - print 'recording...' - buf = p.readsamps(500000) - print 'done.' - p.closeport() - - return buf - -def playit (buf) : - p = al.openport('hello', 'w') - print 'playing...' - p.writesamps(buf) - while p.getfilled() > 0: - time.sleep(0.01) - print 'done.' - p.closeport() - -while 1 : - playit (recordit ()) diff --git a/Demo/sgi/al/record.py b/Demo/sgi/al/record.py deleted file mode 100755 index e5c0f5b2d8..0000000000 --- a/Demo/sgi/al/record.py +++ /dev/null @@ -1,23 +0,0 @@ -# Record mono 16bits samples from the audio device and send them to stdout. -# Assume the sampling rate is compatible. -# Use a small queue size to minimize delays. - -import al, sys -import AL - -BUFSIZE = 2000 -QSIZE = 4000 - -def main(): - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(QSIZE) - p = al.openport('', 'r', c) - while 1: - data = p.readsamps(BUFSIZE) - sys.stdout.write(data) - -try: - main() -except KeyboardInterrupt: - sys.exit(1) diff --git a/Demo/sgi/al/unicast.py b/Demo/sgi/al/unicast.py deleted file mode 100755 index 0d537b180f..0000000000 --- a/Demo/sgi/al/unicast.py +++ /dev/null @@ -1,26 +0,0 @@ -#! /usr/bin/env python - -# unicast host [port] -# -# Similar to "broadcast.py" but sends to a specific host only; -# use "radio.py" on the designated host to receive. -# This is less stressful on other hosts on the same ethernet segment -# if you need to send to one host only. - -import sys, al -from socket import * - -host = sys.argv[1] - -port = 5555 -if sys.argv[2:]: port = eval(sys.argv[1]) - -s = socket(AF_INET, SOCK_DGRAM) - -p = al.openport('unicast', 'r') - -address = host, port -while 1: - # 700 samples equals 1400 bytes, or about the max packet size! - data = p.readsamps(700) - s.sendto(data, address) diff --git a/Demo/sgi/al/x.py b/Demo/sgi/al/x.py deleted file mode 100755 index ecc12d8198..0000000000 --- a/Demo/sgi/al/x.py +++ /dev/null @@ -1,12 +0,0 @@ -# Demonstrate that rsh exits when the remote end closes std{in,out,err}. -# rsh voorn exec /ufs/guido/bin/sgi/python /ufs/guido/mm/demo/audio/x.py - -print 'hoi!' -import sys -sys.stdin.close() -sys.stdout.close() -sys.stderr.close() -import time -time.sleep(5) -sys.stdout = open('@', 'w') -sys.stdout.write('Hello\n') diff --git a/Demo/sgi/audio/README b/Demo/sgi/audio/README deleted file mode 100644 index 02a3701f92..0000000000 --- a/Demo/sgi/audio/README +++ /dev/null @@ -1,8 +0,0 @@ -Programs that demonstrate the use of the audio device on the SGI 4D/25. -These require the built-in module 'audio'. - -XXX This hardware is already obsolete; see ../al for examples of audio -XXX on the Indigo and 4D/35. - -play Read a sound sample from a file and play it through the - speaker. Options to set volume, sampling rate etc. diff --git a/Demo/sgi/audio/play.py b/Demo/sgi/audio/play.py deleted file mode 100755 index 68a6a31bbb..0000000000 --- a/Demo/sgi/audio/play.py +++ /dev/null @@ -1,75 +0,0 @@ -#! /usr/bin/env python - -import sys -import audio - -import string -import getopt -import auds - -debug = [] - -DEF_RATE = 3 - -def main(): - # - gain = 100 - rate = 0 - starter = audio.write - stopper = 0 - # - optlist, args = getopt.getopt(sys.argv[1:], 'adg:r:') - # - for optname, optarg in optlist: - if 0: - pass - elif optname == '-d': - debug.append(1) - elif optname == '-g': - gain = string.atoi(optarg) - if not (0 < gain < 256): - raise optarg.error, '-g gain out of range' - elif optname == '-r': - rate = string.atoi(optarg) - if not (1 <= rate <= 3): - raise optarg.error, '-r rate out of range' - elif optname == '-a': - starter = audio.start_playing - stopper = audio.wait_playing - # - audio.setoutgain(gain) - audio.setrate(rate) - # - if not args: - play(starter, rate, auds.loadfp(sys.stdin)) - else: - real_stopper = 0 - for file in args: - if real_stopper: - real_stopper() - play(starter, rate, auds.load(file)) - real_stopper = stopper - -def play(starter, rate, data): - magic = data[:4] - if magic == '0008': - mrate = 3 - elif magic == '0016': - mrate = 2 - elif magic == '0032': - mrate = 1 - else: - mrate = 0 - if mrate: - data = data[4:] - else: - mrate = DEF_RATE - if not rate: rate = mrate - audio.setrate(rate) - starter(data) - -try: - main() -finally: - audio.setoutgain(0) - audio.done() diff --git a/Demo/sgi/cd/CD.doc b/Demo/sgi/cd/CD.doc deleted file mode 100755 index 67f6a028f0..0000000000 --- a/Demo/sgi/cd/CD.doc +++ /dev/null @@ -1,46 +0,0 @@ -Introduction. - -A number of programs have been written which access the Silicon -Graphics CD-ROM player. These programs all use the interface defined -in readcd.py (see readcd.doc for documentation). - -Specifying music stretches. - -The programs that are capable of reading music CD's all use the same -syntax to describe which part of the CD is to be read. The syntax -closely corresponds to the available methods in readcd.py. - -The music to be read is divided into stretches of music. Each stretch -must be specified as a separate argument on the command line. A -stretch can be a whole CD track, specified as a single number; or it -can be a start time and a end time. The start and end times must be -specified as a tuple, thus: ``(starttime, endtime)''. Don't forget to -quote the parenthesis to the shell. Both starttime and endtime can be -``None'', a simple number which refers to a CD track, or a tuple -consisting of either 3 or 4 elements. A starttime of ``None'' refers -to the start of the CD, an endtime of ``None'' refers to the end of -the CD. A tuple of 3 elements is an absolute time on the CD. The -three elements are (minutes, seconds, frames). A tuple of 4 elements -is a track-relative time. The four elements are (track, minutes, -seconds, frames). - -When one stretch ends at the end of a track and the following stretch -starts at the next track, there is the option of either playing or not -playing the pause between the two tracks. When either the end time of -the first stretch or the start time of the second stretch is specified -using absolute or track-relative times, the pause will not be played. -When both times are specified as simple track numbers, the pause will -be played. - -If no stretches are specified, the whole CD will be played. - -The programs. - -Currently, the following programs exist. -playcd [ stretch specification ] - Play (part of) a CD through the system loadspeaker or - headphone set. -cdaiff [ file [ stretch specification ] ] - Copy (part of) a CD to a file. The file will be written in - AIFF format. If no file is specified, cdaiff will write to - the file ``@'' in the current directory. diff --git a/Demo/sgi/cd/README b/Demo/sgi/cd/README deleted file mode 100644 index 016e4d1bb7..0000000000 --- a/Demo/sgi/cd/README +++ /dev/null @@ -1,28 +0,0 @@ -These are some programs to work with the SCSI CD-ROM player's audio -interface (see cdaudio(3) in IRIX 4.0 or higher; tested only on 4.0.2). - -See also the SGI-specific standard module 'readcd', documented as -"readcd.lib" in the library. - -cdwin.py A trivial window interface to play a CD over the CD - player's audio jack. More functionality is left as an - excersice to the reader. Needs module stdwin. - -listcd.py List the table-of-contents of a CD (data CDs will - appear as a single track). - -playcd.py Read audio data from the CD and play it over the - Indigo's built-in speker or audio jack. Needs module al. - -sendcd.py Read audio data from the CD and send it as UDP packets - over the network (to recvcd.py). - -recvcd.py Receive UDP packets containing CD audio data (from - sendcd.py) and play them over the Indigo's built-in - speaker or audio jack. Needs module al. (Doesn't - actually use module cd.) - -cdaiff.py Dump CD audio to disk in AIFF format. - -Note that to read *data* CD-ROMs you must open /dev/rdsk/dks0d4s7 or -some such special file... diff --git a/Demo/sgi/cd/cdaiff.py b/Demo/sgi/cd/cdaiff.py deleted file mode 100755 index a1b490f4ab..0000000000 --- a/Demo/sgi/cd/cdaiff.py +++ /dev/null @@ -1,33 +0,0 @@ -import sys -import readcd -import aifc -import AL -import cd - -Error = 'cdaiff.Error' - -def writeaudio(a, type, data): - a.writeframesraw(data) - -def main(): - if len(sys.argv) > 1: - a = aifc.open(sys.argv[1], 'w') - else: - a = aifc.open('@', 'w') - a.setsampwidth(AL.SAMPLE_16) - a.setnchannels(AL.STEREO) - a.setframerate(AL.RATE_44100) - r = readcd.Readcd() - for arg in sys.argv[2:]: - x = eval(arg) - try: - if len(x) <> 2: - raise Error, 'bad argument' - r.appendstretch(x[0], x[1]) - except TypeError: - r.appendtrack(x) - r.setcallback(cd.audio, writeaudio, a) - r.play() - a.close() - -main() diff --git a/Demo/sgi/cd/listcd.py b/Demo/sgi/cd/listcd.py deleted file mode 100755 index 2cfadb6b5e..0000000000 --- a/Demo/sgi/cd/listcd.py +++ /dev/null @@ -1,24 +0,0 @@ -# List track info from CD player. - -import cd - -def main(): - c = cd.open() - info = [] - while 1: - try: - info.append(c.gettrackinfo(len(info) + 1)) - except RuntimeError: - break - for i in range(len(info)): - start, total = info[i] - print 'Track', zfill(i+1), triple(start), triple(total) - -def triple((a, b, c)): - return zfill(a) + ':' + zfill(b) + ':' + zfill(c) - -def zfill(n): - s = `n` - return '0' * (2 - len(s)) + s - -main() diff --git a/Demo/sgi/cd/playcd.py b/Demo/sgi/cd/playcd.py deleted file mode 100755 index 44fa5a0697..0000000000 --- a/Demo/sgi/cd/playcd.py +++ /dev/null @@ -1,102 +0,0 @@ -# Play CD audio on speaker or headphones. - -callbacktypes = ['audio','pnum','index','ptime','atime','catalog','ident','control'] - -def playaudio(port, type, audio): - port.writesamps(audio) - -def prtrack(cdinfo, type, pnum): - if cdinfo.track[pnum] <> '': - print 'playing "' + cdinfo.track[pnum] + '"' - else: - print callbacktypes[type]+': '+`pnum` - -def callback(arg, type, data): - print callbacktypes[type]+': '+`data` - -def tcallback(arg, type, data): - print callbacktypes[type]+': '+triple(data) - -def triple((a, b, c)): - return zfill(a) + ':' + zfill(b) + ':' + zfill(c) - -def zfill(n): - s = `n` - return '0' * (2 - len(s)) + s - -def prtrackinfo(info): - for i in range(len(info)): - start, total = info[i] - print 'Track', zfill(i+1), triple(start), triple(total) - -statedict = ['ERROR', 'NODISK', 'READY', 'PLAYING', 'PAUSED', 'STILL'] - -def prstatus(status): - state, track, curtime, abstime, totaltime, first, last, \ - scsi_audio, cur_block, dummy = status - print 'Status:', - if 0 <= state < len(statedict): - print statedict[state] - else: - print state - print 'Track: ', track - print 'Time: ', triple(curtime) - print 'Abs: ', triple(abstime) - print 'Total: ', triple(totaltime) - print 'First: ', first - print 'Last: ', last - print 'SCSI: ', scsi_audio - print 'Block: ', cur_block - print 'Future:', dummy - -def main(): - import sys, readcd, al, AL, cd, cdplayer - verbose = 0 - r = readcd.Readcd() - prstatus(r.getstatus()) - prtrackinfo(r.gettrackinfo()) - cdinfo = cdplayer.Cdplayer(r.gettrackinfo()) - if cdinfo.title <> '': - print 'Title: "' + cdinfo.title + '"' - if cdinfo.artist <> '': - print 'Artist: ' + cdinfo.artist - for arg in sys.argv[1:]: - if arg == '-v': - verbose = 1 - continue - x = eval(arg) - try: - l = len(x) - r.appendstretch(x[0], x[1]) - except TypeError: - r.appendtrack(x) - try: - oldparams = [AL.OUTPUT_RATE, 0] - params = oldparams[:] - al.getparams(AL.DEFAULT_DEVICE, oldparams) - params[1] = AL.RATE_44100 - al.setparams(AL.DEFAULT_DEVICE, params) - config = al.newconfig() - config.setwidth(AL.SAMPLE_16) - config.setchannels(AL.STEREO) - port = al.openport('CD Player', 'w', config) - - for i in range(8): - r.setcallback(i, callback, None) - if verbose: - r.setcallback(cd.ptime, tcallback, None) - r.setcallback(cd.atime, tcallback, None) - else: - r.removecallback(cd.ptime) - r.removecallback(cd.atime) - r.setcallback(cd.pnum, prtrack, cdinfo) - r.setcallback(cd.audio, playaudio, port) - - data = r.play() - except KeyboardInterrupt: - status = r.getstatus() - print 'Interrupted at '+triple(status[2])+' into track '+ \ - `status[1]`+' (absolute time '+triple(status[3])+')' - al.setparams(AL.DEFAULT_DEVICE, oldparams) - -main() diff --git a/Demo/sgi/cd/recvcd.py b/Demo/sgi/cd/recvcd.py deleted file mode 100755 index e7496d1925..0000000000 --- a/Demo/sgi/cd/recvcd.py +++ /dev/null @@ -1,36 +0,0 @@ -# Receive UDP packets from sendcd.py and play them on the speaker or -# audio jack. - -import al, AL -from socket import * -from cd import DATASIZE - -PORT = 50505 # Must match the port in sendcd.py - -def main(): - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', PORT) - - oldparams = [AL.OUTPUT_RATE, 0] - params = oldparams[:] - al.getparams(AL.DEFAULT_DEVICE, oldparams) - params[1] = AL.RATE_44100 - try: - al.setparams(AL.DEFAULT_DEVICE, params) - config = al.newconfig() - config.setwidth(AL.SAMPLE_16) - config.setchannels(AL.STEREO) - port = al.openport('CD Player', 'w', config) - - while 1: - data = s.recv(DATASIZE) - if not data: - print 'EOF' - break - port.writesamps(data) - except KeyboardInterrupt: - pass - - al.setparams(AL.DEFAULT_DEVICE, oldparams) - -main() diff --git a/Demo/sgi/cd/sendcd.py b/Demo/sgi/cd/sendcd.py deleted file mode 100755 index a6cf8e76a6..0000000000 --- a/Demo/sgi/cd/sendcd.py +++ /dev/null @@ -1,154 +0,0 @@ -# Read CD audio data from the SCSI CD player and send it as UDP -# packets to "recvcd.py" on another host. -# -# Usage: python sendcd.py [options] host [track | minutes seconds [frames]] -# -# Options: -# "-l" list track info and quit. -# "-s" display status and quit. -# -# Arguments: -# host host to send the audio data to (required unless -l or -s). -# track track number where to start; alternatively, -# min sec [frames] absolute address where to start; -# default is continue at current point according to status. - -import cd -import sys -from socket import * -import getopt - -PORT = 50505 # Must match the port in readcd.py - -def main(): - try: - optlist, args = getopt.getopt(sys.argv[1:], 'ls') - except getopt.error, msg: - sys.stderr.write(msg + '\n') - sys.exit(2) - - player = cd.open() - prstatus(player) - size = player.bestreadsize() - - if optlist: - for opt, arg in optlist: - if opt == '-l': - prtrackinfo(player) - elif opt == '-s': - prstatus(player) - return - - if not args: - sys.stderr.write('usage: ' + sys.argv[0] + ' host [track]\n') - sys.exit(2) - host, args = args[0], args[1:] - - sys.stdout.write('waiting for socket... ') - sys.stdout.flush() - port = socket(AF_INET, SOCK_DGRAM) - port.connect(host, PORT) - print 'socket connected' - - parser = cd.createparser() - parser.setcallback(cd.audio, audiocallback, port) - parser.setcallback(cd.pnum, pnumcallback, player) - parser.setcallback(cd.index, indexcallback, None) - ## cd.ptime: too many calls - ## cd.atime: too many calls - parser.setcallback(cd.catalog, catalogcallback, None) - parser.setcallback(cd.ident, identcallback, None) - parser.setcallback(cd.control, controlcallback, None) - - if len(args) >= 2: - if len(args) >= 3: - [min, sec, frame] = args[:3] - else: - [min, sec] = args - frame = '0' - min, sec, frame = eval(min), eval(sec), eval(frame) - print 'Seek to', triple(min, sec, frame) - dummy = player.seek(min, sec, frame) - elif len(args) == 1: - track = eval(args[0]) - print 'Seek to track', track - dummy = player.seektrack(track) - else: - min, sec, frame = player.getstatus()[3] - print 'Try to seek back to', triple(min, sec, frame) - try: - player.seek(min, sec, frame) - except RuntimeError: - print 'Seek failed' - - try: - while 1: - frames = player.readda(size) - if frames == '': - print 'END OF CD' - break - parser.parseframe(frames) - except KeyboardInterrupt: - print '[Interrupted]' - pass - -def prtrackinfo(player): - info = [] - while 1: - try: - info.append(player.gettrackinfo(len(info) + 1)) - except RuntimeError: - break - for i in range(len(info)): - start, total = info[i] - print 'Track', zfill(i+1), triple(start), triple(total) - -def audiocallback(port, type, data): -## sys.stdout.write('#') -## sys.stdout.flush() - port.send(data) - -def pnumcallback(player, type, data): - print 'pnum =', `data` - prstatus(player) - -def indexcallback(arg, type, data): - print 'index =', `data` - -def catalogcallback(arg, type, data): - print 'catalog =', `data` - -def identcallback(arg, type, data): - print 'ident =', `data` - -def controlcallback(arg, type, data): - print 'control =', `data` - -statedict = ['ERROR', 'NODISK', 'READY', 'PLAYING', 'PAUSED', 'STILL'] - -def prstatus(player): - state, track, curtime, abstime, totaltime, first, last, \ - scsi_audio, cur_block, dummy = player.getstatus() - print 'Status:', - if 0 <= state < len(statedict): - print statedict[state] - else: - print state - print 'Track: ', track - print 'Time: ', triple(curtime) - print 'Abs: ', triple(abstime) - print 'Total: ', triple(totaltime) - print 'First: ', first - print 'Last: ', last - print 'SCSI: ', scsi_audio - print 'Block: ', cur_block - print 'Future:', dummy - -def triple((a, b, c)): - return zfill(a) + ':' + zfill(b) + ':' + zfill(c) - -def zfill(n): - s = `n` - return '0' * (2 - len(s)) + s - -main() diff --git a/Demo/sgi/flp/.cvsignore b/Demo/sgi/flp/.cvsignore deleted file mode 100644 index 4cee222e1d..0000000000 --- a/Demo/sgi/flp/.cvsignore +++ /dev/null @@ -1 +0,0 @@ -tcache.fdc test_cb.fdc test_nocb.fdc diff --git a/Demo/sgi/flp/tcache.fd b/Demo/sgi/flp/tcache.fd deleted file mode 100755 index 2ae91facd0..0000000000 --- a/Demo/sgi/flp/tcache.fd +++ /dev/null @@ -1,51 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 2 - -=============== FORM =============== -Name: first -Width: 340.000000 -Height: 160.000000 -Number of Objects: 1 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 340.000000 160.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 10.000000 -lcol: 0 -label: -name: -callback: -argument: - -=============== FORM =============== -Name: second -Width: 150.000000 -Height: 400.000000 -Number of Objects: 1 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 150.000000 400.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 10.000000 -lcol: 0 -label: -name: -callback: -argument: - -============================== -create_the_forms diff --git a/Demo/sgi/flp/tcache.py b/Demo/sgi/flp/tcache.py deleted file mode 100755 index cf713fc325..0000000000 --- a/Demo/sgi/flp/tcache.py +++ /dev/null @@ -1,32 +0,0 @@ -# Test bug in caching of forms - -import sys -import os -import flp - -filename = 'tcache.fd' -cachename = filename + 's' - -def first(): - try: - os.unlink(cachename) - except os.error: - pass - first = flp.parse_form(filename, 'first') - -def second(): - forms = flp.parse_forms(filename) - k = forms.keys() - if 'first' in k and 'second' in k: - print 'OK' - else: - print 'BAD!', k - -def main(): - if sys.argv[1:]: - second() - else: - first() - print 'Now run the script again with an argument' - -main() diff --git a/Demo/sgi/flp/test_cb.fd b/Demo/sgi/flp/test_cb.fd deleted file mode 100755 index e83fd1f46b..0000000000 --- a/Demo/sgi/flp/test_cb.fd +++ /dev/null @@ -1,75 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 1 - -=============== FORM =============== -Name: main_form -Width: 170.000000 -Height: 190.000000 -Number of Objects: 4 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 170.000000 190.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 10.000000 140.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Button 1 -name: button1 -callback: button1CB -argument: 0 - --------------------- -class: 11 -type: 0 -box: 10.000000 100.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Button 2 -name: button2 -callback: button2CB -argument: 0 - --------------------- -class: 11 -type: 6 -box: 10.000000 10.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: EXIT -name: exitbutton -callback: exitbuttonCB -argument: 0 - -============================== -create_the_forms diff --git a/Demo/sgi/flp/test_cb.py b/Demo/sgi/flp/test_cb.py deleted file mode 100755 index 41635036d3..0000000000 --- a/Demo/sgi/flp/test_cb.py +++ /dev/null @@ -1,61 +0,0 @@ -# -# Example 2 - Using fl in python with callbacks. -# -# The form is named 'main_form' and resides on file 'test_cb.fd'. -# It has three objects named button1, button2 and exitbutton. -# All buttons have callbacks with the same names as their corresponding -# buttons but with CB appended. -# -import fl # The forms library -import FL # Symbolic constants for the above -import flp # The module to parse .fd files -import sys - -# The following struct is created to hold the instance variables -# main_form, button1, button2 and exitbutton. - -class myform: - # - # The constructor parses and creates the form, but doesn't - # display it (yet). - def __init__(self, number): - # - # First we parse the form - parsetree = flp.parse_form('test_cb', 'main_form') - # - # Next we create it - - flp.create_full_form(self, parsetree) - - # And keep our number - self.number = number - - # - # The show function displays the form. It doesn't do any interaction, - # though. - def show(self): - self.main_form.show_form(FL.PLACE_SIZE, 1, '') - - # The callback functions - def button1CB(self, obj, arg): - print 'Button 1 pressed on form', self.number - - def button2CB(self, obj, arg): - print 'Button 2 pressed on form', self.number - - def exitbuttonCB(self, obj, arg): - print 'Ok, bye bye' - sys.exit(0) - -# -# The main program. Instantiate two variables of the forms class -# and interact with them. - -form1 = myform(1) -form2 = myform(2) - -form1.show() -form2.show() - -obj = fl.do_forms() -print 'do_forms() returned. This should not happen. obj=', obj diff --git a/Demo/sgi/flp/test_nocb.fd b/Demo/sgi/flp/test_nocb.fd deleted file mode 100755 index 4d3f7ef925..0000000000 --- a/Demo/sgi/flp/test_nocb.fd +++ /dev/null @@ -1,75 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 1 - -=============== FORM =============== -Name: main_form -Width: 170.000000 -Height: 190.000000 -Number of Objects: 4 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 170.000000 190.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 10.000000 140.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Button 1 -name: button1 -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 10.000000 100.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Button 2 -name: button2 -callback: -argument: - --------------------- -class: 11 -type: 6 -box: 10.000000 10.000000 150.000000 40.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: EXIT -name: exitbutton -callback: -argument: - -============================== -create_the_forms diff --git a/Demo/sgi/flp/test_nocb.py b/Demo/sgi/flp/test_nocb.py deleted file mode 100755 index 6346da3ed9..0000000000 --- a/Demo/sgi/flp/test_nocb.py +++ /dev/null @@ -1,45 +0,0 @@ -# -# Example 1 - Using fl in python without callbacks. -# -# The form is named 'main_form' and resides on file 'test_nocb.fd'. -# It has three objects named button1, button2 and exitbutton. -# -import fl # The forms library -import FL # Symbolic constants for the above -import flp # The module to parse .fd files -import sys - -# The following struct is created to hold the instance variables -# main_form, button1, button2 and exitbutton. - -class struct: pass -container = struct() - -# -# We now first parse the forms file - -parsetree = flp.parse_form('test_nocb', 'main_form') - -# -# Next we create it - -flp.create_full_form(container, parsetree) - -# -# And display it - -container.main_form.show_form(FL.PLACE_MOUSE, 1, '') - -# -# And interact until the exit button is pressed -while 1: - selected_obj = fl.do_forms() - if selected_obj == container.button1: - print 'Button 1 selected' - elif selected_obj == container.button2: - print 'Button 2 selected' - elif selected_obj == container.exitbutton: - print 'Ok, bye bye' - sys.exit(0) - else: - print 'do_forms() returned unknown object ', selected_obj diff --git a/Demo/sgi/gl/README b/Demo/sgi/gl/README deleted file mode 100644 index a89a502138..0000000000 --- a/Demo/sgi/gl/README +++ /dev/null @@ -1,35 +0,0 @@ -These demos run only on SGI machines and require the 'gl' built-in module. -The demonstrate the abilities of SGI's GL library as well as the ease of -GL programming in Python. Most demos require the Z-buffer (aka -24-bitplane) option. Press ESC to get out of any of them. - -backface.py Demonstrates the 'backface' GL function. - -kites.py Show 3 flying kites. Demonstrates the rendering speed - obtainable by Python programs. - -kunst.py Cute demo showing a ball suspended on four cables in - the central room of the CWI building. You can specify - three functions Fx(t), Fy(t), Fz(t) which define the - movement of the ball. Try something like sin(t), - cos(t), sin(2*t). - -mclock.py A colorful clock with more options than you can - remember. Works on 8-bit machines, but allows more - colors on 24-bit machines. See mclock.doc for more - info. - -mixing.py Demonstrates the effect of color mixing: through - frequent color switching it gives the effect of white - light. - -nurbs.py A simple demonstration of the 'nurbs' GL functions. - Press left mouse button to toggle surface trimming. - -zrgb.py Displays a 3-D Gouraud-shaded figure which can be moved - around with the mouse. - -glstdwin/ This is quite different: a partial STDWIN emulation - using GL! Requires only small changes to Python - programs that use STDWIN. Some features not yet - implemented, e.g., scroll bars. diff --git a/Demo/sgi/gl/backface.py b/Demo/sgi/gl/backface.py deleted file mode 100755 index 41c69d60a2..0000000000 --- a/Demo/sgi/gl/backface.py +++ /dev/null @@ -1,140 +0,0 @@ -#! /usr/bin/env python - -# backface -# -# draw a cube that can run with backface() turned on or off. -# cube is moved when LEFTMOUSE is pressed and mouse itself is moved. - -from gl import * -from DEVICE import * -from GL import * - -CUBE_SIZE = 200.0 -CUBE_OBJ = 1 - -def main () : - # - x = 0 - y = 0 - moveit = 0 - # - initialize() - # - while (1) : - # - while (qtest()) : - dev, val = qread() - # - if dev == ESCKEY : - backface(0) - return - # - elif dev == REDRAW : - reshapeviewport() - drawcube(x,y) - # - elif dev == LEFTMOUSE : - # - # LEFTMOUSE down - moveit = val - # - elif dev == BKEY : - backface(1) - drawcube(x,y) - # - elif dev == FKEY : - backface(0) - drawcube(x,y) - # - if moveit : - x = getvaluator(MOUSEX) - y = getvaluator(MOUSEY) - drawcube(x,y) - - -def initialize () : - foreground () - keepaspect (1, 1) - gid = winopen('backface') - winset(gid) - winconstraints() - # - doublebuffer() - gconfig() - shademodel(FLAT) - # - ortho(-1024.0, 1024.0, -1024.0, 1024.0, -1024.0, 1024.0) - # - qdevice(ESCKEY) - qdevice(REDRAW) - qdevice(LEFTMOUSE) - qdevice(BKEY) - qdevice(FKEY) - qenter(REDRAW,gid) - # - backface(1) - -# -# define a cube -def cube () : - # - # front face - pushmatrix() - translate(0.0,0.0,CUBE_SIZE) - color(RED) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # right face - pushmatrix() - translate(CUBE_SIZE, 0.0, 0.0) - rotate(900, 'y') - color(GREEN) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # back face - pushmatrix() - translate(0.0, 0.0, -CUBE_SIZE) - rotate(1800, 'y') - color(BLUE) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # left face - pushmatrix() - translate(-CUBE_SIZE, 0.0, 0.0) - rotate(-900, 'y') - color(CYAN) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # top face - pushmatrix() - translate(0.0, CUBE_SIZE, 0.0) - rotate(-900, 'x') - color(MAGENTA) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - # - # bottom face - pushmatrix() - translate(0.0, -CUBE_SIZE, 0.0) - rotate(900, 'x') - color(YELLOW) - rectf(-CUBE_SIZE,-CUBE_SIZE,CUBE_SIZE,CUBE_SIZE) - popmatrix() - -def drawcube(x,y) : - # - pushmatrix() - rotate(2*x, 'x') - rotate(2*y, 'y') - color(BLACK) - clear() - cube() - popmatrix() - swapbuffers() - - -main () diff --git a/Demo/sgi/gl/glinfo.py b/Demo/sgi/gl/glinfo.py deleted file mode 100755 index dae99f1583..0000000000 --- a/Demo/sgi/gl/glinfo.py +++ /dev/null @@ -1,20 +0,0 @@ -#! /usr/bin/env python - -# Print the values of all values that can be inquired with getgdesc(). -# See man getgdesc() for a description. - -import gl -import GL - -def main(): - names = [] - maxlen = 0 - for name in dir(GL): - if name[:3] == 'GD_': - names.append(name) - maxlen = max(maxlen, len(name)) - for name in names: - print name + (maxlen - len(name))*' ' + '=', - print gl.getgdesc(getattr(GL, name)) - -main() diff --git a/Demo/sgi/gl/kites.py b/Demo/sgi/gl/kites.py deleted file mode 100755 index cde69cb2e8..0000000000 --- a/Demo/sgi/gl/kites.py +++ /dev/null @@ -1,194 +0,0 @@ -#! /usr/bin/env python - -# *** This only works correctly on a 24 bit-plane machine. *** -# -# A simple Python program that tests the some parts of the -# GL library. It shows the speed that can be obtained when -# doing simple graphics. -# -# The bottleneck in this program is NOT Python but the graphics -# engine; i.e Python can feed the graphics pipeline fast enough -# on the 4D/25G. -# -# This program show 3 kites flying around the screen. It uses -# -# * bgnpolygon, endpolygon -# * v3, n3 -# * lmdef, lmbind -# -# Usage : -# -# ESC -> exit program -# MOUSE3 -> freeze toggle -# MOUSE2 -> one step (use this in freeze state) - -from GL import * -from gl import * -import DEVICE -from math import * - -# -# viewobj : sets the rotation, translation and scaling -# set appropiate material, call drawobject() -# -def viewobj (r, s, t, mat) : - pushmatrix() - rot (r * 10.0, 'X') - rot (r * 10.0, 'Y') - rot (r * 10.0, 'Z') - scale (s[0], s[1], s[2]) - translate (t[0], t[1], t[2]) - lmbind(MATERIAL, mat) - drawobject() - popmatrix() - -# -# makeobj : the constructor of the object -# -def mkobj () : - v0 = (-5.0 ,0.0, 0.0) - v1 = (0.0 ,5.0, 0.0) - v2 = (5.0 ,0.0, 0.0) - v3 = (0.0 ,2.0, 0.0) - n0 = (sqrt(2.0)/2.0, sqrt(2.0)/2.0, 0.0) - vn = ((v0, n0), (v1, n0), (v2, n0), (v3, n0)) - # - return vn - -# -# the object itself as an array of vertices and normals -# -kite = mkobj () - -# -# drawobject : draw a triangle. with bgnpolygon -# -def drawobject () : - # - bgnpolygon() - vnarray (kite) - endpolygon() - -# -# identity matrix -# -idmat=[1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0] - -# -# the rgb-value of light-blue -# -LightBlue = (43,169,255) - -# -# the different materials. -# -m1=[SPECULAR,0.0,0.0,0.6,DIFFUSE,0.0,0.0,0.8,SHININESS,20.0,LMNULL] -m2=[SPECULAR,0.8,0.0,0.1,DIFFUSE,0.8,0.0,0.3,SHININESS,120.0,LMNULL] -m3=[SPECULAR,0.0,1.0,0.0,DIFFUSE,0.0,0.6,0.0,SHININESS,120.0,LMNULL] - -# -# lightsources -# -light1 = [LCOLOR,1.0,1.0,1.0,POSITION,15.0,15.0,0.0,1.0,LMNULL] -light2 = [LCOLOR,1.0,1.0,1.0,POSITION,-15.0,15.0,0.0,1.0,LMNULL] - -# -# the lightmodel -# -model = [AMBIENT,0.2,0.2,0.2,LMNULL] - -# -# initgl : opens the window, configures the pipeline to 2buf and zbuf, -# sets the viewing, defines and binds the materials -# -def initgl () : - # - # open window - # - foreground () - keepaspect (1, 1) - prefposition (100, 500, 100, 500) - w = winopen ('PYTHON lights') - keepaspect (1, 1) - winconstraints() - # - # configure pipeline (zbuf, 2buf, GOURAUD and RGBmode) - # - zbuffer (1) - doublebuffer () - shademodel (GOURAUD) - RGBmode () - gconfig () - # - # define and bind materials (set perspective BEFORE loadmat !) - # - mmode(MVIEWING) - perspective (900, 1.0, 1.0, 20.0) - loadmatrix(idmat) - lmdef(DEFMATERIAL, 1, m1) - lmdef(DEFMATERIAL, 2, m2) - lmdef(DEFMATERIAL, 3, m3) - lmdef(DEFLIGHT, 1, light1) - lmdef(DEFLIGHT, 2, light2) - lmdef(DEFLMODEL, 1, model) - lmbind(LIGHT0,1) - lmbind(LIGHT1,2) - lmbind(LMODEL,1) - # - # set viewing - # - lookat (0.0, 0.0, 10.0, 0.0, 0.0, 0.0, 0) - # - # ask for the REDRAW and ESCKEY events - # - qdevice(DEVICE.MOUSE3) - qdevice(DEVICE.MOUSE2) - qdevice(DEVICE.REDRAW) - qdevice(DEVICE.ESCKEY) - -# -# GoForIT : use 2buf to redraw the object 2n times. index i is used as -# the (smoothly changing) rotation angle -# -def GoForIt(i) : - freeze = 1 - while 1 : - if freeze <> 0 : - i = i + 1 - # - # clear z-buffer and clear background to light-blue - # - zclear() - c3i (LightBlue) - clear() - # - # draw the 3 traiangles scaled above each other. - # - viewobj(float(i),[1.0,1.0,1.0],[1.0,1.0,1.0],1) - viewobj(float(i),[0.75,0.75,0.75],[0.0,2.0,2.0],2) - viewobj(float(i),[0.5,0.5,0.5],[0.0,4.0,4.0],3) - # - swapbuffers() - # - if qtest() <> 0 : - dev, val = qread() - if dev == DEVICE.ESCKEY : - break - elif dev == DEVICE.REDRAW : - reshapeviewport () - elif dev == DEVICE.MOUSE3 and val <> 0 : - freeze = 1 - freeze - elif dev == DEVICE.MOUSE2 and val <> 0 : - i = i + 1 - - -# the main program -# -def main () : - initgl () - GoForIt (0) - -# -# exec main -# -main () diff --git a/Demo/sgi/gl/kunst.py b/Demo/sgi/gl/kunst.py deleted file mode 100755 index f37f979ef8..0000000000 --- a/Demo/sgi/gl/kunst.py +++ /dev/null @@ -1,426 +0,0 @@ -#! /usr/bin/env python -# Simulate the artwork in the hall. -# Jack Jansen, Feb 91. - -from gl import * -from GL import * -from math import * -from DEVICE import * -import sys -import __main__ -main_dict = __main__.__dict__ - -SPOTDIRECTION = 103 -SPOTLIGHT = 104 - -# -# Make a cylinder paralel with the Z axis with center (X,Y,0) -# and radius 1 -def mkcyl(nslice, nparts, docircle): - cyl = [] - step = 2.0 / float(nslice) - z = -1.0 - for i in range(nslice): - cyl.append(mkslice(z, z+step, nparts, docircle)) - z = z + step - return drawcylinder(cyl) -# -# Make one part of a cylinder -# -def mkslice(z1, z2, nparts, docircle): - if docircle: - w1 = z1 - w2 = z2 - w1 = sqrt(1.0-w1*w1) - w2 = sqrt(1.0-w2*w2) - normalz = 1.0 - else: - w1 = 1.0 - w2 = 1.0 - normalz = 0.0 - slice = [] - step = (2.0*pi)/float(nparts) - angle = 0.0 - for i in range(nparts+1): - vx = cos(angle) - vy = sin(angle) - slice.append( ((vx*w1,vy*w1,z1), (vx*w1, vy*w1, z1*normalz)) ) - slice.append( ((vx*w2,vy*w2,z2), (vx*w2, vy*w2, z2*normalz)) ) - angle = angle + step - return slice -# -# Drawcylinder : draw the cylinder -# -class struct: pass -curobj = struct() -curobj.curobj = 1 -def drawcylinder(cyl): - obj = curobj.curobj - curobj.curobj = curobj.curobj+1 - makeobj(obj) - for slice in cyl: - bgntmesh() - vnarray(slice) - endtmesh() - closeobj() - return obj -# -def drawnormals(cyl): - for slice in cyl: - for triang in slice: - bgnline() - v3f(triang[0]) - v3f(triang[0][0] + triang[1][0], triang[0][1] + triang[1][1], triang[0][2] + triang[1][2]) - endline() -def drawfloors(): - obj = curobj.curobj - curobj.curobj = curobj.curobj+1 - makeobj(obj) - bgnpolygon() - v3i(4,6,-6) - v3i(-6,6,-6) - v3i(-6,-6,-6) - v3i(4,-6,-6) - endpolygon() - for floor in range(3): - pos = -1 + 5*floor - bgnpolygon() - v3i(4,4,pos) - v3i(-6,4,pos) - v3i(-6,6,pos) - v3i(4,6,pos) - endpolygon() - bgnpolygon() - v3i(-4,4,pos) - v3i(-4,-4,pos) - v3i(-6,-4,pos) - v3i(-6,4,pos) - endpolygon() - bgnpolygon() - v3i(-6,-4,pos) - v3i(-6,-6,pos) - v3i(4,-6,pos) - v3i(4,-4,pos) - endpolygon() - closeobj() - return obj -def drawdoors(): - obj = curobj.curobj - curobj.curobj = curobj.curobj+1 - makeobj(obj) - for floor in range(3): - pos = -1+5*floor - bgnpolygon() - v3i(-2,6,pos) - v3i(-2,6,pos+3) - v3i(0,6,pos+3) - v3i(0,6,pos) - endpolygon() - closeobj() - return obj -def drawrailing(): - obj = curobj.curobj - curobj.curobj = curobj.curobj+1 - makeobj(obj) - for floor in range(3): - pos = -1 + 5*floor - bgnpolygon() - v3i(4,4,pos) - v3i(4,4,pos-1) - v3i(-4,4,pos-1) - v3i(-4,4,pos) - endpolygon() - bgnpolygon() - v3i(-4,4,pos) - v3i(-4,4,pos-1) - v3i(-4,-4,pos-1) - v3i(-4,-4,pos) - endpolygon() - bgnpolygon() - v3i(-4,-4,pos) - v3i(-4,-4,pos-1) - v3i(4,-4,pos-1) - v3i(4,-4,pos) - endpolygon() - closeobj() - return obj -def drawwalls(): - obj = curobj.curobj - curobj.curobj = curobj.curobj+1 - makeobj(obj) - bgnpolygon() - v3i(4,6,-6) - v3i(4,6,18) - v3i(-6,6,18) - v3i(-6,6,-6) - endpolygon() - bgnpolygon() - v3i(-6,6,-6) - v3i(-6,6,18) - v3i(-6,-6,18) - v3i(-6,-6,-6) - endpolygon() - bgnpolygon() - v3i(-6,-6,-6) - v3i(-6,-6,18) - v3i(4,-6,18) - v3i(4,-6,-6) - endpolygon() - bgnpolygon() - v3i(4,-6,-6) - v3i(4,-6,18) - v3i(4,4,18) - v3i(4,4,-6) - endpolygon() - closeobj() - return obj -def axis(): - bgnline() - cpack(0xff0000) - v3i(-1,0,0) - v3i(1,0,0) - v3f(1.0, 0.1, 0.1) - endline() - bgnline() - cpack(0xff00) - v3i(0,-1,0) - v3i(0,1,0) - v3f(0.1, 1.0, 0.1) - endline() - bgnline() - cpack(0xff) - v3i(0,0,-1) - v3i(0,0,1) - v3f(0.1,0.1,1.0) - endline() -# -green_velvet = [ DIFFUSE, 0.05, 0.4, 0.05, LMNULL] -silver = [ DIFFUSE, 0.3, 0.3, 0.3, SPECULAR, 0.9, 0.9, 0.95, \ - SHININESS, 40.0, LMNULL] -floormat = [ AMBIENT, 0.5, 0.25, 0.15, DIFFUSE, 0.5, 0.25, 0.15, SPECULAR, 0.6, 0.3, 0.2, SHININESS, 20.0, LMNULL] -wallmat = [ DIFFUSE, 0.4, 0.2, 0.1, AMBIENT, 0.4, 0.20, 0.10, SPECULAR, 0.0, 0.0, 0.0, SHININESS, 20.0, LMNULL] -offwhite = [ DIFFUSE, 0.8, 0.8, 0.6, AMBIENT, 0.8, 0.8, 0.6, SPECULAR, 0.9, 0.9, 0.9, SHININESS, 30.0, LMNULL] -doormat = [ DIFFUSE, 0.1, 0.2, 0.5, AMBIENT, 0.2, 0.4, 1.0, SPECULAR, 0.2, 0.4, 1.0, SHININESS, 60.0, LMNULL] - -toplight = [ LCOLOR, 1.0, 1.0, 0.5, \ - POSITION, 0.0, 0.0, 11.0, 1.0, LMNULL] -floor1light = [ LCOLOR, 1.0, 1.0, 1.0, POSITION, 3.9, -3.9, 0.0, 1.0, \ - SPOTDIRECTION, 1.0, 1.0, 0.0, SPOTLIGHT, 10.0, 90.0, LMNULL] - -lmodel = [ AMBIENT, 0.92, 0.8, 0.5, LOCALVIEWER, 1.0, LMNULL] -# -def lighting(): - lmdef(DEFMATERIAL, 1, green_velvet) - lmdef(DEFMATERIAL, 2, silver) - lmdef(DEFMATERIAL, 3, floormat) - lmdef(DEFMATERIAL, 4, wallmat) - lmdef(DEFMATERIAL, 5, offwhite) - lmdef(DEFMATERIAL, 6, doormat) - lmdef(DEFLIGHT, 1, toplight) - lmdef(DEFLIGHT, 2, floor1light) - lmdef(DEFLMODEL, 1, lmodel) - lmbind(MATERIAL, 1) - lmbind(LIGHT0, 1) - lmbind(LIGHT1, 2) - lmbind(LMODEL, 1) -IdMat=[1.0,0.0,0.0,0.0, 0.0,1.0,0.0,0.0, 0.0,0.0,1.0,0.0, 0.0,0.0,0.0,1.0] -# -def defun(axis): - done = 0 - while not done: - print 'F'+axis+'(t) = ', - s = sys.stdin.readline(100) - print - try: - s = 'def f'+axis+'(t): return '+s - exec(s, main_dict) - done = 1 - except RuntimeError: - print 'Sorry, there is a syntax error in your expression' -def getfunctions(): - print 'Welcome to the CWI art simulator. You can now enter X, Y and Z' - print 'coordinates as a function of t.' - print 'Normal trig functions are available. Please use floating point' - print 'values only (so 0.0 for 0). Comments to jack@cwi.nl' - defun('x') - defun('y') - defun('z') - print 'Ok, here you go. Use mouse+right button to move up/down,' - print 'mouse+middle to speed up/slow down time. type ESC to quit simulation' -def main(): - getfunctions() - foreground() - prefposition(100,600,100,600) - void = winopen('cyl') - qdevice(ESCKEY) - qdevice(MOUSE1) - qdevice(MOUSE2) - qdevice(PKEY) - RGBmode() - doublebuffer() - gconfig() - zbuffer(1) - mmode(MVIEWING) - perspective(400, 1.0, 1.0, 20.0) - loadmatrix(IdMat) - vx = 0.0 - vy = -6.0 - vz = 0.0 - lookat(0.0, -6.0, 0.0, 0.0, 0.0, 0.0, 0) - lighting() - t = -1.0 - step = 1.0 - bol = mkcyl(12,24, 1) - cable = mkcyl(1, 6, 0) - floors = drawfloors() - walls = drawwalls() - pillar = mkcyl(1,4,0) - railing = drawrailing() - doors = drawdoors() - shademodel(GOURAUD) - mousing = -1 - pausing = 0 - while 1: - # - # Check for some user input - # - if qtest(): - dev, value = qread() - if dev == PKEY and value == 1: - pausing = 1 - if dev == ESCKEY: - break - elif (dev==MOUSE1 or dev==MOUSE2) and value == 1: - if mousing > 0: - vx = 0.0 - vy = -6.0 - vz = 0.0 - mousing = dev - oldx = getvaluator(MOUSEX) - oldy = getvaluator(MOUSEY) - elif (dev==MOUSE1 or dev==MOUSE2): - mousing = -1 - if mousing >= 0: - newx = getvaluator(MOUSEX) - newy = getvaluator(MOUSEY) - if newy <> oldy and mousing==MOUSE1: - vz = vz + float(newy - oldy)/100.0 - dist = sqrt(vx*vx + vy*vy + vz*vz) - perspective(400, 1.0, 1.0, dist+16.0) - loadmatrix(IdMat) - if vz < 0.0: - lookat(vx, vy, vz, 0.0, 0.0, 0.0, 1800) - else: - lookat(vx, vy, vz, 0.0, 0.0, 0.0, 0) - if newy <> oldy and mousing==MOUSE2: - step = step * exp(float(newy-oldy)/400.0) - if getbutton(CTRLKEY) == 0: - t = t + step - else: - t = t - step - if getbutton(LEFTSHIFTKEY) == 0: - shademodel(GOURAUD) - else: - shademodel(FLAT) - # - # Draw background and axis - cpack(0x105090) - clear() - zclear() - cpack(0x905010) - axis() - # - # Draw object - # - bolx = fx(t) - boly = fy(t) - bolz = fz(t) - err = '' - if bolx < -4.0 or bolx > 4.0: - err = 'X('+`bolx`+') out of range [-4,4]' - if boly < -4.0 or boly > 4.0: - err = 'Y('+`boly`+') out of range [-4,4]' - if bolz < -4.0 or bolz > 8.0: - err = 'Z('+`bolz`+') out of range [-4,8]' - if not err: - pushmatrix() - translate(bolx, boly, bolz) - scale(0.3, 0.3, 0.3) - lmbind(MATERIAL, 2) - callobj(bol) - popmatrix() - # - # Draw the cables - # - bolz = bolz + 0.3 - pushmatrix() - linesmooth(SML_ON) - bgnline() - v3i(-4,-4,9) - v3f(bolx, boly, bolz) - endline() - bgnline() - v3i(-4,4,9) - v3f(bolx, boly, bolz) - endline() - bgnline() - v3i(4,-4,9) - v3f(bolx, boly, bolz) - endline() - bgnline() - v3i(4,4,9) - v3f(bolx, boly, bolz) - endline() - popmatrix() - # - # draw the floors - # - lmbind(MATERIAL, 3) - callobj(floors) - lmbind(MATERIAL, 4) - callobj(walls) - lmbind(MATERIAL, 5) - pushmatrix() - translate(-4.5,4.5,3.0) - scale(0.2,0.2,9.0) - rotate(450,'z') - callobj(pillar) - popmatrix() - callobj(railing) - lmbind(MATERIAL, 6) - pushmatrix() - translate(0.0, -0.01, 0.0) - callobj(doors) - popmatrix() - if mousing == MOUSE2 or err: - cpack(0xff0000) - cmov(0.0, 0.0, 0.4) - charstr('t='+`t`) - if mousing == MOUSE2: - cpack(0xff0000) - cmov(0.0, 0.0, 0.2) - charstr('delta-t='+`step`) - if err: - cpack(0xff00) - cmov(0.0, 0.0, 0.2) - print err - charstr(err) - pausing = 1 - if pausing: - cpack(0xff00) - cmov(0.0, 0.0, 0.0) - charstr('Pausing, type P to continue') - swapbuffers() - if pausing: - while 1: - dv=qread() - if dv==(PKEY,1): - break - if dv==(ESCKEY,1): - sys.exit(0) - pausing = 0 -# -try: - main() -except KeyboardInterrupt: - sys.exit(1) diff --git a/Demo/sgi/gl/mclock.doc b/Demo/sgi/gl/mclock.doc deleted file mode 100755 index 2208f33fb3..0000000000 --- a/Demo/sgi/gl/mclock.doc +++ /dev/null @@ -1,60 +0,0 @@ -Newsgroups: cwi.sgi -Subject: Re: new clock -Distribution: cwi.sgi -References: <2246@charon.cwi.nl> - -Last week I wrote: - ->For your enjoyment I have implemented a colorful clock. - -The clock has now been extended with some new facilities: a menu, an -alarm and a gong. These may require some explanation beyond what's in -the usage message. - -Menu ----- -The right mouse button now pops up a menu that allows you to turn the -seconds hand on or off and to switch the alarm off. - -Alarm ------ - -The left and middle buttons set the alarm. When it is on, the alarm -time is displayed as a time on a 24 hour clock in the bottom left -corner. It is also indicated by two red triangles, corresponding to the -little (hours) and big (minutes) hand. These hands can be moved around: -the left mouse button moves the minutes hand, the middle button moves -the hourds hand. Watch out for differences of twelve hours (always -check the digital display); these can be corrected by dragging the hours -hand once around the dial. - -When the alarm goes off, two things happen: a shell command specified on -the command line with the -a option is executed (in the background), and -the clock's colors change every two seconds, for five minutes. You can -also turn the alarm off by using the menu accessible through the right -mouse button. - -There is no default command for the -a option; if it is not specified, -only the changing of the colors happens. If you have an 8 ohm speaker -connected to the audio output of your Personal Iris, a suitable command -would be: - - mclock -a '/ufs/guido/bin/sgi/play /ufs/guido/lib/sounds/alarm' - -Gong ----- - -Some people like a clock that makes noises every hour, or even more -often. This is supported by the -g and -G options. With -g you specify -a shell command to be executed to sound the gong; with -G you can -specify the interval between gong calls, in seconds (default is one hour). -The shell command is executed in the background. It is given two -arguments: the hours (on a 24 hour clock!) and the minutes. The -executable Python script /ufs/guido/bin/sgi/chime is a suitable example. -Again, this only works if you have installed a speaker (I bet 8 ohm -speakers are going to be in demand!) - --- -Guido van Rossum, Centre for Mathematics and Computer Science (CWI), Amsterdam -guido@cwi.nl or ..!hp4nl!cwi.nl!guido or guido%cwi.nl@uunet.uu.net -"A thing of beauty is a joy till sunrise" diff --git a/Demo/sgi/gl/mclock.py b/Demo/sgi/gl/mclock.py deleted file mode 100755 index 6af01ba991..0000000000 --- a/Demo/sgi/gl/mclock.py +++ /dev/null @@ -1,736 +0,0 @@ -#! /usr/bin/env python - -# "M Clock" -# -# An implementation in software of an original design by Rob Juda. -# Clock implementation: Guido van Rossum. -# Alarm and Gong features: Sape Mullender. -# -# XXX TO DO: -# add arguments to specify initial window position and size -# find out local time zone difference automatically -# add a date indicator -# allow multiple alarms -# allow the menu to change more parameters - -import sys - -from gl import * -from GL import * -from DEVICE import * -import time -import getopt -import string -import os -from math import pi -import math - -FULLC = 3600 # Full circle in 1/10-ths of a degree -MIDN = 900 # Angle of the 12 o'clock position -R, G, B = 0, 1, 2 # Indices of colors in RGB list - -HOUR = 3600 # Number of seconds per hour -MINUTE = 60 # Number of seconds per minute - -class struct: pass # Class to define featureless structures -Gl = struct() # Object to hold writable global variables - -# Default constants (used in multiple places) - -SCREENBG = 127, 156, 191 -NPARTS = 9 -TITLE = 'M Clock' - -# Set timezone, check for daylight saving time -TZDIFF = time.timezone -if time.localtime(time.time())[-1]: - TZDIFF = time.altzone - -# Default parameters - -Gl.foreground = 0 # If set, run in the foreground -Gl.fullscreen = 0 # If set, run on full screen -Gl.tzdiff = TZDIFF # Seconds west of Greenwich (winter time) -Gl.nparts = NPARTS # Number of parts each circle is divided in (>= 2) -Gl.debug = 0 # If set, print debug output -Gl.doublebuffer = 1 # If set, use double buffering -Gl.update = 0 # Update interval; seconds hand is suppressed if > 1 -Gl.colorsubset = 0 # If set, display only a subset of the colors -Gl.cyan = 0 # If set, display cyan overlay (big hand) -Gl.magenta = 0 # If set, display magenta overlay (little hand) -Gl.yellow = 0 # If set, display yellow overlay (fixed background) -Gl.black = 0 # If set, display black overlay (hands) -Gl.colormap = 0 # If set, use colormap mode instead of RGB mode -Gl.warnings = 0 # If set, print warnings -Gl.title = '' # Window title (default set later) -Gl.name = 'mclock' # Window title for resources -Gl.border = 1 # If set, use a window border (and title) -Gl.bg = 0, 0, 0 # Background color R, G, B value -Gl.iconic = 0 # Set in iconic state -Gl.fg = 255, 0, 0 # Alarm background RGB (either normal or alarm) -Gl.ox,Gl.oy = 0,0 # Window origin -Gl.cx,Gl.cy = 0,0 # Window size -Gl.alarm_set = 0 # Alarm on or off -Gl.alarm_on = 0 # Alarm is ringing -Gl.alarm_time = 0 # Alarm time in seconds after midnight -Gl.alarm_hours = 0 # Alarm hour setting, 24 hour clock -Gl.alarm_minutes = 0 # Alarm minutes setting -Gl.alarm_rgb = 0,0,0 # Alarm display RGB colors -Gl.alarm_cmd = '' # Command to execute when alarm goes off -Gl.mouse2down = 0 # Mouse button state -Gl.mouse3down = 0 # Mouse button state -Gl.gong_cmd = '' # Command to execute when chimes go off -Gl.gong_int = 3600 # Gong interval -Gl.indices = R, G, B # Colors (permuted when alarm is on) - -def main(): - # - sys.stdout = sys.stderr # All output is errors/warnings etc. - # - try: - args = getoptions() - except string.atoi_error, value: - usage(string.atoi_error, value) - except getopt.error, msg: - usage(getopt.error, msg) - # - if args: - realtime = 0 - hours = string.atoi(args[0]) - minutes = seconds = 0 - if args[1:]: minutes = string.atoi(args[1]) - if args[2:]: seconds = string.atoi(args[2]) - localtime = ((hours*60)+minutes)*60+seconds - else: - realtime = 1 - # - if Gl.title == '': - if realtime: - Gl.title = TITLE - else: - title = '' - for arg in args: title = title + ' ' + arg - Gl.title = title[1:] - del title - # - wid = makewindow() - Gl.ox,Gl.oy = getorigin() - Gl.cx,Gl.cy = getsize() - initmenu() - clearall() - # - if not Gl.update: - Gl.update = 60 - # - if Gl.update <= 1: - Gl.timernoise = 6 - else: - Gl.timernoise = 60 - noise(TIMER0, Gl.timernoise) - # - qdevice(WINSHUT) - qdevice(WINQUIT) - qdevice(ESCKEY) - if realtime: - qdevice(TIMER0) - qdevice(REDRAW) - qdevice(WINFREEZE) - qdevice(WINTHAW) - qdevice(MENUBUTTON) # MOUSE1 - qdevice(MOUSE3) # Left button - qdevice(MOUSE2) # Middle button - unqdevice(INPUTCHANGE) - # - lasttime = 0 - Gl.change = 1 - while 1: - if realtime: - localtime = int(time.time() - Gl.tzdiff) - if Gl.alarm_set: - if localtime%(24*HOUR) == Gl.alarm_time: - # Ring the alarm! - if Gl.debug: - print 'Rrrringg!' - Gl.alarm_on = 1 - if Gl.alarm_cmd <> '': - d = os.system(Gl.alarm_cmd+' '+`Gl.alarm_time/3600`+' '+`(Gl.alarm_time/60)%60` + ' &') - Gl.change = 1 - clearall() - if Gl.alarm_on: - if (localtime - Gl.alarm_time) % (24*HOUR) > 300: - # More than 5 minutes away from alarm - Gl.alarm_on = 0 - if Gl.debug: - print 'Alarm turned off' - Gl.change = 1 - clearall() - Gl.indices = R, G, B - else: - if localtime % 2 == 0: - # Permute color indices - Gl.indices = Gl.indices[2:] + Gl.indices[:2] - Gl.change = 1 - if Gl.gong_cmd <> '' and localtime%Gl.gong_int == 0: - d = os.system(Gl.gong_cmd+' '+`(localtime/3600)%24`+' '+`(localtime/60)%60` + ' &') - if localtime/Gl.update <> lasttime/Gl.update: - if Gl.debug: print 'new time' - Gl.change = 1 - if Gl.change: - if Gl.debug: print 'drawing' - doit(localtime) - lasttime = localtime - Gl.change = 0 - dev, data = qread() - if Gl.debug and dev <> TIMER0: - print dev, data - if dev == TIMER0: - if Gl.debug > 1: - print dev, data - elif dev == MOUSE3: - mousex = getvaluator(MOUSEX) - mousey = getvaluator(MOUSEY) - if mouseclick(3, data, mousex, mousey): - Gl.change = 1 - elif dev == MOUSE2: - mousex = getvaluator(MOUSEX) - mousey = getvaluator(MOUSEY) - if mouseclick(2, data, mousex, mousey): - Gl.change = 1 - elif dev == MOUSEX: - mousex = data - if Gl.mouse2down: - mouse2track(mousex, mousey) - if Gl.mouse3down: - mouse3track(mousex, mousey) - elif dev == MOUSEY: - mousey = data - if Gl.mouse2down: - mouse2track(mousex, mousey) - if Gl.mouse3down: - mouse3track(mousex, mousey) - elif dev == REDRAW or dev == REDRAWICONIC: - if Gl.debug: - if dev == REDRAW: print 'REDRAW' - else: print 'REDRAWICONIC' - reshapeviewport() - Gl.ox,Gl.oy = getorigin() - Gl.cx,Gl.cy = getsize() - Gl.change = 1 - clearall() - elif dev == MENUBUTTON: - if Gl.debug: print 'MENUBUTTON' - handlemenu() - elif dev == WINFREEZE: - if Gl.debug: print 'WINFREEZE' - Gl.iconic = 1 - noise(TIMER0, 60*60) # Redraw every 60 seconds only - elif dev == WINTHAW: - if Gl.debug: print 'WINTHAW' - Gl.iconic = 0 - noise(TIMER0, Gl.timernoise) - Gl.change = 1 - elif dev == ESCKEY or dev == WINSHUT or dev == WINQUIT: - if Gl.debug: print 'Exit' - sys.exit(0) - -def getoptions(): - optlist, args = getopt.getopt(sys.argv[1:], 'A:a:B:bc:dFfG:g:n:sT:t:u:wCMYK') - for optname, optarg in optlist: - if optname == '-A': - Gl.fg = eval(optarg) # Should be (r,g,b) - elif optname == '-a': - Gl.alarm_cmd = optarg - elif optname == '-B': - Gl.bg = eval(optarg) # Should be (r,g,b) - elif optname == '-b': - Gl.border = 0 - elif optname == '-c': - Gl.colormap = string.atoi(optarg) - elif optname == '-d': - Gl.debug = Gl.debug + 1 - Gl.warnings = 1 - elif optname == '-F': - Gl.foreground = 1 - elif optname == '-f': - Gl.fullscreen = 1 - elif optname == '-G': - Gl.gong_int = 60*string.atoi(optarg) - elif optname == '-g': - Gl.gong_cmd = optarg - elif optname == '-n': - Gl.nparts = string.atoi(optarg) - elif optname == '-s': - Gl.doublebuffer = 0 - elif optname == '-T': - Gl.title = Gl.name = optarg - elif optname == '-t': - Gl.tzdiff = string.atoi(optarg) - elif optname == '-u': - Gl.update = string.atoi(optarg) - elif optname == '-w': - Gl.warnings = 1 - elif optname == '-C': - Gl.cyan = Gl.colorsubset = 1 - elif optname == '-M': - Gl.magenta = Gl.colorsubset = 1 - elif optname == '-Y': - Gl.yellow = Gl.colorsubset = 1 - elif optname == '-K': - Gl.black = Gl.colorsubset = 1 - else: - print 'Unsupported option', optname - return args - -def usage(exc, msg): - if sys.argv: - progname = os.path.basename(sys.argv[0]) - else: - progname = 'mclock' - # - print progname + ':', - if exc == string.atoi_error: - print 'non-numeric argument:', - print msg - # - print 'usage:', progname, '[options] [hh [mm [ss]]]' - # - print '-A r,g,b : alarm background red,green,blue [255,0,0]' - print '-a cmd : shell command executed when alarm goes off' - print '-B r,g,b : background red,green,blue [0,0,0]' - print ' (-B SCREENBG uses the default screen background)' - print '-b : suppress window border and title' - print '-c cmapid : select explicit colormap' - print '-d : more debug output (implies -F, -w)' - print '-F : run in foreground' - print '-f : use full screen' - print '-G intrvl : interval between chimes in minutes [60]' - print '-g cmd : shell command executed when chimes go off' - print '-s : single buffer mode' - print '-w : print various warnings' - print '-n nparts : number of parts [' + `NPARTS` + ']' - print '-T title : alternate window title [\'' + TITLE + '\']' - print '-t tzdiff : time zone difference [' + `TZDIFF` + ']' - print '-u update : update interval [60]' - print '-CMYK : Cyan, Magenta, Yellow or blacK overlay only' - print 'if hh [mm [ss]] is specified, display that time statically' - print 'on machines with < 12 bitplanes, -s is forced on' - # - sys.exit(2) - -def doit(localtime): - hands = makehands(localtime) - list = makelist(hands) - render(list, hands) - -def makehands(localtime): - localtime = localtime % (12*HOUR) - seconds_hand = MIDN + FULLC - (localtime*60) % FULLC - big_hand = (MIDN + FULLC - (localtime%HOUR)) % FULLC - little_hand = (MIDN + FULLC - ((localtime/12) % HOUR)) % FULLC - return little_hand, big_hand, seconds_hand - -def makelist(hands): - little_hand, big_hand, seconds_hand = hands - total = [] - if Gl.cyan or not Gl.colorsubset: - total = total + makesublist(big_hand, Gl.indices[0]) - if Gl.magenta or not Gl.colorsubset: - total = total + makesublist(little_hand, Gl.indices[1]) - if Gl.yellow or not Gl.colorsubset: - total = total + makesublist(MIDN, Gl.indices[2]) - total.sort() - return total - -def makesublist(first, icolor): - list = [] - alpha = FULLC/Gl.nparts - a = first - alpha/2 - for i in range(Gl.nparts): - angle = (a + i*alpha + FULLC) % FULLC - value = 255*(Gl.nparts-1-i)/(Gl.nparts-1) - list.append((angle, icolor, value)) - list.sort() - a, icolor, value = list[0] - if a <> 0: - a, icolor, value = list[len(list)-1] - t = 0, icolor, value - list.insert(0, t) - return list - -def rgb_fg(): - return Gl.fg - # Obsolete code: - if Gl.alarm_on: - return Gl.bg - else: - return Gl.fg - -def rgb_bg(): - return Gl.bg - # Obsolete code: - if Gl.alarm_on: - return Gl.fg - else: - return Gl.bg - -def clearall(): - Gl.c3i(rgb_bg()) - clear() - if Gl.doublebuffer: - swapbuffers() - clear() - -def draw_alarm(color): - frontbuffer(TRUE) - Gl.c3i(color) - pushmatrix() - rotate(-((Gl.alarm_time/12)%3600), 'z') - bgnpolygon() - v2f( 0.00,1.00) - v2f( 0.04,1.05) - v2f(-0.04,1.05) - endpolygon() - popmatrix() - # - pushmatrix() - rotate(-((Gl.alarm_time)%3600), 'z') - bgnpolygon() - v2f( 0.00,1.05) - v2f( 0.07,1.10) - v2f(-0.07,1.10) - endpolygon() - popmatrix() - # - cmov2(-1.06, -1.06) - charstr(string.rjust(`Gl.alarm_time/3600`,2)) - charstr(':') - charstr(string.zfill((Gl.alarm_time/60)%60,2)) - frontbuffer(FALSE) - -def render(list, (little_hand, big_hand, seconds_hand)): - # - if Gl.colormap: - resetindex() - # - if not list: - Gl.c3i((255, 255, 255)) # White - circf(0.0, 0.0, 1.0) - else: - list.append((3600, 0, 255)) # Sentinel - # - rgb = [255, 255, 255] - a_prev = 0 - for a, icolor, value in list: - if a <> a_prev: - [r, g, b] = rgb - if Gl.debug > 1: - print rgb, a_prev, a - Gl.c3i((r, g, b)) - arcf(0.0, 0.0, 1.0, a_prev, a) - rgb[icolor] = value - a_prev = a - # - if Gl.black or not Gl.colorsubset: - # - # Draw the hands -- in black - # - Gl.c3i((0, 0, 0)) - # - if Gl.update == 1 and not Gl.iconic: - # Seconds hand is only drawn if we update every second - pushmatrix() - rotate(seconds_hand, 'z') - bgnline() - v2f(0.0, 0.0) - v2f(1.0, 0.0) - endline() - popmatrix() - # - pushmatrix() - rotate(big_hand, 'z') - rectf(0.0, -0.01, 0.97, 0.01) - circf(0.0, 0.0, 0.01) - circf(0.97, 0.0, 0.01) - popmatrix() - # - pushmatrix() - rotate(little_hand, 'z') - rectf(0.04, -0.02, 0.63, 0.02) - circf(0.04, 0.0, 0.02) - circf(0.63, 0.0, 0.02) - popmatrix() - # - # Draw the alarm time, if set or being set - # - if Gl.alarm_set: - draw_alarm(rgb_fg()) - # - if Gl.doublebuffer: swapbuffers() - -def makewindow(): - # - if Gl.debug or Gl.foreground: - foreground() - # - if Gl.fullscreen: - scrwidth, scrheight = getgdesc(GD_XPMAX), getgdesc(GD_YPMAX) - prefposition(0, scrwidth-1, 0, scrheight-1) - else: - keepaspect(1, 1) - prefsize(80, 80) - # - if not Gl.border: - noborder() - wid = winopen(Gl.name) - wintitle(Gl.title) - # - if not Gl.fullscreen: - keepaspect(1, 1) - minsize(10, 10) - maxsize(2000, 2000) - iconsize(66, 66) - winconstraints() - # - nplanes = getplanes() - nmaps = getgdesc(GD_NMMAPS) - if Gl.warnings: - print nplanes, 'color planes,', nmaps, 'color maps' - # - if Gl.doublebuffer and not Gl.colormap and nplanes < 12: - if Gl.warnings: print 'forcing single buffer mode' - Gl.doublebuffer = 0 - # - if Gl.colormap: - if not Gl.colormap: - Gl.colormap = nmaps - 1 - if Gl.warnings: - print 'not enough color planes available', - print 'for RGB mode; forcing colormap mode' - print 'using color map number', Gl.colormap - if not Gl.colorsubset: - needed = 3 - else: - needed = Gl.cyan + Gl.magenta + Gl.yellow - needed = needed*Gl.nparts - if Gl.bg <> (0, 0, 0): - needed = needed+1 - if Gl.fg <> (0, 0, 0): - needed = needed+1 - if Gl.doublebuffer: - if needed > available(nplanes/2): - Gl.doublebuffer = 0 - if Gl.warnings: - print 'not enough colors available', - print 'for double buffer mode;', - print 'forcing single buffer mode' - else: - nplanes = nplanes/2 - if needed > available(nplanes): - # Do this warning always - print 'still not enough colors available;', - print 'parts will be left white' - print '(needed', needed, 'but have only', - print available(nplanes), 'colors available)' - # - if Gl.doublebuffer: - doublebuffer() - gconfig() - # - if Gl.colormap: - Gl.c3i = pseudo_c3i - fixcolormap() - else: - Gl.c3i = c3i - RGBmode() - gconfig() - # - if Gl.fullscreen: - # XXX Should find out true screen size using getgdesc() - ortho2(-1.1*1.280, 1.1*1.280, -1.1*1.024, 1.1*1.024) - else: - ortho2(-1.1, 1.1, -1.1, 1.1) - # - return wid - -def available(nplanes): - return pow(2, nplanes) - 1 # Reserve one pixel for black - -def fixcolormap(): - multimap() - gconfig() - nplanes = getplanes() - if Gl.warnings: - print 'multimap mode has', nplanes, 'color planes' - imap = Gl.colormap - Gl.startindex = pow(2, nplanes) - 1 - Gl.stopindex = 1 - setmap(imap) - mapcolor(0, 0, 0, 0) # Fixed entry for black - if Gl.bg <> (0, 0, 0): - r, g, b = Gl.bg - mapcolor(1, r, g, b) # Fixed entry for Gl.bg - Gl.stopindex = 2 - if Gl.fg <> (0, 0, 0): - r, g, b = Gl.fg - mapcolor(2, r, g, b) # Fixed entry for Gl.fg - Gl.stopindex = 3 - Gl.overflow_seen = 0 - resetindex() - -def resetindex(): - Gl.index = Gl.startindex - -r0g0b0 = (0, 0, 0) - -def pseudo_c3i(rgb): - if rgb == r0g0b0: - index = 0 - elif rgb == Gl.bg: - index = 1 - elif rgb == Gl.fg: - index = 2 - else: - index = definecolor(rgb) - color(index) - -def definecolor(rgb): - index = Gl.index - if index < Gl.stopindex: - if Gl.debug: print 'definecolor hard case', rgb - # First see if we already have this one... - for index in range(Gl.stopindex, Gl.startindex+1): - if rgb == getmcolor(index): - if Gl.debug: print 'return', index - return index - # Don't clobber reserverd colormap entries - if not Gl.overflow_seen: - # Shouldn't happen any more, hence no Gl.warnings test - print 'mclock: out of colormap entries' - Gl.overflow_seen = 1 - return Gl.stopindex - r, g, b = rgb - if Gl.debug > 1: print 'mapcolor', (index, r, g, b) - mapcolor(index, r, g, b) - Gl.index = index - 1 - return index - -# Compute n**i -def pow(n, i): - x = 1 - for j in range(i): x = x*n - return x - -def mouseclick(mouse, updown, x, y): - if updown == 1: - # mouse button came down, start tracking - if Gl.debug: - print 'mouse', mouse, 'down at', x, y - if mouse == 2: - Gl.mouse2down = 1 - mouse2track(x, y) - elif mouse == 3: - Gl.mouse3down = 1 - mouse3track(x, y) - else: - print 'fatal error' - qdevice(MOUSEX) - qdevice(MOUSEY) - return 0 - else: - # mouse button came up, stop tracking - if Gl.debug: - print 'mouse', mouse, 'up at', x, y - unqdevice(MOUSEX) - unqdevice(MOUSEY) - if mouse == 2: - mouse2track(x, y) - Gl.mouse2down = 0 - elif mouse == 3: - mouse3track(x, y) - Gl.mouse3down = 0 - else: - print 'fatal error' - Gl.alarm_set = 1 - return 1 - -def mouse3track(x, y): - # first compute polar coordinates from x and y - cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 - x, y = x - cx, y - cy - if (x, y) == (0, 0): return # would cause an exception - minutes = int(30.5 + 30.0*math.atan2(float(-x), float(-y))/pi) - if minutes == 60: minutes = 0 - a,b = Gl.alarm_minutes/15, minutes/15 - if (a,b) == (0,3): - # Moved backward through 12 o'clock: - Gl.alarm_hours = Gl.alarm_hours - 1 - if Gl.alarm_hours < 0: Gl.alarm_hours = Gl.alarm_hours + 24 - if (a,b) == (3,0): - # Moved forward through 12 o'clock: - Gl.alarm_hours = Gl.alarm_hours + 1 - if Gl.alarm_hours >= 24: Gl.alarm_hours = Gl.alarm_hours - 24 - Gl.alarm_minutes = minutes - seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE - if seconds <> Gl.alarm_time: - draw_alarm(rgb_bg()) - Gl.alarm_time = seconds - draw_alarm(rgb_fg()) - -def mouse2track(x, y): - # first compute polar coordinates from x and y - cx, cy = Gl.ox + Gl.cx/2, Gl.oy + Gl.cy/2 - x, y = x - cx, y - cy - if (x, y) == (0, 0): return # would cause an exception - hours = int(6.5 - float(Gl.alarm_minutes)/60.0 + 6.0*math.atan2(float(-x), float(-y))/pi) - if hours == 12: hours = 0 - if (Gl.alarm_hours,hours) == (0,11): - # Moved backward through midnight: - Gl.alarm_hours = 23 - elif (Gl.alarm_hours,hours) == (12,11): - # Moved backward through noon: - Gl.alarm_hours = 11 - elif (Gl.alarm_hours,hours) == (11,0): - # Moved forward through noon: - Gl.alarm_hours = 12 - elif (Gl.alarm_hours,hours) == (23,0): - # Moved forward through midnight: - Gl.alarm_hours = 0 - elif Gl.alarm_hours < 12: - Gl.alarm_hours = hours - else: - Gl.alarm_hours = hours + 12 - seconds = Gl.alarm_hours * HOUR + Gl.alarm_minutes * MINUTE - if seconds <> Gl.alarm_time: - draw_alarm(rgb_bg()) - Gl.alarm_time = seconds - draw_alarm(rgb_fg()) - -def initmenu(): - Gl.pup = pup = newpup() - addtopup(pup, 'M Clock%t|Alarm On/Off|Seconds Hand On/Off|Quit', 0) - -def handlemenu(): - item = dopup(Gl.pup) - if item == 1: - # Toggle alarm - if Gl.alarm_set: - Gl.alarm_set = 0 - Gl.alarm_on = 0 - else: - Gl.alarm_set = 1 - Gl.change = 1 - clearall() - elif item == 2: - # Toggle Seconds Hand - if Gl.update == 1: - Gl.update = 60 - Gl.timernoise = 60 - else: - Gl.update = 1 - Gl.timernoise = 6 - Gl.change = 1 - elif item == 3: - if Gl.debug: print 'Exit' - sys.exit(0) - -main() diff --git a/Demo/sgi/gl/mixing.py b/Demo/sgi/gl/mixing.py deleted file mode 100755 index 9a4c9c1fca..0000000000 --- a/Demo/sgi/gl/mixing.py +++ /dev/null @@ -1,116 +0,0 @@ -#! /usr/bin/env python - -# Use Gouraud shading to mix colors. Requires Z-buffer. -# It changes the color assignments so fast that you see white. -# Left button pauses, middle rotates the square. ESC to quit. -# Experiment with a larger window (too slow) or smaller window (really white). - -from GL import * -from gl import * -import DEVICE -from math import * - -# -# tekenvlak : draw a square. with bgnpolygon -# -def tekenvlak (vc) : - bgnpolygon() - #vcarray (vc) - for i in vc : - c3f (i[1]) - v3f (i[0]) - endpolygon() - -# -# tekendoos : draw a box -# -def tekendoos (col) : - v = [(-5.0,0.0,0.0),(0.0,5.0,0.0),(5.0,0.0,0.0),(0.0,-5.0,0.0)] - vc = [(v[0],col[0]),(v[1],col[1]),(v[2],col[2]),(v[3],col[1])] - tekenvlak (vc) - -# -# initialize gl -# -def initgl () : - # - # open window - # - foreground () - keepaspect (1, 1) - prefposition (100, 500, 100, 500) - w = winopen ('PYTHON RGB') - keepaspect (1, 1) - winconstraints() - # - # configure pipeline (2buf, GOURAUD and RGBmode) - # - doublebuffer () - zbuffer (1) - shademodel (GOURAUD) - RGBmode () - gconfig () - # - # set viewing - # - perspective (900, 1, 1.0, 10.0) - polarview (10.0, 0, 0, 0) - # - # ask for the REDRAW and ESCKEY events - # - qdevice(DEVICE.MOUSE2) - qdevice(DEVICE.MOUSE3) - qdevice(DEVICE.REDRAW) - qdevice(DEVICE.ESCKEY) - - -# -# the color black -# -black = 0 -# -# GoForIT : use 2buf to redraw the object 2n times. index i is used as -# the (smoothly changing) rotation angle -# -def GoForIt(i) : - col = [(255.0,0.0,0.0), (0.0,255.0,0.0), (0.0,0.0,255.0)] - twist = 0 - freeze = 1 - while 1 : - if freeze <> 0 : - col[0],col[1],col[2] = col[1],col[2],col[0] - # - # clear z-buffer and clear background to light-blue - # - zclear() - cpack (black) - clear() - # - tekendoos (col) - # - swapbuffers() - # - if qtest() <> 0 : - dev, val = qread() - if dev == DEVICE.ESCKEY : - break - elif dev == DEVICE.REDRAW : - reshapeviewport () - elif dev == DEVICE.MOUSE2 and val <> 0 : - twist = twist + 30 - perspective (900, 1, 1.0, 10.0) - polarview (10.0, 0, 0, twist) - elif dev == DEVICE.MOUSE3 and val <> 0 : - freeze = 1 - freeze - - -# the main program -# -def main () : - initgl () - GoForIt (0) - -# -# exec main -# -main () diff --git a/Demo/sgi/gl/nurbs.py b/Demo/sgi/gl/nurbs.py deleted file mode 100755 index 6efef48bd1..0000000000 --- a/Demo/sgi/gl/nurbs.py +++ /dev/null @@ -1,171 +0,0 @@ -#! /usr/bin/env python - -# Rotate a 3D surface created using NURBS. -# -# Press left mouse button to toggle surface trimming. -# Press ESC to quit. -# -# See the GL manual for an explanation of NURBS. - -from gl import * -from GL import * -from DEVICE import * - -TRUE = 1 -FALSE = 0 -ORDER = 4 - -idmat = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1] - -surfknots = [-1, -1, -1, -1, 1, 1, 1, 1] - -def make_ctlpoints(): - c = [] - # - ci = [] - ci.append((-2.5, -3.7, 1.0)) - ci.append((-1.5, -3.7, 3.0)) - ci.append((1.5, -3.7, -2.5)) - ci.append((2.5, -3.7, -0.75)) - c.append(ci) - # - ci = [] - ci.append((-2.5, -2.0, 3.0)) - ci.append((-1.5, -2.0, 4.0)) - ci.append((1.5, -2.0, -3.0)) - ci.append((2.5, -2.0, 0.0)) - c.append(ci) - # - ci = [] - ci.append((-2.5, 2.0, 1.0)) - ci.append((-1.5, 2.0, 0.0)) - ci.append((1.5, 2.0, -1.0)) - ci.append((2.5, 2.0, 2.0)) - c.append(ci) - # - ci = [] - ci.append((-2.5, 2.7, 1.25)) - ci.append((-1.5, 2.7, 0.1)) - ci.append((1.5, 2.7, -0.6)) - ci.append((2.5, 2.7, 0.2)) - c.append(ci) - # - return c - -ctlpoints = make_ctlpoints() - -trimknots = [0., 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 4.] - -def make_trimpoints(): - c = [] - c.append((1.0, 0.0, 1.0)) - c.append((1.0, 1.0, 1.0)) - c.append((0.0, 2.0, 2.0)) - c.append((-1.0, 1.0, 1.0)) - c.append((-1.0, 0.0, 1.0)) - c.append((-1.0, -1.0, 1.0)) - c.append((0.0, -2.0, 2.0)) - c.append((1.0, -1.0, 1.0) ) - c.append((1.0, 0.0, 1.0)) - return c - -trimpoints = make_trimpoints() - -def main(): - init_windows() - setup_queue() - make_lights() - init_view() - # - set_scene() - setnurbsproperty( N_ERRORCHECKING, 1.0 ) - setnurbsproperty( N_PIXEL_TOLERANCE, 50.0 ) - trim_flag = 0 - draw_trim_surface(trim_flag) - # - while 1: - while qtest(): - dev, val = qread() - if dev == ESCKEY: - return - elif dev == WINQUIT: - dglclose(-1) # this for DGL only - return - elif dev == REDRAW: - reshapeviewport() - set_scene() - draw_trim_surface(trim_flag) - elif dev == LEFTMOUSE: - if val: - trim_flag = (not trim_flag) - set_scene() - draw_trim_surface(trim_flag) - -def init_windows(): - foreground() - #prefposition(0, 500, 0, 500) - wid = winopen('nurbs') - wintitle('NURBS Surface') - doublebuffer() - RGBmode() - gconfig() - lsetdepth(0x000, 0x7fffff) - zbuffer( TRUE ) - -def setup_queue(): - qdevice(ESCKEY) - qdevice(REDRAW) - qdevice(RIGHTMOUSE) - qdevice(WINQUIT) - qdevice(LEFTMOUSE) #trimming - -def init_view(): - mmode(MPROJECTION) - ortho( -4., 4., -4., 4., -4., 4. ) - # - mmode(MVIEWING) - loadmatrix(idmat) - # - lmbind(MATERIAL, 1) - -def set_scene(): - lmbind(MATERIAL, 0) - RGBcolor(150,150,150) - lmbind(MATERIAL, 1) - clear() - zclear() - # - rotate( 100, 'y' ) - rotate( 100, 'z' ) - -def draw_trim_surface(trim_flag): - bgnsurface() - nurbssurface(surfknots, surfknots, ctlpoints, ORDER, ORDER, N_XYZ) - if trim_flag: - bgntrim() - nurbscurve(trimknots, trimpoints, ORDER-1, N_STW) - endtrim() - endsurface() - swapbuffers() - -def make_lights(): - lmdef(DEFLMODEL,1,[]) - lmdef(DEFLIGHT,1,[]) - # - # define material #1 - # - a = [] - a = a + [EMISSION, 0.0, 0.0, 0.0] - a = a + [AMBIENT, 0.1, 0.1, 0.1] - a = a + [DIFFUSE, 0.6, 0.3, 0.3] - a = a + [SPECULAR, 0.0, 0.6, 0.0] - a = a + [SHININESS, 2.0] - a = a + [LMNULL] - lmdef(DEFMATERIAL, 1, a) - # - # turn on lighting - # - lmbind(LIGHT0, 1) - lmbind(LMODEL, 1) - -main() diff --git a/Demo/sgi/gl/zrgb.py b/Demo/sgi/gl/zrgb.py deleted file mode 100755 index 2ad68c997b..0000000000 --- a/Demo/sgi/gl/zrgb.py +++ /dev/null @@ -1,168 +0,0 @@ -#! /usr/bin/env python - -# zrgb (Requires Z buffer.) -# -# This program demostrates zbuffering 3 intersecting RGB polygons while -# in doublebuffer mode where, movement of the mouse with the LEFTMOUSE -# button depressed will, rotate the 3 polygons. This is done by compound -# rotations allowing continuous screen-oriented rotations. -# -# Press the "Esc" key to exit. - -from gl import * -from GL import * -from DEVICE import * - - -idmat=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1] - -def main() : - # - # old and new mouse position - # - # - mode = 0 - omx = 0 - mx = 0 - omy = 0 - my = 0 - # - objmat=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1] - # - initialize () - # - draw_scene (objmat) - # - while (1) : - # - dev, val = qread() - # - if dev == ESCKEY : - if val : - break - # exit when key is going up, not down - # this avoids the scenario where a window - # underneath this program's window - # would otherwise "eat up" the up- - # event of the Esc key being released - return - # - elif dev == REDRAW : - reshapeviewport() - draw_scene(objmat) - # - elif dev == LEFTMOUSE: - omx = mx - omy = my - if val : - mode = 1 - else : - mode = 0 - elif dev == MOUSEX : - omx = mx - mx = val - #print omx, mx - objmat = update_scene(objmat,mx,my,omx,omy,mode) - # - elif dev == MOUSEY : - omy = my - my = val - #print omy, my - objmat = update_scene(objmat,mx,my,omx,omy,mode) - # - - -def initialize () : - # - foreground () - keepaspect(5, 4) - w = winopen('Zbuffered RGB') - # - doublebuffer() - RGBmode() - gconfig() - zbuffer(1) - lsetdepth(0x0, 0x7FFFFF) - # - qdevice(ESCKEY) - qdevice(LEFTMOUSE) - qdevice(MOUSEX) - qdevice(MOUSEY) - -def update_scene (mat, mx, my, omx, omy, mode) : - # - if mode == 1 : - mat = orient(mat, mx, my, omx, omy) - draw_scene(mat) - return mat - -def orient (mat, mx, my, omx, omy) : - # - # - pushmatrix() - loadmatrix(idmat) - # - if mx - omx : rot (float (mx - omx), 'y') - if omy - my : rot (float (omy - my), 'x') - # - multmatrix(mat) - mat = getmatrix() - # - popmatrix() - # - return mat - -def draw_scene (mat) : - RGBcolor(40, 100, 200) - clear() - zclear() - # - perspective(400, 1.25, 30.0, 60.0) - translate(0.0, 0.0, -40.0) - multmatrix(mat) - # - # skews original view to show all polygons - # - rotate(-580, 'y') - draw_polys() - # - swapbuffers() - -polygon1 = [(-10.0,-10.0,0.0),(10.0,-10.0,0.0),(-10.0,10.0,0.0)] - -polygon2 = [(0.0,-10.0,-10.0),(0.0,-10.0,10.0),(0.0,5.0,-10.0)] - -polygon3 = [(-10.0,6.0,4.0),(-10.0,3.0,4.0),(4.0,-9.0,-10.0),(4.0,-6.0,-10.0)] - -def draw_polys(): - bgnpolygon() - cpack(0x0) - v3f(polygon1[0]) - cpack(0x007F7F7F) - v3f(polygon1[1]) - cpack(0x00FFFFFF) - v3f(polygon1[2]) - endpolygon() - # - bgnpolygon() - cpack(0x0000FFFF) - v3f(polygon2[0]) - cpack(0x007FFF00) - v3f(polygon2[1]) - cpack(0x00FF0000) - v3f(polygon2[2]) - endpolygon() - # - bgnpolygon() - cpack(0x0000FFFF) - v3f(polygon3[0]) - cpack(0x00FF00FF) - v3f(polygon3[1]) - cpack(0x00FF0000) - v3f(polygon3[2]) - cpack(0x00FF00FF) - v3f(polygon3[3]) - endpolygon() - - -main () diff --git a/Demo/sgi/sv/README b/Demo/sgi/sv/README deleted file mode 100644 index 38e51407fe..0000000000 --- a/Demo/sgi/sv/README +++ /dev/null @@ -1,23 +0,0 @@ -Demo programs for the SGI Video library for the Indigo (IRIX 4.0.5). - -These are more-or-less literal translations of the C programs from the -Indigo Video Programming Guide, by Sjoerd Mullender, with some changes -by Guido. - -Note that none of the example programs save any data to a file, -although this would be easy to do (e.g. individual grabbed frames -could be written as SGI image files using the imgfile module). - -We have written a Python program to record live video to file (within -the limits of the Indigo video board), and a suite of programs to -manipulate and display such files. At the moment we don't distribute -these programs, since the file format is, eh..., weird, to say the -least. However, if you are really interested we can mail you the -source. - -Also note that we haven't tried using video *output* yet. - -simpleinput.py Live video in a resizable window -rgbgrab.py Grab still frames -contcapt.py Continuous capturing -burstcapt.py Burst capturing diff --git a/Demo/sgi/sv/burstcapt.py b/Demo/sgi/sv/burstcapt.py deleted file mode 100755 index ce1e579f36..0000000000 --- a/Demo/sgi/sv/burstcapt.py +++ /dev/null @@ -1,52 +0,0 @@ -import sys -import sv, SV -import gl, GL, DEVICE - -def main(): - format = SV.RGB8_FRAMES - requestedwidth = SV.PAL_XMAX - queuesize = 30 - if sys.argv[1:]: - queuesize = eval(sys.argv[1]) - - v = sv.OpenVideo() - svci = (format, requestedwidth, 0, queuesize, 0) - - go = raw_input('Press return to capture ' + `queuesize` + ' frames: ') - result = v.CaptureBurst(svci) - svci, buffer, bitvec = result -## svci, buffer = result # XXX If bit vector not yet implemented - - print 'Captured', svci[3], 'frames, i.e.', len(buffer)/1024, 'K bytes' - - w, h = svci[1:3] - framesize = w * h - - gl.prefposition(300, 300+w-1, 100, 100+h-1) - gl.foreground() - win = gl.winopen('Burst Capture') - gl.RGBmode() - gl.gconfig() - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.ESCKEY) - - print 'Click left mouse for next frame' - - for i in range(svci[3]): - inverted_frame = sv.RGB8toRGB32(1, \ - buffer[i*framesize:(i+1)*framesize], w, h) - gl.lrectwrite(0, 0, w-1, h-1, inverted_frame) - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE and val == 1: - break - if dev == DEVICE.REDRAW: - gl.lrectwrite(0, 0, w-1, h-1, inverted_frame) - if dev == DEVICE.ESCKEY: - v.CloseVideo() - gl.winclose(win) - return - v.CloseVideo() - gl.winclose(win) - -main() diff --git a/Demo/sgi/sv/contcapt.py b/Demo/sgi/sv/contcapt.py deleted file mode 100755 index 6c0a0003bb..0000000000 --- a/Demo/sgi/sv/contcapt.py +++ /dev/null @@ -1,107 +0,0 @@ -import sys -import sv, SV -import gl, GL, DEVICE - -def main(): - format = SV.RGB8_FRAMES - framerate = 25 - queuesize = 16 - samplingrate = 2 - - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - width = SV.PAL_XMAX - height = SV.PAL_YMAX - framefreq = 25 - else: - width = SV.NTSC_XMAX - height = SV.NTSC_YMAX - framefreq = 30 - - # Allow resizing window if capturing RGB frames, which can be scaled - if format == SV.RGB8_FRAMES: - gl.keepaspect(width, height) - gl.maxsize(width, height) - gl.stepunit(8, 6) - gl.minsize(120, 90) - else: - if format == SV.YUV411_FRAMES_AND_BLANKING_BUFFER: - height = height + SV.BLANKING_BUFFER_SIZE - gl.prefposition(300, 300+width-1, 100, 100+height-1) - - # Open the window - gl.foreground() - win = gl.winopen('Continuous Capture') - gl.RGBmode() - gl.gconfig() - if format == SV.RGB8_FRAMES: - width, height = gl.getsize() - gl.pixmode(GL.PM_SIZE, 8) - else: - gl.pixmode(GL.PM_SIZE, 32) - - svci = (format, width, height, queuesize, samplingrate) - [svci] - - svci = v.InitContinuousCapture(svci) - width, height = svci[1:3] - [svci] - - hz = gl.getgdesc(GL.GD_TIMERHZ) - gl.noise(DEVICE.TIMER0, hz / framerate) - gl.qdevice(DEVICE.TIMER0) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - ndisplayed = 0 - lastfieldID = 0 - - while 1: - dev, val = gl.qread() - if dev == DEVICE.REDRAW: - oldw = width - oldh = height - width, height = gl.getsize() - if oldw != width or oldh != height: - v.EndContinuousCapture() - gl.viewport(0, width-1, 0, height-1) - svci = (svci[0], width, height) + svci[3:] - svci = v.InitContinuousCapture(svci) - width, height = svci[1:3] - [svci] - if ndisplayed: - print 'lost', - print fieldID/(svci[4]*2) - ndisplayed, - print 'frames' - ndisplayed = 0 - elif dev == DEVICE.TIMER0: - try: - captureData, fieldID = v.GetCaptureData() - except sv.error, val: - if val <> 'no data available': - print val - continue - if fieldID - lastfieldID <> 2*samplingrate: - print lastfieldID, fieldID - lastfieldID = fieldID - if svci[0] == SV.RGB8_FRAMES: - rgbbuf = captureData.InterleaveFields(1) - else: - rgbbuf = captureData.YUVtoRGB(1) - captureData.UnlockCaptureData() - gl.lrectwrite(0, 0, width-1, height-1, rgbbuf) - ndisplayed = ndisplayed + 1 - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - v.EndContinuousCapture() - v.CloseVideo() - gl.winclose(win) - print fieldID, ndisplayed, svci[4] - print 'lost', fieldID/(svci[4]*2) - ndisplayed, - print 'frames' - return - -main() diff --git a/Demo/sgi/sv/rgbgrab.py b/Demo/sgi/sv/rgbgrab.py deleted file mode 100755 index 8013a531f4..0000000000 --- a/Demo/sgi/sv/rgbgrab.py +++ /dev/null @@ -1,81 +0,0 @@ -import sys -import sv, SV -import gl, GL, DEVICE -import time - -def main(): - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - width = SV.PAL_XMAX - height = SV.PAL_YMAX - elif param[1] == SV.NTSC: - width = SV.NTSC_XMAX - height = SV.NTSC_YMAX - else: - print 'Unknown video standard', param[1] - sys.exit(1) - - # Initially all windows are half size - grabwidth, grabheight = width/2, height/2 - - # Open still window - gl.foreground() - gl.prefsize(grabwidth, grabheight) - still_win = gl.winopen('Grabbed frame') - gl.keepaspect(width, height) - gl.maxsize(width, height) - gl.winconstraints() - gl.RGBmode() - gl.gconfig() - gl.clear() - gl.pixmode(GL.PM_SIZE, 8) - - # Open live window - gl.foreground() - gl.prefsize(grabwidth, grabheight) - live_win = gl.winopen('Live video') - gl.keepaspect(width, height) - gl.maxsize(width, height) - gl.winconstraints() - - # Bind live video - v.SetSize(gl.getsize()) - v.BindGLWindow(live_win, SV.IN_REPLACE) - - print 'Use leftmouse to grab frame' - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - frame = None - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE and val == 0: - w, h, fields = v.CaptureOneFrame(SV.RGB8_FRAMES, \ - grabwidth, grabheight) - frame = sv.InterleaveFields(1, fields, w, h) - gl.winset(still_win) - gl.lrectwrite(0, 0, w - 1, h - 1, frame) - gl.winset(live_win) - if dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - v.CloseVideo() - gl.winclose(live_win) - gl.winclose(still_win) - break - if dev == DEVICE.REDRAW and val == still_win: - gl.winset(still_win) - gl.reshapeviewport() - gl.clear() - grabwidth, grabheight = gl.getsize() - if frame: - gl.lrectwrite(0, 0, w - 1, h - 1, frame) - gl.winset(live_win) - if dev == DEVICE.REDRAW and val == live_win: - v.SetSize(gl.getsize()) - v.BindGLWindow(live_win, SV.IN_REPLACE) - -main() diff --git a/Demo/sgi/sv/simpleinput.py b/Demo/sgi/sv/simpleinput.py deleted file mode 100755 index 97b75fafb0..0000000000 --- a/Demo/sgi/sv/simpleinput.py +++ /dev/null @@ -1,22 +0,0 @@ -import sv, SV -import gl, DEVICE - -def main(): - gl.foreground() - gl.prefsize(SV.PAL_XMAX, SV.PAL_YMAX) - win = gl.winopen('video test') - v = sv.OpenVideo() - params = [SV.VIDEO_MODE, SV.COMP, SV.BROADCAST, SV.PAL] - v.SetParam(params) - v.BindGLWindow(win, SV.IN_REPLACE) - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - while 1: - dev, val = gl.qread() - if dev in (DEVICE.ESCKEY, DEVICE.WINSHUT, DEVICE.WINQUIT): - v.CloseVideo() - gl.winclose(win) - return - -main() diff --git a/Demo/sgi/video/.cvsignore b/Demo/sgi/video/.cvsignore deleted file mode 100755 index 6d28ed64d1..0000000000 --- a/Demo/sgi/video/.cvsignore +++ /dev/null @@ -1 +0,0 @@ -VeditForm.fdc diff --git a/Demo/sgi/video/DisplayVideoIn.py b/Demo/sgi/video/DisplayVideoIn.py deleted file mode 100755 index 6dbc7bcc38..0000000000 --- a/Demo/sgi/video/DisplayVideoIn.py +++ /dev/null @@ -1,99 +0,0 @@ -# Live video input from display class. - -import gl -import GL - -# The live video input class. -# Only instantiate this if have_video is true! - -class DisplayVideoIn: - - # Initialize an instance. Arguments: - # vw, vh: size of the video window data to be captured. - # position defaults to 0, 0 but can be set later - def __init__(self, pktmax, vw, vh, type): - self.pktmax = pktmax - self.realwidth, self.realheight = vw, vh - if type <> 'rgb': - raise 'Incorrent video data type', type - self.type = type - self.width = vw - self.height = vh - # - # Open dummy window - # - gl.foreground() - gl.noport() - self.wid = gl.winopen('DisplayVideoIn') - - self.x0 = 0 - self.x1 = self.x0 + self.width - 1 - self.y0 = 0 - self.y1 = self.y0 + self.height - 1 - # Compute # full lines per packet - self.lpp = pktmax / self.linewidth() - if self.lpp <= 0: - raise 'No lines in packet', self.linewidth() - self.pktsize = self.lpp*self.linewidth() - self.data = None - self.old_data = None - self.dataoffset = 0 - self.lpos = 0 - self.hints = 0 - - # Change the size of the video being displayed. - - def resizevideo(self, vw, vh): - self.width = vw - self.height = vh - self.x1 = self.x0 + self.width - 1 - self.y1 = self.y0 + self.height - 1 - - def positionvideo(self, x, y): - self.x0 = x - self.y0 = y - self.x1 = self.x0 + self.width - 1 - self.y1 = self.y0 + self.height - 1 - - # Remove an instance. - # This turns off continuous capture. - - def close(self): - gl.winclose(self.wid) - - # Get the length in bytes of a video line - def linewidth(self): - return self.width*4 - - # Get the next video packet. - # This returns (lpos, data) where: - # - lpos is the line position - # - data is a piece of data - # The dimensions of data are: - # - pixel depth = 1 byte - # - scan line width = self.width (the vw argument to __init__()) - # - number of scan lines = self.lpp (PKTMAX / vw) - - def getnextpacket(self): - if not self.data or self.dataoffset >= len(self.data): - self.old_data = self.data - self.data = gl.readdisplay(self.x0, self.y0, \ - self.x1, self.y1, self.hints) - self.dataoffset = 0 - self.lpos = 0 - data = self.data[self.dataoffset:self.dataoffset+self.pktsize] - while self.old_data and \ - self.dataoffset+self.pktsize < len(self.data): - odata = self.old_data[self.dataoffset: \ - self.dataoffset+self.pktsize] - if odata <> data: - break - print 'skip', self.lpos - self.lpos = self.lpos + self.lpp - self.dataoffset = self.dataoffset + self.pktsize - data = self.data[self.dataoffset:\ - self.dataoffset+self.pktsize] - lpos = self.lpos - self.dataoffset = self.dataoffset + self.pktsize - self.lpos = self.lpos + self.lpp - return lpos, data diff --git a/Demo/sgi/video/Dsend.py b/Demo/sgi/video/Dsend.py deleted file mode 100755 index 7e197f7df9..0000000000 --- a/Demo/sgi/video/Dsend.py +++ /dev/null @@ -1,188 +0,0 @@ -#! /usr/bin/env python - -# Send live video UDP packets. -# Usage: Vsend [-b] [-h height] [-p port] [-s size] [-t ttl] [-w width] -# [host] .. - -import sys -import time -import struct -import string -import math -from socket import * -from SOCKET import * -import gl, GL, DEVICE -sys.path.append('/ufs/guido/src/video') -import DisplayVideoIn -import LiveVideoOut -import SV -import getopt -from IN import * - -from senddefs import * - -def usage(msg): - print msg - print 'usage: Vsend [-b] [-h height] [-p port] [-s size] [-t ttl] [-c type] [-m]', - print '[-w width] [host] ...' - print '-b : broadcast on local net' - print '-h height : window height (default ' + `DEFHEIGHT` + ')' - print '-p port : port to use (default ' + `DEFPORT` + ')' - print '-t ttl : time-to-live (multicast only; default 1)' - print '-s size : max packet size (default ' + `DEFPKTMAX` + ')' - print '-S size : use this packet size/window size' - print '-w width : window width (default ' + `DEFWIDTH` + ')' - print '-v : print packet rate' - print '-x xpos : set x position' - print '-y ypos : set y position' - print '[host] ...: host(s) to send to (default multicast to ' + \ - DEFMCAST + ')' - sys.exit(2) - - -def main(): - sys.stdout = sys.stderr - - hosts = [] - port = DEFPORT - ttl = -1 - pktmax = DEFPKTMAX - width = DEFWIDTH - height = DEFHEIGHT - vtype = 'rgb' - verbose = 0 - xpos = ypos = 0 - - try: - opts, args = getopt.getopt(sys.argv[1:], 'bh:p:s:S:t:w:vx:y:') - except getopt.error, msg: - usage(msg) - - try: - for opt, optarg in opts: - if opt == '-p': - port = string.atoi(optarg) - if opt == '-b': - host = '' - if opt == '-t': - ttl = string.atoi(optarg) - if opt == '-S': - pktmax = string.atoi(optarg) - vidmax = SV.PAL_XMAX*SV.PAL_YMAX - if vidmax <= pktmax: - width = SV.PAL_XMAX - height = SV.PAL_YMAX - pktmax = vidmax - else: - factor = float(vidmax)/float(pktmax) - factor = math.sqrt(factor) - width = int(SV.PAL_XMAX/factor)-7 - height = int(SV.PAL_YMAX/factor)-5 - print 'video:',width,'x',height, - print 'pktsize',width*height,'..', - print pktmax - if opt == '-s': - pktmax = string.atoi(optarg) - if opt == '-w': - width = string.atoi(optarg) - if opt == '-h': - height = string.atoi(optarg) - if opt == '-c': - vtype = optarg - if opt == '-v': - verbose = 1 - if opt == '-x': - xpos = string.atoi(optarg) - if opt == '-y': - ypos = string.atoi(optarg) - except string.atoi_error, msg: - usage('bad integer: ' + msg) - - for host in args: - hosts.append(gethostbyname(host)) - - if not hosts: - hosts.append(gethostbyname(DEFMCAST)) - - gl.foreground() - gl.prefsize(width, height) - gl.stepunit(8, 6) - wid = gl.winopen('Vsend') - gl.keepaspect(width, height) - gl.stepunit(8, 6) - gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) - gl.winconstraints() - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINFREEZE) - gl.qdevice(DEVICE.WINTHAW) - width, height = gl.getsize() - - lvo = LiveVideoOut.LiveVideoOut(wid, width, height, vtype) - - lvi = DisplayVideoIn.DisplayVideoIn(pktmax, width, height, vtype) - - if xpos or ypos: - lvi.positionvideo(xpos, ypos) - - s = socket(AF_INET, SOCK_DGRAM) - s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) - if ttl >= 0: - s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, chr(ttl)) - - frozen = 0 - - lasttime = int(time.time()) - nframe = 0 - while 1: - - if gl.qtest(): - dev, val = gl.qread() - if dev in (DEVICE.ESCKEY, \ - DEVICE.WINSHUT, DEVICE.WINQUIT): - break - if dev == DEVICE.WINFREEZE: - frozen = 1 - if dev == DEVICE.WINTHAW: - frozen = 0 - if dev == DEVICE.REDRAW: - w, h = gl.getsize() - x, y = gl.getorigin() - if (w, h) <> (width, height): - width, height = w, h - lvi.resizevideo(width, height) - lvo.resizevideo(width, height) - - rv = lvi.getnextpacket() - if not rv: - time.sleep(0.010) - continue - - pos, data = rv - print pos, len(data) # DBG - - if not frozen: - lvo.putnextpacket(pos, data) - - hdr = struct.pack('hhh', pos, width, height) - for host in hosts: - try: - # print len(hdr+data) # DBG - s.sendto(hdr + data, (host, port)) - except error, msg: # really socket.error - if msg[0] <> 121: # no buffer space available - raise error, msg # re-raise it - print 'Warning:', msg[1] - if pos == 0 and verbose: - nframe = nframe+1 - if int(time.time()) <> lasttime: - print nframe / (time.time()-lasttime), 'fps' - nframe = 0 - lasttime = int(time.time()) - - lvi.close() - lvo.close() - - -main() diff --git a/Demo/sgi/video/IN.py b/Demo/sgi/video/IN.py deleted file mode 100755 index ffc2852596..0000000000 --- a/Demo/sgi/video/IN.py +++ /dev/null @@ -1,54 +0,0 @@ -IPPROTO_IP = 0 -IPPROTO_ICMP = 1 -IPPROTO_IGMP = 2 -IPPROTO_GGP = 3 -IPPROTO_TCP = 6 -IPPROTO_EGP = 8 -IPPROTO_PUP = 12 -IPPROTO_UDP = 17 -IPPROTO_IDP = 22 -IPPROTO_TP = 29 -IPPROTO_XTP = 36 -IPPROTO_EON = 80 -IPPROTO_RAW = 255 -IPPROTO_MAX = 256 -IPPORT_RESERVED = 1024 -IPPORT_USERRESERVED = 5000 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = 0x00ffffff -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = 0x0000ffff -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = 0x000000ff -IN_CLASSD_NET = 0xf0000000 -IN_CLASSD_NSHIFT = 28 -IN_CLASSD_HOST = 0x0fffffff -INADDR_ANY = 0x00000000 -INADDR_BROADCAST = 0xffffffff -INADDR_LOOPBACK = 0x7F000001 -INADDR_UNSPEC_GROUP = 0xe0000000 -INADDR_ALLHOSTS_GROUP = 0xe0000001 -INADDR_MAX_LOCAL_GROUP = 0xe00000ff -INADDR_NONE = 0xffffffff -IN_LOOPBACKNET = 127 -IP_OPTIONS = 1 -IP_HDRINCL = 7 -IP_TOS = 8 -IP_TTL = 9 -IP_RECVOPTS = 10 -IP_RECVRETOPTS = 11 -IP_RECVDSTADDR = 12 -IP_RETOPTS = 13 -IP_MULTICAST_IF = 2 -IP_MULTICAST_TTL = 3 -IP_MULTICAST_LOOP = 4 -IP_ADD_MEMBERSHIP = 5 -IP_DROP_MEMBERSHIP = 6 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 -IP_MAX_MEMBERSHIPS = 20 diff --git a/Demo/sgi/video/LiveVideoIn.py b/Demo/sgi/video/LiveVideoIn.py deleted file mode 100755 index 661ea738b2..0000000000 --- a/Demo/sgi/video/LiveVideoIn.py +++ /dev/null @@ -1,139 +0,0 @@ -# Live video input class. -# Note that importing this module attempts to initialize video. - - -# Check if video is available. -# There are three reasons for failure here: -# (1) this version of Python may not have the sv or imageop modules; -# (2) this machine may not have a video board; -# (3) initializing the video board may fail for another reason. -# The global variable have_video is set to true iff we reall do have video. - -try: - import sv - import SV - import imageop - try: - v = sv.OpenVideo() - have_video = 1 - except sv.error: - have_video = 0 -except ImportError: - have_video = 0 - - -# The live video input class. -# Only instantiate this if have_video is true! - -class LiveVideoIn: - - # Initialize an instance. Arguments: - # vw, vh: size of the video window data to be captured. - # For some reason, vw MUST be a multiple of 4. - # Note that the data has to be cropped unless vw and vh are - # just right for the video board (vw:vh == 4:3 and vh even). - - def __init__(self, pktmax, vw, vh, type): - if not have_video: - raise RuntimeError, 'no video available' - if vw % 4 != 0: - raise ValueError, 'vw must be a multiple of 4' - self.pktmax = pktmax - realvw = vh*SV.PAL_XMAX/SV.PAL_YMAX - if realvw < vw: - realvw = vw - self.realwidth, self.realheight = v.QuerySize(realvw, vh) - if not type in ('rgb8', 'grey', 'mono', 'grey2', 'grey4'): - raise 'Incorrent video data type', type - self.type = type - if type in ('grey', 'grey4', 'grey2', 'mono'): - v.SetParam([SV.COLOR, SV.MONO, SV.INPUT_BYPASS, 1]) - else: - v.SetParam([SV.COLOR, SV.DEFAULT_COLOR, \ - SV.INPUT_BYPASS, 0]) - # Initialize capture - (mode, self.realwidth, self.realheight, qsize, rate) = \ - v.InitContinuousCapture(SV.RGB8_FRAMES, \ - self.realwidth, self.realheight, 1, 2) - self.width = vw - self.height = vh - self.x0 = (self.realwidth-self.width)/2 - self.x1 = self.x0 + self.width - 1 - self.y0 = (self.realheight-self.height)/2 - self.y1 = self.y0 + self.height - 1 - # Compute # full lines per packet - self.lpp = pktmax / self.linewidth() - self.pktsize = self.lpp*self.linewidth() - self.data = None - self.dataoffset = 0 - self.lpos = 0 - self.justright = (self.realwidth == self.width and \ - self.realheight == self.height) -## if not self.justright: -## print 'Want:', self.width, 'x', self.height, -## print '; grab:', self.realwidth, 'x', self.realheight - - # Change the size of the video being displayed. - - def resizevideo(self, vw, vh): - self.close() - self.__init__(self.pktmax, vw, vh, self.type) - - # Remove an instance. - # This turns off continuous capture. - - def close(self): - v.EndContinuousCapture() - - # Get the length in bytes of a video line - def linewidth(self): - if self.type == 'mono': - return (self.width+7)/8 - elif self.type == 'grey2': - return (self.width+3)/4 - elif self.type == 'grey4': - return (self.width+1)/2 - else: - return self.width - - # Get the next video packet. - # This returns (lpos, data) where: - # - lpos is the line position - # - data is a piece of data - # The dimensions of data are: - # - pixel depth = 1 byte - # - scan line width = self.width (the vw argument to __init__()) - # - number of scan lines = self.lpp (PKTMAX / vw) - - def getnextpacket(self): - if not self.data or self.dataoffset >= len(self.data): - try: - cd, id = v.GetCaptureData() - except sv.error: - return None - data = cd.InterleaveFields(1) - cd.UnlockCaptureData() - if self.justright: - self.data = data - else: - self.data = imageop.crop(data, 1, \ - self.realwidth, \ - self.realheight, \ - self.x0, self.y0, \ - self.x1, self.y1) - self.lpos = 0 - self.dataoffset = 0 - if self.type == 'mono': - self.data = imageop.dither2mono(self.data, \ - self.width, self.height) - elif self.type == 'grey2': - self.data = imageop.dither2grey2(self.data, \ - self.width, self.height) - elif self.type == 'grey4': - self.data = imageop.grey2grey4(self.data, \ - self.width, self.height) - data = self.data[self.dataoffset:self.dataoffset+self.pktsize] - lpos = self.lpos - self.dataoffset = self.dataoffset + self.pktsize - self.lpos = self.lpos + self.lpp - return lpos, data diff --git a/Demo/sgi/video/LiveVideoOut.py b/Demo/sgi/video/LiveVideoOut.py deleted file mode 100755 index 6ee1846d41..0000000000 --- a/Demo/sgi/video/LiveVideoOut.py +++ /dev/null @@ -1,130 +0,0 @@ -# Live video output (display video on the screen, presumably from the net) - -import gl -from VFile import Displayer - - -# Video output (displayer) class. - -class LiveVideoOut: - - # Call this to initialize things. Arguments: - # wid: the window id where the video is to be displayed (centered) - # vw, vh: size of the video image to be displayed - - def __init__(self, wid, vw, vh, type): - ##print 'Init', wid, xywh - ##print 'video', vw, vw - self.vw = vw - self.vh = vh - self.disp = Displayer() - if not type in ('rgb', 'rgb8', 'grey', 'mono', 'grey2', \ - 'grey4'): - raise 'Incorrent live video output type', type - if type == 'rgb': - info = (type, vw, vh, 0, 32, 0, 0, 0, 0) - else: - info = (type, vw, vh, 1, 8, 0, 0, 0, 0) - self.disp.setinfo(info) - self.wid = wid - oldwid = gl.winget() - gl.winset(wid) - self.disp.initcolormap() - self.reshapewindow() - gl.winset(oldwid) - - # Call this in response to every REDRAW event for the window - # or if the window size has changed for other reasons. - - def reshapewindow(self): - oldwid = gl.winget() - gl.winset(self.wid) - gl.reshapeviewport() - w, h = gl.getsize() - self.disp.xorigin = (w-self.vw)/2 - self.disp.yorigin = (h-self.vh)/2 - self.disp.clear() - gl.winset(oldwid) - - # Call this to change the size of the video images being displayed. - # Implies reshapewindow(). - - def resizevideo(self, vw, vh): - self.vw, self.vh = vw, vh - self.disp.setsize(vw, vh) - self.reshapewindow() - - # Return the number of bytes in one video line - def linewidth(self): - if self.disp.format == 'rgb': - return self.vw*4 - if self.disp.format == 'mono': - return (self.vw+7)/8 - elif self.disp.format == 'grey2': - return (self.vw+3)/4 - elif self.disp.format == 'grey4': - return (self.vw+1)/2 - else: - return self.vw - - # Call this to display the next video packet. Arguments: - # pos: line number where the packet begins - # data: image data of the packet - # (these correspond directly to the return values from - # LiveVideoIn.getnextpacket()). - - def putnextpacket(self, pos, data): - nline = len(data)/self.linewidth() - if nline*self.linewidth() <> len(data): - print 'Incorrect-sized video fragment ignored' - return - oldwid = gl.winget() - gl.winset(self.wid) - self.disp.showpartframe(data, None, (0, pos, self.vw, nline)) - gl.winset(oldwid) - - # Call this to close the window. - - def close(self): - pass - - # Call this to set optional mirroring of video - def setmirror(self, mirrored): - f, w, h, pf, c0, c1, c2, o, cp = self.disp.getinfo() - if type(pf) == type(()): - xpf, ypf = pf - else: - xpf = ypf = pf - xpf = abs(xpf) - if mirrored: - xpf = -xpf - info = (f, w, h, (xpf, ypf), c0, c1, c2, o, cp) - self.disp.setinfo(info) - self.disp.initcolormap() - self.disp.clear() - -# -# This derived class has one difference with the base class: the video is -# not displayed until an entire image has been gotten -# -class LiveVideoOutSlow(LiveVideoOut): - - # Reshapewindow - Realloc buffer. - # (is also called by __init__() indirectly) - - def reshapewindow(self): - LiveVideoOut.reshapewindow(self) - self.buffer = '\0'*self.linewidth()*self.vh - self.isbuffered = [] - - # putnextpacket - buffer incoming data until a complete - # image has been received - - def putnextpacket(self, pos, data): - if pos in self.isbuffered or pos == 0: - LiveVideoOut.putnextpacket(self, 0, self.buffer) - self.isbuffered = [] - self.isbuffered.append(pos) - bpos = pos * self.linewidth() - epos = bpos + len(data) - self.buffer = self.buffer[:bpos] + data + self.buffer[epos:] diff --git a/Demo/sgi/video/Makefile b/Demo/sgi/video/Makefile deleted file mode 100755 index 266ea52587..0000000000 --- a/Demo/sgi/video/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -all: v2i i2v - -v2i: v2i.o - $(CC) v2i.o -limage -o v2i - -i2v: i2v.o - $(CC) i2v.o -limage -o i2v diff --git a/Demo/sgi/video/OldVcopy.py b/Demo/sgi/video/OldVcopy.py deleted file mode 100755 index 0eb1c7f4f9..0000000000 --- a/Demo/sgi/video/OldVcopy.py +++ /dev/null @@ -1,148 +0,0 @@ -#! /usr/bin/env python - -# Copy a video file, interactively, frame-by-frame. - -import sys -import getopt -from gl import * -from DEVICE import * -import VFile -import VGrabber -import string -import imageop - -def report(time, iframe): - print 'Frame', iframe, ': t =', time - -def usage(): - sys.stderr.write('usage: Vcopy [-t type] [-m threshold] [-a] infile outfile\n') - sys.stderr.write('-t Convert to other type\n') - sys.stderr.write('-a Automatic\n') - sys.stderr.write('-m Convert grey to mono with threshold\n') - sys.stderr.write('-d Convert grey to mono with dithering\n') - sys.exit(2) - -def help(): - print 'Command summary:' - print 'n get next image from input' - print 'w write current image to output' - -class GrabbingVoutFile(VFile.VoutFile, VGrabber.VGrabber): - pass - -def main(): - foreground() - try: - opts, args = getopt.getopt(sys.argv[1:], 't:am:d') - except getopt.error, msg: - print msg - usage() - if len(args) <> 2: - usage() - [ifile, ofile] = args - print 'open film ', ifile - ifilm = VFile.VinFile(ifile) - print 'open output ', ofile - ofilm = GrabbingVoutFile(ofile) - - ofilm.setinfo(ifilm.getinfo()) - - use_grabber = 0 - continuous = 0 - tomono = 0 - tomonodither = 0 - for o, a in opts: - if o == '-t': - ofilm.format = a - use_grabber = 1 - if o == '-a': - continuous = 1 - if o == '-m': - if ifilm.format <> 'grey': - print '-m only supported for greyscale' - sys.exit(1) - tomono = 1 - treshold = string.atoi(a) - ofilm.format = 'mono' - if o == '-d': - if ifilm.format <> 'grey': - print '-m only supported for greyscale' - sys.exit(1) - tomonodither = 1 - ofilm.format = 'mono' - - ofilm.writeheader() - # - prefsize(ifilm.width, ifilm.height) - w = winopen(ifile) - qdevice(KEYBD) - qdevice(ESCKEY) - qdevice(WINQUIT) - qdevice(WINSHUT) - print 'qdevice calls done' - # - help() - # - time, data, cdata = ifilm.getnextframe() - ifilm.showframe(data, cdata) - iframe = 1 - report(time, iframe) - # - while 1: - if continuous: - dev = KEYBD - else: - dev, val = qread() - if dev in (ESCKEY, WINQUIT, WINSHUT): - break - if dev == REDRAW: - reshapeviewport() - elif dev == KEYBD: - if continuous: - c = '0' - else: - c = chr(val) - #XXX Debug - if c == 'R': - c3i(255,0,0) - clear() - if c == 'G': - c3i(0,255,0) - clear() - if c == 'B': - c3i(0,0,255) - clear() - if c == 'w' or continuous: - if use_grabber: - try: - data, cdata = ofilm.grabframe() - except VFile.Error, msg: - print msg - break - if tomono: - data = imageop.grey2mono(data, \ - ifilm.width, ifilm.height, \ - treshold) - if tomonodither: - data = imageop.dither2mono(data, \ - ifilm.width, ifilm.height) - ofilm.writeframe(time, data, cdata) - print 'Frame', iframe, 'written.' - if c == 'n' or continuous: - try: - time,data,cdata = ifilm.getnextframe() - ifilm.showframe(data, cdata) - iframe = iframe+1 - report(time, iframe) - except EOFError: - print 'EOF' - if continuous: - break - ringbell() - elif dev == INPUTCHANGE: - pass - else: - print '(dev, val) =', (dev, val) - ofilm.close() - -main() diff --git a/Demo/sgi/video/README b/Demo/sgi/video/README deleted file mode 100644 index 6abe698795..0000000000 --- a/Demo/sgi/video/README +++ /dev/null @@ -1,113 +0,0 @@ -CMIF video tools -================ - -This directory contains Python and C programs to manipulate files -containing digitized video in the "CMIF video format". - -An introduction to using the basic tools is in the file "video.doc". - -A description of the video file format is in the file "cmif-film.ms" -(troff/nroff -ms input). - - -History -------- - -We started this in October 1991, when we had a large framegrabber -board on loan from SGI for a few weeks: we developed a movie recording -program and added numerous features, including still frame capture and -synchronous sound recording using a second machine (the machine -holding the framegrabber board didn't have audio). - -During the following months, when we started using and processing the -recorded film fragments, the "CMIF video format" was revised several -times, and we eventually created an object-oriented interface for -reading and writing various incarnations of these files, called VFile. -(This module is also used by our flagship application, the CMIF -editor, not in this directory but in /ufs/guido/mm/.) - -When we got our own Indigo entry-level video board (in June 1992) and -a version of the Irix video library that supported capturing PAL -format (in August 1992), Sjoerd added an interface to the video -library to Python (sv) and Guido wrote Vrec.py (based upon a still -frame grabber by Sjoerd, in turn based upon SGI demo code in C) to -record a movie using it. Vrec was soon followed by modernized -versions of the other programs (Vinfo, Vplay, Vtime) and an -interactive editor (Vedit). Finally, VFile was rewritten for more -modularity, functionality and robustness, and various other tools were -added as needed. Also, new options were added to existing tools, and -several new video file formats were added. - - Guido van Rossum - Jack Jansen - Sjoerd Mullender - - -Overview of files ------------------ - -cmif-film.ms description of the CMIF video file format (more than a - little out of date -- read the source for VFile for - more info about new file formats) - - -These are programs with a command line interface: - -Vrec.py record video movies using the Indigo video library and - board - -Vplay.py play video movies - -Vinfo.py show statistics on movies - -Vtime.py Copy a video file, manipulating the time codes (e.g. - faster/slower, or regenerate time codes, or drop - frames too close apart) - -Vcopy.py Universal video file copying tool. Can manipulate the - time codes, change the type, size, and packfactor. - Subsumes Vtime.py. - -Vmkjpeg.py compress an rgb or grey video file to jpeg[grey] format - -Vunjpeg.py expand a jpeg[grey] video file to rgb or grey format - -Vfix.py truncate the scan line width of a video file to - a multiple of 4 ('grey' images only) - -Vedit.py interactive video editing program (uses the FORMS library) - -Vsend.py unicast or multicast live video as UDP packets - -Vreceive.py receive transmissions from Vsend - -Vaddcache.py add a "cached index" to a video file, for faster playing - -Vrecb.py like Vrec.py but uses "burst capture" -- somewhat specialized - -Dsend.py like Vsend.py but sends screen snapshots (to Vreceive.py) - -DisplayVideoIn.py Like LiveVideoIn.py but reads screen snapshots - -rgb2video.py combine a sequence of rgb image files into a CMIF video file - -video2rgb.py split a CMIF video file into a sequence of rgb image files - - -These modules and files are used by the above programs: - -VFile.py classes that read and write CMIF video files - -Viewer.py two viewer classes used by Vedit - -LiveVideoIn.py live video input class, used by Vsend - -LiveVideoOut.py live video output class, used by Vsend and Vreceive - -imgconv.py Image conversion subroutines for rgb2video.py - -senddefs.py Defaults shared by Vsend and Vreceice - -watchcursor.py Generally useful module to define a watch cursor in GL - -VeditForm.fd FORMS' fdesign definition for Vedit's form diff --git a/Demo/sgi/video/VCR.py b/Demo/sgi/video/VCR.py deleted file mode 100755 index 535a7da3eb..0000000000 --- a/Demo/sgi/video/VCR.py +++ /dev/null @@ -1,534 +0,0 @@ -import fcntl -import IOCTL -from IOCTL import * -import sys -import struct -import select -import posix -import time - -DEVICE='/dev/ttyd2' - -class UnixFile: - def open(self, name, mode): - self.fd = posix.open(name, mode) - return self - - def read(self, len): - return posix.read(self.fd, len) - - def write(self, data): - dummy = posix.write(self.fd, data) - - def flush(self): - pass - - def fileno(self): - return self.fd - - def close(self): - dummy = posix.close(self.fd) - -def packttyargs(*args): - if type(args) <> type(()): - raise 'Incorrect argtype for packttyargs' - if type(args[0]) == type(1): - iflag, oflag, cflag, lflag, line, chars = args - elif type(args[0]) == type(()): - if len(args) <> 1: - raise 'Only 1 argument expected' - iflag, oflag, cflag, lflag, line, chars = args[0] - elif type(args[0]) == type([]): - if len(args) <> 1: - raise 'Only 1 argument expected' - [iflag, oflag, cflag, lflag, line, chars] = args[0] - str = struct.pack('hhhhb', iflag, oflag, cflag, lflag, line) - for c in chars: - str = str + c - return str - -def nullttyargs(): - chars = ['\0']*IOCTL.NCCS - return packttyargs(0, 0, 0, 0, 0, chars) - -def unpackttyargs(str): - args = str[:-IOCTL.NCCS] - rawchars = str[-IOCTL.NCCS:] - chars = [] - for c in rawchars: - chars.append(c) - iflag, oflag, cflag, lflag, line = struct.unpack('hhhhb', args) - return (iflag, oflag, cflag, lflag, line, chars) - -def initline(name): - fp = UnixFile().open(name, 2) - ofp = fp - fd = fp.fileno() - rv = fcntl.ioctl(fd, IOCTL.TCGETA, nullttyargs()) - iflag, oflag, cflag, lflag, line, chars = unpackttyargs(rv) - iflag = iflag & ~(INPCK|ISTRIP|INLCR|IUCLC|IXON|IXOFF) - oflag = oflag & ~OPOST - cflag = B9600|CS8|CREAD|CLOCAL - lflag = lflag & ~(ISIG|ICANON|ECHO|TOSTOP) - chars[VMIN] = chr(1) - chars[VTIME] = chr(0) - arg = packttyargs(iflag, oflag, cflag, lflag, line, chars) - dummy = fcntl.ioctl(fd, IOCTL.TCSETA, arg) - return fp, ofp - -# -# -error = 'VCR.error' - -# Commands/replies: -COMPLETION = '\x01' -ACK ='\x0a' -NAK ='\x0b' - -NUMBER_N = 0x30 -ENTER = '\x40' - -EXP_7= '\xde' -EXP_8= '\xdf' - -CL ='\x56' -CTRL_ENABLE = EXP_8 + '\xc6' -SEARCH_DATA = EXP_8 + '\x93' -ADDR_SENSE = '\x60' - -PLAY ='\x3a' -STOP ='\x3f' -EJECT='\x2a' -FF ='\xab' -REW ='\xac' -STILL='\x4f' -STEP_FWD ='\x2b' # Was: '\xad' -FM_SELECT=EXP_8 + '\xc8' -FM_STILL=EXP_8 + '\xcd' -PREVIEW=EXP_7 + '\x9d' -REVIEW=EXP_7 + '\x9e' -DM_OFF=EXP_8 + '\xc9' -DM_SET=EXP_8 + '\xc4' -FWD_SHUTTLE='\xb5' -REV_SHUTTLE='\xb6' -EM_SELECT=EXP_8 + '\xc0' -N_FRAME_REC=EXP_8 + '\x92' -SEARCH_PREROLL=EXP_8 + '\x90' -EDIT_PB_STANDBY=EXP_8 + '\x96' -EDIT_PLAY=EXP_8 + '\x98' -AUTO_EDIT=EXP_7 + '\x9c' - -IN_ENTRY=EXP_7 + '\x90' -IN_ENTRY_RESET=EXP_7 + '\x91' -IN_ENTRY_SET=EXP_7 + '\x98' -IN_ENTRY_INC=EXP_7 + '\x94' -IN_ENTRY_DEC=EXP_7 + '\x95' -IN_ENTRY_SENSE=EXP_7 + '\x9a' - -OUT_ENTRY=EXP_7 + '\x92' -OUT_ENTRY_RESET=EXP_7 + '\x93' -OUT_ENTRY_SET=EXP_7 + '\x99' -OUT_ENTRY_INC=EXP_7 + '\x96' -OUT_ENTRY_DEC=EXP_7 + '\x98' -OUT_ENTRY_SENSE=EXP_7 + '\x9b' - -MUTE_AUDIO = '\x24' -MUTE_AUDIO_OFF = '\x25' -MUTE_VIDEO = '\x26' -MUTE_VIDEO_OFF = '\x27' -MUTE_AV = EXP_7 + '\xc6' -MUTE_AV_OFF = EXP_7 + '\xc7' - -DEBUG=0 - -class VCR: - def __init__(self): - self.ifp, self.ofp = initline(DEVICE) - self.busy_cmd = None - self.async = 0 - self.cb = None - self.cb_arg = None - - def _check(self): - if self.busy_cmd: - raise error, 'Another command active: '+self.busy_cmd - - def _endlongcmd(self, name): - if not self.async: - self.waitready() - return 1 - self.busy_cmd = name - return 'VCR BUSY' - - def fileno(self): - return self.ifp.fileno() - - def setasync(self, async): - self.async = async - - def setcallback(self, cb, arg): - self.setasync(1) - self.cb = cb - self.cb_arg = arg - - def poll(self): - if not self.async: - raise error, 'Can only call poll() in async mode' - if not self.busy_cmd: - return - if self.testready(): - if self.cb: - apply(self.cb, (self.cb_arg,)) - - def _cmd(self, cmd): - if DEBUG: - print '>>>',`cmd` - self.ofp.write(cmd) - self.ofp.flush() - - def _waitdata(self, len, tout): - rep = '' - while len > 0: - if tout == None: - ready, d1, d2 = select.select( \ - [self.ifp], [], []) - else: - ready, d1, d2 = select.select( \ - [self.ifp], [], [], tout) - if ready == []: -## if rep: -## print 'FLUSHED:', `rep` - return None - data = self.ifp.read(1) - if DEBUG: - print '<<<',`data` - if data == NAK: - return NAK - rep = rep + data - len = len - 1 - return rep - - def _reply(self, len): - data = self._waitdata(len, 10) - if data == None: - raise error, 'Lost contact with VCR' - return data - - def _getnumber(self, len): - data = self._reply(len) - number = 0 - for c in data: - digit = ord(c) - NUMBER_N - if digit < 0 or digit > 9: - raise error, 'Non-digit in number'+`c` - number = number*10 + digit - return number - - def _iflush(self): - dummy = self._waitdata(10000, 0) -## if dummy: -## print 'IFLUSH:', dummy - - def simplecmd(self,cmd): - self._iflush() - for ch in cmd: - self._cmd(ch) - rep = self._reply(1) - if rep == NAK: - return 0 - elif rep <> ACK: - raise error, 'Unexpected reply:' + `rep` - return 1 - - def replycmd(self, cmd): - if not self.simplecmd(cmd[:-1]): - return 0 - self._cmd(cmd[-1]) - - def _number(self, number, digits): - if number < 0: - raise error, 'Unexpected negative number:'+ `number` - maxnum = pow(10, digits) - if number > maxnum: - raise error, 'Number too big' - while maxnum > 1: - number = number % maxnum - maxnum = maxnum / 10 - digit = number / maxnum - ok = self.simplecmd(chr(NUMBER_N + digit)) - if not ok: - raise error, 'Error while transmitting number' - - def initvcr(self, *optarg): - timeout = None - if optarg <> (): - timeout = optarg[0] - starttime = time.time() - self.busy_cmd = None - self._iflush() - while 1: -## print 'SENDCL' - self._cmd(CL) - rep = self._waitdata(1, 2) -## print `rep` - if rep in ( None, CL, NAK ): - if timeout: - if time.time() - starttime > timeout: - raise error, \ - 'No reply from VCR' - continue - break - if rep <> ACK: - raise error, 'Unexpected reply:' + `rep` - dummy = self.simplecmd(CTRL_ENABLE) - - def waitready(self): - rep = self._waitdata(1, None) - if rep == None: - raise error, 'Unexpected None reply from waitdata' - if rep not in (COMPLETION, ACK): - self._iflush() - raise error, 'Unexpected waitready reply:' + `rep` - self.busy_cmd = None - - def testready(self): - rep = self._waitdata(1, 0) - if rep == None: - return 0 - if rep not in (COMPLETION, ACK): - self._iflush() - raise error, 'Unexpected waitready reply:' + `rep` - self.busy_cmd = None - return 1 - - def play(self): return self.simplecmd(PLAY) - def stop(self): return self.simplecmd(STOP) - def ff(self): return self.simplecmd(FF) - def rew(self): return self.simplecmd(REW) - def eject(self):return self.simplecmd(EJECT) - def still(self):return self.simplecmd(STILL) - def step(self): return self.simplecmd(STEP_FWD) - - def goto(self, (h, m, s, f)): - if not self.simplecmd(SEARCH_DATA): - return 0 - self._number(h, 2) - self._number(m, 2) - self._number(s, 2) - self._number(f, 2) - if not self.simplecmd(ENTER): - return 0 - return self._endlongcmd('goto') - - # XXXX TC_SENSE doesn't seem to work - def faulty_where(self): - self._check() - self._cmd(TC_SENSE) - h = self._getnumber(2) - m = self._getnumber(2) - s = self._getnumber(2) - f = self._getnumber(2) - return (h, m, s, f) - - def where(self): - return self.addr2tc(self.sense()) - - def sense(self): - self._check() - self._cmd(ADDR_SENSE) - num = self._getnumber(5) - return num - - def addr2tc(self, num): - f = num % 25 - num = num / 25 - s = num % 60 - num = num / 60 - m = num % 60 - h = num / 60 - return (h, m, s, f) - - def tc2addr(self, (h, m, s, f)): - return ((h*60 + m)*60 + s)*25 + f - - def fmmode(self, mode): - self._check() - if mode == 'off': - arg = 0 - elif mode == 'buffer': - arg = 1 - elif mode == 'dnr': - arg = 2 - else: - raise error, 'fmmode arg should be off, buffer or dnr' - if not self.simplecmd(FM_SELECT): - return 0 - self._number(arg, 1) - if not self.simplecmd(ENTER): - return 0 - return 1 - - def mute(self, mode, value): - self._check() - if mode == 'audio': - cmds = (MUTE_AUDIO_OFF, MUTE_AUDIO) - elif mode == 'video': - cmds = (MUTE_VIDEO_OFF, MUTE_VIDEO) - elif mode == 'av': - cmds = (MUTE_AV_OFF, MUTE_AV) - else: - raise error, 'mute type should be audio, video or av' - cmd = cmds[value] - return self.simplecmd(cmd) - - def editmode(self, mode): - self._check() - if mode == 'off': - a0 = a1 = a2 = 0 - elif mode == 'format': - a0 = 4 - a1 = 7 - a2 = 4 - elif mode == 'asmbl': - a0 = 1 - a1 = 7 - a2 = 4 - elif mode == 'insert-video': - a0 = 2 - a1 = 4 - a2 = 0 - else: - raise 'editmode should be off,format,asmbl or insert-video' - if not self.simplecmd(EM_SELECT): - return 0 - self._number(a0, 1) - self._number(a1, 1) - self._number(a2, 1) - if not self.simplecmd(ENTER): - return 0 - return 1 - - def autoedit(self): - self._check() - return self._endlongcmd(AUTO_EDIT) - - def nframerec(self, num): - if not self.simplecmd(N_FRAME_REC): - return 0 - self._number(num, 4) - if not self.simplecmd(ENTER): - return 0 - return self._endlongcmd('nframerec') - - def fmstill(self): - if not self.simplecmd(FM_STILL): - return 0 - return self._endlongcmd('fmstill') - - def preview(self): - if not self.simplecmd(PREVIEW): - return 0 - return self._endlongcmd('preview') - - def review(self): - if not self.simplecmd(REVIEW): - return 0 - return self._endlongcmd('review') - - def search_preroll(self): - if not self.simplecmd(SEARCH_PREROLL): - return 0 - return self._endlongcmd('search_preroll') - - def edit_pb_standby(self): - if not self.simplecmd(EDIT_PB_STANDBY): - return 0 - return self._endlongcmd('edit_pb_standby') - - def edit_play(self): - if not self.simplecmd(EDIT_PLAY): - return 0 - return self._endlongcmd('edit_play') - - def dmcontrol(self, mode): - self._check() - if mode == 'off': - return self.simplecmd(DM_OFF) - if mode == 'multi freeze': - num = 1000 - elif mode == 'zoom freeze': - num = 2000 - elif mode == 'digital slow': - num = 3000 - elif mode == 'freeze': - num = 4011 - else: - raise error, 'unknown dmcontrol argument: ' + `mode` - if not self.simplecmd(DM_SET): - return 0 - self._number(num, 4) - if not self.simplecmd(ENTER): - return 0 - return 1 - - def fwdshuttle(self, num): - if not self.simplecmd(FWD_SHUTTLE): - return 0 - self._number(num, 1) - return 1 - - def revshuttle(self, num): - if not self.simplecmd(REV_SHUTTLE): - return 0 - self._number(num, 1) - return 1 - - def getentry(self, which): - self._check() - if which == 'in': - cmd = IN_ENTRY_SENSE - elif which == 'out': - cmd = OUT_ENTRY_SENSE - self.replycmd(cmd) - h = self._getnumber(2) - m = self._getnumber(2) - s = self._getnumber(2) - f = self._getnumber(2) - return (h, m, s, f) - - def inentry(self, arg): - return self.ioentry(arg, (IN_ENTRY, IN_ENTRY_RESET, \ - IN_ENTRY_SET, IN_ENTRY_INC, IN_ENTRY_DEC)) - - def outentry(self, arg): - return self.ioentry(arg, (OUT_ENTRY, OUT_ENTRY_RESET, \ - OUT_ENTRY_SET, OUT_ENTRY_INC, OUT_ENTRY_DEC)) - - def ioentry(self, arg, (Load, Clear, Set, Inc, Dec)): - self._check() - if type(arg) == type(()): - h, m, s, f = arg - if not self.simplecmd(Set): - return 0 - self._number(h,2) - self._number(m,2) - self._number(s,2) - self._number(f,2) - if not self.simplecmd(ENTER): - return 0 - return 1 - elif arg == 'reset': - cmd = Clear - elif arg == 'load': - cmd = Load - elif arg == '+': - cmd = Inc - elif arg == '-': - cmd = Dec - else: - raise error, 'Arg should be +,-,reset,load or (h,m,s,f)' - return self.simplecmd(cmd) - - def cancel(self): - d = self.simplecmd(CL) - self.busy_cmd = None diff --git a/Demo/sgi/video/VFile.py b/Demo/sgi/video/VFile.py deleted file mode 100755 index 2f435d4fd1..0000000000 --- a/Demo/sgi/video/VFile.py +++ /dev/null @@ -1,1193 +0,0 @@ -# Classes to read and write CMIF video files. -# (For a description of the CMIF video format, see cmif-file.ms.) - - -# Layers of functionality: -# -# VideoParams: maintain essential parameters of a video file -# Displayer: display a frame in a window (with some extra parameters) -# BasicVinFile: read a CMIF video file -# BasicVoutFile: write a CMIF video file -# VinFile: BasicVinFile + Displayer -# VoutFile: BasicVoutFile + Displayer -# -# XXX Future extension: -# BasicVinoutFile: supports overwriting of individual frames - - -# Imported modules - -import sys -try: - import gl - import GL - import GET - no_gl = 0 -except ImportError: - no_gl = 1 -import colorsys -import imageop - - -# Exception raised for various occasions - -Error = 'VFile.Error' # file format errors -CallError = 'VFile.CallError' # bad call -AssertError = 'VFile.AssertError' # internal malfunction - - -# Max nr. of colormap entries to use - -MAXMAP = 4096 - 256 - - -# Parametrizations of colormap handling based on color system. -# (These functions are used via eval with a constructed argument!) - -def conv_grey(l, x, y): - return colorsys.yiq_to_rgb(l, 0, 0) - -def conv_grey4(l, x, y): - return colorsys.yiq_to_rgb(l*17, 0, 0) - -def conv_mono(l, x, y): - return colorsys.yiq_to_rgb(l*255, 0, 0) - -def conv_yiq(y, i, q): - return colorsys.yiq_to_rgb(y, (i-0.5)*1.2, q-0.5) - -def conv_hls(l, h, s): - return colorsys.hls_to_rgb(h, l, s) - -def conv_hsv(v, h, s): - return colorsys.hsv_to_rgb(h, s, v) - -def conv_rgb(r, g, b): - raise Error, 'Attempt to make RGB colormap' - -def conv_rgb8(rgb, d1, d2): - rgb = int(rgb*255.0) - r = (rgb >> 5) & 0x07 - g = (rgb ) & 0x07 - b = (rgb >> 3) & 0x03 - return (r/7.0, g/7.0, b/3.0) - -def conv_jpeg(r, g, b): - raise Error, 'Attempt to make RGB colormap (jpeg)' - -conv_jpeggrey = conv_grey -conv_grey2 = conv_grey - - -# Choose one of the above based upon a color system name - -def choose_conversion(format): - try: - return eval('conv_' + format) - except: - raise Error, 'Unknown color system: ' + `format` - - -# Inverses of the above - -def inv_grey(r, g, b): - y, i, q = colorsys.rgb_to_yiq(r, g, b) - return y, 0, 0 - -def inv_yiq(r, g, b): - y, i, q = colorsys.rgb_to_yiq(r, g, b) - return y, i/1.2 + 0.5, q + 0.5 - -def inv_hls(r, g, b): - h, l, s = colorsys.rgb_to_hls(r, g, b) - return l, h, s - -def inv_hsv(r, g, b): - h, s, v = colorsys.rgb_to_hsv(r, g, b) - return v, h, s - -def inv_rgb(r, g, b): - raise Error, 'Attempt to invert RGB colormap' - -def inv_rgb8(r, g, b): - r = int(r*7.0) - g = int(g*7.0) - b = int(b*7.0) - rgb = ((r&7) << 5) | ((b&3) << 3) | (g&7) - return rgb / 255.0, 0, 0 - -def inv_jpeg(r, g, b): - raise Error, 'Attempt to invert RGB colormap (jpeg)' - -inv_jpeggrey = inv_grey - - -# Choose one of the above based upon a color system name - -def choose_inverse(format): - try: - return eval('inv_' + format) - except: - raise Error, 'Unknown color system: ' + `format` - - -# Predicate to see whether this is an entry level (non-XS) Indigo. -# If so we can lrectwrite 8-bit wide pixels into a window in RGB mode - -def is_entry_indigo(): - # XXX hack, hack. We should call gl.gversion() but that doesn't - # exist in earlier Python versions. Therefore we check the number - # of bitplanes *and* the size of the monitor. - xmax = gl.getgdesc(GL.GD_XPMAX) - if xmax <> 1024: return 0 - ymax = gl.getgdesc(GL.GD_YPMAX) - if ymax != 768: return 0 - r = gl.getgdesc(GL.GD_BITS_NORM_SNG_RED) - g = gl.getgdesc(GL.GD_BITS_NORM_SNG_GREEN) - b = gl.getgdesc(GL.GD_BITS_NORM_SNG_BLUE) - return (r, g, b) == (3, 3, 2) - - -# Predicate to see whether this machine supports pixmode(PM_SIZE) with -# values 1 or 4. -# -# XXX Temporarily disabled, since it is unclear which machines support -# XXX which pixelsizes. -# -# XXX The XS appears to support 4 bit pixels, but (looking at osview) it -# XXX seems as if the conversion is done by the kernel (unpacking ourselves -# XXX is faster than using PM_SIZE=4) - -def support_packed_pixels(): - return 0 # To be architecture-dependent - - - -# Tables listing bits per pixel for some formats - -bitsperpixel = { \ - 'rgb': 32, \ - 'rgb8': 8, \ - 'grey': 8, \ - 'grey4': 4, \ - 'grey2': 2, \ - 'mono': 1, \ - 'compress': 32, \ -} - -bppafterdecomp = {'jpeg': 32, 'jpeggrey': 8} - - -# Base class to manage video format parameters - -class VideoParams: - - # Initialize an instance. - # Set all parameters to something decent - # (except width and height are set to zero) - - def __init__(self): - # Essential parameters - self.frozen = 0 # if set, can't change parameters - self.format = 'grey' # color system used - # Choose from: grey, rgb, rgb8, hsv, yiq, hls, jpeg, jpeggrey, - # mono, grey2, grey4 - self.width = 0 # width of frame - self.height = 0 # height of frame - self.packfactor = 1, 1 # expansion using rectzoom - # Colormap info - self.c0bits = 8 # bits in first color dimension - self.c1bits = 0 # bits in second color dimension - self.c2bits = 0 # bits in third color dimension - self.offset = 0 # colormap index offset (XXX ???) - self.chrompack = 0 # set if separate chrominance data - self.setderived() - self.decompressor = None - - # Freeze the parameters (disallow changes) - - def freeze(self): - self.frozen = 1 - - # Unfreeze the parameters (allow changes) - - def unfreeze(self): - self.frozen = 0 - - # Set some values derived from the standard info values - - def setderived(self): - if self.frozen: raise AssertError - if bitsperpixel.has_key(self.format): - self.bpp = bitsperpixel[self.format] - else: - self.bpp = 0 - xpf, ypf = self.packfactor - self.xpf = abs(xpf) - self.ypf = abs(ypf) - self.mirror_image = (xpf < 0) - self.upside_down = (ypf < 0) - self.realwidth = self.width / self.xpf - self.realheight = self.height / self.ypf - - # Set colormap info - - def setcmapinfo(self): - stuff = 0, 0, 0, 0, 0 - if self.format in ('rgb8', 'grey'): - stuff = 8, 0, 0, 0, 0 - if self.format == 'grey4': - stuff = 4, 0, 0, 0, 0 - if self.format == 'grey2': - stuff = 2, 0, 0, 0, 0 - if self.format == 'mono': - stuff = 1, 0, 0, 0, 0 - self.c0bits, self.c1bits, self.c2bits, \ - self.offset, self.chrompack = stuff - - # Set the frame width and height (e.g. from gl.getsize()) - - def setsize(self, width, height): - if self.frozen: raise CallError - width = (width/self.xpf)*self.xpf - height = (height/self.ypf)*self.ypf - self.width, self.height = width, height - self.setderived() - - # Retrieve the frame width and height (e.g. for gl.prefsize()) - - def getsize(self): - return (self.width, self.height) - - # Set the format - - def setformat(self, format): - if self.frozen: raise CallError - self.format = format - self.setderived() - self.setcmapinfo() - - # Get the format - - def getformat(self): - return self.format - - # Set the packfactor - - def setpf(self, pf): - if self.frozen: raise CallError - if type(pf) == type(1): - pf = (pf, pf) - if type(pf) is not type(()) or len(pf) <> 2: raise CallError - self.packfactor = pf - self.setderived() - - # Get the packfactor - - def getpf(self): - return self.packfactor - - # Set all parameters - - def setinfo(self, values): - if self.frozen: raise CallError - self.setformat(values[0]) - self.setpf(values[3]) - self.setsize(values[1], values[2]) - (self.c0bits, self.c1bits, self.c2bits, \ - self.offset, self.chrompack) = values[4:9] - if self.format == 'compress' and len(values) > 9: - self.compressheader = values[9] - self.setderived() - - # Retrieve all parameters in a format suitable for a subsequent - # call to setinfo() - - def getinfo(self): - return (self.format, self.width, self.height, self.packfactor,\ - self.c0bits, self.c1bits, self.c2bits, self.offset, \ - self.chrompack) - - def getcompressheader(self): - return self.compressheader - - def setcompressheader(self, ch): - self.compressheader = ch - - # Write the relevant bits to stdout - - def printinfo(self): - print 'Format: ', self.format - print 'Size: ', self.width, 'x', self.height - print 'Pack: ', self.packfactor, '; chrom:', self.chrompack - print 'Bpp: ', self.bpp - print 'Bits: ', self.c0bits, self.c1bits, self.c2bits - print 'Offset: ', self.offset - - # Calculate data size, if possible - # (Not counting frame header or cdata size) - - def calcframesize(self): - if not self.bpp: raise CallError - size = self.width/self.xpf * self.height/self.ypf - size = (size * self.bpp + 7) / 8 - return size - - # Decompress a possibly compressed frame. This method is here - # since you sometimes want to use it on a VFile instance and sometimes - # on a Displayer instance. - # - # XXXX This should also handle jpeg. Actually, the whole mechanism - # should be much more of 'ihave/iwant' style, also allowing you to - # read, say, greyscale images from a color movie. - - def decompress(self, data): - if self.format <> 'compress': - return data - if not self.decompressor: - import cl - scheme = cl.QueryScheme(self.compressheader) - self.decompressor = cl.OpenDecompressor(scheme) - headersize = self.decompressor.ReadHeader(self.compressheader) - width = self.decompressor.GetParam(cl.IMAGE_WIDTH) - height = self.decompressor.GetParam(cl.IMAGE_HEIGHT) - params = [cl.ORIGINAL_FORMAT, cl.RGBX, \ - cl.ORIENTATION, cl.BOTTOM_UP, \ - cl.FRAME_BUFFER_SIZE, width*height*cl.BytesPerPixel(cl.RGBX)] - self.decompressor.SetParams(params) - data = self.decompressor.Decompress(1, data) - return data - - -# Class to display video frames in a window. -# It is the caller's responsibility to ensure that the correct window -# is current when using showframe(), initcolormap(), clear() and clearto() - -class Displayer(VideoParams): - - # Initialize an instance. - # This does not need a current window - - def __init__(self): - if no_gl: - raise RuntimeError, \ - 'no gl module available, so cannot display' - VideoParams.__init__(self) - # User-settable parameters - self.magnify = 1.0 # frame magnification factor - self.xorigin = 0 # x frame offset - self.yorigin = 0 # y frame offset (from bottom) - self.quiet = 0 # if set, don't print messages - self.fallback = 1 # allow fallback to grey - # Internal flags - self.colormapinited = 0 # must initialize window - self.skipchrom = 0 # don't skip chrominance data - self.color0 = None # magic, used by clearto() - self.fixcolor0 = 0 # don't need to fix color0 - self.mustunpack = (not support_packed_pixels()) - - # setinfo() must reset some internal flags - - def setinfo(self, values): - VideoParams.setinfo(self, values) - self.colormapinited = 0 - self.skipchrom = 0 - self.color0 = None - self.fixcolor0 = 0 - - # Show one frame, initializing the window if necessary - - def showframe(self, data, chromdata): - self.showpartframe(data, chromdata, \ - (0,0,self.width,self.height)) - - def showpartframe(self, data, chromdata, (x,y,w,h)): - pmsize = self.bpp - xpf, ypf = self.xpf, self.ypf - if self.upside_down: - gl.pixmode(GL.PM_TTOB, 1) - if self.mirror_image: - gl.pixmode(GL.PM_RTOL, 1) - if self.format in ('jpeg', 'jpeggrey'): - import jpeg - data, width, height, bytes = jpeg.decompress(data) - pmsize = bytes*8 - elif self.format == 'compress': - data = self.decompress(data) - pmsize = 32 - elif self.format in ('mono', 'grey4'): - if self.mustunpack: - if self.format == 'mono': - data = imageop.mono2grey(data, \ - w/xpf, h/ypf, 0x20, 0xdf) - elif self.format == 'grey4': - data = imageop.grey42grey(data, \ - w/xpf, h/ypf) - pmsize = 8 - elif self.format == 'grey2': - data = imageop.grey22grey(data, w/xpf, h/ypf) - pmsize = 8 - if not self.colormapinited: - self.initcolormap() - if self.fixcolor0: - gl.mapcolor(self.color0) - self.fixcolor0 = 0 - xfactor = yfactor = self.magnify - xfactor = xfactor * xpf - yfactor = yfactor * ypf - if chromdata and not self.skipchrom: - cp = self.chrompack - cx = int(x*xfactor*cp) + self.xorigin - cy = int(y*yfactor*cp) + self.yorigin - cw = (w+cp-1)/cp - ch = (h+cp-1)/cp - gl.rectzoom(xfactor*cp, yfactor*cp) - gl.pixmode(GL.PM_SIZE, 16) - gl.writemask(self.mask - ((1 << self.c0bits) - 1)) - gl.lrectwrite(cx, cy, cx + cw - 1, cy + ch - 1, \ - chromdata) - # - if pmsize < 32: - gl.writemask((1 << self.c0bits) - 1) - gl.pixmode(GL.PM_SIZE, pmsize) - w = w/xpf - h = h/ypf - x = x/xpf - y = y/ypf - gl.rectzoom(xfactor, yfactor) - x = int(x*xfactor)+self.xorigin - y = int(y*yfactor)+self.yorigin - gl.lrectwrite(x, y, x + w - 1, y + h - 1, data) - gl.gflush() - - # Initialize the window: set RGB or colormap mode as required, - # fill in the colormap, and clear the window - - def initcolormap(self): - self.colormapinited = 1 - self.color0 = None - self.fixcolor0 = 0 - if self.format in ('rgb', 'jpeg', 'compress'): - self.set_rgbmode() - gl.RGBcolor(200, 200, 200) # XXX rather light grey - gl.clear() - return - # This only works on an Entry-level Indigo from IRIX 4.0.5 - if self.format == 'rgb8' and is_entry_indigo() and \ - gl.gversion() == 'GL4DLG-4.0.': # Note trailing '.'! - self.set_rgbmode() - gl.RGBcolor(200, 200, 200) # XXX rather light grey - gl.clear() - gl.pixmode(GL.PM_SIZE, 8) - return - self.set_cmode() - self.skipchrom = 0 - if self.offset == 0: - self.mask = 0x7ff - else: - self.mask = 0xfff - if not self.quiet: - sys.stderr.write('Initializing color map...') - self._initcmap() - gl.clear() - if not self.quiet: - sys.stderr.write(' Done.\n') - - # Set the window in RGB mode (may be overridden for Glx window) - - def set_rgbmode(self): - gl.RGBmode() - gl.gconfig() - - # Set the window in colormap mode (may be overridden for Glx window) - - def set_cmode(self): - gl.cmode() - gl.gconfig() - - # Clear the window to a default color - - def clear(self): - if not self.colormapinited: raise CallError - if gl.getdisplaymode() in (GET.DMRGB, GET.DMRGBDOUBLE): - gl.RGBcolor(200, 200, 200) # XXX rather light grey - gl.clear() - return - gl.writemask(0xffffffff) - gl.clear() - - # Clear the window to a given RGB color. - # This may steal the first color index used; the next call to - # showframe() will restore the intended mapping for that index - - def clearto(self, r, g, b): - if not self.colormapinited: raise CallError - if gl.getdisplaymode() in (GET.DMRGB, GET.DMRGBDOUBLE): - gl.RGBcolor(r, g, b) - gl.clear() - return - index = self.color0[0] - self.fixcolor0 = 1 - gl.mapcolor(index, r, g, b) - gl.writemask(0xffffffff) - gl.clear() - gl.gflush() - - # Do the hard work for initializing the colormap (internal). - # This also sets the current color to the first color index - # used -- the caller should never change this since it is used - # by clear() and clearto() - - def _initcmap(self): - map = [] - if self.format in ('mono', 'grey4') and self.mustunpack: - convcolor = conv_grey - else: - convcolor = choose_conversion(self.format) - maxbits = gl.getgdesc(GL.GD_BITS_NORM_SNG_CMODE) - if maxbits > 11: - maxbits = 11 - c0bits = self.c0bits - c1bits = self.c1bits - c2bits = self.c2bits - if c0bits+c1bits+c2bits > maxbits: - if self.fallback and c0bits < maxbits: - # Cannot display frames in this mode, use grey - self.skipchrom = 1 - c1bits = c2bits = 0 - convcolor = choose_conversion('grey') - else: - raise Error, 'Sorry, '+`maxbits`+ \ - ' bits max on this machine' - maxc0 = 1 << c0bits - maxc1 = 1 << c1bits - maxc2 = 1 << c2bits - if self.offset == 0 and maxbits == 11: - offset = 2048 - else: - offset = self.offset - if maxbits <> 11: - offset = offset & ((1< type(()): - raise Error, filename + ': Bad (w,h,pf) info' - if len(x) == 3: - width, height, packfactor = x - if packfactor == 0 and version < 3.0: - format = 'rgb' - c0bits = 0 - elif len(x) == 2 and version <= 1.0: - width, height = x - packfactor = 2 - else: - raise Error, filename + ': Bad (w,h,pf) info' - if type(packfactor) is type(0): - if packfactor == 0: packfactor = 1 - xpf = ypf = packfactor - else: - xpf, ypf = packfactor - if upside_down: - ypf = -ypf - packfactor = (xpf, ypf) - xpf = abs(xpf) - ypf = abs(ypf) - width = (width/xpf) * xpf - height = (height/ypf) * ypf - # - # Return (version, values) - # - values = (format, width, height, packfactor, \ - c0bits, c1bits, c2bits, offset, chrompack, compressheader) - return (version, values) - - -# Read a *frame* header -- separate functions per version. -# Return (timecode, datasize, chromdatasize). -# Raise EOFError if end of data is reached. -# Raise Error if data is bad. - -def readv0frameheader(fp): - line = fp.readline() - if not line or line == '\n': raise EOFError - try: - t = eval(line[:-1]) - except: - raise Error, 'Bad 0.0 frame header' - return (t, 0, 0) - -def readv1frameheader(fp): - line = fp.readline() - if not line or line == '\n': raise EOFError - try: - t, datasize = eval(line[:-1]) - except: - raise Error, 'Bad 1.0 frame header' - return (t, datasize, 0) - -def readv2frameheader(fp): - line = fp.readline() - if not line or line == '\n': raise EOFError - try: - t, datasize = eval(line[:-1]) - except: - raise Error, 'Bad 2.0 frame header' - return (t, datasize, 0) - -def readv3frameheader(fp): - line = fp.readline() - if not line or line == '\n': raise EOFError - try: - t, datasize, chromdatasize = x = eval(line[:-1]) - except: - raise Error, 'Bad 3.[01] frame header' - return x - - -# Write a CMIF video file header (always version 3.1) - -def writefileheader(fp, values): - (format, width, height, packfactor, \ - c0bits, c1bits, c2bits, offset, chrompack) = values - # - # Write identifying header - # - fp.write('CMIF video 3.1\n') - # - # Write color encoding info - # - if format in ('rgb', 'jpeg'): - data = (format, 0) - elif format in ('grey', 'jpeggrey', 'mono', 'grey2', 'grey4'): - data = (format, c0bits) - else: - data = (format, (c0bits, c1bits, c2bits, chrompack, offset)) - fp.write(`data`+'\n') - # - # Write frame geometry info - # - data = (width, height, packfactor) - fp.write(`data`+'\n') - -def writecompressfileheader(fp, cheader, values): - (format, width, height, packfactor, \ - c0bits, c1bits, c2bits, offset, chrompack) = values - # - # Write identifying header - # - fp.write('CMIF video 3.1\n') - # - # Write color encoding info - # - data = (format, cheader) - fp.write(`data`+'\n') - # - # Write frame geometry info - # - data = (width, height, packfactor) - fp.write(`data`+'\n') - - -# Basic class for reading CMIF video files - -class BasicVinFile(VideoParams): - - def __init__(self, filename): - if type(filename) != type(''): - fp = filename - filename = '???' - elif filename == '-': - fp = sys.stdin - else: - fp = open(filename, 'r') - self.initfp(fp, filename) - - def initfp(self, fp, filename): - VideoParams.__init__(self) - self.fp = fp - self.filename = filename - self.version, values = readfileheader(fp, filename) - self.setinfo(values) - self.freeze() - if self.version == 0.0: - w, h, pf = self.width, self.height, self.packfactor - if pf == 0: - self._datasize = w*h*4 - else: - self._datasize = (w/pf) * (h/pf) - self._readframeheader = self._readv0frameheader - elif self.version == 1.0: - self._readframeheader = readv1frameheader - elif self.version == 2.0: - self._readframeheader = readv2frameheader - elif self.version in (3.0, 3.1): - self._readframeheader = readv3frameheader - else: - raise Error, \ - filename + ': Bad version: ' + `self.version` - self.framecount = 0 - self.atframeheader = 1 - self.eofseen = 0 - self.errorseen = 0 - try: - self.startpos = self.fp.tell() - self.canseek = 1 - except IOError: - self.startpos = -1 - self.canseek = 0 - - def _readv0frameheader(self, fp): - t, ds, cs = readv0frameheader(fp) - ds = self._datasize - return (t, ds, cs) - - def close(self): - self.fp.close() - del self.fp - del self._readframeheader - - def rewind(self): - if not self.canseek: - raise Error, self.filename + ': can\'t seek' - self.fp.seek(self.startpos) - self.framecount = 0 - self.atframeheader = 1 - self.eofseen = 0 - self.errorseen = 0 - - def warmcache(self): - print '[BasicVinFile.warmcache() not implemented]' - - def printinfo(self): - print 'File: ', self.filename - print 'Size: ', getfilesize(self.filename) - print 'Version: ', self.version - VideoParams.printinfo(self) - - def getnextframe(self): - t, ds, cs = self.getnextframeheader() - data, cdata = self.getnextframedata(ds, cs) - return (t, data, cdata) - - def skipnextframe(self): - t, ds, cs = self.getnextframeheader() - self.skipnextframedata(ds, cs) - return t - - def getnextframeheader(self): - if self.eofseen: raise EOFError - if self.errorseen: raise CallError - if not self.atframeheader: raise CallError - self.atframeheader = 0 - try: - return self._readframeheader(self.fp) - except Error, msg: - self.errorseen = 1 - # Patch up the error message - raise Error, self.filename + ': ' + msg - except EOFError: - self.eofseen = 1 - raise EOFError - - def getnextframedata(self, ds, cs): - if self.eofseen: raise EOFError - if self.errorseen: raise CallError - if self.atframeheader: raise CallError - if ds: - data = self.fp.read(ds) - if len(data) < ds: - self.eofseen = 1 - raise EOFError - else: - data = '' - if cs: - cdata = self.fp.read(cs) - if len(cdata) < cs: - self.eofseen = 1 - raise EOFError - else: - cdata = '' - self.atframeheader = 1 - self.framecount = self.framecount + 1 - return (data, cdata) - - def skipnextframedata(self, ds, cs): - if self.eofseen: raise EOFError - if self.errorseen: raise CallError - if self.atframeheader: raise CallError - # Note that this won't raise EOFError for a partial frame - # since there is no easy way to tell whether a seek - # ended up beyond the end of the file - if self.canseek: - self.fp.seek(ds + cs, 1) # Relative seek - else: - dummy = self.fp.read(ds + cs) - del dummy - self.atframeheader = 1 - self.framecount = self.framecount + 1 - - -# Subroutine to return a file's size in bytes - -def getfilesize(filename): - import os, stat - try: - st = os.stat(filename) - return st[stat.ST_SIZE] - except os.error: - return 0 - - -# Derived class implementing random access and index cached in the file - -class RandomVinFile(BasicVinFile): - - def initfp(self, fp, filename): - BasicVinFile.initfp(self, fp, filename) - self.index = [] - - def warmcache(self): - if len(self.index) == 0: - try: - self.readcache() - except Error: - self.buildcache() - else: - print '[RandomVinFile.warmcache(): too late]' - self.rewind() - - def buildcache(self): - self.index = [] - self.rewind() - while 1: - try: dummy = self.skipnextframe() - except EOFError: break - self.rewind() - - def writecache(self): - # Raises IOerror if the file is not seekable & writable! - import marshal - if len(self.index) == 0: - self.buildcache() - if len(self.index) == 0: - raise Error, self.filename + ': No frames' - self.fp.seek(0, 2) - self.fp.write('\n/////CMIF/////\n') - pos = self.fp.tell() - data = `pos` - data = '\n-*-*-CMIF-*-*-\n' + data + ' '*(15-len(data)) + '\n' - try: - marshal.dump(self.index, self.fp) - self.fp.write(data) - self.fp.flush() - finally: - self.rewind() - - def readcache(self): - # Raises Error if there is no cache in the file - import marshal - if len(self.index) <> 0: - raise CallError - self.fp.seek(-32, 2) - data = self.fp.read() - if data[:16] <> '\n-*-*-CMIF-*-*-\n' or data[-1:] <> '\n': - self.rewind() - raise Error, self.filename + ': No cache' - pos = eval(data[16:-1]) - self.fp.seek(pos) - try: - self.index = marshal.load(self.fp) - except TypeError: - self.rewind() - raise Error, self.filename + ': Bad cache' - self.rewind() - - def getnextframeheader(self): - if self.framecount < len(self.index): - return self._getindexframeheader(self.framecount) - if self.framecount > len(self.index): - raise AssertError, \ - 'managed to bypass index?!?' - rv = BasicVinFile.getnextframeheader(self) - if self.canseek: - pos = self.fp.tell() - self.index.append((rv, pos)) - return rv - - def getrandomframe(self, i): - t, ds, cs = self.getrandomframeheader(i) - data, cdata = self.getnextframedata(ds, cs) - return t, data, cdata - - def getrandomframeheader(self, i): - if i < 0: raise ValueError, 'negative frame index' - if not self.canseek: - raise Error, self.filename + ': can\'t seek' - if i < len(self.index): - return self._getindexframeheader(i) - if len(self.index) > 0: - rv = self.getrandomframeheader(len(self.index)-1) - else: - self.rewind() - rv = self.getnextframeheader() - while i > self.framecount: - self.skipnextframedata() - rv = self.getnextframeheader() - return rv - - def _getindexframeheader(self, i): - (rv, pos) = self.index[i] - self.fp.seek(pos) - self.framecount = i - self.atframeheader = 0 - self.eofseen = 0 - self.errorseen = 0 - return rv - - -# Basic class for writing CMIF video files - -class BasicVoutFile(VideoParams): - - def __init__(self, filename): - if type(filename) != type(''): - fp = filename - filename = '???' - elif filename == '-': - fp = sys.stdout - else: - fp = open(filename, 'w') - self.initfp(fp, filename) - - def initfp(self, fp, filename): - VideoParams.__init__(self) - self.fp = fp - self.filename = filename - self.version = 3.1 # In case anyone inquries - - def flush(self): - self.fp.flush() - - def close(self): - self.fp.close() - del self.fp - - def prealloc(self, nframes): - if not self.frozen: raise CallError - data = '\xff' * (self.calcframesize() + 64) - pos = self.fp.tell() - for i in range(nframes): - self.fp.write(data) - self.fp.seek(pos) - - def writeheader(self): - if self.frozen: raise CallError - if self.format == 'compress': - writecompressfileheader(self.fp, self.compressheader, \ - self.getinfo()) - else: - writefileheader(self.fp, self.getinfo()) - self.freeze() - self.atheader = 1 - self.framecount = 0 - - def rewind(self): - self.fp.seek(0) - self.unfreeze() - self.atheader = 1 - self.framecount = 0 - - def printinfo(self): - print 'File: ', self.filename - VideoParams.printinfo(self) - - def writeframe(self, t, data, cdata): - if data: ds = len(data) - else: ds = 0 - if cdata: cs = len(cdata) - else: cs = 0 - self.writeframeheader(t, ds, cs) - self.writeframedata(data, cdata) - - def writeframeheader(self, t, ds, cs): - if not self.frozen: self.writeheader() - if not self.atheader: raise CallError - data = `(t, ds, cs)` - n = len(data) - if n < 63: data = data + ' '*(63-n) - self.fp.write(data + '\n') - self.atheader = 0 - - def writeframedata(self, data, cdata): - if not self.frozen or self.atheader: raise CallError - if data: self.fp.write(data) - if cdata: self.fp.write(cdata) - self.atheader = 1 - self.framecount = self.framecount + 1 - - -# Classes that combine files with displayers: - -class VinFile(RandomVinFile, Displayer): - - def initfp(self, fp, filename): - Displayer.__init__(self) - RandomVinFile.initfp(self, fp, filename) - - def shownextframe(self): - t, data, cdata = self.getnextframe() - self.showframe(data, cdata) - return t - - -class VoutFile(BasicVoutFile, Displayer): - - def initfp(self, fp, filename): - Displayer.__init__(self) -## Grabber.__init__(self) # XXX not needed - BasicVoutFile.initfp(self, fp, filename) - - -# Simple test program (VinFile only) - -def test(): - import time - if sys.argv[1:]: filename = sys.argv[1] - else: filename = 'film.video' - vin = VinFile(filename) - vin.printinfo() - gl.foreground() - gl.prefsize(vin.getsize()) - wid = gl.winopen(filename) - vin.initcolormap() - t0 = time.time() - while 1: - try: t, data, cdata = vin.getnextframe() - except EOFError: break - dt = t0 + t - time.time() - if dt > 0: time.time(dt) - vin.showframe(data, cdata) - time.sleep(2) diff --git a/Demo/sgi/video/VGrabber.py b/Demo/sgi/video/VGrabber.py deleted file mode 100755 index 242ebf2231..0000000000 --- a/Demo/sgi/video/VGrabber.py +++ /dev/null @@ -1,80 +0,0 @@ -# Class to grab frames from a window. -# (This has fewer user-settable parameters than Displayer.) -# It is the caller's responsibility to initialize the window and to -# ensure that it is current when using grabframe() - -import gl, GL -import VFile -import GET -from VFile import Error - -class VGrabber(VFile.VideoParams): - - # XXX The constructor of VideoParams is just fine, for now - - # Grab a frame. - # Return (data, chromdata) just like getnextframe(). - - def grabframe(self): - grabber = choose_grabber(self.format) - return grabber(self.width, self.height, self.packfactor) - - -# Choose one of the grabber functions below based upon a color system name - -def choose_grabber(format): - try: - return eval('grab_' + format) - except: - raise Error, 'Unknown color system: ' + `format` - - -# Routines to grab data, per color system (only a few really supported). -# (These functions are used via eval with a constructed argument!) - -def grab_rgb(w, h, pf): - if gl.getdisplaymode() <> GET.DMRGB: - raise Error, 'Sorry, can only grab rgb in single-buf rgbmode' - if pf <> (1, 1): - raise Error, 'Sorry, only grab rgb with packfactor (1,1)' - return gl.lrectread(0, 0, w-1, h-1), None - -def grab_rgb8(w, h, pf): - if gl.getdisplaymode() <> GET.DMRGB: - raise Error, 'Sorry, can only grab rgb8 in single-buf rgbmode' - if pf <> (1, 1): - raise Error, 'Sorry, can only grab rgb8 with packfactor (1,1)' - if not VFile.is_entry_indigo(): - raise Error, 'Sorry, can only grab rgb8 on entry level Indigo' - # XXX Dirty Dirty here. - # XXX Set buffer to cmap mode, grab image and set it back. - gl.cmode() - gl.gconfig() - gl.pixmode(GL.PM_SIZE, 8) - data = gl.lrectread(0, 0, w-1, h-1) - data = data[:w*h] # BUG FIX for python lrectread - gl.RGBmode() - gl.gconfig() - gl.pixmode(GL.PM_SIZE, 32) - return data, None - -def grab_grey(w, h, pf): - raise Error, 'Sorry, grabbing grey not implemented' - -def grab_yiq(w, h, pf): - raise Error, 'Sorry, grabbing yiq not implemented' - -def grab_hls(w, h, pf): - raise Error, 'Sorry, grabbing hls not implemented' - -def grab_hsv(w, h, pf): - raise Error, 'Sorry, grabbing hsv not implemented' - -def grab_jpeg(w, h, pf): - data, dummy = grab_rgb(w, h, pf) - import jpeg - data = jpeg.compress(data, w, h, 4) - return data, None - -def grab_jpeggrey(w, h, pf): - raise Error, 'sorry, grabbing jpeggrey not implemented' diff --git a/Demo/sgi/video/Vaddcache.py b/Demo/sgi/video/Vaddcache.py deleted file mode 100755 index 4c8fdac1c6..0000000000 --- a/Demo/sgi/video/Vaddcache.py +++ /dev/null @@ -1,80 +0,0 @@ -#! /usr/bin/env python - -# Add a cache to each of the files given as command line arguments - - -# Usage: -# -# Vaddcache [file] ... - - -# Options: -# -# file ... : file(s) to modify; default film.video - - -import sys -sys.path.append('/ufs/guido/src/video') -import VFile -import getopt - - -# Global options - -# None - - -# Main program -- mostly command line parsing - -def main(): - opts, args = getopt.getopt(sys.argv[1:], '') - if not args: - args = ['film.video'] - sts = 0 - for filename in args: - if process(filename): - sts = 1 - sys.exit(sts) - - -# Process one file - -def process(filename): - try: - fp = open(filename, 'r+') - vin = VFile.RandomVinFile(fp) - vin.filename = filename - except IOError, msg: - sys.stderr.write(filename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(filename + ': EOF in video file\n') - return 1 - - try: - vin.readcache() - hascache = 1 - except VFile.Error: - hascache = 0 - - if hascache: - sys.stderr.write(filename + ': already has a cache\n') - vin.close() - return 1 - - vin.printinfo() - vin.warmcache() - vin.writecache() - vin.close() - return 0 - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vb.py b/Demo/sgi/video/Vb.py deleted file mode 100755 index e1b06d6836..0000000000 --- a/Demo/sgi/video/Vb.py +++ /dev/null @@ -1,962 +0,0 @@ -#! /usr/bin/env python - -# Video bag of tricks: record video(+audio) in various formats and modes - -# XXX To do: -# - audio -# - improve user interface -# - help button? -# - command line options to set initial settings -# - save settings in a file -# - ...? - -import sys -import time -import getopt -import string -import os -sts = os.system('makemap') # Must be before "import fl" to work -import sgi -import gl -import GL -import DEVICE -import fl -import FL -import flp -import watchcursor -import sv -import SV -import VFile -import VGrabber -import imageop -sys.path.append('/ufs/jack/src/av/vcr') -import VCR -try: - import cl -except ImportError: - cl = None - -ARROW = 0 -WATCH = 1 -watchcursor.defwatch(WATCH) - -def main(): -## fl.set_graphics_mode(0, 1) - vb = VideoBagOfTricks() - while 1: - dummy = fl.do_forms() - [dummy] - -StopCapture = 'StopCapture' - -VideoFormatLabels = ['Video off', 'rgb8', 'grey8', 'grey4', 'grey2', \ - 'grey2 dith', 'mono dith', 'mono thresh', 'rgb24', 'rgb24-jpeg', \ - 'compress'] -VideoFormats = ['', 'rgb8', 'grey', 'grey4', 'grey2', \ - 'grey2', 'mono', 'mono', 'rgb', 'jpeg', 'compress'] - -VideoModeLabels = ['Continuous', 'Burst', 'Single frame', 'VCR sync'] -[VM_CONT, VM_BURST, VM_SINGLE, VM_VCR] = range(1, 5) - -AudioFormatLabels = ['Audio off', \ - '16 bit mono', '16 bit stereo', '8 bit mono', '8 bit stereo'] -[A_OFF, A_16_MONO, A_16_STEREO, A_8_MONO, A_8_STEREO] = range(1, 6) - -VcrSpeedLabels = ['normal', '1/3', '1/5', '1/10', '1/30', 'single-step'] -VcrSpeeds = [None, 5, 4, 3, 2, 1, 0] - -RgbSizeLabels = ['full', 'quarter', 'sixteenth'] - -# init file stuff: -if os.environ.has_key('HOME'): - HOME=os.environ['HOME'] -else: - HOME='.' -VB_INIT_FILE=HOME + '/.Vb_init' - -VB_INIT_KEYS=['vfile', 'vmode', 'mono_thresh', 'vformat', 'comp_scheme', \ - 'rgb24_size', 'afile', 'aformat'] - -class VideoBagOfTricks: - - # Init/close stuff - - def __init__(self): - self.window = None - formdef = flp.parse_form('VbForm', 'form') - flp.create_full_form(self, formdef) - self.setdefaults() - if self.vmode <> VM_CONT: - self.g_cont.hide_object() - if self.vmode <> VM_BURST: - self.g_burst.hide_object() - if self.vmode <> VM_SINGLE: - self.g_single.hide_object() - if self.vmode <> VM_VCR: - self.g_vcr.hide_object() - if self.vformat <> 'compress': - self.g_compress.hide_object() - - self.openvideo() - self.makewindow() - self.bindvideo() - if self.use_24: - self.optfullsizewindow() - self.showform() - fl.set_event_call_back(self.do_event) - - def close(self): - self.close_video() - self.close_audio() - self.savedefaults() - raise SystemExit, 0 - - def showform(self): - # Get position of video window - gl.winset(self.window) - x, y = gl.getorigin() - width, height = gl.getsize() - # Calculate position of form window - x1 = x + width + 10 - x2 = x1 + int(self.form.w) - 1 - y2 = y + height - 1 - y1 = y2 - int(self.form.h) + 1 - # Position and show form window - gl.prefposition(x1, x2, y1, y2) - self.form.show_form(FL.PLACE_FREE, FL.TRUE, 'Vb Control') - - def getdefaultdefaults(self): - # Video defaults - self.vfile = 'film.video' - self.vmode = VM_CONT - self.mono_thresh = 128 - self.vformat = 'rgb8' - self.comp_scheme = 'Uncompressed' - self.rgb24_size = 1 - # Missing: drop, rate, maxmem, nframes, rate, vcrspeed - # Audio defaults: - self.afile = 'film.aiff' - self.aformat = A_OFF - - def getdefaults(self): - self.getdefaultdefaults() - # XXXX Read defaults file and override. - try: - fp = open(VB_INIT_FILE, 'r') - except IOError: - print 'Vb: no init file' - self.initcont = {} - return - data = fp.read(1000000) - try: - self.initcont = eval(data) - except: - print 'Vb: Ill-formatted init file' - self.initcont = {} - for k in self.initcont.keys(): - if hasattr(self, k): - setattr(self, k, self.initcont[k]) - - def savedefaults(self): - newdb = {} - for k in VB_INIT_KEYS: - newdb[k] = getattr(self, k) - if newdb <> self.initcont: - try: - fp = open(VB_INIT_FILE, 'w') - except IOError: - print 'Vb: Cannot create', VB_INIT_FILE - return - fp.write(`newdb`) - fp.close() - - def setdefaults(self): - self.getdefaults() - self.vcr = None - self.vout = None - self.capturing = 0 - self.c_vformat.clear_choice() - for label in VideoFormatLabels: - self.c_vformat.addto_choice(label) - self.c_vformat.set_choice(1 + VideoFormats.index(self.vformat)) - self.c_vmode.clear_choice() - for label in VideoModeLabels: - self.c_vmode.addto_choice(label) - self.c_vmode.set_choice(self.vmode) - self.get_vformat() - self.b_drop.set_button(1) - self.in_rate.set_input('2') - self.in_maxmem.set_input('1.0') - self.in_nframes.set_input('0') - self.in_nframes_vcr.set_input('1') - self.in_rate_vcr.set_input('1') - self.c_vcrspeed.clear_choice() - for label in VcrSpeedLabels: - self.c_vcrspeed.addto_choice(label) - self.c_vcrspeed.set_choice(4) - self.c_rgb24_size.clear_choice() - for label in RgbSizeLabels: - self.c_rgb24_size.addto_choice(label) - self.c_rgb24_size.set_choice(self.rgb24_size) - if cl: - algs = cl.QueryAlgorithms(cl.VIDEO) - self.all_comp_schemes = [] - for i in range(0, len(algs), 2): - if algs[i+1] in (cl.COMPRESSOR, cl.CODEC): - self.all_comp_schemes.append(algs[i]) - self.c_cformat.clear_choice() - for label in self.all_comp_schemes: - self.c_cformat.addto_choice(label) - i = self.all_comp_schemes.index(self.comp_scheme) - self.c_cformat.set_choice(i+1) - # Audio defaults - self.aout = None - self.aport = None - self.c_aformat.clear_choice() - for label in AudioFormatLabels: - self.c_aformat.addto_choice(label) - self.c_aformat.set_choice(self.aformat) - self.get_aformat() - - def openvideo(self): - try: - self.video = sv.OpenVideo() - except sv.error, msg: - print 'Error opening video:', msg - self.video = None - param = [SV.BROADCAST, SV.PAL] - if self.video: self.video.GetParam(param) - if param[1] == SV.PAL: - x = SV.PAL_XMAX - y = SV.PAL_YMAX - elif param[1] == SV.NTSC: - x = SV.NTSC_XMAX - y = SV.NTSC_YMAX - else: - print 'Unknown video standard:', param[1] - sys.exit(1) - self.maxx, self.maxy = x, y - self.curx = 256 - self.cury = 256*3/4 - - def makewindow(self): - x, y = self.maxx, self.maxy - gl.foreground() - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - width = self.curx - height = self.cury - if width and height: - # Place the window at (150, 150) from top left - # (the video board likes this location...) - x1 = 150 - x2 = x1+width-1 - SCRHEIGHT = 768 - y2 = SCRHEIGHT-1-150 - y1 = y2-height+1 - gl.prefposition(x1, x2, y1, y2) - self.window = gl.winopen('Vb video') - self.settitle() - if width: - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.winconstraints() - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - - def optfullsizewindow(self): - if not self.window: - return - gl.winset(self.window) - if self.use_24: - x, y = self.maxx, self.maxy - else: - x, y = self.curx, self.cury - left, bottom = gl.getorigin() - width, height = gl.getsize() - bottom = bottom+height-y - gl.prefposition(left, left+x-1, bottom, bottom+y-1) - gl.winconstraints() - if not self.use_24: - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.maxsize(self.maxx, self.maxy) - gl.winconstraints() - self.bindvideo() - - def bindvideo(self): - if not self.video: return - x, y = gl.getsize() - if not self.use_24: - self.curx, self.cury = x, y - self.video.SetSize(x, y) - drop = self.b_drop.get_button() - if drop: - param = [SV.FIELDDROP, 1, SV.GENLOCK, SV.GENLOCK_OFF] - else: - param = [SV.FIELDDROP, 0, SV.GENLOCK, SV.GENLOCK_ON] - if self.rgb: - param = param+[SV.COLOR, SV.DEFAULT_COLOR, \ - SV.DITHER, 1, \ - SV.INPUT_BYPASS, 0] - else: - param = param+[SV.COLOR, SV.MONO, SV.DITHER, 0, \ - SV.INPUT_BYPASS, 1] - self.video.BindGLWindow(self.window, SV.IN_REPLACE) - self.video.SetParam(param) - - def rebindvideo(self): - gl.winset(self.window) - self.bindvideo() - - def reset(self): - self.close_video() - self.close_audio() - if self.vcr: - try: - ok = self.vcr.still() - except VCR.error: - pass - self.vcr = None - self.b_capture.set_button(0) - - # Event handler (catches resize of video window) - - def do_event(self, dev, val): - #print 'Event:', dev, val - if dev in (DEVICE.WINSHUT, DEVICE.WINQUIT): - self.close() - if dev == DEVICE.REDRAW and val == self.window: - self.rebindvideo() - self.settitle() - - # Video controls: format, mode, file - - def cb_vformat(self, *args): - self.reset() - self.get_vformat() - if self.mono_use_thresh: - s = `self.mono_thresh` - s = fl.show_input('Please enter mono threshold', s) - if s: - try: - self.mono_thresh = string.atoi(s) - except string.atoi_error: - fl.show_message('Bad input, using', \ - `self.mono_thresh`, '') - self.rebindvideo() - - def cb_cformat(self, *args): - i = self.c_cformat.get_choice() - self.comp_scheme = self.all_comp_schemes[i-1] - - - def cb_vmode(self, *args): - if self.vcr: - self.vcr = None - self.vmode = self.c_vmode.get_choice() - self.form.freeze_form() - self.g_cont.hide_object() - self.g_burst.hide_object() - self.g_single.hide_object() - self.g_vcr.hide_object() - if self.vmode == VM_CONT: - self.g_cont.show_object() - elif self.vmode == VM_BURST: - self.g_burst.show_object() - elif self.vmode == VM_SINGLE: - self.g_single.show_object() - elif self.vmode == VM_VCR: - self.g_vcr.show_object() - self.form.unfreeze_form() - - def cb_vfile(self, *args): - filename = self.vfile - hd, tl = os.path.split(filename) - filename = fl.file_selector('Video save file:', hd, '', tl) - if filename: - self.reset() - hd, tl = os.path.split(filename) - if hd == os.getcwd(): - filename = tl - self.vfile = filename - - # Video mode specific video controls - - def cb_rate(self, *args): - pass - - def cb_drop(self, *args): - self.rebindvideo() - - def cb_maxmem(self, *args): - pass - - def cb_nframes(self, *args): - pass - - def cb_fps(self, *args): - pass - - def cb_nframes_vcr(self, *args): - pass - - def cb_rate_vcr(self, *args): - pass - - def cb_vcrspeed(self, *args): - pass - - def cb_rgb24_size(self, *args): - i = self.c_rgb24_size.get_choice() - if i: - self.rgb24_size = i - - # Audio controls: format, file - - def cb_aformat(self, *args): - self.get_aformat() - - def cb_afile(self, *args): - filename = self.afile - hd, tl = os.path.split(filename) - filename = fl.file_selector('Audio save file:', hd, '', tl) - if filename: - self.reset() - hd, tl = os.path.split(filename) - if hd == os.getcwd(): - filename = tl - self.afile = filename - - # General controls: capture, reset, play, quit - - def cb_capture(self, *args): - if self.capturing: - raise StopCapture - if not self.b_capture.get_button(): - return - if not self.video or not self.vformat: - gl.ringbell() - return - if self.vmode == VM_CONT: - self.cont_capture() - elif self.vmode == VM_BURST: - self.burst_capture() - elif self.vmode == VM_SINGLE: - self.single_capture(None, None) - elif self.vmode == VM_VCR: - self.vcr_capture() - - def cb_reset(self, *args): - self.reset() - - def cb_play(self, *args): - self.reset() - sts = os.system('Vplay -q ' + self.vfile + ' &') - - def cb_quit(self, *args): - self.close() - - # Capture routines - - def burst_capture(self): - self.setwatch() - gl.winset(self.window) - x, y = gl.getsize() - if self.use_24: - fl.show_message('Sorry, no 24 bit continuous capture yet', '', '') - return - vformat = SV.RGB8_FRAMES - nframes = self.getint(self.in_nframes, 0) - if nframes == 0: - maxmem = self.getint(self.in_maxmem, 1.0) - memsize = int(maxmem * 1024 * 1024) - nframes = self.calcnframes(memsize) - info = (vformat, x, y, nframes, 1) - try: - info2, data, bitvec = self.video.CaptureBurst(info) - except sv.error, msg: - self.b_capture.set_button(0) - self.setarrow() - fl.show_message('Capture error:', str(msg), '') - return - if info <> info2: print info, '<>', info2 - self.save_burst(info2, data, bitvec) - self.setarrow() - - def calcnframes(self, memsize): - gl.winset(self.window) - x, y = gl.getsize() - pixels = x*y - pixels = pixels/2 # XXX always assume fields - if self.mono or self.grey: - n = memsize/pixels - else: - n = memsize/(4*pixels) - return max(1, n) - - def save_burst(self, info, data, bitvec): - (vformat, x, y, nframes, rate) = info - self.open_if_closed() - fieldsize = x*y/2 - nskipped = 0 - realframeno = 0 - tpf = 1000 / 50.0 # XXX - for frameno in range(0, nframes*2): - if frameno <> 0 and \ - bitvec[frameno] == bitvec[frameno-1]: - nskipped = nskipped + 1 - continue - # - # Save field. - # XXX Works only for fields and top-to-bottom - # - start = frameno*fieldsize - field = data[start:start+fieldsize] - realframeno = realframeno + 1 - fn = int(realframeno*tpf) - if not self.write_frame(fn, field): - break - - def cont_capture(self): - saved_label = self.b_capture.label - self.b_capture.label = 'Stop\n' + saved_label - self.open_if_closed() - self.init_cont() - fps = 59.64 # Fields per second - # XXX (fps of Indigo monitor, not of PAL or NTSC!) - tpf = 1000.0 / fps # Time per field in msec - self.capturing = 1 - self.start_audio() - while 1: - try: - void = fl.check_forms() - except StopCapture: - break - try: - cd, id = self.video.GetCaptureData() - except sv.error: - sgi.nap(1) - continue - id = id + 2*self.rate - data = cd.InterleaveFields(1) - cd.UnlockCaptureData() - t = id*tpf - if not self.write_frame(t, data): - break - self.stop_audio() - self.capturing = 0 - self.end_cont() - if self.aout: - # If recording audio, can't capture multiple sequences - self.reset() - self.b_capture.label = saved_label - - def single_capture(self, stepfunc, timecode): - self.open_if_closed() - self.init_cont() - while 1: - try: - cd, id = self.video.GetCaptureData() - break - except sv.error: - pass - sgi.nap(1) - if stepfunc: # This might step the video - d=stepfunc() # to the next frame - if not self.use_24: - data = cd.InterleaveFields(1) - else: - x, y = self.vout.getsize() - if self.use_compress: - if self.rgb24_size == 1: - data = cd.YUVtoYUV422DC(0) - elif self.rgb24_size == 2: - data = cd.YUVtoYUV422DC_quarter(1) - x = x/2 - y = y/2 - elif self.rgb24_size == 3: - data = cd.YUVtoYUV422DC_sixteenth(1) - x = x/4 - y = y/4 - else: - data = cd.YUVtoRGB(1) - if self.maxx*self.maxy*4 <> len(data): - print 'maxx,maxy,exp,got=', self.maxx, - print self.maxy,self.maxx*self.maxy*4, - print len(data) - fl.showmessage('Wrong sized data') - return 0 - if self.rgb24_size <> 1: - data = imageop.scale(data, 4, \ - self.maxx, self.maxy, x, y) - if self.use_jpeg: - import jpeg - data = jpeg.compress(data, x, y, 4) - if self.use_compress: - data = self.compressor.Compress(1, data) - cd.UnlockCaptureData() - self.end_cont() - if timecode == None: - timecode = (self.nframes+1) * (1000/25) - return self.write_frame(timecode, data) - - def vcr_capture(self): - if not self.vcr: - try: - print 'Connecting to VCR ...' - self.vcr = VCR.VCR() - print 'Waiting for VCR to come online ...' - self.vcr.initvcr() - print 'Preparing VCR ...' - if not (self.vcr.fmmode('dnr') and \ - self.vcr.dmcontrol('digital slow')): - self.vcr_error('digital slow failed') - return - print 'VCR OK.' - except VCR.error, msg: - self.vcr = None - self.vcr_error(msg) - return - if not self.vcr.still(): - self.vcr_error('still failed') - return - self.open_if_closed() - rate = self.getint(self.in_rate_vcr, 1) - rate = max(rate, 1) - vcrspeed = self.c_vcrspeed.get_choice() - vcrspeed = VcrSpeeds[vcrspeed] - if vcrspeed == 0: - stepfunc = self.vcr.step - else: - stepfunc = None - self.speed_factor = rate - addr = start_addr = self.vcr.sense() - if not self.single_capture(None, 0): - return - print 'captured %02d:%02d:%02d:%02d' % self.vcr.addr2tc(addr) - count = self.getint(self.in_nframes_vcr, 1) - 1 - if count <= 0: - while rate > 0: - if not self.vcr.step(): - self.vcr_error('step failed') - here = self.vcr.sense() - if here > addr: - rate = rate - (here - addr) - addr = here - return - if not self.vcr.fwdshuttle(vcrspeed): - self.vcr_error('fwd shuttle failed') - return - cycle = 0 - while count > 0: - try: - here = self.vcr.sense() - except VCR.error, msg: - self.vcr_error(msg) - break - if here <> addr: - if here <> addr+1: - print 'Missed', here-addr-1, - print 'frame' + 's'*(here-addr-1 <> 1) - cycle = (cycle+1) % rate - if cycle == 0: - tc = (here-start_addr)*40 - if not self.single_capture(stepfunc, \ - tc): - break - print 'captured %02d:%02d:%02d:%02d' \ - % self.vcr.addr2tc(here) - count = count -1 - addr = here - if self.vcr and not self.vcr.still(): - self.vcr_error('still failed') - - def vcr_error(self, msg): - self.reset() - fl.show_message('VCR error:', str(msg), '') - - # Init/end continuous capture mode - - def init_cont(self): - qsize = 1 - if self.vmode == VM_CONT: - self.rate = self.getint(self.in_rate, 2) - else: - self.rate = 2 - x, y = self.vout.getsize() - if self.use_24: - info = (SV.YUV411_FRAMES, x, y, qsize, self.rate) - else: - info = (SV.RGB8_FRAMES, x, y, qsize, self.rate) - info2 = self.video.InitContinuousCapture(info) - if info2 <> info: - # XXX This is really only debug info - print 'Info mismatch: requested', info, 'got', info2 - - def end_cont(self): - self.video.EndContinuousCapture() - - # Misc stuff - - def settitle(self): - gl.winset(self.window) - x, y = gl.getsize() - title = 'Vb ' + self.vfile + ' (%dx%d)' % (x, y) - gl.wintitle(title) - - def get_vformat(self): - i = self.c_vformat.get_choice() - label = VideoFormatLabels[i-1] - format = VideoFormats[i-1] - if format == 'compress' and cl == None: - fl.show_message('Sorry, no compression library support') - format = '' - label = 'Video off' - self.vformat = format - if self.vformat == '': - self.form.freeze_form() - self.g_video.hide_object() - self.g_cont.hide_object() - self.g_burst.hide_object() - self.g_single.hide_object() - self.form.unfreeze_form() - else: - self.g_video.show_object() - if self.vmode == VM_CONT: - self.g_cont.show_object() - elif self.vmode == VM_BURST: - self.g_burst.show_object() - elif self.vmode == VM_SINGLE: - self.g_single.show_object() - # - self.rgb = (format[:3] == 'rgb' or format == 'compress') - self.mono = (format == 'mono') - self.grey = (format[:4] == 'grey') - self.use_24 = (format in ('rgb', 'jpeg', 'compress')) - if self.use_24: - self.g_rgb24.show_object() - else: - self.g_rgb24.hide_object() - self.use_jpeg = (format == 'jpeg') - self.mono_use_thresh = (label == 'mono thresh') - self.use_compress = (format == 'compress') - if self.use_compress: - self.g_compress.show_object() - else: - self.g_compress.hide_object() - s = format[4:] - if self.grey and s: - self.greybits = string.atoi(s) - else: - self.greybits = 8 - if label == 'grey2 dith': - self.greybits = -2 - # - convertor = None - if self.grey: - if self.greybits == 2: - convertor = imageop.grey2grey2 - elif self.greybits == 4: - convertor = imageop.grey2grey4 - elif self.greybits == -2: - convertor = imageop.dither2grey2 - self.convertor = convertor - self.optfullsizewindow() - - def get_aformat(self): - self.reset() - self.aformat = self.c_aformat.get_choice() - if self.aformat == A_OFF: - self.g_audio.hide_object() - else: - self.g_audio.show_object() - - def init_compressor(self, w, h): - self.compressor = None - scheme = cl.QuerySchemeFromName(cl.VIDEO, self.comp_scheme) - self.compressor = cl.OpenCompressor(scheme) - parambuf = [cl.IMAGE_WIDTH, w, \ - cl.IMAGE_HEIGHT, h, \ - cl.ORIGINAL_FORMAT, cl.YUV422DC] - self.compressor.SetParams(parambuf) - return self.compressor.Compress(0, '') - - def open_if_closed(self): - if not self.vout: - self.open_video() - if not self.aout: - self.open_audio() - - # File I/O handling - - def open_video(self): - self.close_video() - gl.winset(self.window) - x, y = gl.getsize() - if self.use_24: - if self.rgb24_size == 2: - x, y = x/2, y/2 - elif self.rgb24_size == 3: - x, y = x/4, y/4 - vout = VFile.VoutFile(self.vfile) - vout.setformat(self.vformat) - if self.vformat == 'compress': - cheader = self.init_compressor(x, y) - vout.setcompressheader(cheader) - vout.setsize(x, y) - if self.vmode == VM_BURST: - vout.setpf((1, -2)) - vout.writeheader() - self.vout = vout - self.nframes = 0 - self.speed_factor = 1 - self.t_nframes.label = `self.nframes` - - def write_frame(self, t, data): - t = t * self.speed_factor - if not self.vout: - gl.ringbell() - return 0 - if self.convertor: - data = self.convertor(data, len(data), 1) - elif self.mono: - if self.mono_use_thresh: - data = imageop.grey2mono(data, \ - len(data), 1,\ - self.mono_thresh) - else: - data = imageop.dither2mono(data, \ - len(data), 1) - try: - self.vout.writeframe(int(t), data, None) - except IOError, msg: - self.reset() - if msg == (0, 'Error 0'): - msg = 'disk full??' - fl.show_message('IOError', str(msg), '') - return 0 - self.nframes = self.nframes + 1 - self.t_nframes.label = `self.nframes` - return 1 - - def close_video(self): - if not self.vout: - return - self.nframes = 0 - self.t_nframes.label = '' - try: - self.vout.close() - except IOError, msg: - if msg == (0, 'Error 0'): - msg = 'disk full??' - fl.show_message('IOError', str(msg), '') - self.vout = None - self.compressor = None - - # Watch cursor handling - - def setwatch(self): - gl.winset(self.form.window) - gl.setcursor(WATCH, 0, 0) - gl.winset(self.window) - gl.setcursor(WATCH, 0, 0) - - def setarrow(self): - gl.winset(self.form.window) - gl.setcursor(ARROW, 0, 0) - gl.winset(self.window) - gl.setcursor(ARROW, 0, 0) - - # Numeric field handling - - def getint(self, field, default): - try: - value = string.atoi(field.get_input()) - except string.atoi_error: - value = default - field.set_input(`value`) - return value - - def getfloat(self, field, default): - try: - value = float(eval(field.get_input())) - except: - value = float(default) - field.set_input(`value`) - return value - - # Audio stuff - - def open_audio(self): - if self.aformat == A_OFF: - return - import aifc - import al - import AL - import thread - self.close_audio() - params = [AL.INPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, params) - rate = params[1] - self.aout = aifc.open(self.afile, 'w') - if self.aformat in (A_16_STEREO, A_8_STEREO): - nch = AL.STEREO - else: - nch = AL.MONO - if self.aformat in (A_16_STEREO, A_16_MONO): - width = AL.SAMPLE_16 - else: - width = AL.SAMPLE_8 - self.aout.setnchannels(nch) - self.aout.setsampwidth(width) - self.aout.setframerate(rate) - c = al.newconfig() - c.setqueuesize(8000) - c.setchannels(nch) - c.setwidth(width) - self.aport = al.openport('Vb audio record', 'r', c) - self.audio_stop = 0 - self.audio_ok = 0 - self.audio_busy = 1 - thread.start_new_thread(self.record_audio, ()) - - def start_audio(self): - if self.aformat == A_OFF: - return - self.audio_ok = 1 - - def record_audio(self, *args): - # This function runs in a separate thread - # Currently no semaphores are used - while not self.audio_stop: - data = self.aport.readsamps(4000) - if self.audio_ok: - self.aout.writeframes(data) - data = None - self.audio_busy = 0 - - def stop_audio(self): - self.audio_ok = 0 - - def close_audio(self): - if self.aout: - self.audio_ok = 0 - self.audio_stop = 1 - while self.audio_busy: - time.sleep(0.1) - self.aout.close() - self.aout = None - if self.aport: - self.aport.closeport() - self.aport = None - - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' - sys.exit(1) diff --git a/Demo/sgi/video/VbForm.fd b/Demo/sgi/video/VbForm.fd deleted file mode 100644 index fd9759fb14..0000000000 --- a/Demo/sgi/video/VbForm.fd +++ /dev/null @@ -1,615 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 1 - -=============== FORM =============== -Name: form -Width: 450.000000 -Height: 260.000000 -Number of Objects: 40 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 450.000000 260.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 11 -type: 5 -box: 330.000000 150.000000 110.000015 60.000004 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 1 -size: 11.000000 -lcol: 0 -label: Capture -name: b_capture -callback: cb_capture -argument: 0 - --------------------- -class: 11 -type: 0 -box: 330.000000 10.000000 110.000008 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Quit -name: b_quit -callback: cb_quit -argument: 0 - --------------------- -class: 11 -type: 0 -box: 330.000000 50.000000 110.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Playback -name: b_play -callback: cb_play -argument: 0 - --------------------- -class: 42 -type: 0 -box: 80.000000 220.000000 120.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Format: -name: c_vformat -callback: cb_vformat -argument: 0 - --------------------- -class: 11 -type: 0 -box: 330.000000 220.000000 110.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Reset -name: b_reset -callback: cb_reset -argument: 0 - --------------------- -class: 42 -type: 0 -box: 80.000000 50.000000 120.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Format: -name: c_aformat -callback: cb_aformat -argument: 0 - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 1668246586 540019308 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_audio -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 10.000000 10.000000 190.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Set audio file... -name: b_afile -callback: cb_afile -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 876099360 892416522 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 1147496041 1852404841 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_video -callback: -argument: - --------------------- -class: 42 -type: 0 -box: 80.000000 180.000000 120.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Mode: -name: c_vmode -callback: cb_vmode -argument: 0 - --------------------- -class: 11 -type: 0 -box: 10.000000 90.000000 190.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Set video file... -name: b_vfile -callback: cb_vfile -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 544171552 1331849829 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_single -callback: -argument: - --------------------- -class: 31 -type: 2 -box: 220.000000 150.000000 100.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: Frames/sec -name: in_fps -callback: cb_fps -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_burst -callback: -argument: - --------------------- -class: 31 -type: 1 -box: 220.000000 150.000000 100.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: Max Mbytes: -name: in_maxmem -callback: cb_maxmem -argument: 0 - --------------------- -class: 31 -type: 2 -box: 220.000000 90.000000 100.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: Nr. of frames: -name: in_nframes -callback: cb_nframes -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_cont -callback: -argument: - --------------------- -class: 31 -type: 2 -box: 250.000000 150.000000 40.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: Capture rate: -name: in_rate -callback: cb_rate -argument: 0 - --------------------- -class: 2 -type: 0 -box: 220.000000 150.000000 30.000000 30.000000 -boxtype: 0 -colors: 47 47 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: 1/ -name: -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 290.000000 150.000000 30.000000 30.000000 -boxtype: 0 -colors: 47 47 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: fr -name: -callback: -argument: - --------------------- -class: 13 -type: 0 -box: 220.000000 90.000000 100.000000 30.000000 -boxtype: 0 -colors: 7 3 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Fielddrop -name: b_drop -callback: cb_drop -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 330.000000 90.000000 110.000000 30.000002 -boxtype: 2 -colors: 47 47 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: t_nframes -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 330.000000 120.000000 110.000000 30.000000 -boxtype: 0 -colors: 47 47 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Frames done: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 640 235 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_vcr -callback: -argument: - --------------------- -class: 31 -type: 2 -box: 220.000000 90.000000 100.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: # frames wtd: -name: in_nframes_vcr -callback: cb_nframes_vcr -argument: 0 - --------------------- -class: 31 -type: 2 -box: 220.000000 150.000000 100.000000 30.000000 -boxtype: 2 -colors: 13 5 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: Sample rate: -name: in_rate_vcr -callback: cb_rate_vcr -argument: 0 - --------------------- -class: 42 -type: 0 -box: 220.000000 10.000000 100.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 0 -style: 0 -size: 11.000000 -lcol: 0 -label: VCR speed: -name: c_vcrspeed -callback: cb_vcrspeed -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 640 235 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 58720287 33751040 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: g_rgb24 -callback: -argument: - --------------------- -class: 42 -type: 0 -box: 260.000000 220.000000 60.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Size: -name: c_rgb24_size -callback: cb_rgb24_size -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 10000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 10.000000 -lcol: 0 -label: -name: g_compress -callback: -argument: - --------------------- -class: 42 -type: 0 -box: 80.000000 140.000000 120.000000 30.000000 -boxtype: 5 -colors: 7 0 -alignment: 2 -style: 0 -size: 11.000000 -lcol: 0 -label: Scheme: -name: c_cformat -callback: cb_cformat -argument: 0 - --------------------- -class: 20000 -type: 0 -box: 0.000000 0.000000 0.000000 0.000000 -boxtype: 0 -colors: 0 0 -alignment: 4 -style: 0 -size: 10.000000 -lcol: 0 -label: -name: -callback: -argument: - -============================== -create_the_forms diff --git a/Demo/sgi/video/Vcopy.py b/Demo/sgi/video/Vcopy.py deleted file mode 100755 index ef4647a166..0000000000 --- a/Demo/sgi/video/Vcopy.py +++ /dev/null @@ -1,291 +0,0 @@ -#! /usr/bin/env python - -# Universal (non-interactive) CMIF video file copier. - - -# Possibilities: -# -# - Manipulate the time base: -# = resample at a fixed rate -# = divide the time codes by a speed factor (to make it go faster/slower) -# = drop frames that are less than n msec apart (to accommodate slow players) -# - Convert to a different format -# - Magnify (scale) the image - - -# Usage function (keep this up-to-date if you change the program!) - -def usage(): - print 'Usage: Vcopy [options] [infile [outfile]]' - print - print 'Options:' - print - print '-t type : new image type (default unchanged)' - print - print '-M magnify : image magnification factor (default unchanged)' - print '-w width : output image width (default height*4/3 if -h used)' - print '-h height : output image height (default width*3/4 if -w used)' - print - print '-p pf : new x and y packfactor (default unchanged)' - print '-x xpf : new x packfactor (default unchanged)' - print '-y ypf : new y packfactor (default unchanged)' - print - print '-m delta : drop frames closer than delta msec (default 0)' - print '-r delta : regenerate input time base delta msec apart' - print '-s speed : speed change factor (default unchanged)' - print - print 'infile : input file (default film.video)' - print 'outfile : output file (default out.video)' - - -import sys -sys.path.append('/ufs/guido/src/video') - -import VFile -import imgconv -import imageop -import getopt -import string - - -# Global options - -speed = 1.0 -mindelta = 0 -regen = None -newpf = None -newtype = None -magnify = None -newwidth = None -newheight = None - - -# Function to turn a string into a float - -atof_error = 'atof_error' # Exception if it fails - -def atof(s): - try: - return float(eval(s)) - except: - raise atof_error - - -# Main program -- mostly command line parsing - -def main(): - global speed, mindelta, regen, newpf, newtype, \ - magnify, newwidth, newheight - - # Parse command line - try: - opts, args = getopt.getopt(sys.argv[1:], \ - 'M:h:m:p:r:s:t:w:x:y:') - except getopt.error, msg: - sys.stdout = sys.stderr - print 'Error:', msg, '\n' - usage() - sys.exit(2) - - xpf = ypf = None - - # Interpret options - try: - for opt, arg in opts: - if opt == '-M': magnify = atof(arg) - if opt == '-h': height = string.atoi(arg) - if opt == '-m': mindelta = string.atoi(arg) - if opt == '-p': xpf = ypf = string.atoi(arg) - if opt == '-r': regen = string.atoi(arg) - if opt == '-s': speed = atof(arg) - if opt == '-t': newtype = arg - if opt == '-w': newwidth = string.atoi(arg) - if opt == '-x': xpf = string.atoi(arg) - if opt == '-y': ypf = string.atoi(arg) - except string.atoi_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires integer argument' - sys.exit(2) - except atof_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires float argument' - sys.exit(2) - - if xpf or ypf: - newpf = (xpf, ypf) - - if newwidth or newheight: - if magnify: - sys.stdout = sys.stderr - print 'Options -w or -h are incompatible with -M' - sys.exit(2) - if not newheight: - newheight = newwidth * 3 / 4 - elif not newwidth: - newwidth = newheight * 4 / 3 - - # Check filename arguments - if len(args) < 1: - args.append('film.video') - if len(args) < 2: - args.append('out.video') - if len(args) > 2: - usage() - sys.exit(2) - if args[0] == args[1]: - sys.stderr.write('Input file can\'t be output file\n') - sys.exit(2) - - # Do the right thing - sts = process(args[0], args[1]) - - # Exit - sys.exit(sts) - - -# Copy one file to another - -def process(infilename, outfilename): - global newwidth, newheight, newpf - - try: - vin = VFile.BasicVinFile(infilename) - except IOError, msg: - sys.stderr.write(infilename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(infilename + ': EOF in video file\n') - return 1 - - try: - vout = VFile.BasicVoutFile(outfilename) - except IOError, msg: - sys.stderr.write(outfilename + ': I/O error: ' + `msg` + '\n') - return 1 - - print '=== input file ===' - vin.printinfo() - - vout.setinfo(vin.getinfo()) - - scale = 0 - flip = 0 - decompress = 0 - - vinfmt = vin.format - if vinfmt == 'compress': - if not newtype or newtype == 'compress': - # compressed->compressed: copy compression header - vout.setcompressheader(vin.getcompressheader()) - else: - # compressed->something else: go via rgb-24 - decompress = 1 - vinfmt = 'rgb' - elif newtype == 'compress': - # something else->compressed: not implemented - sys.stderr.write('Sorry, conversion to compressed not yet implemented\n') - return 1 - if newtype: - vout.setformat(newtype) - try: - convert = imgconv.getconverter(vinfmt, vout.format) - except imgconv.error, msg: - sys.stderr.write(str(msg) + '\n') - return 1 - - if newpf: - xpf, ypf = newpf - if not xpf: xpf = vin.xpf - if not ypf: ypf = vout.ypf - newpf = (xpf, ypf) - vout.setpf(newpf) - - if newwidth and newheight: - scale = 1 - - if vin.upside_down <> vout.upside_down or \ - vin.mirror_image <> vout.mirror_image: - flip = 1 - - inwidth, inheight = vin.getsize() - inwidth = inwidth / vin.xpf - inheight = inheight / vin.ypf - - if magnify: - newwidth = int(vout.width * magnify) - newheight = int(vout.height * magnify) - scale = 1 - - if scale: - vout.setsize(newwidth, newheight) - else: - newwidth, newheight = vout.getsize() - - if vin.packfactor <> vout.packfactor: - scale = 1 - - if scale or flip: - if vout.bpp not in (8, 32): - sys.stderr.write('Can\'t scale or flip this type\n') - return 1 - - newwidth = newwidth / vout.xpf - newheight = newheight / vout.ypf - - print '=== output file ===' - vout.printinfo() - vout.writeheader() - - told = 0 - nin = 0 - nout = 0 - tin = 0 - tout = 0 - - while 1: - try: - tin, data, cdata = vin.getnextframe() - except EOFError: - break - if decompress: - data = vin.decompress(data) - nin = nin + 1 - if regen: - tout = nin * regen - else: - tout = tin - tout = int(tout / speed) - if tout - told < mindelta: - continue - told = tout - if newtype: - data = convert(data, inwidth, inheight) - if scale: - data = imageop.scale(data, vout.bpp/8, \ - inwidth, inheight, newwidth, newheight) - if flip: - x0, y0 = 0, 0 - x1, y1 = newwidth-1, newheight-1 - if vin.upside_down <> vout.upside_down: - y1, y0 = y0, y1 - if vin.mirror_image <> vout.mirror_image: - x1, x0 = x0, x1 - data = imageop.crop(data, vout.bpp/8, \ - newwidth, newheight, x0, y0, x1, y1) - print 'Writing frame', nout - vout.writeframe(tout, data, cdata) - nout = nout + 1 - - vout.close() - vin.close() - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/VcrIndex.py b/Demo/sgi/video/VcrIndex.py deleted file mode 100755 index 80212ee561..0000000000 --- a/Demo/sgi/video/VcrIndex.py +++ /dev/null @@ -1,327 +0,0 @@ -# -# A VCR index. -# -import os -import string - -error='VcrIndex.error' -VERSION_STRING='#!VcrIndex 1.1\n' -PREV_VERSION_STRING='#!VcrIndex 1.0\n' - -class VcrIndex: - def __init__(self, name): - self.curmovie = None - self.curscene = None - self.modified = 0 - self.filename = name - self.basename = os.path.basename(name) - self.editable = [] - if not name: - self.movies = {} - return - try: - fp = open(name, 'r') - except IOError: - self.movies = {} - return - header = fp.readline() - if header == PREV_VERSION_STRING: - print 'Converting old-format database...' - data = fp.read(100000) - self.movies = eval(data) - for m in self.movies.keys(): - d = self.movies[m] - newd = {} - for s in d.keys(): - newsd = {} - newsd['START'] = d[s] - if s == 'START': - s = '-ALL-' - newd[s] = newsd - - self.movies[m] = newd - print 'Done.' - return - if header <> VERSION_STRING: - print 'VcrIndex: incorrect version string:', header - self.movies = {} - return - data = fp.read(100000) - self.movies = eval(data) - # - # Save database to given file (or same file as read from if no - # filename given). - # - def save(self, name): - if not name: - name = self.filename - if not name: - raise error, 'No filename given' - self.filename = name - bupname = name + '~' - try: - os.unlink(bupname) - except os.error: - pass - try: - os.rename(name, bupname) - except os.error: - pass - fp = open(name, 'w') - data = str(self.movies) - fp.write(VERSION_STRING) - fp.write(data) - fp.write('\n') - fp.close() - self.modified = 0 - # - # Get a list of movie names in tape order - # - def get_movienames(self): - names = self.movies.keys() - sorted = [] - for name in names: - sorted.append(self.movies[name]['-ALL-']['START'], name) - sorted.sort() - rv = [] - for pos, name in sorted: - rv.append(name) - return rv - # - # Get a list of scene names in tape order - # - def get_scenenames(self): - if not self.curmovie: - return [] - scenedict = self.movies[self.curmovie] - names = scenedict.keys() - sorted = [] - for name in names: - sorted.append(scenedict[name], name) - sorted.sort() - rv = [] - for pos, name in sorted: - rv.append(name) - return rv - # - # Get a list of scene ids (format '00:02:32:12 name') in tape order - # - def get_sceneids(self): - if not self.curmovie: - return [] - scenedict = self.movies[self.curmovie] - names = scenedict.keys() - sorted = [] - for name in names: - sorted.append(scenedict[name]['START'], name) - sorted.sort() - rv = [] - for pos, name in sorted: - str = '%02d:%02d:%02d:%02d ' % pos - rv.append(str + name) - return rv - # - # Does a movie exist? - # - def movie_exists(self, name): - return self.movies.has_key(name) - # - # Select a movie. - # - def movie_select(self, name): - if not self.movies.has_key(name): - raise error, 'No such movie: '+name - self.curmovie = name - self.curscene = None - # - # Get movie dictionary, or raise an error if no current movie. - # - def _getmoviedict(self): - if not self.curmovie: - raise error, 'No current movie' - return self.movies[self.curmovie] - # - # Rename a movie. - # - def movie_rename(self, newname): - scenedict = self._getmoviedict() - if self.movie_exists(newname): - raise error, 'Movie already exists: '+newname - del self.movies[self.curmovie] - self.movies[newname] = scenedict - self.curmovie = newname - self.modified = 1 - # - # Copy a movie. - # - def movie_copy(self, newname): - scenedict = self._getmoviedict() - if self.movie_exists(newname): - raise error, 'Movie already exists: '+newname - newdict = {} - for k in scenedict.keys(): - olddata = scenedict[k] - newdata = {} - for i in olddata.keys(): - newdata[i] = olddata[i] - newdict[k] = newdata - self.movies[newname] = newdict - self.curmovie = newname - self.modified = 1 - # - # Delete a movie. - # - def movie_delete(self): - if not self.curmovie: - raise error, 'No current movie' - del self.movies[self.curmovie] - self.curmovie = None - self.curscene = None - self.modified = 1 - # - # Create a new movie. - # - def movie_new(self, name, pos): - if self.movie_exists(name): - raise error, 'Movie already exists: '+name - newdict = {} - newsdict = {} - newsdict['START'] = pos - newdict['-ALL-'] = newsdict - self.movies[name] = newdict - self.curmovie = name - self.curscene = None - self.modified = 1 - # - # Does a scene exist? - # - def scene_exists(self, name): - scenedict = self._getmoviedict() - return scenedict.has_key(name) - # - # Select a current scene. - # - def scene_select(self, name): - scenedict = self._getmoviedict() - if not scenedict.has_key(name): - raise error, 'No such scene: '+name - self.curscene = name - # - # Rename a scene. - # - def scene_rename(self, newname): - scenedict = self._getmoviedict() - if not self.curscene: - raise error, 'No current scene' - if scenedict.has_key(newname): - raise error, 'Scene already exists: '+newname - if self.curscene == '-ALL-': - raise error, 'Cannot rename -ALL-' - scenedict[newname] = scenedict[self.curscene] - del scenedict[self.curscene] - self.curscene = newname - self.modified = 1 - # - # Copy a scene. - # - def scene_copy(self, newname): - scenedict = self._getmoviedict() - if not self.curscene: - raise error, 'No current scene' - if scenedict.has_key(newname): - raise error, 'Scene already exists: '+newname - scenedict[newname] = scenedict[self.curscene] - self.curscene = newname - self.modified = 1 - # - # Delete a scene. - # - def scene_delete(self): - scenedict = self._getmoviedict() - if not self.curscene: - raise error, 'No current scene' - if self.curscene == '-ALL-': - raise error, 'Cannot delete -ALL-' - del scenedict[self.curscene] - self.curscene = None - self.modified = 1 - # - # Add a new scene. - # - def scene_new(self, newname, pos): - scenedict = self._getmoviedict() - if scenedict.has_key(newname): - raise error, 'Scene already exists: '+newname - newdict = {} - newdict['START'] = pos - scenedict[newname] = newdict - self.curscene = newname - self.modified = 1 - # - # Get scene data. - # - def _getscenedata(self): - scenedict = self._getmoviedict() - if not self.curscene: - raise error, 'No current scene' - return scenedict[self.curscene] - # - # Data manipulation routines. - # - def pos_get(self): - return self._getscenedata()['START'] - # - def pos_set(self, pos): - data = self._getscenedata() - data['START'] = pos - self.modified = 1 - # - def comment_get(self): - data = self._getscenedata() - if data.has_key('COMMENT'): - return data['COMMENT'] - else: - return '' - # - def comment_set(self, comment): - data = self._getscenedata() - data['COMMENT'] = comment - self.modified = 1 - # - # Get the scene id of the current scene. - # - def get_cursceneid(self): - pos = self._getscenedata()['START'] - str = '%02d:%02d:%02d:%02d ' % pos - return str + self.curscene - # - # Convert a scene id to a scene name. - # - def scene_id2name(self, id): - pos = string.find(id, ' ') - if pos <= 0: - raise error, 'Not a scene id: '+id - return id[pos+1:] - # - # Select a scene given a position. - # - def pos_select(self, pos): - prevmovie = None - movies = self.get_movienames() - for movie in movies: - mpos = self.movies[movie]['-ALL-']['START'] - if mpos > pos: - break - prevmovie = movie - if not prevmovie: - raise error, 'Scene before BOT' - - self.movie_select(prevmovie) - scenes = self.get_scenenames() - scenedict = self._getmoviedict() - prevscene = 'START' - for scene in scenes: - if scenedict[scene]['START'] > pos: - break - prevscene = scene - self.scene_select(prevscene) diff --git a/Demo/sgi/video/Vedit.py b/Demo/sgi/video/Vedit.py deleted file mode 100755 index 60ef49fabe..0000000000 --- a/Demo/sgi/video/Vedit.py +++ /dev/null @@ -1,301 +0,0 @@ -#! /usr/bin/env python - -# Edit CMIF movies interactively -- copy one or more files to an output file - - -# XXX To do: -# -# - convert between formats (grey, rgb, rgb8, ...) -# - change size -# - cut out a given area of the image -# - change time base (a la Vtime) - - -import sys -import os -import gl, GL, DEVICE -import fl, FL -import flp -import Viewer -import getopt -import string -import watchcursor - -ARROW = 0 -WATCH = 1 -watchcursor.defwatch(WATCH) - - -def main(): - qsize = 40 - opts, args = getopt.getopt(sys.argv[1:], 'q:') - for o, a in opts: - if o == '-q': - qsize = string.atoi(a) - ed = Editor(qsize) - if args[0:]: - ed.open_input(args[0]) - if args[1:]: - ed.open_output(args[1]) - while 1: - dummy = fl.do_forms() - - -class Editor: - - def __init__(self, qsize): - self.qsize = qsize - self.vin = None - self.vout = None - self.ifile = '' - self.ofile = '' - formdef = flp.parse_form('VeditForm', 'form') - flp.create_full_form(self, formdef) - self.form.show_form(FL.PLACE_SIZE, FL.TRUE, 'Vedit') - fl.set_event_call_back(self.do_event) - - def do_event(self, dev, val): - if dev == DEVICE.REDRAW: - if self.vin: - self.vin.redraw(val) - if self.vout: - self.vout.redraw(val) - - def busy(self): - gl.winset(self.form.window) - gl.setcursor(WATCH, 0, 0) - - def ready(self): - gl.winset(self.form.window) - gl.setcursor(ARROW, 0, 0) - - - def iocheck(self): - self.msg('') - if self.vin == None and self.vout == None: - self.err('Please open input and output files first') - return 0 - return self.icheck() and self.ocheck() - - def icheck(self): - self.msg('') - if self.vin == None: - self.err('Please open an input file first') - return 0 - return 1 - - def ocheck(self): - self.msg('') - if self.vout == None: - self.err('Please open an output file first') - return 0 - return 1 - - - def cb_in_new(self, *args): - self.msg('') - hd, tl = os.path.split(self.ifile) - filename = fl.file_selector('Input video file', hd, '', tl) - if not filename: return - self.open_input(filename) - - def cb_in_close(self, *args): - self.msg('') - self.close_input() - - def cb_in_skip(self, *args): - if not self.icheck(): return - if not self.vin.get(): self.err('End of input file') - self.ishow() - - def cb_in_back(self, *args): - if not self.icheck(): return - if not self.vin.backup(): self.err('Begin of input file') - self.ishow() - - def cb_in_slider(self, *args): - if not self.icheck(): return - left, pos, right = self.vin.qinfo() - i = int(self.in_slider.get_slider_value()) - i = max(i, left) - i = min(i, right) - if i == pos: return - if not self.vin.seek(i): - self.err('Input seek failed') - self.ishow() - - def cb_in_rewind(self, *args): - if not self.icheck(): return - self.vin.rewind() - self.ishow() - - - def cb_copy(self, *args): - if not self.iocheck(): return - data = self.vin.get() - if not data: - self.err('End of input file') - self.ishow() - return - if self.vout.getinfo() <> self.vin.getinfo(): - print 'Copying info...' - self.vout.setinfo(self.vin.getinfo()) - if self.vin.format == 'compress': - self.vout.setcompressheader(\ - self.vin.getcompressheader()) - self.vout.put(data) - self.oshow() - self.ishow() - - def cb_uncopy(self, *args): - if not self.iocheck(): return - if not self.vout.backup(): - self.err('Output buffer exhausted') - return - self.oshow() - if not self.vin.backup(): - self.err('Begin of input file') - return - self.ishow() - - - def cb_out_new(self, *args): - self.msg('') - hd, tl = os.path.split(self.ofile) - filename = fl.file_selector('Output video file', hd, '', tl) - if not filename: return - self.open_output(filename) - - def cb_out_close(self, *args): - self.msg('') - self.close_output() - - def cb_out_skip(self, *args): - if not self.ocheck(): return - if not self.vout.forward(): self.err('Output buffer exhausted') - self.oshow() - - def cb_out_back(self, *args): - if not self.ocheck(): return - if not self.vout.backup(): self.err('Output buffer exhausted') - self.oshow() - - def cb_out_slider(self, *args): - if not self.ocheck(): return - i = int(self.out_slider.get_slider_value()) - left, pos, right = self.vout.qinfo() - i = int(self.out_slider.get_slider_value()) - i = max(i, left) - i = min(i, right) - if i == pos: return - if not self.vout.seek(i): - self.err('Output seek failed') - self.oshow() - - def cb_out_trunc(self, *arcs): - if not self.ocheck(): return - self.vout.trunc() - self.oshow() - - def cb_out_rewind(self, *args): - if not self.ocheck(): return - self.vout.rewind() - self.oshow() - - - def cb_quit(self, *args): - self.close_input() - self.close_output() - sys.exit(0) - - - def open_input(self, filename): - self.ifile = filename - basename = os.path.split(filename)[1] - title = 'in: ' + basename - try: - vin = Viewer.InputViewer(filename, title) - except: - self.err('Can\'t open input file', filename) - return - self.close_input() - self.vin = vin - self.in_file.label = basename - self.ishow() - - def close_input(self): - if self.vin: - self.busy() - self.msg('Closing input file...') - self.vin.close() - self.ready() - self.msg('') - self.vin = None - self.in_file.label = '(none)' - self.format('in') - - def ishow(self): - self.vin.show() - self.format('in') - - def open_output(self, filename): - self.ofile = filename - basename = os.path.split(filename)[1] - title = 'out: ' + basename - try: - vout = Viewer.OutputViewer(filename, \ - title, self.qsize) - except: - self.err('Can\'t open output file', filename) - return - self.close_output() - self.vout = vout - self.out_file.label = basename - if self.vin: - self.vout.setinfo(self.vin.getinfo()) - self.oshow() - - def close_output(self): - if self.vout: - self.busy() - self.msg('Closing output file...') - self.vout.close() - self.ready() - self.msg('') - self.vout = None - self.out_file.label = '(none)' - self.format('out') - - def oshow(self): - self.vout.show() - self.format('out') - - - def msg(self, *args): - str = string.strip(string.join(args)) - self.msg_area.label = str - - def err(self, *args): - gl.ringbell() - apply(self.msg, args) - - def format(self, io): - v = getattr(self, 'v' + io) - if v == None: - left = right = pos = 0 - else: - left, pos, right = v.qinfo() - getattr(self, io + '_info1').label = `left` - getattr(self, io + '_info2').label = `pos` - getattr(self, io + '_info3').label = `right` - sl = getattr(self, io + '_slider') - self.form.freeze_form() - sl.set_slider_bounds(left, right) - sl.set_slider_value(pos) - self.form.unfreeze_form() - - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/VeditForm.fd b/Demo/sgi/video/VeditForm.fd deleted file mode 100644 index ba59de4d4f..0000000000 --- a/Demo/sgi/video/VeditForm.fd +++ /dev/null @@ -1,435 +0,0 @@ -Magic: 12321 - -Internal Form Definition File - (do not change) - -Number of forms: 1 - -=============== FORM =============== -Name: form -Width: 510.000000 -Height: 350.000000 -Number of Objects: 28 - --------------------- -class: 1 -type: 1 -box: 0.000000 0.000000 510.000000 350.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 1 -type: 6 -box: 10.000000 130.000000 240.000000 209.999985 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 1 -type: 6 -box: 260.000000 130.000000 240.000000 209.999985 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 10.000000 10.000000 430.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: CMIF Video Editor, by Guido van Rossum -name: msg_area -callback: -argument: - --------------------- -class: 11 -type: 4 -box: 200.000000 90.000000 120.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -> Copy -> -name: -callback: cb_copy -argument: 0 - --------------------- -class: 11 -type: 4 -box: 210.000000 220.000000 30.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: @> -name: -callback: cb_in_skip -argument: 0 - --------------------- -class: 11 -type: 0 -box: 20.000000 140.000000 220.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Rewind -name: -callback: cb_in_rewind -argument: 0 - --------------------- -class: 11 -type: 0 -box: 270.000000 140.000000 100.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Reset -name: -callback: cb_out_rewind -argument: 0 - --------------------- -class: 11 -type: 0 -box: 20.000000 260.000000 160.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: New input file... -name: -callback: cb_in_new -argument: 0 - --------------------- -class: 11 -type: 0 -box: 330.000000 260.000000 160.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: New output file... -name: -callback: cb_out_new -argument: 0 - --------------------- -class: 2 -type: 0 -box: 20.000000 300.000000 220.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: (none) -name: in_file -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 270.000000 300.000000 220.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: (none) -name: out_file -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 450.000000 10.000000 50.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Quit -name: -callback: cb_quit -argument: 0 - --------------------- -class: 11 -type: 4 -box: 270.000000 220.000000 30.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: @< -name: -callback: cb_out_back -argument: 0 - --------------------- -class: 11 -type: 4 -box: 20.000000 220.000000 30.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: @< -name: -callback: cb_in_back -argument: 0 - --------------------- -class: 11 -type: 4 -box: 460.000000 220.000000 30.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: @> -name: -callback: cb_out_skip -argument: 0 - --------------------- -class: 11 -type: 4 -box: 200.000000 50.000000 120.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Uncopy -name: -callback: cb_uncopy -argument: 0 - --------------------- -class: 11 -type: 0 -box: 190.000000 260.000000 50.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Close -name: -callback: cb_in_close -argument: 0 - --------------------- -class: 11 -type: 0 -box: 270.000000 260.000000 50.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Close -name: -callback: cb_out_close -argument: 0 - --------------------- -class: 21 -type: 1 -box: 60.000000 220.000000 140.000000 30.000000 -boxtype: 2 -colors: 47 47 -alignment: 1 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: in_slider -callback: cb_in_slider -argument: 0 - --------------------- -class: 21 -type: 1 -box: 310.000000 220.000000 140.000000 30.000000 -boxtype: 2 -colors: 47 47 -alignment: 1 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: out_slider -callback: cb_out_slider -argument: 0 - --------------------- -class: 2 -type: 0 -box: 20.000000 180.000000 30.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 8.000000 -lcol: 0 -label: -name: in_info1 -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 100.000000 180.000000 60.000004 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: in_info2 -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 210.000000 180.000000 30.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 8.000000 -lcol: 0 -label: -name: in_info3 -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 270.000000 180.000000 30.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 8.000000 -lcol: 0 -label: -name: out_info1 -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 350.000000 180.000000 60.000004 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: -name: out_info2 -callback: -argument: - --------------------- -class: 2 -type: 0 -box: 460.000000 180.000000 30.000000 30.000000 -boxtype: 6 -colors: 47 47 -alignment: 4 -style: 0 -size: 8.000000 -lcol: 0 -label: -name: out_info3 -callback: -argument: - --------------------- -class: 11 -type: 0 -box: 390.000000 140.000000 100.000000 30.000000 -boxtype: 1 -colors: 47 47 -alignment: 4 -style: 0 -size: 11.000000 -lcol: 0 -label: Truncate -name: -callback: cb_out_trunc -argument: 0 - -============================== -create_the_forms diff --git a/Demo/sgi/video/Vfix.py b/Demo/sgi/video/Vfix.py deleted file mode 100755 index 4870c1b979..0000000000 --- a/Demo/sgi/video/Vfix.py +++ /dev/null @@ -1,90 +0,0 @@ -#! /usr/bin/env python - -# Copy a video file, fixing the line width to be a multiple of 4 - - -# Usage: -# -# Vfix [infile [outfile]] - - -# Options: -# -# infile : input file (default film.video) -# outfile : output file (default out.video) - - -import sys -import imageop -sys.path.append('/ufs/guido/src/video') -import VFile - - -# Main program -- mostly command line parsing - -def main(): - args = sys.argv[1:] - if len(args) < 1: - args.append('film.video') - if len(args) < 2: - args.append('out.video') - if len(args) > 2: - sys.stderr.write('usage: Vfix [infile [outfile]]\n') - sys.exit(2) - sts = process(args[0], args[1]) - sys.exit(sts) - - -# Copy one file to another - -def process(infilename, outfilename): - try: - vin = VFile.BasicVinFile(infilename) - except IOError, msg: - sys.stderr.write(infilename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(infilename + ': EOF in video file\n') - return 1 - - try: - vout = VFile.BasicVoutFile(outfilename) - except IOError, msg: - sys.stderr.write(outfilename + ': I/O error: ' + `msg` + '\n') - return 1 - - info = vin.getinfo() - if info[0] <> 'grey': - sys.stderr.write('Vfix: input not in grey format\n') - return 1 - vout.setinfo(info) - inwidth, height = vin.getsize() - pf = vin.packfactor - if (inwidth/pf)%4 == 0: - sys.stderr.write('Vfix: fix not necessary\n') - return 1 - outwidth = (inwidth/pf/4)*4*pf - print 'inwidth =', inwidth, 'outwidth =', outwidth - vout.setsize(outwidth, height) - vout.writeheader() - n = 0 - try: - while 1: - t, data, cdata = vin.getnextframe() - n = n + 1 - sys.stderr.write('Frame ' + `n` + '...') - data = imageop.crop(data, 1, inwidth/pf, height/pf, \ - 0, 0, outwidth/pf-1, height/pf-1) - vout.writeframe(t, data, None) - sys.stderr.write('\n') - except EOFError: - pass - return 0 - - -# Don't forget to call the main program - -main() diff --git a/Demo/sgi/video/Vgeneric.py b/Demo/sgi/video/Vgeneric.py deleted file mode 100755 index 182adbe2ca..0000000000 --- a/Demo/sgi/video/Vgeneric.py +++ /dev/null @@ -1,2 +0,0 @@ -import sys, posixpath -exec('import ' + posixpath.basename(sys.argv[0]) + '\n') diff --git a/Demo/sgi/video/Viewer.py b/Demo/sgi/video/Viewer.py deleted file mode 100755 index 07cba54cec..0000000000 --- a/Demo/sgi/video/Viewer.py +++ /dev/null @@ -1,255 +0,0 @@ -import gl, GL -import VFile -import os - - -class InputViewer: - - def __init__(self, filename, title, *args): - try: - self.vin = VFile.VinFile(filename) - except (EOFError, VFile.Error): - raise IOError, 'bad video input file' - self.vin.warmcache() - if not title: - title = os.path.split(filename)[1] - self.filename = filename - self.title = title - self.qsize = len(self.vin.index) - gl.foreground() - gl.prefsize(self.vin.width, self.vin.height) - self.wid = -1 - self.reset() - - def close(self): - self.vin.close() - if self.wid > 0: - gl.winclose(self.wid) - - def rewind(self): - self.vin.rewind() - self.reset() - - def getinfo(self): - return self.vin.getinfo() - - # Internal - def reset(self): - if self.wid > 0: - gl.winset(self.wid) - gl.clear() - self.vin.initcolormap() - self.qindex = 0 - - def show(self): - if self.wid < 0: - gl.foreground() - gl.prefsize(self.vin.width, self.vin.height) - self.wid = gl.winopen(self.title) - gl.clear() - self.vin.initcolormap() - gl.winset(self.wid) - if self.qindex >= self.qsize: - self.vin.clear() - return - dt, d, cd = self.vin.getrandomframe(self.qindex) - self.vin.showframe(d, cd) - - def redraw(self, wid): - if wid == self.wid >= 0: - gl.winset(self.wid) - gl.reshapeviewport() - self.vin.clear() - self.show() - - def get(self): - if self.qindex >= self.qsize: - return None - if self.qindex > 0: - prevt, ds, cs = \ - self.vin.getrandomframeheader(self.qindex-1) - else: - prevt = 0 - t, data, cdata = self.vin.getrandomframe(self.qindex) - self.qindex = self.qindex + 1 - return t-prevt, data, cdata - - def backup(self): - if self.qindex == 0: - return 0 - self.qindex = self.qindex - 1 - return 1 - - def seek(self, i): - if not 0 <= i <= self.qsize: - return 0 - self.qindex = i - return 1 - - def tell(self): - return self.qindex - - def qsizes(self): - return self.qindex, self.qsize - self.qindex - - def qinfo(self): - return 0, self.qindex, self.qsize - - -class OutputViewer: - - def __init__(self, filename, title, qsize): - try: - self.vout = VFile.VoutFile(filename) - except (EOFError, VFile.Error): - raise IOError, 'bad video output file' - if not title: - title = os.path.split(filename)[1] - self.filename = filename - self.title = title - self.qsize = qsize - gl.foreground() - self.wid = -1 - self.reset() - - def close(self): - while self.queue: - self.flushq() - self.vout.close() - if self.wid > 0: - gl.winclose(self.wid) - - def rewind(self): - info = self.vout.getinfo() - self.vout.close() - self.vout = VFile.VoutFile(self.filename) - self.vout.setinfo(info) - self.reset() - - def getinfo(self): - return self.vout.getinfo() - - def setinfo(self, info): - if info == self.getinfo(): return # No change - self.vout.setinfo(info) - if self.wid > 0: - gl.winclose(self.wid) - self.wid = -1 - - # Internal - def reset(self): - if self.wid > 0: - gl.winset(self.wid) - gl.clear() - self.vout.initcolormap() - self.queue = [] - self.spares = [] - self.written = 0 - self.lastt = 0 - - # Internal - def flushq(self): - if self.written == 0: - self.vout.writeheader() - dt, d, cd = self.queue[0] - self.lastt = self.lastt + dt - self.vout.writeframe(self.lastt, d, cd) - del self.queue[0] - self.written = self.written + 1 - - def show(self): - if self.wid < 0: - gl.foreground() - gl.prefsize(self.vout.width, self.vout.height) - self.wid = gl.winopen(self.title) - gl.clear() - self.vout.initcolormap() - gl.winset(self.wid) - if not self.queue: - self.vout.clear() - return - dt, d, cd = self.queue[-1] - self.vout.showframe(d, cd) - - def redraw(self, wid): - if wid == self.wid >= 0: - gl.winset(self.wid) - gl.reshapeviewport() - self.vout.clear() - self.show() - - def backup(self): - if len(self.queue) < 1: return 0 - self.spares.insert(0, self.queue[-1]) - del self.queue[-1] - return 1 - - def forward(self): - if not self.spares: return 0 - self.queue.append(self.spares[0]) - del self.spares[0] - return 1 - - def put(self, item): - self.queue.append(item) - self.spares = [] - while len(self.queue) > self.qsize: - self.flushq() - - def seek(self, i): - i = i - self.written - if not 0 <= i <= len(self.queue) + len(self.spares): - return 0 - while i < len(self.queue): - if not self.backup(): - return 0 - while i > len(self.queue): - if not self.forward(): - return 0 - return 1 - - def trunc(self): - del self.spares[:] - - def tell(self): - return self.written + len(self.queue) - - def qsizes(self): - return len(self.queue), len(self.spares) - - def qinfo(self): - first = self.written - pos = first + len(self.queue) - last = pos + len(self.spares) - return first, pos, last - - -def test(): - import sys - a = InputViewer(sys.argv[1], '') - b = OutputViewer(sys.argv[2], '') - b.setinfo(a.getinfo()) - - while 1: - a.show() - data = a.get() - if data is None: - break - b.put(data) - b.show() - - while a.backup(): - data = a.get() - b.put(data) - b.show() - if a.backup(): a.show() - - while 1: - data = a.get() - if data is None: - break - b.put(data) - b.show() - a.show() - - b.close() diff --git a/Demo/sgi/video/Vinfo.py b/Demo/sgi/video/Vinfo.py deleted file mode 100755 index 0d9d29423c..0000000000 --- a/Demo/sgi/video/Vinfo.py +++ /dev/null @@ -1,174 +0,0 @@ -#! /usr/bin/env python - -# Print some info about a CMIF movie file - - -# Usage: -# -# Vinfo [-d] [-q] [-s] [-t] [file] ... - - -# Options: -# -# -d : print deltas between frames instead of frame times -# -q : quick: don't read the frames -# -s : don't print times (but do count frames and print the total) -# -t : terse (one line/file, implies -s) -# file ... : file(s) to inspect; default film.video - - -import sys -sys.path.append('/ufs/guido/src/video') -import VFile -import getopt -import string - - -# Global options - -short = 0 -quick = 0 -delta = 0 -terse = 0 -maxwidth = 10 - - -# Main program -- mostly command line parsing - -def main(): - global short, quick, delta, terse, maxwidth - try: - opts, args = getopt.getopt(sys.argv[1:], 'dqst') - except getopt.error, msg: - sys.stdout = sys.stderr - print msg - print 'usage: Vinfo [-d] [-q] [-s] [-t] [file] ...' - sys.exit(2) - for opt, arg in opts: - if opt == '-q': - quick = 1 - if opt == '-d': - delta = 1 - if opt == '-s': - short = 1 - if opt == '-t': - terse = short = 1 - if not args: - args = ['film.video'] - for filename in args: - maxwidth = max(maxwidth, len(filename)) - sts = 0 - for filename in args: - if process(filename): - sts = 1 - sys.exit(sts) - - -# Process one file - -def process(filename): - try: - vin = VFile.RandomVinFile(filename) - except IOError, msg: - sys.stderr.write(filename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(filename + ': EOF in video file\n') - return 1 - - if terse: - print string.ljust(filename, maxwidth), - kbytes = (VFile.getfilesize(filename) + 1023) / 1024 - print string.rjust(`kbytes`, 5) + 'K', - print ' ', string.ljust(`vin.version`, 5), - print string.ljust(vin.format, 8), - print string.rjust(`vin.width`, 4), - print string.rjust(`vin.height`, 4), - if type(vin.packfactor) == type(()): - xpf, ypf = vin.packfactor - s = string.rjust(`xpf`, 2) + ',' + \ - string.rjust(`ypf`, 2) - else: - s = string.rjust(`vin.packfactor`, 2) - if type(vin.packfactor) == type(0) and \ - vin.format not in ('rgb', 'jpeg') and \ - (vin.width/vin.packfactor) % 4 <> 0: - s = s + '! ' - else: - s = s + ' ' - print s, - sys.stdout.flush() - else: - vin.printinfo() - - if quick: - if terse: - print - vin.close() - return 0 - - try: - vin.readcache() - if not terse: - print '[Using cached index]' - except VFile.Error: - if not terse: - print '[Constructing index on the fly]' - - if not short: - if delta: - print 'Frame time deltas:', - else: - print 'Frame times:', - - n = 0 - t = 0 - told = 0 - datasize = 0 - while 1: - try: - t, ds, cs = vin.getnextframeheader() - vin.skipnextframedata(ds, cs) - except EOFError: - break - datasize = datasize + ds - if cs: datasize = datasize + cs - if not short: - if n%8 == 0: - sys.stdout.write('\n') - if delta: - sys.stdout.write('\t' + `t - told`) - told = t - else: - sys.stdout.write('\t' + `t`) - n = n+1 - - if not short: print - - if terse: - print string.rjust(`n`, 6), - if t: print string.rjust(`int(n*10000.0/t)*0.1`, 5), - print - else: - print 'Total', n, 'frames in', t*0.001, 'sec.', - if t: print '-- average', int(n*10000.0/t)*0.1, 'frames/sec', - print - print 'Total data', 0.1 * int(datasize / 102.4), 'Kbytes', - if t: - print '-- average', - print 0.1 * int(datasize / 0.1024 / t), 'Kbytes/sec', - print - - vin.close() - return 0 - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vmkjpeg.py b/Demo/sgi/video/Vmkjpeg.py deleted file mode 100755 index 0c9687a8c5..0000000000 --- a/Demo/sgi/video/Vmkjpeg.py +++ /dev/null @@ -1,92 +0,0 @@ -#! /usr/bin/env python - -# Compress an rgb or grey video file to jpeg format - - -# Usage: -# -# Vmkjpeg [infile [outfile]] - - -# Options: -# -# infile : input file (default film.video) -# outfile : output file (default out.video) - - -import sys -import jpeg -sys.path.append('/ufs/guido/src/video') -import VFile - - -# Main program -- mostly command line parsing - -def main(): - args = sys.argv[1:] - if len(args) < 1: - args.append('film.video') - if len(args) < 2: - args.append('out.video') - if len(args) > 2: - sys.stderr.write('usage: Vmkjpeg [infile [outfile]]\n') - sys.exit(2) - sts = process(args[0], args[1]) - sys.exit(sts) - - -# Copy one file to another - -def process(infilename, outfilename): - try: - vin = VFile.BasicVinFile(infilename) - except IOError, msg: - sys.stderr.write(infilename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(infilename + ': EOF in video file\n') - return 1 - - try: - vout = VFile.BasicVoutFile(outfilename) - except IOError, msg: - sys.stderr.write(outfilename + ': I/O error: ' + `msg` + '\n') - return 1 - - info = vin.getinfo() - if info[0] == 'rgb': - width, height = vin.getsize() - bytes = 4 - format = 'jpeg' - elif info[0] == 'grey': - width, height = vin.getsize() - pf = vin.packfactor - width, height = width / pf, height / pf - bytes = 1 - format = 'jpeggrey' - else: - sys.stderr.write('Vmkjpeg: input not in rgb or grey format\n') - return 1 - info = (format,) + info[1:] - vout.setinfo(info) - vout.writeheader() - n = 0 - try: - while 1: - t, data, cdata = vin.getnextframe() - n = n + 1 - sys.stderr.write('Frame ' + `n` + '...') - data = jpeg.compress(data, width, height, bytes) - vout.writeframe(t, data, None) - sys.stderr.write('\n') - except EOFError: - pass - return 0 - - -# Don't forget to call the main program - -main() diff --git a/Demo/sgi/video/Vplay.py b/Demo/sgi/video/Vplay.py deleted file mode 100755 index 176c0e5a0c..0000000000 --- a/Demo/sgi/video/Vplay.py +++ /dev/null @@ -1,355 +0,0 @@ -#! /usr/bin/env python - -# Play CMIF movie files - - -# Help function - -def help(): - print 'Usage: Vplay [options] [file] ...' - print - print 'Options:' - print '-M magnify : magnify the image by the given factor' - print '-d : write some debug stuff on stderr' - print '-l : loop, playing the movie over and over again' - print '-m delta : drop frames closer than delta seconds (default 0.)' - print '-n : don\'t wait after each file' - print '-q : quiet, no informative messages' - print '-r delta : regenerate input time base delta seconds apart' - print '-s speed : speed change factor (default 1.0)' - print '-t : use a 2nd thread for read-ahead' - print '-x left : window offset from left of screen' - print '-y top : window offset from top of screen' - print '-w width : window width' - print '-h height : window height' - print '-b color : background color (white,black or (r,g,b))' - print 'file ... : file(s) to play; default film.video' - print - print 'User interface:' - print 'Press the left mouse button to stop or restart the movie.' - print 'Press ESC or use the window manager Close or Quit command' - print 'to close the window and play the next file (if any).' - - -# Imported modules - -import sys -sys.path.append('/ufs/guido/src/video') # Increase chance of finding VFile -import VFile -import time -import gl, GL -from DEVICE import REDRAW, ESCKEY, LEFTMOUSE, WINSHUT, WINQUIT -import getopt -import string - - -# Global options - -debug = 0 -looping = 0 -magnify = 1 -mindelta = 0 -nowait = 0 -quiet = 0 -regen = None -speed = 1.0 -threading = 0 -xoff = yoff = None -xwsiz = ywsiz = None -bgcolor = None - - -# Main program -- mostly command line parsing - -def main(): - global debug, looping, magnify, mindelta, nowait, quiet, regen, speed - global threading, xoff, yoff, xwsiz, ywsiz, bgcolor - - # Parse command line - try: - opts, args = getopt.getopt(sys.argv[1:], \ - 'M:dlm:nqr:s:tx:y:w:h:b:') - except getopt.error, msg: - sys.stdout = sys.stderr - print 'Error:', msg, '\n' - help() - sys.exit(2) - - # Interpret options - try: - for opt, arg in opts: - if opt == '-M': magnify = float(eval(arg)) - if opt == '-d': debug = debug + 1 - if opt == '-l': looping = 1 - if opt == '-m': mindelta = float(eval(arg)) - if opt == '-n': nowait = 1 - if opt == '-q': quiet = 1 - if opt == '-r': regen = float(eval(arg)) - if opt == '-s': - try: - speed = float(eval(arg)) - except: - sys.stdout = sys.stderr - print 'Option -s needs float argument' - sys.exit(2) - if opt == '-t': - try: - import thread - threading = 1 - except ImportError: - print 'Sorry, this version of Python', - print 'does not support threads:', - print '-t ignored' - if opt == '-x': xoff = string.atoi(arg) - if opt == '-y': yoff = string.atoi(arg) - if opt == '-w': xwsiz = string.atoi(arg) - if opt == '-h': ywsiz = string.atoi(arg) - if opt == '-b': - if arg == 'black': - bgcolor = (0,0,0) - elif arg == 'white': - bgcolor = (255,255,255) - else: - try: - bgcolor = eval(arg) - xxr, xxg, xxb = bgcolor - except: - print '-b needs (r,g,b) tuple' - sys.exit(2) - except string.atoi_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires integer argument' - sys.exit(2) - - # Check validity of certain options combinations - if nowait and looping: - print 'Warning: -n and -l are mutually exclusive; -n ignored' - nowait = 0 - if xoff <> None and yoff == None: - print 'Warning: -x without -y ignored' - if xoff == None and yoff <> None: - print 'Warning: -y without -x ignored' - - # Process all files - if not args: args = ['film.video'] - sts = 0 - for filename in args: - sts = (process(filename) or sts) - - # Exit with proper exit status - sys.exit(sts) - - -# Process one movie file - -def process(filename): - try: - vin = VFile.VinFile(filename) - except IOError, msg: - sys.stderr.write(filename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(filename + ': EOF in video header\n') - return 1 - - if not quiet: - vin.printinfo() - - gl.foreground() - - width, height = int(vin.width * magnify), int(vin.height * magnify) - xborder = yborder = 0 - if xwsiz: - vin.xorigin = (xwsiz - width)/2 - width = xwsiz - if ywsiz: - vin.yorigin = (ywsiz - height)/2 - height = ywsiz - if xoff <> None and yoff <> None: - scrheight = gl.getgdesc(GL.GD_YPMAX) - gl.prefposition(xoff, xoff+width-1, \ - scrheight-yoff-height, scrheight-yoff-1) - else: - gl.prefsize(width, height) - - win = gl.winopen(filename) - gl.clear() - - if quiet: vin.quiet = 1 - vin.initcolormap() - - if bgcolor: - r, g, b = bgcolor - vin.clearto(r,g,b) - - gl.qdevice(ESCKEY) - gl.qdevice(WINSHUT) - gl.qdevice(WINQUIT) - gl.qdevice(LEFTMOUSE) - - stop = 0 - - while not stop: - gl.wintitle(filename) - stop = (playonce(vin) or nowait) - gl.wintitle('(done) ' + filename) - if not looping: - while not stop: - dev, val = gl.qread() - if dev == REDRAW: - if bgcolor: - r,g,b = bgcolor - vin.clearto(r,g,b) - else: - vin.clear() - if dev == LEFTMOUSE and val == 1: - break # Continue outer loop - if dev == ESCKEY and val == 1 or \ - dev in (WINSHUT, WINQUIT): - stop = 1 - - # Set xoff, yoff for the next window from the current window - global xoff, yoff - xoff, yoff = gl.getorigin() - width, height = gl.getsize() - scrheight = gl.getgdesc(GL.GD_YPMAX) - yoff = scrheight - yoff - height - gl.winclose(win) - - return 0 - - -# Play a movie once; return 1 if user wants to stop, 0 if not - -def playonce(vin): - vin.rewind() - vin.colormapinited = 1 - vin.magnify = magnify - - if threading: - MAXSIZE = 20 # Don't read ahead too much - import thread - import Queue - queue = Queue.Queue(MAXSIZE) - stop = [] - thread.start_new_thread(read_ahead, (vin, queue, stop)) - # Get the read-ahead thread going - while queue.qsize() < MAXSIZE/2 and not stop: - time.sleep(0.100) - - tin = 0 - toffset = 0 - oldtin = 0 - told = 0 - nin = 0 - nout = 0 - nlate = 0 - nskipped = 0 - data = None - - tlast = t0 = time.time() - - while 1: - if gl.qtest(): - dev, val = gl.qread() - if dev == ESCKEY and val == 1 or \ - dev in (WINSHUT, WINQUIT) or \ - dev == LEFTMOUSE and val == 1: - if debug: sys.stderr.write('\n') - if threading: - stop.append(None) - while 1: - item = queue.get() - if item == None: break - return (dev != LEFTMOUSE) - if dev == REDRAW: - gl.reshapeviewport() - if data: vin.showframe(data, cdata) - if threading: - if debug and queue.empty(): sys.stderr.write('.') - item = queue.get() - if item == None: break - tin, data, cdata = item - else: - try: - tin, size, csize = vin.getnextframeheader() - except EOFError: - break - tin = tin*0.001 - nin = nin+1 - if tin+toffset < oldtin: - print 'Fix reversed time:', oldtin, 'to', tin - toffset = oldtin - tin - tin = tin + toffset - oldtin = tin - if regen: tout = nin * regen - else: tout = tin - tout = tout / speed - if tout - told < mindelta: - nskipped = nskipped + 1 - if not threading: - vin.skipnextframedata(size, csize) - else: - if not threading: - try: - data, cdata = \ - vin.getnextframedata(size, csize) - except EOFError: - if not quiet: - print '[incomplete last frame]' - break - now = time.time() - dt = (tout-told) - (now-tlast) - told = tout - if debug: sys.stderr.write(`round(dt, 3)` + ' ') - if dt < 0: nlate = nlate + 1 - if dt > 0: - time.sleep(dt) - now = time.time() - tlast = now - vin.showframe(data, cdata) - nout = nout + 1 - - t1 = time.time() - - if debug: sys.stderr.write('\n') - - if quiet: return 0 - - print 'Recorded:', nin, 'frames in', round(tin, 3), 'sec.', - if tin: print '-- average', round(nin/tin, 1), 'frames/sec', - print - - if nskipped: print 'Skipped', nskipped, 'frames' - - tout = t1-t0 - print 'Played:', nout, - print 'frames in', round(tout, 3), 'sec.', - if tout: print '-- average', round(nout/tout, 1), 'frames/sec', - print - - if nlate: print 'There were', nlate, 'late frames' - - return 0 - - -# Read-ahead thread - -def read_ahead(vin, queue, stop): - try: - while not stop: queue.put(vin.getnextframe()) - except EOFError: - pass - queue.put(None) - stop.append(None) - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vrec.py b/Demo/sgi/video/Vrec.py deleted file mode 100755 index 11039bbfd1..0000000000 --- a/Demo/sgi/video/Vrec.py +++ /dev/null @@ -1,413 +0,0 @@ -#! /usr/bin/env python -#! /ufs/guido/bin/sgi/python-405 - -# Capture a CMIF movie using the Indigo video library and board - -# The CMIF video file format is documented in cmif-film.ms. -# Audio data is recorded in AIFF format, using the input sampling -# rate, source and volume set by the audio panel, in mono, 8 -# bits/sample. - - -# Usage and help functions (keep this up-to-date if you change the program!) - -def usage(): - print 'Usage: Vrec [options] [moviefile [audiofile]]' - print - print 'Options:' - print '-a : record audio as well' - print '-q queuesize : set the capture queue size (default 2)' - print '-r rate : capture 1 out of every "rate" frames', \ - '(default and min 2)' - print '-w width : initial window width', \ - '(default 256, use 0 for interactive placement)' - print '-n : Don\'t write to file, only timing info' - print '-d : drop fields if needed' - print '-g bits : greyscale (2, 4 or 8 bits)' - print '-G : 2-bit greyscale dithered' - print '-m : monochrome dithered' - print '-M value : monochrome thresholded with value' - print '-f : Capture fields (in stead of frames)' - print '-P frames : preallocate space for "frames" frames' - print 'moviefile : here goes the movie data (default film.video)' - print 'audiofile : with -a, here goes the audio data', \ - '(default film.aiff)' - -def help(): - print 'Press the left mouse button to start recording, release it to' - print 'end recording. You can record as many times as you wish, but' - print 'each recording overwrites the output file(s) -- only the last' - print 'recording is kept.' - print - print 'Press ESC or use the window manager Quit or Close window option' - print 'to quit. If you quit before recording anything, the output' - print 'file(s) are not touched.' - - -# Imported modules - -import sys -sys.path.append('/ufs/guido/src/video') -import sv, SV -import VFile -import gl, GL, DEVICE -import al, AL -import time -import posix -import getopt -import string -import imageop -import sgi - - -# Main program - -def main(): - format = SV.RGB8_FRAMES - qsize = 2 - audio = 0 - rate = 2 - width = 0 - norecord = 0 - drop = 0 - mono = 0 - grey = 0 - greybits = 0 - monotreshold = -1 - fields = 0 - preallocspace = 0 - - # Parse command line - try: - opts, args = getopt.getopt(sys.argv[1:], 'aq:r:w:ndg:mM:GfP:') - except getopt.error, msg: - sys.stdout = sys.stderr - print 'Error:', msg, '\n' - usage() - sys.exit(2) - - # Interpret options - try: - for opt, arg in opts: - if opt == '-a': - audio = 1 - elif opt == '-q': - qsize = string.atoi(arg) - elif opt == '-r': - rate = string.atoi(arg) - if rate < 2: - sys.stderr.write( \ - '-r rate must be >= 2\n') - sys.exit(2) - elif opt == '-w': - width = string.atoi(arg) - elif opt == '-n': - norecord = 1 - elif opt == '-d': - drop = 1 - elif opt == '-g': - grey = 1 - greybits = string.atoi(arg) - if not greybits in (2, 4, 8): - sys.stderr.write( \ - 'Only 2, 4 or 8 bit greyscale supported\n') - sys.exit(2) - elif opt == '-G': - grey = 1 - greybits = -2 - elif opt == '-m': - mono = 1 - elif opt == '-M': - mono = 1 - monotreshold = string.atoi(arg) - elif opt == '-f': - fields = 1 - elif opt == '-P': - preallocspace = string.atoi(arg) - except string.atoi_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires integer argument' - sys.exit(2) - - # Check excess arguments - # If norecord is on, refuse filename arguments - if norecord: - if args: - sys.stdout = sys.stderr - print 'With -n, no filename arguments are used\n' - usage() - sys.exit(2) - elif args[2:]: - sys.stdout = sys.stderr - print 'Too many filename arguments\n' - usage() - sys.exit(2) - - # Process file arguments - if args: - filename = args[0] - else: - filename = 'film.video' - - if args[1:] and not audio: - sys.stderr.write('-a turned on by appearance of 2nd file\n') - audio = 1 - - if audio: - if args[1:]: - audiofilename = args[1] - else: - audiofilename = 'film.aiff' - else: - audiofilename = None - - if norecord: - filename = audiofilename = '' - - # Open video - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - x = SV.PAL_XMAX - y = SV.PAL_YMAX - elif param[1] == SV.NTSC: - x = SV.NTSC_XMAX - y = SV.NTSC_YMAX - else: - print 'Unknown video standard', param[1] - sys.exit(1) - - gl.foreground() - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - if width: - height = width*3/4 - x1 = 150 - x2 = x1 + width-1 - y2 = 768-150 - y1 = y2-height+1 - gl.prefposition(x1, x2, y1, y2) - win = gl.winopen(filename) - if width: - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.winconstraints() - x, y = gl.getsize() - print x, 'x', y - - v.SetSize(x, y) - - if drop: - param = [SV.FIELDDROP, 1, SV.GENLOCK, SV.GENLOCK_OFF] - else: - param = [SV.FIELDDROP, 0, SV.GENLOCK, SV.GENLOCK_ON] - if mono or grey: - param = param+[SV.COLOR, SV.MONO, SV.DITHER, 0, \ - SV.INPUT_BYPASS, 1] - else: - param = param+[SV.COLOR, SV.DEFAULT_COLOR, SV.INPUT_BYPASS, 0] - - v.BindGLWindow(win, SV.IN_REPLACE) - v.SetParam(param) - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - help() - - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE: - if val == 1: - info = format, x, y, qsize, rate - record(v, info, filename, audiofilename,\ - mono, grey, greybits, monotreshold, \ - fields, preallocspace) - elif dev == DEVICE.REDRAW: - # Window resize (or move) - x, y = gl.getsize() - print x, 'x', y - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - # Quit - v.CloseVideo() - gl.winclose(win) - break - - -# Record until the mouse is released (or any other GL event) -# XXX audio not yet supported - -def record(v, info, filename, audiofilename, mono, grey, greybits, \ - monotreshold, fields, preallocspace): - import thread - format, x, y, qsize, rate = info - fps = 59.64 # Fields per second - # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) - tpf = 1000.0 / fps # Time per field in msec - if filename: - vout = VFile.VoutFile(filename) - if mono: - format = 'mono' - elif grey and greybits == 8: - format = 'grey' - elif grey: - format = 'grey'+`abs(greybits)` - else: - format = 'rgb8' - vout.setformat(format) - vout.setsize(x, y) - if fields: - vout.setpf((1, -2)) - vout.writeheader() - if preallocspace: - print 'Preallocating space...' - vout.prealloc(preallocspace) - print 'done.' - MAXSIZE = 20 # XXX should be a user option - import Queue - queue = Queue.Queue(MAXSIZE) - done = thread.allocate_lock() - done.acquire_lock() - convertor = None - if grey: - if greybits == 2: - convertor = imageop.grey2grey2 - elif greybits == 4: - convertor = imageop.grey2grey4 - elif greybits == -2: - convertor = imageop.dither2grey2 - thread.start_new_thread(saveframes, \ - (vout, queue, done, mono, monotreshold, convertor)) - if audiofilename: - audiodone = thread.allocate_lock() - audiodone.acquire_lock() - audiostop = [] - initaudio(audiofilename, audiostop, audiodone) - gl.wintitle('(rec) ' + filename) - lastid = 0 - t0 = time.time() - count = 0 - ids = [] - v.InitContinuousCapture(info) - while not gl.qtest(): - try: - cd, id = v.GetCaptureData() - except sv.error: - #time.sleep(0.010) # XXX is this necessary? - sgi.nap(1) # XXX Try by Jack - continue - ids.append(id) - - id = id + 2*rate -## if id <> lastid + 2*rate: -## print lastid, id - lastid = id - count = count+1 - if fields: - data1, data2 = cd.GetFields() - cd.UnlockCaptureData() - if filename: - queue.put((data1, int(id*tpf))) - queue.put((data2, int((id+1)*tpf))) - else: - data = cd.InterleaveFields(1) - cd.UnlockCaptureData() - if filename: - queue.put((data, int(id*tpf))) - t1 = time.time() - gl.wintitle('(busy) ' + filename) - print lastid, 'fields in', round(t1-t0, 3), 'sec', - print '--', round(lastid/(t1-t0), 1), 'fields/sec' - print 'Captured',count*2, 'fields,', - print round(count*2/(t1-t0), 1), 'f/s', - if lastid: - print '(', - print round(count*200.0/lastid), '%, or', - print round(count*rate*200.0/lastid), '% of wanted rate )', - print - if ids: - print 'Ids:', - t0 = ids[0] - del ids[0] - for t1 in ids: - print t1-t0, - t0 = t1 - print - if filename and audiofilename: - audiostop.append(None) - audiodone.acquire_lock() - v.EndContinuousCapture() - if filename: - queue.put(None) # Sentinel - done.acquire_lock() - gl.wintitle('(done) ' + filename) - - -# Thread to save the frames to the file - -def saveframes(vout, queue, done, mono, monotreshold, convertor): - while 1: - x = queue.get() - if not x: - break - data, t = x - if convertor: - data = convertor(data, len(data), 1) - elif mono and monotreshold >= 0: - data = imageop.grey2mono(data, len(data), 1,\ - monotreshold) - elif mono: - data = imageop.dither2mono(data, len(data), 1) - vout.writeframe(t, data, None) - sys.stderr.write('Done writing video\n') - vout.close() - done.release_lock() - - -# Initialize audio recording - -AQSIZE = 8000 # XXX should be a user option - -def initaudio(filename, stop, done): - import thread, aifc - afile = aifc.open(filename, 'w') - afile.setnchannels(AL.MONO) - afile.setsampwidth(AL.SAMPLE_8) - params = [AL.INPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, params) - print 'audio sampling rate =', params[1] - afile.setframerate(params[1]) - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(AQSIZE) - c.setwidth(AL.SAMPLE_8) - aport = al.openport(filename, 'r', c) - thread.start_new_thread(audiorecord, (afile, aport, stop, done)) - - -# Thread to record audio samples - -def audiorecord(afile, aport, stop, done): - while not stop: - data = aport.readsamps(AQSIZE/2) - afile.writesampsraw(data) - del data - afile.close() - print 'Done writing audio' - done.release_lock() - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vrecb.py b/Demo/sgi/video/Vrecb.py deleted file mode 100755 index 5cdde9e621..0000000000 --- a/Demo/sgi/video/Vrecb.py +++ /dev/null @@ -1,429 +0,0 @@ -#! /usr/bin/env python - -# Capture a CMIF movie using the Indigo video library and board in burst mode - - -# User interface: -# -# Start the application. Resize the window to the desired movie size. -# Press the left mouse button to start recording, release it to end -# recording. You can record as many times as you wish, but each time -# you overwrite the output file(s), so only the last recording is -# kept. -# -# Press ESC or select the window manager Quit or Close window option -# to quit. If you quit before recording anything, the output file(s) -# are not touched. - - -import sys -sys.path.append('/ufs/guido/src/video') -import sv, SV -import VFile -import gl, GL, DEVICE -import al, AL -import time -import posix -import getopt -import string -import imageop -import sgi - - -# Usage and help functions (keep this up-to-date if you change the program!) - -def usage(): - print 'Usage: Vrecb [options] [moviefile [audiofile]]' - print - print 'Options:' - print '-a : record audio as well' - print '-r rate : capture 1 out of every "rate" frames', \ - '(default and min 1)' - print '-w width : initial window width', \ - '(default 256, use 0 for interactive placement)' - print '-d : drop fields if needed' - print '-g bits : greyscale (2, 4 or 8 bits)' - print '-G : 2-bit greyscale dithered' - print '-m : monochrome dithered' - print '-M value : monochrome thresholded with value' - print '-f : Capture fields (instead of frames)' - print '-n number : Capture this many frames (default 60)' - print '-N memsize : Capture frames fitting in this many kbytes' - print 'moviefile : here goes the movie data (default film.video)' - -def help(): - print 'Press the left mouse button to start recording.' - print 'Recording time is determined by the -n option.' - print 'You can record as many times as you wish, but each' - print 'recording overwrites the output file(s) -- only the' - print 'last recording is kept.' - print - print 'Press ESC or use the window manager Quit or Close window option' - print 'to quit. If you quit before recording anything, the output' - print 'file(s) are not touched.' - - -# Main program - -def main(): - format = SV.RGB8_FRAMES - audio = 0 - rate = 1 - width = 256 - drop = 0 - mono = 0 - grey = 0 - greybits = 0 - monotreshold = -1 - fields = 0 - number = 0 - memsize = 0 - - try: - opts, args = getopt.getopt(sys.argv[1:], 'ar:w:dg:mM:Gfn:N:') - except getopt.error, msg: - sys.stdout = sys.stderr - print 'Error:', msg, '\n' - usage() - sys.exit(2) - - try: - for opt, arg in opts: - if opt == '-a': - audio = 1 - if opt == '-r': - rate = string.atoi(arg) - if rate < 1: - sys.stderr.write('-r rate must be >= 1\n') - sys.exit(2) - elif opt == '-w': - width = string.atoi(arg) - elif opt == '-d': - drop = 1 - elif opt == '-g': - grey = 1 - greybits = string.atoi(arg) - if not greybits in (2,4,8): - sys.stderr.write( \ - 'Only 2, 4 or 8 bit greyscale supported\n') - sys.exit(2) - elif opt == '-G': - grey = 1 - greybits = -2 - elif opt == '-m': - mono = 1 - elif opt == '-M': - mono = 1 - monotreshold = string.atoi(arg) - elif opt == '-f': - fields = 1 - elif opt == '-n': - number = string.atoi(arg) - elif opt == '-N': - memsize = string.atoi(arg) - if 0 < memsize < 1024: - memsize = memsize * 1024 - if 0 < memsize < 1024*1024: - memsize = memsize * 1024 - print 'memsize', memsize - except string.atoi_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires integer argument' - sys.exit(2) - - if number <> 0 and memsize <> 0: - sys.stderr.write('-n and -N are mutually exclusive\n') - sys.exit(2) - if number == 0 and memsize == 0: - number = 60 - - if not fields: - print '-f option assumed until somebody fixes it' - fields = 1 - - if args[2:]: - sys.stderr.write('usage: Vrecb [options] [file [audiofile]]\n') - sys.exit(2) - - if args: - filename = args[0] - else: - filename = 'film.video' - - if args[1:] and not audio: - sys.stderr.write('-a turned on by appearance of 2nd file\n') - audio = 1 - - if audio: - if args[1:]: - audiofilename = args[1] - else: - audiofilename = 'film.aiff' - else: - audiofilename = None - - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - x = SV.PAL_XMAX - y = SV.PAL_YMAX - elif param[1] == SV.NTSC: - x = SV.NTSC_XMAX - y = SV.NTSC_YMAX - else: - print 'Unknown video standard', param[1] - sys.exit(1) - - gl.foreground() - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - if width: - height = width*3/4 - x1 = 150 - x2 = x1 + width-1 - y2 = 768-150 - y1 = y2-height+1 - gl.prefposition(x1, x2, y1, y2) - win = gl.winopen(filename) - if width: - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.winconstraints() - x, y = gl.getsize() - print x, 'x', y - if memsize: - number = calcnumber(x, y, grey or mono, memsize) - print number, 'frames' - v.SetSize(x, y) - - if drop: - param = [SV.FIELDDROP, 1, SV.GENLOCK, SV.GENLOCK_OFF] - else: - param = [SV.FIELDDROP, 0, SV.GENLOCK, SV.GENLOCK_ON] - if mono or grey: - param = param+[SV.COLOR, SV.MONO, SV.DITHER, 0, \ - SV.INPUT_BYPASS, 1] - else: - param = param+[SV.COLOR, SV.DEFAULT_COLOR, SV.INPUT_BYPASS, 0] - - v.BindGLWindow(win, SV.IN_REPLACE) - v.SetParam(param) - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - help() - - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE: - if val == 1: - info = format, x, y, number, rate - record(v, info, filename, audiofilename, \ - mono, grey, \ - greybits, monotreshold, fields) - elif dev == DEVICE.REDRAW: - # Window resize (or move) - x, y = gl.getsize() - print x, 'x', y - if memsize: - number = calcnumber(x, y, grey or mono, memsize) - print number, 'frames' - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - # Quit - v.CloseVideo() - gl.winclose(win) - break - - -def calcnumber(x, y, grey, memsize): - pixels = x*y - pixels = pixels/2 # XXX always assume fields - if grey: n = memsize/pixels - else: n = memsize/(4*pixels) - return max(1, n) - - -# Record until the mouse is released (or any other GL event) -# XXX audio not yet supported - -def record(v, info, filename, audiofilename, \ - mono, grey, greybits, monotreshold, fields): - import thread - format, x, y, number, rate = info - fps = 59.64 # Fields per second - # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) - tpf = 1000.0 / fps # Time per field in msec - # - # Go grab - # - if audiofilename: - gl.wintitle('(start audio) ' + filename) - audiodone = thread.allocate_lock() - audiodone.acquire_lock() - audiostart = thread.allocate_lock() - audiostart.acquire_lock() - audiostop = [] - initaudio(audiofilename, audiostop, audiostart, audiodone) - audiostart.acquire_lock() - gl.wintitle('(rec) ' + filename) - try: - ninfo, data, bitvec = v.CaptureBurst(info) - except sv.error, arg: - print 'CaptureBurst failed:', arg - print 'info:', info - gl.wintitle(filename) - return - gl.wintitle('(save) '+ filename) - # - # Check results - # - if info <> ninfo: - print 'Sorry, format changed.' - print 'Wanted:',info - print 'Got :',ninfo - gl.wintitle(filename) - return - # print bitvec - if x*y*number <> len(data): - print 'Funny data length: wanted',x,'*',y,'*', number,'=',\ - x*y*number,'got',len(data) - gl.wintitle(filename) - return - # - # Save - # - if filename and audiofilename: - audiostop.append(None) - audiodone.acquire_lock() - if filename: - # - # Construct header and write it - # - try: - vout = VFile.VoutFile(filename) - except IOError, msg: - print filename, ':', msg - sys.exit(1) - if mono: - vout.format = 'mono' - elif grey and greybits == 8: - vout.format = 'grey' - elif grey: - vout.format = 'grey'+`abs(greybits)` - else: - vout.format = 'rgb8' - vout.width = x - vout.height = y - if fields: - vout.packfactor = (1,-2) - else: - print 'Sorry, can only save fields at the moment' - print '(i.e. you *must* use the -f option)' - gl.wintitle(filename) - return - vout.writeheader() - # - # Compute convertor, if needed - # - convertor = None - if grey: - if greybits == 2: - convertor = imageop.grey2grey2 - elif greybits == 4: - convertor = imageop.grey2grey4 - elif greybits == -2: - convertor = imageop.dither2grey2 - fieldsize = x*y/2 - nskipped = 0 - realframeno = 0 - tpf = 1000 / 50.0 #XXXX - # Trying to find the pattern in frame skipping - okstretch = 0 - skipstretch = 0 - for frameno in range(0, number*2): - if frameno <> 0 and \ - bitvec[frameno] == bitvec[frameno-1]: - nskipped = nskipped + 1 - if okstretch: - print okstretch, 'ok', - okstretch = 0 - skipstretch = skipstretch + 1 - continue - if skipstretch: - print skipstretch, 'skipped' - skipstretch = 0 - okstretch = okstretch + 1 - # - # Save field. - # XXXX Works only for fields and top-to-bottom - # - start = frameno*fieldsize - field = data[start:start+fieldsize] - if convertor: - field = convertor(field, len(field), 1) - elif mono and monotreshold >= 0: - field = imageop.grey2mono( \ - field, len(field), 1, monotreshold) - elif mono: - field = imageop.dither2mono( \ - field, len(field), 1) - realframeno = realframeno + 1 - vout.writeframe(int(realframeno*tpf), field, None) - print okstretch, 'ok', - print skipstretch, 'skipped' - print 'Skipped', nskipped, 'duplicate frames' - vout.close() - - gl.wintitle('(done) ' + filename) -# Initialize audio recording - -AQSIZE = 8*8000 # XXX should be a user option - -def initaudio(filename, stop, start, done): - import thread, aifc - afile = aifc.open(filename, 'w') - afile.setnchannels(AL.MONO) - afile.setsampwidth(AL.SAMPLE_8) - params = [AL.INPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, params) - print 'audio sampling rate =', params[1] - afile.setframerate(params[1]) - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(AQSIZE) - c.setwidth(AL.SAMPLE_8) - aport = al.openport(filename, 'r', c) - thread.start_new_thread(audiorecord, (afile, aport, stop, start, done)) - - -# Thread to record audio samples - -def audiorecord(afile, aport, stop, start, done): - start.release_lock() - leeway = 4 - while leeway > 0: - if stop: - leeway = leeway - 1 - data = aport.readsamps(AQSIZE/8) - afile.writesampsraw(data) - del data - afile.close() - print 'Done writing audio' - done.release_lock() - - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vrecc.py b/Demo/sgi/video/Vrecc.py deleted file mode 100755 index 6a539f8192..0000000000 --- a/Demo/sgi/video/Vrecc.py +++ /dev/null @@ -1,281 +0,0 @@ -#! /ufs/guido/bin/sgi/python-405 -#! /ufs/guido/bin/sgi/python - -# Capture a continuous CMIF movie using the Indigo video library and board - - -# Usage: -# -# makemovie [-r rate] [-w width] [moviefile] - - -# Options: -# -# -r rate : capture 1 out of every 'rate' frames (default 1) -# -w width : initial window width (default interactive placement) -# -d : drop fields if needed -# -g bits : greyscale (2, 4 or 8 bits) -# -G : 2-bit greyscale dithered -# -m : monochrome dithered -# -M value : monochrome tresholded with value -# -f : Capture fields (in stead of frames) -# -n number : Capture 'number' fields (default 60) -# -# moviefile : here goes the movie data (default film.video); -# the format is documented in cmif-film.ms - - -# User interface: -# -# Start the application. Resize the window to the desired movie size. -# Press the left mouse button to start recording, release it to end -# recording. You can record as many times as you wish, but each time -# you overwrite the output file(s), so only the last recording is -# kept. -# -# Press ESC or select the window manager Quit or Close window option -# to quit. If you quit before recording anything, the output file(s) -# are not touched. - - -import sys -sys.path.append('/ufs/guido/src/video') -import sv, SV -import VFile -import gl, GL, DEVICE -import al, AL -import time -import posix -import getopt -import string -import imageop -import sgi - -# Main program - -def main(): - format = SV.RGB8_FRAMES - rate = 1 - width = 0 - drop = 0 - mono = 0 - grey = 0 - greybits = 0 - monotreshold = -1 - fields = 0 - number = 60 - - opts, args = getopt.getopt(sys.argv[1:], 'r:w:dg:mM:Gfn:') - for opt, arg in opts: - if opt == '-r': - rate = string.atoi(arg) - if rate < 2: - sys.stderr.write('-r rate must be >= 2\n') - sys.exit(2) - elif opt == '-w': - width = string.atoi(arg) - elif opt == '-d': - drop = 1 - elif opt == '-g': - grey = 1 - greybits = string.atoi(arg) - if not greybits in (2,4,8): - print 'Only 2, 4 or 8 bit greyscale supported' - elif opt == '-G': - grey = 1 - greybits = -2 - elif opt == '-m': - mono = 1 - elif opt == '-M': - mono = 1 - monotreshold = string.atoi(arg) - elif opt == '-f': - fields = 1 - elif opt == '-n': - number = string.atoi(arg) - - if args[2:]: - sys.stderr.write('usage: Vrec [options] [file]\n') - sys.exit(2) - - if args: - filename = args[0] - else: - filename = 'film.video' - - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - x = SV.PAL_XMAX - y = SV.PAL_YMAX - elif param[1] == SV.NTSC: - x = SV.NTSC_XMAX - y = SV.NTSC_YMAX - else: - print 'Unknown video standard', param[1] - sys.exit(1) - - gl.foreground() - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - if width: - gl.prefsize(width, width*3/4) - win = gl.winopen(filename) - if width: - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.winconstraints() - x, y = gl.getsize() - print x, 'x', y - - v.SetSize(x, y) - - if drop: - param = [SV.FIELDDROP, 1, SV.GENLOCK, SV.GENLOCK_OFF] - else: - param = [SV.FIELDDROP, 0, SV.GENLOCK, SV.GENLOCK_ON] - if mono or grey: - param = param+[SV.COLOR, SV.MONO, SV.INPUT_BYPASS, 1] - else: - param = param+[SV.COLOR, SV.DEFAULT_COLOR, SV.INPUT_BYPASS, 0] - v.SetParam(param) - - v.BindGLWindow(win, SV.IN_REPLACE) - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - print 'Press left mouse to start recording' - - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE: - if val == 1: - info = format, x, y, number, rate - record(v, info, filename, mono, grey, \ - greybits, monotreshold, fields) - elif dev == DEVICE.REDRAW: - # Window resize (or move) - x, y = gl.getsize() - print x, 'x', y - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - # Quit - v.CloseVideo() - gl.winclose(win) - break - - -# Record until the mouse is released (or any other GL event) -# XXX audio not yet supported - -def record(v, info, filename, mono, grey, greybits, monotreshold, fields): - import thread - format, x, y, number, rate = info - fps = 59.64 # Fields per second - # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) - tpf = 1000.0 / fps # Time per field in msec - # - # Go grab - # - gl.wintitle('(rec) ' + filename) - try: - ninfo, data, bitvec = v.CaptureBurst(info) - except sv.error, arg: - print 'CaptureBurst failed:', arg - print 'info:', info - gl.wintitle(filename) - return - gl.wintitle('(save) '+ filename) - # - # Check results - # - if info <> ninfo: - print 'Sorry, format changed.' - print 'Wanted:',info - print 'Got :',ninfo - gl.wintitle(filename) - return - # print bitvec - if x*y*number <> len(data): - print 'Funny data length: wanted',x,'*',y,'*', number,'=',\ - x*y*number,'got',len(data) - gl.wintitle(filename) - return - # - # Save - # - if filename: - # - # Construct header and write it - # - vout = VFile.VoutFile().init(filename) - if mono: - vout.format = 'mono' - elif grey and greybits == 8: - vout.format = 'grey' - elif grey: - vout.format = 'grey'+`abs(greybits)` - else: - vout.format = 'rgb8' - vout.width = x - vout.height = y - if fields: - vout.packfactor = (1,-2) - else: - print 'Sorry, can only save fields at the moment' - gl.wintitle(filename) - return - vout.writeheader() - # - # Compute convertor, if needed - # - convertor = None - if grey: - if greybits == 2: - convertor = imageop.grey2grey2 - elif greybits == 4: - convertor = imageop.grey2grey4 - elif greybits == -2: - convertor = imageop.dither2grey2 - fieldsize = x*y/2 - nskipped = 0 - realframeno = 0 - tpf = 1000 / 50.0 #XXXX - for frameno in range(0, number*2): - if frameno <> 0 and \ - bitvec[frameno] == bitvec[frameno-1]: - nskipped = nskipped + 1 - continue - # - # Save field. - # XXXX Works only for fields and top-to-bottom - # - start = frameno*fieldsize - field = data[start:start+fieldsize] - if convertor: - field = convertor(field, x, y) - elif mono and monotreshold >= 0: - field = imageop.grey2mono(field, x, y, \ - 1, monotreshold) - elif mono: - field = imageop.dither2mono(field, x, y) - vout.writeframe(int(realframeno*tpf), field, None) - print 'Skipped',nskipped,'duplicate frames' - vout.close() - - gl.wintitle('(done) ' + filename) - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/Vreceive.py b/Demo/sgi/video/Vreceive.py deleted file mode 100755 index 84aa5a531b..0000000000 --- a/Demo/sgi/video/Vreceive.py +++ /dev/null @@ -1,135 +0,0 @@ -#! /usr/bin/env python - -# Receive live video UDP packets. -# Usage: Vreceive [port] - -import sys -import struct -from socket import * # syscalls and support functions -from SOCKET import * # -from IN import * # -import select -import struct -import gl, GL, DEVICE -sys.path.append('/ufs/guido/src/video') -import LiveVideoOut -import regsub -import getopt - -from senddefs import * - - -# Print usage message and exit(2). - -def usage(msg): - print msg - print 'usage: Vreceive [-m mcastgrp] [-p port] [-c type]' - print '-m mcastgrp: multicast group (default ' + `DEFMCAST` + ')' - print '-p port : port (default ' + `DEFPORT` + ')' - print '-c type : signal type: rgb8, grey or mono (default rgb8)' - sys.exit(2) - - -# Main program: parse options and main loop. - -def main(): - - sys.stdout = sys.stderr - - group = DEFMCAST - port = DEFPORT - width = DEFWIDTH - height = DEFHEIGHT - vtype = 'rgb8' - - try: - opts, args = getopt.getopt(sys.argv[1:], 'm:p:c:') - except getopt.error, msg: - usage(msg) - - try: - for opt, optarg in opts: - if opt == '-p': - port = string.atoi(optarg) - if opt == '-m': - group = gethostbyname(optarg) - if opt == '-c': - vtype = optarg - except string.atoi_error, msg: - usage('bad integer: ' + msg) - - s = opensocket(group, port) - - gl.foreground() - gl.prefsize(width, height) - wid = gl.winopen('Vreceive') - gl.winconstraints() - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.WINQUIT) - - lvo = LiveVideoOut.LiveVideoOut(wid, width, height, vtype) - - ifdlist = [gl.qgetfd(), s.fileno()] - ofdlist = [] - xfdlist = [] - timeout = 1.0 - selectargs = (ifdlist, ofdlist, xfdlist, timeout) - - while 1: - - if gl.qtest(): - dev, val = gl.qread() - if dev in (DEVICE.ESCKEY, \ - DEVICE.WINSHUT, DEVICE.WINQUIT): - break - if dev == DEVICE.REDRAW: - lvo.reshapewindow() - elif s.avail(): - data = s.recv(16*1024) - pos, w, h = struct.unpack('hhh', data[:6]) - if (w, h) <> (width, height): - x, y = gl.getorigin() - y = y + height - h - gl.winposition(x, x+w-1, y, y+h-1) - width, height = w, h - lvo.resizevideo(width, height) - lvo.putnextpacket(pos, data[6:]) - else: - x = select.select(selectargs) - - lvo.close() - - -# Subroutine to create and properly initialize the receiving socket - -def opensocket(group, port): - - # Create the socket - s = socket(AF_INET, SOCK_DGRAM) - - # Allow multiple copies of this program on one machine - s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) # (Not strictly needed) - - # Bind the port to it - s.bind('', port) - - # Look up the group once - group = gethostbyname(group) - - # Construct binary group address - group_bytes = eval(regsub.gsub('\.', ',', group)) - grpaddr = 0 - for byte in group_bytes: grpaddr = (grpaddr << 8) | byte - - # Construct struct mreq from grpaddr and ifaddr - ifaddr = INADDR_ANY - mreq = struct.pack('ll', grpaddr, ifaddr) - - # Add group membership - s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) - - return s - - -main() diff --git a/Demo/sgi/video/Vsend.py b/Demo/sgi/video/Vsend.py deleted file mode 100755 index 4c4786140c..0000000000 --- a/Demo/sgi/video/Vsend.py +++ /dev/null @@ -1,152 +0,0 @@ -#! /usr/bin/env python - -# Send live video UDP packets. -# Usage: Vsend [-b] [-h height] [-p port] [-s size] [-t ttl] [-w width] -# [host] .. - -import sys -import time -import struct -import string -from socket import * -from SOCKET import * -import gl, GL, DEVICE -sys.path.append('/ufs/guido/src/video') -import LiveVideoIn -import LiveVideoOut -import SV -import getopt -from IN import * - -from senddefs import * - -def usage(msg): - print msg - print 'usage: Vsend [-b] [-h height] [-p port] [-s size] [-t ttl] [-c type] [-m]', - print '[-w width] [host] ...' - print '-b : broadcast on local net' - print '-h height : window height (default ' + `DEFHEIGHT` + ')' - print '-p port : port to use (default ' + `DEFPORT` + ')' - print '-t ttl : time-to-live (multicast only; default 1)' - print '-s size : max packet size (default ' + `DEFPKTMAX` + ')' - print '-w width : window width (default ' + `DEFWIDTH` + ')' - print '-c type : Type: rgb8, mono or grey (default rgb8)' - print '[host] ...: host(s) to send to (default multicast to ' + \ - DEFMCAST + ')' - sys.exit(2) - - -def main(): - sys.stdout = sys.stderr - - hosts = [] - port = DEFPORT - ttl = -1 - pktmax = DEFPKTMAX - width = DEFWIDTH - height = DEFHEIGHT - vtype = 'rgb8' - - try: - opts, args = getopt.getopt(sys.argv[1:], 'bh:p:s:t:w:c:') - except getopt.error, msg: - usage(msg) - - try: - for opt, optarg in opts: - if opt == '-p': - port = string.atoi(optarg) - if opt == '-b': - host = '' - if opt == '-t': - ttl = string.atoi(optarg) - if opt == '-s': - pktmax = string.atoi(optarg) - if opt == '-w': - width = string.atoi(optarg) - if opt == '-h': - height = string.atoi(optarg) - if opt == '-c': - vtype = optarg - except string.atoi_error, msg: - usage('bad integer: ' + msg) - - for host in args: - hosts.append(gethostbyname(host)) - - if not hosts: - hosts.append(gethostbyname(DEFMCAST)) - - if not LiveVideoIn.have_video: - print 'Sorry, no video available (use python-405)' - sys.exit(1) - - gl.foreground() - gl.prefsize(width, height) - gl.stepunit(8, 6) - wid = gl.winopen('Vsend') - gl.keepaspect(width, height) - gl.stepunit(8, 6) - gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) - gl.winconstraints() - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINFREEZE) - gl.qdevice(DEVICE.WINTHAW) - width, height = gl.getsize() - - lvo = LiveVideoOut.LiveVideoOut(wid, width, height, vtype) - - lvi = LiveVideoIn.LiveVideoIn(pktmax, width, height, vtype) - - s = socket(AF_INET, SOCK_DGRAM) - s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) - if ttl >= 0: - s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, chr(ttl)) - - frozen = 0 - - while 1: - - if gl.qtest(): - dev, val = gl.qread() - if dev in (DEVICE.ESCKEY, \ - DEVICE.WINSHUT, DEVICE.WINQUIT): - break - if dev == DEVICE.WINFREEZE: - frozen = 1 - if dev == DEVICE.WINTHAW: - frozen = 0 - if dev == DEVICE.REDRAW: - w, h = gl.getsize() - x, y = gl.getorigin() - if (w, h) <> (width, height): - width, height = w, h - lvi.resizevideo(width, height) - lvo.resizevideo(width, height) - - rv = lvi.getnextpacket() - if not rv: - time.sleep(0.010) - continue - - pos, data = rv - - if not frozen: - lvo.putnextpacket(pos, data) - - hdr = struct.pack('hhh', pos, width, height) - for host in hosts: - try: - s.sendto(hdr + data, (host, port)) - except error, msg: # really socket.error - if msg[0] <> 121: # no buffer space available - raise error, msg # re-raise it - print 'Warning:', msg[1] - - lvi.close() - lvo.close() - - -main() diff --git a/Demo/sgi/video/Vstat.py b/Demo/sgi/video/Vstat.py deleted file mode 100755 index a29b1ff04b..0000000000 --- a/Demo/sgi/video/Vstat.py +++ /dev/null @@ -1,23 +0,0 @@ -#! /usr/bin/env python - -# Print the value of all video parameters - -import sys -import sv, SV - -def main(): - v = sv.OpenVideo() - for name in dir(SV): - const = getattr(SV, name) - if type(const) is type(0): - sys.stdout.flush() - params = [const, 0] - try: - v.GetParam(params) - except sv.error, msg: -## print name, msg - continue - print name, params - -main() - diff --git a/Demo/sgi/video/Vtime.py b/Demo/sgi/video/Vtime.py deleted file mode 100755 index 651deee00d..0000000000 --- a/Demo/sgi/video/Vtime.py +++ /dev/null @@ -1,117 +0,0 @@ -#! /usr/bin/env python - -# Manipulate the time base of CMIF movies - - -# Possibilities: -# -# - resample at a fixed rate -# - divide the time codes by a speed factor (to make it go faster/slower) -# - drop frames that are less than n msec apart (to accommodate slow players) - - -# Usage: -# -# Vtime [-m msec] [-r msec] [-s speed] [infile [outfile]] - - -# Options: -# -# -m n : drop frames closer than n msec (default 0) -# -r n : regenerate input time base n msec apart -# -s speed : speed change factor after other processing (default 1.0) -# infile : input file (default film.video) -# outfile : output file (default out.video) - - -import sys -sys.path.append('/ufs/guido/src/video') -import VFile -import getopt -import string - - -# Global options - -speed = 1.0 -mindelta = 0 -regen = None - - -# Main program -- mostly command line parsing - -def main(): - global speed, mindelta - opts, args = getopt.getopt(sys.argv[1:], 'm:r:s:') - for opt, arg in opts: - if opt == '-m': - mindelta = string.atoi(arg) - elif opt == '-r': - regen = string.atoi(arg) - elif opt == '-s': - speed = float(eval(arg)) - if len(args) < 1: - args.append('film.video') - if len(args) < 2: - args.append('out.video') - if len(args) > 2: - sys.stderr.write('usage: Vtime [options] [infile [outfile]]\n') - sys.exit(2) - sts = process(args[0], args[1]) - sys.exit(sts) - - -# Copy one file to another - -def process(infilename, outfilename): - try: - vin = VFile.BasicVinFile(infilename) - except IOError, msg: - sys.stderr.write(infilename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(infilename + ': EOF in video file\n') - return 1 - - try: - vout = VFile.BasicVoutFile(outfilename) - except IOError, msg: - sys.stderr.write(outfilename + ': I/O error: ' + `msg` + '\n') - return 1 - - vout.setinfo(vin.getinfo()) - vout.writeheader() - - told = 0 - nin = 0 - nout = 0 - tin = 0 - tout = 0 - - while 1: - try: - tin, data, cdata = vin.getnextframe() - except EOFError: - break - nin = nin + 1 - if regen: - tout = nin * regen - else: - tout = tin - tout = int(tout / speed) - if tout - told < mindelta: - continue - told = tout - vout.writeframe(tout, data, cdata) - nout = nout + 1 - - vout.close() - vin.close() - - -# Don't forget to call the main program - -main() diff --git a/Demo/sgi/video/Vunjpeg.py b/Demo/sgi/video/Vunjpeg.py deleted file mode 100755 index 3321d23e87..0000000000 --- a/Demo/sgi/video/Vunjpeg.py +++ /dev/null @@ -1,97 +0,0 @@ -#! /usr/bin/env python - -# Decompress a jpeg or jpeggrey video file to rgb format - - -# Usage: -# -# Vunjpeg [infile [outfile]] - - -# Options: -# -# infile : input file (default film.video) -# outfile : output file (default out.video) - - -import sys -import jpeg -sys.path.append('/ufs/guido/src/video') -import VFile - - -# Main program -- mostly command line parsing - -def main(): - args = sys.argv[1:] - if len(args) < 1: - args.append('film.video') - if len(args) < 2: - args.append('out.video') - if len(args) > 2: - sys.stderr.write('usage: Vunjpeg [infile [outfile]]\n') - sys.exit(2) - sts = process(args[0], args[1]) - sys.exit(sts) - - -# Copy one file to another - -def process(infilename, outfilename): - try: - vin = VFile.BasicVinFile(infilename) - except IOError, msg: - sys.stderr.write(infilename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(infilename + ': EOF in video file\n') - return 1 - - try: - vout = VFile.BasicVoutFile(outfilename) - except IOError, msg: - sys.stderr.write(outfilename + ': I/O error: ' + `msg` + '\n') - return 1 - - info = vin.getinfo() - if info[0] == 'jpeg': - format = 'rgb' - width, height = vin.getsize() - bytes = 4 - elif info[0] == 'jpeggrey': - format = 'grey' - width, height = vin.getsize() - pf = vin.packfactor - width, height = width/pf, height/pf - bytes = 1 - else: - sys.stderr.write('Vunjpeg: input not in jpeg[grey] format\n') - return 1 - info = (format,) + info[1:] - vout.setinfo(info) - vout.writeheader() - sts = 0 - n = 0 - try: - while 1: - t, data, cdata = vin.getnextframe() - n = n + 1 - sys.stderr.write('Frame ' + `n` + '...') - data, w, h, b = jpeg.decompress(data) - if (w, h, b) <> (width, height, bytes): - sys.stderr.write('jpeg data has wrong size\n') - sts = 1 - else: - vout.writeframe(t, data, None) - sys.stderr.write('\n') - except EOFError: - pass - return sts - - -# Don't forget to call the main program - -main() diff --git a/Demo/sgi/video/aplay.py b/Demo/sgi/video/aplay.py deleted file mode 100755 index a11f95a5e3..0000000000 --- a/Demo/sgi/video/aplay.py +++ /dev/null @@ -1,167 +0,0 @@ -#! /usr/bin/env python - -# Play synchronous video and audio. -# Highly experimental! - -import sys -import getopt -import string -import os - -import VFile -import aifc - -import gl, GL, DEVICE -import al, AL - - -def usage(): - sys.stderr.write( \ - 'usage: aplay [-o offset] [-q qsize] videofile audiofile\n') - sys.exit(2) - -def main(): - offset = 0 - qsize = 0 # This defaults to 1/10 second of sound - videofile = 'film.video' - audiofile = 'film.aiff' - - try: - opts, args = getopt.getopt(sys.argv[1:], 'o:q:') - except getopt.error, msg: - sys.stderr.write(msg + '\n') - usage() - - try: - for o, a in opts: - if o == '-o': - offset = string.atoi(a) - if o == '-q': - qsize = string.atoi(a) - except string.atoi_error: - sys.stderr.write(o + ' arg must be integer\n') - usage() - - if len(args) > 2: - usage() - - if args: videofile = args[0] - if args[1:]: audiofile = args[1] - - if not os.path.exists(videofile) and \ - os.path.exists(videofile + '.video'): - if not args[1:] and os.path.exists(videofile + '.aiff'): - audiofile = videofile + '.aiff' - videofile = videofile + '.video' - - print 'Opening video input file..' - vin = VFile.VinFile(videofile) - - print 'Opening audio input file..' - ain = aifc.open(audiofile, 'r') - print 'rate :', ain.getframerate() - print 'channels:', ain.getnchannels() - print 'frames :', ain.getnframes() - print 'width :', ain.getsampwidth() - print 'kbytes :', \ - ain.getnframes() * ain.getnchannels() * ain.getsampwidth() - - print 'Opening audio output port..' - c = al.newconfig() - c.setchannels(ain.getnchannels()) - c.setwidth(ain.getsampwidth()) - nullsample = '\0' * ain.getsampwidth() - samples_per_second = ain.getnchannels() * ain.getframerate() - if qsize <= 0: qsize = samples_per_second / 10 - qsize = max(qsize, 512) - c.setqueuesize(qsize) - saveparams = [AL.OUTPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, saveparams) - newparams = [AL.OUTPUT_RATE, ain.getframerate()] - al.setparams(AL.DEFAULT_DEVICE, newparams) - aport = al.openport(audiofile, 'w', c) - - print 'Opening video output window..' - gl.foreground() - gl.prefsize(vin.width, vin.height) - wid = gl.winopen(videofile + ' + ' + audiofile) - gl.clear() - vin.initcolormap() - - print 'Playing..' - gl.qdevice(DEVICE.ESCKEY) - gl.qdevice(DEVICE.LEFTARROWKEY) - gl.qdevice(DEVICE.RIGHTARROWKEY) -## gl.qdevice(DEVICE.UPARROWKEY) -## gl.qdevice(DEVICE.DOWNARROWKEY) - gl.qdevice(DEVICE.SPACEKEY) - - while 1: - samples_written = 0 - samples_read = 0 - lastt = 0 - pause = 0 - while 1: - if gl.qtest(): - dev, val = gl.qread() - if val == 1: - if dev == DEVICE.ESCKEY: - sys.exit(0) - elif dev == DEVICE.LEFTARROWKEY: - offset = offset - 100 - print 'offset =', offset - elif dev == DEVICE.RIGHTARROWKEY: - offset = offset + 100 - print 'offset =', offset - elif dev == DEVICE.SPACEKEY: - pause = (not pause) - - if pause: - continue - - try: - t, data, cdata = vin.getnextframe() - except EOFError: - break - t = int(t) - dt = t - lastt - lastt = t - target = samples_per_second * t / 1000 - n = target - samples_written + qsize - offset - if n > 0: - # This call will block until the time is right: - try: - samples = ain.readframes(n) - except EOFError: - samples = '' - k = len(samples) / len(nullsample) - samples_read = samples_read + k - if k < n: - samples = samples + (n-k) * nullsample - aport.writesamps(samples) - samples_written = samples_written + n - vin.showframe(data, cdata) - - while 1: - try: - samples = ain.readframes(qsize) - except EOFError: - break - if not samples: - break - aport.writesamps(samples) - k = len(samples) / len(nullsample) - samples_read = samples_read + k - samples_written = samples_written + k - - print samples_read, 'samples ==', - print samples_read * 1.0 / samples_per_second, 'sec.' - print lastt, 'milliseconds' - - print 'Restarting..' - ain.close() - ain = aifc.open(audiofile, 'r') - vin.rewind() - - -main() diff --git a/Demo/sgi/video/cam.py b/Demo/sgi/video/cam.py deleted file mode 100755 index fa8966f8b3..0000000000 --- a/Demo/sgi/video/cam.py +++ /dev/null @@ -1,129 +0,0 @@ -import sys -from socket import * -from gl import * -from GL import * -from DEVICE import * -from time import millitimer - -HS = 40 # Header size (must be same as in tv.py) - -# Rely on UDP packet (de)fragmentation for smoother images -# (Changed for broadcast) -MAX = 16000 - -PF = 2 # Default packfactor - -# Default receiver station is voorn. -# Kwik has no yellow pages, so... -HOST = '192.16.201.121' -PORT = 5555 - -if sys.argv[1:]: - PF = eval(sys.argv[1]) - -if sys.argv[2:]: - HOST = sys.argv[2] - if HOST == 'all': - HOST = '' - MAX = 1400 - -PF2 = PF*PF - -def main(): - centerx, centery = 400, 300 - - foreground() - wid = winopen('cam') - RGBmode() - doublebuffer() - gconfig() - qdevice(ESCKEY) - - w, h = getsize() - ortho2(0, w, 0, h) - w = w/PF*PF - h = h/PF*PF - - readsource(SRC_FRAMEGRABBER) - - s = socket(AF_INET, SOCK_DGRAM) - if HOST == '': - s.allowbroadcast(1) - addr = HOST, PORT - - bytesperline = w/PF2 - linesperchunk = MAX/bytesperline - linesperchunk = linesperchunk/PF*PF - nchunks = (h+linesperchunk-1)/linesperchunk - - print 'MAX=', MAX, - print 'linesperchunk=', linesperchunk, - print 'nchunks=', nchunks, - print 'w=', w, 'h=', h - - x1, x2 = 0, w-1 - - t1 = millitimer() - nframes = 0 - fps = 0 - - msg = '' - - while 1: - while qtest(): - dev, val = qread() - if dev == REDRAW: - reshapeviewport() - w, h = getsize() - ortho2(0, w, 0, h) - w = w/PF*PF - h = h/PF*PF - - bytesperline = w/PF2 - linesperchunk = MAX/bytesperline - linesperchunk = linesperchunk/PF*PF - nchunks = (h+linesperchunk-1)/linesperchunk - - print 'MAX=', MAX, - print 'linesperchunk=', linesperchunk, - print 'nchunks=', nchunks, - print 'w=', w, 'h=', h - - x1, x2 = 0, w-1 - - fps = 0 - - elif dev == ESCKEY: - winclose(wid) - return - - readsource(SRC_FRAMEGRABBER) - - nframes = nframes+1 - if nframes >= fps: - t2 = millitimer() - if t2 <> t1: - fps = int(10000.0*nframes/(t2-t1)) * 0.1 - msg = `fps` + ' frames/sec' - t1 = t2 - nframes = 0 - - RGBcolor(255,255,255) - cmov2i(9,9) - charstr(msg) - - swapbuffers() - rectcopy(centerx-w/2, centery-w/2, centerx+w/2, centery+w/2, 0, 0) - - for i in range(nchunks): - y1 = i*linesperchunk - y2 = y1 + linesperchunk-1 - if y2 >= h: y2 = h-1 - data = lrectread(x1, y1, x2, y2) - data2 = packrect(x2-x1+1, y2-y1+1, PF, data) - prefix = `w, h, PF, x1, y1, x2, y2` - prefix = prefix + ' ' * (HS-len(prefix)) - data3 = prefix + data2 - s.sendto(data3, addr) - -main() diff --git a/Demo/sgi/video/camcorder.py b/Demo/sgi/video/camcorder.py deleted file mode 100755 index 9b7618c436..0000000000 --- a/Demo/sgi/video/camcorder.py +++ /dev/null @@ -1,266 +0,0 @@ -from gl import * -from GL import * -from DEVICE import * -import time -import sys -import getopt -import socket -import posix -import vtime - -# Preallocation parameter -PREALLOC = 4 # Megabyte - -# Sync audio parameters -SYNCPORT = 10000 -CTLPORT = 10001 - -from vpregs import * - -class Struct(): pass -epoch = Struct() - -def getvideosize(): - w = getvideo(VP_WIDTH) - h = getvideo(VP_HEIGHT) - print 'WIDTH,HEIGHT:', w, h - print 'GB{X,Y}ORG:', getvideo(VP_GBXORG), getvideo(VP_GBYORG) - print 'FB{X,Y}ORG:', getvideo(VP_FBXORG), getvideo(VP_FBYORG) - x = 0 - y = 0 - return x,y,w,h - -framelist = [] - -def prealloc(w, h): - nbytes = w*h*4 - limit = PREALLOC*1024*1024 - total = 0 - list = [] - print 'Prealloc to', PREALLOC, 'Megabytes...' - while total+nbytes <= limit: - list.append('x'*nbytes) - total = total + nbytes - print 'Done.' - -def grabframe(f,x,y,w,h,pf): - readsource(SRC_FRONT) - if pf: - w = w/pf*pf - h = h/pf*pf - data = lrectread(x,y,x+w-1,y+h-1) - t = time.millitimer()-epoch.epoch - framelist.append(data, t) - readsource(SRC_FRAMEGRABBER) - -def saveframes(f, w, h, pf): - for data, t in framelist: - if pf: - w = w/pf*pf - h = h/pf*pf - data = packrect(w,h,pf,data) - f.write(`t` + ',' + `len(data)` + '\n') - f.write(data) - framelist[:] = [] - -def saveframe(f,x,y,w,h,pf, notime): - readsource(SRC_FRONT) - if pf: - w = w/pf*pf - h = h/pf*pf - data = lrectread(x,y,x+w-1,y+h-1) - if pf: data = packrect(w,h,pf,data) - if notime: t = 0 - else: t = time.millitimer()-epoch.epoch - f.write(`t` + ',' + `len(data)` + '\n') - f.write(data) - readsource(SRC_FRAMEGRABBER) - -def drawframe(x,y,w,h,col): - drawmode(OVERDRAW) - color(col) - bgnline() - v2i(x-1,y-1) ; v2i(x+w,y-1); v2i(x+w,y+h); v2i(x-1,y+h); v2i(x-1,y-1) - endline() - drawmode(NORMALDRAW) - -def usage(): - sys.stderr.write('Usage: camcorder ' + \ - '[-c] [-p packfactor] [-a audiomachine [-s]] [outputfile]\n') - sys.exit(2) - -def wrheader(f, w, h, pf): - f.write('CMIF video 1.0\n') - f.write(`w,h,pf` + '\n') - print 'width,height,pf:', w, h, pf, - if pf == 0: pf = 4 - print '(i.e.,', w*h*pf, 'bytes/frame)' - -def main(): - foreground() - pf = 2 - ausync = 0 - austart = 0 - optlist, args = getopt.getopt(sys.argv[1:],'ca:sp:') - for opt, arg in optlist: - if opt == '-c': - pf = 0 - elif opt == '-a': - ausync = 1 - aumachine = arg - elif opt == '-s': - austart = 1 - elif opt == '-p': - pf = int(eval(arg)) - else: - usage() - if args: - if len(args) > 1: - print 'Too many arguments' - usage() - filename = args[0] - else: - filename = 'film.video' - if austart: - if not ausync: - print 'Cannot use -s without -a' - usage() - print 'Starting audio recorder...' - posix.system('rsh '+aumachine+' syncrecord '+socket.gethostname()+' &') - if ausync: - print 'Syncing to audio recorder...' - globtime = vtime.VTime().init(1,aumachine,SYNCPORT) - ctl = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) - ctl.bind((socket.gethostname(),CTLPORT)) - aua = (socket.gethostbyname(aumachine), CTLPORT) - print 'Done.' - vidx, vidy, w, h = getvideosize() - #prefsize(w,h) - winx, winy = 1280-w-10, 1024-h-30 - prefposition(winx,winx+w-1,winy,winy+h-1) - win = winopen(filename) - f = open(filename, 'w') - w, h = getsize() - realw, realh = w, h - ####doublebuffer() - RGBmode() - gconfig() - qdevice(LEFTMOUSE) - qdevice(RKEY) - qdevice(SKEY) - qdevice(CKEY) - qdevice(PKEY) - qdevice(ESCKEY) - qdevice(WINQUIT) - qdevice(WINSHUT) - inrunning = 1 - outrunning = 0 - stop = 'stop' - readsource(SRC_FRAMEGRABBER) - mousing = 0 - epoch.epoch = time.millitimer() - stoptime = epoch.epoch - sizewritten = 0 - x, y = realw/4, realh/4 - w, h = w/2, h/2 - prealloc(w, h) - try: - drawframe(x,y,w,h,1) - nframe = 0 - num = 0 - while 1: - insingle = 0 - outsingle = 0 - if mousing: - drawframe(x,y,w,h,0) - ox, oy = getorigin() - if sizewritten: - x = getvaluator(MOUSEX)-ox - y = getvaluator(MOUSEY)-oy - else: - w = getvaluator(MOUSEX)-x-ox - h = getvaluator(MOUSEY)-y-oy - drawframe(x,y,w,h,1) - if qtest() or \ - not (mousing or inrunning or insingle or outrunning or outsingle): - ev, val = qread() - if ev == LEFTMOUSE and val == 1: - drawframe(x,y,w,h,0) - mousing = 1 - ox, oy = getorigin() - x = getvaluator(MOUSEX)-ox - y = getvaluator(MOUSEY)-oy - elif ev == LEFTMOUSE and val == 0: - if h < 0: - y, h = y+h, -h - if w < 0: - x, w = x+w, -w - mousing = 0 - if not sizewritten: - wrheader(f, w, h, pf) - sizewritten = 1 - prealloc(w, h) - elif ev == RKEY and val == 1: - if not inrunning: - ringbell() - else: - outrunning = 1 - wasstopped = time.millitimer() - stoptime - epoch.epoch = epoch.epoch + wasstopped - nframe = 0 - starttime = time.millitimer() - if ausync: - ctl.sendto(`(1,starttime)`, aua) - elif ev == PKEY and val == 1 and outrunning: - outrunning = 0 - stoptime = time.millitimer() - if ausync: - ctl.sendto(`(0,stoptime)`, aua) - fps = nframe * 1000.0 / (time.millitimer()-starttime) - print 'Recorded', nframe, - print 'frames at', 0.1*int(fps*10),'frames/sec' - print 'Saving...' - saveframes(f, w, h, pf) - print 'Done.' - elif ev == PKEY and val == 1 and not outrunning: - outsingle = 1 - elif ev == CKEY and val == 1: - inrunning = 1 - elif ev == SKEY and val == 1: - if outrunning: - ringbell() - elif inrunning: - inrunning = 0 - else: - insingle = 1 - elif ev in (ESCKEY, WINQUIT, WINSHUT): - if ausync: - ctl.sendto(`(2,time.millitimer())`, aua) - raise stop - elif ev == REDRAW: - drawframe(x,y,w,h,0) - reshapeviewport() - drawframe(x,y,w,h,1) - if inrunning or insingle: - if outrunning: - rectcopy(vidx+x,vidy+y,vidx+x+w-1,vidy+y+h-1,x,y) - else: - rectcopy(vidx,vidy,vidx+realw-1,vidx+realh-1,0,0) - ####swapbuffers() - if outrunning or outsingle: - nframe = nframe + 1 - if not sizewritten: - wrheader(f, w, h, pf) - sizewritten = 1 - if outrunning: - grabframe(f, x, y, w, h, pf) - else: - saveframe(f, x, y, w, h, pf, outsingle) - except stop: - pass - finally: - drawmode(OVERDRAW) - color(0) - clear() - -main() diff --git a/Demo/sgi/video/cmif-film.ms b/Demo/sgi/video/cmif-film.ms deleted file mode 100755 index aa114d9788..0000000000 --- a/Demo/sgi/video/cmif-film.ms +++ /dev/null @@ -1,200 +0,0 @@ -.de PP -.LP -.. -.de pT -.IP \fB\\$1\fP -.. -.TL -CMIF video file format -.AU -Jack Jansen -(Version of 27-Feb-92) -.SH -Introduction -.PP -The CMIF video format was invented to allow various applications -to exchange video data. The format consists of -a header containing global information (like data format) -followed by a sequence of frames, each consisting of a header -followed by the actual frame data. -All information except pixel data is -encoded in ASCII. Pixel data is \fIalways\fP encoded in Silicon Graphics -order, which means that the first pixel in the frame is the lower left -pixel on the screen. -.PP -All ASCII data except the first line of the file -is in python format. This means that -outer parentheses can be ommitted, and parentheses around a tuple with -one element can also be omitted. So, the lines -.IP -.ft C -.nf -('grey',(4)) -('grey',4) -'grey',4 -.LP -have the same meaning. -To ease parsing in C programs, however, it is advised that there are -no parenteses around single items, and that there are parentheses around -lists. So, the second format above is preferred. -.PP -The current version is version 3, but this document will also explain -shortly what the previous formats looked like. -.SH -Header. -.PP -The header consists of three lines. The first line identifies the file -as a CMIF video file, and gives the version number. -It looks as follows: -.IP -.ft C -CMIF video 3.0 -.LP -All programs expect the layout to be exactly like this, so no -extra spaces, etc. should be added. -.PP -The second line specifies the data format. Its format is a python -tuple with two members. The first member is a string giving the format -type and the second is a tuple containing type-specific information. -The following formats are currently understood: -.pT rgb -The video data is 24 bit RGB packed into 32 bit words. -R is the least significant byte, then G and then B. The top byte is -unused. -.IP -There is no type-specific information, so the complete data format -line is -.IP -.ft C -('rgb',()) -.pT grey -The video data is greyscale, at most 8 bits. Data is packed into -8 bit bytes (in the low-order bits). The extra information is the -number of significant bits, so an example data format line is -.IP -.ft C -('grey',(6)) -.pT yiq -The video data is in YIQ format. This is a format that has one luminance -component, Y, and two chrominance components, I and Q. The luminance and -chrominance components are encoded in \fItwo\fP pixel arrays: first an -array of 8-bit luminance values followed by a array of 16 bit chrominance -values. See the section on chrominance coding for details. -.IP -The type specific part contains the number of bits for Y, I and Q, -the chrominance packfactor and the colormap offset. So, a sample format -information line of -.IP -.ft C -('yiq',(5,3,3,2,1024)) -.IP -means that the pictures have 5 bit Y values (in the luminance array), -3 bits of I and Q each (in the chrominance array), chrominance data -is packed for 2x2 pixels, and the first colormap index used is 1024. -.pT hls -The video data is in HLS format. L is the luminance component, H and S -are the chrominance components. The data format and type specific information -are the same as for the yiq format. -.pT hsv -The video data is in HSV format. V is the luminance component, H and S -are the chrominance components. Again, data format and type specific -information are the same as for the yiq format. -.pT rgb8 -The video data is in 8 bit dithered rgb format. This is the format -used internally by the Indigo. bit 0-2 are green, bit 3-4 are blue and -bit 5-7 are red. Because rgb8 is treated more-or-less like yiq format -internally the type-specific information is the same, with zeroes for -the (unused) chrominance sizes: -.IP -.ft C -('rgb8',(8,0,0,0,0)) -.PP -The third header line contains width and height of the video image, -in pixels, and the pack factor of the picture. For compatability, RGB -images must have a pack factor of 0 (zero), and non-RGB images must -have a pack factor of at least 1. -The packfactor is the amount of compression done on the original video -signal to obtain pictures. In other words, if only one out of three pixels -and lines is stored (so every 9 original pixels have one pixel in the -data) the packfactor is three. Width and height are the size of the -\fIoriginal\fP picture. -Viewers are expected to enlarge the picture so it is shown in the -original size. RGB videos cannot be packed. -So, a size line like -.IP -.ft C -200,200,2 -.LP -means that this was a 200x200 picture that is stored as 100x100 pixels. -.SH -Frame header -.PP -Each frame is preceded by a single header line. This line contains timing information -and optional size information. The time information is mandatory, and -contains the time this frame should be displayed, in milliseconds since -the start of the film. Frames should be stored in chronological order. -.PP -An optional second number is interpreted as the size of the luminance -data in bytes. Currently this number, if present, should always be the -same as \fCwidth*height/(packfactor*packfactor)\fP (times 4 for RGB -data), but this might change if we come up with variable-length encoding -for frame data. -.PP -An optional third number is the size of the chrominance data -in bytes. If present, the number should be equal to -.ft C -luminance_size2*/(chrompack*chrompack). -.SH -Frame data -.PP -For RGB films, the frame data is an array of 32 bit pixels containing -RGB data in the lower 24 bits. For greyscale films, the frame data -is an array of 8 bit pixels. For split luminance/chrominance films the -data consists of two parts: first an array of 8 bit luminance values -followed by an array of 16 bit chrominance values. -.PP -For all data formats, the data is stored left-to-right, bottom-to-top. -.SH -Chrominance coding -.PP -Since the human eye is apparently more sensitive to luminance changes -than to chrominance changes we support a coding where we split the luminance -and chrominance components of the video image. The main point of this -is that it allows us to transmit chrominance data in a coarser granularity -than luminance data, for instance one chrominance pixel for every -2x2 luminance pixels. According to the theory this should result in an -acceptable picture while reducing the data by a fair amount. -.PP -The coding of split chrominance/luminance data is a bit tricky, to -make maximum use of the graphics hardware on the Personal Iris. Therefore, -there are the following constraints on the number of bits used: -.IP - -No more than 8 luminance bits, -.IP - -No more than 11 bits total, -.IP - -The luminance bits are in the low-end of the data word, and are stored -as 8 bit bytes, -.IP - -The two sets of chrominance bits are stored in 16 bit words, correctly -aligned, -.IP - -The color map offset is added to the chrominance data. The offset should -be at most 4096-256-2**(total number of bits). To reduce interference with -other applications the offset should be at least 1024. -.LP -So, as an example, an HLS video with 5 bits L, 4 bits H, 2 bits S and an -offset of 1024 will look as follows in-core and in-file: -.IP -.nf -.ft C - 31 15 11 10 9 8 5 4 0 - +-----------------------------------+ -incore + 0+ 1+ S + H + L + - +-----------------------------------+ - +----------+ -L-array + 0 + L + - +----------+ - +-----------------------+ -C-array + 0+ 1+ S + H + 0 + - +-----------------------+ diff --git a/Demo/sgi/video/colorsys.py b/Demo/sgi/video/colorsys.py deleted file mode 100755 index dd3a033b26..0000000000 --- a/Demo/sgi/video/colorsys.py +++ /dev/null @@ -1,106 +0,0 @@ -# -# Module color - do color conversions -# - -ONE_THIRD=1.0/3.0 -ONE_SIXTH=1.0/6.0 -TWO_THIRD=2.0/3.0 - -def rgb_to_yiq(r,g,b): - y = 0.3*r + 0.59*g + 0.11*b - i = 0.6*r - 0.28*g - 0.32*b - q = 0.21*r- 0.52*g + 0.31*b - return (y,i,q) -def yiq_to_rgb(y,i,q): - r = y + 0.948262*i + 0.624013*q - g = y - 0.276066*i - 0.639810*q - b = y - 1.105450*i + 1.729860*q - if r < 0.0: r = 0.0 - if g < 0.0: g = 0.0 - if b < 0.0: b = 0.0 - if r > 1.0: r = 1.0 - if g > 1.0: g = 1.0 - if b > 1.0: b = 1.0 - return (r,g,b) - -def _v(m1,m2,hue): - if hue >= 1.0: hue = hue - 1.0 - if hue < 0.0: hue = hue + 1.0 - if hue < ONE_SIXTH: - return m1 + (m2-m1)*hue*6.0 - if hue < 0.5: - return m2 - if hue < TWO_THIRD: - return m1 + (m2-m1)*(TWO_THIRD-hue)*6.0 - return m1 - -def rgb_to_hls(r,g,b): - maxc = max(r,g,b) - minc = min(r,g,b) - l = (minc+maxc)/2.0 - if minc == maxc: - return 0.0, l, 0.0 - if l <= 0.5: - s = (maxc-minc)/(maxc+minc) - else: - s = (maxc-minc)/(2-maxc-minc) - rc = (maxc-r)/(maxc-minc) - gc = (maxc-g)/(maxc-minc) - bc = (maxc-b)/(maxc-minc) - if r == maxc: - h = bc-gc - elif g == maxc: - h = 2.0+rc-bc - else: - h = 4.0+gc-rc - h = h/6.0 - if h < 0.0: - h = h + 1.0 - return h,l,s -def hls_to_rgb(h,l,s): - if s == 0.0: - return l,l,l - if l <= 0.5: - m2 = l * (1.0+s) - else: - m2 = l+s-(l*s) - m1 = 2.0*l - m2 - return (_v(m1,m2,h+ONE_THIRD), _v(m1,m2,h), _v(m1,m2,h-ONE_THIRD)) - -def rgb_to_hsv(r,g,b): - maxc = max(r,g,b) - minc = min(r,g,b) - v = maxc - if minc == maxc: - return 0.0, 0.0, v - s = (maxc-minc)/maxc - rc = (maxc-r)/(maxc-minc) - gc = (maxc-g)/(maxc-minc) - bc = (maxc-b)/(maxc-minc) - if r == maxc: - h = bc-gc - elif g == maxc: - h = 2.0+rc-bc - else: - h = 4.0+gc-rc - h = h/6.0 - if h < 0.0: - h = h + 1.0 - return h,s,v -def hsv_to_rgb(h,s,v): - if s == 0.0: - return v,v,v - i = int(h*6.0) - f = (h*6.0)-i - p = v*(1.0-s) - q = v*(1.0-s*f) - t = v*(1.0-s*(1.0-f)) - if i in (0,6): return v,t,p - if i == 1: return q,v,p - if i == 2: return p,v,t - if i == 3: return p,q,v - if i == 4: return t,p,v - if i == 5: return v,p,q - print i, h, f - print h, s, v - raise 'Bad color' diff --git a/Demo/sgi/video/i2v.c b/Demo/sgi/video/i2v.c deleted file mode 100755 index 21dfabe2b2..0000000000 --- a/Demo/sgi/video/i2v.c +++ /dev/null @@ -1,80 +0,0 @@ -/* - * i2v -- image-to-video. - * Convert an SGI image file to a format that is immediately usable - * by lrectwrite. - * The header of the file contains a description (in ASCII) - * padded to 8196 byte for fast access of the rest of the file. - * - * Based upon "showimg.c" by Paul Haeberli. - * --Guido van Rossum, CWI, Amsterdam - */ -#include -#include -#include -#include - -unsigned short rs[8192]; -unsigned short gs[8192]; -unsigned short bs[8192]; - -IMAGE *image; -int xsize, ysize, zsize; -FILE *fp; - -char header[100]; -char *progname = "i2v"; - -main(argc,argv) -int argc; -char **argv; -{ - int y; - if (argc > 0) progname = argv[0]; - if( argc != 3 ) { - fprintf(stderr, "usage: %s infile outfile\n", progname); - exit(2); - } - if( (image=iopen(argv[1],"r")) == NULL ) { - fprintf(stderr, "%s: can't open input file %s\n",progname, argv[1]); - exit(1); - } - xsize = image->xsize; - ysize = image->ysize; - zsize = image->zsize; - if ((fp = fopen(argv[2], "w")) == NULL) { - fprintf(stderr,"%s: can't open output file %s\n", progname, argv[2]); - exit(1); - } - fprintf(fp, "CMIF video 1.0\n"); - fprintf(fp, "(%d, %d, %d)\n", xsize, ysize, 0); - fprintf(fp, "0, %ld\n", (long)xsize * (long)ysize * sizeof(long)); - fflush(fp); - for(y = 0; y < ysize; y++) { - if(zsize<3) { - getrow(image, rs, y, 0); - writepacked(xsize, rs, rs, rs); - } else { - getrow(image, rs, y, 0); - getrow(image, gs, y, 1); - getrow(image, bs, y, 2); - writepacked(xsize, rs, gs, bs); - } - } - exit(0); -} - -writepacked(n, rsptr, gsptr, bsptr) - int n; - short *rsptr, *gsptr, *bsptr; -{ - long parray[8192]; - long *pptr = parray; - int i = n; - while (--i >= 0) { - *pptr++ = *rsptr++ | (*gsptr++<<8) | (*bsptr++<<16); - } - if (fwrite((char *) parray, sizeof(long), n, fp) != n) { - perror("fwrite"); - exit(1); - } -} diff --git a/Demo/sgi/video/imgconv.py b/Demo/sgi/video/imgconv.py deleted file mode 100755 index 8fc98b4abb..0000000000 --- a/Demo/sgi/video/imgconv.py +++ /dev/null @@ -1,139 +0,0 @@ -import imageop - -error = 'imgconv.error' - -LOSSY = 1 -NOT_LOSSY = 0 - -def null(img, x, y): - return img - -def mono2grey(img, x, y): - return imageop.mono2grey(img, x, y, 0, 255) - -def grey2jpeggrey(img, x, y): - import jpeg - return jpeg.compress(img, x, y, 1) - -def rgb2jpeg(img, x, y): - import jpeg - return jpeg.compress(img, x, y, 4) - -def jpeggrey2grey(img, width, height): - import jpeg - data, width, height, bytesperpixel = jpeg.decompress(img) - if bytesperpixel <> 1: raise RuntimeError, 'not greyscale jpeg' - return data - -def jpeg2rgb(img, width, height): - import jpeg - data, width, height, bytesperpixel = jpeg.decompress(img) - if bytesperpixel <> 4: raise RuntimeError, 'not rgb jpeg' - return data - -converters = [ \ - ('grey', 'grey4', imageop.grey2grey4, LOSSY), \ - ('grey', 'grey2', imageop.dither2grey2, LOSSY), \ - ('grey', 'mono', imageop.dither2mono, LOSSY), \ - ('mono', 'grey', mono2grey, NOT_LOSSY), \ - ('grey2', 'grey', imageop.grey22grey, NOT_LOSSY), \ - ('grey4', 'grey', imageop.grey42grey, NOT_LOSSY), \ - ('rgb', 'rgb8', imageop.rgb2rgb8, LOSSY), \ - ('rgb8', 'rgb', imageop.rgb82rgb, NOT_LOSSY), \ - ('rgb', 'grey', imageop.rgb2grey, LOSSY), \ - ('grey', 'rgb', imageop.grey2rgb, NOT_LOSSY), \ - ('jpeggrey','grey',jpeggrey2grey, NOT_LOSSY), \ - ('grey', 'jpeggrey',grey2jpeggrey, LOSSY), \ - ('jpeg', 'rgb', jpeg2rgb, NOT_LOSSY), \ - ('rgb', 'jpeg', rgb2jpeg, LOSSY), \ -] - -built = {} - -def addconverter(fcs, tcs, lossy, func): - for i in range(len(converters)): - ifcs, itcs, irtn, ilossy = converters[i] - if (fcs, tcs) == (ifcs, itcs): - converters[i] = (fcs, tcs, func, lossy) - return - converters.append((fcs,tcs,lossy,func)) - -def getconverter(fcs, tcs): - # - # If formats are the same return the dummy converter - # - if fcs == tcs: return null - # - # Otherwise, if we have a converter return that one - # - for ifcs, itcs, irtn, ilossy in converters: - if (fcs, tcs) == (ifcs, itcs): - return irtn - # - # Finally, we try to create a converter - # - if not built.has_key(fcs): - built[fcs] = enumerate_converters(fcs) - if not built[fcs].has_key(tcs): - raise error, 'Sorry, conversion from '+fcs+' to '+tcs+ \ - ' is not implemented' - if len(built[fcs][tcs]) == 3: - # - # Converter not instantiated yet - # - built[fcs][tcs].append(instantiate_converter(built[fcs][tcs])) - cf = built[fcs][tcs][3] - return cf - -def enumerate_converters(fcs): - cvs = {} - formats = [fcs] - steps = 0 - while 1: - workdone = 0 - for ifcs, itcs, irtn, ilossy in converters: - if ifcs == fcs: - template = [ilossy, 1, [irtn]] - elif cvs.has_key(ifcs): - template = cvs[ifcs][:] - template[2] = template[2][:] - if ilossy: - template[0] = ilossy - template[1] = template[1] + 1 - template[2].append(irtn) - else: - continue - if not cvs.has_key(itcs): - cvs[itcs] = template - workdone = 1 - else: - previous = cvs[itcs] - if template < previous: - cvs[itcs] = template - workdone = 1 - if not workdone: - break - steps = steps + 1 - if steps > len(converters): - print '------------------loop in emunerate_converters--------' - print 'CONVERTERS:' - print converters - print 'RESULTS:' - print cvs - raise error, 'Internal error - loop' - return cvs - -def instantiate_converter(args): - list = args[2] - cl = RtConverters(list) - args.append(cl.convert) - return args - -class RtConverters: - def __init__(self, list): - self.list = list - - def convert(self, img, w, h): - for cv in self.list: - img = cv(img, w, h) - return img diff --git a/Demo/sgi/video/makemovie.py b/Demo/sgi/video/makemovie.py deleted file mode 100755 index 5cb41cde2e..0000000000 --- a/Demo/sgi/video/makemovie.py +++ /dev/null @@ -1,218 +0,0 @@ -#! /ufs/guido/bin/sgi/python -#! /ufs/guido/src/video/py - -# Capture a CMIF movie using the Indigo video library and board - - -# Usage: -# -# makemovie [-q queuesize] [-t recordtime] [-a] [moviefile [audiofile]] - - -# Options: -# -# -q queuesize : set the capture queue size (default and max 16) -# -t recordtime : set the record time in seconds (default 5 seconds) -# -a : record audio as well -# moviefile : here goes the movie data (default film.video); -# the format is documented in cmif-film.ms -# audiofile : with -a, here goes the audio data (default film.aiff); -# audio data is recorded in AIFF format, using the -# input sampling rate, source and volume set by the -# audio panel, in mono, 8 bits/sample - - -# User interface: -# -# Start the application. Resize the window to the desired movie size. -# Click the left mouse button to start recording (recording starts -# when you release the mouse button). Recording time is specified by -# the -t option (XXX this should change). -# -# Press ESC or select the window manager Quit or Close window option -# to quit. (You can do this without recording -- then the output -# files are untouched.) -# -# (It is possible to record more than once; but this doesn't set the -# time stamps correctly yet, and doesn't work at all with audio. So -# don't use.) - - -# XXX To do: -# -# fix timestamps for second and further recordings -# fix audio " " " " " -# flush audio buffer when recording starts -# make code more readable - - -import sys -sys.path.append('/ufs/guido/src/video') -import sv, SV -import VFile -import gl, GL, DEVICE -import al, AL -import time -import posix -import getopt -import string - - -def main(): - QSIZE = 16 - TIME = 5 - audio = 0 - - opts, args = getopt.getopt(sys.argv[1:], 'aq:t:') - for opt, arg in opts: - if opt == '-a': - audio = 1 - elif opt == '-q': - QSIZE = string.atoi(arg) - elif opt == '-t': - TIME = string.atoi(arg) - - if args: - filename = args[0] - else: - filename = 'film.video' - - if audio: - if args[1:]: - audiofilename = args[1] - else: - audiofilename = 'film.aiff' - - gl.foreground() - - x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 - print x, 'x', y - - gl.minsize(40, 30) - gl.stepunit(8, 6) - gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) - gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) - win = gl.winopen(filename) - x, y = gl.getsize() - print x, 'x', y - - v = sv.OpenVideo() - v.BindGLWindow(win, SV.IN_REPLACE) - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - - v.SetCaptureFormat(SV.RGB_FRAMES) - v.SetCaptureMode(SV.BLOCKING_CAPTURE) - v.SetQueueSize(QSIZE) - v.InitCapture() - if v.GetQueueSize() != QSIZE: - QSIZE = v.GetQueueSize() - print 'Warning: QSIZE reduced to', QSIZE - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - print 'Click left mouse to start recording', TIME, 'seconds' - ofile = None - afile = None - # Mouse down opens the file & freezes window - # Mouse up starts recording frames - - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE: - # Start recording - if val == 1: - # Mouse down -- preparations - if ofile == None: - ofile = VFile.VoutFile().init(filename) - ofile.format = 'rgb8' - ofile.width = x - ofile.height = y - ofile.writeheader() - # XXX other format bits? - # The window can't be resized from now - gl.prefsize(x, y) - gl.winconstraints() - gl.wintitle('* ' + filename) - if audio: - afile = initaudio(audiofilename) - continue - # Mouse up -- start actual recording - global recording, stop_recording - if audio: - stop_recording = 0 - recording.release() - t0 = time.millitimer() - v.StartCapture() - while 1: - t = time.millitimer() - t0 - if t >= TIME*1000: - break - if v.GetCaptured() > 2: - doframe(v, ofile, x, y, t) - v.StopCapture() - stop_recording = 1 - while v.GetCaptured() > 0: - doframe(v, ofile, x, y, t) - t = time.millitimer() - t0 - gl.wintitle(filename) - elif dev == DEVICE.REDRAW: - # Window resize (or move) - x, y = gl.getsize() - print x, 'x', y - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - # Quit - if ofile: - ofile.close() - if afile: - afile.destroy() - posix._exit(0) - # EndCapture dumps core... - v.EndCapture() - v.CloseVideo() - gl.winclose(win) - -def doframe(v, ofile, x, y, t): - cd, start = v.GetCaptureData() - data = cd.interleave(x, y) - cd.UnlockCaptureData() - ofile.writeframe(t, data, None) - -AQSIZE = 16000 - -def initaudio(filename): - import thread, aiff - global recording, stop_recording - afile = aiff.Aiff().init(filename, 'w') - afile.nchannels = AL.MONO - afile.sampwidth = AL.SAMPLE_8 - params = [AL.INPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, params) - print 'rate =', params[1] - afile.samprate = params[1] - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(AQSIZE) - c.setwidth(AL.SAMPLE_8) - aport = al.openport(filename, 'r', c) - recording = thread.allocate_lock() - recording.acquire() - stop_recording = 0 - thread.start_new_thread(recorder, (afile, aport)) - return afile - -def recorder(afile, aport): - # XXX recording more than one fragment doesn't work - # XXX (the thread never dies) - recording.acquire() - while not stop_recording: - data = aport.readsamps(AQSIZE/2) - afile.writesampsraw(data) - del data - -main() diff --git a/Demo/sgi/video/rgb2video.py b/Demo/sgi/video/rgb2video.py deleted file mode 100755 index b6c34ebc35..0000000000 --- a/Demo/sgi/video/rgb2video.py +++ /dev/null @@ -1,79 +0,0 @@ -import sys -import VFile -import getopt -import imgfile -import string -import imgconv - -def main(): - format = None - interval = 40 - outfile = 'film.video' - - try: - opts, args = getopt.getopt(sys.argv[1:], 'f:i:o:') - except getopt.error: - usage() - sys.exit(1) - for opt, arg in opts: - if opt == '-f': - format = arg - elif opt == '-i': - interval = string.atoi(arg) - elif opt == '-o': - outfile = arg - else: - usage() - sys.exit(1) - if not args: - usage() - sys.exit(1) - - xsize, ysize, zsize = imgfile.getsizes(args[0]) - nxsize = xsize - - if zsize == 3: - oformat = 'rgb' - elif zsize == 1: - oformat = 'grey' - if xsize % 4: - addbytes = 4-(xsize%4) - nxsize = xsize + addbytes - print 'rgb2video: add',addbytes,'pixels per line' - else: - print 'rgb2video: incorrect number of planes:',zsize - sys.exit(1) - - if format == None: - format = oformat - cfunc = imgconv.getconverter(oformat, format) - - vout = VFile.VoutFile(outfile) - vout.format = format - vout.width = nxsize - vout.height = ysize - vout.writeheader() - t = 0 - sys.stderr.write('Processing ') - for img in args: - sys.stderr.write(img + ' ') - if imgfile.getsizes(img) <> (xsize, ysize, zsize): - print 'rgb2video: Image is different size:', img - sys.exit(1) - data = imgfile.read(img) - if xsize <> nxsize: - ndata = '' - for i in range(0,len(data), xsize): - curline = data[i:i+xsize] - ndata = ndata + curline + ('\0'*(nxsize-xsize)) - data = ndata - vout.writeframe(t, cfunc(data, nxsize, ysize), None) - t = t + interval - sys.stderr.write('\n') - vout.close() - -def usage(): - print 'Usage: rgb2video [-o output] [-i frameinterval] [-f format] rgbfile ...' - -main() - diff --git a/Demo/sgi/video/senddefs.py b/Demo/sgi/video/senddefs.py deleted file mode 100755 index c3ce2cd1e9..0000000000 --- a/Demo/sgi/video/senddefs.py +++ /dev/null @@ -1,11 +0,0 @@ -# Defaults shared by Vsend and Vreceice - -DEFMCAST = '225.0.0.250' -DEFPORT = 5555 - -PKTMAX_UCAST = 16*1024 - 6 -PKTMAX_BCAST = 1450 -DEFPKTMAX = PKTMAX_BCAST - -DEFWIDTH = 400 -DEFHEIGHT = 300 diff --git a/Demo/sgi/video/squash.c b/Demo/sgi/video/squash.c deleted file mode 100755 index d5ea946924..0000000000 --- a/Demo/sgi/video/squash.c +++ /dev/null @@ -1,130 +0,0 @@ -#include - -long *bm; -long h, w; -long factor; - -#define OC(x,xi) ((x)*factor+(xi)) -#define BM(x,xi,y,yi) bm[OC(y,yi)*w+OC(x,xi)] - -#define COMP(r,g,b) ((r) | ((g)<<8) | ((b) << 16)) - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int nh, nw; - int x, y, xi, yi; - int num; - int r, g, b; - long data; - long *nbm, *nbmp; - int i; - int bits, mask, roundbit, addbit; - int pf; - int newfmt = 0; - - if( argc != 2 && argc != 3) { - fprintf(stderr, "Usage: squash factor [bits]\n"); - exit(1); - } - factor = atoi(argv[1]); - if ( argc > 2 ) { - bits = atoi(argv[2]); - mask = (1 << bits) - 1; - mask <<= (8-bits); - roundbit = 1 << (7-bits); - addbit = 1 << (8-bits); - fprintf(stderr, "%x %x %x\n", mask, roundbit, addbit); - } else { - mask = 0xff; - roundbit = 0; - addbit = 0; - } - gets(lbuf); - if ( strncmp( lbuf, "CMIF", 4) == 0 ) { - newfmt = 1; - gets(lbuf); - if( sscanf(lbuf, "(%d,%d,%d)", &w, &h, &pf) != 3) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - if ( pf != 0 ) { - fprintf(stderr, "%s: packed file\n", argv[0]); - exit(1); - } - } else { - if ( sscanf(lbuf, "(%d,%d)", &w, &h) != 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - } - nh = h / factor; - nw = w / factor; - if ( newfmt ) - printf("CMIF video 1.0\n(%d,%d,%d)\n", nw, nh, 0); - else - printf("(%d,%d)\n", nw, nh); - if ( (bm = (long *)malloc(h*w*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - if ( (nbm = (long *)malloc(nh*nw*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - while( !feof(stdin) ) { - { int t, s; - gets(lbuf); - if ( feof(stdin) ) break; - if ( sscanf(lbuf, "%d,%d", &t,&s) == 2) { - if ( s != h*w*4 ) { - fprintf(stderr, "Size changed from %d to %d: %s\n",4*h*w,s, lbuf); - exit(1); - } - printf("%d, %d\n", t, nh*nw*4); - } else { - puts(lbuf); - } - } - fprintf(stderr, "Reading %d\n", h*w*sizeof(long)); - if ( (i=fread(bm, 1, h*w*sizeof(long), stdin)) != h*w*sizeof(long)) { - fprintf(stderr, "%s: short read, %d wanted %d\n", argv[0], - i, h*w*sizeof(long)); - exit(1); - } - nbmp = nbm; - for( y=0; y - -long *bm; -long h, w; -long factor; - -#define OC(x,xi) ((x)*factor+(xi)) -#define BM(x,xi,y,yi) bm[OC(y,yi)*w+OC(x,xi)] - -#define COMP(r,g,b) ((r) | ((g)<<8) | ((b) << 16)) - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int nh, nw; - int x, y, xi, yi; - int num; - int r, g, b; - long data; - long *nbm, *nbmp; - int i; - - if( argc != 2) { - fprintf(stderr, "Usage: squash factor\n"); - exit(1); - } - factor = atoi(argv[1]); - gets(lbuf); - if ( sscanf(lbuf, "(%d,%d)", &w, &h) != 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - nh = h / factor; - nw = w / factor; - printf("(%d,%d)\n", nw, nh); - if ( (bm = (long *)malloc(h*w*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - if ( (nbm = (long *)malloc(nh*nw*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - while( !feof(stdin) ) { - gets(lbuf); - if ( feof(stdin) ) break; - puts(lbuf); - fprintf(stderr, "Reading %d\n", h*w*sizeof(long)); - if ( (i=fread(bm, 1, h*w*sizeof(long), stdin)) != h*w*sizeof(long)) { - fprintf(stderr, "%s: short read, %d wanted %d\n", argv[0], - i, h*w*sizeof(long)); - exit(1); - } - nbmp = nbm; - for( y=0; y size: - raise EOFError - dostat(w2, h2, data) - nframes = nframes+1 - t1 = millitimer() - - t = 0.001 * (t1-t0) - fps = 0.1 * int(10*nframes/t) - print nframes, 'frames in', t, 'sec. =', fps, 'frames/sec.' - -def dostat(w, h, data): - print - stat3(w, h, data) - -# Statistic op 1: frequencies of byte values -def stat1(w, h, data): - bins = [0]*256 - for c in data: - i = ord(c) - bins[i] = bins[i]+1 - prbins(bins) - -def prbins(bins): - import string - s = '' - tot = 0 - for i in range(256): - tot = tot + bins[i] - s = s + string.rjust(`bins[i]`, 4) - if len(s) >= 4*16: - print s, string.rjust(`tot`, 7) - s = '' - tot = 0 - -# Statistic op 2: run lengths -def stat2(w, h, data): - runs = [] - for y in range(h): - count, value = 0, ord(data[y*w]) - for c in data[y*w : y*w+w]: - i = ord(c) - if i <> value: - runs.append(count, value) - count, value = 0, i - count = count+1 - runs.append(count, value) - print len(runs), 'runs =', 0.1 * (10*w*h/len(runs)), 'bytes/run' - -# Statistic op 3: frequencies of byte differences -def stat3(w, h, data): - bins = [0]*256 - prev = 0 - for c in data: - i = ord(c) - delta = divmod(i-prev, 256)[1] - prev = i - bins[delta] = bins[delta]+1 - prbins(bins) - -# Try packing -def packblock(w, h, data): - res = '' - for y in range(h): - res = res + packline(data[y*w : y*w+w]) - return res - -def packline(line): - bytes = [] - for c in line: - bytes.append(ord(c)) - prev = bytes[0] - i, n = 1, len(bytes) - while i < n: - for pack in (0, 2, 4, 8): - if pack == 0: - lo, hi = 0, 0 - else: - hi = pow(2, pack-1)-1 - lo = -hi-1 - p = prev - j = i - count = 0 - while j < n: - x = bytes[j] - delta = byte(x-p) - if not lo <= delta <= hi: - break - p = x - j = j+1 - -def byte(x): return divmod(x, 256)[1] - -main() diff --git a/Demo/sgi/video/svgrab24.c b/Demo/sgi/video/svgrab24.c deleted file mode 100755 index 3418b145da..0000000000 --- a/Demo/sgi/video/svgrab24.c +++ /dev/null @@ -1,97 +0,0 @@ -/* - * svgrab24 - Grab the current video input image into an rgb file. - * - * Jack Jansen, CWI, May 93. - * - * Adapted from grabone.c - */ - -#ident "$Revision$" - -#include -#include -#include -#include -#include -#include -#include - -main(int argc, char *argv[]) -{ - SVhandle V; - svCaptureInfo ci; - boolean debug; - int ch, errflg; - int bufferSize; - long *buffer; - IMAGE *imgfile; - short *r, *g, *b; - int x, y; - char *ProgName = argv[0]; - - debug = FALSE; - ci.format = SV_RGB32_FRAMES; - ci.width = 0; - ci.height = 0; - ci.size = 1; - - argv++; argc--; - if ( argc > 2 && strcmp(argv[0], "-w") == 0) { - ci.width = atoi(argv[1]); - argc -= 2; - argv += 2; - } - if ( argc != 1 ) { - fprintf(stderr, "Usage: %s [-w width] rgbfilename\n", ProgName); - exit(1); - } - - /* Open video device */ - if ((V = svOpenVideo()) == NULL) { - svPerror("open"); - exit(1); - } - - if (svQueryCaptureBufferSize(V, &ci, &bufferSize) < 0) { - svPerror("svQueryCaptureBufferSize"); - exit(1); - } - buffer = malloc(bufferSize); - - if (svCaptureOneFrame(V, ci.format, &ci.width, &ci.height, buffer) < 0) { - svPerror("svCaptureOneFrame"); - exit(1); - } - if (debug) { - printf("captured size: %d by %d\n", ci.width, ci.height); - } - - if ( (imgfile=iopen(argv[0], "w", RLE(1), 3, ci.width, ci.height, 3)) == 0) { - perror(argv[1]); - exit(1); - } - r = (short *)malloc(ci.width*sizeof(short)); - g = (short *)malloc(ci.width*sizeof(short)); - b = (short *)malloc(ci.width*sizeof(short)); - if ( !r || !g || !b ) { - fprintf(stderr, "%s: malloc failed\n", ProgName); - exit(1); - } - for(y=0; y>8) & 0xff; - b[x] = (data>>16) & 0xff; - } - if ( putrow(imgfile, r, y, 0) == 0 || - putrow(imgfile, g, y, 1) == 0 || - putrow(imgfile, b, y, 2) == 0) { - fprintf(stderr, "%s: putrow failed\n", ProgName); - exit(1); - } - } - iclose(imgfile); - exit(0); -} diff --git a/Demo/sgi/video/syncaudio.py b/Demo/sgi/video/syncaudio.py deleted file mode 100755 index fd09d2879c..0000000000 --- a/Demo/sgi/video/syncaudio.py +++ /dev/null @@ -1,94 +0,0 @@ -import AL -import al -import sys -import vtime -import socket -import time - - -SLEEPTIME = 500 # 500 ms sleeps -SAMPLEFREQ = 16000 # 16Khz samples -SAMPLERATE = AL.RATE_16000 -NEEDBUFFERED = SAMPLEFREQ # Buffer 1 second of sound -BUFFERSIZE = NEEDBUFFERED*4 # setqueuesize() par for 2 second sound - -AVSYNCPORT = 10000 # Port for time syncing -AVCTLPORT = 10001 # Port for record start/stop - -def main(): - if len(sys.argv) <> 3: - print 'Usage: ', sys.argv[0], 'videohostname soundfile' - sys.exit(1) - # - ofile = open(sys.argv[2], 'w') - # - globaltime = vtime.VTime().init(0,sys.argv[1],AVSYNCPORT) - # - ctl = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) - ctl.bind((socket.gethostname(),AVCTLPORT)) - # - inp = openmic() - # - out = 0 # Open aiff file - # - while 1: - if mainloop(None, ctl, inp, out, globaltime): - break - if mainloop(ofile, ctl, inp, out, globaltime): - break - pass # Close aiff file - sys.exit(0) -# -def openmic(): - conf = al.newconfig() - conf.setqueuesize(BUFFERSIZE) - conf.setwidth(AL.SAMPLE_16) - conf.setchannels(AL.MONO) - return al.openport('micr','r',conf) -# -def mainloop(ofile, ctl, inp, out, globaltime): - # - # Wait for sync packet, keeping 1-2 seconds of sound in the - # buffer - # - totsamps = 0 - totbytes = 0 - starttime = time.millitimer() - while 1: - time.millisleep(SLEEPTIME) - if ctl.avail(): - break - nsamples = inp.getfilled()-NEEDBUFFERED - if nsamples>0: - data = inp.readsamps(nsamples) - totsamps = totsamps + nsamples - totbytes = totbytes + len(data) - if ofile <> None: - ofile.write(data) - # - # Compute his starttime and the timestamp of the first byte in the - # buffer. Discard all buffered data upto his starttime - # - startstop,histime = eval(ctl.recv(100)) - if (ofile == None and startstop == 0) or \ - (ofile <> None and startstop == 1): - print 'Sync error: saving=',save,' request=',startstop - sys.exit(1) - filllevel = inp.getfilled() - filltime = time.millitimer() - filltime = filltime - filllevel / (SAMPLEFREQ/1000) - starttime = globaltime.his2mine(histime) - nsamples = starttime - filltime - if nsamples < 0: - print 'Start/stop signal came too late' - sys.exit(1) - nsamples = nsamples * (SAMPLEFREQ / 1000) - data = inp.readsamps(nsamples) - totsamps = totsamps + nsamples - totbytes = totbytes + len(data) - print 'Time: ', time.millitimer()-starttime, ', Bytes: ', totbytes, ', Samples: ', totsamps - if ofile <> None: - ofile.write(data) - return (startstop == 2) - -main() diff --git a/Demo/sgi/video/tomono.c b/Demo/sgi/video/tomono.c deleted file mode 100755 index 546af68afd..0000000000 --- a/Demo/sgi/video/tomono.c +++ /dev/null @@ -1,165 +0,0 @@ -#include - -long *bm; -long *nbm; -long h, w; -int nh, nw; -long factor; - -#define OC(x,xi) ((x)*factor+(xi)) -#define BM(x,xi,y,yi) bm[OC(y,yi)*w+OC(x,xi)] - -#define COMP(r,g,b) ((r) | ((g)<<8) | ((b) << 16)) - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -#define CHOICEFUNC(np1, np2) ( random() & 1 ) - -int inlevels = 3*255; -int outlevels = 1; - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int x, y, xi, yi; - int num; - int r, g, b; - long data; - int i; - double greyness; - int inpixels, outpixels; - int resid; - - setvbuf(stdout, 0, _IOFBF, 1024*128); - if( argc != 2) { - fprintf(stderr, "Usage: tomono factor\n"); - exit(1); - } - factor = atoi(argv[1]); - gets(lbuf); - if ( sscanf(lbuf, "(%d,%d)", &w, &h) != 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - nh = h / factor; - nw = w / factor; - printf("(%d,%d)\n", nw, nh); - if ( (bm = (long *)malloc(h*w*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - if ( (nbm = (long *)malloc(nh*nw*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - while( !feof(stdin) ) { - gets(lbuf); - if ( feof(stdin) ) break; - puts(lbuf); - fprintf(stderr, "Reading %d\n", h*w*sizeof(long)); - if ( (i=fread(bm, 1, h*w*sizeof(long), stdin)) != h*w*sizeof(long)) { - fprintf(stderr, "%s: short read, %d wanted %d\n", argv[0], - i, h*w*sizeof(long)); - exit(1); - } - /* - ** Compute picture blackness. - */ - inpixels = 0; - inpixels = countpixels(0,0,w,h); - greyness = (double)inpixels/(h*w*inlevels); - fprintf(stderr, "%3.1f%% grey\n", 100.0*greyness); - outpixels = (int)(greyness*outlevels*nh*nw); - fprintf(stderr, "Inpixels: %d (%d) Outpixels %d\n", inpixels, inpixels/inlevels, outpixels); - resid = fillpixels(0,0,nw,nh,0,0,w,h,outpixels); - if ( resid > 1 ) fprintf(stderr, "Residue: %d pixels\n", resid); - fprintf(stderr, "Writing %d\n", (nh*nw)*sizeof(long)); - fwrite(nbm, 1, (nh*nw)*sizeof(long), stdout); - } - exit(0); -} - -countpixels(x0,y0,x1,y1) -{ - int x, y, tot, data; - - tot = 0; - for( y=y0; y= x1 && y0+1 >= y1 ) { - if ( npixels ) { - nbm[y0*nw+x0] = 0xffffff; -/* fprintf(stderr, "->%d,%d\n", x0,y0); */ - return npixels - 1; - } - return 0; - } - if ( x1-x0 < y1-y0 ) { - if ( y1 - y0 <= 2 ) - m = y0 + 1; - else - m = y0+1+(random()%(y1-y0-1)); -/* fprintf(stderr,"%d,%d %d,%d Y %d\n", x0, x1, y0, y1, m); */ - /* om = (oy0+oy1)/2; */ om = m; - p1 = countpixels(ox0,oy0,ox1,om); - p2 = countpixels(ox0,om,ox1,oy1); - np1 = (int)(((float)p1/(p1+p2))*npixels); - np2 = (int)(((float)p2/(p1+p2))*npixels); - rp = npixels - np1 - np2; - if ( rp ) { - np1 += rp/2; - rp = rp - rp/2; - np2 += rp; - } - resid = 0; - if ( CHOICEFUNC(np1, np2) ) { - resid = fillpixels(x0,y0,x1,m,ox0,oy0,ox1,om,np1+resid); - resid = fillpixels(x0,m,x1,y1,ox0,om,ox1,oy1,np2+resid); - } else { - resid = fillpixels(x0,m,x1,y1,ox0,om,ox1,oy1,np2+resid); - resid = fillpixels(x0,y0,x1,m,ox0,oy0,ox1,om,np1+resid); - } - } else { - if ( x1 - x0 <= 2 ) - m = x0 + 1; - else - m = x0+1+(random()%(x1-x0-1)); -/* fprintf(stderr,"%d,%d %d,%d X %d\n", x0, x1, y0, y1, m); */ - /* om = (ox0+ox1)/2; */ om = m; - p1 = countpixels(ox0,oy0,om,oy1); - p2 = countpixels(om,oy0,ox1,oy1); - np1 = (int)(((float)p1/(p1+p2))*npixels); - np2 = (int)(((float)p2/(p1+p2))*npixels); - rp = npixels - np1 - np2; - if ( rp ) { - np1 += rp/2; - rp = rp - rp/2; - np2 += rp; - } - resid = 0; - if ( CHOICEFUNC(np1, np2) ) { - resid = fillpixels(x0,y0,m,y1,ox0,oy0,om,oy1,np1+resid); - resid = fillpixels(m,y0,x1,y1,om,oy0,ox1,oy1,np2+resid); - } else { - resid = fillpixels(m,y0,x1,y1,om,oy0,ox1,oy1,np2+resid); - resid = fillpixels(x0,y0,m,y1,ox0,oy0,om,oy1,np1+resid); - } - } - return resid; -} diff --git a/Demo/sgi/video/tv.py b/Demo/sgi/video/tv.py deleted file mode 100755 index da4bacbb63..0000000000 --- a/Demo/sgi/video/tv.py +++ /dev/null @@ -1,79 +0,0 @@ -import string - -from socket import * -from gl import * -from GL import * -from DEVICE import * -from time import millisleep, millitimer - -PORT = 5555 - -PF = 2 # packfactor -HS = 40 # Header size - -def testimage(): - RGBcolor(0, 0, 0) - clear() - RGBcolor(0, 255, 0) - cmov2i(10, 10) - charstr('Waiting...') - -def reshape(): - reshapeviewport() - w, h = getsize() - ortho2(0, w, 0, h) - testimage() - return w, h - -def main(): - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', PORT) - - foreground() - wid = winopen('tv') - RGBmode() - gconfig() - qdevice(ESCKEY) - - oldw, oldh = getsize() - ortho2(0, oldw, 0, oldh) - testimage() - - t1 = millitimer() - - while 1: - if qtest(): - dev, val = qread() - if dev == ESCKEY: - winclose(wid) - return - elif dev == REDRAW: - oldw, oldh = reshape() - elif s.avail(): - data = s.recv(17000) - header = string.strip(data[:HS]) - w, h, pf, x1, y1, x2, y2 = eval(header) - if (w, h) <> (oldw, oldh): - x, y = getorigin() - x, y = x-1, y+21 # TWM correction - winposition(x, x+w-1, y+oldh-h, y+oldh-1) - oldw, oldh = reshape() - data2 = data[HS:] - dx = (x2-x1+1)/pf - dy = (y2-y1+1)/pf - data3 = unpackrect(dx, dy, 1, data2) - rectzoom(pf, pf) - lrectwrite(x1, y1, x1+dx-1, y1+dy-1, data3) - t1 = millitimer() - else: - t2 = millitimer() - if t2-t1 >= 5000: - testimage() - t1 = t2 - else: - millisleep(10) - - winclose(wid) - return data - -main() diff --git a/Demo/sgi/video/v2i.c b/Demo/sgi/video/v2i.c deleted file mode 100755 index 5f8f3b5dec..0000000000 --- a/Demo/sgi/video/v2i.c +++ /dev/null @@ -1,79 +0,0 @@ -/* Convert the first image of a CMIF video movie file to SGI .rgb format. - usage: v2i videofile imagefile [planemask] - link with -limage -*/ - -#include -#include - -long bm[1280]; -short rb[1280], gb[1280], bb[1280]; -long w, h, pf; - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int x, y; - int i; - IMAGE * of; - int pmask; - - if( argc != 3 && argc != 4) { - fprintf(stderr, "Usage: v2i videofile imgfile [planemask]\n"); - exit(2); - } - if ( argc == 4) - pmask = atoi(argv[3]); - else - pmask = 7; - if ( freopen(argv[1], "r", stdin) == NULL ) { - perror(argv[1]); - exit(1); - } - if (fgets(lbuf, sizeof lbuf, stdin) == NULL) { - fprintf(stderr, "Immediate EOF\n"); - exit(1); - } - if (strncmp(lbuf, "CMIF", 4) == 0) { - /* Skip optional header line */ - if (fgets(lbuf, sizeof lbuf, stdin) == NULL) { - fprintf(stderr, "Immediate EOF after header\n"); - exit(1); - } - } - pf = 2; /* Default */ - if ( sscanf(lbuf, "(%d,%d,%d)", &w, &h, &pf) < 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - fgets(lbuf, sizeof lbuf, stdin); /* Skip time info */ - if ( w > 1280 ) { - fprintf(stderr, "%s: Sorry, too wide\n", argv[0]); - exit(1); - } - if ( (of=iopen(argv[2], "w", RLE(1), 3, w, h, 3)) == 0) { - perror(argv[2]); - exit(1); - } - for( y=0; y 2: - usage() - [ifile, ofile] = args - print 'open film ', ifile - ifilm = VFile.VinFile().init(ifile) - print 'open output ', ofile - ofilm = VFile.VoutFile().init(ofile) - - ofilm.setinfo(ifilm.getinfo()) - - use_grabber = 0 - continuous = 0 - tomono = 0 - tomonodither = 0 - for o, a in opts: - if o == '-t': - ofilm.format = a - use_grabber = 1 - if o == '-a': - continuous = 1 - if o == '-m': - if ifilm.format <> 'grey': - print '-m only supported for greyscale' - sys.exit(1) - tomono = 1 - treshold = string.atoi(a) - ofilm.format = 'mono' - if o == '-d': - if ifilm.format <> 'grey': - print '-m only supported for greyscale' - sys.exit(1) - tomonodither = 1 - ofilm.format = 'mono' - - ofilm.writeheader() - # - prefsize(ifilm.width, ifilm.height) - w = winopen(ifile) - qdevice(KEYBD) - qdevice(ESCKEY) - qdevice(WINQUIT) - qdevice(WINSHUT) - print 'qdevice calls done' - # - help() - # - time, data, cdata = ifilm.getnextframe() - ifilm.showframe(data, cdata) - iframe = 1 - report(time, iframe) - # - while 1: - if continuous: - dev = KEYBD - else: - dev, val = qread() - if dev in (ESCKEY, WINQUIT, WINSHUT): - break - if dev == REDRAW: - reshapeviewport() - elif dev == KEYBD: - if continuous: - c = '0' - else: - c = chr(val) - #XXX Debug - if c == 'R': - c3i(255,0,0) - clear() - if c == 'G': - c3i(0,255,0) - clear() - if c == 'B': - c3i(0,0,255) - clear() - if c == 'w' or continuous: - if use_grabber: - data, cdata = ofilm.grabframe() - if tomono: - data = imageop.grey2mono(data, \ - ifilm.width, ifilm.height, \ - treshold) - if tomonodither: - data = imageop.dither2mono(data, \ - ifilm.width, ifilm.height) - ofilm.writeframe(time, data, cdata) - print 'Frame', iframe, 'written.' - if c == 'n' or continuous: - try: - time,data,cdata = ifilm.getnextframe() - ifilm.showframe(data, cdata) - iframe = iframe+1 - report(time, iframe) - except EOFError: - print 'EOF' - if continuous: - break - ringbell() - elif dev == INPUTCHANGE: - pass - else: - print '(dev, val) =', (dev, val) - ofilm.close() - -main() diff --git a/Demo/sgi/video/video.doc b/Demo/sgi/video/video.doc deleted file mode 100755 index 982c008f7e..0000000000 --- a/Demo/sgi/video/video.doc +++ /dev/null @@ -1,109 +0,0 @@ - CMIF video tools - -This document gives a quick introduction to some of the tools useful -for recording, editing and playing back video data in CMIF video -format. All the tools mentioned currently live in /ufs/guido/bin/sgi. -A description of the CMIF video file format can be found in -/ufs/jack/cmif-film.ms. - - Recording video - -There are two tools to record video, Vrec and and Vrecb. Vrec does -continuous capture, but can capture at most 15 frames per second. -Vrecb uses burst capture, enabling it to capture all frames. It -captures to main memory, however, so it cannot handle long video -fragments. The following options are common to both programs: - - -r rate Capture one out of 'rate' frames. Default (and - minimum) is 1 for Vrecb, 2 for Vrec. There are some - caveats for recording PAL, see below. - -w width Set initial window width (and height, implicitly). - -g bits Create greyscale film in stead of 8-bit dithered color - film. Allowable values for 'bits' are 2, 4 or 8. - -m Create monochrome dithered film. These look horrible. - -M threshold Create monochrome thresholded film with specified - threshold (in range 0..255). - -G Create 2-bit dithered greyscale film. - -f Capture fields in stead of frames. The film is created - in such a way that the picture will be suitably - enlarged on playback, so aspect ratio, etc. are - maintained. - -d Drop fields if they would cause data from two video - fields to be combined. See the section on PAL for more - details. - -Options for Vrec: - -a Record audio as well. You will have to twiddle audio - and video later if you want lipsync playback. - -q queuesize Set size of the video board circular buffer. A little - experimentation with this may lead to more video being - captured, but not always. - -P frames Preallocate diskspace for 'frames' images. This may - enable you to capture more frames. - -Options for Vrecb: - -n number Capture 'number' frames. Default is 60 (2 seconds). - -Both programs accept a filename to store the video on (default -film.video) and Vrec also accepts an audio file name (default -film.aiff). When you want to record you press the left mouse button. -Vrec stops recording when you release the mouse button and Vrecb stops -after the predetermined number of frames have been recorded. During -recording the picture may look funny, but do not let this worry you, -the film will be ok. - -After recording and saving, Vrec will print the deltas of the field -numbers recorded. A list of '4 4 4 4'... means that all possible -frames (one out of two) have been recorded. Vrecb will tell you how -many duplicate fields have been skipped. See below on PAL useage -again. - - PAL caveats - -The IndigoVideo board converts the incoming video signal to the 60Hz -(59.something, actually) display rate. All further operations, -including capture, are done with respect to display rate. This is -especially bothersome in the case of PAL video, since it means one out -of 5 frames will be duplicated. Together with the fact that, in -continuous capture, you can only capture every second frame this leads -to strange and wondrous effects. The frame numbers returned by the -video board (and displayed by Vrec) are display frame numbers, and so -bear only a very complicated (and probably non-deterministic) relation -to PAL frame numbers. For recording simple videos this is probably no -problem. You can use Vrec and try using -d to see which gives the best -result. On the other hand, if you need every frame and no duplicates -either you have to use Vrecb and supply the -d and -f option. This -will give you exactly the fields as they appeared on the PAL tape. - - Video playback - -The easiest way to play back a video is to use Vplay. Calling it with -an argument of -? will make it list all its options. A few options may -need a bit of explanation: - -M magnify Magnify the images by the given factor. This still - takes any magnification specified in the film (if it - is a field film, for instance) in account. - -w width and - -h height Normally the window will be the correct size for the - film. You can set height and width, though, if you - want the window to be bigger. This is especially - useful if you want to record the film back to - videotape, since you can playback in a window that is - bigger than PAL size with a black background and you - will have no distracting window-manager thingies on - your videotape. - - Video Editing - -Vedit is a (very simple) video editor that allows you to select images -from the input movie and copy them to an output movie. Both input and -output films have a modest buffer that you can move around in. - -Vaddcache takes a movie and adds a frame location cache to it. This -will make some other programs run faster. - -rgb2video converts a set of SGI .rgb files to a movie. - -There are a few programs that can do image format conversion on movies -(i.e. convert an 8-bit dithered RGB movie to a greyscale movie), but -nothing very complete yet. Look at Vcopy.py for more information. diff --git a/Demo/sgi/video/video.py b/Demo/sgi/video/video.py deleted file mode 100755 index 1b81bd83f7..0000000000 --- a/Demo/sgi/video/video.py +++ /dev/null @@ -1,218 +0,0 @@ -import getopt -from gl import * -from GL import * -from DEVICE import * -import time -import sys -import al -import AL - -sys.path.append('/ufs/guido/src/video') # Increase chance to find colorsys -import colorsys - -BUFFERSIZE = 32000 - -class Struct(): pass -epoch = Struct() -epoch.correcttiming = 1 -EndOfFile = 'End of file' -bye = 'bye' - -def openspkr(): - conf = al.newconfig() - conf.setqueuesize(BUFFERSIZE) - conf.setwidth(AL.SAMPLE_16) - conf.setchannels(AL.MONO) - return al.openport('spkr','w',conf) - -def openvideo(name): - try: - f = open(name, 'r') - except: - sys.stderr.write(name + ': cannot open\n') - sys.exit(1) - line = f.readline() - if not line: raise EndOfFile - colorinfo = (8, 0, 0, 0) - if line[:4] == 'CMIF': - if line[:14] == 'CMIF video 2.0': - line = f.readline() - colorinfo = eval(line[:-1]) - line = f.readline() - x = eval(line[:-1]) - if len(x) == 3: w, h, pf = x - else: w, h = x; pf = 2 - if pf and w/pf % 4 <> 0: - sys.stderr.write( \ - 'warning: stride not a multiple of 4 -- may not work on Indigo XS\n') - return f, w, h, pf, colorinfo - -def loadframe(f,w,h,pf,af,spkr, (ybits,ibits,qbits,chrompack),mf): - line = f.readline() - if line == '': - raise EndOfFile - x = eval(line[:-1]) - if type(x) == type(0) or type(x) == type(0.0): - tijd = x - if pf == 0: - size = w*h*4 - else: - size = (w/pf) * (h/pf) - else: - tijd, size = x - data = f.read(size) - if len(data) <> size: - raise EndOfFile - if pf: - w = w/pf - h = h/pf - if chrompack: - cw = (w+chrompack-1)/chrompack - ch = (h+chrompack-1)/chrompack - chromdata = f.read(2*cw*ch) - rectzoom(pf*chrompack*mf,pf*chrompack*mf) - pixmode(PM_SIZE,16) - writemask(0x7ff - ((1< 1: - rectzoom(mf,mf) - lrectwrite(0,0,w-1,h-1,data) - # This is ugly here, but the only way to get the two - # channels started in sync - #if af <> None: - # playsound(af,spkr) - ct = time.millitimer() - epoch.epoch - if epoch.correcttiming and tijd > 0 and ct < tijd: - time.millisleep(tijd-ct) - #swapbuffers() - return tijd - -def initcmap(ybits,ibits,qbits,chrompack): - if ybits+ibits+qbits > 11: - raise 'Sorry, 11 bits max' - maxy = pow(2,ybits) - maxi = pow(2,ibits) - maxq = pow(2,qbits) - for i in range(2048,4096-256): - mapcolor(i, 0, 255, 0) - for y in range(maxy): - yv = float(y)/float(maxy-1) - for i in range(maxi): - if maxi == 1: iv = 0 - else: iv = (float(i)/float(maxi-1))-0.5 - for q in range(maxq): - if maxq == 1: qv = 0 - else: qv = (float(q)/float(maxq-1))-0.5 - index = 2048 + y + (i << ybits) + (q << (ybits+ibits)) - rv,gv,bv = colorsys.yiq_to_rgb(yv,iv,qv) - r,g,b = int(rv*255.0), int(gv*255.0), int(bv*255.0) - if index < 4096 - 256: - mapcolor(index, r,g,b) - -def playsound(af, spkr): - nsamp = spkr.getfillable() - data = af.read(nsamp*2) - spkr.writesamps(data) - -def main(): - looping = 0 - packfactor = 0 - magfactor = 1 - try: - opts, args = getopt.getopt(sys.argv[1:], 'm:p:lF') - except getopt.error: - sys.stderr.write('usage: video ' + \ - '[-l] [-p pf] [-m mag] [-F] [moviefile [soundfile [skipbytes]]]\n') - sys.exit(2) - for opt, arg in opts: - if opt == '-m': - magfactor = int(eval(arg)) - elif opt == '-p': - packfactor = int(eval(arg)) - elif opt == '-l': - looping = 1 - elif opt == '-F': - epoch.correcttiming = 0 - if args: - filename = args[0] - else: - filename = 'film.video' - f, w, h, pf, cinfo = openvideo(filename) - if 0 < packfactor <> pf: - w = w/pf*packfactor - h = h/pf*packfactor - pf = packfactor - if args[1:]: - audiofilename = args[1] - af = open(audiofilename, 'r') - spkr = openspkr() - afskip = 0 - if args[2:]: - afskip = eval(args[2]) - af.seek(afskip) - else: - af, spkr = None, None - foreground() - prefsize(w*magfactor,h*magfactor) - win = winopen(filename) - if pf: - #doublebuffer() - cmode() - else: - RGBmode() - #doublebuffer() - gconfig() - if pf: - initcmap(cinfo) - color(2048) - clear() - writemask(2047) - pixmode(PM_SIZE,8) # 8 bit pixels - qdevice(ESCKEY) - qdevice(WINSHUT) - qdevice(WINQUIT) - running = 1 - epoch.epoch = time.millitimer() - nframe = 0 - tijd = 1 - if looping: - looping = f.tell() - try: - while 1: - if running: - try: - tijd = loadframe(f, w, h, pf, af, spkr, cinfo,magfactor) - nframe = nframe + 1 - except EndOfFile: - running = 0 - t = time.millitimer() - if tijd > 0: - print 'Recorded at', - print 0.1 * int(nframe * 10000.0 / tijd), - print 'frames/sec' - print 'Played', nframe, 'frames at', - print 0.1 * int(nframe * 10000.0 / (t-epoch.epoch)), - print 'frames/sec' - if looping: - f.seek(looping) - epoch.epoch = time.millitimer() - nframe = 0 - running = 1 - if af <> None: - af.seek(afskip) - if af <> None: - playsound(af,spkr) - if not running or qtest(): - dev, val = qread() - if dev in (ESCKEY, WINSHUT, WINQUIT): - raise bye - elif dev == REDRAW: - reshapeviewport() - except bye: - pass - -main() diff --git a/Demo/sgi/video/video2rgb.py b/Demo/sgi/video/video2rgb.py deleted file mode 100755 index bbfa6b8238..0000000000 --- a/Demo/sgi/video/video2rgb.py +++ /dev/null @@ -1,159 +0,0 @@ -#! /usr/bin/env python - -# Convert CMIF movie file(s) to a sequence of rgb images - - -# Help function - -def help(): - print 'Usage: video2rgb [options] [file] ...' - print - print 'Options:' - print '-q : quiet, no informative messages' - print '-m : create monochrome (greyscale) image files' - print '-f prefix : create image files with names "prefix0000.rgb"' - print 'file ... : file(s) to convert; default film.video' - - -# Imported modules - -import sys -sys.path.append('/ufs/jack/src/av/video') # Increase chance of finding VFile -import VFile -import time -import getopt -import string -import imgfile -import imgconv - - -# Global options - -quiet = 0 -prefix = 'film' -seqno = 0 -mono = 0 - - -# Main program -- mostly command line parsing - -def main(): - global quiet, prefix, mono - - # Parse command line - try: - opts, args = getopt.getopt(sys.argv[1:], 'qmf:') - except getopt.error, msg: - sys.stdout = sys.stderr - print 'Error:', msg, '\n' - help() - sys.exit(2) - - # Interpret options - try: - for opt, arg in opts: - if opt == '-q': quiet = 1 - if opt == '-f': prefix = arg - if opt == '-m': mono = 1 - except string.atoi_error: - sys.stdout = sys.stderr - print 'Option', opt, 'requires integer argument' - sys.exit(2) - - # Process all files - if not args: args = ['film.video'] - sts = 0 - for filename in args: - sts = (process(filename) or sts) - - # Exit with proper exit status - sys.exit(sts) - - -# Process one movie file - -def process(filename): - try: - vin = VFile.VinFile(filename) - except IOError, msg: - sys.stderr.write(filename + ': I/O error: ' + `msg` + '\n') - return 1 - except VFile.Error, msg: - sys.stderr.write(msg + '\n') - return 1 - except EOFError: - sys.stderr.write(filename + ': EOF in video header\n') - return 1 - - if not quiet: - vin.printinfo() - - width, height = int(vin.width), int(vin.height) - - try: - if mono: - cf = imgconv.getconverter(vin.format, 'grey') - else: - cf = imgconv.getconverter(vin.format, 'rgb') - except imgconv.error: - print 'Sorry, no converter available for type',vin.format - return - - if mono: - depth = 1 - bpp = 1 - else: - depth = 3 - bpp = 4 - - convert(vin, cf, width, height, depth, bpp, vin.packfactor) - -def convert(vin, cf, width, height, depth, bpp, pf): - global seqno - - if type(pf) == type(()): - xpf, ypf = pf - elif pf == 0: - xpf = ypf = 1 - else: - xpf = ypf = pf - while 1: - try: - time, data, cdata = vin.getnextframe() - except EOFError: - return - if cdata: - print 'Film contains chromdata!' - return - data = cf(data, width/xpf, height/abs(ypf)) - if pf: - data = applypackfactor(data, width, height, pf, bpp) - s = `seqno` - s = '0'*(4-len(s)) + s - fname = prefix + s + '.rgb' - seqno = seqno + 1 - if not quiet: - print 'Writing',fname,'...' - imgfile.write(fname, data, width, height, depth) - -def applypackfactor(image, w, h, pf, bpp): - import imageop - if type(pf) == type(()): - xpf, ypf = pf - elif pf == 0: - xpf = ypf = 1 - else: - xpf = ypf = pf - w1 = w/xpf - h1 = h/abs(ypf) - if ypf < 0: - ypf = -ypf - image = imageop.crop(image, bpp, w1, h1, 0, h1-1, w1-1, 0) - return imageop.scale(image, bpp, w1, h1, w, h) - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/vinfo.py b/Demo/sgi/video/vinfo.py deleted file mode 100755 index 7f98237a97..0000000000 --- a/Demo/sgi/video/vinfo.py +++ /dev/null @@ -1,90 +0,0 @@ -from gl import * -from GL import * -from DEVICE import * -import time -import sys -import getopt - -class Struct(): pass -epoch = Struct() -EndOfFile = 'End of file' -bye = 'bye' - -def openvideo(filename): - f = open(filename, 'r') - line = f.readline() - if not line: raise EndOfFile - if line[:4] == 'CMIF': line = f.readline() - x = eval(line[:-1]) - if len(x) == 3: w, h, pf = x - else: w, h = x; pf = 2 - return f, w, h, pf - -def loadframe(f, w, h, pf): - line = f.readline() - if line == '': - raise EndOfFile - x = eval(line[:-1]) - if type(x) == type(0) or type(x) == type(0.0): - tijd = x - if pf == 0: - size = w*h*4 - else: - size = (w/pf) * (h/pf) - else: - tijd, size = x - f.seek(size, 1) - return tijd - -def main(): - delta = 0 - short = 0 - try: - opts, names = getopt.getopt(sys.argv[1:], 'ds') - except getopt.error, msg: - sys.stderr.write(msg + '\n') - sys.stderr.write('usage: vinfo [-d] [-s] [file] ...\n') - sys.exit(2) - for opt, arg in opts: - if opt == '-d': delta = 1 # print delta between frames - elif opt == '-s': short = 1 # short: don't print times - if names == []: - names = ['film.video'] - for name in names: - try: - f, w, h, pf = openvideo(name) - except: - sys.stderr.write(name + ': cannot open\n') - continue - if pf == 0: - size = w*h*4 - else: - size = (w/pf) * (h/pf) - print name, ':', w, 'x', h, '; pf =', pf, ', size =', size, - if pf == 0: - print '(color)', - else: - print '(' + `(w/pf)` + 'x' + `(h/pf)` + ')', - if (w/pf)%4 <> 0: print '!!!', - print - num = 0 - try: - otijd = 0 - while not short: - try: - tijd = loadframe(f, w, h, pf) - if delta: print '\t' + `tijd-otijd`, - else: print '\t' + `tijd`, - otijd = tijd - num = num + 1 - if num % 8 == 0: - print - except EndOfFile: - raise bye - except bye: - pass - if num % 8 <> 0: - print - f.close() - -main() diff --git a/Demo/sgi/video/vpregs.py b/Demo/sgi/video/vpregs.py deleted file mode 100755 index d33f1fe93e..0000000000 --- a/Demo/sgi/video/vpregs.py +++ /dev/null @@ -1,28 +0,0 @@ -VID_VP = 0x1000000 - -# Set vp1 register tokens -VP_GBXORG = (VID_VP +0x01) -VP_GBYORG = (VID_VP +0x02) -VP_FBXORG = (VID_VP +0x03) -VP_FBYORG = (VID_VP +0x04) -VP_WIDTH = (VID_VP +0x05) -VP_HEIGHT = (VID_VP +0x06) -VP_PIXCNT = (VID_VP +0x07) -VP_HBLANK = (VID_VP +0x08) -VP_VBLANK = (VID_VP +0x09) -VP_BRITE = (VID_VP +0x0A) -VP_CONT = (VID_VP +0x0B) -VP_HUE = (VID_VP +0x0C) -VP_SAT = (VID_VP +0x0D) -VP_ALPHA = (VID_VP +0X0E) -VP_FGMODE = (VID_VP +0x0F) -VP_MAPSRC = (VID_VP +0x10) -VP_MAPADD = (VID_VP +0x11) -VP_MAPRED = (VID_VP +0x12) -VP_MAPGREEN = (VID_VP +0x13) -VP_MAPBLUE = (VID_VP +0x14) -VP_MAPSTROBE = (VID_VP +0x15) -VP_DIGVAL = (VID_VP +0x16) -VP_STATUS0 = (VID_VP +0x17) -VP_STATUS1 = (VID_VP +0x18) -VP_CMD = (VID_VP +0x19) diff --git a/Demo/sgi/video/vtime.py b/Demo/sgi/video/vtime.py deleted file mode 100755 index c333e57983..0000000000 --- a/Demo/sgi/video/vtime.py +++ /dev/null @@ -1,106 +0,0 @@ -# -# Module vtime - Keep virtual time between two nodes. -# -# We try for synchronised clocks by sending a packet of the for -# (1,mytime,0) to the other side, and waiting (at most) a second for -# a reply. This reply has the form (2,mytime,histime), and we can -# estimate the time difference by defining histime to be exactly half-way -# between the time we sent our message and got our reply. We send a -# final (3,mynewtime,histime) message to allow the other side to do the -# same computations. -# -# Note that the protocol suffers heavily from the 2-army problem. -# It'll have to do until I can read up on time-sync protocols, though. -# -from socket import * -import time - -MSGSIZE = 100 -MSGTIMEOUT = 1000 - -recv_timeout = 'receive timeout' -bad_connect = 'Bad connection' - -def timeavg(a,b): - return int((long(a)+b)/2L) -def tryrecv(s): - cnt = 0 - while 1: - if s.avail(): - return s.recvfrom(MSGSIZE) - time.millisleep(100) - cnt = cnt + 100 - if cnt > MSGTIMEOUT: - raise recv_timeout - -class VTime(): - def init(self,(client,host,port)): - s = socket(AF_INET, SOCK_DGRAM) - host = gethostbyname(host) - localhost = gethostbyname(gethostname()) - raddr = (host,port) - s.bind((localhost,port)) - if client: - # - # We loop here because we want the *second* measurement - # for accuracy - for loopct in (0,2): - curtijd = time.millitimer() - check = `(loopct,curtijd,0)` - s.sendto(check,raddr) - while 1: - try: - if loopct: - data, other = s.recvfrom(MSGSIZE) - else: - data, other = tryrecv(s) - newtijd = time.millitimer() - if other <> raddr: - print 'Someone else syncing to us: ', other - raise bad_connect - data = eval(data) - if data[:2] == (loopct+1,curtijd): - break - if data[0] <> 2: - print 'Illegal sync reply: ', data - raise bad_connect - except recv_timeout: - curtijd = time.millitimer() - check = `(loopct,curtijd,0)` - s.sendto(check,raddr) - histime = data[2] - s.sendto(`(4,newtijd,histime)`,raddr) - mytime = timeavg(curtijd,newtijd) - #mytime = curtijd - self.timediff = histime - mytime - else: - while 1: - data,other = s.recvfrom(MSGSIZE) - if other <> raddr: - print 'Someone else syncing to us: ', other, ' Wanted ', raddr - raise bad_connect - data = eval(data) - if data[0] in (0,2): - curtijd = time.millitimer() - s.sendto(`(data[0]+1,data[1],curtijd)`,raddr) - elif data[0] == 4: - newtijd = time.millitimer() - histime = data[1] - mytime = timeavg(curtijd,newtijd) - #mytime = curtijd - self.timediff = histime-mytime - break - else: - print 'Funny data: ', data - raise bad_connect - return self - # - def his2mine(self,tijd): - return tijd - self.timediff - # - def mine2his(self, tijd): - return tijd + self.timediff - -def test(clt, host, port): - xx = VTime().init(clt,host,port) - print 'Time diff: ', xx.his2mine(0) diff --git a/Demo/sgi/video/watchcursor.py b/Demo/sgi/video/watchcursor.py deleted file mode 100755 index aae3f85d50..0000000000 --- a/Demo/sgi/video/watchcursor.py +++ /dev/null @@ -1,45 +0,0 @@ -# Define a 16x16 cursor looking like a watch - -# X11 bitmap file: -##define x_width 16 -##define x_height 16 -#static char x_bits[] = { -# 0xf0, 0x0f, 0xf8, 0x1f, 0x1c, 0x38, 0x8e, 0x71, 0x87, 0xe1, 0x83, 0xc1, -# 0x83, 0xc1, 0xf3, 0xc1, 0xf3, 0xc1, 0x03, 0xc0, 0x03, 0xc0, 0x07, 0xe0, -# 0x0e, 0x70, 0x1c, 0x38, 0xf8, 0x1f, 0xf0, 0x0f}; - - -watch = [ \ - 0x0ff0,\ - 0x1ff8,\ - 0x381c,\ - 0x718e,\ - 0xe187,\ - 0xc183,\ - 0xc183,\ - 0xc1f3,\ - 0xc1f3,\ - 0xc003,\ - 0xc003,\ - 0xe007,\ - 0x700e,\ - 0x381c,\ - 0x1ff8,\ - 0x0ff0,\ - ] - -watch.reverse() # Turn it upside-down - -def defwatch(index): - import gl - gl.defcursor(index, watch*8) - gl.curorigin(index, 8, 8) - -def test(): - import gl - gl.foreground() - gl.winopen('test watchcursor') - defwatch(1) - gl.setcursor(1, 0, 0) - import time - time.sleep(10) diff --git a/Demo/sockets/ChangeLog b/Demo/sockets/ChangeLog deleted file mode 100755 index c1d41b1f67..0000000000 --- a/Demo/sockets/ChangeLog +++ /dev/null @@ -1,35 +0,0 @@ -Mon Nov 16 17:55:30 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Restructured mcast. - -Tue Nov 3 13:08:41 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Fixed ftp.py to use 'global' instead of a hack - -25-Oct-1992 - -* Added gopher.py - -2-Oct-1992 - -* Changed /usr/local/python to /usr/local/bin/python - -Thu Sep 24 12:33:56 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Improved computation of mcast group bytes (use regsub.gsub()) - -Tue Sep 8 23:20:51 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Added mcast.py and IN.py. - -* Use setsockopt() instead of allowbroadcast() in broadcast.py. - -Mon Aug 10 12:45:43 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* README: added broadcast.py, ftp.py, radio.py - -------------------------------------------------------------------------------- -^^^ Log entries after release of 0.9.6 ^^^ -------------------------------------------------------------------------------- - - diff --git a/Demo/sockets/README b/Demo/sockets/README deleted file mode 100644 index 21ed808cc3..0000000000 --- a/Demo/sockets/README +++ /dev/null @@ -1,22 +0,0 @@ -This directory contains some demonstrations of the socket module: - -broadcast.py Broadcast the time to radio.py. -echosvr.py About the simplest TCP server possible. -finger.py Client for the 'finger' protocol. -ftp.py A very simple ftp client. -gopher.py A simple gopher client. -radio.py Receive time broadcasts from broadcast.py. -telnet.py Client for the 'telnet' protocol. -throughput.py Client and server to measure TCP throughput. -unixclient.py Unix socket example, client side -unixserver.py Unix socket example, server side -udpecho.py Client and server for the UDP echo protocol. - -The following file is only relevant on SGI machines (or other systems -that support multicast): - -mcast.py A Python translation of - /usr/people/4Dgifts/examples/network/mcast.c - (Note that IN.py is in ../../lib/sgi.) - -See also ../../lib/nntp.py for another example of socket code. diff --git a/Demo/sockets/broadcast.py b/Demo/sockets/broadcast.py deleted file mode 100755 index a02b081a2e..0000000000 --- a/Demo/sockets/broadcast.py +++ /dev/null @@ -1,17 +0,0 @@ -# Send UDP broadcast packets - -MYPORT = 50000 - -import sys, time -from socket import * - -s = socket(AF_INET, SOCK_DGRAM) -s.bind(('', 0)) -s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) - -while 1: - data = `time.time()` + '\n' - s.sendto(data, ('', MYPORT)) - time.sleep(2) - - diff --git a/Demo/sockets/echosvr.py b/Demo/sockets/echosvr.py deleted file mode 100755 index a37f9c26eb..0000000000 --- a/Demo/sockets/echosvr.py +++ /dev/null @@ -1,31 +0,0 @@ -#! /usr/bin/env python - -# Python implementation of an 'echo' tcp server: echo all data it receives. -# -# This is the simplest possible server, servicing a single request only. - -import sys -from socket import * - -# The standard echo port isn't very useful, it requires root permissions! -# ECHO_PORT = 7 -ECHO_PORT = 50000 + 7 -BUFSIZE = 1024 - -def main(): - if len(sys.argv) > 1: - port = int(eval(sys.argv[1])) - else: - port = ECHO_PORT - s = socket(AF_INET, SOCK_STREAM) - s.bind(('', port)) - s.listen(1) - conn, (remotehost, remoteport) = s.accept() - print 'connected by', remotehost, remoteport - while 1: - data = conn.recv(BUFSIZE) - if not data: - break - conn.send(data) - -main() diff --git a/Demo/sockets/finger.py b/Demo/sockets/finger.py deleted file mode 100755 index 0c2baed0b4..0000000000 --- a/Demo/sockets/finger.py +++ /dev/null @@ -1,58 +0,0 @@ -#! /usr/bin/env python - -# Python interface to the Internet finger daemon. -# -# Usage: finger [options] [user][@host] ... -# -# If no host is given, the finger daemon on the local host is contacted. -# Options are passed uninterpreted to the finger daemon! - - -import sys, string -from socket import * - - -# Hardcode the number of the finger port here. -# It's not likely to change soon... -# -FINGER_PORT = 79 - - -# Function to do one remote finger invocation. -# Output goes directly to stdout (although this can be changed). -# -def finger(host, args): - s = socket(AF_INET, SOCK_STREAM) - s.connect((host, FINGER_PORT)) - s.send(args + '\n') - while 1: - buf = s.recv(1024) - if not buf: break - sys.stdout.write(buf) - sys.stdout.flush() - - -# Main function: argument parsing. -# -def main(): - options = '' - i = 1 - while i < len(sys.argv) and sys.argv[i][:1] == '-': - options = options + sys.argv[i] + ' ' - i = i+1 - args = sys.argv[i:] - if not args: - args = [''] - for arg in args: - if '@' in arg: - at = string.index(arg, '@') - host = arg[at+1:] - arg = arg[:at] - else: - host = '' - finger(host, options + arg) - - -# Call the main function. -# -main() diff --git a/Demo/sockets/ftp.py b/Demo/sockets/ftp.py deleted file mode 100755 index 8260c52f9c..0000000000 --- a/Demo/sockets/ftp.py +++ /dev/null @@ -1,146 +0,0 @@ -# A simple FTP client. -# -# The information to write this program was gathered from RFC 959, -# but this is not a complete implementation! Yet it shows how a simple -# FTP client can be built, and you are welcome to extend it to suit -# it to your needs... -# -# How it works (assuming you've read the RFC): -# -# User commands are passed uninterpreted to the server. However, the -# user never needs to send a PORT command. Rather, the client opens a -# port right away and sends the appropriate PORT command to the server. -# When a response code 150 is received, this port is used to receive -# the data (which is written to stdout in this version), and when the -# data is exhausted, a new port is opened and a corresponding PORT -# command sent. In order to avoid errors when reusing ports quickly -# (and because there is no s.getsockname() method in Python yet) we -# cycle through a number of ports in the 50000 range. - - -import sys, posix, string -from socket import * - - -BUFSIZE = 1024 - -# Default port numbers used by the FTP protocol. -# -FTP_PORT = 21 -FTP_DATA_PORT = FTP_PORT - 1 - -# Change the data port to something not needing root permissions. -# -FTP_DATA_PORT = FTP_DATA_PORT + 50000 - - -# Main program (called at the end of this file). -# -def main(): - hostname = sys.argv[1] - control(hostname) - - -# Control process (user interface and user protocol interpreter). -# -def control(hostname): - # - # Create control connection - # - s = socket(AF_INET, SOCK_STREAM) - s.connect((hostname, FTP_PORT)) - f = s.makefile('r') # Reading the replies is easier from a file... - # - # Control loop - # - r = None - while 1: - code = getreply(f) - if code in ('221', 'EOF'): break - if code == '150': - getdata(r) - code = getreply(f) - r = None - if not r: - r = newdataport(s, f) - cmd = getcommand() - if not cmd: break - s.send(cmd + '\r\n') - - -# Create a new data port and send a PORT command to the server for it. -# (Cycle through a number of ports to avoid problems with reusing -# a port within a short time.) -# -nextport = 0 -# -def newdataport(s, f): - global nextport - port = nextport + FTP_DATA_PORT - nextport = (nextport+1) % 16 - r = socket(AF_INET, SOCK_STREAM) - r.bind((gethostbyname(gethostname()), port)) - r.listen(1) - sendportcmd(s, f, port) - return r - - -# Send an appropriate port command. -# -def sendportcmd(s, f, port): - hostname = gethostname() - hostaddr = gethostbyname(hostname) - hbytes = string.splitfields(hostaddr, '.') - pbytes = [`port/256`, `port%256`] - bytes = hbytes + pbytes - cmd = 'PORT ' + string.joinfields(bytes, ',') - s.send(cmd + '\r\n') - code = getreply(f) - - -# Process an ftp reply and return the 3-digit reply code (as a string). -# The reply should be a line of text starting with a 3-digit number. -# If the 4th char is '-', it is a multi-line reply and is -# terminate by a line starting with the same 3-digit number. -# Any text while receiving the reply is echoed to the file. -# -def getreply(f): - line = f.readline() - if not line: return 'EOF' - print line, - code = line[:3] - if line[3:4] == '-': - while 1: - line = f.readline() - if not line: break # Really an error - print line, - if line[:3] == code and line[3:4] != '-': break - return code - - -# Get the data from the data connection. -# -def getdata(r): - print '(accepting data connection)' - conn, host = r.accept() - print '(data connection accepted)' - while 1: - data = conn.recv(BUFSIZE) - if not data: break - sys.stdout.write(data) - print '(end of data connection)' - -# Get a command from the user. -# -def getcommand(): - try: - while 1: - line = raw_input('ftp.py> ') - if line: return line - except EOFError: - return '' - - -# Call the main program. -# -main() diff --git a/Demo/sockets/gopher.py b/Demo/sockets/gopher.py deleted file mode 100755 index a2ab3a2f6c..0000000000 --- a/Demo/sockets/gopher.py +++ /dev/null @@ -1,347 +0,0 @@ -#! /usr/bin/env python - -# A simple gopher client. -# -# Usage: gopher [ [selector] host [port] ] - -import string -import sys -import os -import socket - -# Default selector, host and port -DEF_SELECTOR = '' -DEF_HOST = 'gopher.micro.umn.edu' -DEF_PORT = 70 - -# Recognized file types -T_TEXTFILE = '0' -T_MENU = '1' -T_CSO = '2' -T_ERROR = '3' -T_BINHEX = '4' -T_DOS = '5' -T_UUENCODE = '6' -T_SEARCH = '7' -T_TELNET = '8' -T_BINARY = '9' -T_REDUNDANT = '+' -T_SOUND = 's' - -# Dictionary mapping types to strings -typename = {'0': '', '1': '', '2': '', '3': '', \ - '4': '', '5': '', '6': '', '7': '', \ - '8': '', '9': '', '+': '', 's': ''} - -# Oft-used characters and strings -CRLF = '\r\n' -TAB = '\t' - -# Open a TCP connection to a given host and port -def open_socket(host, port): - if not port: - port = DEF_PORT - elif type(port) == type(''): - port = string.atoi(port) - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.connect((host, port)) - return s - -# Send a selector to a given host and port, return a file with the reply -def send_request(selector, host, port): - s = open_socket(host, port) - s.send(selector + CRLF) - s.shutdown(1) - return s.makefile('r') - -# Get a menu in the form of a list of entries -def get_menu(selector, host, port): - f = send_request(selector, host, port) - list = [] - while 1: - line = f.readline() - if not line: - print '(Unexpected EOF from server)' - break - if line[-2:] == CRLF: - line = line[:-2] - elif line[-1:] in CRLF: - line = line[:-1] - if line == '.': - break - if not line: - print '(Empty line from server)' - continue - typechar = line[0] - parts = string.splitfields(line[1:], TAB) - if len(parts) < 4: - print '(Bad line from server:', `line`, ')' - continue - if len(parts) > 4: - print '(Extra info from server:', parts[4:], ')' - parts.insert(0, typechar) - list.append(parts) - f.close() - return list - -# Get a text file as a list of lines, with trailing CRLF stripped -def get_textfile(selector, host, port): - list = [] - get_alt_textfile(selector, host, port, list.append) - return list - -# Get a text file and pass each line to a function, with trailing CRLF stripped -def get_alt_textfile(selector, host, port, func): - f = send_request(selector, host, port) - while 1: - line = f.readline() - if not line: - print '(Unexpected EOF from server)' - break - if line[-2:] == CRLF: - line = line[:-2] - elif line[-1:] in CRLF: - line = line[:-1] - if line == '.': - break - if line[:2] == '..': - line = line[1:] - func(line) - f.close() - -# Get a binary file as one solid data block -def get_binary(selector, host, port): - f = send_request(selector, host, port) - data = f.read() - f.close() - return data - -# Get a binary file and pass each block to a function -def get_alt_binary(selector, host, port, func, blocksize): - f = send_request(selector, host, port) - while 1: - data = f.read(blocksize) - if not data: - break - func(data) - -# A *very* simple interactive browser - -# Browser main command, has default arguments -def browser(*args): - selector = DEF_SELECTOR - host = DEF_HOST - port = DEF_PORT - n = len(args) - if n > 0 and args[0]: - selector = args[0] - if n > 1 and args[1]: - host = args[1] - if n > 2 and args[2]: - port = args[2] - if n > 3: - raise RuntimeError, 'too many args' - try: - browse_menu(selector, host, port) - except socket.error, msg: - print 'Socket error:', msg - sys.exit(1) - except KeyboardInterrupt: - print '\n[Goodbye]' - -# Browse a menu -def browse_menu(selector, host, port): - list = get_menu(selector, host, port) - while 1: - print '----- MENU -----' - print 'Selector:', `selector` - print 'Host:', host, ' Port:', port - print - for i in range(len(list)): - item = list[i] - typechar, description = item[0], item[1] - print string.rjust(`i+1`, 3) + ':', description, - if typename.has_key(typechar): - print typename[typechar] - else: - print '' - print - while 1: - try: - str = raw_input('Choice [CR == up a level]: ') - except EOFError: - print - return - if not str: - return - try: - choice = string.atoi(str) - except string.atoi_error: - print 'Choice must be a number; try again:' - continue - if not 0 < choice <= len(list): - print 'Choice out of range; try again:' - continue - break - item = list[choice-1] - typechar = item[0] - [i_selector, i_host, i_port] = item[2:5] - if typebrowser.has_key(typechar): - browserfunc = typebrowser[typechar] - try: - browserfunc(i_selector, i_host, i_port) - except (IOError, socket.error): - print '***', sys.exc_type, ':', sys.exc_value - else: - print 'Unsupported object type' - -# Browse a text file -def browse_textfile(selector, host, port): - x = None - try: - p = os.popen('${PAGER-more}', 'w') - x = SaveLines(p) - get_alt_textfile(selector, host, port, x.writeln) - except IOError, msg: - print 'IOError:', msg - if x: - x.close() - f = open_savefile() - if not f: - return - x = SaveLines(f) - try: - get_alt_textfile(selector, host, port, x.writeln) - print 'Done.' - except IOError, msg: - print 'IOError:', msg - x.close() - -# Browse a search index -def browse_search(selector, host, port): - while 1: - print '----- SEARCH -----' - print 'Selector:', `selector` - print 'Host:', host, ' Port:', port - print - try: - query = raw_input('Query [CR == up a level]: ') - except EOFError: - print - break - query = string.strip(query) - if not query: - break - if '\t' in query: - print 'Sorry, queries cannot contain tabs' - continue - browse_menu(selector + TAB + query, host, port) - -# "Browse" telnet-based information, i.e. open a telnet session -def browse_telnet(selector, host, port): - if selector: - print 'Log in as', `selector` - if type(port) <> type(''): - port = `port` - sts = os.system('set -x; exec telnet ' + host + ' ' + port) - if sts: - print 'Exit status:', sts - -# "Browse" a binary file, i.e. save it to a file -def browse_binary(selector, host, port): - f = open_savefile() - if not f: - return - x = SaveWithProgress(f) - get_alt_binary(selector, host, port, x.write, 8*1024) - x.close() - -# "Browse" a sound file, i.e. play it or save it -def browse_sound(selector, host, port): - browse_binary(selector, host, port) - -# Dictionary mapping types to browser functions -typebrowser = {'0': browse_textfile, '1': browse_menu, \ - '4': browse_binary, '5': browse_binary, '6': browse_textfile, \ - '7': browse_search, \ - '8': browse_telnet, '9': browse_binary, 's': browse_sound} - -# Class used to save lines, appending a newline to each line -class SaveLines: - def __init__(self, f): - self.f = f - def writeln(self, line): - self.f.write(line + '\n') - def close(self): - sts = self.f.close() - if sts: - print 'Exit status:', sts - -# Class used to save data while showing progress -class SaveWithProgress: - def __init__(self, f): - self.f = f - def write(self, data): - sys.stdout.write('#') - sys.stdout.flush() - self.f.write(data) - def close(self): - print - sts = self.f.close() - if sts: - print 'Exit status:', sts - -# Ask for and open a save file, or return None if not to save -def open_savefile(): - try: - savefile = raw_input( \ - 'Save as file [CR == don\'t save; |pipeline or ~user/... OK]: ') - except EOFError: - print - return None - savefile = string.strip(savefile) - if not savefile: - return None - if savefile[0] == '|': - cmd = string.strip(savefile[1:]) - try: - p = os.popen(cmd, 'w') - except IOError, msg: - print `cmd`, ':', msg - return None - print 'Piping through', `cmd`, '...' - return p - if savefile[0] == '~': - savefile = os.path.expanduser(savefile) - try: - f = open(savefile, 'w') - except IOError, msg: - print `savefile`, ':', msg - return None - print 'Saving to', `savefile`, '...' - return f - -# Test program -def test(): - if sys.argv[4:]: - print 'usage: gopher [ [selector] host [port] ]' - sys.exit(2) - elif sys.argv[3:]: - browser(sys.argv[1], sys.argv[2], sys.argv[3]) - elif sys.argv[2:]: - try: - port = string.atoi(sys.argv[2]) - selector = '' - host = sys.argv[1] - except string.atoi_error: - selector = sys.argv[1] - host = sys.argv[2] - port = '' - browser(selector, host, port) - elif sys.argv[1:]: - browser('', sys.argv[1]) - else: - browser() - -# Call the test program as a main program -test() diff --git a/Demo/sockets/mcast.py b/Demo/sockets/mcast.py deleted file mode 100755 index cc7a7e07d4..0000000000 --- a/Demo/sockets/mcast.py +++ /dev/null @@ -1,94 +0,0 @@ -# Send/receive UDP multicast packets. -# Requires that your OS kernel supports IP multicast. -# This is built-in on SGI, still optional for most other vendors. -# -# Usage: -# mcast -s (sender) -# mcast -b (sender, using broadcast instead multicast) -# mcast (receivers) - -MYPORT = 8123 -MYGROUP = '225.0.0.250' - -import sys -import time -import struct -import regsub -from socket import * - - -# Main program -def main(): - flags = sys.argv[1:] - # - if flags: - sender(flags[0]) - else: - receiver() - - -# Sender subroutine (only one per local area network) -def sender(flag): - s = socket(AF_INET, SOCK_DGRAM) - if flag == '-b': - s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) - mygroup = '' - else: - mygroup = MYGROUP - ttl = struct.pack('b', 1) # Time-to-live - s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl) - while 1: - data = `time.time()` -## data = data + (1400 - len(data)) * '\0' - s.sendto(data, (mygroup, MYPORT)) - time.sleep(1) - - -# Receiver subroutine (as many as you like) -def receiver(): - # Open and initialize the socket - s = openmcastsock(MYGROUP, MYPORT) - # - # Loop, printing any data we receive - while 1: - data, sender = s.recvfrom(1500) - while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's - print sender, ':', `data` - - -# Open a UDP socket, bind it to a port and select a multicast group -def openmcastsock(group, port): - # Import modules used only here - import string - import struct - # - # Create a socket - s = socket(AF_INET, SOCK_DGRAM) - # - # Allow multiple copies of this program on one machine - # (not strictly needed) - s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) - # - # Bind it to the port - s.bind(('', port)) - # - # Look up multicast group address in name server - # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format) - group = gethostbyname(group) - # - # Construct binary group address - bytes = map(int, string.split(group, ".")) - grpaddr = 0 - for byte in bytes: grpaddr = (grpaddr << 8) | byte - # - # Construct struct mreq from grpaddr and ifaddr - ifaddr = INADDR_ANY - mreq = struct.pack('ll', htonl(grpaddr), htonl(ifaddr)) - # - # Add group membership - s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) - # - return s - - -main() diff --git a/Demo/sockets/radio.py b/Demo/sockets/radio.py deleted file mode 100755 index 6131d40053..0000000000 --- a/Demo/sockets/radio.py +++ /dev/null @@ -1,14 +0,0 @@ -# Receive UDP packets transmitted by a broadcasting service - -MYPORT = 50000 - -import sys -from socket import * - -s = socket(AF_INET, SOCK_DGRAM) -s.bind(('', MYPORT)) - -while 1: - data, wherefrom = s.recvfrom(1500, 0) - sys.stderr.write(`wherefrom` + '\n') - sys.stdout.write(data) diff --git a/Demo/sockets/rpython.py b/Demo/sockets/rpython.py deleted file mode 100755 index 77b2a7a516..0000000000 --- a/Demo/sockets/rpython.py +++ /dev/null @@ -1,35 +0,0 @@ -#! /usr/bin/env python - -# Remote python client. -# Execute Python commands remotely and send output back. - -import sys -import string -from socket import * - -PORT = 4127 -BUFSIZE = 1024 - -def main(): - if len(sys.argv) < 3: - print "usage: rpython host command" - sys.exit(2) - host = sys.argv[1] - port = PORT - i = string.find(host, ':') - if i >= 0: - port = string.atoi(port[i+1:]) - host = host[:i] - command = string.join(sys.argv[2:]) - s = socket(AF_INET, SOCK_STREAM) - s.connect((host, port)) - s.send(command) - s.shutdown(1) - reply = '' - while 1: - data = s.recv(BUFSIZE) - if not data: break - reply = reply + data - print reply, - -main() diff --git a/Demo/sockets/rpythond.py b/Demo/sockets/rpythond.py deleted file mode 100755 index 1109a99e18..0000000000 --- a/Demo/sockets/rpythond.py +++ /dev/null @@ -1,52 +0,0 @@ -#! /usr/bin/env python - -# Remote python server. -# Execute Python commands remotely and send output back. -# WARNING: This version has a gaping security hole -- it accepts requests -# from any host on the Internet! - -import sys -from socket import * -import StringIO -import traceback - -PORT = 4127 -BUFSIZE = 1024 - -def main(): - if len(sys.argv) > 1: - port = int(eval(sys.argv[1])) - else: - port = PORT - s = socket(AF_INET, SOCK_STREAM) - s.bind(('', port)) - s.listen(1) - while 1: - conn, (remotehost, remoteport) = s.accept() - print 'connected by', remotehost, remoteport - request = '' - while 1: - data = conn.recv(BUFSIZE) - if not data: - break - request = request + data - reply = execute(request) - conn.send(reply) - conn.close() - -def execute(request): - stdout = sys.stdout - stderr = sys.stderr - sys.stdout = sys.stderr = fakefile = StringIO.StringIO() - try: - try: - exec request in {}, {} - except: - print - traceback.print_exc(100) - finally: - sys.stderr = stderr - sys.stdout = stdout - return fakefile.getvalue() - -main() diff --git a/Demo/sockets/telnet.py b/Demo/sockets/telnet.py deleted file mode 100755 index ee7c43b874..0000000000 --- a/Demo/sockets/telnet.py +++ /dev/null @@ -1,109 +0,0 @@ -#! /usr/bin/env python - -# Minimal interface to the Internet telnet protocol. -# -# It refuses all telnet options and does not recognize any of the other -# telnet commands, but can still be used to connect in line-by-line mode. -# It's also useful to play with a number of other services, -# like time, finger, smtp and even ftp. -# -# Usage: telnet host [port] -# -# The port may be a service name or a decimal port number; -# it defaults to 'telnet'. - - -import sys, posix, time -from socket import * - -BUFSIZE = 1024 - -# Telnet protocol characters - -IAC = chr(255) # Interpret as command -DONT = chr(254) -DO = chr(253) -WONT = chr(252) -WILL = chr(251) - -def main(): - host = sys.argv[1] - try: - hostaddr = gethostbyname(host) - except error: - sys.stderr.write(sys.argv[1] + ': bad host name\n') - sys.exit(2) - # - if len(sys.argv) > 2: - servname = sys.argv[2] - else: - servname = 'telnet' - # - if '0' <= servname[:1] <= '9': - port = eval(servname) - else: - try: - port = getservbyname(servname, 'tcp') - except error: - sys.stderr.write(servname + ': bad tcp service name\n') - sys.exit(2) - # - s = socket(AF_INET, SOCK_STREAM) - # - try: - s.connect((host, port)) - except error, msg: - sys.stderr.write('connect failed: ' + `msg` + '\n') - sys.exit(1) - # - pid = posix.fork() - # - if pid == 0: - # child -- read stdin, write socket - while 1: - line = sys.stdin.readline() - s.send(line) - else: - # parent -- read socket, write stdout - iac = 0 # Interpret next char as command - opt = '' # Interpret next char as option - while 1: - data = s.recv(BUFSIZE) - if not data: - # EOF; kill child and exit - sys.stderr.write( '(Closed by remote host)\n') - posix.kill(pid, 9) - sys.exit(1) - cleandata = '' - for c in data: - if opt: - print ord(c) - s.send(opt + c) - opt = '' - elif iac: - iac = 0 - if c == IAC: - cleandata = cleandata + c - elif c in (DO, DONT): - if c == DO: print '(DO)', - else: print '(DONT)', - opt = IAC + WONT - elif c in (WILL, WONT): - if c == WILL: print '(WILL)', - else: print '(WONT)', - opt = IAC + DONT - else: - print '(command)', ord(c) - elif c == IAC: - iac = 1 - print '(IAC)', - else: - cleandata = cleandata + c - sys.stdout.write(cleandata) - sys.stdout.flush() - - -try: - main() -except KeyboardInterrupt: - pass diff --git a/Demo/sockets/throughput.py b/Demo/sockets/throughput.py deleted file mode 100755 index fa250e7755..0000000000 --- a/Demo/sockets/throughput.py +++ /dev/null @@ -1,93 +0,0 @@ -#! /usr/bin/env python - -# Test network throughput. -# -# Usage: -# 1) on host_A: throughput -s [port] # start a server -# 2) on host_B: throughput -c count host_A [port] # start a client -# -# The server will service multiple clients until it is killed. -# -# The client performs one transfer of count*BUFSIZE bytes and -# measures the time it takes (roundtrip!). - - -import sys, time -from socket import * - -MY_PORT = 50000 + 42 - -BUFSIZE = 1024 - - -def main(): - if len(sys.argv) < 2: - usage() - if sys.argv[1] == '-s': - server() - elif sys.argv[1] == '-c': - client() - else: - usage() - - -def usage(): - sys.stdout = sys.stderr - print 'Usage: (on host_A) throughput -s [port]' - print 'and then: (on host_B) throughput -c count host_A [port]' - sys.exit(2) - - -def server(): - if len(sys.argv) > 2: - port = eval(sys.argv[2]) - else: - port = MY_PORT - s = socket(AF_INET, SOCK_STREAM) - s.bind(('', port)) - s.listen(1) - print 'Server ready...' - while 1: - conn, (host, remoteport) = s.accept() - while 1: - data = conn.recv(BUFSIZE) - if not data: - break - del data - conn.send('OK\n') - conn.close() - print 'Done with', host, 'port', remoteport - - -def client(): - if len(sys.argv) < 4: - usage() - count = int(eval(sys.argv[2])) - host = sys.argv[3] - if len(sys.argv) > 4: - port = eval(sys.argv[4]) - else: - port = MY_PORT - testdata = 'x' * (BUFSIZE-1) + '\n' - t1 = time.time() - s = socket(AF_INET, SOCK_STREAM) - t2 = time.time() - s.connect((host, port)) - t3 = time.time() - i = 0 - while i < count: - i = i+1 - s.send(testdata) - s.shutdown(1) # Send EOF - t4 = time.time() - data = s.recv(BUFSIZE) - t5 = time.time() - print data - print 'Raw timers:', t1, t2, t3, t4, t5 - print 'Intervals:', t2-t1, t3-t2, t4-t3, t5-t4 - print 'Total:', t5-t1 - print 'Throughput:', round((BUFSIZE*count*0.001) / (t5-t1), 3), - print 'K/sec.' - - -main() diff --git a/Demo/sockets/udpecho.py b/Demo/sockets/udpecho.py deleted file mode 100755 index 4410165e3a..0000000000 --- a/Demo/sockets/udpecho.py +++ /dev/null @@ -1,63 +0,0 @@ -#! /usr/bin/env python - -# Client and server for udp (datagram) echo. -# -# Usage: udpecho -s [port] (to start a server) -# or: udpecho -c host [port] 2: - port = eval(sys.argv[2]) - else: - port = ECHO_PORT - s = socket(AF_INET, SOCK_DGRAM) - s.bind(('', port)) - print 'udp echo server ready' - while 1: - data, addr = s.recvfrom(BUFSIZE) - print 'server received', `data`, 'from', `addr` - s.sendto(data, addr) - -def client(): - if len(sys.argv) < 3: - usage() - host = sys.argv[2] - if len(sys.argv) > 3: - port = eval(sys.argv[3]) - else: - port = ECHO_PORT - addr = host, port - s = socket(AF_INET, SOCK_DGRAM) - s.bind(('', 0)) - print 'udp echo client ready, reading stdin' - while 1: - line = sys.stdin.readline() - if not line: - break - s.sendto(line, addr) - data, fromaddr = s.recvfrom(BUFSIZE) - print 'client received', `data`, 'from', `fromaddr` - -main() diff --git a/Demo/sockets/unicast.py b/Demo/sockets/unicast.py deleted file mode 100644 index 1e9caebd2a..0000000000 --- a/Demo/sockets/unicast.py +++ /dev/null @@ -1,16 +0,0 @@ -# Send UDP broadcast packets - -MYPORT = 50000 - -import sys, time -from socket import * - -s = socket(AF_INET, SOCK_DGRAM) -s.bind(('', 0)) - -while 1: - data = `time.time()` + '\n' - s.sendto(data, ('', MYPORT)) - time.sleep(2) - - diff --git a/Demo/sockets/unixclient.py b/Demo/sockets/unixclient.py deleted file mode 100644 index a0d80f6083..0000000000 --- a/Demo/sockets/unixclient.py +++ /dev/null @@ -1,10 +0,0 @@ -# Echo client demo using Unix sockets -# Piet van Oostrum -from socket import * -FILE = 'blabla' -s = socket(AF_UNIX, SOCK_STREAM) -s.connect(FILE) -s.send('Hello, world') -data = s.recv(1024) -s.close() -print 'Received', `data` diff --git a/Demo/sockets/unixserver.py b/Demo/sockets/unixserver.py deleted file mode 100644 index d4c706188f..0000000000 --- a/Demo/sockets/unixserver.py +++ /dev/null @@ -1,15 +0,0 @@ -# Echo server demo using Unix sockets (handles one connection only) -# Piet van Oostrum -from socket import * -FILE = 'blabla' -s = socket(AF_UNIX, SOCK_STREAM) -s.bind(FILE) -print 'Sock name is: ['+s.getsockname()+']' -s.listen(1) -conn, addr = s.accept() -print 'Connected by', addr -while 1: - data = conn.recv(1024) - if not data: break - conn.send(data) -conn.close() diff --git a/Demo/threads/Coroutine.py b/Demo/threads/Coroutine.py deleted file mode 100644 index 0cf9255362..0000000000 --- a/Demo/threads/Coroutine.py +++ /dev/null @@ -1,160 +0,0 @@ -# Coroutine implementation using Python threads. -# -# Combines ideas from Guido's Generator module, and from the coroutine -# features of Icon and Simula 67. -# -# To run a collection of functions as coroutines, you need to create -# a Coroutine object to control them: -# co = Coroutine() -# and then 'create' a subsidiary object for each function in the -# collection: -# cof1 = co.create(f1 [, arg1, arg2, ...]) # [] means optional, -# cof2 = co.create(f2 [, arg1, arg2, ...]) #... not list -# cof3 = co.create(f3 [, arg1, arg2, ...]) -# etc. The functions need not be distinct; 'create'ing the same -# function multiple times gives you independent instances of the -# function. -# -# To start the coroutines running, use co.tran on one of the create'd -# functions; e.g., co.tran(cof2). The routine that first executes -# co.tran is called the "main coroutine". It's special in several -# respects: it existed before you created the Coroutine object; if any of -# the create'd coroutines exits (does a return, or suffers an unhandled -# exception), EarlyExit error is raised in the main coroutine; and the -# co.detach() method transfers control directly to the main coroutine -# (you can't use co.tran() for this because the main coroutine doesn't -# have a name ...). -# -# Coroutine objects support these methods: -# -# handle = .create(func [, arg1, arg2, ...]) -# Creates a coroutine for an invocation of func(arg1, arg2, ...), -# and returns a handle ("name") for the coroutine so created. The -# handle can be used as the target in a subsequent .tran(). -# -# .tran(target, data=None) -# Transfer control to the create'd coroutine "target", optionally -# passing it an arbitrary piece of data. To the coroutine A that does -# the .tran, .tran acts like an ordinary function call: another -# coroutine B can .tran back to it later, and if it does A's .tran -# returns the 'data' argument passed to B's tran. E.g., -# -# in coroutine coA in coroutine coC in coroutine coB -# x = co.tran(coC) co.tran(coB) co.tran(coA,12) -# print x # 12 -# -# The data-passing feature is taken from Icon, and greatly cuts -# the need to use global variables for inter-coroutine communication. -# -# .back( data=None ) -# The same as .tran(invoker, data=None), where 'invoker' is the -# coroutine that most recently .tran'ed control to the coroutine -# doing the .back. This is akin to Icon's "&source". -# -# .detach( data=None ) -# The same as .tran(main, data=None), where 'main' is the -# (unnameable!) coroutine that started it all. 'main' has all the -# rights of any other coroutine: upon receiving control, it can -# .tran to an arbitrary coroutine of its choosing, go .back to -# the .detach'er, or .kill the whole thing. -# -# .kill() -# Destroy all the coroutines, and return control to the main -# coroutine. None of the create'ed coroutines can be resumed after a -# .kill(). An EarlyExit exception does a .kill() automatically. It's -# a good idea to .kill() coroutines you're done with, since the -# current implementation consumes a thread for each coroutine that -# may be resumed. - -import thread -import sync - -class _CoEvent: - def __init__(self, func): - self.f = func - self.e = sync.event() - - def __repr__(self): - if self.f is None: - return 'main coroutine' - else: - return 'coroutine for func ' + self.f.func_name - - def __hash__(self): - return id(self) - - def __cmp__(x,y): - return cmp(id(x), id(y)) - - def resume(self): - self.e.post() - - def wait(self): - self.e.wait() - self.e.clear() - -Killed = 'Coroutine.Killed' -EarlyExit = 'Coroutine.EarlyExit' - -class Coroutine: - def __init__(self): - self.active = self.main = _CoEvent(None) - self.invokedby = {self.main: None} - self.killed = 0 - self.value = None - self.terminated_by = None - - def create(self, func, *args): - me = _CoEvent(func) - self.invokedby[me] = None - thread.start_new_thread(self._start, (me,) + args) - return me - - def _start(self, me, *args): - me.wait() - if not self.killed: - try: - try: - apply(me.f, args) - except Killed: - pass - finally: - if not self.killed: - self.terminated_by = me - self.kill() - - def kill(self): - if self.killed: - raise TypeError, 'kill() called on dead coroutines' - self.killed = 1 - for coroutine in self.invokedby.keys(): - coroutine.resume() - - def back(self, data=None): - return self.tran( self.invokedby[self.active], data ) - - def detach(self, data=None): - return self.tran( self.main, data ) - - def tran(self, target, data=None): - if not self.invokedby.has_key(target): - raise TypeError, '.tran target ' + `target` + \ - ' is not an active coroutine' - if self.killed: - raise TypeError, '.tran target ' + `target` + ' is killed' - self.value = data - me = self.active - self.invokedby[target] = me - self.active = target - target.resume() - - me.wait() - if self.killed: - if self.main is not me: - raise Killed - if self.terminated_by is not None: - raise EarlyExit, `self.terminated_by` + ' terminated early' - - return self.value - -# end of module diff --git a/Demo/threads/Generator.py b/Demo/threads/Generator.py deleted file mode 100644 index fbba06ad0b..0000000000 --- a/Demo/threads/Generator.py +++ /dev/null @@ -1,84 +0,0 @@ -# Generator implementation using threads - -import thread - -Killed = 'Generator.Killed' - -class Generator: - # Constructor - def __init__(self, func, args): - self.getlock = thread.allocate_lock() - self.putlock = thread.allocate_lock() - self.getlock.acquire() - self.putlock.acquire() - self.func = func - self.args = args - self.done = 0 - self.killed = 0 - thread.start_new_thread(self._start, ()) - # Internal routine - def _start(self): - try: - self.putlock.acquire() - if not self.killed: - try: - apply(self.func, (self,) + self.args) - except Killed: - pass - finally: - if not self.killed: - self.done = 1 - self.getlock.release() - # Called by producer for each value; raise Killed if no more needed - def put(self, value): - if self.killed: - raise TypeError, 'put() called on killed generator' - self.value = value - self.getlock.release() # Resume consumer thread - self.putlock.acquire() # Wait for next get() call - if self.killed: - raise Killed - # Called by producer to get next value; raise EOFError if no more - def get(self): - if self.killed: - raise TypeError, 'get() called on killed generator' - self.putlock.release() # Resume producer thread - self.getlock.acquire() # Wait for value to appear - if self.done: - raise EOFError # Say there are no more values - return self.value - # Called by consumer if no more values wanted - def kill(self): - if self.killed: - raise TypeError, 'kill() called on killed generator' - self.killed = 1 - self.putlock.release() - # Clone constructor - def clone(self): - return Generator(self.func, self.args) - -def pi(g): - k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L - while 1: - # Next approximation - p, q, k = k*k, 2L*k+1L, k+1L - a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 - # Print common digits - d, d1 = a/b, a1/b1 - while d == d1: - g.put(int(d)) - a, a1 = 10L*(a%b), 10L*(a1%b1) - d, d1 = a/b, a1/b1 - -def test(): - g = Generator(pi, ()) - g.kill() - g = Generator(pi, ()) - for i in range(10): print g.get(), - print - h = g.clone() - g.kill() - while 1: - print h.get(), - -test() diff --git a/Demo/threads/README b/Demo/threads/README deleted file mode 100644 index fe27818cc5..0000000000 --- a/Demo/threads/README +++ /dev/null @@ -1,14 +0,0 @@ -This directory contains some demonstrations of the thread module. - -These are mostly "proof of concept" type applications: - -Generator.py Generator class implemented with threads. -bug.py Demonstrate a bug with importing modules in threads. -find.py Parallelized "find(1)" (looks for directories). -sync.py Condition variables primitives by Tim Peters. -telnet.py Version of ../sockets/telnet.py using threads. -wpi.py Version of ../scripts/pi.py using threads (needs stdwin). - -Coroutine.py Coroutines using threads, by Tim Peters (22 May 94) -fcmp.py Example of above, by Tim -squasher.py Another example of above, also by Tim diff --git a/Demo/threads/bug.py b/Demo/threads/bug.py deleted file mode 100644 index 6c5edac4bf..0000000000 --- a/Demo/threads/bug.py +++ /dev/null @@ -1,69 +0,0 @@ -# The following self-contained little program usually freezes with most -# threads reporting -# -# Unhandled exception in thread: -# Traceback (innermost last): -# File "importbug.py", line 6 -# x = whrandom.randint(1,3) -# AttributeError: randint -# -# Here's the program; it doesn't use anything from the attached module: - -import thread - -def task(): - global N - import whrandom - x = whrandom.randint(1,3) - a.acquire() - N = N - 1 - if N == 0: done.release() - a.release() - -a = thread.allocate_lock() -done = thread.allocate_lock() -N = 10 - -done.acquire() -for i in range(N): - thread.start_new_thread(task, ()) -done.acquire() -print 'done' - - -# Sticking an acquire/release pair around the 'import' statement makes the -# problem go away. -# -# I believe that what happens is: -# -# 1) The first thread to hit the import atomically reaches, and executes -# most of, get_module. In particular, it finds Lib/whrandom.pyc, -# installs its name in sys.modules, and executes -# -# v = eval_code(co, d, d, d, (object *)NULL); -# -# to initialize the module. -# -# 2) eval_code "ticker"-slices the 1st thread out, and gives another thread -# a chance. When this 2nd thread hits the same 'import', import_module -# finds 'whrandom' in sys.modules, so just proceeds. -# -# 3) But the 1st thread is still "in the middle" of executing whrandom.pyc. -# So the 2nd thread has a good chance of trying to look up 'randint' -# before the 1st thread has placed it in whrandom's dict. -# -# 4) The more threads there are, the more likely that at least one of them -# will do this before the 1st thread finishes the import work. -# -# If that's right, a perhaps not-too-bad workaround would be to introduce a -# static "you can't interrupt this thread" flag in ceval.c, check it before -# giving up interpreter_lock, and have IMPORT_NAME set it & restore (plain -# clearing would not work) it around its call to import_module. To its -# credit, there's something wonderfully perverse about fixing a race via an -# unprotected static . -# -# as-with-most-other-things-(pseudo-)parallel-programming's-more-fun- -# in-python-too!-ly y'rs - tim -# -# Tim Peters tim@ksr.com -# not speaking for Kendall Square Research Corp diff --git a/Demo/threads/fcmp.py b/Demo/threads/fcmp.py deleted file mode 100644 index 83ebe01103..0000000000 --- a/Demo/threads/fcmp.py +++ /dev/null @@ -1,64 +0,0 @@ -# Coroutine example: controlling multiple instances of a single function - -from Coroutine import * - -# fringe visits a nested list in inorder, and detaches for each non-list -# element; raises EarlyExit after the list is exhausted -def fringe( co, list ): - for x in list: - if type(x) is type([]): - fringe(co, x) - else: - co.back(x) - -def printinorder( list ): - co = Coroutine() - f = co.create(fringe, co, list) - try: - while 1: - print co.tran(f), - except EarlyExit: - pass - print - -printinorder([1,2,3]) # 1 2 3 -printinorder([[[[1,[2]]],3]]) # ditto -x = [0, 1, [2, [3]], [4,5], [[[6]]] ] -printinorder(x) # 0 1 2 3 4 5 6 - -# fcmp lexicographically compares the fringes of two nested lists -def fcmp( l1, l2 ): - co1 = Coroutine(); f1 = co1.create(fringe, co1, l1) - co2 = Coroutine(); f2 = co2.create(fringe, co2, l2) - while 1: - try: - v1 = co1.tran(f1) - except EarlyExit: - try: - v2 = co2.tran(f2) - except EarlyExit: - return 0 - co2.kill() - return -1 - try: - v2 = co2.tran(f2) - except EarlyExit: - co1.kill() - return 1 - if v1 != v2: - co1.kill(); co2.kill() - return cmp(v1,v2) - -print fcmp(range(7), x) # 0; fringes are equal -print fcmp(range(6), x) # -1; 1st list ends early -print fcmp(x, range(6)) # 1; 2nd list ends early -print fcmp(range(8), x) # 1; 2nd list ends early -print fcmp(x, range(8)) # -1; 1st list ends early -print fcmp([1,[[2],8]], - [[[1],2],8]) # 0 -print fcmp([1,[[3],8]], - [[[1],2],8]) # 1 -print fcmp([1,[[2],8]], - [[[1],2],9]) # -1 - -# end of example diff --git a/Demo/threads/find.py b/Demo/threads/find.py deleted file mode 100644 index 11fb65aada..0000000000 --- a/Demo/threads/find.py +++ /dev/null @@ -1,154 +0,0 @@ -# A parallelized "find(1)" using the thread module. - -# This demonstrates the use of a work queue and worker threads. -# It really does do more stats/sec when using multiple threads, -# although the improvement is only about 20-30 percent. - -# I'm too lazy to write a command line parser for the full find(1) -# command line syntax, so the predicate it searches for is wired-in, -# see function selector() below. (It currently searches for files with -# group or world write permission.) - -# Usage: parfind.py [-w nworkers] [directory] ... -# Default nworkers is 4, maximum appears to be 8 (on Irix 4.0.2) - - -import sys -import getopt -import string -import time -import os -from stat import * -import thread - - -# Work queue class. Usage: -# wq = WorkQ() -# wq.addwork(func, (arg1, arg2, ...)) # one or more calls -# wq.run(nworkers) -# The work is done when wq.run() completes. -# The function calls executed by the workers may add more work. -# Don't use keyboard interrupts! - -class WorkQ: - - # Invariants: - - # - busy and work are only modified when mutex is locked - # - len(work) is the number of jobs ready to be taken - # - busy is the number of jobs being done - # - todo is locked iff there is no work and somebody is busy - - def __init__(self): - self.mutex = thread.allocate() - self.todo = thread.allocate() - self.todo.acquire() - self.work = [] - self.busy = 0 - - def addwork(self, func, args): - job = (func, args) - self.mutex.acquire() - self.work.append(job) - self.mutex.release() - if len(self.work) == 1: - self.todo.release() - - def _getwork(self): - self.todo.acquire() - self.mutex.acquire() - if self.busy == 0 and len(self.work) == 0: - self.mutex.release() - self.todo.release() - return None - job = self.work[0] - del self.work[0] - self.busy = self.busy + 1 - self.mutex.release() - if len(self.work) > 0: - self.todo.release() - return job - - def _donework(self): - self.mutex.acquire() - self.busy = self.busy - 1 - if self.busy == 0 and len(self.work) == 0: - self.todo.release() - self.mutex.release() - - def _worker(self): - time.sleep(0.00001) # Let other threads run - while 1: - job = self._getwork() - if not job: - break - func, args = job - apply(func, args) - self._donework() - - def run(self, nworkers): - if not self.work: - return # Nothing to do - for i in range(nworkers-1): - thread.start_new(self._worker, ()) - self._worker() - self.todo.acquire() - - -# Main program - -def main(): - sys.argv.append("/tmp") - nworkers = 4 - opts, args = getopt.getopt(sys.argv[1:], '-w:') - for opt, arg in opts: - if opt == '-w': - nworkers = string.atoi(arg) - if not args: - args = [os.curdir] - - wq = WorkQ() - for dir in args: - wq.addwork(find, (dir, selector, wq)) - - t1 = time.time() - wq.run(nworkers) - t2 = time.time() - - sys.stderr.write('Total time ' + `t2-t1` + ' sec.\n') - - -# The predicate -- defines what files we look for. -# Feel free to change this to suit your purpose - -def selector(dir, name, fullname, stat): - # Look for group or world writable files - return (stat[ST_MODE] & 0022) != 0 - - -# The find procedure -- calls wq.addwork() for subdirectories - -def find(dir, pred, wq): - try: - names = os.listdir(dir) - except os.error, msg: - print `dir`, ':', msg - return - for name in names: - if name not in (os.curdir, os.pardir): - fullname = os.path.join(dir, name) - try: - stat = os.lstat(fullname) - except os.error, msg: - print `fullname`, ':', msg - continue - if pred(dir, name, fullname, stat): - print fullname - if S_ISDIR(stat[ST_MODE]): - if not os.path.ismount(fullname): - wq.addwork(find, (fullname, pred, wq)) - - -# Call the main program - -main() diff --git a/Demo/threads/squasher.py b/Demo/threads/squasher.py deleted file mode 100644 index 0d59cb839b..0000000000 --- a/Demo/threads/squasher.py +++ /dev/null @@ -1,105 +0,0 @@ -# Coroutine example: general coroutine transfers -# -# The program is a variation of a Simula 67 program due to Dahl & Hoare, -# (Dahl/Dijkstra/Hoare, Structured Programming; Academic Press, 1972) -# who in turn credit the original example to Conway. -# -# We have a number of input lines, terminated by a 0 byte. The problem -# is to squash them together into output lines containing 72 characters -# each. A semicolon must be added between input lines. Runs of blanks -# and tabs in input lines must be squashed into single blanks. -# Occurrences of "**" in input lines must be replaced by "^". -# -# Here's a test case: - -test = """\ - d = sqrt(b**2 - 4*a*c) -twoa = 2*a - L = -b/twoa - R = d/twoa - A1 = L + R - A2 = L - R\0 -""" - -# The program should print: - -# d = sqrt(b^2 - 4*a*c);twoa = 2*a; L = -b/twoa; R = d/twoa; A1 = L + R; -#A2 = L - R -#done - -# getline: delivers the next input line to its invoker -# disassembler: grabs input lines from getline, and delivers them one -# character at a time to squasher, also inserting a semicolon into -# the stream between lines -# squasher: grabs characters from disassembler and passes them on to -# assembler, first replacing "**" with "^" and squashing runs of -# whitespace -# assembler: grabs characters from squasher and packs them into lines -# with 72 character each, delivering each such line to putline; -# when it sees a null byte, passes the last line to putline and -# then kills all the coroutines -# putline: grabs lines from assembler, and just prints them - -from Coroutine import * - -def getline(text): - for line in string.splitfields(text, '\n'): - co.tran(codisassembler, line) - -def disassembler(): - while 1: - card = co.tran(cogetline) - for i in range(len(card)): - co.tran(cosquasher, card[i]) - co.tran(cosquasher, ';') - -def squasher(): - while 1: - ch = co.tran(codisassembler) - if ch == '*': - ch2 = co.tran(codisassembler) - if ch2 == '*': - ch = '^' - else: - co.tran(coassembler, ch) - ch = ch2 - if ch in ' \t': - while 1: - ch2 = co.tran(codisassembler) - if ch2 not in ' \t': - break - co.tran(coassembler, ' ') - ch = ch2 - co.tran(coassembler, ch) - -def assembler(): - line = '' - while 1: - ch = co.tran(cosquasher) - if ch == '\0': - break - if len(line) == 72: - co.tran(coputline, line) - line = '' - line = line + ch - line = line + ' ' * (72 - len(line)) - co.tran(coputline, line) - co.kill() - -def putline(): - while 1: - line = co.tran(coassembler) - print line - -import string -co = Coroutine() -cogetline = co.create(getline, test) -coputline = co.create(putline) -coassembler = co.create(assembler) -codisassembler = co.create(disassembler) -cosquasher = co.create(squasher) - -co.tran(coputline) -print 'done' - -# end of example diff --git a/Demo/threads/sync.py b/Demo/threads/sync.py deleted file mode 100644 index a8556c48ef..0000000000 --- a/Demo/threads/sync.py +++ /dev/null @@ -1,603 +0,0 @@ -# Defines classes that provide synchronization objects. Note that use of -# this module requires that your Python support threads. -# -# condition(lock=None) # a POSIX-like condition-variable object -# barrier(n) # an n-thread barrier -# event() # an event object -# semaphore(n=1) # a semaphore object, with initial count n -# mrsw() # a multiple-reader single-writer lock -# -# CONDITIONS -# -# A condition object is created via -# import this_module -# your_condition_object = this_module.condition(lock=None) -# -# As explained below, a condition object has a lock associated with it, -# used in the protocol to protect condition data. You can specify a -# lock to use in the constructor, else the constructor will allocate -# an anonymous lock for you. Specifying a lock explicitly can be useful -# when more than one condition keys off the same set of shared data. -# -# Methods: -# .acquire() -# acquire the lock associated with the condition -# .release() -# release the lock associated with the condition -# .wait() -# block the thread until such time as some other thread does a -# .signal or .broadcast on the same condition, and release the -# lock associated with the condition. The lock associated with -# the condition MUST be in the acquired state at the time -# .wait is invoked. -# .signal() -# wake up exactly one thread (if any) that previously did a .wait -# on the condition; that thread will awaken with the lock associated -# with the condition in the acquired state. If no threads are -# .wait'ing, this is a nop. If more than one thread is .wait'ing on -# the condition, any of them may be awakened. -# .broadcast() -# wake up all threads (if any) that are .wait'ing on the condition; -# the threads are woken up serially, each with the lock in the -# acquired state, so should .release() as soon as possible. If no -# threads are .wait'ing, this is a nop. -# -# Note that if a thread does a .wait *while* a signal/broadcast is -# in progress, it's guaranteeed to block until a subsequent -# signal/broadcast. -# -# Secret feature: `broadcast' actually takes an integer argument, -# and will wake up exactly that many waiting threads (or the total -# number waiting, if that's less). Use of this is dubious, though, -# and probably won't be supported if this form of condition is -# reimplemented in C. -# -# DIFFERENCES FROM POSIX -# -# + A separate mutex is not needed to guard condition data. Instead, a -# condition object can (must) be .acquire'ed and .release'ed directly. -# This eliminates a common error in using POSIX conditions. -# -# + Because of implementation difficulties, a POSIX `signal' wakes up -# _at least_ one .wait'ing thread. Race conditions make it difficult -# to stop that. This implementation guarantees to wake up only one, -# but you probably shouldn't rely on that. -# -# PROTOCOL -# -# Condition objects are used to block threads until "some condition" is -# true. E.g., a thread may wish to wait until a producer pumps out data -# for it to consume, or a server may wish to wait until someone requests -# its services, or perhaps a whole bunch of threads want to wait until a -# preceding pass over the data is complete. Early models for conditions -# relied on some other thread figuring out when a blocked thread's -# condition was true, and made the other thread responsible both for -# waking up the blocked thread and guaranteeing that it woke up with all -# data in a correct state. This proved to be very delicate in practice, -# and gave conditions a bad name in some circles. -# -# The POSIX model addresses these problems by making a thread responsible -# for ensuring that its own state is correct when it wakes, and relies -# on a rigid protocol to make this easy; so long as you stick to the -# protocol, POSIX conditions are easy to "get right": -# -# A) The thread that's waiting for some arbitrarily-complex condition -# (ACC) to become true does: -# -# condition.acquire() -# while not (code to evaluate the ACC): -# condition.wait() -# # That blocks the thread, *and* releases the lock. When a -# # condition.signal() happens, it will wake up some thread that -# # did a .wait, *and* acquire the lock again before .wait -# # returns. -# # -# # Because the lock is acquired at this point, the state used -# # in evaluating the ACC is frozen, so it's safe to go back & -# # reevaluate the ACC. -# -# # At this point, ACC is true, and the thread has the condition -# # locked. -# # So code here can safely muck with the shared state that -# # went into evaluating the ACC -- if it wants to. -# # When done mucking with the shared state, do -# condition.release() -# -# B) Threads that are mucking with shared state that may affect the -# ACC do: -# -# condition.acquire() -# # muck with shared state -# condition.release() -# if it's possible that ACC is true now: -# condition.signal() # or .broadcast() -# -# Note: You may prefer to put the "if" clause before the release(). -# That's fine, but do note that anyone waiting on the signal will -# stay blocked until the release() is done (since acquiring the -# condition is part of what .wait() does before it returns). -# -# TRICK OF THE TRADE -# -# With simpler forms of conditions, it can be impossible to know when -# a thread that's supposed to do a .wait has actually done it. But -# because this form of condition releases a lock as _part_ of doing a -# wait, the state of that lock can be used to guarantee it. -# -# E.g., suppose thread A spawns thread B and later wants to wait for B to -# complete: -# -# In A: In B: -# -# B_done = condition() ... do work ... -# B_done.acquire() B_done.acquire(); B_done.release() -# spawn B B_done.signal() -# ... some time later ... ... and B exits ... -# B_done.wait() -# -# Because B_done was in the acquire'd state at the time B was spawned, -# B's attempt to acquire B_done can't succeed until A has done its -# B_done.wait() (which releases B_done). So B's B_done.signal() is -# guaranteed to be seen by the .wait(). Without the lock trick, B -# may signal before A .waits, and then A would wait forever. -# -# BARRIERS -# -# A barrier object is created via -# import this_module -# your_barrier = this_module.barrier(num_threads) -# -# Methods: -# .enter() -# the thread blocks until num_threads threads in all have done -# .enter(). Then the num_threads threads that .enter'ed resume, -# and the barrier resets to capture the next num_threads threads -# that .enter it. -# -# EVENTS -# -# An event object is created via -# import this_module -# your_event = this_module.event() -# -# An event has two states, `posted' and `cleared'. An event is -# created in the cleared state. -# -# Methods: -# -# .post() -# Put the event in the posted state, and resume all threads -# .wait'ing on the event (if any). -# -# .clear() -# Put the event in the cleared state. -# -# .is_posted() -# Returns 0 if the event is in the cleared state, or 1 if the event -# is in the posted state. -# -# .wait() -# If the event is in the posted state, returns immediately. -# If the event is in the cleared state, blocks the calling thread -# until the event is .post'ed by another thread. -# -# Note that an event, once posted, remains posted until explicitly -# cleared. Relative to conditions, this is both the strength & weakness -# of events. It's a strength because the .post'ing thread doesn't have to -# worry about whether the threads it's trying to communicate with have -# already done a .wait (a condition .signal is seen only by threads that -# do a .wait _prior_ to the .signal; a .signal does not persist). But -# it's a weakness because .clear'ing an event is error-prone: it's easy -# to mistakenly .clear an event before all the threads you intended to -# see the event get around to .wait'ing on it. But so long as you don't -# need to .clear an event, events are easy to use safely. -# -# SEMAPHORES -# -# A semaphore object is created via -# import this_module -# your_semaphore = this_module.semaphore(count=1) -# -# A semaphore has an integer count associated with it. The initial value -# of the count is specified by the optional argument (which defaults to -# 1) passed to the semaphore constructor. -# -# Methods: -# -# .p() -# If the semaphore's count is greater than 0, decrements the count -# by 1 and returns. -# Else if the semaphore's count is 0, blocks the calling thread -# until a subsequent .v() increases the count. When that happens, -# the count will be decremented by 1 and the calling thread resumed. -# -# .v() -# Increments the semaphore's count by 1, and wakes up a thread (if -# any) blocked by a .p(). It's an (detected) error for a .v() to -# increase the semaphore's count to a value larger than the initial -# count. -# -# MULTIPLE-READER SINGLE-WRITER LOCKS -# -# A mrsw lock is created via -# import this_module -# your_mrsw_lock = this_module.mrsw() -# -# This kind of lock is often useful with complex shared data structures. -# The object lets any number of "readers" proceed, so long as no thread -# wishes to "write". When a (one or more) thread declares its intention -# to "write" (e.g., to update a shared structure), all current readers -# are allowed to finish, and then a writer gets exclusive access; all -# other readers & writers are blocked until the current writer completes. -# Finally, if some thread is waiting to write and another is waiting to -# read, the writer takes precedence. -# -# Methods: -# -# .read_in() -# If no thread is writing or waiting to write, returns immediately. -# Else blocks until no thread is writing or waiting to write. So -# long as some thread has completed a .read_in but not a .read_out, -# writers are blocked. -# -# .read_out() -# Use sometime after a .read_in to declare that the thread is done -# reading. When all threads complete reading, a writer can proceed. -# -# .write_in() -# If no thread is writing (has completed a .write_in, but hasn't yet -# done a .write_out) or reading (similarly), returns immediately. -# Else blocks the calling thread, and threads waiting to read, until -# the current writer completes writing or all the current readers -# complete reading; if then more than one thread is waiting to -# write, one of them is allowed to proceed, but which one is not -# specified. -# -# .write_out() -# Use sometime after a .write_in to declare that the thread is done -# writing. Then if some other thread is waiting to write, it's -# allowed to proceed. Else all threads (if any) waiting to read are -# allowed to proceed. -# -# .write_to_read() -# Use instead of a .write_in to declare that the thread is done -# writing but wants to continue reading without other writers -# intervening. If there are other threads waiting to write, they -# are allowed to proceed only if the current thread calls -# .read_out; threads waiting to read are only allowed to proceed -# if there are are no threads waiting to write. (This is a -# weakness of the interface!) - -import thread - -class condition: - def __init__(self, lock=None): - # the lock actually used by .acquire() and .release() - if lock is None: - self.mutex = thread.allocate_lock() - else: - if hasattr(lock, 'acquire') and \ - hasattr(lock, 'release'): - self.mutex = lock - else: - raise TypeError, 'condition constructor requires ' \ - 'a lock argument' - - # lock used to block threads until a signal - self.checkout = thread.allocate_lock() - self.checkout.acquire() - - # internal critical-section lock, & the data it protects - self.idlock = thread.allocate_lock() - self.id = 0 - self.waiting = 0 # num waiters subject to current release - self.pending = 0 # num waiters awaiting next signal - self.torelease = 0 # num waiters to release - self.releasing = 0 # 1 iff release is in progress - - def acquire(self): - self.mutex.acquire() - - def release(self): - self.mutex.release() - - def wait(self): - mutex, checkout, idlock = self.mutex, self.checkout, self.idlock - if not mutex.locked(): - raise ValueError, \ - "condition must be .acquire'd when .wait() invoked" - - idlock.acquire() - myid = self.id - self.pending = self.pending + 1 - idlock.release() - - mutex.release() - - while 1: - checkout.acquire(); idlock.acquire() - if myid < self.id: - break - checkout.release(); idlock.release() - - self.waiting = self.waiting - 1 - self.torelease = self.torelease - 1 - if self.torelease: - checkout.release() - else: - self.releasing = 0 - if self.waiting == self.pending == 0: - self.id = 0 - idlock.release() - mutex.acquire() - - def signal(self): - self.broadcast(1) - - def broadcast(self, num = -1): - if num < -1: - raise ValueError, '.broadcast called with num ' + `num` - if num == 0: - return - self.idlock.acquire() - if self.pending: - self.waiting = self.waiting + self.pending - self.pending = 0 - self.id = self.id + 1 - if num == -1: - self.torelease = self.waiting - else: - self.torelease = min( self.waiting, - self.torelease + num ) - if self.torelease and not self.releasing: - self.releasing = 1 - self.checkout.release() - self.idlock.release() - -class barrier: - def __init__(self, n): - self.n = n - self.togo = n - self.full = condition() - - def enter(self): - full = self.full - full.acquire() - self.togo = self.togo - 1 - if self.togo: - full.wait() - else: - self.togo = self.n - full.broadcast() - full.release() - -class event: - def __init__(self): - self.state = 0 - self.posted = condition() - - def post(self): - self.posted.acquire() - self.state = 1 - self.posted.broadcast() - self.posted.release() - - def clear(self): - self.posted.acquire() - self.state = 0 - self.posted.release() - - def is_posted(self): - self.posted.acquire() - answer = self.state - self.posted.release() - return answer - - def wait(self): - self.posted.acquire() - if not self.state: - self.posted.wait() - self.posted.release() - -class semaphore: - def __init__(self, count=1): - if count <= 0: - raise ValueError, 'semaphore count %d; must be >= 1' % count - self.count = count - self.maxcount = count - self.nonzero = condition() - - def p(self): - self.nonzero.acquire() - while self.count == 0: - self.nonzero.wait() - self.count = self.count - 1 - self.nonzero.release() - - def v(self): - self.nonzero.acquire() - if self.count == self.maxcount: - raise ValueError, '.v() tried to raise semaphore count above ' \ - 'initial value ' + `maxcount` - self.count = self.count + 1 - self.nonzero.signal() - self.nonzero.release() - -class mrsw: - def __init__(self): - # critical-section lock & the data it protects - self.rwOK = thread.allocate_lock() - self.nr = 0 # number readers actively reading (not just waiting) - self.nw = 0 # number writers either waiting to write or writing - self.writing = 0 # 1 iff some thread is writing - - # conditions - self.readOK = condition(self.rwOK) # OK to unblock readers - self.writeOK = condition(self.rwOK) # OK to unblock writers - - def read_in(self): - self.rwOK.acquire() - while self.nw: - self.readOK.wait() - self.nr = self.nr + 1 - self.rwOK.release() - - def read_out(self): - self.rwOK.acquire() - if self.nr <= 0: - raise ValueError, \ - '.read_out() invoked without an active reader' - self.nr = self.nr - 1 - if self.nr == 0: - self.writeOK.signal() - self.rwOK.release() - - def write_in(self): - self.rwOK.acquire() - self.nw = self.nw + 1 - while self.writing or self.nr: - self.writeOK.wait() - self.writing = 1 - self.rwOK.release() - - def write_out(self): - self.rwOK.acquire() - if not self.writing: - raise ValueError, \ - '.write_out() invoked without an active writer' - self.writing = 0 - self.nw = self.nw - 1 - if self.nw: - self.writeOK.signal() - else: - self.readOK.broadcast() - self.rwOK.release() - - def write_to_read(self): - self.rwOK.acquire() - if not self.writing: - raise ValueError, \ - '.write_to_read() invoked without an active writer' - self.writing = 0 - self.nw = self.nw - 1 - self.nr = self.nr + 1 - if not self.nw: - self.readOK.broadcast() - self.rwOK.release() - -# The rest of the file is a test case, that runs a number of parallelized -# quicksorts in parallel. If it works, you'll get about 600 lines of -# tracing output, with a line like -# test passed! 209 threads created in all -# as the last line. The content and order of preceding lines will -# vary across runs. - -def _new_thread(func, *args): - global TID - tid.acquire(); id = TID = TID+1; tid.release() - io.acquire(); alive.append(id); \ - print 'starting thread', id, '--', len(alive), 'alive'; \ - io.release() - thread.start_new_thread( func, (id,) + args ) - -def _qsort(tid, a, l, r, finished): - # sort a[l:r]; post finished when done - io.acquire(); print 'thread', tid, 'qsort', l, r; io.release() - if r-l > 1: - pivot = a[l] - j = l+1 # make a[l:j] <= pivot, and a[j:r] > pivot - for i in range(j, r): - if a[i] <= pivot: - a[j], a[i] = a[i], a[j] - j = j + 1 - a[l], a[j-1] = a[j-1], pivot - - l_subarray_sorted = event() - r_subarray_sorted = event() - _new_thread(_qsort, a, l, j-1, l_subarray_sorted) - _new_thread(_qsort, a, j, r, r_subarray_sorted) - l_subarray_sorted.wait() - r_subarray_sorted.wait() - - io.acquire(); print 'thread', tid, 'qsort done'; \ - alive.remove(tid); io.release() - finished.post() - -def _randarray(tid, a, finished): - io.acquire(); print 'thread', tid, 'randomizing array'; \ - io.release() - for i in range(1, len(a)): - wh.acquire(); j = randint(0,i); wh.release() - a[i], a[j] = a[j], a[i] - io.acquire(); print 'thread', tid, 'randomizing done'; \ - alive.remove(tid); io.release() - finished.post() - -def _check_sort(a): - if a != range(len(a)): - raise ValueError, ('a not sorted', a) - -def _run_one_sort(tid, a, bar, done): - # randomize a, and quicksort it - # for variety, all the threads running this enter a barrier - # at the end, and post `done' after the barrier exits - io.acquire(); print 'thread', tid, 'randomizing', a; \ - io.release() - finished = event() - _new_thread(_randarray, a, finished) - finished.wait() - - io.acquire(); print 'thread', tid, 'sorting', a; io.release() - finished.clear() - _new_thread(_qsort, a, 0, len(a), finished) - finished.wait() - _check_sort(a) - - io.acquire(); print 'thread', tid, 'entering barrier'; \ - io.release() - bar.enter() - io.acquire(); print 'thread', tid, 'leaving barrier'; \ - io.release() - io.acquire(); alive.remove(tid); io.release() - bar.enter() # make sure they've all removed themselves from alive - ## before 'done' is posted - bar.enter() # just to be cruel - done.post() - -def test(): - global TID, tid, io, wh, randint, alive - import random - randint = random.randint - - TID = 0 # thread ID (1, 2, ...) - tid = thread.allocate_lock() # for changing TID - io = thread.allocate_lock() # for printing, and 'alive' - wh = thread.allocate_lock() # for calls to random - alive = [] # IDs of active threads - - NSORTS = 5 - arrays = [] - for i in range(NSORTS): - arrays.append( range( (i+1)*10 ) ) - - bar = barrier(NSORTS) - finished = event() - for i in range(NSORTS): - _new_thread(_run_one_sort, arrays[i], bar, finished) - finished.wait() - - print 'all threads done, and checking results ...' - if alive: - raise ValueError, ('threads still alive at end', alive) - for i in range(NSORTS): - a = arrays[i] - if len(a) != (i+1)*10: - raise ValueError, ('length of array', i, 'screwed up') - _check_sort(a) - - print 'test passed!', TID, 'threads created in all' - -if __name__ == '__main__': - test() - -# end of module diff --git a/Demo/threads/telnet.py b/Demo/threads/telnet.py deleted file mode 100644 index 3c70cb0038..0000000000 --- a/Demo/threads/telnet.py +++ /dev/null @@ -1,114 +0,0 @@ -# Minimal interface to the Internet telnet protocol. -# -# *** modified to use threads *** -# -# It refuses all telnet options and does not recognize any of the other -# telnet commands, but can still be used to connect in line-by-line mode. -# It's also useful to play with a number of other services, -# like time, finger, smtp and even ftp. -# -# Usage: telnet host [port] -# -# The port may be a service name or a decimal port number; -# it defaults to 'telnet'. - - -import sys, os, time -from socket import * -import thread - -BUFSIZE = 8*1024 - -# Telnet protocol characters - -IAC = chr(255) # Interpret as command -DONT = chr(254) -DO = chr(253) -WONT = chr(252) -WILL = chr(251) - -def main(): - if len(sys.argv) < 2: - sys.stderr.write('usage: telnet hostname [port]\n') - sys.exit(2) - host = sys.argv[1] - try: - hostaddr = gethostbyname(host) - except error: - sys.stderr.write(sys.argv[1] + ': bad host name\n') - sys.exit(2) - # - if len(sys.argv) > 2: - servname = sys.argv[2] - else: - servname = 'telnet' - # - if '0' <= servname[:1] <= '9': - port = eval(servname) - else: - try: - port = getservbyname(servname, 'tcp') - except error: - sys.stderr.write(servname + ': bad tcp service name\n') - sys.exit(2) - # - s = socket(AF_INET, SOCK_STREAM) - # - try: - s.connect((host, port)) - except error, msg: - sys.stderr.write('connect failed: ' + `msg` + '\n') - sys.exit(1) - # - thread.start_new(child, (s,)) - parent(s) - -def parent(s): - # read socket, write stdout - iac = 0 # Interpret next char as command - opt = '' # Interpret next char as option - while 1: - data, dummy = s.recvfrom(BUFSIZE) - if not data: - # EOF -- exit - sys.stderr.write( '(Closed by remote host)\n') - sys.exit(1) - cleandata = '' - for c in data: - if opt: - print ord(c) -## print '(replying: ' + `opt+c` + ')' - s.send(opt + c) - opt = '' - elif iac: - iac = 0 - if c == IAC: - cleandata = cleandata + c - elif c in (DO, DONT): - if c == DO: print '(DO)', - else: print '(DONT)', - opt = IAC + WONT - elif c in (WILL, WONT): - if c == WILL: print '(WILL)', - else: print '(WONT)', - opt = IAC + DONT - else: - print '(command)', ord(c) - elif c == IAC: - iac = 1 - print '(IAC)', - else: - cleandata = cleandata + c - sys.stdout.write(cleandata) - sys.stdout.flush() -## print 'Out:', `cleandata` - -def child(s): - # read stdin, write socket - while 1: - line = sys.stdin.readline() -## print 'Got:', `line` - if not line: break - s.send(line) - -main() diff --git a/Demo/tix/BUGS.txt b/Demo/tix/BUGS.txt deleted file mode 100644 index 052a1e634f..0000000000 --- a/Demo/tix/BUGS.txt +++ /dev/null @@ -1,8 +0,0 @@ -$Id$ - -1) There seems to be a problem with ComboBox that shows up -in the ExFileSelectBox demo. The popdown scrolled list widget -is being created, then destroyed. This does not happen in Tcl Tix. -This is probably a sympton in Tix from _tkinter; if you find the cause -of this, please post a patch on http://tix.sourceforge.net. - diff --git a/Demo/tix/INSTALL.txt b/Demo/tix/INSTALL.txt deleted file mode 100644 index 9dc3093c50..0000000000 --- a/Demo/tix/INSTALL.txt +++ /dev/null @@ -1,81 +0,0 @@ -$Id$ - -Installing PyTix ----------------- - -0) To use PyTix, you need Tcl/Tk (V8.2+), Tix (V8.1+) and Python (V2.1+). - PyTix has been written and tested on a Intel Pentium running RH Linux 5.2 - and Mandrake Linux 7.0 and Windows with the above mentioned packages. - - Older versions, e.g. Tix 4.1 and Tk 8.0, might also work. - - There is nothing OS-specific in PyTix itself so it should work on - any machine with Tix and Python installed. You can get Tcl and Tk - from http://dev.scriptics.com and Tix from http://tix.sourceforge.net. - -1) Build and install Tcl/Tk 8.2 or 8.3. Build and install Tix 8.1 or better. - Ensure that Tix is properly installed by running tixwish and executing - the demo programs. Under Unix, use the --enable-shared configure option - for all three. We recommend tcl8.2.3 for this release of PyTix. - -2) Modify Modules/Setup.dist and setup.py to change the version of the - tix library from tix4.1.8.0 to tix8.1.8.2 - These modified files can be used for Tkinter with or without Tix. - -3) The default is to build dynamically, and use the Tcl 'package require'. - To build statically, modify the Modules/Setup file to link in the Tix - library according to the comments in the file. On Linux this looks like: - -# *** Always uncomment this (leave the leading underscore in!): -_tkinter _tkinter.c tkappinit.c -DWITH_APPINIT \ -# *** Uncomment and edit to reflect where your Tcl/Tk libraries are: - -L/usr/local/lib \ -# *** Uncomment and edit to reflect where your Tcl/Tk headers are: - -I/usr/local/include \ -# *** Uncomment and edit to reflect where your X11 header files are: - -I/usr/X11R6/include \ -# *** Or uncomment this for Solaris: -# -I/usr/openwin/include \ -# *** Uncomment and edit for BLT extension only: -# -DWITH_BLT -I/usr/local/blt/blt8.0-unoff/include -lBLT8.0 \ -# *** Uncomment and edit for PIL (TkImaging) extension only: -# (See http://www.pythonware.com/products/pil/ for more info) -# -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \ -# *** Uncomment and edit for TOGL extension only: -# -DWITH_TOGL togl.c \ -# *** Uncomment and edit for Tix extension only: - -DWITH_TIX -ltix8.1.8.2 \ -# *** Uncomment and edit to reflect your Tcl/Tk versions: - -ltk8.2 -ltcl8.2 \ -# *** Uncomment and edit to reflect where your X11 libraries are: - -L/usr/X11R6/lib \ -# *** Or uncomment this for Solaris: -# -L/usr/openwin/lib \ -# *** Uncomment these for TOGL extension only: -# -lGL -lGLU -lXext -lXmu \ -# *** Uncomment for AIX: -# -lld \ -# *** Always uncomment this; X11 libraries to link with: - -lX11 - -4) Rebuild Python and reinstall. - -You should now have a working Tix implementation in Python. To see if all -is as it should be, run the 'tixwidgets.py' script in the Demo/tix directory. -Under X windows, do - /usr/local/bin/python Demo/tix/tixwidgets.py - -If this does not work, you may need to tell python where to find -the Tcl, Tk and Tix library files. This is done by setting the -TCL_LIBRARY, TK_LIBRARY and TIX_LIBRARY environment variables. Try this: - - env TCL_LIBRARY=/usr/local/lib/tcl8.2 \ - TK_LIBRARY=/usr/local/lib/tk8.2 \ - TIX_LIBRARY=/usr/local/lib/tix8.1 \ - /usr/local/bin/python Demo/tix/tixwidgets.py - - -If you find any bugs or have suggestions for improvement, please report them -via http://tix.sourceforge.net - - diff --git a/Demo/tix/README.txt b/Demo/tix/README.txt deleted file mode 100644 index 15e85cd265..0000000000 --- a/Demo/tix/README.txt +++ /dev/null @@ -1,19 +0,0 @@ -About PyTix ------------ - -PyTix is based on an idea of Jean-Marc Lugrin (lugrin@ms.com) who wrote -pytix (another Python-Tix marriage). Tix widgets are an attractive and -useful extension to Tk. See http://tix.sourceforge.net -for more details about Tix and how to get it. - -Features: - 1) It is almost complete. - 2) Tix widgets are represented by classes in Python. Sub-widgets - are members of the mega-widget class. For example, if a - particular TixWidget (e.g. ScrolledText) has an embedded widget - (Text in this case), it is possible to call the methods of the - child directly. - 3) The members of the class are created automatically. In the case - of widgets like ButtonBox, the members are added dynamically. - - diff --git a/Demo/tix/bitmaps/about.xpm b/Demo/tix/bitmaps/about.xpm deleted file mode 100755 index 33ffcc06ef..0000000000 --- a/Demo/tix/bitmaps/about.xpm +++ /dev/null @@ -1,50 +0,0 @@ -/* XPM */ -static char * about_xpm[] = { -"50 40 7 1", -" s None c None", -". c black", -"X c white", -"o c gray70", -"O c navy", -"+ c red", -"@ c yellow", -" ", -" ", -" ", -" ................................. ", -" ..XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXoo. ", -" .XooooooooooooooooooooooooooooooXo. ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXooXo. ", -" ..oooooooooooooooooooooooooooooooXo. ", -" ...............................XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo.++++ ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo+++ ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo+++++ ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo++++++ ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo+++ + ", -" .OOOOO@@@@@OOOOOOOOOOOOOOOOOOO.Xo++. ", -" .OOOOOOO@OOOOO@OOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOO@OOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOO@OOOO@@OOO@OOO@OOOOOOO.XoXo. ", -" .OOOOOOO@OOOOO@OOOO@O@OOOOOOOO.XoXo. ", -" .OOOOOOO@OOOOO@OOOOO@OOOOOOOOO.XoXo. ", -" .OOOOOOO@OOOOO@OOOOO@OOOOOOOOO.XoXo. ", -" .OOOOOOO@OOOOO@OOOO@O@OOOOOOOO.XoXo. ", -" .OOOOOOO@OOOO@@@OO@OOO@OOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XoXo. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo.. ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo ", -" OOOOOOOOOOOOOOOOOOOOOOOOOOOOO.X. ", -" ............................. ", -" ", -" ", -" "}; diff --git a/Demo/tix/bitmaps/bold.xbm b/Demo/tix/bitmaps/bold.xbm deleted file mode 100755 index ebff8d1178..0000000000 --- a/Demo/tix/bitmaps/bold.xbm +++ /dev/null @@ -1,6 +0,0 @@ -#define bold_width 16 -#define bold_height 16 -static unsigned char bold_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0xfc, 0x07, 0xfc, 0x0f, 0x18, 0x1c, 0x18, 0x18, - 0x18, 0x18, 0x18, 0x1c, 0xf8, 0x0f, 0xf8, 0x0f, 0x18, 0x18, 0x18, 0x30, - 0x18, 0x30, 0x18, 0x38, 0xfc, 0x3f, 0xfc, 0x1f}; diff --git a/Demo/tix/bitmaps/capital.xbm b/Demo/tix/bitmaps/capital.xbm deleted file mode 100755 index fb4e0703b1..0000000000 --- a/Demo/tix/bitmaps/capital.xbm +++ /dev/null @@ -1,6 +0,0 @@ -#define capital_width 16 -#define capital_height 16 -static unsigned char capital_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x08, 0x30, 0x0c, 0x30, 0x06, - 0x30, 0x03, 0xb0, 0x01, 0xf0, 0x00, 0xf0, 0x00, 0xf0, 0x01, 0xb0, 0x03, - 0x30, 0x07, 0x30, 0x0e, 0x30, 0x1c, 0x00, 0x00}; diff --git a/Demo/tix/bitmaps/centerj.xbm b/Demo/tix/bitmaps/centerj.xbm deleted file mode 100755 index 9d2c064834..0000000000 --- a/Demo/tix/bitmaps/centerj.xbm +++ /dev/null @@ -1,6 +0,0 @@ -#define centerj_width 16 -#define centerj_height 16 -static unsigned char centerj_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3e, 0x00, 0x00, 0xc0, 0x0d, - 0x00, 0x00, 0x58, 0x77, 0x00, 0x00, 0xb0, 0x3b, 0x00, 0x00, 0xdc, 0xf7, - 0x00, 0x00, 0xf0, 0x3e, 0x00, 0x00, 0xd8, 0x7e}; diff --git a/Demo/tix/bitmaps/combobox.xbm b/Demo/tix/bitmaps/combobox.xbm deleted file mode 100755 index f5947f57b4..0000000000 --- a/Demo/tix/bitmaps/combobox.xbm +++ /dev/null @@ -1,14 +0,0 @@ -#define combobox_width 32 -#define combobox_height 32 -static unsigned char combobox_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xfc, 0xff, 0xff, 0x3e, 0x04, 0x00, 0x80, 0x2a, 0x04, 0x00, 0x80, 0x2a, - 0x04, 0x00, 0x80, 0x2a, 0x04, 0x00, 0x80, 0x2b, 0xfc, 0xff, 0xff, 0x3e, - 0x08, 0x00, 0x00, 0x20, 0x08, 0x00, 0x00, 0x3e, 0x08, 0x00, 0x00, 0x2a, - 0x28, 0x49, 0x00, 0x2a, 0x08, 0x00, 0x00, 0x3e, 0x08, 0x00, 0x00, 0x22, - 0x08, 0x00, 0x00, 0x22, 0x28, 0x49, 0x12, 0x22, 0x08, 0x00, 0x00, 0x22, - 0x08, 0x00, 0x00, 0x22, 0x08, 0x00, 0x00, 0x22, 0x28, 0x49, 0x02, 0x22, - 0x08, 0x00, 0x00, 0x3e, 0x08, 0x00, 0x00, 0x2a, 0x08, 0x00, 0x00, 0x2a, - 0xf8, 0xff, 0xff, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; diff --git a/Demo/tix/bitmaps/combobox.xpm b/Demo/tix/bitmaps/combobox.xpm deleted file mode 100755 index d0234ab8e2..0000000000 --- a/Demo/tix/bitmaps/combobox.xpm +++ /dev/null @@ -1,49 +0,0 @@ -/* XPM */ -static char * combobox_xpm[] = { -"50 40 6 1", -" s None c None", -". c black", -"X c white", -"o c #FFFF80808080", -"O c gray70", -"+ c #808000008080", -" ", -" ", -" ", -" .................................... XXXXXXX ", -" .ooooooooooooooooooooooooooooooooooX X . . ", -" .ooooooooooooooooooooooooooooooooooX X . . ", -" .oooo.oooooooooooooooooooooooooooooX X . . ", -" .oo.o..oo.o.oo.o.ooooooooooooooooooX X . . ", -" .o..o.o.o.oo.oo.oo.ooooooooooooooooX X ... . ", -" .oo.oo.oo.o.oo.ooo.ooooooooooooooooX X . . ", -" .ooooooooooooooooooooooooooooooooooX X . ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X...... ", -" ", -" ", -" ", -" XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ", -" X............................................ ", -" X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ", -" X.O+OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.OX OX. ", -" X.O++OOO+OO+++OOOOOOOOOOOOOOOOOOOOOOOX.X ..X. ", -" X.O+O+O+OOO+O+OOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ", -" X.O++OOO+OO+++OOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ", -" X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.XXXXX. ", -" X.O.....X..........................OOX.X .X. ", -" X.OX...XXX.X.XX.XX.................OOX.X .X. ", -" X.OX.X..X..X.XX..XX.X..............OOX.X .X. ", -" X.O.X...X..X.X...X..X..............OOX.X .X. ", -" X.OOOOOOOOOOOOOOOOOOOOOOOO+OOOOOOOOOOX.X .X. ", -" X.OOOOOOOOO+OOO+OOOOO+OOOO+OOOOOOOOOOX.X .X. ", -" X.O+++OO+OO+O+OO++O++OO+OO+OOOOOOOOOOX.X...X. ", -" X.OO+OO++OO+O+OO+OOO+OO+O++OOOOOOOOOOX.OOOOX. ", -" X.OOOOOOOO+OOOOO++OO+OOOOOOOOOOOOOOOOX.OOOOX. ", -" X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.X .X. ", -" X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.O .OX. ", -" X.OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOX.OOOOX. ", -" X.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.XXXXX. ", -" X............................................ ", -" ", -" ", -" "}; diff --git a/Demo/tix/bitmaps/combobox.xpm.1 b/Demo/tix/bitmaps/combobox.xpm.1 deleted file mode 100755 index 63792a4908..0000000000 --- a/Demo/tix/bitmaps/combobox.xpm.1 +++ /dev/null @@ -1,47 +0,0 @@ -/* XPM */ -static char * combobox_xpm[] = { -"50 40 4 1", -" s None c None", -". c black", -"X c #FFFF80808080", -"o c gray70", -" ", -" ", -" ", -" .................................... ....... ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . . ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . . ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . . ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . . ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . ... . ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . . ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. . . ", -" .................................... ....... ", -" ", -" ............................................. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .o...................................o.ooooo. ", -" .o...................................o.ooooo. ", -" .o...................................o.ooooo. ", -" .o...................................o.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" .ooooooooooooooooooooooooooooooooooooo.ooooo. ", -" ............................................. ", -" ", -" ", -" ", -" ", -" "}; diff --git a/Demo/tix/bitmaps/drivea.xbm b/Demo/tix/bitmaps/drivea.xbm deleted file mode 100755 index 83c636c670..0000000000 --- a/Demo/tix/bitmaps/drivea.xbm +++ /dev/null @@ -1,14 +0,0 @@ -#define drivea_width 32 -#define drivea_height 32 -static unsigned char drivea_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xf8, 0xff, 0xff, 0x1f, 0x08, 0x00, 0x00, 0x18, 0xa8, 0xaa, 0xaa, 0x1a, - 0x48, 0x55, 0xd5, 0x1d, 0xa8, 0xaa, 0xaa, 0x1b, 0x48, 0x55, 0x55, 0x1d, - 0xa8, 0xfa, 0xaf, 0x1a, 0xc8, 0xff, 0xff, 0x1d, 0xa8, 0xfa, 0xaf, 0x1a, - 0x48, 0x55, 0x55, 0x1d, 0xa8, 0xaa, 0xaa, 0x1a, 0x48, 0x55, 0x55, 0x1d, - 0xa8, 0xaa, 0xaa, 0x1a, 0xf8, 0xff, 0xff, 0x1f, 0xf8, 0xff, 0xff, 0x1f, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; diff --git a/Demo/tix/bitmaps/drivea.xpm b/Demo/tix/bitmaps/drivea.xpm deleted file mode 100755 index 4d274b995f..0000000000 --- a/Demo/tix/bitmaps/drivea.xpm +++ /dev/null @@ -1,43 +0,0 @@ -/* XPM */ -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", -/* pixels */ -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" .......................... ", -" .XXXXXXXXXXXXXXXXXXXXXXXo. ", -" .XooooooooooooooooooooooO. ", -" .Xooooooooooooooooo..oooO. ", -" .Xooooooooooooooooo..oooO. ", -" .XooooooooooooooooooooooO. ", -" .Xoooooooo.......oooooooO. ", -" .Xoo...................oO. ", -" .Xoooooooo.......oooooooO. ", -" .XooooooooooooooooooooooO. ", -" .XooooooooooooooooooooooO. ", -" .XooooooooooooooooooooooO. ", -" .XooooooooooooooooooooooO. ", -" .oOOOOOOOOOOOOOOOOOOOOOOO. ", -" .......................... ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" "}; diff --git a/Demo/tix/bitmaps/exit.xpm b/Demo/tix/bitmaps/exit.xpm deleted file mode 100755 index 505a07bdf6..0000000000 --- a/Demo/tix/bitmaps/exit.xpm +++ /dev/null @@ -1,48 +0,0 @@ -/* XPM */ -static char * exit_xpm[] = { -"50 40 5 1", -" s None c None", -". c black", -"X c white", -"o c #000080800000", -"O c yellow", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ....................................... ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. ", -" .XoooooooooooooooooooooooooooooooooooX. ", -" .XoooooooooooooooooooooooooooooooooooX. ", -" .XoooooooooooooooooooooooOoooooooooooX. ", -" .XoooooooooooooooooooooooOOooooooooooX. ", -" .XoooooooooooooooooooooooOOOoooooooooX. ", -" .XoooooOOOOOOOOOOOOOOOOOOOOOOooooooooX. ", -" .XoooooOOOOOOOOOOOOOOOOOOOOOOOoooooooX. ", -" .XoooooOOOOOOOOOOOOOOOOOOOOOOOOooooooX. ", -" .XoooooOOOOOOOOOOOOOOOOOOOOOOOOOoooooX. ", -" .XoooooOOOOOOOOOOOOOOOOOOOOOOOOooooooX. ", -" .XoooooOOOOOOOOOOOOOOOOOOOOOOOoooooooX. ", -" .XoooooOOOOOOOOOOOOOOOOOOOOOOooooooooX. ", -" .XoooooooooooooooooooooooOOOoooooooooX. ", -" .XoooooooooooooooooooooooOOooooooooooX. ", -" .XoooooooooooooooooooooooOoooooooooooX. ", -" .XoooooooooooooooooooooooooooooooooooX. ", -" .XoooooooooooooooooooooooooooooooooooX. ", -" .XoooooooooooooooooooooooooooooooooooX. ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX. ", -" ....................................... ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" "}; diff --git a/Demo/tix/bitmaps/filebox.xbm b/Demo/tix/bitmaps/filebox.xbm deleted file mode 100755 index c8f7ac255b..0000000000 --- a/Demo/tix/bitmaps/filebox.xbm +++ /dev/null @@ -1,14 +0,0 @@ -#define filebox_width 32 -#define filebox_height 32 -static unsigned char filebox_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0x3f, 0x04, 0x00, 0x00, 0x20, - 0xe4, 0xff, 0xff, 0x27, 0x24, 0x00, 0x00, 0x24, 0x24, 0x00, 0x00, 0x24, - 0xe4, 0xff, 0xff, 0x27, 0x04, 0x00, 0x00, 0x20, 0xe4, 0x7f, 0xfe, 0x27, - 0x24, 0x50, 0x02, 0x25, 0x24, 0x40, 0x02, 0x24, 0x24, 0x50, 0x02, 0x25, - 0x24, 0x40, 0x02, 0x24, 0x24, 0x50, 0x02, 0x25, 0x24, 0x40, 0x02, 0x24, - 0x24, 0x50, 0x02, 0x25, 0xe4, 0x7f, 0xfe, 0x27, 0x04, 0x00, 0x00, 0x20, - 0xe4, 0xff, 0xff, 0x27, 0x24, 0x00, 0x00, 0x24, 0x24, 0x00, 0x00, 0x24, - 0xe4, 0xff, 0xff, 0x27, 0x04, 0x00, 0x00, 0x20, 0xfc, 0xff, 0xff, 0x3f, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; diff --git a/Demo/tix/bitmaps/filebox.xpm b/Demo/tix/bitmaps/filebox.xpm deleted file mode 100755 index 7377ee60e6..0000000000 --- a/Demo/tix/bitmaps/filebox.xpm +++ /dev/null @@ -1,49 +0,0 @@ -/* XPM */ -static char * filebox_xpm[] = { -"50 40 6 1", -" s None c None", -". c white", -"X c gray80", -"o c black", -"O c #FFFF80808080", -"+ c gray70", -" ", -" ", -" ", -" ............................................ ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXooXooXoXooXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXooXooXoXooXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXooooooooooooooooooooooooooooooooooooo.XXo ", -" .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XXo ", -" .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.XXo ", -" .XX......................................XXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXoooooooooooooooo.XXXXoooooooooooooooo.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XXo+++++++++++++++.XXXXo+++++++++++++++.XXo ", -" .XX.................XXXX.................XXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXooXooXoXooXoXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXooXooXoXooXoXooXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXoooooooooooooooooooooooooooooooooooooo.Xo ", -" .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo ", -" .XXoOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO.Xo ", -" .XX.......................................Xo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .ooooooooooooooooooooooooooooooooooooooooooo ", -" ", -" ", -" "}; diff --git a/Demo/tix/bitmaps/italic.xbm b/Demo/tix/bitmaps/italic.xbm deleted file mode 100755 index 169c3cb75f..0000000000 --- a/Demo/tix/bitmaps/italic.xbm +++ /dev/null @@ -1,6 +0,0 @@ -#define italic_width 16 -#define italic_height 16 -static unsigned char italic_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x80, 0x3f, 0x00, 0x06, 0x00, 0x06, - 0x00, 0x03, 0x00, 0x03, 0x80, 0x01, 0x80, 0x01, 0xc0, 0x00, 0xc0, 0x00, - 0x60, 0x00, 0x60, 0x00, 0xfc, 0x01, 0xfc, 0x01}; diff --git a/Demo/tix/bitmaps/justify.xbm b/Demo/tix/bitmaps/justify.xbm deleted file mode 100755 index bba660acec..0000000000 --- a/Demo/tix/bitmaps/justify.xbm +++ /dev/null @@ -1,6 +0,0 @@ -#define justify_width 16 -#define justify_height 16 -static unsigned char justify_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xec, 0xdb, 0x00, 0x00, 0x7c, 0xdb, - 0x00, 0x00, 0xbc, 0xf7, 0x00, 0x00, 0xdc, 0xde, 0x00, 0x00, 0x6c, 0xdf, - 0x00, 0x00, 0x6c, 0xef, 0x00, 0x00, 0xdc, 0xdf}; diff --git a/Demo/tix/bitmaps/leftj.xbm b/Demo/tix/bitmaps/leftj.xbm deleted file mode 100755 index 5f8e006f4e..0000000000 --- a/Demo/tix/bitmaps/leftj.xbm +++ /dev/null @@ -1,6 +0,0 @@ -#define leftj_width 16 -#define leftj_height 16 -static unsigned char leftj_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xcc, 0x6d, 0x00, 0x00, 0xdc, 0x01, - 0x00, 0x00, 0xec, 0x0e, 0x00, 0x00, 0xfc, 0x7e, 0x00, 0x00, 0xdc, 0x03, - 0x00, 0x00, 0x6c, 0x3b, 0x00, 0x00, 0x6c, 0x1f}; diff --git a/Demo/tix/bitmaps/netw.xbm b/Demo/tix/bitmaps/netw.xbm deleted file mode 100755 index a684d65d4b..0000000000 --- a/Demo/tix/bitmaps/netw.xbm +++ /dev/null @@ -1,14 +0,0 @@ -#define netw_width 32 -#define netw_height 32 -static unsigned char netw_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0x02, 0x40, - 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x52, - 0x00, 0x00, 0x0a, 0x52, 0x00, 0x00, 0x8a, 0x51, 0x00, 0x00, 0x0a, 0x50, - 0x00, 0x00, 0x4a, 0x50, 0x00, 0x00, 0x0a, 0x50, 0x00, 0x00, 0x0a, 0x50, - 0x00, 0x00, 0xfa, 0x5f, 0x00, 0x00, 0x02, 0x40, 0xfe, 0x7f, 0x52, 0x55, - 0x02, 0x40, 0xaa, 0x6a, 0xfa, 0x5f, 0xfe, 0x7f, 0x0a, 0x50, 0xfe, 0x7f, - 0x0a, 0x52, 0x80, 0x00, 0x0a, 0x52, 0x80, 0x00, 0x8a, 0x51, 0x80, 0x00, - 0x0a, 0x50, 0x80, 0x00, 0x4a, 0x50, 0x80, 0x00, 0x0a, 0x50, 0xe0, 0x03, - 0x0a, 0x50, 0x20, 0x02, 0xfa, 0xdf, 0x3f, 0x03, 0x02, 0x40, 0xa0, 0x02, - 0x52, 0x55, 0xe0, 0x03, 0xaa, 0x6a, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, - 0xfe, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; diff --git a/Demo/tix/bitmaps/netw.xpm b/Demo/tix/bitmaps/netw.xpm deleted file mode 100755 index fff6593bca..0000000000 --- a/Demo/tix/bitmaps/netw.xpm +++ /dev/null @@ -1,45 +0,0 @@ -/* XPM */ -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", -/* pixels */ -" ", -" .............. ", -" .XXXXXXXXXXXX. ", -" .XooooooooooO. ", -" .Xo.......XoO. ", -" .Xo.++++o+XoO. ", -" .Xo.++++o+XoO. ", -" .Xo.++oo++XoO. ", -" .Xo.++++++XoO. ", -" .Xo.+o++++XoO. ", -" .Xo.++++++XoO. ", -" .Xo.XXXXXXXoO. ", -" .XooooooooooO. ", -" .Xo@ooo....oO. ", -" .............. .XooooooooooO. ", -" .XXXXXXXXXXXX. .XooooooooooO. ", -" .XooooooooooO. .OOOOOOOOOOOO. ", -" .Xo.......XoO. .............. ", -" .Xo.++++o+XoO. @ ", -" .Xo.++++o+XoO. @ ", -" .Xo.++oo++XoO. @ ", -" .Xo.++++++XoO. @ ", -" .Xo.+o++++XoO. @ ", -" .Xo.++++++XoO. ..... ", -" .Xo.XXXXXXXoO. .XXX. ", -" .XooooooooooO.@@@@@@.X O. ", -" .Xo@ooo....oO. .OOO. ", -" .XooooooooooO. ..... ", -" .XooooooooooO. ", -" .OOOOOOOOOOOO. ", -" .............. ", -" "}; diff --git a/Demo/tix/bitmaps/optmenu.xpm b/Demo/tix/bitmaps/optmenu.xpm deleted file mode 100755 index 63bab81299..0000000000 --- a/Demo/tix/bitmaps/optmenu.xpm +++ /dev/null @@ -1,48 +0,0 @@ -/* XPM */ -static char * optmenu_xpm[] = { -"50 40 5 1", -" s None c None", -". c white", -"X c gray80", -"o c gray50", -"O c black", -" ", -" ", -" .............................. ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXOXOXXOXXOXXXXOOXXXXXXXXXXo ", -" .XXXOXOXXOXOXXXOXXOXXXXXXXXXXo ", -" .XXXXOXXOXXOXXXOXXXOXXXXXXXXXo ", -" .XXXXOXXXOXXOOXXOXOXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo.............o ", -" .............................o o ", -" ..XXXOXXXXXOXXXXXXXXOXXXXXXXOo o ", -" ..XXOXOXOXXOXOXXXOXXOXXXXXXXOo ...... o ", -" ..XXXOXXXOXXOXXXOXXXOXXXXXXXOo . o o ", -" ..XXOXXXOXXXOXOXXOXXOXXXXXXXOo . o o ", -" ..XXXXXXXXXXXXXXXXXXXXXXXXXXOo .ooooo o ", -" .OOOOOOOOOOOOOOOOOOOOOOOOOOOOo o ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo o ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXooooooooooooooo ", -" .XXXXOXXXXXOXXXXXXXXXXXXXXXXXo ", -" .XXXOXXXXXXXXXOXXXXXXXXXXXXXXo ", -" .XXXXOXXOXXOXOXOXXXXXXXXXXXXXo ", -" .XXXXXOXXOXOXXXXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXOXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXOXOXXXXXXXOXOXXXXXOXXXXXXo ", -" .XXXXXOXOXOXXOXXXXXOXXOXXXXXXo ", -" .XXXXOXXOXOXOXXXOXOXOXXOXXXXXo ", -" .XXXOXXXXOXXOXXXOXXOXXXXOXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" .XXXXXXXXXXXXXXXXXXXXXXXXXXXXo ", -" oooooooooooooooooooooooooooooo ", -" ", -" ", -" ", -" "}; diff --git a/Demo/tix/bitmaps/rightj.xbm b/Demo/tix/bitmaps/rightj.xbm deleted file mode 100755 index 1d438e0090..0000000000 --- a/Demo/tix/bitmaps/rightj.xbm +++ /dev/null @@ -1,6 +0,0 @@ -#define rightj_width 16 -#define rightj_height 16 -static unsigned char rightj_bits[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xdb, 0x00, 0x00, 0x70, 0xdb, - 0x00, 0x00, 0x00, 0xef, 0x00, 0x00, 0xd8, 0xde, 0x00, 0x00, 0xc0, 0xdd, - 0x00, 0x00, 0xa0, 0xef, 0x00, 0x00, 0xd8, 0xde}; diff --git a/Demo/tix/bitmaps/select.xpm b/Demo/tix/bitmaps/select.xpm deleted file mode 100755 index 392e5a0834..0000000000 --- a/Demo/tix/bitmaps/select.xpm +++ /dev/null @@ -1,52 +0,0 @@ -/* XPM */ -static char * select_xpm[] = { -"50 40 9 1", -" s None c None", -". c black", -"X c gray95", -"o c gray50", -"O c gray70", -"+ c navy", -"@ c #000080800000", -"# c #808000000000", -"$ c white", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" .............................................. ", -" .XXXXXXXXXXooooooooooooXXXXXXXXXXXoXXXXXXXXXX. ", -" .X ooOOOOOOOOOOXX oX o. ", -" .X ooOOOOOOOOOOXX oX o. ", -" .X ++++ ooOOOOOOOOOOXX ... oX @ o. ", -" .X +++++ ooOOOOOOOOOOXX . . oX @@@ o. ", -" .X +++ + ooOOOOOOOOOOXX . . oX @ @ o. ", -" .X + + ooOO#####OOOXX . . oX @ @ o. ", -" .X + + ooOO#OOO##OOXX . oX @ @ o. ", -" .X + + ooO##OOOO##OXX . oX @ @ o. ", -" .X ++ ++ ooO###OOO#OOXX . oX @ @ o. ", -" .X +++++++ ooO#######OOXX . oX @ @ o. ", -" .X + + ooO##O#OO#OOXX . oX @ @ o. ", -" .X + ++ ooO##OOOOO#OXX . . oX @ @ o. ", -" .X + + ooOO#OOOOO#OXX . . oX @ @@ o. ", -" .X + ++ ooOO#OOOOO#OXX .... oX @@@@@ o. ", -" .X ooOO######OOXX oX o. ", -" .X ooOOOOOOOOOOXX $oX o. ", -" .XoooooooooooXXXXXXXXXXXoooooooooooXooooooooo. ", -" .............................................. ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" ", -" "}; diff --git a/Demo/tix/bitmaps/tix.gif b/Demo/tix/bitmaps/tix.gif deleted file mode 100755 index e7d51a086cc20c9a402e953237850ffba4d81844..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcwPel00001 literal 11042 zcwPY_E8WybNk%v~Vf+Bq0OJ4v00030|Nj60{{R4j{{R4jf`b450D=Gj!^6V>f&hYo z009300D^)50000000000EC2ui0Q>;e06+x)5XecZy*TU5yZ>M)j$~;DXo?Q$AfUn< z&v6jD^lZ<#(9?sUa7c6seZkw!m^==VOk8oATvD&WfYZk{cDcD67D(1<$Wf!pIG_YL)C7%{D`W8( z#sL5WSt^{Z)(tT*a^T1Ua6%RsXrQT60tP~&kQ%@MQWXZ=WDQVo;8dt!nS!+%)#=l+ zW}OyDo3&}xrUVWYTsoFuS*UBFrX98@Q{wRGDQZTr4;>vVP6h6g~0)=ay0<^g6`3kV!|6Tinn-;Hv! z>_+2my@X?-JV35x%eABLeQmd(YU$YBVlCZJ?A`3(QJmi0^bz4-vWlG7sf_Uo;FHih zp$zqa{kQ`U+!bp*YG$@jVWt=VSOQk}+<)NFW?E}05){UJhxA9s;p85E#4dlqI=vV!VN1#Tx8#uV1_B?m|`kmfSC%UiDrQMS;rTG zxt*3^bY2|^rc?T{m8SuF^4V0H2dIgrpn~pZXgaM-Nn$yhD0XEF6v>Cl9;J987nzsZ z=jWb*rg^5PW~N1`0sskVpG;qdgjRNNhWAztnCkcCrkb*a=BK0Pnx+_xa99kZzSZ#P zM83l3%aobMdRMIWDNrW=pmLF_Kvi-zcVAqq&Y9h6+%=QxWcgv*s+ylVHK?<)Hp{Cc zh6QCtqr@?W3nr#$7!RtG-IpwxdR@vVZf1q6sdGX`Wo?+O!u3>uY)!aTh2AoIXH%T= z`DK~}pewNg0&v`$P3DYa?=)=eL@aQV=28x2sp^Yg%Mv53uy)#QaHUiuh#!H;y`gxeE=YhY1m_GtSPle zb~R*?Y`1M!R4}^8EVcSU%WSBE20-p$L`6c#i0qnJH6B(6a1R|>wtH+I;D(v+WKrGO zvRQrpY3`X^T}tHtf!c=Gu;c#vD=Mz!o@@G`f2LVW%63=-4koDY) zt1*Li;bX!AumBLG9Swc^W6HO}5*rL|FlXO_OJ`Oko~@{+gpu>0#2^Q}F~J36gNjco zx`v!5RbwJJY({a46~P3^LkQ+;;qG>azPL1pJQ8HpZv_zVTA12IN`!{H=ltSLkUC7O7n4(&AEdY;6N1ZOonmxNl^9>^q>f>=RFdd(0g+7p#XJ^3|2>n zO*(4-cI`}H>)u(2i>^QrJrQUdW>HUJJ=C3V@MnBt7c4OhhoNdLCmduD4ypNO2Z)0u z$+p*s^k@_ph!96jO!*TUW{8%DIioN}L=IZOVh@yRX$}y&(44C0H>S+$$ey%~HTbP| zrL1Nzo?6DAUb3vY3@0e32Gw@(K%p{4+$qMGO0k}m9c?|#ImlX5q(qSyVZq?OpZFs*%A&6`0%Gi9mvgBA~vl)*xZfEQkA?Y z2!%ac9$dN;78K6xJM^nxgVvUN;Kd_C^l(i|Rxjm5%jzo3@LOo~d@uTYmPGla)+m z?#8}a+qzQ%)K$jVv^goZip49=jZ~8LzrO6r#eT|l^+we(Z-$jHjm?8aJrN3L@3OJ% zP~ogz_Og8eYE;vMA;(PRWp2-pP5}dQ@)%T}FApkE!YpPLYXfpkdVw*zO!8eG%gJCP!(kbDDc2qQ*xiHyqsT-(DCp`9boMRm8Rif;Q z?Yy?SoEmN8dvU-gZeuHS5)0VN(SS?$J?a#&i#xgp{qSWA)#yg2rp#qzNB|xXoFV?2 zsHns_Ws%jmbjA73PgxahrR4#wJkP4Wx~uc5upyLHpLDTsQ@<+{t^~M5tRIi^a_Twr zY;JSd$?+_8eb!6o-`vedq1-5z0(71ZPs%1`S9 z<5THs)u)XIP*73*YHW2X4JnmgripPr_c-0eq3y2#Sg+WCb}g;{GxaN62SYw{w>0~= zWDV0ZB$fhlfj?aj_?K=e8?Cu{cz69#7*@odi~&lxRe#Xj4EG=^_M) z7B&^pH~J9-L=h2Tl1B+Z8F~~Eb%1mukrIhU1&Blhy7fkt^++huHv)i1pA=aN5m|85 z4tTayTg6)MuwMTLO(X|v@@Gx$H4l>zP7GE?48$lswK_4Thwm^|Iv_idB29US3BhED z`X(jm@dyh5RAV(m-mq5N14-FXFRhh+QPWC-!v%HN0@u|4h^VMms;7z!1~|zFdP}E% zji`u<0R?>)O7D?PYy@q^1Sz?giloF46D3(Y*dZ?949bBr@^l2wPyx!&NsD0u(m0LO zSdG?rjo6rtA^=m|$c=y3jc~vo?qpCnG-1O*jtC`EH3p8}_zB{ei&nype#THEg;S?x zQFI_x>=asERTFqnj9GJv>_7t_MN)r|UgofB{>BQvcv^l#kou?u_Q;M46?IZYTfy>I zR3dd?g-Xx%Q<9=6qr_GT`H)NncrAr`k{FTdMNk#_cWcm3QPppZh=~KKet`9dC5Kj> zc#_vJO9}}NGL&UA#COFsB`m30E*V$IcvbAzD}6}+MuA9^!z6GunGODENe*_2{U~U8 zsEDHs2;~FP~Ez?zCNJ>8dQy$_$ zQx}M1gN2Ul#Z4Z$i*NTej|OSKmLPU1B1ABKB!qG0Qia#^N< zX@rh+#8LLir&Qn|8Ri+@r7$uVgTM9v74`L?a03U4s(Y`&Ev%tD+`*!bN_jk^8HU1i zcPLIYMvIqfi+AOfM)N_(6R2q_8wGM5$kQ#anqNOx9RLQYx#40q1*IwDiGf90oOBPs zN|auS1Z~oS{Sj=1DjRSXs796`5Yr<;qhV-Dc@ASCIO0aK0&poKtZkW^gS6HO`JFk$^?fM z#Csj|tt~rdC)-<&_FFgdBW)J{C*8NQUFvveMi2;45LcUBJTekIOAs=VS%U+a5BZiT zI$`sORv1!1fe@tOGg&dUZ{VG0hjbxv z0B;*69pfyX7H%GMCTD0Ch7z!-W?|OKOH$(n^vQ^5>6x9Hc}GVk8e=8^b1VBLU(LlD zh?*IaW@!Mzs%K%UcG79ah9?yxYJx&KF(ikwgjGm2HKnMXlO><=HEW@JH@dqfB`xds{)3fQMirKa=on~(Jaf8iLYr^ww zNi;3@@pk%h!4S7*ZovYXqHTMkV)Pb#;HEJjbDHe}l*;FK!mFotiZ4lX7G-lWlH)t1 zqAC}JdDDTg3{o0C{ADbhJ`1C9sFOOl20S55ng9uiiIs@Y_PHgP@k#e3{R46J!eb1qXnx=AOZn)S1l%36hkugz3pfoKE*k#)}lZ?n=T zZ9;RN0e5`-Yw$b&rVm46a(8pH(zr+$x*ek*P|1_mfJx?1hs{TuKpQeJBYi-ObKiO= zJQ5dlkv@Ff7p)SeG^!OSFoH1y!@*O~9NEVm`H z`Hv=j4jy&?I4L~5r*sL}2S#>mYaVR6xdwJl^c^nEJz?5UZq=PvY$Fgq&t*-kNgxqqROfl!Tze8MngHf>n=~^cY zjZLhXBiyMt{Lgy~IS7Z!R6IPSa(&D@vXE-byT^j_!?;8TeAH7t=}SPAT%Z2Pz5X_j zWa)>7kia5Hc7vSA{PR9*K}6*|%92+bFsNT$l*8sbZF*tu7441tCO+h9(|oeF8XxHq*StYH4DsLNj-0phA8CR4%!TCIxiXRLM-8IC?r+ zq7Q-pHIPUOLrXsS0^ar!%m&vN^VToCBVXr+Zk$nPU5ptIt=>1cCbd@8^On~Jq&hT2 ztvb1hK*53Kq+a=I3-o7mOtW<^B%}N%s_l$@O5;2MYk&(*-U&;{0j=GdVmi8e;UmYI zT&0=0$pToG-?kHXyX?)B%|w|qCNuc2-n?D%bJxIzWTqiB03CZQG<{w7DV5um9QlVe zkOa1bC0D6Uv<=Xd-PLAe9|S$sCyU+I@d*bWIj6irVI1Omp@ZZ#n5+a1UoHySd<8@( z07VF8lYMj^WE2hlC3g2E98nnn>plZuq1IIyT~Pp-l@Niug&}cAxdSj@k`VrlgUo{e z5N61JRHmY8Qz>t(1k;QM{qyEUIfPh#knQHE=kf?m;Q)l;2r2E~2h;uSJkC5oJ_C0t z`IKMzW#9OgpZS6hf0R#CwOEhnv`)_8`G^snX#e%`$FmqEVJ1;h#^DJjh54GV`h1Rv zyW9$KAeV39t z@b{bFjU&Zb3+aAd_0}}OPoKak&7DA3mupqa^gc9>tqY#OyyO%*#)Gx0Sn$h@E7!%*r)kJk76C~kCZ->} zytyuwvoE=u#X3c=4Xe8|o-ezc%eJf##z+#-GP)Kxkt)NVKBd1RDHTH0wagE$(5pF5 z(=4pZ&sv`t$=uA%V$Zc*6t&Y}D_PW3RU%d*S4mEr;bGt3%4g)ntzO!c4C1XuGdH`i z-F36_czKf3#=;WmX}}?C)9ju}|KQA{(dpZ|aEQjKslhCvGjwwQ(kR+A&tg1W_80+? zl8+j{CA16*do)SmMJ}*Twu1!DA}MDC5iv~E4jxLB5szWJ<*MVVeL}36lgKMzOI?w~ zC9V08*`b)-V8)S24&#`WIIC*H_U=wc3x4+TS+c^IvaDm;ARMQ~oWhNkj@oOxFzv*P zX76gPx$I!Fw?Xvn5qk8IReCMUF)ZkCE}>GQSS}J+cjQ!gjro#W3UF~Tz;&Dqt|sfP z;?2qgHil-XiN%4x{Z7UO~jHkyH z@&sVWAK_fpRRV%aB31$lr1i>1g9OsiB@F%10AOqXt+jvv3KarTLWylNStaNkVNpkW z^pyZ$4IqHW0EjL0P(q0ywum${OAn)+RxpAZ8AB6S6e@L--~c&=m~_}*t)=$fM3ZG! z8c69qkX1<~wKrHr2`%*CWDySdM}vu-@X>{Ttyj{96;9aTMAb~QPEc|i_aIlo`w3l6 zNOd94ZXlI+2m=CWnc9Ja9k|wG^C@D|Vg;Ug;zA9c*;=5jCA8WCfM)n$V|7)OV0&R^ z*k_524t8i@i@ukNaIs4b7Z6$uV&r|uyb8d0tQ`Penu{%>Wdp2sTI#gFB_eGj2F6%u zrW0+u-fH0vx@w~P7ChJk?k+U%Uwsz*Ua15B2fSJV42XR4l9L0`>vMyuXd?fx(jeeS zTfVvNzk!XEWzkhhJz&u#j+$Dl2WQ;$zFi)icGHV39ADQNhrM)}VP?D90R*>wauSit zDIE%3ymYL|M(uoa2@Ig~0JI@}nOc{Hzr9-2`=~wAsD-$l@z}rr-uCrZKcH#grA}Y{ z!HYLua{N_NzABT_1&YbUG^I0KAOQ9tMlkJpkAA}=Lf`N;H}9EGc0ilo0>P&~mdPu7 zGFu!43IOO#mBBffoMg{cOSH1wRlIqVv(*}e)}E!FjzYg zf^Tlw(;E*-S3|*t@P5dHLS52;LJkoBCR8-xhEl4e0qhZRVGUFu65)rloFxuXE+Zq` z8fZH-8jpQG#GM2+n8PA^v3(a*9~1TCu65bve<3N0c1)zM3=~j?YMWc*FBr31m& zySD{#ljaMb868Q!;L)&}K*SxA@b-)-8egFI&6NhX!aB$ zH+MwqI$<}`LV+yW6m9aXs8J`FO`mSGX?oi!E(tom9}#h^o4i*B z>qag6k%2x`Wa%VG^RPTpZzV94DE92NK}1F@uw#8)y}F0ZpW9=*c&+64qLT z{3aK{6bGjIMX!h;kb!pNvHb<~f0Ld+_X|46XX+~GN0F{(0i^|P8rp^c|+wNmi zOIFxU7J;r@lCW^3&bcJRFb?GdA3lOgb#mn`R=5@nb;Toit?EY!sBUyM8nIPbcV5EU z?SJVuTk;tQlRv^QMZ?IWL?HkH5u5OYW0gWh%Ilbq+248#(kH3%qf0x%OH4Q-U`u9k zWdydafoayt|MIfBF;-;1z=&XJWUs&(?iYE>ichtz6{?jRK_86*qAYEwod-IJTrpcR z8VE^IS)F_|;`}0{WsrY8erh=m9l%3``6E>~oiz(Z6;ztlfR`i)UQUKdm9hw~6nYle*uf{x`{iWo@7LJmm%_GRrqS zfCV^74^$A$dyS0H`5b}+iHbJGci!)TM;+(_hj(A)EKej(vg1;~`Pui)Xuo3n=W9>< z)DL>-t1n;__~5!S`?%QvQY7JgMR(43-fCh4eQ-f<8TRn|cIYDU#|zx0q|9TkbX+DGd(s;%NICl(Uh6i!z@M&wwx1jKMql9OwaLJV z+gX!)xA^H%jt7_2H9xb_1MJCz_?IAMw81u7?$s@NRkIuA!A~ph#i_pKbKaJfce}8C z3Hf&alV0G{HaHUxll_I~A=gyh%w=k1fl<4?e+$4xTQ~7jwSXf41xT^bOSXHXpI|~A zCTKtRyRGJ9wWs5|X*+-tkQ|s$4=B4MeAqv{aw-#43*5uGc_KStGr(edLEu}!0{XR^ z^D2^xK$e+6DkCl1t1@PzmTU7l`NO;LIPI_s+*6uHNnL6j@N@H057!wheesnv6XyBfFu zFu^0nh{8SeLlxXPn5iC}BQ;@Zx}>uwTGB2d(ykmN#N=bT%%ieZlR`zK#24_uN~nwv zd$=~ZD_t`|UIVTM+e2K;D({;?8(PKOs}-8UJc&X-dds2q3By=SJ|7glQ(U#=Q#nAZ z4&PD`?R$YuWT6(~k^m_I+%qlnTg18>Jp!z!3(Ezwa#ZA>+PEW32GzbYZL z`|w0;5VTA|u7?9I5WpYID?>e;#k3Mc@sh?pv>=S4qcozOq53?FRK|2W#k_k#Q#&{1 z5<3O~k*2bV>Qkl?+%>c?hKO82vjfN-B)ebBn-r76oGiYmX(L{$EF-uiKKw}kGZaKy zyqB}HJij^)EfR1r~do|i($?Bg64a7RVE$9|Nz^Vvy|e8kvFtXYCZ1S3j@8M=Aw zM`cvXyL+FLq&?0!D6c@WIdn-TgG0-~3VRI88r;gQ{K?XR#yNAxnS?B-S(=anDZ05N zLdmMN1h!;+JGXo;xNL^KqRVr#%a&ZS>!Y=S1i@HgOJReSfBd*h5*Dq5Od?{$=(3j; zGauMl8Ph>aDucGuEG@r+nNXxmXCW9uxsJK?ww4pS*YnK7OUWjKjWPik03c0t`-4Oi zJ>6*)*KEY{W5K5hD|~t}nhBcvsuhqUJ3(p_ew@N|TeScPxb~k|X(qPAQIdL`qwv%pZwA`NP2Yqpju&sC!a2M6{OY zjHAbszuyZ&=R3Ut(6&DN(AYo@>mZQ&oRh0Wi3C7_zvRl1%*A569b=O`8LUF`M5LH$ z9OE-9LX4WBL%S;l(jfJ{;(3bCunlheGZOWznu9Y!DLv1dz<#6veYspv;3m zcgrD04Ad_AQuRBZ!i=|gL$x1e)I|l-lam|;;E&8mC zyFEr@yD=N)ag#$yt`>_I!b#V41~Xdn^j|Ti?Lae^>_j$RWSZjM@~e6 zX+gKY#KK}#I(7w19+aUk{HJ=O%xUzue8tz%%fO3czCP79xqv7Q%$ZA*FtEc!7%XLZGavBEobHLLB(#qGV2T{S>U678Uk zf$af?YLU5JQ(aNZ_RBJZ3CUJ-w@GXy%cQ{5S{iEPJfRGqy!F1A%{vA3#9D+Yu%dM zK#ZGRA5>K98PZx^E@DtZh$0HDNufV6Sh?NHNIgmaGQ6q6WI=ti(mqwdV4;OJ0QLdX?Tve`lJlDRm%u%Dl zrHMiNbyt_=T=Ppz#j>cv&7CmZ9-B0~18zKbi(T8*Hk1mk_7$$@FpsGM0L?krts#hy zj7*~xKKOymQiEB*bXR3Wob+2iN9rduGD`Q0*_@s_d4C7(my40E5 z+@dtK)s)P!VoiK9-J6nM;p<;!9G_oO;lnc4kbFjl1->8UKq6xY>H)1BQ3Wu@72&mr zhK*Wtb=Zjvy+zF18id)|%_eHgos5cN+7aUa>;+8ddfmdbAtD7Ya00FP40q4RbA!DEaTqn!`MZQ5#wEV2!T>Iyaf?n`8Z=v z)nsGcRLH9{0Iah*Ye(-|m}%VKT7e|d3868}TX^hEo<-#L`#Cv0Q8e^PD zfHk22DoHw+H5S%f)m1$jI$}A)fq8mT(LyvMF_Q010g(PO2>@wCaOX#Xp&?Oe6hIl6 zMi~$j4KHRVCDV{Z1CQl88y$R@p1u(O{)3_<)MA)ZAmI;sNp+5rFq!QLi*HTpbTp=wjf%SNXS3!LwNB{^m}vl_X%e%Du|}B-Xcs%7y}LeZ zQ9`eNc!lUYv^ZP~Vt_eQX6F;clR`G>vtDh~?q|(j#|IvPwMGF3z|VPj?Y*Ww&9D!` zHpWvRZNmd?5KQfINNbpO+7Ju|_U#NZz->(YyWu?F<$=%NhFe0mVB#k3Or(x+{UhaJ zDsoImm5gBOsA$DIlM(z9g3NCJ_C{vrWLxcCZ$ArdfjB(5OgQtFuP@lYrfqNkhDm?$ zhJ=M}lW`EFaHgpcWjj2$Z%c3WHtjex=l_oITDXk(+J&s+R;kc%FEP?GQ4L!Qji|gs z(GJHWNa|w-aAf|_0k@o5OKvm}yul6-0v}#BbwcEFjQJLj4N&JcZSnkeO3j?`PVf&1 zKT+le%^QEB3zyRYqAMT&I_zWb497Z21@a&MEs@AvP&SJk{&04-k%d%8DF2c;op3Z~ zZ}1l5ze_J9yuXYdY!78~3o&ynPjlqP^X&ex0H?JUDp}jka})@->z;9^TJ!kUb1om> z5<88>8*@cZ4;cyWVU*z4O7Z;Ol3wi?;QbJ*=OdS{sU4!zutp*22>fjymixw4F|GKFX3MRdT_`vjC zm=R(I?_y>$T_fZ{Yp+Qs0VTyT;4KVhzrN3usZ2=$N)e2f^7ee-gU+N+DFPLD&j%o2 zxLoIlZAafyY8FtLE%5MSvIq-x_x3?Xu#5hQepiKuIrn!D_}L0= len(maker_list): - i = 0 - elif i < 0: - 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). - demo_maker.set(maker_list[i]) - -def validate_maker(w): - try: - i = maker_list.index(demo_maker.get()) - except: - # Works here though. Why ? Beats me. - return maker_list[0] - # Works here though. Why ? Beats me. - return maker_list[i] - -def ok_command(w): - print "Selected", demo_num_engines.get(), "of", demo_maker.get(), " engines each of thrust", demo_thrust.get() - w.destroy() - -if __name__ == '__main__': - root = Tix.Tk() - RunSample(root) - root.mainloop() diff --git a/Demo/tix/samples/NoteBook.py b/Demo/tix/samples/NoteBook.py deleted file mode 100755 index 993dcc6c31..0000000000 --- a/Demo/tix/samples/NoteBook.py +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/local/bin/python -# -# $Id$ -# -# Tix Demostration Program -# -# This sample program is structured in such a way so that it can be -# executed from the Tix demo program "tixwidgets": it must have a -# procedure called "RunSample". It should also have the "if" statment -# at the end of this file so that it can be run as a standalone -# program. - -# This file demonstrates the use of the tixNoteBook widget, which allows -# you to lay out your interface using a "notebook" metaphore -# -import Tix - -def RunSample(w): - global root - root = w - - # We use these options to set the sizes of the subwidgets inside the - # notebook, so that they are well-aligned on the screen. - prefix = Tix.OptionName(w) - if prefix: - prefix = '*'+prefix - else: - 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) - w.option_add(prefix+'*TixNoteBook*tagPadX', 8) - - # Create the notebook widget and set its backpagecolor to gray. - # Note that the -backpagecolor option belongs to the "nbframe" - # subwidget. - 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. - 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) - - #---------------------------------------- - # Create the first page - #---------------------------------------- - # Create two frames: one for the common buttons, one for the - # other widgets - # - 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 - #---------------------------------------- - - 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.pack(side=Tix.TOP, padx=2, pady=2) - cancel.pack(side=Tix.TOP, padx=2, pady=2) - -if __name__ == '__main__': - root = Tix.Tk() - RunSample(root) - root.mainloop() diff --git a/Demo/tix/samples/OptMenu.py b/Demo/tix/samples/OptMenu.py deleted file mode 100755 index 2d05938372..0000000000 --- a/Demo/tix/samples/OptMenu.py +++ /dev/null @@ -1,68 +0,0 @@ -#!/usr/local/bin/python -# -# $Id$ -# -# Tix Demostration Program -# -# This sample program is structured in such a way so that it can be -# executed from the Tix demo program "tixwidgets": it must have a -# procedure called "RunSample". It should also have the "if" statment -# at the end of this file so that it can be run as a standalone -# program. - -# This file demonstrates the use of the tixOptionMenu widget -- you can -# use it for the user to choose from a fixed set of options -# -import Tix - -options = {'text':'Plain Text', 'post':'PostScript', 'html':'HTML', - 'tex':'LaTeX', 'rtf':'Rich Text Format'} - -def RunSample(w): - global demo_opt_from, demo_opt_to - - demo_opt_from = Tix.StringVar() - demo_opt_to = Tix.StringVar() - - 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') - - to_file = Tix.OptionMenu(top, label="To File Format : ", - 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"! - # - for opt in options.keys(): - 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') - - from_file.pack(side=Tix.TOP, anchor=Tix.W, pady=3, padx=6) - to_file.pack(side=Tix.TOP, anchor=Tix.W, pady=3, padx=6) - - box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) - box.add('ok', text='Ok', underline=0, width=6, - command=lambda w=w: ok_command(w)) - box.add('cancel', text='Cancel', underline=0, width=6, - command=lambda w=w: w.destroy()) - box.pack(side=Tix.BOTTOM, fill=Tix.X) - top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) - -def ok_command(w): - print "Convert file from", demo_opt_from.get(), " to", demo_opt_to.get() - w.destroy() - -if __name__ == '__main__': - root = Tix.Tk() - RunSample(root) - root.mainloop() diff --git a/Demo/tix/samples/PopMenu.py b/Demo/tix/samples/PopMenu.py deleted file mode 100755 index c2301cf78c..0000000000 --- a/Demo/tix/samples/PopMenu.py +++ /dev/null @@ -1,56 +0,0 @@ -# Tix Demostration Program -# -# $Id$ -# -# -# This sample program is structured in such a way so that it can be -# executed from the Tix demo program "widget": it must have a -# procedure called "RunSample". It should also have the "if" statment -# at the end of this file so that it can be run as a standalone -# program using tixwish. - -# This file demonstrates the use of the tixPopupMenu widget. -# -import Tix - -def RunSample(w): - # We create the frame and the button, then we'll bind the PopupMenu - # to both widgets. The result is, when you press the right mouse - # button over $w.top or $w.top.but, the PopupMenu will come up. - # - top = Tix.Frame(w, relief=Tix.RAISED, bd=1) - but = Tix.Button(top, text='Press the right mouse button over this button or its surrounding area') - but.pack(expand=1, fill=Tix.BOTH, padx=50, pady=50) - - p = Tix.PopupMenu(top, title='Popup Test') - p.bind_widget(top) - p.bind_widget(but) - - # Set the entries inside the PopupMenu widget. - # [Hint] You have to manipulate the "menu" subwidget. - # $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) - p.menu.add_command(label='Select', underline=0) - p.menu.add_command(label='Find', underline=0) - p.menu.add_command(label='System', underline=1) - p.menu.add_command(label='Help', underline=0) - m1 = Tix.Menu(p.menu) - m1.add_command(label='Hello') - p.menu.add_cascade(label='More', menu=m1) - - but.pack(side=Tix.TOP, padx=40, pady=50) - - box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) - box.add('ok', text='Ok', underline=0, width=6, - command=lambda w=w: w.destroy()) - box.add('cancel', text='Cancel', underline=0, width=6, - command=lambda w=w: w.destroy()) - box.pack(side=Tix.BOTTOM, fill=Tix.X) - top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) - -if __name__ == '__main__': - root = Tix.Tk() - RunSample(root) - root.mainloop() diff --git a/Demo/tix/samples/SHList1.py b/Demo/tix/samples/SHList1.py deleted file mode 100755 index 5122bbcdda..0000000000 --- a/Demo/tix/samples/SHList1.py +++ /dev/null @@ -1,107 +0,0 @@ -#!/usr/local/bin/python -# -# $Id$ -# -# Tix Demostration Program -# -# This sample program is structured in such a way so that it can be -# executed from the Tix demo program "tixwidgets": it must have a -# procedure called "RunSample". It should also have the "if" statment -# at the end of this file so that it can be run as a standalone -# program using tixwish. - -# This file demonstrates the use of the tixScrolledHList widget. -# - -import Tix - -def RunSample (w) : - - # We create the frame and the ScrolledHList widget - # at the top of the dialog box - # - top = Tix.Frame( w, relief=Tix.RAISED, bd=1) - - # Put a simple hierachy into the HList (two levels). Use colors and - # separator widgets (frames) to make the list look fancy - # - top.a = Tix.ScrolledHList(top) - top.a.pack( expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.TOP) - - - # This is our little relational database - # - bosses = [ - ('jeff', 'Jeff Waxman'), - ('john', 'John Lee'), - ('peter', 'Peter Kenson') - ] - - employees = [ - ('alex', 'john', 'Alex Kellman'), - ('alan', 'john', 'Alan Adams'), - ('andy', 'peter', 'Andreas Crawford'), - ('doug', 'jeff', 'Douglas Bloom'), - ('jon', 'peter', 'Jon Baraki'), - ('chris', 'jeff', 'Chris Geoffrey'), - ('chuck', 'jeff', 'Chuck McLean') - ] - - hlist=top.a.hlist - - # Let configure the appearance of the HList subwidget - # - hlist.config( separator='.', width=25, drawbranch=0, indent=10) - - count=0 - for boss,name in bosses : - if count : - f=Tix.Frame(hlist, name='sep%d' % count, height=2, width=150, - bd=2, relief=Tix.SUNKEN, bg=hlist['bg'] ) - - hlist.add_child( itemtype=Tix.WINDOW, - window=f, state=Tix.DISABLED ) - - hlist.add(boss, itemtype=Tix.TEXT, text=name) - count = count+1 - - - for person,boss,name in employees : - # '.' is the separator character we chose above - # - key= boss + '.' + person - # ^^^^ ^^^^^^ - # parent entryPath / child's name - - 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: - # - # hlist.addchild( boss, text=name) - # ^^^^ - # parent entryPath - - - # Use a ButtonBox to hold the buttons. - # - box= Tix.ButtonBox(top, orientation=Tix.HORIZONTAL ) - box.add( 'ok', text='Ok', underline=0, width=6, - command = lambda w=w: w.destroy() ) - - box.add( 'cancel', text='Cancel', underline=0, width=6, - command = lambda w=w: w.destroy() ) - - box.pack( side=Tix.BOTTOM, fill=Tix.X) - top.pack( side=Tix.TOP, fill=Tix.BOTH, expand=1 ) - - -# This "if" statement makes it possible to run this script file inside or -# outside of the main demo program "widget". -# -if __name__== '__main__' : - root=Tix.Tk() - RunSample(root) - root.mainloop() diff --git a/Demo/tix/samples/SHList2.py b/Demo/tix/samples/SHList2.py deleted file mode 100755 index e1a7a7c21b..0000000000 --- a/Demo/tix/samples/SHList2.py +++ /dev/null @@ -1,148 +0,0 @@ -#!/usr/local/bin/python -# -# $Id$ -# -# Tix Demostration Program -# -# This sample program is structured in such a way so that it can be -# executed from the PyTix demo program "tixwidget": it must have a -# procedure called "RunSample". It should also have the "if" statment -# at the end of this file so that it can be run as a standalone -# program using tixwish. - -# 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. -# - -import Tix - -def RunSample (w) : - - # We create the frame and the ScrolledHList widget - # at the top of the dialog box - # - top = Tix.Frame( w, relief=Tix.RAISED, bd=1) - - # Put a simple hierachy into the HList (two levels). Use colors and - # separator widgets (frames) to make the list look fancy - # - top.a = Tix.ScrolledHList(top, options='hlist.columns 3 hlist.header 1' ) - - top.a.pack( expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.TOP) - - hlist=top.a.hlist - - # Create the title for the HList widget - # >> Notice that we have set the hlist.header subwidget option to true - # so that the header is displayed - # - - boldfont=hlist.tk.call('tix','option','get','bold_font') - - # First some styles for the headers - style={} - style['header'] = Tix.DisplayStyle(Tix.TEXT, fg='black', refwindow=top, - anchor=Tix.CENTER, padx=8, pady=2, font = boldfont ) - - hlist.header_create(0, itemtype=Tix.TEXT, text='Name', - style=style['header']) - hlist.header_create(1, itemtype=Tix.TEXT, text='Position', - style=style['header']) - - # Notice that we use 3 columns in the hlist widget. This way when the user - # expands the windows wide, the right side of the header doesn't look - # chopped off. The following line ensures that the 3 column header is - # not shown unless the hlist window is wider than its contents. - # - hlist.column_width(2,0) - - # This is our little relational database - # - boss = ('doe', 'John Doe', 'Director') - - managers = [ - ('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') - ] - - style['mgr_name'] = Tix.DisplayStyle(Tix.TEXT, refwindow=top, - fg='#202060', selectforeground = '#202060', font = boldfont ) - - style['mgr_posn'] = Tix.DisplayStyle(Tix.TEXT, padx=8, refwindow=top, - fg='#202060', selectforeground='#202060' ) - - style['empl_name'] = Tix.DisplayStyle(Tix.TEXT, refwindow=top, - fg='#602020', selectforeground = '#602020', font = boldfont ) - - style['empl_posn'] = Tix.DisplayStyle(Tix.TEXT, padx=8, refwindow=top, - fg='#602020', selectforeground = '#602020' ) - - # Let configure the appearance of the HList subwidget - # - hlist.config(separator='.', width=25, drawbranch=0, indent=10) - hlist.column_width(0, chars=20) - - # Create the boss - # - hlist.add ('.', itemtype=Tix.TEXT, text=boss[1], - style=style['mgr_name']) - hlist.item_create('.', 1, itemtype=Tix.TEXT, text=boss[2], - style=style['mgr_posn']) - - # Create the managers - # - - for key,name,posn in managers : - e= '.'+ key - hlist.add(e, itemtype=Tix.TEXT, text=name, - style=style['mgr_name']) - hlist.item_create(e, 1, itemtype=Tix.TEXT, text=posn, - style=style['mgr_posn']) - - - for key,mgr,name,posn in employees : - # "." is the separator character we chose above - - entrypath = '.' + mgr + '.' + key - - # ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ - # parent entryPath / child's name - - hlist.add(entrypath, text=name, style=style['empl_name']) - hlist.item_create(entrypath, 1, itemtype=Tix.TEXT, - text = posn, style = style['empl_posn'] ) - - - # Use a ButtonBox to hold the buttons. - # - box= Tix.ButtonBox(top, orientation=Tix.HORIZONTAL ) - box.add( 'ok', text='Ok', underline=0, width=6, - command = lambda w=w: w.destroy() ) - - box.add( 'cancel', text='Cancel', underline=0, width=6, - command = lambda w=w: w.destroy() ) - - box.pack( side=Tix.BOTTOM, fill=Tix.X) - top.pack( side=Tix.TOP, fill=Tix.BOTH, expand=1 ) - - -# This "if" statement makes it possible to run this script file inside or -# outside of the main demo program "widget". -# -if __name__== '__main__' : - root=Tix.Tk() - RunSample(root) - root.mainloop() diff --git a/Demo/tix/samples/Tree.py b/Demo/tix/samples/Tree.py deleted file mode 100755 index b0520fbba5..0000000000 --- a/Demo/tix/samples/Tree.py +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/local/bin/python -# -# $Id$ -# -# Tix Demostration Program -# -# This sample program is structured in such a way so that it can be -# executed from the Tix demo program "tixwidgets": it must have a -# procedure called "RunSample". It should also have the "if" statment -# at the end of this file so that it can be run as a standalone -# program. - -# This file demonstrates how to use the TixTree widget to display -# dynamic hierachical data (the files in the Unix file system) -# - -import Tix, os - -def RunSample(w): - top = Tix.Frame(w, relief=Tix.RAISED, bd=1) - tree = Tix.Tree(top, options='separator "/"') - tree.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.LEFT) - tree['opencmd'] = lambda dir=None, w=tree: opendir(w, dir) - - # The / directory is added in the "open" mode. The user can open it - # and then browse its subdirectories ... - adddir(tree, "/") - - box = Tix.ButtonBox(w, orientation=Tix.HORIZONTAL) - box.add('ok', text='Ok', underline=0, command=w.destroy, width=6) - box.add('cancel', text='Cancel', underline=0, command=w.destroy, width=6) - box.pack(side=Tix.BOTTOM, fill=Tix.X) - top.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) - -def adddir(tree, dir): - if dir == '/': - text = '/' - else: - text = os.path.basename(dir) - tree.hlist.add(dir, itemtype=Tix.IMAGETEXT, text=text, - image=tree.tk.call('tix', 'getimage', 'folder')) - try: - os.listdir(dir) - tree.setmode(dir, 'open') - except os.error: - # 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 -# inside that directory into the Tree widget. -# -# Note we didn't specify the closecmd option for the Tree widget, so it -# performs the default action when the user presses the (-) indicator or -# double clicks on a directory whose mode is "close": hide all of its child -# entries -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) - 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 __name__ == '__main__': - root = Tix.Tk() - RunSample(root) - root.mainloop() diff --git a/Demo/tix/tixwidgets.py b/Demo/tix/tixwidgets.py deleted file mode 100644 index b2873648d8..0000000000 --- a/Demo/tix/tixwidgets.py +++ /dev/null @@ -1,819 +0,0 @@ -#! /usr/local/bin/python -# -# $Id$ -# -# tixwidgets.py -- -# This is a demo program of all Tix widgets available from Python. If -# you have installed Python & Tix properly, you can execute this as -# -# % tixwidget.py -# - -import os, sys, Tix - -class Demo: - pass - -root = Tix.Tk() - -demo = Demo() -demo.dir = None # script directory -demo.balloon = None # balloon widget -demo.useBalloons = Tix.StringVar() -demo.useBalloons.set('0') -demo.statusbar = None # status bar widget -demo.welmsg = None # Msg widget -demo.welfont = '' # font name -demo.welsize = '' # font size - -def main(): - global demo, root - - progname = sys.argv[0] - dirname = os.path.dirname(progname) - if dirname and dirname != os.curdir: - demo.dir = dirname - index = -1 - for i in range(len(sys.path)): - p = sys.path[i] - if p in ("", os.curdir): - index = i - if index >= 0: - sys.path[index] = dirname - else: - sys.path.insert(0, dirname) - else: - demo.dir = os.getcwd() - sys.path.insert(0, demo.dir+'/samples') - - root.withdraw() - root = Tix.Toplevel() - root.title('Tix Widget Demonstration') - root.geometry('780x570+50+50') - - demo.balloon = Tix.Balloon(root) - frame1 = MkMainMenu(root) - frame2 = MkMainNotebook(root) - frame3 = MkMainStatus(root) - frame1.pack(side=Tix.TOP, fill=Tix.X) - frame3.pack(side=Tix.BOTTOM, fill=Tix.X) - frame2.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=4, pady=4) - demo.balloon['statusbar'] = demo.statusbar - root.mainloop() - -def exit_cmd(event=None): - sys.exit() - -def MkMainMenu(top): - global demo - - w = Tix.Frame(top, bd=2, relief=Tix.RAISED) - file = Tix.Menubutton(w, text='File', underline=0, takefocus=0) - help = Tix.Menubutton(w, text='Help', underline=0, takefocus=0) - file.pack(side=Tix.LEFT) - help.pack(side=Tix.RIGHT) - fm = Tix.Menu(file) - file['menu'] = fm - hm = Tix.Menu(help) - help['menu'] = hm - - fm.add_command(label='Exit', underline=1, accelerator='Ctrl+X', - command=exit_cmd) - hm.add_checkbutton(label='BalloonHelp', underline=0, command=ToggleHelp, - variable=demo.useBalloons) - # The trace variable option doesn't seem to work, instead I use 'command' - #apply(w.tk.call, ('trace', 'variable', demo.useBalloons, 'w', - # ToggleHelp)) - top.bind_all("", exit_cmd) - top.bind_all("", exit_cmd) - return w - -def MkMainNotebook(top): - top.option_add('*TixNoteBook*tagPadX', 6) - top.option_add('*TixNoteBook*tagPadY', 4) - top.option_add('*TixNoteBook*borderWidth', 2) - top.option_add('*TixNoteBook*font', - '-*-helvetica-bold-o-normal-*-14-*-*-*-*-*-*-*') - w = Tix.NoteBook(top, ipadx=5, ipady=5) - w.add('wel', label='Welcome', underline=0, - createcmd=lambda w=w, name='wel': MkWelcome(w, name)) - w.add('cho', label='Choosers', underline=0, - createcmd=lambda w=w, name='cho': MkChoosers(w, name)) - w.add('scr', label='Scrolled Widgets', underline=0, - createcmd=lambda w=w, name='scr': MkScroll(w, name)) - w.add('mgr', label='Manager Widgets', underline=0, - createcmd=lambda w=w, name='mgr': MkManager(w, name)) - w.add('dir', label='Directory List', underline=0, - createcmd=lambda w=w, name='dir': MkDirList(w, name)) - w.add('exp', label='Run Sample Programs', underline=0, - createcmd=lambda w=w, name='exp': MkSample(w, name)) - return w - -def MkMainStatus(top): - global demo - - w = Tix.Frame(top, relief=Tix.RAISED, bd=1) - demo.statusbar = Tix.Label(w, relief=Tix.SUNKEN, bd=1, font='-*-helvetica-medium-r-normal-*-14-*-*-*-*-*-*-*') - demo.statusbar.form(padx=3, pady=3, left=0, right='%70') - return w - -def MkWelcome(nb, name): - w = nb.page(name) - bar = MkWelcomeBar(w) - text = MkWelcomeText(w) - bar.pack(side=Tix.TOP, fill=Tix.X, padx=2, pady=2) - text.pack(side=Tix.TOP, fill=Tix.BOTH, expand=1) - -def MkWelcomeBar(top): - global demo - - w = Tix.Frame(top, bd=2, relief=Tix.GROOVE) - b1 = Tix.ComboBox(w, command=lambda w=top: MainTextFont(w)) - b2 = Tix.ComboBox(w, command=lambda w=top: MainTextFont(w)) - b1.entry['width'] = 15 - b1.slistbox.listbox['height'] = 3 - b2.entry['width'] = 4 - b2.slistbox.listbox['height'] = 3 - - demo.welfont = b1 - demo.welsize = b2 - - b1.insert(Tix.END, 'Courier') - b1.insert(Tix.END, 'Helvetica') - b1.insert(Tix.END, 'Lucida') - b1.insert(Tix.END, 'Times Roman') - - b2.insert(Tix.END, '8') - b2.insert(Tix.END, '10') - b2.insert(Tix.END, '12') - b2.insert(Tix.END, '14') - b2.insert(Tix.END, '18') - - b1.pick(1) - b2.pick(3) - - b1.pack(side=Tix.LEFT, padx=4, pady=4) - 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') - demo.balloon.bind_widget(b2, msg='Point size', - statusmsg='Choose the font size for this page') - return w - -def MkWelcomeText(top): - global demo - - w = Tix.ScrolledWindow(top, scrollbar='auto') - win = w.window - text = 'Welcome to TIX in Python' - title = Tix.Label(win, font='-*-times-bold-r-normal-*-18-*-*-*-*-*-*-*', - bd=0, width=30, anchor=Tix.N, text=text) - msg = Tix.Message(win, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - 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\ -For more information, see http://tix.sourceforge.net.') - title.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10) - msg.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10) - demo.welmsg = msg - return w - -def MainTextFont(w): - global demo - - if not demo.welmsg: - return - font = demo.welfont['value'] - point = demo.welsize['value'] - if font == 'Times Roman': - font = 'times' - fontstr = '-*-%s-bold-r-normal-*-%s-*-*-*-*-*-*-*' % (font, point) - demo.welmsg['font'] = fontstr - -def ToggleHelp(): - if demo.useBalloons.get() == '1': - demo.balloon['state'] = 'both' - else: - demo.balloon['state'] = 'none' - -def MkChoosers(nb, name): - w = nb.page(name) - prefix = Tix.OptionName(w) - if not prefix: - prefix = '' - w.option_add('*' + prefix + '*TixLabelFrame*label.padX', 4) - - til = Tix.LabelFrame(w, label='Chooser Widgets') - cbx = Tix.LabelFrame(w, label='tixComboBox') - ctl = Tix.LabelFrame(w, label='tixControl') - sel = Tix.LabelFrame(w, label='tixSelect') - opt = Tix.LabelFrame(w, label='tixOptionMenu') - fil = Tix.LabelFrame(w, label='tixFileEntry') - fbx = Tix.LabelFrame(w, label='tixFileSelectBox') - tbr = Tix.LabelFrame(w, label='Tool Bar') - - MkTitle(til.frame) - MkCombo(cbx.frame) - MkControl(ctl.frame) - MkSelect(sel.frame) - MkOptMenu(opt.frame) - MkFileEnt(fil.frame) - MkFileBox(fbx.frame) - MkToolBar(tbr.frame) - - # First column: comBox and selector - cbx.form(top=0, left=0, right='%33') - sel.form(left=0, right='&'+str(cbx), top=cbx) - opt.form(left=0, right='&'+str(cbx), top=sel, bottom=-1) - - # Second column: title .. etc - til.form(left=cbx, top=0,right='%66') - ctl.form(left=cbx, right='&'+str(til), top=til) - fil.form(left=cbx, right='&'+str(til), top=ctl) - tbr.form(left=cbx, right='&'+str(til), top=fil, bottom=-1) - - # - # Third column: file selection - fbx.form(right=-1, top=0, left='%66') - -def MkCombo(w): - prefix = Tix.OptionName(w) - if not prefix: prefix = '' - w.option_add('*' + prefix + '*TixComboBox*label.width', 10) - w.option_add('*' + prefix + '*TixComboBox*label.anchor', Tix.E) - w.option_add('*' + prefix + '*TixComboBox*entry.width', 14) - - static = Tix.ComboBox(w, label='Static', editable=0) - editable = Tix.ComboBox(w, label='Editable', editable=1) - history = Tix.ComboBox(w, label='History', editable=1, history=1, - anchor=Tix.E) - static.insert(Tix.END, 'January') - static.insert(Tix.END, 'February') - static.insert(Tix.END, 'March') - static.insert(Tix.END, 'April') - static.insert(Tix.END, 'May') - static.insert(Tix.END, 'June') - static.insert(Tix.END, 'July') - static.insert(Tix.END, 'August') - static.insert(Tix.END, 'September') - static.insert(Tix.END, 'October') - static.insert(Tix.END, 'November') - static.insert(Tix.END, 'December') - - editable.insert(Tix.END, 'Angola') - editable.insert(Tix.END, 'Bangladesh') - editable.insert(Tix.END, 'China') - editable.insert(Tix.END, 'Denmark') - editable.insert(Tix.END, 'Ecuador') - - history.insert(Tix.END, '/usr/bin/ksh') - history.insert(Tix.END, '/usr/local/lib/python') - history.insert(Tix.END, '/var/adm') - - static.pack(side=Tix.TOP, padx=5, pady=3) - editable.pack(side=Tix.TOP, padx=5, pady=3) - history.pack(side=Tix.TOP, padx=5, pady=3) - -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 - elif idx >= len(states): - idx = 0 -# following doesn't work. -# return states[idx] - demo_spintxt.set(states[idx]) # this works - -def spin_validate(w): - global states, demo_spintxt - - try: - i = states.index(demo_spintxt.get()) - except: - return states[0] - return states[i] - # why this procedure works as opposed to the previous one beats me. - -def MkControl(w): - global demo_spintxt - - prefix = Tix.OptionName(w) - if not prefix: prefix = '' - w.option_add('*' + prefix + '*TixControl*label.width', 10) - w.option_add('*' + prefix + '*TixControl*label.anchor', Tix.E) - w.option_add('*' + prefix + '*TixControl*entry.width', 13) - - demo_spintxt = Tix.StringVar() - demo_spintxt.set(states[0]) - simple = Tix.Control(w, label='Numbers') - spintxt = Tix.Control(w, label='States', variable=demo_spintxt) - spintxt['incrcmd'] = lambda w=spintxt: spin_cmd(w, 1) - spintxt['decrcmd'] = lambda w=spintxt: spin_cmd(w, -1) - spintxt['validatecmd'] = lambda w=spintxt: spin_validate(w) - - simple.pack(side=Tix.TOP, padx=5, pady=3) - spintxt.pack(side=Tix.TOP, padx=5, pady=3) - -def MkSelect(w): - prefix = Tix.OptionName(w) - if not prefix: prefix = '' - w.option_add('*' + prefix + '*TixSelect*label.anchor', Tix.CENTER) - w.option_add('*' + prefix + '*TixSelect*orientation', Tix.VERTICAL) - w.option_add('*' + prefix + '*TixSelect*labelSide', Tix.TOP) - - sel1 = Tix.Select(w, label='Mere Mortals', allowzero=1, radio=1) - sel2 = Tix.Select(w, label='Geeks', allowzero=1, radio=0) - - sel1.add('eat', text='Eat') - sel1.add('work', text='Work') - sel1.add('play', text='Play') - sel1.add('party', text='Party') - sel1.add('sleep', text='Sleep') - - sel2.add('eat', text='Eat') - sel2.add('prog1', text='Program') - sel2.add('prog2', text='Program') - sel2.add('prog3', text='Program') - sel2.add('sleep', text='Sleep') - - sel1.pack(side=Tix.LEFT, padx=5, pady=3, fill=Tix.X) - sel2.pack(side=Tix.LEFT, padx=5, pady=3, fill=Tix.X) - -def MkOptMenu(w): - prefix = Tix.OptionName(w) - if not prefix: prefix = '' - w.option_add('*' + prefix + '*TixOptionMenu*label.anchor', Tix.E) - m = Tix.OptionMenu(w, label='File Format : ', options='menubutton.width 15') - m.add_command('text', label='Plain Text') - m.add_command('post', label='PostScript') - m.add_command('format', label='Formatted Text') - m.add_command('html', label='HTML') - m.add_command('sep') - m.add_command('tex', label='LaTeX') - m.add_command('rtf', label='Rich Text Format') - - m.pack(fill=Tix.X, padx=5, pady=3) - -def MkFileEnt(w): - msg = Tix.Message(w, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - 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) - -def MkFileBox(w): - msg = Tix.Message(w, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - relief=Tix.FLAT, width=240, anchor=Tix.N, - text='The TixFileSelectBox 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) - -def MkToolBar(w): - global demo - - prefix = Tix.OptionName(w) - if not prefix: prefix = '' - w.option_add('*' + prefix + '*TixSelect*frame.borderWidth', 1) - msg = Tix.Message(w, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - 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='') - para = Tix.Select(w, allowzero=0, radio=1, label='') - - font.add('bold', bitmap='@' + demo.dir + '/bitmaps/bold.xbm') - font.add('italic', bitmap='@' + demo.dir + '/bitmaps/italic.xbm') - font.add('underline', bitmap='@' + demo.dir + '/bitmaps/underline.xbm') - font.add('capital', bitmap='@' + demo.dir + '/bitmaps/capital.xbm') - - para.add('left', bitmap='@' + demo.dir + '/bitmaps/leftj.xbm') - para.add('right', bitmap='@' + demo.dir + '/bitmaps/rightj.xbm') - para.add('center', bitmap='@' + demo.dir + '/bitmaps/centerj.xbm') - para.add('justify', bitmap='@' + demo.dir + '/bitmaps/justify.xbm') - - msg.pack(side=Tix.TOP, expand=1, fill=Tix.BOTH, padx=3, pady=3) - bar.pack(side=Tix.TOP, fill=Tix.X, padx=3, pady=3) - font.pack({'in':bar}, side=Tix.LEFT, padx=3, pady=3) - para.pack({'in':bar}, side=Tix.LEFT, padx=3, pady=3) - -def MkTitle(w): - prefix = Tix.OptionName(w) - if not prefix: prefix = '' - w.option_add('*' + prefix + '*TixSelect*frame.borderWidth', 1) - msg = Tix.Message(w, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - 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): - w = nb.page(name) - prefix = Tix.OptionName(w) - if not prefix: - prefix = '' - w.option_add('*' + prefix + '*TixLabelFrame*label.padX', 4) - - sls = Tix.LabelFrame(w, label='tixScrolledListBox') - swn = Tix.LabelFrame(w, label='tixScrolledWindow') - stx = Tix.LabelFrame(w, label='tixScrolledText') - - MkSList(sls.frame) - MkSWindow(swn.frame) - MkSText(stx.frame) - - sls.form(top=0, left=0, right='%33', bottom=-1) - swn.form(top=0, left=sls, right='%66', bottom=-1) - stx.form(top=0, left=swn, right=-1, bottom=-1) - -def MkSList(w): - top = Tix.Frame(w, width=300, height=330) - bot = Tix.Frame(w) - msg = Tix.Message(top, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - 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) - list.listbox.insert(Tix.END, 'Alabama') - list.listbox.insert(Tix.END, 'California') - list.listbox.insert(Tix.END, 'Montana') - list.listbox.insert(Tix.END, 'New Jersey') - list.listbox.insert(Tix.END, 'New York') - list.listbox.insert(Tix.END, 'Pennsylvania') - list.listbox.insert(Tix.END, 'Washington') - - rh = Tix.ResizeHandle(top, bg='black', - 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) - btn.pack(anchor=Tix.CENTER) - top.pack(expand=1, fill=Tix.BOTH) - bot.pack(fill=Tix.BOTH) - list.bind('', func=lambda arg=0, rh=rh, list=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) - list.update() - rh.attach_widget(list) - -def MkSWindow(w): - global demo - - top = Tix.Frame(w, width=330, height=330) - bot = Tix.Frame(w) - msg = Tix.Message(top, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - relief=Tix.FLAT, width=200, anchor=Tix.N, - text='The TixScrolledWindow widget allows you to scroll any kind of Tk widget. It is more versatile than a scrolled canvas widget.') - win = Tix.ScrolledWindow(top, scrollbar='auto') - image = Tix.Image('photo', file=demo.dir + "/bitmaps/tix.gif") - lbl = Tix.Label(win.window, image=image) - lbl.pack(expand=1, fill=Tix.BOTH) - - 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) - btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SWindow_reset(w,x)) - top.propagate(0) - msg.pack(fill=Tix.X) - btn.pack(anchor=Tix.CENTER) - top.pack(expand=1, fill=Tix.BOTH) - bot.pack(fill=Tix.BOTH) - win.bind('', func=lambda arg=0, rh=rh, win=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) - win.update() - rh.attach_widget(win) - -def MkSText(w): - top = Tix.Frame(w, width=330, height=330) - bot = Tix.Frame(w) - msg = Tix.Message(top, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - relief=Tix.FLAT, width=200, anchor=Tix.N, - text='The TixScrolledWindow 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, 'This is a text widget embedded in a scrolled window. Although the original Tix demo does not have any text here, I decided to put in some so that you can see the effect of scrollbars etc.') - 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) - btn = Tix.Button(bot, text='Reset', command=lambda w=rh, x=win: SText_reset(w,x)) - top.propagate(0) - msg.pack(fill=Tix.X) - btn.pack(anchor=Tix.CENTER) - top.pack(expand=1, fill=Tix.BOTH) - bot.pack(fill=Tix.BOTH) - win.bind('', func=lambda arg=0, rh=rh, win=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) - win.update() - rh.attach_widget(win) - -def MkManager(nb, name): - w = nb.page(name) - prefix = Tix.OptionName(w) - if not prefix: - prefix = '' - w.option_add('*' + prefix + '*TixLabelFrame*label.padX', 4) - - pane = Tix.LabelFrame(w, label='tixPanedWindow') - note = Tix.LabelFrame(w, label='tixNoteBook') - - MkPanedWindow(pane.frame) - MkNoteBook(note.frame) - - pane.form(top=0, left=0, right=note, bottom=-1) - note.form(top=0, right=-1, bottom=-1) - -def MkPanedWindow(w): - msg = Tix.Message(w, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - 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.Label(w, text='Newsgroup: comp.lang.python') - pane = Tix.PanedWindow(w, orientation='vertical') - - p1 = pane.add('list', min=70, size=100) - p2 = pane.add('text', min=70) - list = Tix.ScrolledListBox(p1) - text = Tix.ScrolledText(p2) - - list.listbox.insert(Tix.END, " 12324 Re: TK is good for your health") - list.listbox.insert(Tix.END, "+ 12325 Re: TK is good for your health") - list.listbox.insert(Tix.END, "+ 12326 Re: Tix is even better for your health (Was: TK is good...)") - list.listbox.insert(Tix.END, " 12327 Re: Tix is even better for your health (Was: TK is good...)") - list.listbox.insert(Tix.END, "+ 12328 Re: Tix is even better for your health (Was: TK is good...)") - list.listbox.insert(Tix.END, " 12329 Re: Tix is even better for your health (Was: TK is good...)") - list.listbox.insert(Tix.END, "+ 12330 Re: Tix is even better for your health (Was: TK is good...)") - - text.text['bg'] = list.listbox['bg'] - text.text['wrap'] = 'none' - text.text.insert(Tix.END, """ -Mon, 19 Jun 1995 11:39:52 comp.lang.tcl Thread 34 of 220 -Lines 353 A new way to put text and bitmaps together iNo responses -ioi@blue.seas.upenn.edu Ioi K. Lam at University of Pennsylvania - -Hi, - -I have implemented a new image type called "compound". It allows you -to glue together a bunch of bitmaps, images and text strings together -to form a bigger image. Then you can use this image with widgets that -support the -image option. For example, you can display a text string string -together with a bitmap, at the same time, inside a TK button widget. -""") - list.pack(expand=1, fill=Tix.BOTH, padx=4, pady=6) - text.pack(expand=1, fill=Tix.BOTH, padx=4, pady=6) - - msg.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH) - group.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH) - pane.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH, expand=1) - -def MkNoteBook(w): - msg = Tix.Message(w, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - 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 + '*TixControl*entry.width', 10) - w.option_add('*' + prefix + '*TixControl*label.width', 18) - w.option_add('*' + prefix + '*TixControl*label.anchor', Tix.E) - w.option_add('*' + prefix + '*TixNoteBook*tagPadX', 8) - - nb = Tix.NoteBook(w, ipadx=6, ipady=6) - nb.add('hard_disk', label="Hard Disk", underline=0) - nb.add('network', label="Network", underline=0) - - # Frame for the buttons that are present on all pages - common = Tix.Frame(nb.hard_disk) - common.pack(side=Tix.RIGHT, padx=2, pady=2, fill=Tix.Y) - CreateCommonButtons(common) - - # Widgets belonging only to this page - a = Tix.Control(nb.hard_disk, value=12, label='Access Time: ') - w = Tix.Control(nb.hard_disk, value=400, label='Write Throughput: ') - r = Tix.Control(nb.hard_disk, value=400, label='Read Throughput: ') - c = Tix.Control(nb.hard_disk, 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) - - common = Tix.Frame(nb.network) - common.pack(side=Tix.RIGHT, padx=2, pady=2, fill=Tix.Y) - CreateCommonButtons(common) - - a = Tix.Control(nb.network, value=12, label='Access Time: ') - w = Tix.Control(nb.network, value=400, label='Write Throughput: ') - r = Tix.Control(nb.network, value=400, label='Read Throughput: ') - c = Tix.Control(nb.network, value=1021, label='Capacity: ') - u = Tix.Control(nb.network, 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) - - msg.pack(side=Tix.TOP, padx=3, pady=3, fill=Tix.BOTH) - nb.pack(side=Tix.TOP, padx=5, pady=5, fill=Tix.BOTH, expand=1) - -def CreateCommonButtons(f): - ok = Tix.Button(f, text='OK', width = 6) - cancel = Tix.Button(f, text='Cancel', width = 6) - ok.pack(side=Tix.TOP, padx=2, pady=2) - cancel.pack(side=Tix.TOP, padx=2, pady=2) - -def MkDirList(nb, name): - w = nb.page(name) - prefix = Tix.OptionName(w) - if not prefix: - prefix = '' - w.option_add('*' + prefix + '*TixLabelFrame*label.padX', 4) - - dir = Tix.LabelFrame(w, label='tixDirList') - fsbox = Tix.LabelFrame(w, label='tixExFileSelectBox') - MkDirListWidget(dir.frame) - MkExFileWidget(fsbox.frame) - dir.form(top=0, left=0, right='%40', bottom=-1) - fsbox.form(top=0, left='%40', right=-1, bottom=-1) - -def MkDirListWidget(w): - msg = Tix.Message(w, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - relief=Tix.FLAT, width=240, anchor=Tix.N, - text='The TixDirList 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) - -def MkExFileWidget(w): - msg = Tix.Message(w, font='-*-helvetica-bold-r-normal-*-14-*-*-*-*-*-*-*', - relief=Tix.FLAT, width=240, anchor=Tix.N, - text='The TixExFileSelectBox 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) - box.pack(side=Tix.TOP, padx=3, pady=3) - -### -### 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', - 'Control' : 'Control', - 'Notebook' : 'NoteBook', - 'Option Menu' : 'OptMenu', - 'Popup Menu' : 'PopMenu', - 'ScrolledHList (1)' : 'SHList1', - 'ScrolledHList (2)' : 'SHList2', - 'Tree (dynamic)' : 'Tree' -} - -stypes = {} -stypes['widget'] = ['Balloon', 'Button Box', 'Combo Box', 'Control', - 'Notebook', 'Option Menu', 'Popup Menu', - 'ScrolledHList (1)', 'ScrolledHList (2)', 'Tree (dynamic)'] -stypes['image'] = ['Compound Image'] - -def MkSample(nb, name): - w = nb.page(name) - prefix = Tix.OptionName(w) - if not prefix: - prefix = '' - w.option_add('*' + prefix + '*TixLabelFrame*label.padX', 4) - - lab = Tix.Label(w, text='Select a sample program:', anchor=Tix.W) - lab1 = Tix.Label(w, text='Source:', anchor=Tix.W) - - slb = Tix.ScrolledHList(w, options='listbox.exportSelection 0') - slb.hlist['command'] = lambda args=0, w=w,slb=slb: Sample_Action(w, slb, 'run') - slb.hlist['browsecmd'] = lambda args=0, w=w,slb=slb: Sample_Action(w, slb, 'browse') - - stext = Tix.ScrolledText(w, name='stext') - stext.text.bind('<1>', stext.text.focus()) - stext.text.bind('', lambda w=stext.text: w.yview(scroll='-1 unit')) - stext.text.bind('', lambda w=stext.text: w.yview(scroll='1 unit')) - stext.text.bind('', lambda w=stext.text: w.xview(scroll='-1 unit')) - stext.text.bind('', lambda w=stext.text: w.xview(scroll='1 unit')) - - run = Tix.Button(w, text='Run ...', name='run', command=lambda args=0, w=w,slb=slb: Sample_Action(w, slb, 'run')) - view = Tix.Button(w, text='View Source ...', name='view', command=lambda args=0,w=w,slb=slb: Sample_Action(w, slb, 'view')) - - lab.form(top=0, left=0, right='&'+str(slb)) - slb.form(left=0, top=lab, bottom=-4) - lab1.form(left='&'+str(stext), top=0, right='&'+str(stext), bottom=stext) - run.form(left=str(slb)+' 30', bottom=-4) - view.form(left=run, bottom=-4) - stext.form(bottom=str(run)+' -5', left='&'+str(run), right='-0', top='&'+str(slb)) - - stext.text['bg'] = slb.hlist['bg'] - stext.text['state'] = 'disabled' - stext.text['wrap'] = 'none' - #XXX stext.text['font'] = fixed_font - - slb.hlist['separator'] = '.' - slb.hlist['width'] = 25 - slb.hlist['drawbranch'] = 0 - slb.hlist['indent'] = 10 - slb.hlist['wideselect'] = 1 - - 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) - slb.hlist.selection_clear() - - run['state'] = 'disabled' - view['state'] = 'disabled' - -def Sample_Action(w, slb, action): - global demo - - run = w._nametowidget(str(w) + '.run') - view = w._nametowidget(str(w) + '.view') - stext = w._nametowidget(str(w) + '.stext') - - hlist = slb.hlist - anchor = hlist.info_anchor() - if not anchor: - run['state'] = 'disabled' - view['state'] = 'disabled' - elif not hlist.info_parent(anchor): - # a comment - return - - run['state'] = 'normal' - view['state'] = 'normal' - key = hlist.info_data(anchor) - title = key - prog = samples[key] - - if action == 'run': - 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') - elif action == 'browse': - ReadFile(stext.text, demo.dir + '/samples/' + prog + '.py') - -def LoadFile(w, fname): - b = Tix.Button(w, text='Close', command=w.destroy) - t = Tix.ScrolledText(w) - # b.form(left=0, bottom=0, padx=4, pady=4) - # t.form(left=0, bottom=b, right='-0', top=0) - t.pack() - b.pack() - - t.text['highlightcolor'] = t['bg'] - t.text['bd'] = 2 - t.text['bg'] = t['bg'] - t.text['wrap'] = 'none' - - ReadFile(t.text, fname) - -def ReadFile(w, fname): - old_state = w['state'] - w['state'] = 'normal' - w.delete('0.0', Tix.END) - - try: - 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 - -if __name__ == '__main__': - main() - diff --git a/Demo/tkinter/README b/Demo/tkinter/README deleted file mode 100644 index 9fa7cb4e24..0000000000 --- a/Demo/tkinter/README +++ /dev/null @@ -1,11 +0,0 @@ -Several collections of example code for Tkinter. - -See the toplevel README for an explanation of the difference between -Tkinter and _tkinter, how to enable the Python Tk interface, and where -to get Matt Conway's lifesaver document. - -Subdirectories: - -guido my original example set (fairly random collection) -matt Matt Conway's examples, to go with his lifesaver document -www a progressing sequence of www clients using Tk diff --git a/Demo/tkinter/Tree.py b/Demo/tkinter/Tree.py deleted file mode 100644 index 010fbd4796..0000000000 --- a/Demo/tkinter/Tree.py +++ /dev/null @@ -1,23 +0,0 @@ -from Tkinter import * - -class Tree: - - def __init__(self, master, cnf = {}): - self.master = master - self.outerframe = Frame(self.master, - {'name': 'outerframe', - Pack: {}, - }) - self.innerframe = Frame(self.outerframe, - {'name': 'innerframe', - Pack: {'side': 'left', - 'fill': 'y'}, - }) - self.button = Menubutton(self.innerframe, - {'name': 'button', - Pack: {}, - }) - # menu? - - def addchild(self): - return Tree(self.outerframe, {}) diff --git a/Demo/tkinter/guido/AttrDialog.py b/Demo/tkinter/guido/AttrDialog.py deleted file mode 100755 index 4878cb5197..0000000000 --- a/Demo/tkinter/guido/AttrDialog.py +++ /dev/null @@ -1,452 +0,0 @@ - -# The options of a widget are described by the following attributes -# of the Pack and Widget dialogs: -# -# Dialog.current: {name: value} -# -- changes during Widget's lifetime -# -# Dialog.options: {name: (default, klass)} -# -- depends on widget class only -# -# Dialog.classes: {klass: (v0, v1, v2, ...) | 'boolean' | 'other'} -# -- totally static, though different between PackDialog and WidgetDialog -# (but even that could be unified) - -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 - -class BooleanOption(Option): - - 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) - -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) - -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('', self.set) - -class ReadonlyOption(Option): - - 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 - -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', - } - -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 - -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, - } - -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 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() - -def remotetest(root, app): - from listtree import listtree - list = listtree(root, app) - list.bind('', 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 - -test() diff --git a/Demo/tkinter/guido/ManPage.py b/Demo/tkinter/guido/ManPage.py deleted file mode 100755 index ccd21b4f7e..0000000000 --- a/Demo/tkinter/guido/ManPage.py +++ /dev/null @@ -1,220 +0,0 @@ -# Widget to display a man page - -import regex -from Tkinter import * -from Tkinter import _tkinter -from ScrolledText import ScrolledText - -# XXX These fonts may have to be changed to match your system -BOLDFONT = '*-Courier-Bold-R-Normal-*-120-*' -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') -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()) - -# 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) - -# Alias -ManPage = ReadonlyManPage - -# Test program. -# 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() - -# Run the test program when called as a script -if __name__ == '__main__': - test() diff --git a/Demo/tkinter/guido/MimeViewer.py b/Demo/tkinter/guido/MimeViewer.py deleted file mode 100755 index 2b98579810..0000000000 --- a/Demo/tkinter/guido/MimeViewer.py +++ /dev/null @@ -1,143 +0,0 @@ -#! /usr/bin/env python - -# View a single MIME multipart message. -# Display each part as a box. - -import string -from types import * -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 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 - -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) - - mh = mhlib.MH() - f = mh.openfolder(folder) - if not message: - message = f.getcurrent() - m = f.openmessage(message) - - root = Tk() - tk = root.tk - - top = MimeViewer(root, '+%s/%d' % (folder, message), m) - top.pack() - top.show() - - root.minsize(1, 1) - - tk.mainloop() - -if __name__ == '__main__': main() diff --git a/Demo/tkinter/guido/ShellWindow.py b/Demo/tkinter/guido/ShellWindow.py deleted file mode 100755 index 98fe30f70d..0000000000 --- a/Demo/tkinter/guido/ShellWindow.py +++ /dev/null @@ -1,151 +0,0 @@ -import os -import sys -import string -from Tkinter import * -from ScrolledText import ScrolledText -from Dialog import Dialog -import signal - -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('', self.inputhandler) - self.bind('', self.sigint) - self.bind('', self.sigterm) - self.bind('', self.sigkill) - self.bind('', 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 - -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() - -if __name__ == '__main__': - test() diff --git a/Demo/tkinter/guido/brownian.py b/Demo/tkinter/guido/brownian.py deleted file mode 100644 index 8007f141cb..0000000000 --- a/Demo/tkinter/guido/brownian.py +++ /dev/null @@ -1,50 +0,0 @@ -# Brownian motion -- an example of a multi-threaded Tkinter program. - -from Tkinter import * -import random -import threading -import time -import sys - -WIDTH = 400 -HEIGHT = 300 -SIGMA = 10 -BUZZ = 2 -RADIUS = 2 -LAMBDA = 10 -FILL = 'red' - -stop = 0 # Set when main loop exits - -def particle(canvas): - r = RADIUS - x = random.gauss(WIDTH/2.0, SIGMA) - y = random.gauss(HEIGHT/2.0, SIGMA) - p = canvas.create_oval(x-r, y-r, x+r, y+r, fill=FILL) - while not stop: - dx = random.gauss(0, BUZZ) - dy = random.gauss(0, BUZZ) - dt = random.expovariate(LAMBDA) - try: - canvas.move(p, dx, dy) - except TclError: - break - time.sleep(dt) - -def main(): - global stop - root = Tk() - canvas = Canvas(root, width=WIDTH, height=HEIGHT) - canvas.pack(fill='both', expand=1) - np = 30 - if sys.argv[1:]: - np = int(sys.argv[1]) - for i in range(np): - t = threading.Thread(target=particle, args=(canvas,)) - t.start() - try: - root.mainloop() - finally: - stop = 1 - -main() diff --git a/Demo/tkinter/guido/canvasevents.py b/Demo/tkinter/guido/canvasevents.py deleted file mode 100644 index 60f409659b..0000000000 --- a/Demo/tkinter/guido/canvasevents.py +++ /dev/null @@ -1,244 +0,0 @@ -#! /usr/bin/env python - -from Tkinter import * -from Canvas import Oval, Group, CanvasText - - -# Fix a bug in Canvas.Group as distributed in Python 1.4. The -# distributed bind() method is broken. This is what should be used: - -class Group(Group): - def bind(self, sequence=None, command=None): - return self.canvas.tag_bind(self.id, sequence, command) - -class Object: - - """Base class for composite graphical objects. - - Objects belong to a canvas, and can be moved around on the canvas. - They also belong to at most one ``pile'' of objects, and can be - transferred between piles (or removed from their pile). - - Objects have a canonical ``x, y'' position which is moved when the - object is moved. Where the object is relative to this position - depends on the object; for simple objects, it may be their center. - - Objects have mouse sensitivity. They can be clicked, dragged and - double-clicked. The behavior may actually determined by the pile - they are in. - - All instance attributes are public since the derived class may - need them. - - """ - - 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) - - def __str__(self): - 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) - - 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 - - def moveto(self, x, 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) - - def tkraise(self): - self.group.tkraise() - - -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) - - -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() - - def bindhandlers(self): - self.group.bind('<1>', self.clickhandler) - self.group.bind('', self.doubleclickhandler) - - def add(self, 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) - - def position(self, object): - object.tkraise() - i = self.objects.index(object) - object.moveto(self.x + i*4, self.y + i*8) - - def clickhandler(self, event): - pass - - def doubleclickhandler(self, event): - pass - - -class MovingPile(Pile): - - def bindhandlers(self): - Pile.bindhandlers(self) - self.group.bind('', self.motionhandler) - self.group.bind('', 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 - - 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) - - def releasehandler(self, event): - objects = self.movethis - if not objects: - return - self.movethis = None - self.finishmove(objects) - - def finishmove(self, objects): - for o in objects: - self.position(o) - - -class Pile1(MovingPile): - - x = 50 - y = 50 - tag = 'p1' - - def __init__(self, demo): - 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) - - def other(self): - 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) - -class Pile2(Pile1): - - x = 150 - y = 50 - tag = 'p2' - - def other(self): - 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) - - -# Main function, run when invoked as a stand-alone Python program. - -def main(): - root = Tk() - demo = Demo(root) - root.protocol('WM_DELETE_WINDOW', root.quit) - root.mainloop() - -if __name__ == '__main__': - main() diff --git a/Demo/tkinter/guido/dialog.py b/Demo/tkinter/guido/dialog.py deleted file mode 100755 index 1f794ae22a..0000000000 --- a/Demo/tkinter/guido/dialog.py +++ /dev/null @@ -1,109 +0,0 @@ -#! /usr/bin/env python - -# A Python function that generates dialog boxes with a text message, -# optional bitmap, and any number of buttons. -# Cf. Ousterhout, Tcl and the Tk Toolkit, Figs. 27.2-3, pp. 269-270. - -from Tkinter import * -import sys - - -def dialog(master, title, text, bitmap, default, *args): - - # 1. Create the top-level window and divide it into top - # and bottom parts. - - w = Toplevel(master, class_='Dialog') - w.title(title) - w.iconname('Dialog') - - top = Frame(w, relief=RAISED, borderwidth=1) - top.pack(side=TOP, fill=BOTH) - bot = Frame(w, relief=RAISED, borderwidth=1) - bot.pack(side=BOTTOM, fill=BOTH) - - # 2. Fill the top part with the bitmap and message. - - msg = Message(top, width='3i', text=text, - 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') - - # 3. Create a row of buttons at the bottom of the dialog. - - var = IntVar() - 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 - - # 4. Set up a binding for , if there's a default, - # set a grab, and claim the focus too. - - if default >= 0: - w.bind('', - lambda e, b=buttons[default], v=var, i=default: - (b.flash(), - v.set(i))) - - oldFocus = w.focus_get() - w.grab_set() - w.focus_set() - - # 5. Wait for the user to respond, then restore the focus - # and return the index of the selected button. - - w.waitvar(var) - w.destroy() - if oldFocus: oldFocus.focus_set() - return var.get() - -# The rest is the test program. - -def go(): - i = dialog(mainWidget, - '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') - print 'pressed button', i - -def test(): - import sys - global mainWidget - mainWidget = Frame() - Pack.config(mainWidget) - start = Button(mainWidget, text='Press Here To Start', command=go) - start.pack() - endit = Button(mainWidget, text="Exit", command=sys.exit) - endit.pack(fill=BOTH) - mainWidget.mainloop() - -if __name__ == '__main__': - test() diff --git a/Demo/tkinter/guido/electrons.py b/Demo/tkinter/guido/electrons.py deleted file mode 100755 index 97dad2d733..0000000000 --- a/Demo/tkinter/guido/electrons.py +++ /dev/null @@ -1,91 +0,0 @@ -#! /usr/bin/env python - -# Simulate "electrons" migrating across the screen. -# An optional bitmap file in can be in the background. -# -# Usage: electrons [n [bitmapfile]] -# -# n is the number of electrons to animate; default is 30. -# -# The bitmap file can be any X11 bitmap file (look in -# /usr/include/X11/bitmaps for samples); it is displayed as the -# background of the animation. Default is no bitmap. - -from Tkinter import * -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 - - -# Main program -def main(): - import sys, string - - # 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 - - # Create the graphical objects... - h = Electrons(n, bitmap) - - # ...and run! - h.run() - - -# Call main when run as script -if __name__ == '__main__': - main() diff --git a/Demo/tkinter/guido/hanoi.py b/Demo/tkinter/guido/hanoi.py deleted file mode 100755 index 9e566c4a30..0000000000 --- a/Demo/tkinter/guido/hanoi.py +++ /dev/null @@ -1,154 +0,0 @@ -# Animated Towers of Hanoi using Tk with optional bitmap file in -# background. -# -# Usage: tkhanoi [n [bitmapfile]] -# -# n is the number of pieces to animate; default is 4, maximum 15. -# -# The bitmap file can be any X11 bitmap file (look in -# /usr/include/X11/bitmaps for samples); it is displayed as the -# background of the animation. Default is no bitmap. - -# This uses Steen Lumholt's Tk interface -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) - - -# 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) - - -# Main program -def main(): - import sys, string - - # 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 - - # Create the graphical objects... - h = Tkhanoi(n, bitmap) - - # ...and run! - h.run() - - -# Call main when run as script -if __name__ == '__main__': - main() diff --git a/Demo/tkinter/guido/hello.py b/Demo/tkinter/guido/hello.py deleted file mode 100755 index 237204fab8..0000000000 --- a/Demo/tkinter/guido/hello.py +++ /dev/null @@ -1,17 +0,0 @@ -# Display hello, world in a button; clicking it quits the program - -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() - -def quit_callback(): - sys.exit(0) - -main() diff --git a/Demo/tkinter/guido/imagedraw.py b/Demo/tkinter/guido/imagedraw.py deleted file mode 100755 index d3dba4565c..0000000000 --- a/Demo/tkinter/guido/imagedraw.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Draw on top of an image""" - -from Tkinter import * -import sys - -def main(): - filename = sys.argv[1] - root = Tk() - img = PhotoImage(file=filename) - w, h = img.width(), img.height() - canv = Canvas(root, width=w, height=h) - canv.create_image(0, 0, anchor=NW, image=img) - canv.pack() - canv.bind('', blob) - root.mainloop() - -def blob(event): - x, y = event.x, event.y - canv = event.widget - r = 5 - canv.create_oval(x-r, y-r, x+r, y+r, fill='red', outline="") - -main() diff --git a/Demo/tkinter/guido/imageview.py b/Demo/tkinter/guido/imageview.py deleted file mode 100755 index d6efed0b2b..0000000000 --- a/Demo/tkinter/guido/imageview.py +++ /dev/null @@ -1,12 +0,0 @@ -from Tkinter import * -import sys - -def main(): - filename = sys.argv[1] - root = Tk() - img = PhotoImage(file=filename) - label = Label(root, image=img) - label.pack() - root.mainloop() - -main() diff --git a/Demo/tkinter/guido/kill.py b/Demo/tkinter/guido/kill.py deleted file mode 100755 index 577af8b8b8..0000000000 --- a/Demo/tkinter/guido/kill.py +++ /dev/null @@ -1,99 +0,0 @@ -#! /usr/bin/env python -# Tkinter interface to Linux `kill' command. - -from Tkinter import * -from string import splitfields -from string import split -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 - -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('', self.do_motion) - self.frame.list.bind('', 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() - diff --git a/Demo/tkinter/guido/listtree.py b/Demo/tkinter/guido/listtree.py deleted file mode 100755 index 523f2096db..0000000000 --- a/Demo/tkinter/guido/listtree.py +++ /dev/null @@ -1,37 +0,0 @@ -# List a remote app's widget tree (names and classes only) - -import sys -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 - -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) - -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 __name__ == '__main__': - main() diff --git a/Demo/tkinter/guido/mbox.py b/Demo/tkinter/guido/mbox.py deleted file mode 100755 index 9aea7ee5b1..0000000000 --- a/Demo/tkinter/guido/mbox.py +++ /dev/null @@ -1,285 +0,0 @@ -#! /usr/bin/env python - -# Scan MH folder, display results in window - -import os -import sys -import regex -import getopt -import string -import mhlib - -from Tkinter import * - -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 - - 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 - - mh = mhlib.MH() - mhf = mh.openfolder(folder) - - # Build widget hierarchy - - root = Tk() - tk = root.tk - - top = Frame(root) - top.pack({'expand': 1, 'fill': 'both'}) - - # Build right part: folder list - - right = Frame(top) - right.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'}) - - foldermenu = Menu(root) - foldermenu.add('command', - {'label': 'Open Folder', - 'command': open_folder}) - foldermenu.add('separator') - foldermenu.add('command', - {'label': 'Quit', - 'command': 'exit'}) - foldermenu.bind('', folder_unpost) - - folderbox['yscrollcommand'] = (folderbar, 'set') - folderbar['command'] = (folderbox, 'yview') - folderbox.bind('', open_folder, 1) - folderbox.bind('<3>', folder_post) - - # Build left part: scan list - - left = Frame(top) - left.pack({'expand': 1, 'fill': 'both', 'side': 'left'}) - - 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'}) - - 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('', scan_unpost) - - scanbox['yscrollcommand'] = (scanbar, 'set') - scanbar['command'] = (scanbox, 'yview') - scanbox.bind('', open_message) - scanbox.bind('<3>', scan_post) - - # Separator between middle and bottom part - - rule2 = Frame(root, {'bg': 'black'}) - rule2.pack({'fill': 'x'}) - - # Build bottom part: current message - - bot = Frame(root) - bot.pack({'expand': 1, 'fill': 'both'}) - # - viewer = None - - # Window manager commands - - root.minsize(800, 1) # Make window resizable - - # Fill folderbox with text - - setfolders() - - # Fill scanbox with text - - rescan() - - # Enter mainloop - - root.mainloop() - -def folder_post(e): - 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') - -def scan_post(e): - 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') - -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() - -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 - -def interestingheader(header): - 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) - -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) - -def fixfocus(near, itop): - n = scanbox.size() - for i in range(n): - line = scanbox.get(`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) - -def rescan(): - 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()) - -main() diff --git a/Demo/tkinter/guido/newmenubardemo.py b/Demo/tkinter/guido/newmenubardemo.py deleted file mode 100644 index cafbf63ef8..0000000000 --- a/Demo/tkinter/guido/newmenubardemo.py +++ /dev/null @@ -1,47 +0,0 @@ -#! /usr/bin/env python - -"""Play with the new Tk 8.0 toplevel menu option.""" - -from Tkinter import * - -class App: - - def __init__(self, master): - self.master = 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.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.top = Toplevel(menu=self.menubar) - - # Rest of app goes here... - -def main(): - root = Tk() - root.withdraw() - app = App(root) - root.mainloop() - -if __name__ == '__main__': - main() diff --git a/Demo/tkinter/guido/optionmenu.py b/Demo/tkinter/guido/optionmenu.py deleted file mode 100644 index be9d3ac2a6..0000000000 --- a/Demo/tkinter/guido/optionmenu.py +++ /dev/null @@ -1,27 +0,0 @@ -# option menu sample (Fredrik Lundh, September 1997) - -from Tkinter import * - -root = Tk() - -# -# standard usage - -var1 = StringVar() -var1.set("One") # default selection - -menu1 = OptionMenu(root, var1, "One", "Two", "Three") -menu1.pack() - -# -# initialize from a sequence - -CHOICES = "Aah", "Bee", "Cee", "Dee", "Eff" - -var2 = StringVar() -var2.set(CHOICES[0]) - -menu2 = apply(OptionMenu, (root, var2) + tuple(CHOICES)) -menu2.pack() - -root.mainloop() diff --git a/Demo/tkinter/guido/paint.py b/Demo/tkinter/guido/paint.py deleted file mode 100644 index 743d500d2b..0000000000 --- a/Demo/tkinter/guido/paint.py +++ /dev/null @@ -1,60 +0,0 @@ -""""Paint program by Dave Michell. - -Subject: tkinter "paint" example -From: Dave Mitchell -To: python-list@cwi.nl -Date: Fri, 23 Jan 1998 12:18:05 -0500 (EST) - - Not too long ago (last week maybe?) someone posted a request -for an example of a paint program using Tkinter. Try as I might -I can't seem to find it in the archive, so i'll just post mine -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 -options like other shapes or colors... - - yours, - dave mitchell - davem@magnet.com -""" - -from Tkinter import * - -"""paint.py: not exactly a paint program.. just a smooth line drawing demo.""" - -b1 = "up" -xold, yold = None, None - -def main(): - root = Tk() - drawing_area = Canvas(root) - drawing_area.pack() - drawing_area.bind("", motion) - drawing_area.bind("", b1down) - drawing_area.bind("", 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- - -def b1up(event): - 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 __name__ == "__main__": - main() diff --git a/Demo/tkinter/guido/rmt.py b/Demo/tkinter/guido/rmt.py deleted file mode 100755 index 6e9a8288fa..0000000000 --- a/Demo/tkinter/guido/rmt.py +++ /dev/null @@ -1,159 +0,0 @@ -#! /usr/bin/env python - -# A Python program implementing rmt, an application for remotely -# controlling other Tk applications. -# Cf. Ousterhout, Tcl and the Tk Toolkit, Figs. 27.5-8, pp. 273-276. - -# Note that because of forward references in the original, we -# sometimes delay bindings until after the corresponding procedure is -# defined. We also introduce names for some unnamed code blocks in -# the original because of restrictions on lambda forms in Python. - -# XXX This should be written in a more Python-like style!!! - -from Tkinter import * -import sys - -# 1. Create basic application structure: menu bar on top of -# text widget, scrollbar on right. - -root = Tk() -tk = root.tk -mBar = Frame(root, relief=RAISED, borderwidth=2) -mBar.pack(fill=X) - -f = Frame(root) -f.pack(expand=1, fill=BOTH) -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-*') -s['command'] = t.yview - -root.title('Tk Remote Controller') -root.iconname('Tk Remote') - -# 2. Create menu button and menus. - -file = Menubutton(mBar, text='File', underline=0) -file.pack(side=LEFT) -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) -file_m.add_command(label='Quit', underline=0, command=sys.exit) - -# 3. Create bindings for text widget to allow commands to be -# entered and information to be selected. New characters -# can only be added at the end of the text (can't ever move -# 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 -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)) -t.bind('', double1) - -def triple1(e): - x = e.x - y = e.y - t.setvar('tk_priv(selectMode)', 'line') - t.tk_textSelectTo(At(x, y)) -t.bind('', triple1) - -def returnkey(e): - t.insert(AtInsert(), '\n') - invoke() -t.bind('', returnkey) - -def controlv(e): - t.insert(AtInsert(), t.selection_get()) - t.yview_pickplace(AtInsert()) - if t.index(AtInsert())[-2:] == '.0': - invoke() -t.bind('', 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()) -t.bind('', backspace) -t.bind('', backspace) -t.bind('', backspace) - - -# 5. Procedure that's invoked when return is typed: if -# there's not yet a complete command (e.g. braces are open) -# then do nothing. Otherwise, execute command (locally or -# remotely), output the result or error message, and issue -# 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()) - -def prompt(): - 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') - -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['postcommand'] = fillAppsMenu -mBar.tk_menuBar(file) - -# 7. Miscellaneous initialization. - -app = root.winfo_name() -prompt() -t.focus() - -root.mainloop() diff --git a/Demo/tkinter/guido/solitaire.py b/Demo/tkinter/guido/solitaire.py deleted file mode 100755 index bd7328da59..0000000000 --- a/Demo/tkinter/guido/solitaire.py +++ /dev/null @@ -1,637 +0,0 @@ -#! /usr/bin/env python - -"""Solitaire game, much like the one that comes with MS Windows. - -Limitations: - -- No cute graphical images for the playing cards faces or backs. -- No scoring or timer. -- No undo. -- No option to turn 3 cards at a time. -- 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 -at times be a little unusual. If you have suggestions, please let me -know! - -""" - -# Imports - -import math -import random - -from Tkinter import * -from Canvas import Rectangle, CanvasText, Group, Window - - -# Fix a bug in Canvas.Group as distributed in Python 1.4. The -# distributed bind() method is broken. Rather than asking you to fix -# the source, we fix it here by deriving a subclass: - -class Group(Group): - def bind(self, sequence=None, command=None): - return self.canvas.tag_bind(self.id, sequence, command) - - -# Constants determining the size and lay-out of cards and stacks. We -# work in a "grid" where each card/stack is surrounded by MARGIN -# pixels of space on each side, so adjacent stacks are separated by -# 2*MARGIN pixels. OFFSET is the offset used for displaying the -# face down cards in the row stacks. - -CARDWIDTH = 100 -CARDHEIGHT = 150 -MARGIN = 10 -XSPACING = CARDWIDTH + 2*MARGIN -YSPACING = CARDHEIGHT + 4*MARGIN -OFFSET = 5 - -# The background color, green to look like a playing table. The -# standard green is way too bright, and dark green is way to dark, so -# we use something in between. (There are a few more colors that -# could be customized, but they are less controversial.) - -BACKGROUND = '#070' - - -# Suits and colors. The values of the symbolic suit names are the -# strings used to display them (you change these and VALNAMES to -# internationalize the game). The COLOR dictionary maps suit names to -# colors (red and black) which must be Tk color names. The keys() of -# the COLOR dictionary conveniently provides us with a list of all -# suits (in arbitrary order). - -HEARTS = 'Heart' -DIAMONDS = 'Diamond' -CLUBS = 'Club' -SPADES = 'Spade' - -RED = 'red' -BLACK = 'black' - -COLOR = {} -for s in (HEARTS, DIAMONDS): - COLOR[s] = RED -for s in (CLUBS, SPADES): - COLOR[s] = BLACK - -ALLSUITS = COLOR.keys() -NSUITS = len(ALLSUITS) - - -# Card values are 1-13. We also define symbolic names for the picture -# cards. ALLVALUES is a list of all card values. - -ACE = 1 -JACK = 11 -QUEEN = 12 -KING = 13 -ALLVALUES = range(1, 14) # (one more than the highest value) -NVALUES = len(ALLVALUES) - - -# VALNAMES is a list that maps a card value to string. It contains a -# dummy element at index 0 so it can be indexed directly with the card -# value. - -VALNAMES = ["", "A"] + map(str, range(2, 11)) + ["J", "Q", "K"] - - -# Solitaire constants. The only one I can think of is the number of -# row stacks. - -NROWS = 7 - - -# The rest of the program consists of class definitions. These are -# further described in their documentation strings. - - -class Card: - - """A playing card. - - A card doesn't record to which stack it belongs; only the stack - records this (it turns out that we always know this from the - context, and this saves a ``double update'' with potential for - inconsistencies). - - Public methods: - - moveto(x, y) -- move the card to an absolute position - moveby(dx, dy) -- move the card by a relative offset - tkraise() -- raise the card to the top of its stack - showface(), showback() -- turn the card face up or down & raise it - - Public read-only instance variables: - - suit, value, color -- the card's suit, value and color - face_shown -- true when the card is shown face up, else false - - 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 - - Private instance variables: - - __back, __rect, __text -- the canvas items making up the card - - (To show the card face up, the text item is placed in front of - rect and the back is placed behind it. To show it face down, this - is reversed. The card is created face down.) - - """ - - def __init__(self, suit, value, canvas): - """Card constructor. - - 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). - - """ - self.suit = suit - self.value = value - self.color = COLOR[suit] - self.face_shown = 0 - - 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) - - 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) - - def __repr__(self): - """Return a string for debug print statements.""" - return "Card(%s, %s)" % (`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) - - 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) - - def tkraise(self): - """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 - - def showback(self): - """Turn the card's face down.""" - self.tkraise() - self.__rect.tkraise() - self.__back.tkraise() - self.face_shown = 0 - - -class Stack: - - """A generic stack of cards. - - This is used as a base class for all other stacks (e.g. the deck, - the suit stacks, and the row stacks). - - Public methods: - - add(card) -- add a card to the stack - delete(card) -- delete a card from the stack - showtop() -- show the top card (if any) face up - deal() -- delete and return the top card, or None if empty - - Method that subclasses may override: - - position(card) -- move the card to its proper (x, y) position - - The default position() method places all cards at the stack's - own (x, y) position. - - userclickhandler(), userdoubleclickhandler() -- called to do - subclass specific things on single and double clicks - - The default user (single) click handler shows the top card - face up. The default user double click handler calls the user - single click handler. - - usermovehandler(cards) -- called to complete a subpile move - - The default user move handler moves all moved cards back to - their original position (by calling the position() method). - - Private methods: - - clickhandler(event), doubleclickhandler(event), - motionhandler(event), releasehandler(event) -- event handlers - - 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('', self.doubleclickhandler) - self.group.bind('', self.motionhandler) - self.group.bind('', self.releasehandler) - self.makebottom() - - def makebottom(self): - pass - - def __repr__(self): - """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) - - def delete(self, card): - self.cards.remove(card) - card.group.dtag(self.group) - - def showtop(self): - 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 - - # Subclass overridable methods - - def position(self, card): - card.moveto(self.x, self.y) - - def userclickhandler(self): - self.showtop() - - def userdoubleclickhandler(self): - self.userclickhandler() - - def usermovehandler(self, cards): - 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) - - def motionhandler(self, event): - self.keepmoving(event) - - def releasehandler(self, event): - self.keepmoving(event) - self.finishmoving() - - def doubleclickhandler(self, 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() - - 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) - - def finishmoving(self): - cards = self.moving - self.moving = None - if cards: - self.usermovehandler(cards) - - -class Deck(Stack): - - """The deck is a stack with support for shuffling. - - New methods: - - fill() -- create the playing cards - shuffle() -- shuffle the playing cards - - A single click moves the top card to the game's open deck and - moves it face up; if we're out of cards, it moves the open deck - back to the deck. - - """ - - 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) - - def fill(self): - 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 - - 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() - - -def randperm(n): - """Function returning a random permutation of range(n).""" - r = range(n) - x = [] - while r: - i = random.choice(r) - x.append(i) - r.remove(i) - return x - - -class OpenStack(Stack): - - def acceptable(self, cards): - 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() - - 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 - - -class SuitStack(OpenStack): - - def makebottom(self): - bottom = Rectangle(self.game.canvas, - self.x, self.y, - self.x+CARDWIDTH, self.y+CARDHEIGHT, - outline='black', fill='') - - def userclickhandler(self): - pass - - def userdoubleclickhandler(self): - 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 - - -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 - - 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) - - -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() - - def wincheck(self): - 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) - - 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() - - 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 - - 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() - - def reset(self): - 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. - -def main(): - root = Tk() - game = Solitaire(root) - root.protocol('WM_DELETE_WINDOW', root.quit) - root.mainloop() - -if __name__ == '__main__': - main() diff --git a/Demo/tkinter/guido/sortvisu.py b/Demo/tkinter/guido/sortvisu.py deleted file mode 100644 index 6fe40024b3..0000000000 --- a/Demo/tkinter/guido/sortvisu.py +++ /dev/null @@ -1,634 +0,0 @@ -#! /usr/bin/env python - -"""Sorting algorithms visualizer using Tkinter. - -This module is comprised of three ``components'': - -- an array visualizer with methods that implement basic sorting -operations (compare, swap) as well as methods for ``annotating'' the -sorting algorithm (e.g. to show the pivot element); - -- a number of sorting algorithms (currently quicksort, insertion sort, -selection sort and bubble sort, as well as a randomization function), -all using the array visualizer for its basic operations and with calls -to its annotation methods; - -- and a ``driver'' class which can be used as a Grail applet or as a -stand-alone application. - -""" - - -from Tkinter import * -from Canvas import Line, Rectangle -import random - - -XGRID = 10 -YGRID = 10 -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) - - 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) - - speed = "normal" - - def setspeed(self, speed): - self.speed = speed - - def destroy(self): - self.frame.destroy() - - in_mainloop = 0 - stop_mainloop = 0 - - def cancel(self): - self.stop_mainloop = 1 - if self.in_mainloop: - self.master.quit() - - def step(self): - if self.in_mainloop: - self.master.quit() - - 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 - - def getsize(self): - 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() - - def hide_partition(self): - 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() - - 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() - - def hide_left_right_pivot(self): - self.hide_left() - self.hide_right() - self.hide_pivot() - - def hide_left(self): - self.left.coords(((0, 0), (0, 0))) - - def hide_right(self): - 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))) - - def hide_pivot(self): - 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) - - def compare(self, i, j): - 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() - - def message(self, msg): - self.label.config(text=msg) - - def countswap(self): - self.nswaps = self.nswaps + 1 - self.updatereport() - - def countcompare(self): - self.ncompares = self.ncompares + 1 - self.updatereport() - - def updatereport(self): - 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('', self.mouse_down) - self.item.bind('', self.mouse_move) - self.item.bind('', self.mouse_up) - - def delete(self): - 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() - - def mouse_move(self, event): - 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) - - 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) - - 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) - - 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 - - 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 - - def nearestindex(self, x): - return int(round(float(x)/XGRID)) - 1 - - -# Subroutines that don't need an object - -def steps(here, there): - nsteps = abs(here - there) - if nsteps <= 3: - nsteps = nsteps * 3 - elif nsteps <= 5: - nsteps = nsteps * 2 - elif 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" - 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)) - res.append(tuple(newpts)) - return res - - -# Various (un)sorting algorithms - -def uniform(array): - size = array.getsize() - array.setdata([(size+1)/2] * size) - array.reset("Uniform data, size %d" % size) - -def distinct(array): - size = array.getsize() - array.setdata(range(1, size+1)) - array.reset("Distinct data, size %d" % size) - -def randomize(array): - array.reset("Randomizing") - n = array.getsize() - for i in range(n): - 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 - 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") - finally: - 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) - 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") - finally: - array.hide_partition() - -def demosort(array): - while 1: - for alg in [quicksort, insertionsort, selectionsort, bubblesort]: - randomize(array) - alg(array) - - -# Sort demo class -- usable as a Grail applet - -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) - - def resize(self, newsize): - 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) - - def c_isort(self): - self.run(insertionsort) - - def c_ssort(self): - self.run(selectionsort) - - def c_bsort(self): - self.run(bubblesort) - - def c_demo(self): - self.run(demosort) - - def c_randomize(self): - self.run(randomize) - - def c_uniform(self): - self.run(uniform) - - def c_distinct(self): - 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 - - def c_cancel(self): - 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() - - def c_quit(self): - if self.busy: - self.array.cancel() - self.master.after_idle(self.master.quit) - - -# Main program -- for stand-alone operation outside Grail - -def main(): - root = Tk() - demo = SortDemo(root) - root.protocol('WM_DELETE_WINDOW', demo.c_quit) - root.mainloop() - -if __name__ == '__main__': - main() diff --git a/Demo/tkinter/guido/svkill.py b/Demo/tkinter/guido/svkill.py deleted file mode 100755 index 1c54e4b165..0000000000 --- a/Demo/tkinter/guido/svkill.py +++ /dev/null @@ -1,128 +0,0 @@ -#! /usr/bin/env python - -# Tkinter interface to SYSV `ps' and `kill' commands. - -from Tkinter import * - -if TkVersion < 4.0: - raise ImportError, "This version of svkill requires Tk 4.0 or later" - -from string import splitfields -from string import split -import commands -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 - -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('', self.do_motion) - self.frame.list.bind('', 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() diff --git a/Demo/tkinter/guido/switch.py b/Demo/tkinter/guido/switch.py deleted file mode 100644 index 3b58f7ce47..0000000000 --- a/Demo/tkinter/guido/switch.py +++ /dev/null @@ -1,55 +0,0 @@ -# Show how to do switchable panels. - -from Tkinter import * - -class App: - - def __init__(self, top=None, master=None): - if top is None: - if master is None: - top = Tk() - else: - top = Toplevel(master) - self.top = top - self.buttonframe = Frame(top) - self.buttonframe.pack() - self.panelframe = Frame(top, borderwidth=2, relief=GROOVE) - self.panelframe.pack(expand=1, fill=BOTH) - self.panels = {} - self.curpanel = None - - def addpanel(self, name, klass): - button = Button(self.buttonframe, text=name, - command=lambda self=self, name=name: self.show(name)) - button.pack(side=LEFT) - frame = Frame(self.panelframe) - instance = klass(frame) - self.panels[name] = (button, frame, instance) - if self.curpanel is None: - self.show(name) - - def show(self, name): - (button, frame, instance) = self.panels[name] - if self.curpanel: - self.curpanel.pack_forget() - self.curpanel = frame - frame.pack(expand=1, fill="both") - -class LabelPanel: - def __init__(self, frame): - self.label = Label(frame, text="Hello world") - self.label.pack() - -class ButtonPanel: - def __init__(self, frame): - self.button = Button(frame, text="Press me") - self.button.pack() - -def main(): - app = App() - app.addpanel("label", LabelPanel) - app.addpanel("button", ButtonPanel) - app.top.mainloop() - -if __name__ == '__main__': - main() diff --git a/Demo/tkinter/guido/tkman.py b/Demo/tkinter/guido/tkman.py deleted file mode 100755 index 84672fc9c1..0000000000 --- a/Demo/tkinter/guido/tkman.py +++ /dev/null @@ -1,267 +0,0 @@ -#! /usr/bin/env python - -# Tk man page browser -- currently only shows the Tcl/Tk man pages - -import sys -import os -import string -import regex -from Tkinter import * -from ManPage import ManPage - -MANNDIRLIST = ['/depot/sundry/man/mann','/usr/local/man/mann'] -MAN3DIRLIST = ['/depot/sundry/man/man3','/usr/local/man/man3'] - -foundmanndir = 0 -for dir in MANNDIRLIST: - if os.path.exists(dir): - MANNDIR = dir - foundmanndir = 1 - -foundman3dir = 0 -for dir in MAN3DIRLIST: - if os.path.exists(dir): - MAN3DIR = dir - foundman3dir = 1 - -if not foundmanndir or not foundman3dir: - sys.stderr.write('\n') - if not foundmanndir: - msg = """\ -Failed to find mann directory. -Please add the correct entry to the MANNDIRLIST -at the top of %s script.""" % \ -sys.argv[0] - sys.stderr.write("%s\n\n" % msg) - if not foundman3dir: - msg = """\ -Failed to find man3 directory. -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.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 - -class SelectionBox: - - 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.entry.bind('', self.entry_cb) - self.search.bind('', self.search_cb) - self.listbox.bind('', self.listbox_cb) - - self.entry.bind('', self.entry_tab) - self.search.bind('', self.search_tab) - self.text.bind('', self.text_tab) - - self.entry.focus_set() - - self.chaptervar.set(MANNDIR) - self.newchapter() - - 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 addlist(self, list): - self.choices[len(self.choices):] = list - self.choices.sort() - 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 search_cb(self, *e): - self.search_string(self.search.get()) - - def entry_tab(self, e): - self.search.focus_set() - - def search_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 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 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() - -main() diff --git a/Demo/tkinter/guido/wish.py b/Demo/tkinter/guido/wish.py deleted file mode 100755 index 4f6fdee903..0000000000 --- a/Demo/tkinter/guido/wish.py +++ /dev/null @@ -1,27 +0,0 @@ -# This is about all it requires to write a wish shell in Python! - -import _tkinter -import os - -tk = _tkinter.create(os.environ['DISPLAY'], 'wish', 'Tk', 1) -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 = '' diff --git a/Demo/tkinter/matt/00-HELLO-WORLD.py b/Demo/tkinter/matt/00-HELLO-WORLD.py deleted file mode 100644 index a32941ba48..0000000000 --- a/Demo/tkinter/matt/00-HELLO-WORLD.py +++ /dev/null @@ -1,27 +0,0 @@ -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. - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - 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='Hello', - command=self.printit) - self.hi_there.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/README b/Demo/tkinter/matt/README deleted file mode 100644 index eb9d30246d..0000000000 --- a/Demo/tkinter/matt/README +++ /dev/null @@ -1,30 +0,0 @@ -This directory contains some ad-hoc examples of Tkinter widget -creation. The files named - - *-simple.py - -are the ones to start with if you're looking for a bare-bones usage of -a widget. The other files are meant to show common usage patters that -are a tad more involved. - -If you have a suggestion for an example program, please send mail to - - conway@virginia.edu - -and I'll include it. - - -matt - -TODO -------- -The X selection -Dialog Boxes -More canvas examples -Message widgets -Text Editors -Scrollbars -Listboxes - - - diff --git a/Demo/tkinter/matt/animation-simple.py b/Demo/tkinter/matt/animation-simple.py deleted file mode 100644 index 435d6fabd1..0000000000 --- a/Demo/tkinter/matt/animation-simple.py +++ /dev/null @@ -1,35 +0,0 @@ -from Tkinter import * - -# This program shows how to use the "after" function to make animation. - -class Test(Frame): - def printit(self): - print "hi" - - 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") - - # 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) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - self.after(10, self.moveThing) - - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/animation-w-velocity-ctrl.py b/Demo/tkinter/matt/animation-w-velocity-ctrl.py deleted file mode 100644 index a45f3f0e8a..0000000000 --- a/Demo/tkinter/matt/animation-w-velocity-ctrl.py +++ /dev/null @@ -1,44 +0,0 @@ -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. - - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - 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.speed = Scale(self, orient=HORIZONTAL, from_=-100, to=100) - - 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) - - def moveThing(self, *args): - velocity = self.speed.get() - str = float(velocity) / 1000.0 - str = `str` + "i" - 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) - - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/bind-w-mult-calls-p-type.py b/Demo/tkinter/matt/bind-w-mult-calls-p-type.py deleted file mode 100644 index 0907e41b07..0000000000 --- a/Demo/tkinter/matt/bind-w-mult-calls-p-type.py +++ /dev/null @@ -1,44 +0,0 @@ -from Tkinter import * -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() - - 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 or (for anything) - self.entrythingy.bind('', 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('', self.print_something_else, "+") - - def print_contents(self, event): - print "hi. contents of entry is now ---->", self.entrythingy.get() - - - def print_something_else(self, event): - print "hi. Now doing something completely different" - - -root = App() -root.master.title("Foo") -root.mainloop() - - - -# 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 -# 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 deleted file mode 100644 index d9896261fa..0000000000 --- a/Demo/tkinter/matt/canvas-demo-simple.py +++ /dev/null @@ -1,28 +0,0 @@ -from Tkinter import * - -# this program creates a canvas and puts a single polygon on the canvas - -class Test(Frame): - def printit(self): - print "hi" - - def createWidgets(self): - 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") - - # 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) - - 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-gridding.py b/Demo/tkinter/matt/canvas-gridding.py deleted file mode 100644 index b200ea4484..0000000000 --- a/Demo/tkinter/matt/canvas-gridding.py +++ /dev/null @@ -1,61 +0,0 @@ -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. - -class Test(Frame): - def printit(self): - 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.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) - - 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() - - 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 - - # this is the size of the gridding squares - self.griddingSize = 50 - - Widget.bind(self.canvasObject, "", self.mouseDown) - Widget.bind(self.canvasObject, "", self.mouseMotion) - - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/canvas-moving-or-creating.py b/Demo/tkinter/matt/canvas-moving-or-creating.py deleted file mode 100644 index 74729a652b..0000000000 --- a/Demo/tkinter/matt/canvas-moving-or-creating.py +++ /dev/null @@ -1,65 +0,0 @@ -from Tkinter import * - -# this file demonstrates a more sophisticated movement -- -# move dots or create new ones if you click outside the dots - -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, "", self.mouseEnter) - self.draw.tag_bind(fred, "", 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 - - ################################################################### - ###### 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") - - 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") - - 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) - - Widget.bind(self.draw, "<1>", self.mouseDown) - Widget.bind(self.draw, "", self.mouseMove) - - 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-moving-w-mouse.py b/Demo/tkinter/matt/canvas-moving-w-mouse.py deleted file mode 100644 index 447e29021f..0000000000 --- a/Demo/tkinter/matt/canvas-moving-w-mouse.py +++ /dev/null @@ -1,55 +0,0 @@ -from Tkinter import * - -# this file demonstrates the movement of a single canvas item under mouse control - -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 - - 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 - - ################################################################### - ###### 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") - - 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") - - 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) - - fred = self.draw.create_oval(0, 0, 20, 20, - fill="green", tags="selected") - - self.draw.tag_bind(fred, "", self.mouseEnter) - self.draw.tag_bind(fred, "", self.mouseLeave) - - Widget.bind(self.draw, "<1>", self.mouseDown) - Widget.bind(self.draw, "", self.mouseMove) - - 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-mult-item-sel.py b/Demo/tkinter/matt/canvas-mult-item-sel.py deleted file mode 100644 index 2368733d04..0000000000 --- a/Demo/tkinter/matt/canvas-mult-item-sel.py +++ /dev/null @@ -1,81 +0,0 @@ -from Tkinter import * - -# allows moving dots with multiple selection. - -SELECTED_COLOR = "red" -UNSELECTED_COLOR = "blue" - -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 - - - def mouseMove(self, event): - 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) - - 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, "", 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) - - 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 deleted file mode 100644 index 704469177e..0000000000 --- a/Demo/tkinter/matt/canvas-reading-tag-info.py +++ /dev/null @@ -1,49 +0,0 @@ -from Tkinter import * - - -class Test(Frame): - def printit(self): - 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) - - 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-w-widget-draw-el.py b/Demo/tkinter/matt/canvas-w-widget-draw-el.py deleted file mode 100644 index a1bb3b5790..0000000000 --- a/Demo/tkinter/matt/canvas-w-widget-draw-el.py +++ /dev/null @@ -1,36 +0,0 @@ -from Tkinter import * - -# this file demonstrates the creation of widgets as part of a canvas object - -class Test(Frame): - def printhi(self): - print "hi" - - def createWidgets(self): - 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.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) - - 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-with-scrollbars.py b/Demo/tkinter/matt/canvas-with-scrollbars.py deleted file mode 100644 index 60c7b132ea..0000000000 --- a/Demo/tkinter/matt/canvas-with-scrollbars.py +++ /dev/null @@ -1,60 +0,0 @@ -from Tkinter import * - -# 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" - - def createWidgets(self): - 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) - - # 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) - - # 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") - - # 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 __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/dialog-box.py b/Demo/tkinter/matt/dialog-box.py deleted file mode 100644 index cbfe29f964..0000000000 --- a/Demo/tkinter/matt/dialog-box.py +++ /dev/null @@ -1,64 +0,0 @@ -from Tkinter import * -from Dialog import Dialog - -# this shows how to create a new window with a button in it -# that can create new windows - -class Test(Frame): - def printit(self): - print "hi" - - def makeWindow(self): - """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 - - - def createWidgets(self): - 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) - - - def __init__(self, master=None): - 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 deleted file mode 100644 index cf82b89ce9..0000000000 --- a/Demo/tkinter/matt/entry-simple.py +++ /dev/null @@ -1,25 +0,0 @@ -from Tkinter import * -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() - - 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 or (for anything) - self.entrythingy.bind('', self.print_contents) - - def print_contents(self, event): - 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 deleted file mode 100644 index 360f97373b..0000000000 --- a/Demo/tkinter/matt/entry-with-shared-variable.py +++ /dev/null @@ -1,47 +0,0 @@ -from Tkinter import * -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 or (for anything) - self.entrythingy.bind('', 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 - # 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) - - def print_contents(self, event): - 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 deleted file mode 100644 index 805a6bc6a8..0000000000 --- a/Demo/tkinter/matt/killing-window-w-wm.py +++ /dev/null @@ -1,42 +0,0 @@ -from Tkinter import * - -# 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). - - -### ******* this isn't really called -- read the comments -def my_delete_callback(): - print "whoops -- tried to delete me!" - -class Test(Frame): - def deathHandler(self, event): - 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) - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - - ### - ### PREVENT WM kills from happening - ### - - # the docs would have you do this: - -# 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("", self.deathHandler) - - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/menu-all-types-of-entries.py b/Demo/tkinter/matt/menu-all-types-of-entries.py deleted file mode 100644 index 1ac51c81ff..0000000000 --- a/Demo/tkinter/matt/menu-all-types-of-entries.py +++ /dev/null @@ -1,250 +0,0 @@ -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 -# pretty closely -# -# -# -# This is a MENUBUTTON -# V -# +-------------+ -# | | -# -# +------------++------------++------------+ -# | || || | -# | File || Edit || Options | <-------- the MENUBAR -# | || || | -# +------------++------------++------------+ -# | New... | -# | Open... | -# | Print | -# | | <-------- This is a MENU. The lines of text in the menu are -# | | MENU ENTRIES -# | +---------------+ -# | Open Files > | file1 | -# | | file2 | -# | | another file | <------ this cascading part is also a MENU -# +----------------| | -# | | -# | | -# | | -# +---------------+ - - - -# some miscellaneous callbacks -def new_file(): - print "opening new file" - -def open_file(): - print "opening OLD file" - -def print_something(): - print "picked a menu item" - - - -anchovies = 0 - -def print_anchovies(): - global anchovies - anchovies = not anchovies - print "anchovies?", anchovies - -def makeCommandMenu(): - # 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... - Command_button.menu = Menu(Command_button) - - # just to be cute, let's disable the undo option: - Command_button.menu.add_command(label="Undo") - # 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='Different Font', underline=0, - 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') - - # 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) - - # set up a pointer from the file menubutton back to the file menu - Command_button['menu'] = Command_button.menu - - return Command_button - - - -def makeCascadeMenu(): - # 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) - - # this is the menu that cascades from the primary pulldown.... - Cascade_button.menu.choices = Menu(Cascade_button.menu) - - # ...and this is a menu that cascades from that. - Cascade_button.menu.choices.wierdones = Menu(Cascade_button.menu.choices) - - # then you define the menus from the deepest level on up. - Cascade_button.menu.choices.wierdones.add_command(label='avacado') - Cascade_button.menu.choices.wierdones.add_command(label='belgian endive') - Cascade_button.menu.choices.wierdones.add_command(label='beefaroni') - - # definition of the menu one level up... - Cascade_button.menu.choices.add_command(label='Chocolate') - Cascade_button.menu.choices.add_command(label='Vanilla') - Cascade_button.menu.choices.add_command(label='TuttiFruiti') - Cascade_button.menu.choices.add_command(label='WopBopaLoopBapABopBamBoom') - 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) - - # and finally, the definition for the top level - Cascade_button.menu.add_cascade(label='more choices', - menu=Cascade_button.menu.choices) - - Cascade_button['menu'] = Cascade_button.menu - - return Cascade_button - -def makeCheckbuttonMenu(): - global fred - # 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 - # 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) - - # 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: - # - # argument what it does - # ----------------------------------- - # 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 - # rules of Tcl_StringMatch - Checkbutton_button.menu.invoke(Checkbutton_button.menu.index('Anchovy')) - - # set up a pointer from the file menubutton back to the file menu - Checkbutton_button['menu'] = Checkbutton_button.menu - - return Checkbutton_button - - -def makeRadiobuttonMenu(): - # 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 - # work through the calback. - Radiobutton_button.menu.add_radiobutton(label='Republican') - Radiobutton_button.menu.add_radiobutton(label='Democrat') - Radiobutton_button.menu.add_radiobutton(label='Libertarian') - Radiobutton_button.menu.add_radiobutton(label='Commie') - Radiobutton_button.menu.add_radiobutton(label='Facist') - Radiobutton_button.menu.add_radiobutton(label='Labor Party') - Radiobutton_button.menu.add_radiobutton(label='Torie') - Radiobutton_button.menu.add_radiobutton(label='Independent') - Radiobutton_button.menu.add_radiobutton(label='Anarchist') - Radiobutton_button.menu.add_radiobutton(label='No Opinion') - - # set up a pointer from the file menubutton back to the file menu - Radiobutton_button['menu'] = Radiobutton_button.menu - - return Radiobutton_button - - -def makeDisabledMenu(): - Dummy_button = Menubutton(mBar, text='Dead Menu', underline=0) - Dummy_button.pack(side=LEFT, padx='2m') - - # this is the standard way of turning off a whole menu - Dummy_button["state"] = DISABLED - return Dummy_button - - -################################################# -#### Main starts here ... -root = Tk() - - -# make a menu bar -mBar = Frame(root, relief=RAISED, borderwidth=2) -mBar.pack(fill=X) - -Command_button = makeCommandMenu() -Cascade_button = makeCascadeMenu() -Checkbutton_button = makeCheckbuttonMenu() -Radiobutton_button = makeRadiobuttonMenu() -NoMenu = makeDisabledMenu() - -# 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) - - -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 deleted file mode 100644 index 28f2c9eff5..0000000000 --- a/Demo/tkinter/matt/menu-simple.py +++ /dev/null @@ -1,118 +0,0 @@ -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 -# pretty closely -# -# -# -# This is a MENUBUTTON -# V -# +-------------+ -# | | -# -# +------------++------------++------------+ -# | || || | -# | File || Edit || Options | <-------- the MENUBAR -# | || || | -# +------------++------------++------------+ -# | New... | -# | Open... | -# | Print | -# | | <------ This is a MENU. The lines of text in the menu are -# | | MENU ENTRIES -# | +---------------+ -# | Open Files > | file1 | -# | | file2 | -# | | another file | <------ this cascading part is also a MENU -# +----------------| | -# | | -# | | -# | | -# +---------------+ - - - -def new_file(): - print "opening new file" - - -def open_file(): - print "opening OLD file" - - -def makeFileMenu(): - # make menu button : "File" - 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, - # 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') - - # set up a pointer from the file menubutton back to the file menu - File_button['menu'] = File_button.menu - - return File_button - - - -def makeEditMenu(): - Edit_button = Menubutton(mBar, text='Edit', underline=0) - Edit_button.pack(side=LEFT, padx="1m") - Edit_button.menu = Menu(Edit_button) - - # just to be cute, let's disable the undo option: - Edit_button.menu.add('command', label="Undo") - # Since the tear-off bar is the 0th entry, - # undo is the 1st entry... - Edit_button.menu.entryconfig(1, state=DISABLED) - - # and these are just for show. No "command" callbacks attached. - Edit_button.menu.add_command(label="Cut") - Edit_button.menu.add_command(label="Copy") - Edit_button.menu.add_command(label="Paste") - - # set up a pointer from the file menubutton back to the file menu - Edit_button['menu'] = Edit_button.menu - - return Edit_button - - -################################################# - -#### Main starts here ... -root = Tk() - - -# make a menu bar -mBar = Frame(root, relief=RAISED, borderwidth=2) -mBar.pack(fill=X) - -File_button = makeFileMenu() -Edit_button = makeEditMenu() - -# 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) - -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 deleted file mode 100644 index 24de2ef202..0000000000 --- a/Demo/tkinter/matt/not-what-you-might-think-1.py +++ /dev/null @@ -1,28 +0,0 @@ -from Tkinter import * - - -class Test(Frame): - def createWidgets(self): - - 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) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.master.title('packer demo') -test.master.iconname('packer') - -test.mainloop() diff --git a/Demo/tkinter/matt/not-what-you-might-think-2.py b/Demo/tkinter/matt/not-what-you-might-think-2.py deleted file mode 100644 index c01854e96c..0000000000 --- a/Demo/tkinter/matt/not-what-you-might-think-2.py +++ /dev/null @@ -1,30 +0,0 @@ -from Tkinter import * - - -class Test(Frame): - def createWidgets(self): - - self.Gpanel = Frame(self, width='1i', height='1i', - background='green') - - # this line turns off the recalculation of geometry by masters. - self.Gpanel.propagate(0) - - 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) - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.master.title('packer demo') -test.master.iconname('packer') - -test.mainloop() diff --git a/Demo/tkinter/matt/packer-and-placer-together.py b/Demo/tkinter/matt/packer-and-placer-together.py deleted file mode 100644 index 4ceec542a5..0000000000 --- a/Demo/tkinter/matt/packer-and-placer-together.py +++ /dev/null @@ -1,42 +0,0 @@ -from Tkinter import * - -# 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 - - -def do_motion(event): - app.button.place(x=event.x, y=event.y) - -def dothis(): - print 'calling me!' - -def createWidgets(top): - # make a frame. Note that the widget is 200 x 200 - # and the window containing is 400x400. We do this - # simply to show that this is possible. The rest of the - # 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. - 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 - # 1/2 way along the top X edge of its' parent - f.button.place(relx=0.5, rely=0.0, anchor=NW) - - # allow the user to move the button SUIT-style. - f.bind('', do_motion) - - return f - -root = Tk() -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 deleted file mode 100644 index 7773cae65d..0000000000 --- a/Demo/tkinter/matt/packer-simple.py +++ /dev/null @@ -1,32 +0,0 @@ -from Tkinter import * - - -class Test(Frame): - def printit(self): - 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) - - self.hi_there = Button(self, text='Hello', - command=self.printit) - self.hi_there.pack(side=LEFT) - - # note how Packer defaults to side=TOP - - self.guy2 = Button(self, text='button 2') - self.guy2.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() - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/placer-simple.py b/Demo/tkinter/matt/placer-simple.py deleted file mode 100644 index b7cae7e59d..0000000000 --- a/Demo/tkinter/matt/placer-simple.py +++ /dev/null @@ -1,40 +0,0 @@ -from Tkinter import * - -# This is a program that tests the placer geom manager - -def do_motion(event): - app.button.place(x=event.x, y=event.y) - -def dothis(): - print 'calling me!' - -def createWidgets(top): - # make a frame. Note that the widget is 200 x 200 - # and the window containing is 400x400. We do this - # simply to show that this is possible. The rest of the - # area is inaccesssible. - f = Frame(top, width=200, height=200, background='green') - - # 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) - - # now make a button - f.button = Button(f, foreground='red', text='amazing', command=dothis) - - # 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) - - # allow the user to move the button SUIT-style. - f.bind('', do_motion) - - return f - -root = Tk() -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 deleted file mode 100644 index dacaa38272..0000000000 --- a/Demo/tkinter/matt/pong-demo-1.py +++ /dev/null @@ -1,54 +0,0 @@ -from Tkinter import * - -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) - - ## 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) - - 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 - - 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 - - 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, `deltax` + "i", `deltay` + "i") - self.after(10, self.moveBall) - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - self.after(10, self.moveBall) - - -game = Pong() - -game.mainloop() diff --git a/Demo/tkinter/matt/printing-coords-of-items.py b/Demo/tkinter/matt/printing-coords-of-items.py deleted file mode 100644 index 6400fd8699..0000000000 --- a/Demo/tkinter/matt/printing-coords-of-items.py +++ /dev/null @@ -1,64 +0,0 @@ -from Tkinter import * - -# this file demonstrates the creation of widgets as part of a canvas object - -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, "", self.mouseEnter) - self.draw.tag_bind(fred, "", 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 - - ################################################################### - ###### 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) - - 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") - - 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) - - Widget.bind(self.draw, "<1>", self.mouseDown) - Widget.bind(self.draw, "", self.mouseMove) - - def __init__(self, master=None): - 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 deleted file mode 100644 index 65dfe52ba1..0000000000 --- a/Demo/tkinter/matt/radiobutton-simple.py +++ /dev/null @@ -1,62 +0,0 @@ -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 -# 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. - - -class Test(Frame): - def printit(self): - 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) - - - def __init__(self, master=None): - Frame.__init__(self, master) - Pack.config(self) - self.createWidgets() - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/rubber-band-box-demo-1.py b/Demo/tkinter/matt/rubber-band-box-demo-1.py deleted file mode 100644 index 5196bf7576..0000000000 --- a/Demo/tkinter/matt/rubber-band-box-demo-1.py +++ /dev/null @@ -1,58 +0,0 @@ -from Tkinter import * - -class Test(Frame): - def printit(self): - 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.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) - - 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() - - def mouseUp(self, event): - 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, "", self.mouseDown) - Widget.bind(self.canvasObject, "", self.mouseMotion) - Widget.bind(self.canvasObject, "", self.mouseUp) - - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/rubber-line-demo-1.py b/Demo/tkinter/matt/rubber-line-demo-1.py deleted file mode 100644 index f6d853560b..0000000000 --- a/Demo/tkinter/matt/rubber-line-demo-1.py +++ /dev/null @@ -1,51 +0,0 @@ -from Tkinter import * - -class Test(Frame): - def printit(self): - 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.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) - - 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() - - 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, "", self.mouseDown) - Widget.bind(self.canvasObject, "", self.mouseMotion) - - -test = Test() - -test.mainloop() diff --git a/Demo/tkinter/matt/slider-demo-1.py b/Demo/tkinter/matt/slider-demo-1.py deleted file mode 100644 index 40395df43c..0000000000 --- a/Demo/tkinter/matt/slider-demo-1.py +++ /dev/null @@ -1,36 +0,0 @@ -from Tkinter import * - -# shows how to make a slider, set and get its value under program control - - -class Test(Frame): - def print_value(self, val): - print "slider now at", val - - 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.reset = Button(self, text='reset slider', - command=self.reset) - - 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) - - def __init__(self, master=None): - 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 deleted file mode 100644 index e79dd5c875..0000000000 --- a/Demo/tkinter/matt/subclass-existing-widgets.py +++ /dev/null @@ -1,29 +0,0 @@ -from Tkinter import * - -# This is a program that makes a simple two button application - - -class New_Button(Button): - def callback(self): - print self.counter - self.counter = self.counter + 1 - -def createWidgets(top): - f = Frame(top) - f.pack() - f.QUIT = Button(f, text='QUIT', foreground='red', command=top.quit) - - f.QUIT.pack(side=LEFT, fill=BOTH) - - # a hello button - f.hi_there = New_Button(f, text='Hello') - # we do this on a different line because we need to reference f.hi_there - f.hi_there.config(command=f.hi_there.callback) - f.hi_there.pack(side=LEFT) - f.hi_there.counter = 43 - - -root = Tk() -createWidgets(root) -root.mainloop() - diff --git a/Demo/tkinter/matt/two-radio-groups.py b/Demo/tkinter/matt/two-radio-groups.py deleted file mode 100644 index 5c17333550..0000000000 --- a/Demo/tkinter/matt/two-radio-groups.py +++ /dev/null @@ -1,110 +0,0 @@ -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"} -# 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) - - - -def makePoliticalParties(var): - # 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': 'Democrat', - 'variable' : var, - 'value' : 2}) - - 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 - Radiobutton_button['menu'] = Radiobutton_button.menu - - return Radiobutton_button - - -def makeFlavors(var): - # 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') - - Radiobutton_button.menu.add_radiobutton(label='Chocolate', - variable=var, value='Chocolate') - - Radiobutton_button.menu.add_radiobutton(label='Rocky Road', - variable=var, value='Rocky Road') - - # choose a default - var.set("Chocolate") - - # set up a pointer from the file menubutton back to the file menu - Radiobutton_button['menu'] = Radiobutton_button.menu - - return Radiobutton_button - - -def printStuff(): - print "party is", party.get() - print "flavor is", flavor.get() - print - -################################################# -#### Main starts here ... -root = Tk() - - -# make a menu bar -mBar = Frame(root, relief=RAISED, borderwidth=2) -mBar.pack(fill=X) - -# make two application variables, -# one to control each radio button set -party = IntVar() -flavor = StringVar() - -Radiobutton_button = makePoliticalParties(party) -Radiobutton_button2 = makeFlavors(flavor) - -# 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) -b.pack(side=TOP) - -root.title('menu demo') -root.iconname('menu demo') - -root.mainloop() diff --git a/Demo/tkinter/matt/window-creation-more.py b/Demo/tkinter/matt/window-creation-more.py deleted file mode 100644 index 492027af60..0000000000 --- a/Demo/tkinter/matt/window-creation-more.py +++ /dev/null @@ -1,35 +0,0 @@ -from Tkinter import * - -# this shows how to create a new window with a button in it -# that can create new windows - -class Test(Frame): - def printit(self): - 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 - - def createWidgets(self): - 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) - - def __init__(self, master=None): - 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 deleted file mode 100644 index 969fefb186..0000000000 --- a/Demo/tkinter/matt/window-creation-simple.py +++ /dev/null @@ -1,31 +0,0 @@ -from Tkinter import * - -# this shows how to spawn off new windows at a button press - -class Test(Frame): - def printit(self): - print "hi" - - def makeWindow(self): - 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) - - # 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() - -test = Test() -test.mainloop() diff --git a/Demo/tkinter/matt/window-creation-w-location.py b/Demo/tkinter/matt/window-creation-w-location.py deleted file mode 100644 index 0ec4e094ec..0000000000 --- a/Demo/tkinter/matt/window-creation-w-location.py +++ /dev/null @@ -1,45 +0,0 @@ -from Tkinter import * - -import sys -##sys.path.append("/users/mjc4y/projects/python/tkinter/utils") -##from TkinterUtils import * - -# this shows how to create a new window with a button in it that -# can create new windows - -class QuitButton(Button): - def __init__(self, master, *args, **kwargs): - if not kwargs.has_key("text"): - kwargs["text"] = "QUIT" - if not kwargs.has_key("command"): - kwargs["command"] = master.quit - apply(Button.__init__, (self, master) + args, kwargs) - -class Test(Frame): - def makeWindow(self, *args): - fred = Toplevel() - - 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() - - ##centerWindow(fred, self.master) - - def createWidgets(self): - 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) - - def __init__(self, master=None): - 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 deleted file mode 100644 index 43161999a1..0000000000 --- a/Demo/xml/elem_count.py +++ /dev/null @@ -1,36 +0,0 @@ -import sys - -from xml.sax import make_parser, handler - -class FancyCounter(handler.ContentHandler): - - def __init__(self): - self._elems = 0 - self._attrs = 0 - self._elem_types = {} - self._attr_types = {} - - def startElement(self, name, attrs): - self._elems = self._elems + 1 - self._attrs = self._attrs + len(attrs) - self._elem_types[name] = self._elem_types.get(name, 0) + 1 - - for name in attrs.keys(): - self._attr_types[name] = self._attr_types.get(name, 0) + 1 - - def endDocument(self): - print "There were", self._elems, "elements." - print "There were", self._attrs, "attributes." - - print "---ELEMENT TYPES" - for pair in self._elem_types.items(): - print "%20s %d" % pair - - print "---ATTRIBUTE TYPES" - 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 deleted file mode 100644 index e42bf1b3c7..0000000000 --- a/Demo/xml/roundtrip.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -A simple demo that reads in an XML document and spits out an equivalent, -but not necessarily identical, document. -""" - -import sys, string - -from xml.sax import saxutils, handler, make_parser - -# --- The ContentHandler - -class ContentGenerator(handler.ContentHandler): - - def __init__(self, out = sys.stdout): - handler.ContentHandler.__init__(self) - self._out = out - - # ContentHandler methods - - def startDocument(self): - self._out.write('\n') - - def startElement(self, name, attrs): - self._out.write('<' + name) - for (name, value) in attrs.items(): - self._out.write(' %s="%s"' % (name, saxutils.escape(value))) - self._out.write('>') - - def endElement(self, name): - self._out.write('' % name) - - def characters(self, content): - self._out.write(saxutils.escape(content)) - - def ignorableWhitespace(self, content): - self._out.write(content) - - def processingInstruction(self, target, data): - self._out.write('' % (target, data)) - -# --- The main program - -parser = make_parser() -parser.setContentHandler(ContentGenerator()) -parser.parse(sys.argv[1]) diff --git a/Demo/xml/rss2html.py b/Demo/xml/rss2html.py deleted file mode 100644 index df5d1c7c07..0000000000 --- a/Demo/xml/rss2html.py +++ /dev/null @@ -1,91 +0,0 @@ -import sys - -from xml.sax import make_parser, handler - -# --- Templates - -top = \ -""" - - - - %s - - - -

      %s

      -""" - -bottom = \ -""" -
    - -
    -
    -Converted to HTML by sax_rss2html.py. -
    - - - -""" - -# --- The ContentHandler - -class RSSHandler(handler.ContentHandler): - - def __init__(self, out = sys.stdout): - handler.ContentHandler.__init__(self) - self._out = out - - self._text = "" - self._parent = None - self._list_started = 0 - self._title = None - self._link = None - self._descr = "" - - # ContentHandler methods - - def startElement(self, name, attrs): - if name == "channel" or name == "image" or name == "item": - self._parent = name - - self._text = "" - - def endElement(self, name): - if self._parent == "channel": - if name == "title": - self._out.write(top % (self._text, self._text)) - elif name == "description": - self._out.write("

    %s

    \n" % self._text) - - elif self._parent == "item": - if name == "title": - self._title = self._text - elif name == "link": - self._link = self._text - elif name == "description": - self._descr = self._text - elif name == "item": - if not self._list_started: - self._out.write("