This is Info file pylibi, produced by Makeinfo-1.55 from the input file lib.texi. This file describes the built-in types, exceptions and functions and the standard modules that come with the Python system. It assumes basic knowledge about the Python language. For an informal introduction to the language, see the Python Tutorial. The Python Reference Manual gives a more formal definition of the language. (These manuals are not yet available in INFO or Texinfo format.) Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. 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 Stichting Mathematisch Centrum or CWI or Corporation for National Research Initiatives or CNRI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. While CWI is the initial source for this software, a modified version is made available by the Corporation for National Research Initiatives (CNRI) at the Internet address ftp://ftp.python.org. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM OR CNRI 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. File: pylibi, Node: Bastion, Prev: rexec, Up: Restricted Execution Standard Module `Bastion' ========================= According to the dictionary, a bastion is "a fortified area or position", or "something that is considered a stronghold." It's a suitable name for this module, which provides a way to forbid access to certain attributes of an object. It must always be used with the `rexec' module, in order to allow restricted-mode programs access to certain safe attributes of an object, while denying access to other, unsafe attributes. - function of module Bastion: Bastion (OBJECT[, FILTER, NAME, CLASS]) Protect the class instance OBJECT, returning a bastion for the object. Any attempt to access one of the object's attributes will have to be approved by the FILTER function; if the access is denied an AttributeError exception will be raised. If present, FILTER must be a function that accepts a string containing an attribute name, and returns true if access to that attribute will be permitted; if FILTER returns false, the access is denied. The default filter denies access to any function beginning with an underscore (`_'). The bastion's string representation will be `' if a value for NAME is provided; otherwise, `repr(OBJECT)' will be used. CLASS, if present, would be a subclass of `BastionClass'; see the code in `bastion.py' for the details. Overriding the default `BastionClass' will rarely be required. File: pylibi, Node: Cryptographic Services, Next: RISCOS ONLY, Prev: Restricted Execution, Up: Top Cryptographic Services ********************** The modules described in this chapter implement various algorithms of a cryptographic nature. They are available at the discretion of the installation. Here's an overview: -- RSA's MD5 message digest algorithm. -- Interface to the GNU MP library for arbitrary precision arithmetic. rotor -- Enigma-like encryption and decryption. Hardcore cypherpunks will probably find the cryptographic modules written by Andrew Kuchling of further interest; the package adds built-in modules for DES and IDEA encryption, provides a Python module for reading and decrypting PGP files, and then some. These modules are not distributed with Python but available separately. See the URL `http://www.magnet.com/~amk/python/pct.html' or send email to `amk@magnet.com' for more information. * Menu: * md5:: * mpz:: * rotor:: File: pylibi, Node: md5, Next: mpz, Prev: Cryptographic Services, Up: Cryptographic Services Built-in Module `md5' ===================== This module implements the interface to RSA's MD5 message digest algorithm (see also Internet RFC 1321). Its use is quite straightforward: use the `md5.new()' to create an md5 object. You can now feed this object with arbitrary strings using the `update()' method, and at any point you can ask it for the "digest" (a strong kind of 128-bit checksum, a.k.a. "fingerprint") of the contatenation of the strings fed to it so far using the `digest()' method. For example, to obtain the digest of the string "Nobody inspects the spammish repetition": >>> import md5 >>> m = md5.new() >>> m.update("Nobody inspects") >>> m.update(" the spammish repetition") >>> m.digest() '\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351' More condensed: >>> md5.new("Nobody inspects the spammish repetition").digest() '\273d\234\203\335\036\245\311\331\336\311\241\215\360\377\351' - function of module md5: new ([ARG]) Return a new md5 object. If ARG is present, the method call `update(ARG)' is made. - function of module md5: md5 ([ARG]) For backward compatibility reasons, this is an alternative name for the `new()' function. An md5 object has the following methods: - Method on md5: update (ARG) Update the md5 object with the string ARG. Repeated calls are equivalent to a single call with the concatenation of all the arguments, i.e. `m.update(a); m.update(b)' is equivalent to `m.update(a+b)'. - Method on md5: digest () Return the digest of the strings passed to the `update()' method so far. This is an 16-byte string which may contain non-ASCII characters, including null bytes. - Method on md5: copy () Return a copy ("clone") of the md5 object. This can be used to efficiently compute the digests of strings that share a common initial substring. File: pylibi, Node: mpz, Next: rotor, Prev: md5, Up: Cryptographic Services Built-in Module `mpz' ===================== This is an optional module. It is only available when Python is configured to include it, which requires that the GNU MP software is installed. This module implements the interface to part of the GNU MP library, which defines arbitrary precision integer and rational number arithmetic routines. Only the interfaces to the *integer* (`mpz_...') routines are provided. If not stated otherwise, the description in the GNU MP documentation can be applied. In general, "mpz"-numbers can be used just like other standard Python numbers, e.g. you can use the built-in operators like `+', `*', etc., as well as the standard built-in functions like `abs', `int', ..., `divmod', `pow'. *Please note:* the bitwise-xor operation has been implemented as a bunch of ands, inverts and ors, because the library lacks an `mpz_xor' function, and I didn't need one. You create an mpz-number by calling the function called `mpz' (see below for an exact description). An mpz-number is printed like this: `mpz(VALUE)'. - function of module mpz: mpz (VALUE) Create a new mpz-number. VALUE can be an integer, a long, another mpz-number, or even a string. If it is a string, it is interpreted as an array of radix-256 digits, least significant digit first, resulting in a positive number. See also the `binary' method, described below. A number of *extra* functions are defined in this module. Non mpz-arguments are converted to mpz-values first, and the functions return mpz-numbers. - function of module mpz: powm (BASE, EXPONENT, MODULUS) Return `pow(BASE, EXPONENT) % MODULUS'. If `EXPONENT == 0', return `mpz(1)'. In contrast to the C-library function, this version can handle negative exponents. - function of module mpz: gcd (OP1, OP2) Return the greatest common divisor of OP1 and OP2. - function of module mpz: gcdext (A, B) Return a tuple `(G, S, T)', such that `A*S + B*T == G == gcd(A, B)'. - function of module mpz: sqrt (OP) Return the square root of OP. The result is rounded towards zero. - function of module mpz: sqrtrem (OP) Return a tuple `(ROOT, REMAINDER)', such that `ROOT*ROOT + REMAINDER == OP'. - function of module mpz: divm (NUMERATOR, DENOMINATOR, MODULUS) Returns a number Q. such that `Q * DENOMINATOR % MODULUS == NUMERATOR'. One could also implement this function in Python, using `gcdext'. An mpz-number has one method: - Method on mpz: binary () Convert this mpz-number to a binary string, where the number has been stored as an array of radix-256 digits, least significant digit first. The mpz-number must have a value greater than or equal to zero, otherwise a `ValueError'-exception will be raised. File: pylibi, Node: rotor, Prev: mpz, Up: Cryptographic Services Built-in Module `rotor' ======================= This module implements a rotor-based encryption algorithm, contributed by Lance Ellinghouse. The design is derived from the Enigma device, a machine used during World War II to encipher messages. A rotor is simply a permutation. For example, if the character `A' is the origin of the rotor, then a given rotor might map `A' to `L', `B' to `Z', `C' to `G', and so on. To encrypt, we choose several different rotors, and set the origins of the rotors to known positions; their initial position is the ciphering key. To encipher a character, we permute the original character by the first rotor, and then apply the second rotor's permutation to the result. We continue until we've applied all the rotors; the resulting character is our ciphertext. We then change the origin of the final rotor by one position, from `A' to `B'; if the final rotor has made a complete revolution, then we rotate the next-to-last rotor by one position, and apply the same procedure recursively. In other words, after enciphering one character, we advance the rotors in the same fashion as a car's odometer. Decoding works in the same way, except we reverse the permutations and apply them in the opposite order. The available functions in this module are: - function of module rotor: newrotor (KEY[, NUMROTORS]) Return a rotor object. KEY is a string containing the encryption key for the object; it can contain arbitrary binary data. The key will be used to randomly generate the rotor permutations and their initial positions. NUMROTORS is the number of rotor permutations in the returned object; if it is omitted, a default value of 6 will be used. Rotor objects have the following methods: - Method on rotor: setkey () Reset the rotor to its initial state. - Method on rotor: encrypt (PLAINTEXT) Reset the rotor object to its initial state and encrypt PLAINTEXT, returning a string containing the ciphertext. The ciphertext is always the same length as the original plaintext. - Method on rotor: encryptmore (PLAINTEXT) Encrypt PLAINTEXT without resetting the rotor object, and return a string containing the ciphertext. - Method on rotor: decrypt (CIPHERTEXT) Reset the rotor object to its initial state and decrypt CIPHERTEXT, returning a string containing the ciphertext. The plaintext string will always be the same length as the ciphertext. - Method on rotor: decryptmore (CIPHERTEXT) Decrypt CIPHERTEXT without resetting the rotor object, and return a string containing the ciphertext. An example usage: >>> import rotor >>> rt = rotor.newrotor('key', 12) >>> rt.encrypt('bar') '\2534\363' >>> rt.encryptmore('bar') '\357\375$' >>> rt.encrypt('bar') '\2534\363' >>> rt.decrypt('\2534\363') 'bar' >>> rt.decryptmore('\357\375$') 'bar' >>> rt.decrypt('\357\375$') 'l(\315' >>> del rt The module's code is not an exact simulation of the original Enigma device; it implements the rotor encryption scheme differently from the original. The most important difference is that in the original Enigma, there were only 5 or 6 different rotors in existence, and they were applied twice to each character; the cipher key was the order in which they were placed in the machine. The Python rotor module uses the supplied key to initialize a random number generator; the rotor permutations and their initial positions are then randomly generated. The original device only enciphered the letters of the alphabet, while this module can handle any 8-bit binary data; it also produces binary output. This module can also operate with an arbitrary number of rotors. The original Enigma cipher was broken in 1944. The version implemented here is probably a good deal more difficult to crack (especially if you use many rotors), but it won't be impossible for a truly skilful and determined attacker to break the cipher. So if you want to keep the NSA out of your files, this rotor cipher may well be unsafe, but for discouraging casual snooping through your files, it will probably be just fine, and may be somewhat safer than using the Unix `crypt' command. File: pylibi, Node: RISCOS ONLY, Next: Function Index, Prev: Cryptographic Services, Up: Top RISCOS ONLY *********** The modules described in this chapter provide interfaces to features that are unique to the RISCOS operating system and UNIX dependent features that have been ported to RISCOS. riscos -- RiscOS ports of some of the posix module (normally used via module `os'). riscospath -- Common RiscOS pathname manipulations (normally used via `os.path'). -- An interface to RiscOS SWI operating system calls drawf -- An interface to the drawfile module. riscoslib -- An experimental interface to the RiscOS toolbox modules. * Menu: * riscos:: * riscospath:: * swi:: * drawf:: * RiscLib:: File: pylibi, Node: riscos, Next: riscospath, Prev: RISCOS ONLY, Up: RISCOS ONLY Built-in Module `riscos' ======================== This module provides RiscOS ports of some POSIX funtions, and some RiscOS specific functions. Errors are reported as exceptions; the usual exceptions are given for type errors, while errors reported by the system calls raise `riscos.error', described below. - exception of module riscos: error This exception is raised when an RiscOS function returns a RiscOS-related error (e.g., not for illegal argument types). Its string value is `'riscos.error''. The accompanying value is a string describing the error, often that returned by the relevant SWI. It defines the following functions: - function of module riscos: chdir (PATH) Change the current working directory to PATH. - function of module riscos: chmod (PATH, MODE) Change the mode of PATH to the numeric MODE. - function of module riscos: expand (PATH) Returns the canonical expansion of a pathname. - function of module riscos: getcwd () Return a string representing the current directory. - function of module riscos: getenv (STRING) Returns the string value of the environment variable STRING or `None' if it does not exist. - function of module riscos: listdir (PATH) Return a list containing the names of the entries in the directory. The list is in arbitrary order. - function of module riscos: mkdir (PATH [, MODE]) Create a directory named PATH, at present MODE is ignored. - function of module riscos: putenv (NAME, STRING [, TYPE]) Sets the environment variable NAME to STRING. *type* -- *Meaning* `0' GSTrans the string `1' Evaluate the string `3' Macro variable `4' No translation TYPE defaults to 4 (no translation of the value string). - function of module riscos: remove (PATH) Remove the directory or file PATH. - function of module riscos: rename (SRC, DST) Rename the file or directory SRC to DST. - function of module riscos: rmdir (PATH) Remove the directory or file PATH (Same as remove). - function of module riscos: settype (FILENAME, TYPE) Sets the type of FILENAME. TYPE can be an integer or a string. - function of module riscos: stat (PATH) Perform a *stat* system call on the given path. The return value is a tuple of at least 10 integers giving the most important (and portable) members of the *stat* structure, in the order `st_mode', `st_ino', `st_dev', `st_nlink', `st_uid', `st_gid', `st_size', `st_atime', `st_mtime', `st_ctime'. The RiscOS version adds three extra values, the file type, attributes and object type, as returned by osfile_read_stamped_no_path. The values `st_ino', `st_dev', `st_nlink', `st_uid' and `st_gid' are all zero. The three times are all equal. Note: The standard module `stat' defines functions and constants that are useful for extracting information from a stat structure. - function of module riscos: system (COMMAND) Execute the command (a string). This is implemented by calling the Standard C function `system()', and has the same limitations. The return value is the exit status of the process as returned by Standard C `system()'. - function of module riscos: unlink (PATH) Unlink PATH (Same as remove). - function of module riscos: utime (PATH, (ATIME, MTIME)) Set the time stamp of the file. (The second argument is a tuple of two items.) At present the second argument is ignored and the time is set to the current time. File: pylibi, Node: riscospath, Next: swi, Prev: riscos, Up: RISCOS ONLY Standard Module `riscospath' ============================ This module implements some useful functions on RiscOS pathnames. *Do not import this module directly.* Instead, import the module `os' and use `os.path'. - function of module riscospath: basename (P) Return the base name of pathname P. This is the second half of the pair returned by `riscospath.split(P)'. - function of module riscospath: commonprefix (LIST) Return the longest string that is a prefix of all strings in LIST. If LIST is empty, return the empty string (`'''). - function of module riscospath: exists (P) Return true if P refers to an existing path. - function of module riscospath: expandvars (P) Return the argument with environment variables expanded. Substrings of the form `$NAME' or `${NAME}' are replaced by the value of environment variable NAME. Malformed variable names and references to non-existing variables are left unchanged. - function of module riscospath: isabs (P) Return true if P is an absolute pathname (has a dollar). - function of module riscospath: isfile (P) Return true if P is an existing file. This includes image files. - function of module riscospath: isdir (P) Return true if P is an existing directory. This includes image files. - function of module riscospath: islink (P) Always returns false. - function of module riscospath: join (P, Q) Join the paths P and Q intelligently: If Q is an absolute path, the return value is Q. Otherwise, the concatenation of P and Q is returned, with a full stop (`'.'') inserted unless P is empty or ends in a slash. - function of module riscospath: normcase (P) Normalize the case of a pathname. This converts upper case to lower case. - function of module riscospath: split (P) Split the pathname P in a pair `(HEAD, TAIL)', where TAIL is the last pathname component and HEAD is everything leading up to that. The TAIL part will never contain a full stop; if P ends in a full stop, TAIL will be empty. If there is no full stop in P, HEAD will be empty. If P is empty, both HEAD and TAIL are empty. Trailing full stops are stripped from HEAD unless it is the root. In nearly all cases, `join(HEAD, TAIL)' equals P. - function of module riscospath: splitext (P) Split the pathname P in a pair `(ROOT, EXT)' such that `ROOT + EXT == P', the last component of ROOT contains no slashess, and EXT is empty or begins with a slash. - function of module riscospath: walk (P, VISIT, ARG) Calls the function VISIT with arguments `(ARG, DIRNAME, NAMES)' for each directory in the directory tree rooted at P (including P itself, if it is a directory). The argument DIRNAME specifies the visited directory, the argument NAMES lists the files in the directory (gotten from `riscos.listdir(DIRNAME)'. The VISIT function may modify NAMES to influence the set of directories visited below DIRNAME, e.g., to avoid visiting certain parts of the tree. (The object referred to by NAMES must be modified in place, using `del' or slice assignment.) File: pylibi, Node: swi, Next: drawf, Prev: riscospath, Up: RISCOS ONLY Built-in Module `swi' ===================== This module provides access to the RiscOS SWI interface. It provides a function `swi' that puts suitable values in the arm registers, calls the SWI and extracts values from registers. As many SWIs manipulate blocks of memory a new object type is provided for handling blocks of memory and inserting and extracting values from them. Errors are reported as exceptions; the usual exceptions are given for type, index and value errors, while errors reported by X versions of the system calls raise `swi.error', described below. Module `swi' defines the following data item: - exception of module swi: error This exception is raised when an RiscOS X SWI returns a RiscOS-related error (e.g., not for illegal argument types). Its string value is `'swi.error''. The accompanying value is a string returned by the SWI. It defines the following functions: - function of module swi: swi (NAME,DESCRIPTOR,...) Calls the swi given by NAME with registers given by DESCRIPTOR. nAME can either be an integer SWI number, or a string SWI name. SWI names are case dependent. To call the X version of the SWI you should set the X bit in the number, or preceed the name with X. DESCRIPTOR is a string that determines the registers to be passed and returned. Values to pass are taken sequentially from the remaining arguments, they are assigned to registers starting from r0. Characters of DESCRIPTOR indicate how to pass values. *Character* *Meaning* -- *Argument Type* `i' pass an integer -- int `s' pass a pointer to a string -- string `b' pass a pointer to the start of a block -- block `e' pass a pointer after the end of a block -- block `0-9' insert 0-9 in the register -- - `-' insert in the register -- - `.' skip a register -- - Note: Strings are read-only. If you want to alter a buffer passed to a SWI you must use a block. If the descriptor contains a semi-colon, characters after this refer to values returned by registers. A single value is returned as an object. Several values are returned as a tuple. *Character* *Meaning* -- *Output Type* `i' return an integer -- int `s' return a string -- string `*' return the carry flag -- int `.' skip a register -- - Example: wimp_initialise >>> from swi import * >>> msgs=block(2,[0x600c0,0]) >>> pname="myprog" >>> wimpver,taskhand=swi(0x600c0,"iisb;ii",310,0x4b534154,pname,msgs) - function of module swi: block (SIZE [, INITIALIZER]) Returns a new block of SIZE words. The initializer must be a string or a list of integers. The initializer is truncated to fit the block. If it is too short it is padded with zeros. If there is no initializer the content of the block is undefined. The memory of a block is guaranteed not to move unless the block is deleted or resized. Blocks support index and slice operations as for lists of integers, except that the block cannot change size, so assignments are truncated or padded as for initialization. Slices beyond the end of the block give index errors. - function of module swi: register (SIZE,ADDRESS) Registers a prexisting memory block of SIZE words as a block. Returns a new block. The memory supplied will not be freed when the block is deleted, or moved when it is resized. Block items support the following data items and methods. - data of module swi: length The length of the block in bytes. Equal to `4*len(BLOCK)'. - data of module swi: start The start address of the memory block. - data of module swi: end The address after the end of the memory block. - function of module swi: padstring (STRING,PADCHAR [,X,Y]) The string is copied into the block between bytes `x' and `y-1'. The string is truncated or padded with PADCHAR as required. X and Y default to 0 and `block.length'. - function of module swi: tostring ([X,Y]) The bytes between `x' and `y-1' are returned as a string. X and Y default to 0 and `block.length'. - function of module swi: nullstring ([X,Y]) The bytes between `x' and `y-1' are returned as a string, the string is terminated before the first null character if any. X and Y default to 0 and `block.length'. - function of module swi: ctrlstring ([X,Y]) The bytes between `x' and `y-1' are returned as a string, the string is terminated before the first control character if any. X and Y default to 0 and `block.length'. - function of module swi: bitset (I,X,Y) `b.bitset(x,y)' is equivalent to b[i]=(b[i]&y)^x. - function of module swi: resize (SIZE) Changes the size of the block. The new size is in words. If the block was created using `register' this just changes the recorded end of the block. Otherwise the block may move, and the data in the block is truncated or zero padded as neccesary. File: pylibi, Node: drawf, Next: RiscLib, Prev: swi, Up: RISCOS ONLY Built-in Module `drawf' ======================= This module provides an interface to the RiscOS drawfile module. It defines a new object type that holds a drawfile. The drawf type is a sequence type. It is considered as a sequence of objects. Assignment to elements and slices, and repetition are not yet implemented. For more details see the documentation on the draw file format, and the DrawFile module. Errors are reported as exceptions; the usual exceptions are given for type, index and value errors, while draw specific errors raise `drawf.error' as described below. Module `drawf' defines the following data items: - exception of module drawf: error This exception is raised on draw specific errors (e.g., not for illegal argument types). Its string value is `'drawf.error''. The accompanying value is a string describing the error. It defines the following functions: - function of module drawf: load (FILENAME) Creates a new drawf object containing the drawfile loaded from the named file. - function of module drawf: new () Creates a new empty drawf object. Drawf objects support the following data items and methods: - data of module drawf: size Returns the length in bytes of the drawfile. - function of module drawf: box ([N]) Returns the bounding box of object number N, or of the whole file if no N is given. The result is a tuple of 4 integers. - function of module drawf: find (X,Y [, N]) Returns the index of the first object in the drawfile whose bounding box contains (X,Y), or the first object after object N if N is given. - function of module drawf: fonttable (FONTDICT) Adds a font table object at the end of a diagram. This would normally be called for an empty diagram, as there should only be one such object, and it must preceed all text objects. FONTDICT is a dictionary with keys the font number, and values the font names. - function of module drawf: group (DRAWF) Appends the contents of DRAWF as a group object. - function of module drawf: path (PATHDESC,STYLE [, DASHPATTERN , DASHSTART]) Adds a path. PATHDESC is a list consisting of integers or pairs of integers. The data is that required for a draw path component, except the initial move and final end are added automatically. The STYLE is a tuple of 4 integers representing the fill colour, outline colour, outline width and path style description. The DASHPATTERN is a list of integers representing lengths of dash elements. DASHSTART is an integer representing the distance into the pattern to start, it defaults to zero. The dash pattern bit of the style description word is set automatically according to the presence of a dash pattern. - function of module drawf: pathcolour (COLOUR [, N ...]) Sets the colour of paths. If no N is given all paths in the diagram are changed, otherwise the N must be indices of path or group objects. The path objects have their colours changed. The group objects are searched recursively for paths. - function of module drawf: pathfill (COLOUR [, N ...]) Sets the fill colour. N is as for `pathcolour'. - function of module drawf: render (FLAGS,TRANS,CLIP,FLAT) Renders the diagram. FLAGS and FLAT are integers. TRANS is the address of a block of 6 integers. CLIP is the address of a block of 4 integers. See the documentation of SWI DrawFile_Render for details. - function of module drawf: save (FILENAME) Saves the contents as a drawfile with name FILENAME. - function of module drawf: text (POINT, TEXT, STYLE) Adds a text object. POINT is a pair giving the x and y coordinates of the start of the text base line. TEXT is the text to print. STYLE is a tuple of 5 integers, the text colour, text background colour hint, font number, and x and y sizes of the font. The sizes are in point. - function of module drawf: textbackground (COLOUR [, N ...]) Sets the text background colour hint. N is interpreted as for `pathcolour' but using groups and text objects. - function of module drawf: textcolour (COLOUR [, N ...]) Sets the text colour. N is interpreted as for `pathcolour' but using groups and text objects. All distances in group objects are in draw units inch. Colours are integers of the form `0xbbggrr00' or`-1' for transparent. File: pylibi, Node: RiscLib, Prev: drawf, Up: RISCOS ONLY Built-in Module `RiscLib' ========================= risclibexperimental These modules provide an experimental interface to the RiscOS toolbox. They provide a class `TBObject' that implements the common toolbox methods, and derived classes `ColourDbox', `IconBar', `Menu', `Quit', `SaveAs', `Window'. They provide a simple event polling system. Neither the modules or the documentation are complete. I have added methods and objects when I needed to use them. The methods provided just call the toolbox SWIs, and can be inspected by examining the code. The event polling system works as follows (using !Ibrowse as an example) : The controlling program imports `tbevent'. `tbevent' imports three dictionaries from a module `events' that include details of the toolbox events, wimp events and wimp messages that the application is interested in. The dictionaries are called `edict', `wdict' and `mdict'. They contain event or message numbers as keys and names as values. See !ibrowse.py.events for an example. The program must supply classes with methods to handle these events. The methods will have the same names as the dictionary values. The program calls tbevent.initialise("") supplying an application directory incuding a Resource file "res" and a "Messages" file. The program registers instances of the handler classes with tbevent (see below). The program then calls `tbevent.poll()' repeatedly. Toolbox event handling works as follows: The ancestor object number of the event is used to find a class instance to handle the event. It is looked up in a dictionary `tbevent.tbclasses' to find the handler, so each class that handles toolbox methods should have a `__init__' method that registers itself in this dictionary. Here is an example from "!Graph" class Display(window.Window): actions={} #1 def __init__(self): window.Window.__init__(self,"Display") #2 tbevent.tbclasses[self.id]=self #3 self.handle=self.getwimphandle() #4 tbevent.winclasses[self.handle]=self #5 In line #2 the underlying window class is initialised. This creates a toolbox object from a template named "Display" (This must be a window object. It should be an ancestor object, but not autocreated). `self.id' is set to the object identifier. Line #3 now registers the class instance as a toolbox event handler. If an event now arrives for an object with this ancestor its event number is looked up in `edict'. The corresponding name should be the name of a method in class `Display'. It will be called for this class instance. The class method names are cached in a dictionary called `actions', so each handler class should contain an empty dictionary as in line #1. Some toolbox events will have no ancestor. These will be sent to a class instance registered with a zero identifier. Most programs will have code such as this, which will handle an autocreated bar icon object. class Orphans: #class to handle events with zero ancestor actions={} def __init__(self): tbevent.tbclasses[0]=self def BarClick(self): a=Display("dir","Top") def E_Q_Quit(self): exit() oi=Orphans() #create an instance of the class (the only one!) Wimp event handling is similar. Wimp codes other than 7, 9, 13, 17 and 18 are sent to class instances registered by their wimp window handles. Codes 7, 9 and 13 are given handles of zero. The classes are registered in the dictionary `tbevent.winclasses'. Lines #4 and #5 in the example above give an example of registration. The names of the actions are obtained from dictionary `wdict'. Codes not in this dictionary are ignored. Note that wimp and toolbox codes use the same `actions' dictionary. This means they must have *different event numbers*. In practice this means not giving low numbers to user defined toolbox events. Starting user defined nubers at `0x1000' is a safe rule. Messages are handled by a single class instance `tbevent.msghandler' method names are looked up from the message number in dictionary `mdict'. For example here is a trivial message handling class that just handles the quit message. class Messenger: #This is the message handler class def Wimp_MQuit(self): exit() tbevent.msghandler=Messenger() #Register the instance Toolbox event methods can examine the toolbox id block as TOOLBOX.IDBLOCK. All methods can use the wimp poll block as TBEVENT.WBLOCK. There is a simple system to assist with debugging built in to `tbevent'. The function `tbevent.report(string,[priority])' broadcasts a wimp message containing the string (truncated to 200 characters). The application "!Reporter" can display these messages. Messages are only sent if `priority<=tbevent.usereport', so debugging messages can be suppressed by setting this variable. `priority' defaults to 16. `tbevent.usereport' is initially 8. `tbevent' generates some reports itself, error reports with priority 2, and reports of all events with priority 32.