code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
"""distutils.extension
Provides the Extension class, used to describe C/C++ extension
modules in setup scripts."""
__revision__ = "$Id: extension.py,v 1.19 2004/10/14 10:02:08 anthonybaxter Exp $"
import os, string, sys
from types import *
try:
import warnings
except ImportError:
warnings = None
# This class is really only used by the "build_ext" command, so it might
# make sense to put it in distutils.command.build_ext. However, that
# module is already big enough, and I want to make this class a bit more
# complex to simplify some common cases ("foo" module in "foo.c") and do
# better error-checking ("foo.c" actually exists).
#
# Also, putting this in build_ext.py means every setup script would have to
# import that large-ish module (indirectly, through distutils.core) in
# order to do anything.
class Extension:
"""Just a collection of attributes that describes an extension
module and everything needed to build it (hopefully in a portable
way, but there are hooks that let you be as unportable as you need).
Instance attributes:
name : string
the full name of the extension, including any packages -- ie.
*not* a filename or pathname, but Python dotted name
sources : [string]
list of source filenames, relative to the distribution root
(where the setup script lives), in Unix form (slash-separated)
for portability. Source files may be C, C++, SWIG (.i),
platform-specific resource files, or whatever else is recognized
by the "build_ext" command as source for a Python extension.
include_dirs : [string]
list of directories to search for C/C++ header files (in Unix
form for portability)
define_macros : [(name : string, value : string|None)]
list of macros to define; each macro is defined using a 2-tuple,
where 'value' is either the string to define it to or None to
define it without a particular value (equivalent of "#define
FOO" in source or -DFOO on Unix C compiler command line)
undef_macros : [string]
list of macros to undefine explicitly
library_dirs : [string]
list of directories to search for C/C++ libraries at link time
libraries : [string]
list of library names (not filenames or paths) to link against
runtime_library_dirs : [string]
list of directories to search for C/C++ libraries at run time
(for shared extensions, this is when the extension is loaded)
extra_objects : [string]
list of extra files to link with (eg. object files not implied
by 'sources', static library that must be explicitly specified,
binary resource files, etc.)
extra_compile_args : [string]
any extra platform- and compiler-specific information to use
when compiling the source files in 'sources'. For platforms and
compilers where "command line" makes sense, this is typically a
list of command-line arguments, but for other platforms it could
be anything.
extra_link_args : [string]
any extra platform- and compiler-specific information to use
when linking object files together to create the extension (or
to create a new static Python interpreter). Similar
interpretation as for 'extra_compile_args'.
export_symbols : [string]
list of symbols to be exported from a shared extension. Not
used on all platforms, and not generally necessary for Python
extensions, which typically export exactly one symbol: "init" +
extension_name.
swig_opts : [string]
any extra options to pass to SWIG if a source file has the .i
extension.
depends : [string]
list of files that the extension depends on
language : string
extension language (i.e. "c", "c++", "objc"). Will be detected
from the source extensions if not provided.
"""
# When adding arguments to this constructor, be sure to update
# setup_keywords in core.py.
def __init__ (self, name, sources,
include_dirs=None,
define_macros=None,
undef_macros=None,
library_dirs=None,
libraries=None,
runtime_library_dirs=None,
extra_objects=None,
extra_compile_args=None,
extra_link_args=None,
export_symbols=None,
swig_opts = None,
depends=None,
language=None,
**kw # To catch unknown keywords
):
assert type(name) is StringType, "'name' must be a string"
assert (type(sources) is ListType and
map(type, sources) == [StringType]*len(sources)), \
"'sources' must be a list of strings"
self.name = name
self.sources = sources
self.include_dirs = include_dirs or []
self.define_macros = define_macros or []
self.undef_macros = undef_macros or []
self.library_dirs = library_dirs or []
self.libraries = libraries or []
self.runtime_library_dirs = runtime_library_dirs or []
self.extra_objects = extra_objects or []
self.extra_compile_args = extra_compile_args or []
self.extra_link_args = extra_link_args or []
self.export_symbols = export_symbols or []
self.swig_opts = swig_opts or []
self.depends = depends or []
self.language = language
# If there are unknown keyword options, warn about them
if len(kw):
L = kw.keys() ; L.sort()
L = map(repr, L)
msg = "Unknown Extension options: " + string.join(L, ', ')
if warnings is not None:
warnings.warn(msg)
else:
sys.stderr.write(msg + '\n')
# class Extension
def read_setup_file (filename):
from distutils.sysconfig import \
parse_makefile, expand_makefile_vars, _variable_rx
from distutils.text_file import TextFile
from distutils.util import split_quoted
# First pass over the file to gather "VAR = VALUE" assignments.
vars = parse_makefile(filename)
# Second pass to gobble up the real content: lines of the form
# <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...]
file = TextFile(filename,
strip_comments=1, skip_blanks=1, join_lines=1,
lstrip_ws=1, rstrip_ws=1)
extensions = []
while 1:
line = file.readline()
if line is None: # eof
break
if _variable_rx.match(line): # VAR=VALUE, handled in first pass
continue
if line[0] == line[-1] == "*":
file.warn("'%s' lines not handled yet" % line)
continue
#print "original line: " + line
line = expand_makefile_vars(line, vars)
words = split_quoted(line)
#print "expanded line: " + line
# NB. this parses a slightly different syntax than the old
# makesetup script: here, there must be exactly one extension per
# line, and it must be the first word of the line. I have no idea
# why the old syntax supported multiple extensions per line, as
# they all wind up being the same.
module = words[0]
ext = Extension(module, [])
append_next_word = None
for word in words[1:]:
if append_next_word is not None:
append_next_word.append(word)
append_next_word = None
continue
suffix = os.path.splitext(word)[1]
switch = word[0:2] ; value = word[2:]
if suffix in (".c", ".cc", ".cpp", ".cxx", ".c++", ".m", ".mm"):
# hmm, should we do something about C vs. C++ sources?
# or leave it up to the CCompiler implementation to
# worry about?
ext.sources.append(word)
elif switch == "-I":
ext.include_dirs.append(value)
elif switch == "-D":
equals = string.find(value, "=")
if equals == -1: # bare "-DFOO" -- no value
ext.define_macros.append((value, None))
else: # "-DFOO=blah"
ext.define_macros.append((value[0:equals],
value[equals+2:]))
elif switch == "-U":
ext.undef_macros.append(value)
elif switch == "-C": # only here 'cause makesetup has it!
ext.extra_compile_args.append(word)
elif switch == "-l":
ext.libraries.append(value)
elif switch == "-L":
ext.library_dirs.append(value)
elif switch == "-R":
ext.runtime_library_dirs.append(value)
elif word == "-rpath":
append_next_word = ext.runtime_library_dirs
elif word == "-Xlinker":
append_next_word = ext.extra_link_args
elif word == "-Xcompiler":
append_next_word = ext.extra_compile_args
elif switch == "-u":
ext.extra_link_args.append(word)
if not value:
append_next_word = ext.extra_link_args
elif suffix in (".a", ".so", ".sl", ".o", ".dylib"):
# NB. a really faithful emulation of makesetup would
# append a .o file to extra_objects only if it
# had a slash in it; otherwise, it would s/.o/.c/
# and append it to sources. Hmmmm.
ext.extra_objects.append(word)
else:
file.warn("unrecognized argument '%s'" % word)
extensions.append(ext)
#print "module:", module
#print "source files:", source_files
#print "cpp args:", cpp_args
#print "lib args:", library_args
#extensions[module] = { 'sources': source_files,
# 'cpp_args': cpp_args,
# 'lib_args': library_args }
return extensions
# read_setup_file ()
| Python |
"""distutils
The main package for the Python Module Distribution Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: __init__.py,v 1.26.2.1 2005/01/20 19:25:24 theller Exp $"
__version__ = "2.4.1"
| Python |
"""distutils.cmd
Provides the Command class, the base class for the command classes
in the distutils.command package.
"""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: cmd.py,v 1.39 2004/11/10 22:23:14 loewis Exp $"
import sys, os, string, re
from types import *
from distutils.errors import *
from distutils import util, dir_util, file_util, archive_util, dep_util
from distutils import log
class Command:
"""Abstract base class for defining command classes, the "worker bees"
of the Distutils. A useful analogy for command classes is to think of
them as subroutines with local variables called "options". The options
are "declared" in 'initialize_options()' and "defined" (given their
final values, aka "finalized") in 'finalize_options()', both of which
must be defined by every command class. The distinction between the
two is necessary because option values might come from the outside
world (command line, config file, ...), and any options dependent on
other options must be computed *after* these outside influences have
been processed -- hence 'finalize_options()'. The "body" of the
subroutine, where it does all its work based on the values of its
options, is the 'run()' method, which must also be implemented by every
command class.
"""
# 'sub_commands' formalizes the notion of a "family" of commands,
# eg. "install" as the parent with sub-commands "install_lib",
# "install_headers", etc. The parent of a family of commands
# defines 'sub_commands' as a class attribute; it's a list of
# (command_name : string, predicate : unbound_method | string | None)
# tuples, where 'predicate' is a method of the parent command that
# determines whether the corresponding command is applicable in the
# current situation. (Eg. we "install_headers" is only applicable if
# we have any C header files to install.) If 'predicate' is None,
# that command is always applicable.
#
# 'sub_commands' is usually defined at the *end* of a class, because
# predicates can be unbound methods, so they must already have been
# defined. The canonical example is the "install" command.
sub_commands = []
# -- Creation/initialization methods -------------------------------
def __init__ (self, dist):
"""Create and initialize a new Command object. Most importantly,
invokes the 'initialize_options()' method, which is the real
initializer and depends on the actual command being
instantiated.
"""
# late import because of mutual dependence between these classes
from distutils.dist import Distribution
if not isinstance(dist, Distribution):
raise TypeError, "dist must be a Distribution instance"
if self.__class__ is Command:
raise RuntimeError, "Command is an abstract class"
self.distribution = dist
self.initialize_options()
# Per-command versions of the global flags, so that the user can
# customize Distutils' behaviour command-by-command and let some
# commands fall back on the Distribution's behaviour. None means
# "not defined, check self.distribution's copy", while 0 or 1 mean
# false and true (duh). Note that this means figuring out the real
# value of each flag is a touch complicated -- hence "self._dry_run"
# will be handled by __getattr__, below.
# XXX This needs to be fixed.
self._dry_run = None
# verbose is largely ignored, but needs to be set for
# backwards compatibility (I think)?
self.verbose = dist.verbose
# Some commands define a 'self.force' option to ignore file
# timestamps, but methods defined *here* assume that
# 'self.force' exists for all commands. So define it here
# just to be safe.
self.force = None
# The 'help' flag is just used for command-line parsing, so
# none of that complicated bureaucracy is needed.
self.help = 0
# 'finalized' records whether or not 'finalize_options()' has been
# called. 'finalize_options()' itself should not pay attention to
# this flag: it is the business of 'ensure_finalized()', which
# always calls 'finalize_options()', to respect/update it.
self.finalized = 0
# __init__ ()
# XXX A more explicit way to customize dry_run would be better.
def __getattr__ (self, attr):
if attr == 'dry_run':
myval = getattr(self, "_" + attr)
if myval is None:
return getattr(self.distribution, attr)
else:
return myval
else:
raise AttributeError, attr
def ensure_finalized (self):
if not self.finalized:
self.finalize_options()
self.finalized = 1
# Subclasses must define:
# initialize_options()
# provide default values for all options; may be customized by
# setup script, by options from config file(s), or by command-line
# options
# finalize_options()
# decide on the final values for all options; this is called
# after all possible intervention from the outside world
# (command-line, option file, etc.) has been processed
# run()
# run the command: do whatever it is we're here to do,
# controlled by the command's various option values
def initialize_options (self):
"""Set default values for all the options that this command
supports. Note that these defaults may be overridden by other
commands, by the setup script, by config files, or by the
command-line. Thus, this is not the place to code dependencies
between options; generally, 'initialize_options()' implementations
are just a bunch of "self.foo = None" assignments.
This method must be implemented by all command classes.
"""
raise RuntimeError, \
"abstract method -- subclass %s must override" % self.__class__
def finalize_options (self):
"""Set final values for all the options that this command supports.
This is always called as late as possible, ie. after any option
assignments from the command-line or from other commands have been
done. Thus, this is the place to code option dependencies: if
'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as
long as 'foo' still has the same value it was assigned in
'initialize_options()'.
This method must be implemented by all command classes.
"""
raise RuntimeError, \
"abstract method -- subclass %s must override" % self.__class__
def dump_options (self, header=None, indent=""):
from distutils.fancy_getopt import longopt_xlate
if header is None:
header = "command options for '%s':" % self.get_command_name()
print indent + header
indent = indent + " "
for (option, _, _) in self.user_options:
option = string.translate(option, longopt_xlate)
if option[-1] == "=":
option = option[:-1]
value = getattr(self, option)
print indent + "%s = %s" % (option, value)
def run (self):
"""A command's raison d'etre: carry out the action it exists to
perform, controlled by the options initialized in
'initialize_options()', customized by other commands, the setup
script, the command-line, and config files, and finalized in
'finalize_options()'. All terminal output and filesystem
interaction should be done by 'run()'.
This method must be implemented by all command classes.
"""
raise RuntimeError, \
"abstract method -- subclass %s must override" % self.__class__
def announce (self, msg, level=1):
"""If the current verbosity level is of greater than or equal to
'level' print 'msg' to stdout.
"""
log.log(level, msg)
def debug_print (self, msg):
"""Print 'msg' to stdout if the global DEBUG (taken from the
DISTUTILS_DEBUG environment variable) flag is true.
"""
from distutils.debug import DEBUG
if DEBUG:
print msg
sys.stdout.flush()
# -- Option validation methods -------------------------------------
# (these are very handy in writing the 'finalize_options()' method)
#
# NB. the general philosophy here is to ensure that a particular option
# value meets certain type and value constraints. If not, we try to
# force it into conformance (eg. if we expect a list but have a string,
# split the string on comma and/or whitespace). If we can't force the
# option into conformance, raise DistutilsOptionError. Thus, command
# classes need do nothing more than (eg.)
# self.ensure_string_list('foo')
# and they can be guaranteed that thereafter, self.foo will be
# a list of strings.
def _ensure_stringlike (self, option, what, default=None):
val = getattr(self, option)
if val is None:
setattr(self, option, default)
return default
elif type(val) is not StringType:
raise DistutilsOptionError, \
"'%s' must be a %s (got `%s`)" % (option, what, val)
return val
def ensure_string (self, option, default=None):
"""Ensure that 'option' is a string; if not defined, set it to
'default'.
"""
self._ensure_stringlike(option, "string", default)
def ensure_string_list (self, option):
"""Ensure that 'option' is a list of strings. If 'option' is
currently a string, we split it either on /,\s*/ or /\s+/, so
"foo bar baz", "foo,bar,baz", and "foo, bar baz" all become
["foo", "bar", "baz"].
"""
val = getattr(self, option)
if val is None:
return
elif type(val) is StringType:
setattr(self, option, re.split(r',\s*|\s+', val))
else:
if type(val) is ListType:
types = map(type, val)
ok = (types == [StringType] * len(val))
else:
ok = 0
if not ok:
raise DistutilsOptionError, \
"'%s' must be a list of strings (got %r)" % \
(option, val)
def _ensure_tested_string (self, option, tester,
what, error_fmt, default=None):
val = self._ensure_stringlike(option, what, default)
if val is not None and not tester(val):
raise DistutilsOptionError, \
("error in '%s' option: " + error_fmt) % (option, val)
def ensure_filename (self, option):
"""Ensure that 'option' is the name of an existing file."""
self._ensure_tested_string(option, os.path.isfile,
"filename",
"'%s' does not exist or is not a file")
def ensure_dirname (self, option):
self._ensure_tested_string(option, os.path.isdir,
"directory name",
"'%s' does not exist or is not a directory")
# -- Convenience methods for commands ------------------------------
def get_command_name (self):
if hasattr(self, 'command_name'):
return self.command_name
else:
return self.__class__.__name__
def set_undefined_options (self, src_cmd, *option_pairs):
"""Set the values of any "undefined" options from corresponding
option values in some other command object. "Undefined" here means
"is None", which is the convention used to indicate that an option
has not been changed between 'initialize_options()' and
'finalize_options()'. Usually called from 'finalize_options()' for
options that depend on some other command rather than another
option of the same command. 'src_cmd' is the other command from
which option values will be taken (a command object will be created
for it if necessary); the remaining arguments are
'(src_option,dst_option)' tuples which mean "take the value of
'src_option' in the 'src_cmd' command object, and copy it to
'dst_option' in the current command object".
"""
# Option_pairs: list of (src_option, dst_option) tuples
src_cmd_obj = self.distribution.get_command_obj(src_cmd)
src_cmd_obj.ensure_finalized()
for (src_option, dst_option) in option_pairs:
if getattr(self, dst_option) is None:
setattr(self, dst_option,
getattr(src_cmd_obj, src_option))
def get_finalized_command (self, command, create=1):
"""Wrapper around Distribution's 'get_command_obj()' method: find
(create if necessary and 'create' is true) the command object for
'command', call its 'ensure_finalized()' method, and return the
finalized command object.
"""
cmd_obj = self.distribution.get_command_obj(command, create)
cmd_obj.ensure_finalized()
return cmd_obj
# XXX rename to 'get_reinitialized_command()'? (should do the
# same in dist.py, if so)
def reinitialize_command (self, command, reinit_subcommands=0):
return self.distribution.reinitialize_command(
command, reinit_subcommands)
def run_command (self, command):
"""Run some other command: uses the 'run_command()' method of
Distribution, which creates and finalizes the command object if
necessary and then invokes its 'run()' method.
"""
self.distribution.run_command(command)
def get_sub_commands (self):
"""Determine the sub-commands that are relevant in the current
distribution (ie., that need to be run). This is based on the
'sub_commands' class attribute: each tuple in that list may include
a method that we call to determine if the subcommand needs to be
run for the current distribution. Return a list of command names.
"""
commands = []
for (cmd_name, method) in self.sub_commands:
if method is None or method(self):
commands.append(cmd_name)
return commands
# -- External world manipulation -----------------------------------
def warn (self, msg):
sys.stderr.write("warning: %s: %s\n" %
(self.get_command_name(), msg))
def execute (self, func, args, msg=None, level=1):
util.execute(func, args, msg, dry_run=self.dry_run)
def mkpath (self, name, mode=0777):
dir_util.mkpath(name, mode, dry_run=self.dry_run)
def copy_file (self, infile, outfile,
preserve_mode=1, preserve_times=1, link=None, level=1):
"""Copy a file respecting verbose, dry-run and force flags. (The
former two default to whatever is in the Distribution object, and
the latter defaults to false for commands that don't define it.)"""
return file_util.copy_file(
infile, outfile,
preserve_mode, preserve_times,
not self.force,
link,
dry_run=self.dry_run)
def copy_tree (self, infile, outfile,
preserve_mode=1, preserve_times=1, preserve_symlinks=0,
level=1):
"""Copy an entire directory tree respecting verbose, dry-run,
and force flags.
"""
return dir_util.copy_tree(
infile, outfile,
preserve_mode,preserve_times,preserve_symlinks,
not self.force,
dry_run=self.dry_run)
def move_file (self, src, dst, level=1):
"""Move a file respectin dry-run flag."""
return file_util.move_file(src, dst, dry_run = self.dry_run)
def spawn (self, cmd, search_path=1, level=1):
"""Spawn an external command respecting dry-run flag."""
from distutils.spawn import spawn
spawn(cmd, search_path, dry_run= self.dry_run)
def make_archive (self, base_name, format,
root_dir=None, base_dir=None):
return archive_util.make_archive(
base_name, format, root_dir, base_dir, dry_run=self.dry_run)
def make_file (self, infiles, outfile, func, args,
exec_msg=None, skip_msg=None, level=1):
"""Special case of 'execute()' for operations that process one or
more input files and generate one output file. Works just like
'execute()', except the operation is skipped and a different
message printed if 'outfile' already exists and is newer than all
files listed in 'infiles'. If the command defined 'self.force',
and it is true, then the command is unconditionally run -- does no
timestamp checks.
"""
if exec_msg is None:
exec_msg = "generating %s from %s" % \
(outfile, string.join(infiles, ', '))
if skip_msg is None:
skip_msg = "skipping %s (inputs unchanged)" % outfile
# Allow 'infiles' to be a single string
if type(infiles) is StringType:
infiles = (infiles,)
elif type(infiles) not in (ListType, TupleType):
raise TypeError, \
"'infiles' must be a string, or a list or tuple of strings"
# If 'outfile' must be regenerated (either because it doesn't
# exist, is out-of-date, or the 'force' flag is true) then
# perform the action that presumably regenerates it
if self.force or dep_util.newer_group (infiles, outfile):
self.execute(func, args, exec_msg, level)
# Otherwise, print the "skip" message
else:
log.debug(skip_msg)
# make_file ()
# class Command
# XXX 'install_misc' class not currently used -- it was the base class for
# both 'install_scripts' and 'install_data', but they outgrew it. It might
# still be useful for 'install_headers', though, so I'm keeping it around
# for the time being.
class install_misc (Command):
"""Common base class for installing some files in a subdirectory.
Currently used by install_data and install_scripts.
"""
user_options = [('install-dir=', 'd', "directory to install the files to")]
def initialize_options (self):
self.install_dir = None
self.outfiles = []
def _install_dir_from (self, dirname):
self.set_undefined_options('install', (dirname, 'install_dir'))
def _copy_files (self, filelist):
self.outfiles = []
if not filelist:
return
self.mkpath(self.install_dir)
for f in filelist:
self.copy_file(f, self.install_dir)
self.outfiles.append(os.path.join(self.install_dir, f))
def get_outputs (self):
return self.outfiles
if __name__ == "__main__":
print "ok"
| Python |
"""Provide access to Python's configuration information. The specific
configuration variables available depend heavily on the platform and
configuration. The values may be retrieved using
get_config_var(name), and the list of variables is available via
get_config_vars().keys(). Additional convenience functions are also
available.
Written by: Fred L. Drake, Jr.
Email: <fdrake@acm.org>
"""
__revision__ = "$Id: sysconfig.py,v 1.61.2.1 2005/01/06 23:16:03 jackjansen Exp $"
import os
import re
import string
import sys
from errors import DistutilsPlatformError
# These are needed in a couple of spots, so just compute them once.
PREFIX = os.path.normpath(sys.prefix)
EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
# python_build: (Boolean) if true, we're either building Python or
# building an extension with an un-installed Python, so we use
# different (hard-wired) directories.
argv0_path = os.path.dirname(os.path.abspath(sys.executable))
landmark = os.path.join(argv0_path, "Modules", "Setup")
python_build = os.path.isfile(landmark)
del argv0_path, landmark
def get_python_version ():
"""Return a string containing the major and minor Python version,
leaving off the patchlevel. Sample return values could be '1.5'
or '2.2'.
"""
return sys.version[:3]
def get_python_inc(plat_specific=0, prefix=None):
"""Return the directory containing installed Python header files.
If 'plat_specific' is false (the default), this is the path to the
non-platform-specific header files, i.e. Python.h and so on;
otherwise, this is the path to platform-specific header files
(namely pyconfig.h).
If 'prefix' is supplied, use it instead of sys.prefix or
sys.exec_prefix -- i.e., ignore 'plat_specific'.
"""
if prefix is None:
prefix = plat_specific and EXEC_PREFIX or PREFIX
if os.name == "posix":
if python_build:
base = os.path.dirname(os.path.abspath(sys.executable))
if plat_specific:
inc_dir = base
else:
inc_dir = os.path.join(base, "Include")
if not os.path.exists(inc_dir):
inc_dir = os.path.join(os.path.dirname(base), "Include")
return inc_dir
return os.path.join(prefix, "include", "python" + sys.version[:3])
elif os.name == "nt":
return os.path.join(prefix, "include")
elif os.name == "mac":
if plat_specific:
return os.path.join(prefix, "Mac", "Include")
else:
return os.path.join(prefix, "Include")
elif os.name == "os2":
return os.path.join(prefix, "Include")
else:
raise DistutilsPlatformError(
"I don't know where Python installs its C header files "
"on platform '%s'" % os.name)
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
"""Return the directory containing the Python library (standard or
site additions).
If 'plat_specific' is true, return the directory containing
platform-specific modules, i.e. any module from a non-pure-Python
module distribution; otherwise, return the platform-shared library
directory. If 'standard_lib' is true, return the directory
containing standard Python library modules; otherwise, return the
directory for site-specific modules.
If 'prefix' is supplied, use it instead of sys.prefix or
sys.exec_prefix -- i.e., ignore 'plat_specific'.
"""
if prefix is None:
prefix = plat_specific and EXEC_PREFIX or PREFIX
if os.name == "posix":
libpython = os.path.join(prefix,
"lib", "python" + get_python_version())
if standard_lib:
return libpython
else:
return os.path.join(libpython, "site-packages")
elif os.name == "nt":
if standard_lib:
return os.path.join(prefix, "Lib")
else:
if sys.version < "2.2":
return prefix
else:
return os.path.join(PREFIX, "Lib", "site-packages")
elif os.name == "mac":
if plat_specific:
if standard_lib:
return os.path.join(prefix, "Lib", "lib-dynload")
else:
return os.path.join(prefix, "Lib", "site-packages")
else:
if standard_lib:
return os.path.join(prefix, "Lib")
else:
return os.path.join(prefix, "Lib", "site-packages")
elif os.name == "os2":
if standard_lib:
return os.path.join(PREFIX, "Lib")
else:
return os.path.join(PREFIX, "Lib", "site-packages")
else:
raise DistutilsPlatformError(
"I don't know where Python installs its library "
"on platform '%s'" % os.name)
def customize_compiler(compiler):
"""Do any platform-specific customization of a CCompiler instance.
Mainly needed on Unix, so we can plug in the information that
varies across Unices and is stored in Python's Makefile.
"""
if compiler.compiler_type == "unix":
(cc, cxx, opt, basecflags, ccshared, ldshared, so_ext) = \
get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS', 'CCSHARED', 'LDSHARED', 'SO')
if os.environ.has_key('CC'):
cc = os.environ['CC']
if os.environ.has_key('CXX'):
cxx = os.environ['CXX']
if os.environ.has_key('LDSHARED'):
ldshared = os.environ['LDSHARED']
if os.environ.has_key('CPP'):
cpp = os.environ['CPP']
else:
cpp = cc + " -E" # not always
if os.environ.has_key('LDFLAGS'):
ldshared = ldshared + ' ' + os.environ['LDFLAGS']
if basecflags:
opt = basecflags + ' ' + opt
if os.environ.has_key('CFLAGS'):
opt = opt + ' ' + os.environ['CFLAGS']
ldshared = ldshared + ' ' + os.environ['CFLAGS']
if os.environ.has_key('CPPFLAGS'):
cpp = cpp + ' ' + os.environ['CPPFLAGS']
opt = opt + ' ' + os.environ['CPPFLAGS']
ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
cc_cmd = cc + ' ' + opt
compiler.set_executables(
preprocessor=cpp,
compiler=cc_cmd,
compiler_so=cc_cmd + ' ' + ccshared,
compiler_cxx=cxx,
linker_so=ldshared,
linker_exe=cc)
compiler.shared_lib_extension = so_ext
def get_config_h_filename():
"""Return full pathname of installed pyconfig.h file."""
if python_build:
inc_dir = os.curdir
else:
inc_dir = get_python_inc(plat_specific=1)
if sys.version < '2.2':
config_h = 'config.h'
else:
# The name of the config.h file changed in 2.2
config_h = 'pyconfig.h'
return os.path.join(inc_dir, config_h)
def get_makefile_filename():
"""Return full pathname of installed Makefile from the Python build."""
if python_build:
return os.path.join(os.path.dirname(sys.executable), "Makefile")
lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
return os.path.join(lib_dir, "config", "Makefile")
def parse_config_h(fp, g=None):
"""Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
if g is None:
g = {}
define_rx = re.compile("#define ([A-Z][A-Z0-9_]+) (.*)\n")
undef_rx = re.compile("/[*] #undef ([A-Z][A-Z0-9_]+) [*]/\n")
#
while 1:
line = fp.readline()
if not line:
break
m = define_rx.match(line)
if m:
n, v = m.group(1, 2)
try: v = int(v)
except ValueError: pass
g[n] = v
else:
m = undef_rx.match(line)
if m:
g[m.group(1)] = 0
return g
# Regexes needed for parsing Makefile (and similar syntaxes,
# like old-style Setup files).
_variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
def parse_makefile(fn, g=None):
"""Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
from distutils.text_file import TextFile
fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1)
if g is None:
g = {}
done = {}
notdone = {}
while 1:
line = fp.readline()
if line is None: # eof
break
m = _variable_rx.match(line)
if m:
n, v = m.group(1, 2)
v = string.strip(v)
if "$" in v:
notdone[n] = v
else:
try: v = int(v)
except ValueError: pass
done[n] = v
# do variable interpolation here
while notdone:
for name in notdone.keys():
value = notdone[name]
m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
if m:
n = m.group(1)
if done.has_key(n):
after = value[m.end():]
value = value[:m.start()] + str(done[n]) + after
if "$" in after:
notdone[name] = value
else:
try: value = int(value)
except ValueError:
done[name] = string.strip(value)
else:
done[name] = value
del notdone[name]
elif notdone.has_key(n):
# get it on a subsequent round
pass
else:
done[n] = ""
after = value[m.end():]
value = value[:m.start()] + after
if "$" in after:
notdone[name] = value
else:
try: value = int(value)
except ValueError:
done[name] = string.strip(value)
else:
done[name] = value
del notdone[name]
else:
# bogus variable reference; just drop it since we can't deal
del notdone[name]
fp.close()
# save the results in the global dictionary
g.update(done)
return g
def expand_makefile_vars(s, vars):
"""Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
'string' according to 'vars' (a dictionary mapping variable names to
values). Variables not present in 'vars' are silently expanded to the
empty string. The variable values in 'vars' should not contain further
variable expansions; if 'vars' is the output of 'parse_makefile()',
you're fine. Returns a variable-expanded version of 's'.
"""
# This algorithm does multiple expansion, so if vars['foo'] contains
# "${bar}", it will expand ${foo} to ${bar}, and then expand
# ${bar}... and so forth. This is fine as long as 'vars' comes from
# 'parse_makefile()', which takes care of such expansions eagerly,
# according to make's variable expansion semantics.
while 1:
m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
if m:
(beg, end) = m.span()
s = s[0:beg] + vars.get(m.group(1)) + s[end:]
else:
break
return s
_config_vars = None
def _init_posix():
"""Initialize the module as appropriate for POSIX systems."""
g = {}
# load the installed Makefile:
try:
filename = get_makefile_filename()
parse_makefile(filename, g)
except IOError, msg:
my_msg = "invalid Python installation: unable to open %s" % filename
if hasattr(msg, "strerror"):
my_msg = my_msg + " (%s)" % msg.strerror
raise DistutilsPlatformError(my_msg)
# On MacOSX we need to check the setting of the environment variable
# MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so
# it needs to be compatible.
# If it isn't set we set it to the configure-time value
if sys.platform == 'darwin' and g.has_key('CONFIGURE_MACOSX_DEPLOYMENT_TARGET'):
cfg_target = g['CONFIGURE_MACOSX_DEPLOYMENT_TARGET']
cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '')
if cur_target == '':
cur_target = cfg_target
os.putenv('MACOSX_DEPLOYMENT_TARGET', cfg_target)
if cfg_target != cur_target:
my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'
% (cur_target, cfg_target))
raise DistutilsPlatformError(my_msg)
# On AIX, there are wrong paths to the linker scripts in the Makefile
# -- these paths are relative to the Python source, but when installed
# the scripts are in another directory.
if python_build:
g['LDSHARED'] = g['BLDSHARED']
elif sys.version < '2.1':
# The following two branches are for 1.5.2 compatibility.
if sys.platform == 'aix4': # what about AIX 3.x ?
# Linker script is in the config directory, not in Modules as the
# Makefile says.
python_lib = get_python_lib(standard_lib=1)
ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix')
python_exp = os.path.join(python_lib, 'config', 'python.exp')
g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp)
elif sys.platform == 'beos':
# Linker script is in the config directory. In the Makefile it is
# relative to the srcdir, which after installation no longer makes
# sense.
python_lib = get_python_lib(standard_lib=1)
linkerscript_path = string.split(g['LDSHARED'])[0]
linkerscript_name = os.path.basename(linkerscript_path)
linkerscript = os.path.join(python_lib, 'config',
linkerscript_name)
# XXX this isn't the right place to do this: adding the Python
# library to the link, if needed, should be in the "build_ext"
# command. (It's also needed for non-MS compilers on Windows, and
# it's taken care of for them by the 'build_ext.get_libraries()'
# method.)
g['LDSHARED'] = ("%s -L%s/lib -lpython%s" %
(linkerscript, PREFIX, sys.version[0:3]))
global _config_vars
_config_vars = g
def _init_nt():
"""Initialize the module as appropriate for NT"""
g = {}
# set basic install directories
g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
# XXX hmmm.. a normal install puts include files here
g['INCLUDEPY'] = get_python_inc(plat_specific=0)
g['SO'] = '.pyd'
g['EXE'] = ".exe"
global _config_vars
_config_vars = g
def _init_mac():
"""Initialize the module as appropriate for Macintosh systems"""
g = {}
# set basic install directories
g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
# XXX hmmm.. a normal install puts include files here
g['INCLUDEPY'] = get_python_inc(plat_specific=0)
import MacOS
if not hasattr(MacOS, 'runtimemodel'):
g['SO'] = '.ppc.slb'
else:
g['SO'] = '.%s.slb' % MacOS.runtimemodel
# XXX are these used anywhere?
g['install_lib'] = os.path.join(EXEC_PREFIX, "Lib")
g['install_platlib'] = os.path.join(EXEC_PREFIX, "Mac", "Lib")
# These are used by the extension module build
g['srcdir'] = ':'
global _config_vars
_config_vars = g
def _init_os2():
"""Initialize the module as appropriate for OS/2"""
g = {}
# set basic install directories
g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
# XXX hmmm.. a normal install puts include files here
g['INCLUDEPY'] = get_python_inc(plat_specific=0)
g['SO'] = '.pyd'
g['EXE'] = ".exe"
global _config_vars
_config_vars = g
def get_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform. Generally this includes
everything needed to build extensions and install both pure modules and
extensions. On Unix, this means every variable defined in Python's
installed Makefile; on Windows and Mac OS it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary.
"""
global _config_vars
if _config_vars is None:
func = globals().get("_init_" + os.name)
if func:
func()
else:
_config_vars = {}
# Normalized versions of prefix and exec_prefix are handy to have;
# in fact, these are the standard versions used most places in the
# Distutils.
_config_vars['prefix'] = PREFIX
_config_vars['exec_prefix'] = EXEC_PREFIX
if args:
vals = []
for name in args:
vals.append(_config_vars.get(name))
return vals
else:
return _config_vars
def get_config_var(name):
"""Return the value of a single variable using the dictionary
returned by 'get_config_vars()'. Equivalent to
get_config_vars().get(name)
"""
return get_config_vars().get(name)
| Python |
"""distutils.bcppcompiler
Contains BorlandCCompiler, an implementation of the abstract CCompiler class
for the Borland C++ compiler.
"""
# This implementation by Lyle Johnson, based on the original msvccompiler.py
# module and using the directions originally published by Gordon Williams.
# XXX looks like there's a LOT of overlap between these two classes:
# someone should sit down and factor out the common code as
# WindowsCCompiler! --GPW
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: bcppcompiler.py,v 1.18 2004/11/10 22:23:13 loewis Exp $"
import sys, os
from distutils.errors import \
DistutilsExecError, DistutilsPlatformError, \
CompileError, LibError, LinkError, UnknownFileError
from distutils.ccompiler import \
CCompiler, gen_preprocess_options, gen_lib_options
from distutils.file_util import write_file
from distutils.dep_util import newer
from distutils import log
class BCPPCompiler(CCompiler) :
"""Concrete class that implements an interface to the Borland C/C++
compiler, as defined by the CCompiler abstract class.
"""
compiler_type = 'bcpp'
# Just set this so CCompiler's constructor doesn't barf. We currently
# don't use the 'set_executables()' bureaucracy provided by CCompiler,
# as it really isn't necessary for this sort of single-compiler class.
# Would be nice to have a consistent interface with UnixCCompiler,
# though, so it's worth thinking about.
executables = {}
# Private class data (need to distinguish C from C++ source for compiler)
_c_extensions = ['.c']
_cpp_extensions = ['.cc', '.cpp', '.cxx']
# Needed for the filename generation methods provided by the
# base class, CCompiler.
src_extensions = _c_extensions + _cpp_extensions
obj_extension = '.obj'
static_lib_extension = '.lib'
shared_lib_extension = '.dll'
static_lib_format = shared_lib_format = '%s%s'
exe_extension = '.exe'
def __init__ (self,
verbose=0,
dry_run=0,
force=0):
CCompiler.__init__ (self, verbose, dry_run, force)
# These executables are assumed to all be in the path.
# Borland doesn't seem to use any special registry settings to
# indicate their installation locations.
self.cc = "bcc32.exe"
self.linker = "ilink32.exe"
self.lib = "tlib.exe"
self.preprocess_options = None
self.compile_options = ['/tWM', '/O2', '/q', '/g0']
self.compile_options_debug = ['/tWM', '/Od', '/q', '/g0']
self.ldflags_shared = ['/Tpd', '/Gn', '/q', '/x']
self.ldflags_shared_debug = ['/Tpd', '/Gn', '/q', '/x']
self.ldflags_static = []
self.ldflags_exe = ['/Gn', '/q', '/x']
self.ldflags_exe_debug = ['/Gn', '/q', '/x','/r']
# -- Worker methods ------------------------------------------------
def compile(self, sources,
output_dir=None, macros=None, include_dirs=None, debug=0,
extra_preargs=None, extra_postargs=None, depends=None):
macros, objects, extra_postargs, pp_opts, build = \
self._setup_compile(output_dir, macros, include_dirs, sources,
depends, extra_postargs)
compile_opts = extra_preargs or []
compile_opts.append ('-c')
if debug:
compile_opts.extend (self.compile_options_debug)
else:
compile_opts.extend (self.compile_options)
for obj in objects:
try:
src, ext = build[obj]
except KeyError:
continue
# XXX why do the normpath here?
src = os.path.normpath(src)
obj = os.path.normpath(obj)
# XXX _setup_compile() did a mkpath() too but before the normpath.
# Is it possible to skip the normpath?
self.mkpath(os.path.dirname(obj))
if ext == '.res':
# This is already a binary file -- skip it.
continue # the 'for' loop
if ext == '.rc':
# This needs to be compiled to a .res file -- do it now.
try:
self.spawn (["brcc32", "-fo", obj, src])
except DistutilsExecError, msg:
raise CompileError, msg
continue # the 'for' loop
# The next two are both for the real compiler.
if ext in self._c_extensions:
input_opt = ""
elif ext in self._cpp_extensions:
input_opt = "-P"
else:
# Unknown file type -- no extra options. The compiler
# will probably fail, but let it just in case this is a
# file the compiler recognizes even if we don't.
input_opt = ""
output_opt = "-o" + obj
# Compiler command line syntax is: "bcc32 [options] file(s)".
# Note that the source file names must appear at the end of
# the command line.
try:
self.spawn ([self.cc] + compile_opts + pp_opts +
[input_opt, output_opt] +
extra_postargs + [src])
except DistutilsExecError, msg:
raise CompileError, msg
return objects
# compile ()
def create_static_lib (self,
objects,
output_libname,
output_dir=None,
debug=0,
target_lang=None):
(objects, output_dir) = self._fix_object_args (objects, output_dir)
output_filename = \
self.library_filename (output_libname, output_dir=output_dir)
if self._need_link (objects, output_filename):
lib_args = [output_filename, '/u'] + objects
if debug:
pass # XXX what goes here?
try:
self.spawn ([self.lib] + lib_args)
except DistutilsExecError, msg:
raise LibError, msg
else:
log.debug("skipping %s (up-to-date)", output_filename)
# create_static_lib ()
def link (self,
target_desc,
objects,
output_filename,
output_dir=None,
libraries=None,
library_dirs=None,
runtime_library_dirs=None,
export_symbols=None,
debug=0,
extra_preargs=None,
extra_postargs=None,
build_temp=None,
target_lang=None):
# XXX this ignores 'build_temp'! should follow the lead of
# msvccompiler.py
(objects, output_dir) = self._fix_object_args (objects, output_dir)
(libraries, library_dirs, runtime_library_dirs) = \
self._fix_lib_args (libraries, library_dirs, runtime_library_dirs)
if runtime_library_dirs:
log.warn("I don't know what to do with 'runtime_library_dirs': %s",
str(runtime_library_dirs))
if output_dir is not None:
output_filename = os.path.join (output_dir, output_filename)
if self._need_link (objects, output_filename):
# Figure out linker args based on type of target.
if target_desc == CCompiler.EXECUTABLE:
startup_obj = 'c0w32'
if debug:
ld_args = self.ldflags_exe_debug[:]
else:
ld_args = self.ldflags_exe[:]
else:
startup_obj = 'c0d32'
if debug:
ld_args = self.ldflags_shared_debug[:]
else:
ld_args = self.ldflags_shared[:]
# Create a temporary exports file for use by the linker
if export_symbols is None:
def_file = ''
else:
head, tail = os.path.split (output_filename)
modname, ext = os.path.splitext (tail)
temp_dir = os.path.dirname(objects[0]) # preserve tree structure
def_file = os.path.join (temp_dir, '%s.def' % modname)
contents = ['EXPORTS']
for sym in (export_symbols or []):
contents.append(' %s=_%s' % (sym, sym))
self.execute(write_file, (def_file, contents),
"writing %s" % def_file)
# Borland C++ has problems with '/' in paths
objects2 = map(os.path.normpath, objects)
# split objects in .obj and .res files
# Borland C++ needs them at different positions in the command line
objects = [startup_obj]
resources = []
for file in objects2:
(base, ext) = os.path.splitext(os.path.normcase(file))
if ext == '.res':
resources.append(file)
else:
objects.append(file)
for l in library_dirs:
ld_args.append("/L%s" % os.path.normpath(l))
ld_args.append("/L.") # we sometimes use relative paths
# list of object files
ld_args.extend(objects)
# XXX the command-line syntax for Borland C++ is a bit wonky;
# certain filenames are jammed together in one big string, but
# comma-delimited. This doesn't mesh too well with the
# Unix-centric attitude (with a DOS/Windows quoting hack) of
# 'spawn()', so constructing the argument list is a bit
# awkward. Note that doing the obvious thing and jamming all
# the filenames and commas into one argument would be wrong,
# because 'spawn()' would quote any filenames with spaces in
# them. Arghghh!. Apparently it works fine as coded...
# name of dll/exe file
ld_args.extend([',',output_filename])
# no map file and start libraries
ld_args.append(',,')
for lib in libraries:
# see if we find it and if there is a bcpp specific lib
# (xxx_bcpp.lib)
libfile = self.find_library_file(library_dirs, lib, debug)
if libfile is None:
ld_args.append(lib)
# probably a BCPP internal library -- don't warn
else:
# full name which prefers bcpp_xxx.lib over xxx.lib
ld_args.append(libfile)
# some default libraries
ld_args.append ('import32')
ld_args.append ('cw32mt')
# def file for export symbols
ld_args.extend([',',def_file])
# add resource files
ld_args.append(',')
ld_args.extend(resources)
if extra_preargs:
ld_args[:0] = extra_preargs
if extra_postargs:
ld_args.extend(extra_postargs)
self.mkpath (os.path.dirname (output_filename))
try:
self.spawn ([self.linker] + ld_args)
except DistutilsExecError, msg:
raise LinkError, msg
else:
log.debug("skipping %s (up-to-date)", output_filename)
# link ()
# -- Miscellaneous methods -----------------------------------------
def find_library_file (self, dirs, lib, debug=0):
# List of effective library names to try, in order of preference:
# xxx_bcpp.lib is better than xxx.lib
# and xxx_d.lib is better than xxx.lib if debug is set
#
# The "_bcpp" suffix is to handle a Python installation for people
# with multiple compilers (primarily Distutils hackers, I suspect
# ;-). The idea is they'd have one static library for each
# compiler they care about, since (almost?) every Windows compiler
# seems to have a different format for static libraries.
if debug:
dlib = (lib + "_d")
try_names = (dlib + "_bcpp", lib + "_bcpp", dlib, lib)
else:
try_names = (lib + "_bcpp", lib)
for dir in dirs:
for name in try_names:
libfile = os.path.join(dir, self.library_filename(name))
if os.path.exists(libfile):
return libfile
else:
# Oops, didn't find it in *any* of 'dirs'
return None
# overwrite the one from CCompiler to support rc and res-files
def object_filenames (self,
source_filenames,
strip_dir=0,
output_dir=''):
if output_dir is None: output_dir = ''
obj_names = []
for src_name in source_filenames:
# use normcase to make sure '.rc' is really '.rc' and not '.RC'
(base, ext) = os.path.splitext (os.path.normcase(src_name))
if ext not in (self.src_extensions + ['.rc','.res']):
raise UnknownFileError, \
"unknown file type '%s' (from '%s')" % \
(ext, src_name)
if strip_dir:
base = os.path.basename (base)
if ext == '.res':
# these can go unchanged
obj_names.append (os.path.join (output_dir, base + ext))
elif ext == '.rc':
# these need to be compiled to .res-files
obj_names.append (os.path.join (output_dir, base + '.res'))
else:
obj_names.append (os.path.join (output_dir,
base + self.obj_extension))
return obj_names
# object_filenames ()
def preprocess (self,
source,
output_file=None,
macros=None,
include_dirs=None,
extra_preargs=None,
extra_postargs=None):
(_, macros, include_dirs) = \
self._fix_compile_args(None, macros, include_dirs)
pp_opts = gen_preprocess_options(macros, include_dirs)
pp_args = ['cpp32.exe'] + pp_opts
if output_file is not None:
pp_args.append('-o' + output_file)
if extra_preargs:
pp_args[:0] = extra_preargs
if extra_postargs:
pp_args.extend(extra_postargs)
pp_args.append(source)
# We need to preprocess: either we're being forced to, or the
# source file is newer than the target (or the target doesn't
# exist).
if self.force or output_file is None or newer(source, output_file):
if output_file:
self.mkpath(os.path.dirname(output_file))
try:
self.spawn(pp_args)
except DistutilsExecError, msg:
print msg
raise CompileError, msg
# preprocess()
| Python |
"""Bastionification utility.
A bastion (for another object -- the 'original') is an object that has
the same methods as the original but does not give access to its
instance variables. Bastions have a number of uses, but the most
obvious one is to provide code executing in restricted mode with a
safe interface to an object implemented in unrestricted mode.
The bastionification routine has an optional second argument which is
a filter function. Only those methods for which the filter method
(called with the method name as argument) returns true are accessible.
The default filter method returns true unless the method name begins
with an underscore.
There are a number of possible implementations of bastions. We use a
'lazy' approach where the bastion's __getattr__() discipline does all
the work for a particular method the first time it is used. This is
usually fastest, especially if the user doesn't call all available
methods. The retrieved methods are stored as instance variables of
the bastion, so the overhead is only occurred on the first use of each
method.
Detail: the bastion class has a __repr__() discipline which includes
the repr() of the original object. This is precomputed when the
bastion is created.
"""
__all__ = ["BastionClass", "Bastion"]
from types import MethodType
class BastionClass:
"""Helper class used by the Bastion() function.
You could subclass this and pass the subclass as the bastionclass
argument to the Bastion() function, as long as the constructor has
the same signature (a get() function and a name for the object).
"""
def __init__(self, get, name):
"""Constructor.
Arguments:
get - a function that gets the attribute value (by name)
name - a human-readable name for the original object
(suggestion: use repr(object))
"""
self._get_ = get
self._name_ = name
def __repr__(self):
"""Return a representation string.
This includes the name passed in to the constructor, so that
if you print the bastion during debugging, at least you have
some idea of what it is.
"""
return "<Bastion for %s>" % self._name_
def __getattr__(self, name):
"""Get an as-yet undefined attribute value.
This calls the get() function that was passed to the
constructor. The result is stored as an instance variable so
that the next time the same attribute is requested,
__getattr__() won't be invoked.
If the get() function raises an exception, this is simply
passed on -- exceptions are not cached.
"""
attribute = self._get_(name)
self.__dict__[name] = attribute
return attribute
def Bastion(object, filter = lambda name: name[:1] != '_',
name=None, bastionclass=BastionClass):
"""Create a bastion for an object, using an optional filter.
See the Bastion module's documentation for background.
Arguments:
object - the original object
filter - a predicate that decides whether a function name is OK;
by default all names are OK that don't start with '_'
name - the name of the object; default repr(object)
bastionclass - class used to create the bastion; default BastionClass
"""
raise RuntimeError, "This code is not secure in Python 2.2 and 2.3"
# Note: we define *two* ad-hoc functions here, get1 and get2.
# Both are intended to be called in the same way: get(name).
# It is clear that the real work (getting the attribute
# from the object and calling the filter) is done in get1.
# Why can't we pass get1 to the bastion? Because the user
# would be able to override the filter argument! With get2,
# overriding the default argument is no security loophole:
# all it does is call it.
# Also notice that we can't place the object and filter as
# instance variables on the bastion object itself, since
# the user has full access to all instance variables!
def get1(name, object=object, filter=filter):
"""Internal function for Bastion(). See source comments."""
if filter(name):
attribute = getattr(object, name)
if type(attribute) == MethodType:
return attribute
raise AttributeError, name
def get2(name, get1=get1):
"""Internal function for Bastion(). See source comments."""
return get1(name)
if name is None:
name = repr(object)
return bastionclass(get2, name)
def _test():
"""Test the Bastion() function."""
class Original:
def __init__(self):
self.sum = 0
def add(self, n):
self._add(n)
def _add(self, n):
self.sum = self.sum + n
def total(self):
return self.sum
o = Original()
b = Bastion(o)
testcode = """if 1:
b.add(81)
b.add(18)
print "b.total() =", b.total()
try:
print "b.sum =", b.sum,
except:
print "inaccessible"
else:
print "accessible"
try:
print "b._add =", b._add,
except:
print "inaccessible"
else:
print "accessible"
try:
print "b._get_.func_defaults =", map(type, b._get_.func_defaults),
except:
print "inaccessible"
else:
print "accessible"
\n"""
exec testcode
print '='*20, "Using rexec:", '='*20
import rexec
r = rexec.RExec()
m = r.add_module('__main__')
m.b = b
r.r_exec(testcode)
if __name__ == '__main__':
_test()
| Python |
"""Implements (a subset of) Sun XDR -- eXternal Data Representation.
See: RFC 1014
"""
import struct
try:
from cStringIO import StringIO as _StringIO
except ImportError:
from StringIO import StringIO as _StringIO
__all__ = ["Error", "Packer", "Unpacker", "ConversionError"]
# exceptions
class Error(Exception):
"""Exception class for this module. Use:
except xdrlib.Error, var:
# var has the Error instance for the exception
Public ivars:
msg -- contains the message
"""
def __init__(self, msg):
self.msg = msg
def __repr__(self):
return repr(self.msg)
def __str__(self):
return str(self.msg)
class ConversionError(Error):
pass
class Packer:
"""Pack various data representations into a buffer."""
def __init__(self):
self.reset()
def reset(self):
self.__buf = _StringIO()
def get_buffer(self):
return self.__buf.getvalue()
# backwards compatibility
get_buf = get_buffer
def pack_uint(self, x):
self.__buf.write(struct.pack('>L', x))
pack_int = pack_uint
pack_enum = pack_int
def pack_bool(self, x):
if x: self.__buf.write('\0\0\0\1')
else: self.__buf.write('\0\0\0\0')
def pack_uhyper(self, x):
self.pack_uint(x>>32 & 0xffffffffL)
self.pack_uint(x & 0xffffffffL)
pack_hyper = pack_uhyper
def pack_float(self, x):
try: self.__buf.write(struct.pack('>f', x))
except struct.error, msg:
raise ConversionError, msg
def pack_double(self, x):
try: self.__buf.write(struct.pack('>d', x))
except struct.error, msg:
raise ConversionError, msg
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.write(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
pack_bytes = 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:
"""Unpacks various data representations from the given buffer."""
def __init__(self, data):
self.reset(data)
def reset(self, data):
self.__buf = data
self.__pos = 0
def get_position(self):
return self.__pos
def set_position(self, position):
self.__pos = position
def get_buffer(self):
return self.__buf
def done(self):
if self.__pos < len(self.__buf):
raise Error('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 = struct.unpack('>L', data)[0]
try:
return int(x)
except OverflowError:
return x
def unpack_int(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)[0]
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):
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):
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
unpack_bytes = unpack_string
def unpack_list(self, unpack_item):
list = []
while 1:
x = self.unpack_uint()
if x == 0: break
if x != 1:
raise ConversionError, '0 or 1 expected, got %r' % (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)
# test suite
def _test():
p = Packer()
packtest = [
(p.pack_uint, (9,)),
(p.pack_bool, (None,)),
(p.pack_bool, ('hello',)),
(p.pack_uhyper, (45L,)),
(p.pack_float, (1.9,)),
(p.pack_double, (1.9,)),
(p.pack_string, ('hello world',)),
(p.pack_list, (range(5), p.pack_uint)),
(p.pack_array, (['what', 'is', 'hapnin', 'doctor'], p.pack_string)),
]
succeedlist = [1] * len(packtest)
count = 0
for method, args in packtest:
print 'pack test', count,
try:
method(*args)
print 'succeeded'
except ConversionError, var:
print 'ConversionError:', var.msg
succeedlist[count] = 0
count = count + 1
data = p.get_buffer()
# now verify
up = Unpacker(data)
unpacktest = [
(up.unpack_uint, (), lambda x: x == 9),
(up.unpack_bool, (), lambda x: not x),
(up.unpack_bool, (), lambda x: x),
(up.unpack_uhyper, (), lambda x: x == 45L),
(up.unpack_float, (), lambda x: 1.89 < x < 1.91),
(up.unpack_double, (), lambda x: 1.89 < x < 1.91),
(up.unpack_string, (), lambda x: x == 'hello world'),
(up.unpack_list, (up.unpack_uint,), lambda x: x == range(5)),
(up.unpack_array, (up.unpack_string,),
lambda x: x == ['what', 'is', 'hapnin', 'doctor']),
]
count = 0
for method, args, pred in unpacktest:
print 'unpack test', count,
try:
if succeedlist[count]:
x = method(*args)
print pred(x) and 'succeeded' or 'failed', ':', x
else:
print 'skipping'
except ConversionError, var:
print 'ConversionError:', var.msg
count = count + 1
if __name__ == '__main__':
_test()
| Python |
#! /usr/bin/env python
"""Tool for measuring execution time of small code snippets.
This module avoids a number of common traps for measuring execution
times. See also Tim Peters' introduction to the Algorithms chapter in
the Python Cookbook, published by O'Reilly.
Library usage: see the Timer class.
Command line usage:
python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement]
Options:
-n/--number N: how many times to execute 'statement' (default: see below)
-r/--repeat N: how many times to repeat the timer (default 3)
-s/--setup S: statement to be executed once initially (default 'pass')
-t/--time: use time.time() (default on Unix)
-c/--clock: use time.clock() (default on Windows)
-v/--verbose: print raw timing results; repeat for more digits precision
-h/--help: print this usage message and exit
statement: statement to be timed (default 'pass')
A multi-line statement may be given by specifying each line as a
separate argument; indented lines are possible by enclosing an
argument in quotes and using leading spaces. Multiple -s options are
treated similarly.
If -n is not given, a suitable number of loops is calculated by trying
successive powers of 10 until the total time is at least 0.2 seconds.
The difference in default timer function is because on Windows,
clock() has microsecond granularity but time()'s granularity is 1/60th
of a second; on Unix, clock() has 1/100th of a second granularity and
time() is much more precise. On either platform, the default timer
functions measure wall clock time, not the CPU time. This means that
other processes running on the same computer may interfere with the
timing. The best thing to do when accurate timing is necessary is to
repeat the timing a few times and use the best time. The -r option is
good for this; the default of 3 repetitions is probably enough in most
cases. On Unix, you can use clock() to measure CPU time.
Note: there is a certain baseline overhead associated with executing a
pass statement. The code here doesn't try to hide it, but you should
be aware of it. The baseline overhead can be measured by invoking the
program without arguments.
The baseline overhead differs between Python versions! Also, to
fairly compare older Python versions to Python 2.3, you may want to
use python -O for the older versions to avoid timing SET_LINENO
instructions.
"""
import gc
import sys
import time
try:
import itertools
except ImportError:
# Must be an older Python version (see timeit() below)
itertools = None
__all__ = ["Timer"]
dummy_src_name = "<timeit-src>"
default_number = 1000000
default_repeat = 3
if sys.platform == "win32":
# On Windows, the best timer is time.clock()
default_timer = time.clock
else:
# On most other platforms the best timer is time.time()
default_timer = time.time
# Don't change the indentation of the template; the reindent() calls
# in Timer.__init__() depend on setup being indented 4 spaces and stmt
# being indented 8 spaces.
template = """
def inner(_it, _timer):
%(setup)s
_t0 = _timer()
for _i in _it:
%(stmt)s
_t1 = _timer()
return _t1 - _t0
"""
def reindent(src, indent):
"""Helper to reindent a multi-line statement."""
return src.replace("\n", "\n" + " "*indent)
class Timer:
"""Class for timing execution speed of small code snippets.
The constructor takes a statement to be timed, an additional
statement used for setup, and a timer function. Both statements
default to 'pass'; the timer function is platform-dependent (see
module doc string).
To measure the execution time of the first statement, use the
timeit() method. The repeat() method is a convenience to call
timeit() multiple times and return a list of results.
The statements may contain newlines, as long as they don't contain
multi-line string literals.
"""
def __init__(self, stmt="pass", setup="pass", timer=default_timer):
"""Constructor. See class doc string."""
self.timer = timer
stmt = reindent(stmt, 8)
setup = reindent(setup, 4)
src = template % {'stmt': stmt, 'setup': setup}
self.src = src # Save for traceback display
code = compile(src, dummy_src_name, "exec")
ns = {}
exec code in globals(), ns
self.inner = ns["inner"]
def print_exc(self, file=None):
"""Helper to print a traceback from the timed code.
Typical use:
t = Timer(...) # outside the try/except
try:
t.timeit(...) # or t.repeat(...)
except:
t.print_exc()
The advantage over the standard traceback is that source lines
in the compiled template will be displayed.
The optional file argument directs where the traceback is
sent; it defaults to sys.stderr.
"""
import linecache, traceback
linecache.cache[dummy_src_name] = (len(self.src),
None,
self.src.split("\n"),
dummy_src_name)
traceback.print_exc(file=file)
def timeit(self, number=default_number):
"""Time 'number' executions of the main statement.
To be precise, this executes the setup statement once, and
then returns the time it takes to execute the main statement
a number of times, as a float measured in seconds. The
argument is the number of times through the loop, defaulting
to one million. The main statement, the setup statement and
the timer function to be used are passed to the constructor.
"""
if itertools:
it = itertools.repeat(None, number)
else:
it = [None] * number
gcold = gc.isenabled()
gc.disable()
timing = self.inner(it, self.timer)
if gcold:
gc.enable()
return timing
def repeat(self, repeat=default_repeat, number=default_number):
"""Call timeit() a few times.
This is a convenience function that calls the timeit()
repeatedly, returning a list of results. The first argument
specifies how many times to call timeit(), defaulting to 3;
the second argument specifies the timer argument, defaulting
to one million.
Note: it's tempting to calculate mean and standard deviation
from the result vector and report these. However, this is not
very useful. In a typical case, the lowest value gives a
lower bound for how fast your machine can run the given code
snippet; higher values in the result vector are typically not
caused by variability in Python's speed, but by other
processes interfering with your timing accuracy. So the min()
of the result is probably the only number you should be
interested in. After that, you should look at the entire
vector and apply common sense rather than statistics.
"""
r = []
for i in range(repeat):
t = self.timeit(number)
r.append(t)
return r
def main(args=None):
"""Main program, used when run as a script.
The optional argument specifies the command line to be parsed,
defaulting to sys.argv[1:].
The return value is an exit code to be passed to sys.exit(); it
may be None to indicate success.
When an exception happens during timing, a traceback is printed to
stderr and the return value is 1. Exceptions at other times
(including the template compilation) are not caught.
"""
if args is None:
args = sys.argv[1:]
import getopt
try:
opts, args = getopt.getopt(args, "n:s:r:tcvh",
["number=", "setup=", "repeat=",
"time", "clock", "verbose", "help"])
except getopt.error, err:
print err
print "use -h/--help for command line help"
return 2
timer = default_timer
stmt = "\n".join(args) or "pass"
number = 0 # auto-determine
setup = []
repeat = default_repeat
verbose = 0
precision = 3
for o, a in opts:
if o in ("-n", "--number"):
number = int(a)
if o in ("-s", "--setup"):
setup.append(a)
if o in ("-r", "--repeat"):
repeat = int(a)
if repeat <= 0:
repeat = 1
if o in ("-t", "--time"):
timer = time.time
if o in ("-c", "--clock"):
timer = time.clock
if o in ("-v", "--verbose"):
if verbose:
precision += 1
verbose += 1
if o in ("-h", "--help"):
print __doc__,
return 0
setup = "\n".join(setup) or "pass"
# Include the current directory, so that local imports work (sys.path
# contains the directory of this script, rather than the current
# directory)
import os
sys.path.insert(0, os.curdir)
t = Timer(stmt, setup, timer)
if number == 0:
# determine number so that 0.2 <= total time < 2.0
for i in range(1, 10):
number = 10**i
try:
x = t.timeit(number)
except:
t.print_exc()
return 1
if verbose:
print "%d loops -> %.*g secs" % (number, precision, x)
if x >= 0.2:
break
try:
r = t.repeat(repeat, number)
except:
t.print_exc()
return 1
best = min(r)
if verbose:
print "raw times:", " ".join(["%.*g" % (precision, x) for x in r])
print "%d loops," % number,
usec = best * 1e6 / number
if usec < 1000:
print "best of %d: %.*g usec per loop" % (repeat, precision, usec)
else:
msec = usec / 1000
if msec < 1000:
print "best of %d: %.*g msec per loop" % (repeat, precision, msec)
else:
sec = msec / 1000
print "best of %d: %.*g sec per loop" % (repeat, precision, sec)
return None
if __name__ == "__main__":
sys.exit(main())
| Python |
#! /usr/bin/env python
'''SMTP/ESMTP client class.
This should follow RFC 821 (SMTP), RFC 1869 (ESMTP), RFC 2554 (SMTP
Authentication) and RFC 2487 (Secure SMTP over TLS).
Notes:
Please remember, when doing ESMTP, that the names of the SMTP service
extensions are NOT the same thing as the option keywords for the RCPT
and MAIL commands!
Example:
>>> import smtplib
>>> s=smtplib.SMTP("localhost")
>>> print s.help()
This is Sendmail version 8.8.4
Topics:
HELO EHLO MAIL RCPT DATA
RSET NOOP QUIT HELP VRFY
EXPN VERB ETRN DSN
For more info use "HELP <topic>".
To report bugs in the implementation send email to
sendmail-bugs@sendmail.org.
For local information send email to Postmaster at your site.
End of HELP info
>>> s.putcmd("vrfy","someone@here")
>>> s.getreply()
(250, "Somebody OverHere <somebody@here.my.org>")
>>> s.quit()
'''
# Author: The Dragon De Monsyne <dragondm@integral.org>
# ESMTP support, test code and doc fixes added by
# Eric S. Raymond <esr@thyrsus.com>
# Better RFC 821 compliance (MAIL and RCPT, and CRLF in data)
# by Carey Evans <c.evans@clear.net.nz>, for picky mail servers.
# RFC 2554 (authentication) support by Gerhard Haering <gerhard@bigfoot.de>.
#
# This was modified from the Python 1.5 library HTTP lib.
import socket
import re
import rfc822
import base64
import hmac
from email.base64MIME import encode as encode_base64
from sys import stderr
__all__ = ["SMTPException","SMTPServerDisconnected","SMTPResponseException",
"SMTPSenderRefused","SMTPRecipientsRefused","SMTPDataError",
"SMTPConnectError","SMTPHeloError","SMTPAuthenticationError",
"quoteaddr","quotedata","SMTP"]
SMTP_PORT = 25
CRLF="\r\n"
OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I)
# Exception classes used by this module.
class SMTPException(Exception):
"""Base class for all exceptions raised by this module."""
class SMTPServerDisconnected(SMTPException):
"""Not connected to any SMTP server.
This exception is raised when the server unexpectedly disconnects,
or when an attempt is made to use the SMTP instance before
connecting it to a server.
"""
class SMTPResponseException(SMTPException):
"""Base class for all exceptions that include an SMTP error code.
These exceptions are generated in some instances when the SMTP
server returns an error code. The error code is stored in the
`smtp_code' attribute of the error, and the `smtp_error' attribute
is set to the error message.
"""
def __init__(self, code, msg):
self.smtp_code = code
self.smtp_error = msg
self.args = (code, msg)
class SMTPSenderRefused(SMTPResponseException):
"""Sender address refused.
In addition to the attributes set by on all SMTPResponseException
exceptions, this sets `sender' to the string that the SMTP refused.
"""
def __init__(self, code, msg, sender):
self.smtp_code = code
self.smtp_error = msg
self.sender = sender
self.args = (code, msg, sender)
class SMTPRecipientsRefused(SMTPException):
"""All recipient addresses refused.
The errors for each recipient are accessible through the attribute
'recipients', which is a dictionary of exactly the same sort as
SMTP.sendmail() returns.
"""
def __init__(self, recipients):
self.recipients = recipients
self.args = ( recipients,)
class SMTPDataError(SMTPResponseException):
"""The SMTP server didn't accept the data."""
class SMTPConnectError(SMTPResponseException):
"""Error during connection establishment."""
class SMTPHeloError(SMTPResponseException):
"""The server refused our HELO reply."""
class SMTPAuthenticationError(SMTPResponseException):
"""Authentication error.
Most probably the server didn't accept the username/password
combination provided.
"""
class SSLFakeSocket:
"""A fake socket object that really wraps a SSLObject.
It only supports what is needed in smtplib.
"""
def __init__(self, realsock, sslobj):
self.realsock = realsock
self.sslobj = sslobj
def send(self, str):
self.sslobj.write(str)
return len(str)
sendall = send
def close(self):
self.realsock.close()
class SSLFakeFile:
"""A fake file like object that really wraps a SSLObject.
It only supports what is needed in smtplib.
"""
def __init__( self, sslobj):
self.sslobj = sslobj
def readline(self):
str = ""
chr = None
while chr != "\n":
chr = self.sslobj.read(1)
str += chr
return str
def close(self):
pass
def quoteaddr(addr):
"""Quote a subset of the email addresses defined by RFC 821.
Should be able to handle anything rfc822.parseaddr can handle.
"""
m = (None, None)
try:
m=rfc822.parseaddr(addr)[1]
except AttributeError:
pass
if m == (None, None): # Indicates parse failure or AttributeError
#something weird here.. punt -ddm
return "<%s>" % addr
else:
return "<%s>" % m
def quotedata(data):
"""Quote data for email.
Double leading '.', and change Unix newline '\\n', or Mac '\\r' into
Internet CRLF end-of-line.
"""
return re.sub(r'(?m)^\.', '..',
re.sub(r'(?:\r\n|\n|\r(?!\n))', CRLF, data))
class SMTP:
"""This class manages a connection to an SMTP or ESMTP server.
SMTP Objects:
SMTP objects have the following attributes:
helo_resp
This is the message given by the server in response to the
most recent HELO command.
ehlo_resp
This is the message given by the server in response to the
most recent EHLO command. This is usually multiline.
does_esmtp
This is a True value _after you do an EHLO command_, if the
server supports ESMTP.
esmtp_features
This is a dictionary, which, if the server supports ESMTP,
will _after you do an EHLO command_, contain the names of the
SMTP service extensions this server supports, and their
parameters (if any).
Note, all extension names are mapped to lower case in the
dictionary.
See each method's docstrings for details. In general, there is a
method of the same name to perform each SMTP command. There is also a
method called 'sendmail' that will do an entire mail transaction.
"""
debuglevel = 0
file = None
helo_resp = None
ehlo_resp = None
does_esmtp = 0
def __init__(self, host = '', port = 0, local_hostname = None):
"""Initialize a new instance.
If specified, `host' is the name of the remote host to which to
connect. If specified, `port' specifies the port to which to connect.
By default, smtplib.SMTP_PORT is used. An SMTPConnectError is raised
if the specified `host' doesn't respond correctly. If specified,
`local_hostname` is used as the FQDN of the local host. By default,
the local hostname is found using socket.getfqdn().
"""
self.esmtp_features = {}
if host:
(code, msg) = self.connect(host, port)
if code != 220:
raise SMTPConnectError(code, msg)
if local_hostname is not None:
self.local_hostname = local_hostname
else:
# RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and
# if that can't be calculated, that we should use a domain literal
# instead (essentially an encoded IP address like [A.B.C.D]).
fqdn = socket.getfqdn()
if '.' in fqdn:
self.local_hostname = fqdn
else:
# We can't find an fqdn hostname, so use a domain literal
addr = socket.gethostbyname(socket.gethostname())
self.local_hostname = '[%s]' % addr
def set_debuglevel(self, debuglevel):
"""Set the debug output level.
A non-false value results in debug messages for connection and for all
messages sent to and received from the server.
"""
self.debuglevel = debuglevel
def connect(self, host='localhost', port = 0):
"""Connect to a host on a given port.
If the hostname ends with a colon (`:') followed by a number, and
there is no port specified, that suffix will be stripped off and the
number interpreted as the port number to use.
Note: This method is automatically invoked by __init__, if a host is
specified during instantiation.
"""
if not port and (host.find(':') == host.rfind(':')):
i = host.rfind(':')
if i >= 0:
host, port = host[:i], host[i+1:]
try: port = int(port)
except ValueError:
raise socket.error, "nonnumeric port"
if not port: port = SMTP_PORT
if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
msg = "getaddrinfo returns an empty list"
self.sock = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
self.sock.connect(sa)
except socket.error, msg:
if self.debuglevel > 0: print>>stderr, 'connect fail:', (host, port)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
(code, msg) = self.getreply()
if self.debuglevel > 0: print>>stderr, "connect:", msg
return (code, msg)
def send(self, str):
"""Send `str' to the server."""
if self.debuglevel > 0: print>>stderr, 'send:', repr(str)
if self.sock:
try:
self.sock.sendall(str)
except socket.error:
self.close()
raise SMTPServerDisconnected('Server not connected')
else:
raise SMTPServerDisconnected('please run connect() first')
def putcmd(self, cmd, args=""):
"""Send a command to the server."""
if args == "":
str = '%s%s' % (cmd, CRLF)
else:
str = '%s %s%s' % (cmd, args, CRLF)
self.send(str)
def getreply(self):
"""Get a reply from the server.
Returns a tuple consisting of:
- server response code (e.g. '250', or such, if all goes well)
Note: returns -1 if it can't read response code.
- server response string corresponding to response code (multiline
responses are converted to a single, multiline string).
Raises SMTPServerDisconnected if end-of-file is reached.
"""
resp=[]
if self.file is None:
self.file = self.sock.makefile('rb')
while 1:
line = self.file.readline()
if line == '':
self.close()
raise SMTPServerDisconnected("Connection unexpectedly closed")
if self.debuglevel > 0: print>>stderr, 'reply:', repr(line)
resp.append(line[4:].strip())
code=line[:3]
# Check that the error code is syntactically correct.
# Don't attempt to read a continuation line if it is broken.
try:
errcode = int(code)
except ValueError:
errcode = -1
break
# Check if multiline response.
if line[3:4]!="-":
break
errmsg = "\n".join(resp)
if self.debuglevel > 0:
print>>stderr, 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
return errcode, errmsg
def docmd(self, cmd, args=""):
"""Send a command, and return its response code."""
self.putcmd(cmd,args)
return self.getreply()
# std smtp commands
def helo(self, name=''):
"""SMTP 'helo' command.
Hostname to send for this command defaults to the FQDN of the local
host.
"""
self.putcmd("helo", name or self.local_hostname)
(code,msg)=self.getreply()
self.helo_resp=msg
return (code,msg)
def ehlo(self, name=''):
""" SMTP 'ehlo' command.
Hostname to send for this command defaults to the FQDN of the local
host.
"""
self.esmtp_features = {}
self.putcmd("ehlo", name or self.local_hostname)
(code,msg)=self.getreply()
# According to RFC1869 some (badly written)
# MTA's will disconnect on an ehlo. Toss an exception if
# that happens -ddm
if code == -1 and len(msg) == 0:
self.close()
raise SMTPServerDisconnected("Server not connected")
self.ehlo_resp=msg
if code != 250:
return (code,msg)
self.does_esmtp=1
#parse the ehlo response -ddm
resp=self.ehlo_resp.split('\n')
del resp[0]
for each in resp:
# To be able to communicate with as many SMTP servers as possible,
# we have to take the old-style auth advertisement into account,
# because:
# 1) Else our SMTP feature parser gets confused.
# 2) There are some servers that only advertise the auth methods we
# support using the old style.
auth_match = OLDSTYLE_AUTH.match(each)
if auth_match:
# This doesn't remove duplicates, but that's no problem
self.esmtp_features["auth"] = self.esmtp_features.get("auth", "") \
+ " " + auth_match.groups(0)[0]
continue
# RFC 1869 requires a space between ehlo keyword and parameters.
# It's actually stricter, in that only spaces are allowed between
# parameters, but were not going to check for that here. Note
# that the space isn't present if there are no parameters.
m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*) ?',each)
if m:
feature=m.group("feature").lower()
params=m.string[m.end("feature"):].strip()
if feature == "auth":
self.esmtp_features[feature] = self.esmtp_features.get(feature, "") \
+ " " + params
else:
self.esmtp_features[feature]=params
return (code,msg)
def has_extn(self, opt):
"""Does the server support a given SMTP service extension?"""
return opt.lower() in self.esmtp_features
def help(self, args=''):
"""SMTP 'help' command.
Returns help text from server."""
self.putcmd("help", args)
return self.getreply()
def rset(self):
"""SMTP 'rset' command -- resets session."""
return self.docmd("rset")
def noop(self):
"""SMTP 'noop' command -- doesn't do anything :>"""
return self.docmd("noop")
def mail(self,sender,options=[]):
"""SMTP 'mail' command -- begins mail xfer session."""
optionlist = ''
if options and self.does_esmtp:
optionlist = ' ' + ' '.join(options)
self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender) ,optionlist))
return self.getreply()
def rcpt(self,recip,options=[]):
"""SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
optionlist = ''
if options and self.does_esmtp:
optionlist = ' ' + ' '.join(options)
self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
return self.getreply()
def data(self,msg):
"""SMTP 'DATA' command -- sends message data to server.
Automatically quotes lines beginning with a period per rfc821.
Raises SMTPDataError if there is an unexpected reply to the
DATA command; the return value from this method is the final
response code received when the all data is sent.
"""
self.putcmd("data")
(code,repl)=self.getreply()
if self.debuglevel >0 : print>>stderr, "data:", (code,repl)
if code != 354:
raise SMTPDataError(code,repl)
else:
q = quotedata(msg)
if q[-2:] != CRLF:
q = q + CRLF
q = q + "." + CRLF
self.send(q)
(code,msg)=self.getreply()
if self.debuglevel >0 : print>>stderr, "data:", (code,msg)
return (code,msg)
def verify(self, address):
"""SMTP 'verify' command -- checks for address validity."""
self.putcmd("vrfy", quoteaddr(address))
return self.getreply()
# a.k.a.
vrfy=verify
def expn(self, address):
"""SMTP 'verify' command -- checks for address validity."""
self.putcmd("expn", quoteaddr(address))
return self.getreply()
# some useful methods
def login(self, user, password):
"""Log in on an SMTP server that requires authentication.
The arguments are:
- user: The user name to authenticate with.
- password: The password for the authentication.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first.
This method will return normally if the authentication was successful.
This method may raise the following exceptions:
SMTPHeloError The server didn't reply properly to
the helo greeting.
SMTPAuthenticationError The server didn't accept the username/
password combination.
SMTPException No suitable authentication method was
found.
"""
def encode_cram_md5(challenge, user, password):
challenge = base64.decodestring(challenge)
response = user + " " + hmac.HMAC(password, challenge).hexdigest()
return encode_base64(response, eol="")
def encode_plain(user, password):
return encode_base64("%s\0%s\0%s" % (user, user, password), eol="")
AUTH_PLAIN = "PLAIN"
AUTH_CRAM_MD5 = "CRAM-MD5"
AUTH_LOGIN = "LOGIN"
if self.helo_resp is None and self.ehlo_resp is None:
if not (200 <= self.ehlo()[0] <= 299):
(code, resp) = self.helo()
if not (200 <= code <= 299):
raise SMTPHeloError(code, resp)
if not self.has_extn("auth"):
raise SMTPException("SMTP AUTH extension not supported by server.")
# Authentication methods the server supports:
authlist = self.esmtp_features["auth"].split()
# List of authentication methods we support: from preferred to
# less preferred methods. Except for the purpose of testing the weaker
# ones, we prefer stronger methods like CRAM-MD5:
preferred_auths = [AUTH_CRAM_MD5, AUTH_PLAIN, AUTH_LOGIN]
# Determine the authentication method we'll use
authmethod = None
for method in preferred_auths:
if method in authlist:
authmethod = method
break
if authmethod == AUTH_CRAM_MD5:
(code, resp) = self.docmd("AUTH", AUTH_CRAM_MD5)
if code == 503:
# 503 == 'Error: already authenticated'
return (code, resp)
(code, resp) = self.docmd(encode_cram_md5(resp, user, password))
elif authmethod == AUTH_PLAIN:
(code, resp) = self.docmd("AUTH",
AUTH_PLAIN + " " + encode_plain(user, password))
elif authmethod == AUTH_LOGIN:
(code, resp) = self.docmd("AUTH",
"%s %s" % (AUTH_LOGIN, encode_base64(user, eol="")))
if code != 334:
raise SMTPAuthenticationError(code, resp)
(code, resp) = self.docmd(encode_base64(password, eol=""))
elif authmethod is None:
raise SMTPException("No suitable authentication method found.")
if code not in [235, 503]:
# 235 == 'Authentication successful'
# 503 == 'Error: already authenticated'
raise SMTPAuthenticationError(code, resp)
return (code, resp)
def starttls(self, keyfile = None, certfile = None):
"""Puts the connection to the SMTP server into TLS mode.
If the server supports TLS, this will encrypt the rest of the SMTP
session. If you provide the keyfile and certfile parameters,
the identity of the SMTP server and client can be checked. This,
however, depends on whether the socket module really checks the
certificates.
"""
(resp, reply) = self.docmd("STARTTLS")
if resp == 220:
sslobj = socket.ssl(self.sock, keyfile, certfile)
self.sock = SSLFakeSocket(self.sock, sslobj)
self.file = SSLFakeFile(sslobj)
return (resp, reply)
def sendmail(self, from_addr, to_addrs, msg, mail_options=[],
rcpt_options=[]):
"""This command performs an entire mail transaction.
The arguments are:
- from_addr : The address sending this mail.
- to_addrs : A list of addresses to send this mail to. A bare
string will be treated as a list with 1 address.
- msg : The message to send.
- mail_options : List of ESMTP options (such as 8bitmime) for the
mail command.
- rcpt_options : List of ESMTP options (such as DSN commands) for
all the rcpt commands.
If there has been no previous EHLO or HELO command this session, this
method tries ESMTP EHLO first. If the server does ESMTP, message size
and each of the specified options will be passed to it. If EHLO
fails, HELO will be tried and ESMTP options suppressed.
This method will return normally if the mail is accepted for at least
one recipient. It returns a dictionary, with one entry for each
recipient that was refused. Each entry contains a tuple of the SMTP
error code and the accompanying error message sent by the server.
This method may raise the following exceptions:
SMTPHeloError The server didn't reply properly to
the helo greeting.
SMTPRecipientsRefused The server rejected ALL recipients
(no mail was sent).
SMTPSenderRefused The server didn't accept the from_addr.
SMTPDataError The server replied with an unexpected
error code (other than a refusal of
a recipient).
Note: the connection will be open even after an exception is raised.
Example:
>>> import smtplib
>>> s=smtplib.SMTP("localhost")
>>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
>>> msg = '''\\
... From: Me@my.org
... Subject: testin'...
...
... This is a test '''
>>> s.sendmail("me@my.org",tolist,msg)
{ "three@three.org" : ( 550 ,"User unknown" ) }
>>> s.quit()
In the above example, the message was accepted for delivery to three
of the four addresses, and one was rejected, with the error code
550. If all addresses are accepted, then the method will return an
empty dictionary.
"""
if self.helo_resp is None and self.ehlo_resp is None:
if not (200 <= self.ehlo()[0] <= 299):
(code,resp) = self.helo()
if not (200 <= code <= 299):
raise SMTPHeloError(code, resp)
esmtp_opts = []
if self.does_esmtp:
# Hmmm? what's this? -ddm
# self.esmtp_features['7bit']=""
if self.has_extn('size'):
esmtp_opts.append("size=%d" % len(msg))
for option in mail_options:
esmtp_opts.append(option)
(code,resp) = self.mail(from_addr, esmtp_opts)
if code != 250:
self.rset()
raise SMTPSenderRefused(code, resp, from_addr)
senderrs={}
if isinstance(to_addrs, basestring):
to_addrs = [to_addrs]
for each in to_addrs:
(code,resp)=self.rcpt(each, rcpt_options)
if (code != 250) and (code != 251):
senderrs[each]=(code,resp)
if len(senderrs)==len(to_addrs):
# the server refused all our recipients
self.rset()
raise SMTPRecipientsRefused(senderrs)
(code,resp) = self.data(msg)
if code != 250:
self.rset()
raise SMTPDataError(code, resp)
#if we got here then somebody got our mail
return senderrs
def close(self):
"""Close the connection to the SMTP server."""
if self.file:
self.file.close()
self.file = None
if self.sock:
self.sock.close()
self.sock = None
def quit(self):
"""Terminate the SMTP session."""
self.docmd("quit")
self.close()
# Test the sendmail method, which tests most of the others.
# Note: This always sends to localhost.
if __name__ == '__main__':
import sys
def prompt(prompt):
sys.stdout.write(prompt + ": ")
return sys.stdin.readline().strip()
fromaddr = prompt("From")
toaddrs = prompt("To").split(',')
print "Enter message, end with ^D:"
msg = ''
while 1:
line = sys.stdin.readline()
if not line:
break
msg = msg + line
print "Message length is %d" % len(msg)
server = SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
| Python |
#! /usr/bin/env python
"""Mimification and unmimification of mail messages.
Decode quoted-printable parts of a mail message or encode using
quoted-printable.
Usage:
mimify(input, output)
unmimify(input, output, decode_base64 = 0)
to encode and decode respectively. Input and output may be the name
of a file or an open file object. Only a readline() method is used
on the input file, only a write() method is used on the output file.
When using file names, the input and output file names may be the
same.
Interactive usage:
mimify.py -e [infile [outfile]]
mimify.py -d [infile [outfile]]
to encode and decode respectively. Infile defaults to standard
input and outfile to standard output.
"""
# Configure
MAXLEN = 200 # if lines longer than this, encode as quoted-printable
CHARSET = 'ISO-8859-1' # default charset for non-US-ASCII mail
QUOTE = '> ' # string replies are quoted with
# End configure
import re
__all__ = ["mimify","unmimify","mime_encode_header","mime_decode_header"]
qp = re.compile('^content-transfer-encoding:\\s*quoted-printable', re.I)
base64_re = re.compile('^content-transfer-encoding:\\s*base64', re.I)
mp = re.compile('^content-type:.*multipart/.*boundary="?([^;"\n]*)', re.I|re.S)
chrset = re.compile('^(content-type:.*charset=")(us-ascii|iso-8859-[0-9]+)(".*)', re.I|re.S)
he = re.compile('^-*\n')
mime_code = re.compile('=([0-9a-f][0-9a-f])', re.I)
mime_head = re.compile('=\\?iso-8859-1\\?q\\?([^? \t\n]+)\\?=', re.I)
repl = re.compile('^subject:\\s+re: ', re.I)
class File:
"""A simple fake file object that knows about limited read-ahead and
boundaries. The only supported method is readline()."""
def __init__(self, file, boundary):
self.file = file
self.boundary = boundary
self.peek = None
def readline(self):
if self.peek is not None:
return ''
line = self.file.readline()
if not line:
return line
if self.boundary:
if line == self.boundary + '\n':
self.peek = line
return ''
if line == self.boundary + '--\n':
self.peek = line
return ''
return line
class HeaderFile:
def __init__(self, file):
self.file = file
self.peek = None
def readline(self):
if self.peek is not None:
line = self.peek
self.peek = None
else:
line = self.file.readline()
if not line:
return line
if he.match(line):
return line
while 1:
self.peek = self.file.readline()
if len(self.peek) == 0 or \
(self.peek[0] != ' ' and self.peek[0] != '\t'):
return line
line = line + self.peek
self.peek = None
def mime_decode(line):
"""Decode a single line of quoted-printable text to 8bit."""
newline = ''
pos = 0
while 1:
res = mime_code.search(line, pos)
if res is None:
break
newline = newline + line[pos:res.start(0)] + \
chr(int(res.group(1), 16))
pos = res.end(0)
return newline + line[pos:]
def mime_decode_header(line):
"""Decode a header line to 8bit."""
newline = ''
pos = 0
while 1:
res = mime_head.search(line, pos)
if res is None:
break
match = res.group(1)
# convert underscores to spaces (before =XX conversion!)
match = ' '.join(match.split('_'))
newline = newline + line[pos:res.start(0)] + mime_decode(match)
pos = res.end(0)
return newline + line[pos:]
def unmimify_part(ifile, ofile, decode_base64 = 0):
"""Convert a quoted-printable part of a MIME mail message to 8bit."""
multipart = None
quoted_printable = 0
is_base64 = 0
is_repl = 0
if ifile.boundary and ifile.boundary[:2] == QUOTE:
prefix = QUOTE
else:
prefix = ''
# read header
hfile = HeaderFile(ifile)
while 1:
line = hfile.readline()
if not line:
return
if prefix and line[:len(prefix)] == prefix:
line = line[len(prefix):]
pref = prefix
else:
pref = ''
line = mime_decode_header(line)
if qp.match(line):
quoted_printable = 1
continue # skip this header
if decode_base64 and base64_re.match(line):
is_base64 = 1
continue
ofile.write(pref + line)
if not prefix and repl.match(line):
# we're dealing with a reply message
is_repl = 1
mp_res = mp.match(line)
if mp_res:
multipart = '--' + mp_res.group(1)
if he.match(line):
break
if is_repl and (quoted_printable or multipart):
is_repl = 0
# read body
while 1:
line = ifile.readline()
if not line:
return
line = re.sub(mime_head, '\\1', line)
if prefix and line[:len(prefix)] == prefix:
line = line[len(prefix):]
pref = prefix
else:
pref = ''
## if is_repl and len(line) >= 4 and line[:4] == QUOTE+'--' and line[-3:] != '--\n':
## multipart = line[:-1]
while multipart:
if line == multipart + '--\n':
ofile.write(pref + line)
multipart = None
line = None
break
if line == multipart + '\n':
ofile.write(pref + line)
nifile = File(ifile, multipart)
unmimify_part(nifile, ofile, decode_base64)
line = nifile.peek
if not line:
# premature end of file
break
continue
# not a boundary between parts
break
if line and quoted_printable:
while line[-2:] == '=\n':
line = line[:-2]
newline = ifile.readline()
if newline[:len(QUOTE)] == QUOTE:
newline = newline[len(QUOTE):]
line = line + newline
line = mime_decode(line)
if line and is_base64 and not pref:
import base64
line = base64.decodestring(line)
if line:
ofile.write(pref + line)
def unmimify(infile, outfile, decode_base64 = 0):
"""Convert quoted-printable parts of a MIME mail message to 8bit."""
if type(infile) == type(''):
ifile = open(infile)
if type(outfile) == type('') and infile == outfile:
import os
d, f = os.path.split(infile)
os.rename(infile, os.path.join(d, ',' + f))
else:
ifile = infile
if type(outfile) == type(''):
ofile = open(outfile, 'w')
else:
ofile = outfile
nifile = File(ifile, None)
unmimify_part(nifile, ofile, decode_base64)
ofile.flush()
mime_char = re.compile('[=\177-\377]') # quote these chars in body
mime_header_char = re.compile('[=?\177-\377]') # quote these in header
def mime_encode(line, header):
"""Code a single line as quoted-printable.
If header is set, quote some extra characters."""
if header:
reg = mime_header_char
else:
reg = mime_char
newline = ''
pos = 0
if len(line) >= 5 and line[:5] == 'From ':
# quote 'From ' at the start of a line for stupid mailers
newline = ('=%02x' % ord('F')).upper()
pos = 1
while 1:
res = reg.search(line, pos)
if res is None:
break
newline = newline + line[pos:res.start(0)] + \
('=%02x' % ord(res.group(0))).upper()
pos = res.end(0)
line = newline + line[pos:]
newline = ''
while len(line) >= 75:
i = 73
while line[i] == '=' or line[i-1] == '=':
i = i - 1
i = i + 1
newline = newline + line[:i] + '=\n'
line = line[i:]
return newline + line
mime_header = re.compile('([ \t(]|^)([-a-zA-Z0-9_+]*[\177-\377][-a-zA-Z0-9_+\177-\377]*)(?=[ \t)]|\n)')
def mime_encode_header(line):
"""Code a single header line as quoted-printable."""
newline = ''
pos = 0
while 1:
res = mime_header.search(line, pos)
if res is None:
break
newline = '%s%s%s=?%s?Q?%s?=' % \
(newline, line[pos:res.start(0)], res.group(1),
CHARSET, mime_encode(res.group(2), 1))
pos = res.end(0)
return newline + line[pos:]
mv = re.compile('^mime-version:', re.I)
cte = re.compile('^content-transfer-encoding:', re.I)
iso_char = re.compile('[\177-\377]')
def mimify_part(ifile, ofile, is_mime):
"""Convert an 8bit part of a MIME mail message to quoted-printable."""
has_cte = is_qp = is_base64 = 0
multipart = None
must_quote_body = must_quote_header = has_iso_chars = 0
header = []
header_end = ''
message = []
message_end = ''
# read header
hfile = HeaderFile(ifile)
while 1:
line = hfile.readline()
if not line:
break
if not must_quote_header and iso_char.search(line):
must_quote_header = 1
if mv.match(line):
is_mime = 1
if cte.match(line):
has_cte = 1
if qp.match(line):
is_qp = 1
elif base64_re.match(line):
is_base64 = 1
mp_res = mp.match(line)
if mp_res:
multipart = '--' + mp_res.group(1)
if he.match(line):
header_end = line
break
header.append(line)
# read body
while 1:
line = ifile.readline()
if not line:
break
if multipart:
if line == multipart + '--\n':
message_end = line
break
if line == multipart + '\n':
message_end = line
break
if is_base64:
message.append(line)
continue
if is_qp:
while line[-2:] == '=\n':
line = line[:-2]
newline = ifile.readline()
if newline[:len(QUOTE)] == QUOTE:
newline = newline[len(QUOTE):]
line = line + newline
line = mime_decode(line)
message.append(line)
if not has_iso_chars:
if iso_char.search(line):
has_iso_chars = must_quote_body = 1
if not must_quote_body:
if len(line) > MAXLEN:
must_quote_body = 1
# convert and output header and body
for line in header:
if must_quote_header:
line = mime_encode_header(line)
chrset_res = chrset.match(line)
if chrset_res:
if has_iso_chars:
# change us-ascii into iso-8859-1
if chrset_res.group(2).lower() == 'us-ascii':
line = '%s%s%s' % (chrset_res.group(1),
CHARSET,
chrset_res.group(3))
else:
# change iso-8859-* into us-ascii
line = '%sus-ascii%s' % chrset_res.group(1, 3)
if has_cte and cte.match(line):
line = 'Content-Transfer-Encoding: '
if is_base64:
line = line + 'base64\n'
elif must_quote_body:
line = line + 'quoted-printable\n'
else:
line = line + '7bit\n'
ofile.write(line)
if (must_quote_header or must_quote_body) and not is_mime:
ofile.write('Mime-Version: 1.0\n')
ofile.write('Content-Type: text/plain; ')
if has_iso_chars:
ofile.write('charset="%s"\n' % CHARSET)
else:
ofile.write('charset="us-ascii"\n')
if must_quote_body and not has_cte:
ofile.write('Content-Transfer-Encoding: quoted-printable\n')
ofile.write(header_end)
for line in message:
if must_quote_body:
line = mime_encode(line, 0)
ofile.write(line)
ofile.write(message_end)
line = message_end
while multipart:
if line == multipart + '--\n':
# read bit after the end of the last part
while 1:
line = ifile.readline()
if not line:
return
if must_quote_body:
line = mime_encode(line, 0)
ofile.write(line)
if line == multipart + '\n':
nifile = File(ifile, multipart)
mimify_part(nifile, ofile, 1)
line = nifile.peek
if not line:
# premature end of file
break
ofile.write(line)
continue
# unexpectedly no multipart separator--copy rest of file
while 1:
line = ifile.readline()
if not line:
return
if must_quote_body:
line = mime_encode(line, 0)
ofile.write(line)
def mimify(infile, outfile):
"""Convert 8bit parts of a MIME mail message to quoted-printable."""
if type(infile) == type(''):
ifile = open(infile)
if type(outfile) == type('') and infile == outfile:
import os
d, f = os.path.split(infile)
os.rename(infile, os.path.join(d, ',' + f))
else:
ifile = infile
if type(outfile) == type(''):
ofile = open(outfile, 'w')
else:
ofile = outfile
nifile = File(ifile, None)
mimify_part(nifile, ofile, 0)
ofile.flush()
import sys
if __name__ == '__main__' or (len(sys.argv) > 0 and sys.argv[0] == 'mimify'):
import getopt
usage = 'Usage: mimify [-l len] -[ed] [infile [outfile]]'
decode_base64 = 0
opts, args = getopt.getopt(sys.argv[1:], 'l:edb')
if len(args) not in (0, 1, 2):
print usage
sys.exit(1)
if (('-e', '') in opts) == (('-d', '') in opts) or \
((('-b', '') in opts) and (('-d', '') not in opts)):
print usage
sys.exit(1)
for o, a in opts:
if o == '-e':
encode = mimify
elif o == '-d':
encode = unmimify
elif o == '-l':
try:
MAXLEN = int(a)
except (ValueError, OverflowError):
print usage
sys.exit(1)
elif o == '-b':
decode_base64 = 1
if len(args) == 0:
encode_args = (sys.stdin, sys.stdout)
elif len(args) == 1:
encode_args = (args[0], sys.stdout)
else:
encode_args = (args[0], args[1])
if decode_base64:
encode_args = encode_args + (decode_base64,)
encode(*encode_args)
| Python |
"""A parser for HTML and XHTML."""
# This file is based on sgmllib.py, but the API is slightly different.
# XXX There should be a way to distinguish between PCDATA (parsed
# character data -- the normal case), RCDATA (replaceable character
# data -- only char and entity references and end tags are special)
# and CDATA (character data -- only end tags are special).
import markupbase
import re
# Regular expressions used for parsing
interesting_normal = re.compile('[&<]')
interesting_cdata = re.compile(r'<(/|\Z)')
incomplete = re.compile('&[a-zA-Z#]')
entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
charref = re.compile('&#(?:[0-9]+|[xX][0-9a-fA-F]+)[^0-9a-fA-F]')
starttagopen = re.compile('<[a-zA-Z]')
piclose = re.compile('>')
commentclose = re.compile(r'--\s*>')
tagfind = re.compile('[a-zA-Z][-.a-zA-Z0-9:_]*')
attrfind = re.compile(
r'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*'
r'(\'[^\']*\'|"[^"]*"|[-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~@]*))?')
locatestarttagend = re.compile(r"""
<[a-zA-Z][-.a-zA-Z0-9:_]* # tag name
(?:\s+ # whitespace before attribute name
(?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name
(?:\s*=\s* # value indicator
(?:'[^']*' # LITA-enclosed value
|\"[^\"]*\" # LIT-enclosed value
|[^'\">\s]+ # bare value
)
)?
)
)*
\s* # trailing whitespace
""", re.VERBOSE)
endendtag = re.compile('>')
endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
class HTMLParseError(Exception):
"""Exception raised for all parse errors."""
def __init__(self, msg, position=(None, None)):
assert msg
self.msg = msg
self.lineno = position[0]
self.offset = position[1]
def __str__(self):
result = self.msg
if self.lineno is not None:
result = result + ", at line %d" % self.lineno
if self.offset is not None:
result = result + ", column %d" % (self.offset + 1)
return result
class HTMLParser(markupbase.ParserBase):
"""Find tags and other markup and call handler functions.
Usage:
p = HTMLParser()
p.feed(data)
...
p.close()
Start tags are handled by calling self.handle_starttag() or
self.handle_startendtag(); end tags by self.handle_endtag(). The
data between tags is passed from the parser to the derived class
by calling self.handle_data() with the data as argument (the data
may be split up in arbitrary chunks). Entity references are
passed by calling self.handle_entityref() with the entity
reference as the argument. Numeric character references are
passed to self.handle_charref() with the string containing the
reference as the argument.
"""
CDATA_CONTENT_ELEMENTS = ("script", "style")
def __init__(self):
"""Initialize and reset this instance."""
self.reset()
def reset(self):
"""Reset this instance. Loses all unprocessed data."""
self.rawdata = ''
self.lasttag = '???'
self.interesting = interesting_normal
markupbase.ParserBase.reset(self)
def feed(self, data):
"""Feed data to the parser.
Call this as often as you want, with as little or as much text
as you want (may include '\n').
"""
self.rawdata = self.rawdata + data
self.goahead(0)
def close(self):
"""Handle any buffered data."""
self.goahead(1)
def error(self, message):
raise HTMLParseError(message, self.getpos())
__starttag_text = None
def get_starttag_text(self):
"""Return full source of start tag: '<...>'."""
return self.__starttag_text
def set_cdata_mode(self):
self.interesting = interesting_cdata
def clear_cdata_mode(self):
self.interesting = interesting_normal
# Internal -- handle data as far as reasonable. May leave state
# and data to be processed by a subsequent call. If 'end' is
# true, force handling all data as if followed by EOF marker.
def goahead(self, end):
rawdata = self.rawdata
i = 0
n = len(rawdata)
while i < n:
match = self.interesting.search(rawdata, i) # < or &
if match:
j = match.start()
else:
j = n
if i < j: self.handle_data(rawdata[i:j])
i = self.updatepos(i, j)
if i == n: break
startswith = rawdata.startswith
if startswith('<', i):
if starttagopen.match(rawdata, i): # < + letter
k = self.parse_starttag(i)
elif startswith("</", i):
k = self.parse_endtag(i)
elif startswith("<!--", i):
k = self.parse_comment(i)
elif startswith("<?", i):
k = self.parse_pi(i)
elif startswith("<!", i):
k = self.parse_declaration(i)
elif (i + 1) < n:
self.handle_data("<")
k = i + 1
else:
break
if k < 0:
if end:
self.error("EOF in middle of construct")
break
i = self.updatepos(i, k)
elif startswith("&#", i):
match = charref.match(rawdata, i)
if match:
name = match.group()[2:-1]
self.handle_charref(name)
k = match.end()
if not startswith(';', k-1):
k = k - 1
i = self.updatepos(i, k)
continue
else:
break
elif startswith('&', i):
match = entityref.match(rawdata, i)
if match:
name = match.group(1)
self.handle_entityref(name)
k = match.end()
if not startswith(';', k-1):
k = k - 1
i = self.updatepos(i, k)
continue
match = incomplete.match(rawdata, i)
if match:
# match.group() will contain at least 2 chars
if end and match.group() == rawdata[i:]:
self.error("EOF in middle of entity or char ref")
# incomplete
break
elif (i + 1) < n:
# not the end of the buffer, and can't be confused
# with some other construct
self.handle_data("&")
i = self.updatepos(i, i + 1)
else:
break
else:
assert 0, "interesting.search() lied"
# end while
if end and i < n:
self.handle_data(rawdata[i:n])
i = self.updatepos(i, n)
self.rawdata = rawdata[i:]
# Internal -- parse processing instr, return end or -1 if not terminated
def parse_pi(self, i):
rawdata = self.rawdata
assert rawdata[i:i+2] == '<?', 'unexpected call to parse_pi()'
match = piclose.search(rawdata, i+2) # >
if not match:
return -1
j = match.start()
self.handle_pi(rawdata[i+2: j])
j = match.end()
return j
# Internal -- handle starttag, return end or -1 if not terminated
def parse_starttag(self, i):
self.__starttag_text = None
endpos = self.check_for_whole_start_tag(i)
if endpos < 0:
return endpos
rawdata = self.rawdata
self.__starttag_text = rawdata[i:endpos]
# Now parse the data between i+1 and j into a tag and attrs
attrs = []
match = tagfind.match(rawdata, i+1)
assert match, 'unexpected call to parse_starttag()'
k = match.end()
self.lasttag = tag = rawdata[i+1:k].lower()
while k < endpos:
m = attrfind.match(rawdata, k)
if not m:
break
attrname, rest, attrvalue = m.group(1, 2, 3)
if not rest:
attrvalue = None
elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
attrvalue[:1] == '"' == attrvalue[-1:]:
attrvalue = attrvalue[1:-1]
attrvalue = self.unescape(attrvalue)
attrs.append((attrname.lower(), attrvalue))
k = m.end()
end = rawdata[k:endpos].strip()
if end not in (">", "/>"):
lineno, offset = self.getpos()
if "\n" in self.__starttag_text:
lineno = lineno + self.__starttag_text.count("\n")
offset = len(self.__starttag_text) \
- self.__starttag_text.rfind("\n")
else:
offset = offset + len(self.__starttag_text)
self.error("junk characters in start tag: %r"
% (rawdata[k:endpos][:20],))
if end.endswith('/>'):
# XHTML-style empty tag: <span attr="value" />
self.handle_startendtag(tag, attrs)
else:
self.handle_starttag(tag, attrs)
if tag in self.CDATA_CONTENT_ELEMENTS:
self.set_cdata_mode()
return endpos
# Internal -- check to see if we have a complete starttag; return end
# or -1 if incomplete.
def check_for_whole_start_tag(self, i):
rawdata = self.rawdata
m = locatestarttagend.match(rawdata, i)
if m:
j = m.end()
next = rawdata[j:j+1]
if next == ">":
return j + 1
if next == "/":
if rawdata.startswith("/>", j):
return j + 2
if rawdata.startswith("/", j):
# buffer boundary
return -1
# else bogus input
self.updatepos(i, j + 1)
self.error("malformed empty start tag")
if next == "":
# end of input
return -1
if next in ("abcdefghijklmnopqrstuvwxyz=/"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
# end of input in or before attribute value, or we have the
# '/' from a '/>' ending
return -1
self.updatepos(i, j)
self.error("malformed start tag")
raise AssertionError("we should not get here!")
# Internal -- parse endtag, return end or -1 if incomplete
def parse_endtag(self, i):
rawdata = self.rawdata
assert rawdata[i:i+2] == "</", "unexpected call to parse_endtag"
match = endendtag.search(rawdata, i+1) # >
if not match:
return -1
j = match.end()
match = endtagfind.match(rawdata, i) # </ + tag + >
if not match:
self.error("bad end tag: %r" % (rawdata[i:j],))
tag = match.group(1)
self.handle_endtag(tag.lower())
self.clear_cdata_mode()
return j
# Overridable -- finish processing of start+end tag: <tag.../>
def handle_startendtag(self, tag, attrs):
self.handle_starttag(tag, attrs)
self.handle_endtag(tag)
# Overridable -- handle start tag
def handle_starttag(self, tag, attrs):
pass
# Overridable -- handle end tag
def handle_endtag(self, tag):
pass
# Overridable -- handle character reference
def handle_charref(self, name):
pass
# Overridable -- handle entity reference
def handle_entityref(self, name):
pass
# Overridable -- handle data
def handle_data(self, data):
pass
# Overridable -- handle comment
def handle_comment(self, data):
pass
# Overridable -- handle declaration
def handle_decl(self, decl):
pass
# Overridable -- handle processing instruction
def handle_pi(self, data):
pass
def unknown_decl(self, data):
self.error("unknown declaration: %r" % (data,))
# Internal -- helper to remove special character quoting
def unescape(self, s):
if '&' not in s:
return s
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("'", "'")
s = s.replace(""", '"')
s = s.replace("&", "&") # Must be last
return s
| Python |
# module 'string' -- A collection of string operations
# Warning: most of the code you see here isn't normally used nowadays. With
# Python 1.6, many of these functions are implemented as methods on the
# standard string object. They used to be implemented by a built-in module
# called strop, but strop is now obsolete itself.
"""Common string manipulations.
Public module variables:
whitespace -- a string containing all characters considered whitespace
lowercase -- a string containing all characters considered lowercase letters
uppercase -- a string containing all characters considered uppercase letters
letters -- a string containing all characters considered letters
digits -- a string containing all characters considered decimal digits
hexdigits -- a string containing all characters considered hexadecimal digits
octdigits -- a string containing all characters considered octal digits
"""
# Some strings for ctype-style character classification
whitespace = ' \t\n\r\v\f'
lowercase = 'abcdefghijklmnopqrstuvwxyz'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
letters = lowercase + uppercase
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
# Case conversion helpers
_idmap = ''
for i in range(256): _idmap = _idmap + chr(i)
del i
# Backward compatible names for exceptions
index_error = ValueError
atoi_error = ValueError
atof_error = ValueError
atol_error = ValueError
# convert UPPER CASE letters to lower case
def lower(s):
"""lower(s) -> string
Return a copy of the string s converted to lowercase.
"""
return s.lower()
# Convert lower case letters to UPPER CASE
def upper(s):
"""upper(s) -> string
Return a copy of the string s converted to uppercase.
"""
return s.upper()
# Swap lower case letters and UPPER CASE
def swapcase(s):
"""swapcase(s) -> string
Return a copy of the string s with upper case characters
converted to lowercase and vice versa.
"""
return s.swapcase()
# Strip leading and trailing tabs and spaces
def strip(s):
"""strip(s) -> string
Return a copy of the string s with leading and trailing
whitespace removed.
"""
return s.strip()
# Strip leading tabs and spaces
def lstrip(s):
"""lstrip(s) -> string
Return a copy of the string s with leading whitespace removed.
"""
return s.lstrip()
# Strip trailing tabs and spaces
def rstrip(s):
"""rstrip(s) -> string
Return a copy of the string s with trailing whitespace
removed.
"""
return s.rstrip()
# Split a string into a list of space/tab-separated words
def split(s, sep=None, maxsplit=0):
"""split(str [,sep [,maxsplit]]) -> list of strings
Return a list of the words in the string s, using sep as the
delimiter string. If maxsplit is nonzero, splits into at most
maxsplit words If sep is not specified, any whitespace string
is a separator. Maxsplit defaults to 0.
(split and splitfields are synonymous)
"""
return s.split(sep, maxsplit)
splitfields = split
# Join fields with optional separator
def join(words, sep = ' '):
"""join(list [,sep]) -> string
Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space.
(joinfields and join are synonymous)
"""
return sep.join(words)
joinfields = join
# for a little bit of speed
_apply = apply
# Find substring, raise exception if not found
def index(s, *args):
"""index(s, sub [,start [,end]]) -> int
Like find but raises ValueError when the substring is not found.
"""
return _apply(s.index, args)
# Find last substring, raise exception if not found
def rindex(s, *args):
"""rindex(s, sub [,start [,end]]) -> int
Like rfind but raises ValueError when the substring is not found.
"""
return _apply(s.rindex, args)
# Count non-overlapping occurrences of substring
def count(s, *args):
"""count(s, sub[, start[,end]]) -> int
Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation.
"""
return _apply(s.count, args)
# Find substring, return -1 if not found
def find(s, *args):
"""find(s, sub [,start [,end]]) -> in
Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return _apply(s.find, args)
# Find last substring, return -1 if not found
def rfind(s, *args):
"""rfind(s, sub [,start [,end]]) -> int
Return the highest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation.
Return -1 on failure.
"""
return _apply(s.rfind, args)
# for a bit of speed
_float = float
_int = int
_long = long
_StringType = type('')
# Convert string to float
def atof(s):
"""atof(s) -> float
Return the floating point number represented by the string s.
"""
if type(s) == _StringType:
return _float(s)
else:
raise TypeError('argument 1: expected string, %s found' %
type(s).__name__)
# Convert string to integer
def atoi(*args):
"""atoi(s [,base]) -> int
Return the integer represented by the string s in the given
base, which defaults to 10. The string s must consist of one
or more digits, possibly preceded by a sign. If base is 0, it
is chosen from the leading characters of s, 0 for octal, 0x or
0X for hexadecimal. If base is 16, a preceding 0x or 0X is
accepted.
"""
try:
s = args[0]
except IndexError:
raise TypeError('function requires at least 1 argument: %d given' %
len(args))
# Don't catch type error resulting from too many arguments to int(). The
# error message isn't compatible but the error type is, and this function
# is complicated enough already.
if type(s) == _StringType:
return _apply(_int, args)
else:
raise TypeError('argument 1: expected string, %s found' %
type(s).__name__)
# Convert string to long integer
def atol(*args):
"""atol(s [,base]) -> long
Return the long integer represented by the string s in the
given base, which defaults to 10. The string s must consist
of one or more digits, possibly preceded by a sign. If base
is 0, it is chosen from the leading characters of s, 0 for
octal, 0x or 0X for hexadecimal. If base is 16, a preceding
0x or 0X is accepted. A trailing L or l is not accepted,
unless base is 0.
"""
try:
s = args[0]
except IndexError:
raise TypeError('function requires at least 1 argument: %d given' %
len(args))
# Don't catch type error resulting from too many arguments to long(). The
# error message isn't compatible but the error type is, and this function
# is complicated enough already.
if type(s) == _StringType:
return _apply(_long, args)
else:
raise TypeError('argument 1: expected string, %s found' %
type(s).__name__)
# Left-justify a string
def ljust(s, width):
"""ljust(s, width) -> string
Return a left-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated.
"""
n = width - len(s)
if n <= 0: return s
return s + ' '*n
# Right-justify a string
def rjust(s, width):
"""rjust(s, width) -> string
Return a right-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated.
"""
n = width - len(s)
if n <= 0: return s
return ' '*n + s
# Center a string
def center(s, width):
"""center(s, width) -> string
Return a center version of s, in a field of the specified
width. padded with spaces as needed. The string is never
truncated.
"""
n = width - len(s)
if n <= 0: return s
half = n/2
if n%2 and width%2:
# This ensures that center(center(s, i), j) = center(s, j)
half = half+1
return ' '*half + s + ' '*(n-half)
# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
# Decadent feature: the argument may be a string or a number
# (Use of this is deprecated; it should be a string as with ljust c.s.)
def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if type(x) == type(''): s = x
else: s = repr(x)
n = len(s)
if n >= width: return s
sign = ''
if s[0] in ('-', '+'):
sign, s = s[0], s[1:]
return sign + '0'*(width-n) + s
# Expand tabs in a string.
# Doesn't take non-printing chars into account, but does understand \n.
def expandtabs(s, tabsize=8):
"""expandtabs(s [,tabsize]) -> string
Return a copy of the string s with all tab characters replaced
by the appropriate number of spaces, depending on the current
column, and the tabsize (default 8).
"""
res = line = ''
for c in s:
if c == '\t':
c = ' '*(tabsize - len(line) % tabsize)
line = line + c
if c == '\n':
res = res + line
line = ''
return res + line
# Character translation through look-up table.
def translate(s, table, deletions=""):
"""translate(s,table [,deletechars]) -> string
Return a copy of the string s, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256.
"""
return s.translate(table, deletions)
# Capitalize a string, e.g. "aBc dEf" -> "Abc def".
def capitalize(s):
"""capitalize(s) -> string
Return a copy of the string s with only its first character
capitalized.
"""
return s.capitalize()
# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
# See also regsub.capwords().
def capwords(s, sep=None):
"""capwords(s, [sep]) -> string
Split the argument into words using split, capitalize each
word using capitalize, and join the capitalized words using
join. Note that this replaces runs of whitespace characters by
a single space.
"""
return join(map(capitalize, s.split(sep)), sep or ' ')
# Construct a translation string
_idmapL = None
def maketrans(fromstr, tostr):
"""maketrans(frm, to) -> string
Return a translation table (a string of 256 bytes long)
suitable for use in string.translate. The strings frm and to
must be of the same length.
"""
if len(fromstr) != len(tostr):
raise ValueError, "maketrans arguments must have same length"
global _idmapL
if not _idmapL:
_idmapL = map(None, _idmap)
L = _idmapL[:]
fromstr = map(ord, fromstr)
for i in range(len(fromstr)):
L[fromstr[i]] = tostr[i]
return join(L, "")
# Substring replacement (global)
def replace(s, old, new, maxsplit=0):
"""replace (str, old, new[, maxsplit]) -> string
Return a copy of string str with all occurrences of substring
old replaced by new. If the optional argument maxsplit is
given, only the first maxsplit occurrences are replaced.
"""
return s.replace(old, new, maxsplit)
# XXX: transitional
#
# If string objects do not have methods, then we need to use the old string.py
# library, which uses strop for many more things than just the few outlined
# below.
try:
''.upper
except AttributeError:
from stringold import *
# Try importing optional built-in module "strop" -- if it exists,
# it redefines some string operations that are 100-1000 times faster.
# It also defines values for whitespace, lowercase and uppercase
# that match <ctype.h>'s definitions.
try:
from strop import maketrans, lowercase, uppercase, whitespace
letters = lowercase + uppercase
except ImportError:
pass # Use the original versions
| Python |
"""TELNET client class.
Based on RFC 854: TELNET Protocol Specification, by J. Postel and
J. Reynolds
Example:
>>> from telnetlib import Telnet
>>> tn = Telnet('www.python.org', 79) # connect to finger port
>>> tn.write('guido\r\n')
>>> print tn.read_all()
Login Name TTY Idle When Where
guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
>>>
Note that read_all() won't read until eof -- it just reads some data
-- but it guarantees to read at least one byte unless EOF is hit.
It is possible to pass a Telnet object to select.select() in order to
wait until more data is available. Note that in this case,
read_eager() may return '' even if there was data on the socket,
because the protocol negotiation may have eaten the data. This is why
EOFError is needed in some cases to distinguish between "no data" and
"connection closed" (since the socket also appears ready for reading
when it is closed).
To do:
- option negotiation
- timeout should be intrinsic to the connection object instead of an
option on one of the read calls only
"""
# Imported modules
import sys
import socket
import select
__all__ = ["Telnet"]
# Tunable parameters
DEBUGLEVEL = 0
# Telnet protocol defaults
TELNET_PORT = 23
# Telnet protocol characters (don't change)
IAC = chr(255) # "Interpret As Command"
DONT = chr(254)
DO = chr(253)
WONT = chr(252)
WILL = chr(251)
theNULL = chr(0)
SE = chr(240) # Subnegotiation End
NOP = chr(241) # No Operation
DM = chr(242) # Data Mark
BRK = chr(243) # Break
IP = chr(244) # Interrupt process
AO = chr(245) # Abort output
AYT = chr(246) # Are You There
EC = chr(247) # Erase Character
EL = chr(248) # Erase Line
GA = chr(249) # Go Ahead
SB = chr(250) # Subnegotiation Begin
# Telnet protocol options code (don't change)
# These ones all come from arpa/telnet.h
BINARY = chr(0) # 8-bit data path
ECHO = chr(1) # echo
RCP = chr(2) # prepare to reconnect
SGA = chr(3) # suppress go ahead
NAMS = chr(4) # approximate message size
STATUS = chr(5) # give status
TM = chr(6) # timing mark
RCTE = chr(7) # remote controlled transmission and echo
NAOL = chr(8) # negotiate about output line width
NAOP = chr(9) # negotiate about output page size
NAOCRD = chr(10) # negotiate about CR disposition
NAOHTS = chr(11) # negotiate about horizontal tabstops
NAOHTD = chr(12) # negotiate about horizontal tab disposition
NAOFFD = chr(13) # negotiate about formfeed disposition
NAOVTS = chr(14) # negotiate about vertical tab stops
NAOVTD = chr(15) # negotiate about vertical tab disposition
NAOLFD = chr(16) # negotiate about output LF disposition
XASCII = chr(17) # extended ascii character set
LOGOUT = chr(18) # force logout
BM = chr(19) # byte macro
DET = chr(20) # data entry terminal
SUPDUP = chr(21) # supdup protocol
SUPDUPOUTPUT = chr(22) # supdup output
SNDLOC = chr(23) # send location
TTYPE = chr(24) # terminal type
EOR = chr(25) # end or record
TUID = chr(26) # TACACS user identification
OUTMRK = chr(27) # output marking
TTYLOC = chr(28) # terminal location number
VT3270REGIME = chr(29) # 3270 regime
X3PAD = chr(30) # X.3 PAD
NAWS = chr(31) # window size
TSPEED = chr(32) # terminal speed
LFLOW = chr(33) # remote flow control
LINEMODE = chr(34) # Linemode option
XDISPLOC = chr(35) # X Display Location
OLD_ENVIRON = chr(36) # Old - Environment variables
AUTHENTICATION = chr(37) # Authenticate
ENCRYPT = chr(38) # Encryption option
NEW_ENVIRON = chr(39) # New - Environment variables
# the following ones come from
# http://www.iana.org/assignments/telnet-options
# Unfortunately, that document does not assign identifiers
# to all of them, so we are making them up
TN3270E = chr(40) # TN3270E
XAUTH = chr(41) # XAUTH
CHARSET = chr(42) # CHARSET
RSP = chr(43) # Telnet Remote Serial Port
COM_PORT_OPTION = chr(44) # Com Port Control Option
SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo
TLS = chr(46) # Telnet Start TLS
KERMIT = chr(47) # KERMIT
SEND_URL = chr(48) # SEND-URL
FORWARD_X = chr(49) # FORWARD_X
PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON
SSPI_LOGON = chr(139) # TELOPT SSPI LOGON
PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT
EXOPL = chr(255) # Extended-Options-List
NOOPT = chr(0)
class Telnet:
"""Telnet interface class.
An instance of this class represents a connection to a telnet
server. The instance is initially not connected; the open()
method must be used to establish a connection. Alternatively, the
host name and optional port number can be passed to the
constructor, too.
Don't try to reopen an already connected instance.
This class has many read_*() methods. Note that some of them
raise EOFError when the end of the connection is read, because
they can return an empty string for other reasons. See the
individual doc strings.
read_until(expected, [timeout])
Read until the expected string has been seen, or a timeout is
hit (default is no timeout); may block.
read_all()
Read all data until EOF; may block.
read_some()
Read at least one byte or EOF; may block.
read_very_eager()
Read all data available already queued or on the socket,
without blocking.
read_eager()
Read either data already queued or some data available on the
socket, without blocking.
read_lazy()
Read all data in the raw queue (processing it first), without
doing any socket I/O.
read_very_lazy()
Reads all data in the cooked queue, without doing any socket
I/O.
read_sb_data()
Reads available data between SB ... SE sequence. Don't block.
set_option_negotiation_callback(callback)
Each time a telnet option is read on the input flow, this callback
(if set) is called with the following parameters :
callback(telnet socket, command, option)
option will be chr(0) when there is no option.
No other action is done afterwards by telnetlib.
"""
def __init__(self, host=None, port=0):
"""Constructor.
When called without arguments, create an unconnected instance.
With a hostname argument, it connects the instance; a port
number is optional.
"""
self.debuglevel = DEBUGLEVEL
self.host = host
self.port = port
self.sock = None
self.rawq = ''
self.irawq = 0
self.cookedq = ''
self.eof = 0
self.iacseq = '' # Buffer for IAC sequence.
self.sb = 0 # flag for SB and SE sequence.
self.sbdataq = ''
self.option_callback = None
if host is not None:
self.open(host, port)
def open(self, host, port=0):
"""Connect to a host.
The optional second argument is the port number, which
defaults to the standard telnet port (23).
Don't try to reopen an already connected instance.
"""
self.eof = 0
if not port:
port = TELNET_PORT
self.host = host
self.port = port
msg = "getaddrinfo returns an empty list"
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
self.sock.connect(sa)
except socket.error, msg:
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
def __del__(self):
"""Destructor -- close the connection."""
self.close()
def msg(self, msg, *args):
"""Print a debug message, when the debug level is > 0.
If extra arguments are present, they are substituted in the
message using the standard string formatting operator.
"""
if self.debuglevel > 0:
print 'Telnet(%s,%d):' % (self.host, self.port),
if args:
print msg % args
else:
print msg
def set_debuglevel(self, debuglevel):
"""Set the debug level.
The higher it is, the more debug output you get (on sys.stdout).
"""
self.debuglevel = debuglevel
def close(self):
"""Close the connection."""
if self.sock:
self.sock.close()
self.sock = 0
self.eof = 1
self.iacseq = ''
self.sb = 0
def get_socket(self):
"""Return the socket object used internally."""
return self.sock
def fileno(self):
"""Return the fileno() of the socket object used internally."""
return self.sock.fileno()
def write(self, buffer):
"""Write a string to the socket, doubling any IAC characters.
Can block if the connection is blocked. May raise
socket.error if the connection is closed.
"""
if IAC in buffer:
buffer = buffer.replace(IAC, IAC+IAC)
self.msg("send %r", buffer)
self.sock.sendall(buffer)
def read_until(self, match, timeout=None):
"""Read until a given string is encountered or until timeout.
When no match is found, return whatever is available instead,
possibly the empty string. Raise EOFError if the connection
is closed and no cooked data is available.
"""
n = len(match)
self.process_rawq()
i = self.cookedq.find(match)
if i >= 0:
i = i+n
buf = self.cookedq[:i]
self.cookedq = self.cookedq[i:]
return buf
s_reply = ([self], [], [])
s_args = s_reply
if timeout is not None:
s_args = s_args + (timeout,)
while not self.eof and select.select(*s_args) == s_reply:
i = max(0, len(self.cookedq)-n)
self.fill_rawq()
self.process_rawq()
i = self.cookedq.find(match, i)
if i >= 0:
i = i+n
buf = self.cookedq[:i]
self.cookedq = self.cookedq[i:]
return buf
return self.read_very_lazy()
def read_all(self):
"""Read all data until EOF; block until connection closed."""
self.process_rawq()
while not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq
self.cookedq = ''
return buf
def read_some(self):
"""Read at least one byte of cooked data unless EOF is hit.
Return '' if EOF is hit. Block if no data is immediately
available.
"""
self.process_rawq()
while not self.cookedq and not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq
self.cookedq = ''
return buf
def read_very_eager(self):
"""Read everything that's possible without blocking in I/O (eager).
Raise EOFError if connection closed and no cooked data
available. Return '' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence.
"""
self.process_rawq()
while not self.eof and self.sock_avail():
self.fill_rawq()
self.process_rawq()
return self.read_very_lazy()
def read_eager(self):
"""Read readily available data.
Raise EOFError if connection closed and no cooked data
available. Return '' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence.
"""
self.process_rawq()
while not self.cookedq and not self.eof and self.sock_avail():
self.fill_rawq()
self.process_rawq()
return self.read_very_lazy()
def read_lazy(self):
"""Process and return data that's already in the queues (lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block
unless in the midst of an IAC sequence.
"""
self.process_rawq()
return self.read_very_lazy()
def read_very_lazy(self):
"""Return any data available in the cooked queue (very lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block.
"""
buf = self.cookedq
self.cookedq = ''
if not buf and self.eof and not self.rawq:
raise EOFError, 'telnet connection closed'
return buf
def read_sb_data(self):
"""Return any data available in the SB ... SE queue.
Return '' if no SB ... SE available. Should only be called
after seeing a SB or SE command. When a new SB command is
found, old unread SB data will be discarded. Don't block.
"""
buf = self.sbdataq
self.sbdataq = ''
return buf
def set_option_negotiation_callback(self, callback):
"""Provide a callback function called after each receipt of a telnet option."""
self.option_callback = callback
def process_rawq(self):
"""Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence.
"""
buf = ['', '']
try:
while self.rawq:
c = self.rawq_getchar()
if not self.iacseq:
if c == theNULL:
continue
if c == "\021":
continue
if c != IAC:
buf[self.sb] = buf[self.sb] + c
continue
else:
self.iacseq += c
elif len(self.iacseq) == 1:
'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
if c in (DO, DONT, WILL, WONT):
self.iacseq += c
continue
self.iacseq = ''
if c == IAC:
buf[self.sb] = buf[self.sb] + c
else:
if c == SB: # SB ... SE start.
self.sb = 1
self.sbdataq = ''
elif c == SE:
self.sb = 0
self.sbdataq = self.sbdataq + buf[1]
buf[1] = ''
if self.option_callback:
# Callback is supposed to look into
# the sbdataq
self.option_callback(self.sock, c, NOOPT)
else:
# We can't offer automatic processing of
# suboptions. Alas, we should not get any
# unless we did a WILL/DO before.
self.msg('IAC %d not recognized' % ord(c))
elif len(self.iacseq) == 2:
cmd = self.iacseq[1]
self.iacseq = ''
opt = c
if cmd in (DO, DONT):
self.msg('IAC %s %d',
cmd == DO and 'DO' or 'DONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + WONT + opt)
elif cmd in (WILL, WONT):
self.msg('IAC %s %d',
cmd == WILL and 'WILL' or 'WONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + DONT + opt)
except EOFError: # raised by self.rawq_getchar()
self.iacseq = '' # Reset on EOF
self.sb = 0
pass
self.cookedq = self.cookedq + buf[0]
self.sbdataq = self.sbdataq + buf[1]
def rawq_getchar(self):
"""Get next char from raw queue.
Block if no data is immediately available. Raise EOFError
when connection is closed.
"""
if not self.rawq:
self.fill_rawq()
if self.eof:
raise EOFError
c = self.rawq[self.irawq]
self.irawq = self.irawq + 1
if self.irawq >= len(self.rawq):
self.rawq = ''
self.irawq = 0
return c
def fill_rawq(self):
"""Fill raw queue from exactly one recv() system call.
Block if no data is immediately available. Set self.eof when
connection is closed.
"""
if self.irawq >= len(self.rawq):
self.rawq = ''
self.irawq = 0
# The buffer size should be fairly small so as to avoid quadratic
# behavior in process_rawq() above
buf = self.sock.recv(50)
self.msg("recv %r", buf)
self.eof = (not buf)
self.rawq = self.rawq + buf
def sock_avail(self):
"""Test whether data is available on the socket."""
return select.select([self], [], [], 0) == ([self], [], [])
def interact(self):
"""Interaction function, emulates a very dumb telnet client."""
if sys.platform == "win32":
self.mt_interact()
return
while 1:
rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
if self in rfd:
try:
text = self.read_eager()
except EOFError:
print '*** Connection closed by remote host ***'
break
if text:
sys.stdout.write(text)
sys.stdout.flush()
if sys.stdin in rfd:
line = sys.stdin.readline()
if not line:
break
self.write(line)
def mt_interact(self):
"""Multithreaded version of interact()."""
import thread
thread.start_new_thread(self.listener, ())
while 1:
line = sys.stdin.readline()
if not line:
break
self.write(line)
def listener(self):
"""Helper for mt_interact() -- this executes in the other thread."""
while 1:
try:
data = self.read_eager()
except EOFError:
print '*** Connection closed by remote host ***'
return
if data:
sys.stdout.write(data)
else:
sys.stdout.flush()
def expect(self, list, timeout=None):
"""Read until one from a list of a regular expressions matches.
The first argument is a list of regular expressions, either
compiled (re.RegexObject instances) or uncompiled (strings).
The optional second argument is a timeout, in seconds; default
is no timeout.
Return a tuple of three items: the index in the list of the
first regular expression that matches; the match object
returned; and the text read up till and including the match.
If EOF is read and no text was read, raise EOFError.
Otherwise, when nothing matches, return (-1, None, text) where
text is the text received so far (may be the empty string if a
timeout happened).
If a regular expression ends with a greedy match (e.g. '.*')
or if more than one expression can match the same input, the
results are undeterministic, and may depend on the I/O timing.
"""
re = None
list = list[:]
indices = range(len(list))
for i in indices:
if not hasattr(list[i], "search"):
if not re: import re
list[i] = re.compile(list[i])
while 1:
self.process_rawq()
for i in indices:
m = list[i].search(self.cookedq)
if m:
e = m.end()
text = self.cookedq[:e]
self.cookedq = self.cookedq[e:]
return (i, m, text)
if self.eof:
break
if timeout is not None:
r, w, x = select.select([self.fileno()], [], [], timeout)
if not r:
break
self.fill_rawq()
text = self.read_very_lazy()
if not text and self.eof:
raise EOFError
return (-1, None, text)
def test():
"""Test program for telnetlib.
Usage: python telnetlib.py [-d] ... [host [port]]
Default host is localhost; default port is 23.
"""
debuglevel = 0
while sys.argv[1:] and sys.argv[1] == '-d':
debuglevel = debuglevel+1
del sys.argv[1]
host = 'localhost'
if sys.argv[1:]:
host = sys.argv[1]
port = 0
if sys.argv[2:]:
portstr = sys.argv[2]
try:
port = int(portstr)
except ValueError:
port = socket.getservbyname(portstr, 'tcp')
tn = Telnet()
tn.set_debuglevel(debuglevel)
tn.open(host, port)
tn.interact()
tn.close()
if __name__ == '__main__':
test()
| Python |
"""Conversion pipeline templates.
The problem:
------------
Suppose you have some data that you want to convert to another format,
such as from GIF image format to PPM image format. Maybe the
conversion involves several steps (e.g. piping it through compress or
uuencode). Some of the conversion steps may require that their input
is a disk file, others may be able to read standard input; similar for
their output. The input to the entire conversion may also be read
from a disk file or from an open file, and similar for its output.
The module lets you construct a pipeline template by sticking one or
more conversion steps together. It will take care of creating and
removing temporary files if they are necessary to hold intermediate
data. You can then use the template to do conversions from many
different sources to many different destinations. The temporary
file names used are different each time the template is used.
The templates are objects so you can create templates for many
different conversion steps and store them in a dictionary, for
instance.
Directions:
-----------
To create a template:
t = Template()
To add a conversion step to a template:
t.append(command, kind)
where kind is a string of two characters: the first is '-' if the
command reads its standard input or 'f' if it requires a file; the
second likewise for the output. The command must be valid /bin/sh
syntax. If input or output files are required, they are passed as
$IN and $OUT; otherwise, it must be possible to use the command in
a pipeline.
To add a conversion step at the beginning:
t.prepend(command, kind)
To convert a file to another file using a template:
sts = t.copy(infile, outfile)
If infile or outfile are the empty string, standard input is read or
standard output is written, respectively. The return value is the
exit status of the conversion pipeline.
To open a file for reading or writing through a conversion pipeline:
fp = t.open(file, mode)
where mode is 'r' to read the file, or 'w' to write it -- just like
for the built-in function open() or for os.popen().
To create a new template object initialized to a given one:
t2 = t.clone()
For an example, see the function test() at the end of the file.
""" # '
import re
import os
import tempfile
import string
__all__ = ["Template"]
# Conversion step kinds
FILEIN_FILEOUT = 'ff' # Must read & write real files
STDIN_FILEOUT = '-f' # Must write a real file
FILEIN_STDOUT = 'f-' # Must read a real file
STDIN_STDOUT = '--' # Normal pipeline element
SOURCE = '.-' # Must be first, writes stdout
SINK = '-.' # Must be last, reads stdin
stepkinds = [FILEIN_FILEOUT, STDIN_FILEOUT, FILEIN_STDOUT, STDIN_STDOUT, \
SOURCE, SINK]
class Template:
"""Class representing a pipeline template."""
def __init__(self):
"""Template() returns a fresh pipeline template."""
self.debugging = 0
self.reset()
def __repr__(self):
"""t.__repr__() implements repr(t)."""
return '<Template instance, steps=%r>' % (self.steps,)
def reset(self):
"""t.reset() restores a pipeline template to its initial state."""
self.steps = []
def clone(self):
"""t.clone() returns a new pipeline template with identical
initial state as the current one."""
t = Template()
t.steps = self.steps[:]
t.debugging = self.debugging
return t
def debug(self, flag):
"""t.debug(flag) turns debugging on or off."""
self.debugging = flag
def append(self, cmd, kind):
"""t.append(cmd, kind) adds a new step at the end."""
if type(cmd) is not type(''):
raise TypeError, \
'Template.append: cmd must be a string'
if kind not in stepkinds:
raise ValueError, \
'Template.append: bad kind %r' % (kind,)
if kind == SOURCE:
raise ValueError, \
'Template.append: SOURCE can only be prepended'
if self.steps and self.steps[-1][1] == SINK:
raise ValueError, \
'Template.append: already ends with SINK'
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
raise ValueError, \
'Template.append: missing $IN in cmd'
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
raise ValueError, \
'Template.append: missing $OUT in cmd'
self.steps.append((cmd, kind))
def prepend(self, cmd, kind):
"""t.prepend(cmd, kind) adds a new step at the front."""
if type(cmd) is not type(''):
raise TypeError, \
'Template.prepend: cmd must be a string'
if kind not in stepkinds:
raise ValueError, \
'Template.prepend: bad kind %r' % (kind,)
if kind == SINK:
raise ValueError, \
'Template.prepend: SINK can only be appended'
if self.steps and self.steps[0][1] == SOURCE:
raise ValueError, \
'Template.prepend: already begins with SOURCE'
if kind[0] == 'f' and not re.search(r'\$IN\b', cmd):
raise ValueError, \
'Template.prepend: missing $IN in cmd'
if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd):
raise ValueError, \
'Template.prepend: missing $OUT in cmd'
self.steps.insert(0, (cmd, kind))
def open(self, file, rw):
"""t.open(file, rw) returns a pipe or file object open for
reading or writing; the file is the other end of the pipeline."""
if rw == 'r':
return self.open_r(file)
if rw == 'w':
return self.open_w(file)
raise ValueError, \
'Template.open: rw must be \'r\' or \'w\', not %r' % (rw,)
def open_r(self, file):
"""t.open_r(file) and t.open_w(file) implement
t.open(file, 'r') and t.open(file, 'w') respectively."""
if not self.steps:
return open(file, 'r')
if self.steps[-1][1] == SINK:
raise ValueError, \
'Template.open_r: pipeline ends width SINK'
cmd = self.makepipeline(file, '')
return os.popen(cmd, 'r')
def open_w(self, file):
if not self.steps:
return open(file, 'w')
if self.steps[0][1] == SOURCE:
raise ValueError, \
'Template.open_w: pipeline begins with SOURCE'
cmd = self.makepipeline('', file)
return os.popen(cmd, 'w')
def copy(self, infile, outfile):
return os.system(self.makepipeline(infile, outfile))
def makepipeline(self, infile, outfile):
cmd = makepipeline(infile, self.steps, outfile)
if self.debugging:
print cmd
cmd = 'set -x; ' + cmd
return cmd
def makepipeline(infile, steps, outfile):
# Build a list with for each command:
# [input filename or '', command string, kind, output filename or '']
list = []
for cmd, kind in steps:
list.append(['', cmd, kind, ''])
#
# Make sure there is at least one step
#
if not list:
list.append(['', 'cat', '--', ''])
#
# Take care of the input and output ends
#
[cmd, kind] = list[0][1:3]
if kind[0] == 'f' and not infile:
list.insert(0, ['', 'cat', '--', ''])
list[0][0] = infile
#
[cmd, kind] = list[-1][1:3]
if kind[1] == 'f' and not outfile:
list.append(['', 'cat', '--', ''])
list[-1][-1] = outfile
#
# Invent temporary files to connect stages that need files
#
garbage = []
for i in range(1, len(list)):
lkind = list[i-1][2]
rkind = list[i][2]
if lkind[1] == 'f' or rkind[0] == 'f':
(fd, temp) = tempfile.mkstemp()
os.close(fd)
garbage.append(temp)
list[i-1][-1] = list[i][0] = temp
#
for item in list:
[inf, cmd, kind, outf] = item
if kind[1] == 'f':
cmd = 'OUT=' + quote(outf) + '; ' + cmd
if kind[0] == 'f':
cmd = 'IN=' + quote(inf) + '; ' + cmd
if kind[0] == '-' and inf:
cmd = cmd + ' <' + quote(inf)
if kind[1] == '-' and outf:
cmd = cmd + ' >' + quote(outf)
item[1] = cmd
#
cmdlist = list[0][1]
for item in list[1:]:
[cmd, kind] = item[1:3]
if item[0] == '':
if 'f' in kind:
cmd = '{ ' + cmd + '; }'
cmdlist = cmdlist + ' |\n' + cmd
else:
cmdlist = cmdlist + '\n' + cmd
#
if garbage:
rmcmd = 'rm -f'
for file in garbage:
rmcmd = rmcmd + ' ' + quote(file)
trapcmd = 'trap ' + quote(rmcmd + '; exit') + ' 1 2 3 13 14 15'
cmdlist = trapcmd + '\n' + cmdlist + '\n' + rmcmd
#
return cmdlist
# Reliably quote a string as a single argument for /bin/sh
_safechars = string.ascii_letters + string.digits + '!@%_-+=:,./' # Safe unquoted
_funnychars = '"`$\\' # Unsafe inside "double quotes"
def quote(file):
for c in file:
if c not in _safechars:
break
else:
return file
if '\'' not in file:
return '\'' + file + '\''
res = ''
for c in file:
if c in _funnychars:
c = '\\' + c
res = res + c
return '"' + res + '"'
# Small test program and example
def test():
print 'Testing...'
t = Template()
t.append('togif $IN $OUT', 'ff')
t.append('giftoppm', '--')
t.append('ppmtogif >$OUT', '-f')
t.append('fromgif $IN $OUT', 'ff')
t.debug(1)
FILE = '/usr/local/images/rgb/rogues/guido.rgb'
t.copy(FILE, '@temp')
print 'Done.'
| Python |
"""Interface to the compiler's internal symbol tables"""
import _symtable
from _symtable import USE, DEF_GLOBAL, DEF_LOCAL, DEF_PARAM, \
DEF_STAR, DEF_DOUBLESTAR, DEF_INTUPLE, DEF_FREE, \
DEF_FREE_GLOBAL, DEF_FREE_CLASS, DEF_IMPORT, DEF_BOUND, \
OPT_IMPORT_STAR, OPT_EXEC, OPT_BARE_EXEC
import weakref
__all__ = ["symtable", "SymbolTable", "newSymbolTable", "Class",
"Function", "Symbol"]
def symtable(code, filename, compile_type):
raw = _symtable.symtable(code, filename, compile_type)
return newSymbolTable(raw[0], filename)
class SymbolTableFactory:
def __init__(self):
self.__memo = weakref.WeakValueDictionary()
def new(self, table, filename):
if table.type == _symtable.TYPE_FUNCTION:
return Function(table, filename)
if table.type == _symtable.TYPE_CLASS:
return Class(table, filename)
return SymbolTable(table, filename)
def __call__(self, table, filename):
key = table, filename
obj = self.__memo.get(key, None)
if obj is None:
obj = self.__memo[key] = self.new(table, filename)
return obj
newSymbolTable = SymbolTableFactory()
def is_free(flags):
if (flags & (USE | DEF_FREE)) \
and (flags & (DEF_LOCAL | DEF_PARAM | DEF_GLOBAL)):
return True
if flags & DEF_FREE_CLASS:
return True
return False
class SymbolTable:
def __init__(self, raw_table, filename):
self._table = raw_table
self._filename = filename
self._symbols = {}
def __repr__(self):
if self.__class__ == SymbolTable:
kind = ""
else:
kind = "%s " % self.__class__.__name__
if self._table.name == "global":
return "<%sSymbolTable for module %s>" % (kind, self._filename)
else:
return "<%sSymbolTable for %s in %s>" % (kind, self._table.name,
self._filename)
def get_type(self):
if self._table.type == _symtable.TYPE_MODULE:
return "module"
if self._table.type == _symtable.TYPE_FUNCTION:
return "function"
if self._table.type == _symtable.TYPE_CLASS:
return "class"
assert self._table.type in (1, 2, 3), \
"unexpected type: %s" % self._table.type
def get_id(self):
return self._table.id
def get_name(self):
return self._table.name
def get_lineno(self):
return self._table.lineno
def is_optimized(self):
return bool(self._table.type == _symtable.TYPE_FUNCTION
and not self._table.optimized)
def is_nested(self):
return bool(self._table.nested)
def has_children(self):
return bool(self._table.children)
def has_exec(self):
"""Return true if the scope uses exec"""
return bool(self._table.optimized & (OPT_EXEC | OPT_BARE_EXEC))
def has_import_star(self):
"""Return true if the scope uses import *"""
return bool(self._table.optimized & OPT_IMPORT_STAR)
def get_identifiers(self):
return self._table.symbols.keys()
def lookup(self, name):
sym = self._symbols.get(name)
if sym is None:
flags = self._table.symbols[name]
namespaces = self.__check_children(name)
sym = self._symbols[name] = Symbol(name, flags, namespaces)
return sym
def get_symbols(self):
return [self.lookup(ident) for ident in self.get_identifiers()]
def __check_children(self, name):
return [newSymbolTable(st, self._filename)
for st in self._table.children
if st.name == name]
def get_children(self):
return [newSymbolTable(st, self._filename)
for st in self._table.children]
class Function(SymbolTable):
# Default values for instance variables
__params = None
__locals = None
__frees = None
__globals = None
def __idents_matching(self, test_func):
return tuple([ident for ident in self.get_identifiers()
if test_func(self._table.symbols[ident])])
def get_parameters(self):
if self.__params is None:
self.__params = self.__idents_matching(lambda x:x & DEF_PARAM)
return self.__params
def get_locals(self):
if self.__locals is None:
self.__locals = self.__idents_matching(lambda x:x & DEF_BOUND)
return self.__locals
def get_globals(self):
if self.__globals is None:
glob = DEF_GLOBAL | DEF_FREE_GLOBAL
self.__globals = self.__idents_matching(lambda x:x & glob)
return self.__globals
def get_frees(self):
if self.__frees is None:
self.__frees = self.__idents_matching(is_free)
return self.__frees
class Class(SymbolTable):
__methods = None
def get_methods(self):
if self.__methods is None:
d = {}
for st in self._table.children:
d[st.name] = 1
self.__methods = tuple(d)
return self.__methods
class Symbol:
def __init__(self, name, flags, namespaces=None):
self.__name = name
self.__flags = flags
self.__namespaces = namespaces or ()
def __repr__(self):
return "<symbol '%s'>" % self.__name
def get_name(self):
return self.__name
def is_referenced(self):
return bool(self.__flags & _symtable.USE)
def is_parameter(self):
return bool(self.__flags & DEF_PARAM)
def is_global(self):
return bool((self.__flags & DEF_GLOBAL)
or (self.__flags & DEF_FREE_GLOBAL))
def is_vararg(self):
return bool(self.__flags & DEF_STAR)
def is_keywordarg(self):
return bool(self.__flags & DEF_DOUBLESTAR)
def is_local(self):
return bool(self.__flags & DEF_BOUND)
def is_free(self):
if (self.__flags & (USE | DEF_FREE)) \
and (self.__flags & (DEF_LOCAL | DEF_PARAM | DEF_GLOBAL)):
return True
if self.__flags & DEF_FREE_CLASS:
return True
return False
def is_imported(self):
return bool(self.__flags & DEF_IMPORT)
def is_assigned(self):
return bool(self.__flags & DEF_LOCAL)
def is_in_tuple(self):
return bool(self.__flags & DEF_INTUPLE)
def is_namespace(self):
"""Returns true if name binding introduces new namespace.
If the name is used as the target of a function or class
statement, this will be true.
Note that a single name can be bound to multiple objects. If
is_namespace() is true, the name may also be bound to other
objects, like an int or list, that does not introduce a new
namespace.
"""
return bool(self.__namespaces)
def get_namespaces(self):
"""Return a list of namespaces bound to this name"""
return self.__namespaces
def get_namespace(self):
"""Returns the single namespace bound to this name.
Raises ValueError if the name is bound to multiple namespaces.
"""
if len(self.__namespaces) != 1:
raise ValueError, "name is bound to multiple namespaces"
return self.__namespaces[0]
if __name__ == "__main__":
import os, sys
src = open(sys.argv[0]).read()
mod = symtable(src, os.path.split(sys.argv[0])[1], "exec")
for ident in mod.get_identifiers():
info = mod.lookup(ident)
print info, info.is_local(), info.is_namespace()
| Python |
# Copyright 2001-2004 by Vinay Sajip. 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 name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP 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.
"""
Additional handlers for the logging package for Python. The core package is
based on PEP 282 and comments thereto in comp.lang.python, and influenced by
Apache's log4j system.
Should work under Python versions >= 1.5.2, except that source line
information is not available unless 'sys._getframe()' is.
Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away!
"""
import sys, logging, socket, types, os, string, cPickle, struct, time, glob
#
# Some constants...
#
DEFAULT_TCP_LOGGING_PORT = 9020
DEFAULT_UDP_LOGGING_PORT = 9021
DEFAULT_HTTP_LOGGING_PORT = 9022
DEFAULT_SOAP_LOGGING_PORT = 9023
SYSLOG_UDP_PORT = 514
class BaseRotatingHandler(logging.FileHandler):
"""
Base class for handlers that rotate log files at a certain point.
Not meant to be instantiated directly. Instead, use RotatingFileHandler
or TimedRotatingFileHandler.
"""
def __init__(self, filename, mode):
"""
Use the specified filename for streamed logging
"""
logging.FileHandler.__init__(self, filename, mode)
def emit(self, record):
"""
Emit a record.
Output the record to the file, catering for rollover as described
in doRollover().
"""
try:
if self.shouldRollover(record):
self.doRollover()
logging.FileHandler.emit(self, record)
except:
self.handleError(record)
class RotatingFileHandler(BaseRotatingHandler):
"""
Handler for logging to a set of files, which switches from one file
to the next when the current file reaches a certain size.
"""
def __init__(self, filename, mode="a", maxBytes=0, backupCount=0):
"""
Open the specified file and use it as the stream for logging.
By default, the file grows indefinitely. You can specify particular
values of maxBytes and backupCount to allow the file to rollover at
a predetermined size.
Rollover occurs whenever the current log file is nearly maxBytes in
length. If backupCount is >= 1, the system will successively create
new files with the same pathname as the base file, but with extensions
".1", ".2" etc. appended to it. For example, with a backupCount of 5
and a base file name of "app.log", you would get "app.log",
"app.log.1", "app.log.2", ... through to "app.log.5". The file being
written to is always "app.log" - when it gets filled up, it is closed
and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
exist, then they are renamed to "app.log.2", "app.log.3" etc.
respectively.
If maxBytes is zero, rollover never occurs.
"""
self.mode = mode
if maxBytes > 0:
self.mode = "a" # doesn't make sense otherwise!
BaseRotatingHandler.__init__(self, filename, self.mode)
self.maxBytes = maxBytes
self.backupCount = backupCount
def doRollover(self):
"""
Do a rollover, as described in __init__().
"""
self.stream.close()
if self.backupCount > 0:
for i in range(self.backupCount - 1, 0, -1):
sfn = "%s.%d" % (self.baseFilename, i)
dfn = "%s.%d" % (self.baseFilename, i + 1)
if os.path.exists(sfn):
#print "%s -> %s" % (sfn, dfn)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(sfn, dfn)
dfn = self.baseFilename + ".1"
if os.path.exists(dfn):
os.remove(dfn)
os.rename(self.baseFilename, dfn)
#print "%s -> %s" % (self.baseFilename, dfn)
self.stream = open(self.baseFilename, "w")
def shouldRollover(self, record):
"""
Determine if rollover should occur.
Basically, see if the supplied record would cause the file to exceed
the size limit we have.
"""
if self.maxBytes > 0: # are we rolling over?
msg = "%s\n" % self.format(record)
self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
if self.stream.tell() + len(msg) >= self.maxBytes:
return 1
return 0
class TimedRotatingFileHandler(BaseRotatingHandler):
"""
Handler for logging to a file, rotating the log file at certain timed
intervals.
If backupCount is > 0, when rollover is done, no more than backupCount
files are kept - the oldest ones are deleted.
"""
def __init__(self, filename, when='h', interval=1, backupCount=0):
BaseRotatingHandler.__init__(self, filename, 'a')
self.when = string.upper(when)
self.backupCount = backupCount
# Calculate the real rollover interval, which is just the number of
# seconds between rollovers. Also set the filename suffix used when
# a rollover occurs. Current 'when' events supported:
# S - Seconds
# M - Minutes
# H - Hours
# D - Days
# midnight - roll over at midnight
# W{0-6} - roll over on a certain day; 0 - Monday
#
# Case of the 'when' specifier is not important; lower or upper case
# will work.
currentTime = int(time.time())
if self.when == 'S':
self.interval = 1 # one second
self.suffix = "%Y-%m-%d_%H-%M-%S"
elif self.when == 'M':
self.interval = 60 # one minute
self.suffix = "%Y-%m-%d_%H-%M"
elif self.when == 'H':
self.interval = 60 * 60 # one hour
self.suffix = "%Y-%m-%d_%H"
elif self.when == 'D' or self.when == 'MIDNIGHT':
self.interval = 60 * 60 * 24 # one day
self.suffix = "%Y-%m-%d"
elif self.when.startswith('W'):
self.interval = 60 * 60 * 24 * 7 # one week
if len(self.when) != 2:
raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when)
if self.when[1] < '0' or self.when[1] > '6':
raise ValueError("Invalid day specified for weekly rollover: %s" % self.when)
self.dayOfWeek = int(self.when[1])
self.suffix = "%Y-%m-%d"
else:
raise ValueError("Invalid rollover interval specified: %s" % self.when)
self.interval = self.interval * interval # multiply by units requested
self.rolloverAt = currentTime + self.interval
# If we are rolling over at midnight or weekly, then the interval is already known.
# What we need to figure out is WHEN the next interval is. In other words,
# if you are rolling over at midnight, then your base interval is 1 day,
# but you want to start that one day clock at midnight, not now. So, we
# have to fudge the rolloverAt value in order to trigger the first rollover
# at the right time. After that, the regular interval will take care of
# the rest. Note that this code doesn't care about leap seconds. :)
if self.when == 'MIDNIGHT' or self.when.startswith('W'):
# This could be done with less code, but I wanted it to be clear
t = time.localtime(currentTime)
currentHour = t[3]
currentMinute = t[4]
currentSecond = t[5]
# r is the number of seconds left between now and midnight
r = (24 - currentHour) * 60 * 60 # number of hours in seconds
r = r + (59 - currentMinute) * 60 # plus the number of minutes (in secs)
r = r + (59 - currentSecond) # plus the number of seconds
self.rolloverAt = currentTime + r
# If we are rolling over on a certain day, add in the number of days until
# the next rollover, but offset by 1 since we just calculated the time
# until the next day starts. There are three cases:
# Case 1) The day to rollover is today; in this case, do nothing
# Case 2) The day to rollover is further in the interval (i.e., today is
# day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to
# next rollover is simply 6 - 2 - 1, or 3.
# Case 3) The day to rollover is behind us in the interval (i.e., today
# is day 5 (Saturday) and rollover is on day 3 (Thursday).
# Days to rollover is 6 - 5 + 3, or 4. In this case, it's the
# number of days left in the current week (1) plus the number
# of days in the next week until the rollover day (3).
if when.startswith('W'):
day = t[6] # 0 is Monday
if day > self.dayOfWeek:
daysToWait = (day - self.dayOfWeek) - 1
self.rolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24))
if day < self.dayOfWeek:
daysToWait = (6 - self.dayOfWeek) + day
self.rolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24))
#print "Will rollover at %d, %d seconds from now" % (self.rolloverAt, self.rolloverAt - currentTime)
def shouldRollover(self, record):
"""
Determine if rollover should occur
record is not used, as we are just comparing times, but it is needed so
the method siguratures are the same
"""
t = int(time.time())
if t >= self.rolloverAt:
return 1
#print "No need to rollover: %d, %d" % (t, self.rolloverAt)
return 0
def doRollover(self):
"""
do a rollover; in this case, a date/time stamp is appended to the filename
when the rollover happens. However, you want the file to be named for the
start of the interval, not the current time. If there is a backup count,
then we have to get a list of matching filenames, sort them and remove
the one with the oldest suffix.
"""
self.stream.close()
# get the time that this sequence started at and make it a TimeTuple
t = self.rolloverAt - self.interval
timeTuple = time.localtime(t)
dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(self.baseFilename, dfn)
if self.backupCount > 0:
# find the oldest log file and delete it
s = glob.glob(self.baseFilename + ".20*")
if len(s) > self.backupCount:
s.sort()
os.remove(s[0])
#print "%s -> %s" % (self.baseFilename, dfn)
self.stream = open(self.baseFilename, "w")
self.rolloverAt = int(time.time()) + self.interval
class SocketHandler(logging.Handler):
"""
A handler class which writes logging records, in pickle format, to
a streaming socket. The socket is kept open across logging calls.
If the peer resets it, an attempt is made to reconnect on the next call.
The pickle which is sent is that of the LogRecord's attribute dictionary
(__dict__), so that the receiver does not need to have the logging module
installed in order to process the logging event.
To unpickle the record at the receiving end into a LogRecord, use the
makeLogRecord function.
"""
def __init__(self, host, port):
"""
Initializes the handler with a specific host address and port.
The attribute 'closeOnError' is set to 1 - which means that if
a socket error occurs, the socket is silently closed and then
reopened on the next logging call.
"""
logging.Handler.__init__(self)
self.host = host
self.port = port
self.sock = None
self.closeOnError = 0
self.retryTime = None
#
# Exponential backoff parameters.
#
self.retryStart = 1.0
self.retryMax = 30.0
self.retryFactor = 2.0
def makeSocket(self):
"""
A factory method which allows subclasses to define the precise
type of socket they want.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, self.port))
return s
def createSocket(self):
"""
Try to create a socket, using an exponential backoff with
a max retry time. Thanks to Robert Olson for the original patch
(SF #815911) which has been slightly refactored.
"""
now = time.time()
# Either retryTime is None, in which case this
# is the first time back after a disconnect, or
# we've waited long enough.
if self.retryTime is None:
attempt = 1
else:
attempt = (now >= self.retryTime)
if attempt:
try:
self.sock = self.makeSocket()
self.retryTime = None # next time, no delay before trying
except:
#Creation failed, so set the retry time and return.
if self.retryTime is None:
self.retryPeriod = self.retryStart
else:
self.retryPeriod = self.retryPeriod * self.retryFactor
if self.retryPeriod > self.retryMax:
self.retryPeriod = self.retryMax
self.retryTime = now + self.retryPeriod
def send(self, s):
"""
Send a pickled string to the socket.
This function allows for partial sends which can happen when the
network is busy.
"""
if self.sock is None:
self.createSocket()
#self.sock can be None either because we haven't reached the retry
#time yet, or because we have reached the retry time and retried,
#but are still unable to connect.
if self.sock:
try:
if hasattr(self.sock, "sendall"):
self.sock.sendall(s)
else:
sentsofar = 0
left = len(s)
while left > 0:
sent = self.sock.send(s[sentsofar:])
sentsofar = sentsofar + sent
left = left - sent
except socket.error:
self.sock.close()
self.sock = None # so we can call createSocket next time
def makePickle(self, record):
"""
Pickles the record in binary format with a length prefix, and
returns it ready for transmission across the socket.
"""
ei = record.exc_info
if ei:
dummy = self.format(record) # just to get traceback text into record.exc_text
record.exc_info = None # to avoid Unpickleable error
s = cPickle.dumps(record.__dict__, 1)
if ei:
record.exc_info = ei # for next handler
slen = struct.pack(">L", len(s))
return slen + s
def handleError(self, record):
"""
Handle an error during logging.
An error has occurred during logging. Most likely cause -
connection lost. Close the socket so that we can retry on the
next event.
"""
if self.closeOnError and self.sock:
self.sock.close()
self.sock = None #try to reconnect next time
else:
logging.Handler.handleError(self, record)
def emit(self, record):
"""
Emit a record.
Pickles the record and writes it to the socket in binary format.
If there is an error with the socket, silently drop the packet.
If there was a problem with the socket, re-establishes the
socket.
"""
try:
s = self.makePickle(record)
self.send(s)
except:
self.handleError(record)
def close(self):
"""
Closes the socket.
"""
if self.sock:
self.sock.close()
self.sock = None
logging.Handler.close(self)
class DatagramHandler(SocketHandler):
"""
A handler class which writes logging records, in pickle format, to
a datagram socket. The pickle which is sent is that of the LogRecord's
attribute dictionary (__dict__), so that the receiver does not need to
have the logging module installed in order to process the logging event.
To unpickle the record at the receiving end into a LogRecord, use the
makeLogRecord function.
"""
def __init__(self, host, port):
"""
Initializes the handler with a specific host address and port.
"""
SocketHandler.__init__(self, host, port)
self.closeOnError = 0
def makeSocket(self):
"""
The factory method of SocketHandler is here overridden to create
a UDP socket (SOCK_DGRAM).
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return s
def send(self, s):
"""
Send a pickled string to a socket.
This function no longer allows for partial sends which can happen
when the network is busy - UDP does not guarantee delivery and
can deliver packets out of sequence.
"""
if self.sock is None:
self.createSocket()
self.sock.sendto(s, (self.host, self.port))
class SysLogHandler(logging.Handler):
"""
A handler class which sends formatted logging records to a syslog
server. Based on Sam Rushing's syslog module:
http://www.nightmare.com/squirl/python-ext/misc/syslog.py
Contributed by Nicolas Untz (after which minor refactoring changes
have been made).
"""
# from <linux/sys/syslog.h>:
# ======================================================================
# priorities/facilities are encoded into a single 32-bit quantity, where
# the bottom 3 bits are the priority (0-7) and the top 28 bits are the
# facility (0-big number). Both the priorities and the facilities map
# roughly one-to-one to strings in the syslogd(8) source code. This
# mapping is included in this file.
#
# priorities (these are ordered)
LOG_EMERG = 0 # system is unusable
LOG_ALERT = 1 # action must be taken immediately
LOG_CRIT = 2 # critical conditions
LOG_ERR = 3 # error conditions
LOG_WARNING = 4 # warning conditions
LOG_NOTICE = 5 # normal but significant condition
LOG_INFO = 6 # informational
LOG_DEBUG = 7 # debug-level messages
# facility codes
LOG_KERN = 0 # kernel messages
LOG_USER = 1 # random user-level messages
LOG_MAIL = 2 # mail system
LOG_DAEMON = 3 # system daemons
LOG_AUTH = 4 # security/authorization messages
LOG_SYSLOG = 5 # messages generated internally by syslogd
LOG_LPR = 6 # line printer subsystem
LOG_NEWS = 7 # network news subsystem
LOG_UUCP = 8 # UUCP subsystem
LOG_CRON = 9 # clock daemon
LOG_AUTHPRIV = 10 # security/authorization messages (private)
# other codes through 15 reserved for system use
LOG_LOCAL0 = 16 # reserved for local use
LOG_LOCAL1 = 17 # reserved for local use
LOG_LOCAL2 = 18 # reserved for local use
LOG_LOCAL3 = 19 # reserved for local use
LOG_LOCAL4 = 20 # reserved for local use
LOG_LOCAL5 = 21 # reserved for local use
LOG_LOCAL6 = 22 # reserved for local use
LOG_LOCAL7 = 23 # reserved for local use
priority_names = {
"alert": LOG_ALERT,
"crit": LOG_CRIT,
"critical": LOG_CRIT,
"debug": LOG_DEBUG,
"emerg": LOG_EMERG,
"err": LOG_ERR,
"error": LOG_ERR, # DEPRECATED
"info": LOG_INFO,
"notice": LOG_NOTICE,
"panic": LOG_EMERG, # DEPRECATED
"warn": LOG_WARNING, # DEPRECATED
"warning": LOG_WARNING,
}
facility_names = {
"auth": LOG_AUTH,
"authpriv": LOG_AUTHPRIV,
"cron": LOG_CRON,
"daemon": LOG_DAEMON,
"kern": LOG_KERN,
"lpr": LOG_LPR,
"mail": LOG_MAIL,
"news": LOG_NEWS,
"security": LOG_AUTH, # DEPRECATED
"syslog": LOG_SYSLOG,
"user": LOG_USER,
"uucp": LOG_UUCP,
"local0": LOG_LOCAL0,
"local1": LOG_LOCAL1,
"local2": LOG_LOCAL2,
"local3": LOG_LOCAL3,
"local4": LOG_LOCAL4,
"local5": LOG_LOCAL5,
"local6": LOG_LOCAL6,
"local7": LOG_LOCAL7,
}
def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER):
"""
Initialize a handler.
If address is specified as a string, UNIX socket is used.
If facility is not specified, LOG_USER is used.
"""
logging.Handler.__init__(self)
self.address = address
self.facility = facility
if type(address) == types.StringType:
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
# syslog may require either DGRAM or STREAM sockets
try:
self.socket.connect(address)
except socket.error:
self.socket.close()
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.socket.connect(address)
self.unixsocket = 1
else:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.unixsocket = 0
self.formatter = None
# curious: when talking to the unix-domain '/dev/log' socket, a
# zero-terminator seems to be required. this string is placed
# into a class variable so that it can be overridden if
# necessary.
log_format_string = '<%d>%s\000'
def encodePriority (self, facility, priority):
"""
Encode the facility and priority. You can pass in strings or
integers - if strings are passed, the facility_names and
priority_names mapping dictionaries are used to convert them to
integers.
"""
if type(facility) == types.StringType:
facility = self.facility_names[facility]
if type(priority) == types.StringType:
priority = self.priority_names[priority]
return (facility << 3) | priority
def close (self):
"""
Closes the socket.
"""
if self.unixsocket:
self.socket.close()
logging.Handler.close(self)
def emit(self, record):
"""
Emit a record.
The record is formatted, and then sent to the syslog server. If
exception information is present, it is NOT sent to the server.
"""
msg = self.format(record)
"""
We need to convert record level to lowercase, maybe this will
change in the future.
"""
msg = self.log_format_string % (
self.encodePriority(self.facility,
string.lower(record.levelname)),
msg)
try:
if self.unixsocket:
self.socket.send(msg)
else:
self.socket.sendto(msg, self.address)
except:
self.handleError(record)
class SMTPHandler(logging.Handler):
"""
A handler class which sends an SMTP email for each logging event.
"""
def __init__(self, mailhost, fromaddr, toaddrs, subject):
"""
Initialize the handler.
Initialize the instance with the from and to addresses and subject
line of the email. To specify a non-standard SMTP port, use the
(host, port) tuple format for the mailhost argument.
"""
logging.Handler.__init__(self)
if type(mailhost) == types.TupleType:
host, port = mailhost
self.mailhost = host
self.mailport = port
else:
self.mailhost = mailhost
self.mailport = None
self.fromaddr = fromaddr
if type(toaddrs) == types.StringType:
toaddrs = [toaddrs]
self.toaddrs = toaddrs
self.subject = subject
def getSubject(self, record):
"""
Determine the subject for the email.
If you want to specify a subject line which is record-dependent,
override this method.
"""
return self.subject
weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
monthname = [None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
def date_time(self):
"""
Return the current date and time formatted for a MIME header.
Needed for Python 1.5.2 (no email package available)
"""
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(time.time())
s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
self.weekdayname[wd],
day, self.monthname[month], year,
hh, mm, ss)
return s
def emit(self, record):
"""
Emit a record.
Format the record and send it to the specified addressees.
"""
try:
import smtplib
try:
from email.Utils import formatdate
except:
formatdate = self.date_time
port = self.mailport
if not port:
port = smtplib.SMTP_PORT
smtp = smtplib.SMTP(self.mailhost, port)
msg = self.format(record)
msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % (
self.fromaddr,
string.join(self.toaddrs, ","),
self.getSubject(record),
formatdate(), msg)
smtp.sendmail(self.fromaddr, self.toaddrs, msg)
smtp.quit()
except:
self.handleError(record)
class NTEventLogHandler(logging.Handler):
"""
A handler class which sends events to the NT Event Log. Adds a
registry entry for the specified application name. If no dllname is
provided, win32service.pyd (which contains some basic message
placeholders) is used. Note that use of these placeholders will make
your event logs big, as the entire message source is held in the log.
If you want slimmer logs, you have to pass in the name of your own DLL
which contains the message definitions you want to use in the event log.
"""
def __init__(self, appname, dllname=None, logtype="Application"):
logging.Handler.__init__(self)
try:
import win32evtlogutil, win32evtlog
self.appname = appname
self._welu = win32evtlogutil
if not dllname:
dllname = os.path.split(self._welu.__file__)
dllname = os.path.split(dllname[0])
dllname = os.path.join(dllname[0], r'win32service.pyd')
self.dllname = dllname
self.logtype = logtype
self._welu.AddSourceToRegistry(appname, dllname, logtype)
self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
self.typemap = {
logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE,
logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE,
logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE,
logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
}
except ImportError:
print "The Python Win32 extensions for NT (service, event "\
"logging) appear not to be available."
self._welu = None
def getMessageID(self, record):
"""
Return the message ID for the event record. If you are using your
own messages, you could do this by having the msg passed to the
logger being an ID rather than a formatting string. Then, in here,
you could use a dictionary lookup to get the message ID. This
version returns 1, which is the base message ID in win32service.pyd.
"""
return 1
def getEventCategory(self, record):
"""
Return the event category for the record.
Override this if you want to specify your own categories. This version
returns 0.
"""
return 0
def getEventType(self, record):
"""
Return the event type for the record.
Override this if you want to specify your own types. This version does
a mapping using the handler's typemap attribute, which is set up in
__init__() to a dictionary which contains mappings for DEBUG, INFO,
WARNING, ERROR and CRITICAL. If you are using your own levels you will
either need to override this method or place a suitable dictionary in
the handler's typemap attribute.
"""
return self.typemap.get(record.levelno, self.deftype)
def emit(self, record):
"""
Emit a record.
Determine the message ID, event category and event type. Then
log the message in the NT event log.
"""
if self._welu:
try:
id = self.getMessageID(record)
cat = self.getEventCategory(record)
type = self.getEventType(record)
msg = self.format(record)
self._welu.ReportEvent(self.appname, id, cat, type, [msg])
except:
self.handleError(record)
def close(self):
"""
Clean up this handler.
You can remove the application name from the registry as a
source of event log entries. However, if you do this, you will
not be able to see the events as you intended in the Event Log
Viewer - it needs to be able to access the registry to get the
DLL name.
"""
#self._welu.RemoveSourceFromRegistry(self.appname, self.logtype)
logging.Handler.close(self)
class HTTPHandler(logging.Handler):
"""
A class which sends records to a Web server, using either GET or
POST semantics.
"""
def __init__(self, host, url, method="GET"):
"""
Initialize the instance with the host, the request URL, and the method
("GET" or "POST")
"""
logging.Handler.__init__(self)
method = string.upper(method)
if method not in ["GET", "POST"]:
raise ValueError, "method must be GET or POST"
self.host = host
self.url = url
self.method = method
def mapLogRecord(self, record):
"""
Default implementation of mapping the log record into a dict
that is sent as the CGI data. Overwrite in your class.
Contributed by Franz Glasner.
"""
return record.__dict__
def emit(self, record):
"""
Emit a record.
Send the record to the Web server as an URL-encoded dictionary
"""
try:
import httplib, urllib
h = httplib.HTTP(self.host)
url = self.url
data = urllib.urlencode(self.mapLogRecord(record))
if self.method == "GET":
if (string.find(url, '?') >= 0):
sep = '&'
else:
sep = '?'
url = url + "%c%s" % (sep, data)
h.putrequest(self.method, url)
if self.method == "POST":
h.putheader("Content-length", str(len(data)))
h.endheaders()
if self.method == "POST":
h.send(data)
h.getreply() #can't do anything with the result
except:
self.handleError(record)
class BufferingHandler(logging.Handler):
"""
A handler class which buffers logging records in memory. Whenever each
record is added to the buffer, a check is made to see if the buffer should
be flushed. If it should, then flush() is expected to do what's needed.
"""
def __init__(self, capacity):
"""
Initialize the handler with the buffer size.
"""
logging.Handler.__init__(self)
self.capacity = capacity
self.buffer = []
def shouldFlush(self, record):
"""
Should the handler flush its buffer?
Returns true if the buffer is up to capacity. This method can be
overridden to implement custom flushing strategies.
"""
return (len(self.buffer) >= self.capacity)
def emit(self, record):
"""
Emit a record.
Append the record. If shouldFlush() tells us to, call flush() to process
the buffer.
"""
self.buffer.append(record)
if self.shouldFlush(record):
self.flush()
def flush(self):
"""
Override to implement custom flushing behaviour.
This version just zaps the buffer to empty.
"""
self.buffer = []
def close(self):
"""
Close the handler.
This version just flushes and chains to the parent class' close().
"""
self.flush()
logging.Handler.close(self)
class MemoryHandler(BufferingHandler):
"""
A handler class which buffers logging records in memory, periodically
flushing them to a target handler. Flushing occurs whenever the buffer
is full, or when an event of a certain severity or greater is seen.
"""
def __init__(self, capacity, flushLevel=logging.ERROR, target=None):
"""
Initialize the handler with the buffer size, the level at which
flushing should occur and an optional target.
Note that without a target being set either here or via setTarget(),
a MemoryHandler is no use to anyone!
"""
BufferingHandler.__init__(self, capacity)
self.flushLevel = flushLevel
self.target = target
def shouldFlush(self, record):
"""
Check for buffer full or a record at the flushLevel or higher.
"""
return (len(self.buffer) >= self.capacity) or \
(record.levelno >= self.flushLevel)
def setTarget(self, target):
"""
Set the target handler for this handler.
"""
self.target = target
def flush(self):
"""
For a MemoryHandler, flushing means just sending the buffered
records to the target, if there is one. Override if you want
different behaviour.
"""
if self.target:
for record in self.buffer:
self.target.handle(record)
self.buffer = []
def close(self):
"""
Flush, set the target to None and lose the buffer.
"""
self.flush()
self.target = None
BufferingHandler.close(self)
| Python |
# Copyright 2001-2004 by Vinay Sajip. 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 name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP 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.
"""
Configuration functions for the logging package for Python. The core package
is based on PEP 282 and comments thereto in comp.lang.python, and influenced
by Apache's log4j system.
Should work under Python versions >= 1.5.2, except that source line
information is not available unless 'sys._getframe()' is.
Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away!
"""
import sys, logging, logging.handlers, string, thread, threading, socket, struct, os
from SocketServer import ThreadingTCPServer, StreamRequestHandler
DEFAULT_LOGGING_CONFIG_PORT = 9030
if sys.platform == "win32":
RESET_ERROR = 10054 #WSAECONNRESET
else:
RESET_ERROR = 104 #ECONNRESET
#
# The following code implements a socket listener for on-the-fly
# reconfiguration of logging.
#
# _listener holds the server object doing the listening
_listener = None
def fileConfig(fname, defaults=None):
"""
Read the logging configuration from a ConfigParser-format file.
This can be called several times from an application, allowing an end user
the ability to select from various pre-canned configurations (if the
developer provides a mechanism to present the choices and load the chosen
configuration).
In versions of ConfigParser which have the readfp method [typically
shipped in 2.x versions of Python], you can pass in a file-like object
rather than a filename, in which case the file-like object will be read
using readfp.
"""
import ConfigParser
cp = ConfigParser.ConfigParser(defaults)
if hasattr(cp, 'readfp') and hasattr(fname, 'readline'):
cp.readfp(fname)
else:
cp.read(fname)
#first, do the formatters...
flist = cp.get("formatters", "keys")
if len(flist):
flist = string.split(flist, ",")
formatters = {}
for form in flist:
sectname = "formatter_%s" % form
opts = cp.options(sectname)
if "format" in opts:
fs = cp.get(sectname, "format", 1)
else:
fs = None
if "datefmt" in opts:
dfs = cp.get(sectname, "datefmt", 1)
else:
dfs = None
f = logging.Formatter(fs, dfs)
formatters[form] = f
#next, do the handlers...
#critical section...
logging._acquireLock()
try:
try:
#first, lose the existing handlers...
logging._handlers.clear()
#now set up the new ones...
hlist = cp.get("handlers", "keys")
if len(hlist):
hlist = string.split(hlist, ",")
handlers = {}
fixups = [] #for inter-handler references
for hand in hlist:
try:
sectname = "handler_%s" % hand
klass = cp.get(sectname, "class")
opts = cp.options(sectname)
if "formatter" in opts:
fmt = cp.get(sectname, "formatter")
else:
fmt = ""
klass = eval(klass, vars(logging))
args = cp.get(sectname, "args")
args = eval(args, vars(logging))
h = apply(klass, args)
if "level" in opts:
level = cp.get(sectname, "level")
h.setLevel(logging._levelNames[level])
if len(fmt):
h.setFormatter(formatters[fmt])
#temporary hack for FileHandler and MemoryHandler.
if klass == logging.handlers.MemoryHandler:
if "target" in opts:
target = cp.get(sectname,"target")
else:
target = ""
if len(target): #the target handler may not be loaded yet, so keep for later...
fixups.append((h, target))
handlers[hand] = h
except: #if an error occurs when instantiating a handler, too bad
pass #this could happen e.g. because of lack of privileges
#now all handlers are loaded, fixup inter-handler references...
for fixup in fixups:
h = fixup[0]
t = fixup[1]
h.setTarget(handlers[t])
#at last, the loggers...first the root...
llist = cp.get("loggers", "keys")
llist = string.split(llist, ",")
llist.remove("root")
sectname = "logger_root"
root = logging.root
log = root
opts = cp.options(sectname)
if "level" in opts:
level = cp.get(sectname, "level")
log.setLevel(logging._levelNames[level])
for h in root.handlers[:]:
root.removeHandler(h)
hlist = cp.get(sectname, "handlers")
if len(hlist):
hlist = string.split(hlist, ",")
for hand in hlist:
log.addHandler(handlers[hand])
#and now the others...
#we don't want to lose the existing loggers,
#since other threads may have pointers to them.
#existing is set to contain all existing loggers,
#and as we go through the new configuration we
#remove any which are configured. At the end,
#what's left in existing is the set of loggers
#which were in the previous configuration but
#which are not in the new configuration.
existing = root.manager.loggerDict.keys()
#now set up the new ones...
for log in llist:
sectname = "logger_%s" % log
qn = cp.get(sectname, "qualname")
opts = cp.options(sectname)
if "propagate" in opts:
propagate = cp.getint(sectname, "propagate")
else:
propagate = 1
logger = logging.getLogger(qn)
if qn in existing:
existing.remove(qn)
if "level" in opts:
level = cp.get(sectname, "level")
logger.setLevel(logging._levelNames[level])
for h in logger.handlers[:]:
logger.removeHandler(h)
logger.propagate = propagate
logger.disabled = 0
hlist = cp.get(sectname, "handlers")
if len(hlist):
hlist = string.split(hlist, ",")
for hand in hlist:
logger.addHandler(handlers[hand])
#Disable any old loggers. There's no point deleting
#them as other threads may continue to hold references
#and by disabling them, you stop them doing any logging.
for log in existing:
root.manager.loggerDict[log].disabled = 1
except:
import traceback
ei = sys.exc_info()
traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
del ei
finally:
logging._releaseLock()
def listen(port=DEFAULT_LOGGING_CONFIG_PORT):
"""
Start up a socket server on the specified port, and listen for new
configurations.
These will be sent as a file suitable for processing by fileConfig().
Returns a Thread object on which you can call start() to start the server,
and which you can join() when appropriate. To stop the server, call
stopListening().
"""
if not thread:
raise NotImplementedError, "listen() needs threading to work"
class ConfigStreamHandler(StreamRequestHandler):
"""
Handler for a logging configuration request.
It expects a completely new logging configuration and uses fileConfig
to install it.
"""
def handle(self):
"""
Handle a request.
Each request is expected to be a 4-byte length,
followed by the config file. Uses fileConfig() to do the
grunt work.
"""
import tempfile
try:
conn = self.connection
chunk = conn.recv(4)
if len(chunk) == 4:
slen = struct.unpack(">L", chunk)[0]
chunk = self.connection.recv(slen)
while len(chunk) < slen:
chunk = chunk + conn.recv(slen - len(chunk))
#Apply new configuration. We'd like to be able to
#create a StringIO and pass that in, but unfortunately
#1.5.2 ConfigParser does not support reading file
#objects, only actual files. So we create a temporary
#file and remove it later.
file = tempfile.mktemp(".ini")
f = open(file, "w")
f.write(chunk)
f.close()
fileConfig(file)
os.remove(file)
except socket.error, e:
if type(e.args) != types.TupleType:
raise
else:
errcode = e.args[0]
if errcode != RESET_ERROR:
raise
class ConfigSocketReceiver(ThreadingTCPServer):
"""
A simple TCP socket-based logging config receiver.
"""
allow_reuse_address = 1
def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
handler=None):
ThreadingTCPServer.__init__(self, (host, port), handler)
logging._acquireLock()
self.abort = 0
logging._releaseLock()
self.timeout = 1
def serve_until_stopped(self):
import select
abort = 0
while not abort:
rd, wr, ex = select.select([self.socket.fileno()],
[], [],
self.timeout)
if rd:
self.handle_request()
logging._acquireLock()
abort = self.abort
logging._releaseLock()
def serve(rcvr, hdlr, port):
server = rcvr(port=port, handler=hdlr)
global _listener
logging._acquireLock()
_listener = server
logging._releaseLock()
server.serve_until_stopped()
return threading.Thread(target=serve,
args=(ConfigSocketReceiver,
ConfigStreamHandler, port))
def stopListening():
"""
Stop the listening server which was created with a call to listen().
"""
global _listener
if _listener:
logging._acquireLock()
_listener.abort = 1
_listener = None
logging._releaseLock()
| Python |
# Copyright 2001-2004 by Vinay Sajip. 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 name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP 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.
"""
Logging package for Python. Based on PEP 282 and comments thereto in
comp.lang.python, and influenced by Apache's log4j system.
Should work under Python versions >= 1.5.2, except that source line
information is not available unless 'sys._getframe()' is.
Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away!
"""
import sys, os, types, time, string, cStringIO
try:
import thread
import threading
except ImportError:
thread = None
__author__ = "Vinay Sajip <vinay_sajip@red-dove.com>"
__status__ = "beta"
__version__ = "0.4.9.6"
__date__ = "20 October 2004"
#---------------------------------------------------------------------------
# Miscellaneous module data
#---------------------------------------------------------------------------
#
#_srcfile is used when walking the stack to check when we've got the first
# caller stack frame.
#
if string.lower(__file__[-4:]) in ['.pyc', '.pyo']:
_srcfile = __file__[:-4] + '.py'
else:
_srcfile = __file__
_srcfile = os.path.normcase(_srcfile)
# _srcfile is only used in conjunction with sys._getframe().
# To provide compatibility with older versions of Python, set _srcfile
# to None if _getframe() is not available; this value will prevent
# findCaller() from being called.
if not hasattr(sys, "_getframe"):
_srcfile = None
#
#_startTime is used as the base when calculating the relative time of events
#
_startTime = time.time()
#
#raiseExceptions is used to see if exceptions during handling should be
#propagated
#
raiseExceptions = 1
#---------------------------------------------------------------------------
# Level related stuff
#---------------------------------------------------------------------------
#
# Default levels and level names, these can be replaced with any positive set
# of values having corresponding names. There is a pseudo-level, NOTSET, which
# is only really there as a lower limit for user-defined levels. Handlers and
# loggers are initialized with NOTSET so that they will log all messages, even
# at user-defined levels.
#
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
_levelNames = {
CRITICAL : 'CRITICAL',
ERROR : 'ERROR',
WARNING : 'WARNING',
INFO : 'INFO',
DEBUG : 'DEBUG',
NOTSET : 'NOTSET',
'CRITICAL' : CRITICAL,
'ERROR' : ERROR,
'WARN' : WARNING,
'WARNING' : WARNING,
'INFO' : INFO,
'DEBUG' : DEBUG,
'NOTSET' : NOTSET,
}
def getLevelName(level):
"""
Return the textual representation of logging level 'level'.
If the level is one of the predefined levels (CRITICAL, ERROR, WARNING,
INFO, DEBUG) then you get the corresponding string. If you have
associated levels with names using addLevelName then the name you have
associated with 'level' is returned.
If a numeric value corresponding to one of the defined levels is passed
in, the corresponding string representation is returned.
Otherwise, the string "Level %s" % level is returned.
"""
return _levelNames.get(level, ("Level %s" % level))
def addLevelName(level, levelName):
"""
Associate 'levelName' with 'level'.
This is used when converting levels to text during message formatting.
"""
_acquireLock()
try: #unlikely to cause an exception, but you never know...
_levelNames[level] = levelName
_levelNames[levelName] = level
finally:
_releaseLock()
#---------------------------------------------------------------------------
# Thread-related stuff
#---------------------------------------------------------------------------
#
#_lock is used to serialize access to shared data structures in this module.
#This needs to be an RLock because fileConfig() creates Handlers and so
#might arbitrary user threads. Since Handler.__init__() updates the shared
#dictionary _handlers, it needs to acquire the lock. But if configuring,
#the lock would already have been acquired - so we need an RLock.
#The same argument applies to Loggers and Manager.loggerDict.
#
_lock = None
def _acquireLock():
"""
Acquire the module-level lock for serializing access to shared data.
This should be released with _releaseLock().
"""
global _lock
if (not _lock) and thread:
_lock = threading.RLock()
if _lock:
_lock.acquire()
def _releaseLock():
"""
Release the module-level lock acquired by calling _acquireLock().
"""
if _lock:
_lock.release()
#---------------------------------------------------------------------------
# The logging record
#---------------------------------------------------------------------------
class LogRecord:
"""
A LogRecord instance represents an event being logged.
LogRecord instances are created every time something is logged. They
contain all the information pertinent to the event being logged. The
main information passed in is in msg and args, which are combined
using str(msg) % args to create the message field of the record. The
record also includes information such as when the record was created,
the source line where the logging call was made, and any exception
information to be logged.
"""
def __init__(self, name, level, pathname, lineno, msg, args, exc_info):
"""
Initialize a logging record with interesting information.
"""
ct = time.time()
self.name = name
self.msg = msg
#
# The following statement allows passing of a dictionary as a sole
# argument, so that you can do something like
# logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2})
# Suggested by Stefan Behnel.
# Note that without the test for args[0], we get a problem because
# during formatting, we test to see if the arg is present using
# 'if self.args:'. If the event being logged is e.g. 'Value is %d'
# and if the passed arg fails 'if self.args:' then no formatting
# is done. For example, logger.warn('Value is %d', 0) would log
# 'Value is %d' instead of 'Value is 0'.
# For the use case of passing a dictionary, this should not be a
# problem.
if args and (len(args) == 1) and args[0] and (type(args[0]) == types.DictType):
args = args[0]
self.args = args
self.levelname = getLevelName(level)
self.levelno = level
self.pathname = pathname
try:
self.filename = os.path.basename(pathname)
self.module = os.path.splitext(self.filename)[0]
except:
self.filename = pathname
self.module = "Unknown module"
self.exc_info = exc_info
self.exc_text = None # used to cache the traceback text
self.lineno = lineno
self.created = ct
self.msecs = (ct - long(ct)) * 1000
self.relativeCreated = (self.created - _startTime) * 1000
if thread:
self.thread = thread.get_ident()
else:
self.thread = None
if hasattr(os, 'getpid'):
self.process = os.getpid()
else:
self.process = None
def __str__(self):
return '<LogRecord: %s, %s, %s, %s, "%s">'%(self.name, self.levelno,
self.pathname, self.lineno, self.msg)
def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied
arguments with the message.
"""
if not hasattr(types, "UnicodeType"): #if no unicode support...
msg = str(self.msg)
else:
try:
msg = str(self.msg)
except UnicodeError:
msg = self.msg #Defer encoding till later
if self.args:
msg = msg % self.args
return msg
def makeLogRecord(dict):
"""
Make a LogRecord whose attributes are defined by the specified dictionary,
This function is useful for converting a logging event received over
a socket connection (which is sent as a dictionary) into a LogRecord
instance.
"""
rv = LogRecord(None, None, "", 0, "", (), None)
rv.__dict__.update(dict)
return rv
#---------------------------------------------------------------------------
# Formatter classes and functions
#---------------------------------------------------------------------------
class Formatter:
"""
Formatter instances are used to convert a LogRecord to text.
Formatters need to know how a LogRecord is constructed. They are
responsible for converting a LogRecord to (usually) a string which can
be interpreted by either a human or an external system. The base Formatter
allows a formatting string to be specified. If none is supplied, the
default value of "%s(message)\\n" is used.
The Formatter can be initialized with a format string which makes use of
knowledge of the LogRecord attributes - e.g. the default value mentioned
above makes use of the fact that the user's message and arguments are pre-
formatted into a LogRecord's message attribute. Currently, the useful
attributes in a LogRecord are described by:
%(name)s Name of the logger (logging channel)
%(levelno)s Numeric logging level for the message (DEBUG, INFO,
WARNING, ERROR, CRITICAL)
%(levelname)s Text logging level for the message ("DEBUG", "INFO",
"WARNING", "ERROR", "CRITICAL")
%(pathname)s Full pathname of the source file where the logging
call was issued (if available)
%(filename)s Filename portion of pathname
%(module)s Module (name portion of filename)
%(lineno)d Source line number where the logging call was issued
(if available)
%(created)f Time when the LogRecord was created (time.time()
return value)
%(asctime)s Textual time when the LogRecord was created
%(msecs)d Millisecond portion of the creation time
%(relativeCreated)d Time in milliseconds when the LogRecord was created,
relative to the time the logging module was loaded
(typically at application startup time)
%(thread)d Thread ID (if available)
%(process)d Process ID (if available)
%(message)s The result of record.getMessage(), computed just as
the record is emitted
"""
converter = time.localtime
def __init__(self, fmt=None, datefmt=None):
"""
Initialize the formatter with specified format strings.
Initialize the formatter either with the specified format string, or a
default as described above. Allow for specialized date formatting with
the optional datefmt argument (if omitted, you get the ISO8601 format).
"""
if fmt:
self._fmt = fmt
else:
self._fmt = "%(message)s"
self.datefmt = datefmt
def formatTime(self, record, datefmt=None):
"""
Return the creation time of the specified LogRecord as formatted text.
This method should be called from format() by a formatter which
wants to make use of a formatted time. This method can be overridden
in formatters to provide for any specific requirement, but the
basic behaviour is as follows: if datefmt (a string) is specified,
it is used with time.strftime() to format the creation time of the
record. Otherwise, the ISO8601 format is used. The resulting
string is returned. This function uses a user-configurable function
to convert the creation time to a tuple. By default, time.localtime()
is used; to change this for a particular formatter instance, set the
'converter' attribute to a function with the same signature as
time.localtime() or time.gmtime(). To change it for all formatters,
for example if you want all logging times to be shown in GMT,
set the 'converter' attribute in the Formatter class.
"""
ct = self.converter(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
s = "%s,%03d" % (t, record.msecs)
return s
def formatException(self, ei):
"""
Format and return the specified exception information as a string.
This default implementation just uses
traceback.print_exception()
"""
import traceback
sio = cStringIO.StringIO()
traceback.print_exception(ei[0], ei[1], ei[2], None, sio)
s = sio.getvalue()
sio.close()
if s[-1] == "\n":
s = s[:-1]
return s
def format(self, record):
"""
Format the specified record as text.
The record's attribute dictionary is used as the operand to a
string formatting operation which yields the returned string.
Before formatting the dictionary, a couple of preparatory steps
are carried out. The message attribute of the record is computed
using LogRecord.getMessage(). If the formatting string contains
"%(asctime)", formatTime() is called to format the event time.
If there is exception information, it is formatted using
formatException() and appended to the message.
"""
record.message = record.getMessage()
if string.find(self._fmt,"%(asctime)") >= 0:
record.asctime = self.formatTime(record, self.datefmt)
s = self._fmt % record.__dict__
if record.exc_info:
# Cache the traceback text to avoid converting it multiple times
# (it's constant anyway)
if not record.exc_text:
record.exc_text = self.formatException(record.exc_info)
if record.exc_text:
if s[-1] != "\n":
s = s + "\n"
s = s + record.exc_text
return s
#
# The default formatter to use when no other is specified
#
_defaultFormatter = Formatter()
class BufferingFormatter:
"""
A formatter suitable for formatting a number of records.
"""
def __init__(self, linefmt=None):
"""
Optionally specify a formatter which will be used to format each
individual record.
"""
if linefmt:
self.linefmt = linefmt
else:
self.linefmt = _defaultFormatter
def formatHeader(self, records):
"""
Return the header string for the specified records.
"""
return ""
def formatFooter(self, records):
"""
Return the footer string for the specified records.
"""
return ""
def format(self, records):
"""
Format the specified records and return the result as a string.
"""
rv = ""
if len(records) > 0:
rv = rv + self.formatHeader(records)
for record in records:
rv = rv + self.linefmt.format(record)
rv = rv + self.formatFooter(records)
return rv
#---------------------------------------------------------------------------
# Filter classes and functions
#---------------------------------------------------------------------------
class Filter:
"""
Filter instances are used to perform arbitrary filtering of LogRecords.
Loggers and Handlers can optionally use Filter instances to filter
records as desired. The base filter class only allows events which are
below a certain point in the logger hierarchy. For example, a filter
initialized with "A.B" will allow events logged by loggers "A.B",
"A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
initialized with the empty string, all events are passed.
"""
def __init__(self, name=''):
"""
Initialize a filter.
Initialize with the name of the logger which, together with its
children, will have its events allowed through the filter. If no
name is specified, allow every event.
"""
self.name = name
self.nlen = len(name)
def filter(self, record):
"""
Determine if the specified record is to be logged.
Is the specified record to be logged? Returns 0 for no, nonzero for
yes. If deemed appropriate, the record may be modified in-place.
"""
if self.nlen == 0:
return 1
elif self.name == record.name:
return 1
elif string.find(record.name, self.name, 0, self.nlen) != 0:
return 0
return (record.name[self.nlen] == ".")
class Filterer:
"""
A base class for loggers and handlers which allows them to share
common code.
"""
def __init__(self):
"""
Initialize the list of filters to be an empty list.
"""
self.filters = []
def addFilter(self, filter):
"""
Add the specified filter to this handler.
"""
if not (filter in self.filters):
self.filters.append(filter)
def removeFilter(self, filter):
"""
Remove the specified filter from this handler.
"""
if filter in self.filters:
self.filters.remove(filter)
def filter(self, record):
"""
Determine if a record is loggable by consulting all the filters.
The default is to allow the record to be logged; any filter can veto
this and the record is then dropped. Returns a zero value if a record
is to be dropped, else non-zero.
"""
rv = 1
for f in self.filters:
if not f.filter(record):
rv = 0
break
return rv
#---------------------------------------------------------------------------
# Handler classes and functions
#---------------------------------------------------------------------------
_handlers = {} #repository of handlers (for flushing when shutdown called)
class Handler(Filterer):
"""
Handler instances dispatch logging events to specific destinations.
The base handler class. Acts as a placeholder which defines the Handler
interface. Handlers can optionally use Formatter instances to format
records as desired. By default, no formatter is specified; in this case,
the 'raw' message as determined by record.message is logged.
"""
def __init__(self, level=NOTSET):
"""
Initializes the instance - basically setting the formatter to None
and the filter list to empty.
"""
Filterer.__init__(self)
self.level = level
self.formatter = None
#get the module data lock, as we're updating a shared structure.
_acquireLock()
try: #unlikely to raise an exception, but you never know...
_handlers[self] = 1
finally:
_releaseLock()
self.createLock()
def createLock(self):
"""
Acquire a thread lock for serializing access to the underlying I/O.
"""
if thread:
self.lock = thread.allocate_lock()
else:
self.lock = None
def acquire(self):
"""
Acquire the I/O thread lock.
"""
if self.lock:
self.lock.acquire()
def release(self):
"""
Release the I/O thread lock.
"""
if self.lock:
self.lock.release()
def setLevel(self, level):
"""
Set the logging level of this handler.
"""
self.level = level
def format(self, record):
"""
Format the specified record.
If a formatter is set, use it. Otherwise, use the default formatter
for the module.
"""
if self.formatter:
fmt = self.formatter
else:
fmt = _defaultFormatter
return fmt.format(record)
def emit(self, record):
"""
Do whatever it takes to actually log the specified logging record.
This version is intended to be implemented by subclasses and so
raises a NotImplementedError.
"""
raise NotImplementedError, 'emit must be implemented '\
'by Handler subclasses'
def handle(self, record):
"""
Conditionally emit the specified logging record.
Emission depends on filters which may have been added to the handler.
Wrap the actual emission of the record with acquisition/release of
the I/O thread lock. Returns whether the filter passed the record for
emission.
"""
rv = self.filter(record)
if rv:
self.acquire()
try:
self.emit(record)
finally:
self.release()
return rv
def setFormatter(self, fmt):
"""
Set the formatter for this handler.
"""
self.formatter = fmt
def flush(self):
"""
Ensure all logging output has been flushed.
This version does nothing and is intended to be implemented by
subclasses.
"""
pass
def close(self):
"""
Tidy up any resources used by the handler.
This version does removes the handler from an internal list
of handlers which is closed when shutdown() is called. Subclasses
should ensure that this gets called from overridden close()
methods.
"""
#get the module data lock, as we're updating a shared structure.
_acquireLock()
try: #unlikely to raise an exception, but you never know...
del _handlers[self]
finally:
_releaseLock()
def handleError(self, record):
"""
Handle errors which occur during an emit() call.
This method should be called from handlers when an exception is
encountered during an emit() call. If raiseExceptions is false,
exceptions get silently ignored. This is what is mostly wanted
for a logging system - most users will not care about errors in
the logging system, they are more interested in application errors.
You could, however, replace this with a custom handler if you wish.
The record which was being processed is passed in to this method.
"""
if raiseExceptions:
import traceback
ei = sys.exc_info()
traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
del ei
class StreamHandler(Handler):
"""
A handler class which writes logging records, appropriately formatted,
to a stream. Note that this class does not close the stream, as
sys.stdout or sys.stderr may be used.
"""
def __init__(self, strm=None):
"""
Initialize the handler.
If strm is not specified, sys.stderr is used.
"""
Handler.__init__(self)
if not strm:
strm = sys.stderr
self.stream = strm
self.formatter = None
def flush(self):
"""
Flushes the stream.
"""
self.stream.flush()
def emit(self, record):
"""
Emit a record.
If a formatter is specified, it is used to format the record.
The record is then written to the stream with a trailing newline
[N.B. this may be removed depending on feedback]. If exception
information is present, it is formatted using
traceback.print_exception and appended to the stream.
"""
try:
msg = self.format(record)
fs = "%s\n"
if not hasattr(types, "UnicodeType"): #if no unicode support...
self.stream.write(fs % msg)
else:
try:
self.stream.write(fs % msg)
except UnicodeError:
self.stream.write(fs % msg.encode("UTF-8"))
self.flush()
except:
self.handleError(record)
class FileHandler(StreamHandler):
"""
A handler class which writes formatted logging records to disk files.
"""
def __init__(self, filename, mode="a"):
"""
Open the specified file and use it as the stream for logging.
"""
StreamHandler.__init__(self, open(filename, mode))
#keep the absolute path, otherwise derived classes which use this
#may come a cropper when the current directory changes
self.baseFilename = os.path.abspath(filename)
self.mode = mode
def close(self):
"""
Closes the stream.
"""
self.flush()
self.stream.close()
StreamHandler.close(self)
#---------------------------------------------------------------------------
# Manager classes and functions
#---------------------------------------------------------------------------
class PlaceHolder:
"""
PlaceHolder instances are used in the Manager logger hierarchy to take
the place of nodes for which no loggers have been defined. This class is
intended for internal use only and not as part of the public API.
"""
def __init__(self, alogger):
"""
Initialize with the specified logger being a child of this placeholder.
"""
self.loggers = [alogger]
def append(self, alogger):
"""
Add the specified logger as a child of this placeholder.
"""
if alogger not in self.loggers:
self.loggers.append(alogger)
#
# Determine which class to use when instantiating loggers.
#
_loggerClass = None
def setLoggerClass(klass):
"""
Set the class to be used when instantiating a logger. The class should
define __init__() such that only a name argument is required, and the
__init__() should call Logger.__init__()
"""
if klass != Logger:
if not issubclass(klass, Logger):
raise TypeError, "logger not derived from logging.Logger: " + \
klass.__name__
global _loggerClass
_loggerClass = klass
def getLoggerClass():
"""
Return the class to be used when instantiating a logger.
"""
return _loggerClass
class Manager:
"""
There is [under normal circumstances] just one Manager instance, which
holds the hierarchy of loggers.
"""
def __init__(self, rootnode):
"""
Initialize the manager with the root node of the logger hierarchy.
"""
self.root = rootnode
self.disable = 0
self.emittedNoHandlerWarning = 0
self.loggerDict = {}
def getLogger(self, name):
"""
Get a logger with the specified name (channel name), creating it
if it doesn't yet exist. This name is a dot-separated hierarchical
name, such as "a", "a.b", "a.b.c" or similar.
If a PlaceHolder existed for the specified name [i.e. the logger
didn't exist but a child of it did], replace it with the created
logger and fix up the parent/child references which pointed to the
placeholder to now point to the logger.
"""
rv = None
_acquireLock()
try:
if self.loggerDict.has_key(name):
rv = self.loggerDict[name]
if isinstance(rv, PlaceHolder):
ph = rv
rv = _loggerClass(name)
rv.manager = self
self.loggerDict[name] = rv
self._fixupChildren(ph, rv)
self._fixupParents(rv)
else:
rv = _loggerClass(name)
rv.manager = self
self.loggerDict[name] = rv
self._fixupParents(rv)
finally:
_releaseLock()
return rv
def _fixupParents(self, alogger):
"""
Ensure that there are either loggers or placeholders all the way
from the specified logger to the root of the logger hierarchy.
"""
name = alogger.name
i = string.rfind(name, ".")
rv = None
while (i > 0) and not rv:
substr = name[:i]
if not self.loggerDict.has_key(substr):
self.loggerDict[substr] = PlaceHolder(alogger)
else:
obj = self.loggerDict[substr]
if isinstance(obj, Logger):
rv = obj
else:
assert isinstance(obj, PlaceHolder)
obj.append(alogger)
i = string.rfind(name, ".", 0, i - 1)
if not rv:
rv = self.root
alogger.parent = rv
def _fixupChildren(self, ph, alogger):
"""
Ensure that children of the placeholder ph are connected to the
specified logger.
"""
for c in ph.loggers:
if string.find(c.parent.name, alogger.name) <> 0:
alogger.parent = c.parent
c.parent = alogger
#---------------------------------------------------------------------------
# Logger classes and functions
#---------------------------------------------------------------------------
class Logger(Filterer):
"""
Instances of the Logger class represent a single logging channel. A
"logging channel" indicates an area of an application. Exactly how an
"area" is defined is up to the application developer. Since an
application can have any number of areas, logging channels are identified
by a unique string. Application areas can be nested (e.g. an area
of "input processing" might include sub-areas "read CSV files", "read
XLS files" and "read Gnumeric files"). To cater for this natural nesting,
channel names are organized into a namespace hierarchy where levels are
separated by periods, much like the Java or Python package namespace. So
in the instance given above, channel names might be "input" for the upper
level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels.
There is no arbitrary limit to the depth of nesting.
"""
def __init__(self, name, level=NOTSET):
"""
Initialize the logger with a name and an optional level.
"""
Filterer.__init__(self)
self.name = name
self.level = level
self.parent = None
self.propagate = 1
self.handlers = []
self.disabled = 0
def setLevel(self, level):
"""
Set the logging level of this logger.
"""
self.level = level
def debug(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'DEBUG'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
"""
if self.manager.disable >= DEBUG:
return
if DEBUG >= self.getEffectiveLevel():
apply(self._log, (DEBUG, msg, args), kwargs)
def info(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'INFO'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.info("Houston, we have a %s", "interesting problem", exc_info=1)
"""
if self.manager.disable >= INFO:
return
if INFO >= self.getEffectiveLevel():
apply(self._log, (INFO, msg, args), kwargs)
def warning(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'WARNING'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)
"""
if self.manager.disable >= WARNING:
return
if self.isEnabledFor(WARNING):
apply(self._log, (WARNING, msg, args), kwargs)
warn = warning
def error(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'ERROR'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.error("Houston, we have a %s", "major problem", exc_info=1)
"""
if self.manager.disable >= ERROR:
return
if self.isEnabledFor(ERROR):
apply(self._log, (ERROR, msg, args), kwargs)
def exception(self, msg, *args):
"""
Convenience method for logging an ERROR with exception information.
"""
apply(self.error, (msg,) + args, {'exc_info': 1})
def critical(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'CRITICAL'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.critical("Houston, we have a %s", "major disaster", exc_info=1)
"""
if self.manager.disable >= CRITICAL:
return
if CRITICAL >= self.getEffectiveLevel():
apply(self._log, (CRITICAL, msg, args), kwargs)
fatal = critical
def log(self, level, msg, *args, **kwargs):
"""
Log 'msg % args' with the integer severity 'level'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
"""
if type(level) != types.IntType:
if raiseExceptions:
raise TypeError, "level must be an integer"
else:
return
if self.manager.disable >= level:
return
if self.isEnabledFor(level):
apply(self._log, (level, msg, args), kwargs)
def findCaller(self):
"""
Find the stack frame of the caller so that we can note the source
file name and line number.
"""
f = sys._getframe(1)
while 1:
co = f.f_code
filename = os.path.normcase(co.co_filename)
if filename == _srcfile:
f = f.f_back
continue
return filename, f.f_lineno
def makeRecord(self, name, level, fn, lno, msg, args, exc_info):
"""
A factory method which can be overridden in subclasses to create
specialized LogRecords.
"""
return LogRecord(name, level, fn, lno, msg, args, exc_info)
def _log(self, level, msg, args, exc_info=None):
"""
Low-level logging routine which creates a LogRecord and then calls
all the handlers of this logger to handle the record.
"""
if _srcfile:
fn, lno = self.findCaller()
else:
fn, lno = "<unknown file>", 0
if exc_info:
if type(exc_info) != types.TupleType:
exc_info = sys.exc_info()
record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info)
self.handle(record)
def handle(self, record):
"""
Call the handlers for the specified record.
This method is used for unpickled records received from a socket, as
well as those created locally. Logger-level filtering is applied.
"""
if (not self.disabled) and self.filter(record):
self.callHandlers(record)
def addHandler(self, hdlr):
"""
Add the specified handler to this logger.
"""
if not (hdlr in self.handlers):
self.handlers.append(hdlr)
def removeHandler(self, hdlr):
"""
Remove the specified handler from this logger.
"""
if hdlr in self.handlers:
#hdlr.close()
self.handlers.remove(hdlr)
def callHandlers(self, record):
"""
Pass a record to all relevant handlers.
Loop through all handlers for this logger and its parents in the
logger hierarchy. If no handler was found, output a one-off error
message to sys.stderr. Stop searching up the hierarchy whenever a
logger with the "propagate" attribute set to zero is found - that
will be the last logger whose handlers are called.
"""
c = self
found = 0
while c:
for hdlr in c.handlers:
found = found + 1
if record.levelno >= hdlr.level:
hdlr.handle(record)
if not c.propagate:
c = None #break out
else:
c = c.parent
if (found == 0) and not self.manager.emittedNoHandlerWarning:
sys.stderr.write("No handlers could be found for logger"
" \"%s\"\n" % self.name)
self.manager.emittedNoHandlerWarning = 1
def getEffectiveLevel(self):
"""
Get the effective level for this logger.
Loop through this logger and its parents in the logger hierarchy,
looking for a non-zero logging level. Return the first one found.
"""
logger = self
while logger:
if logger.level:
return logger.level
logger = logger.parent
return NOTSET
def isEnabledFor(self, level):
"""
Is this logger enabled for level 'level'?
"""
if self.manager.disable >= level:
return 0
return level >= self.getEffectiveLevel()
class RootLogger(Logger):
"""
A root logger is not that different to any other logger, except that
it must have a logging level and there is only one instance of it in
the hierarchy.
"""
def __init__(self, level):
"""
Initialize the logger with the name "root".
"""
Logger.__init__(self, "root", level)
_loggerClass = Logger
root = RootLogger(WARNING)
Logger.root = root
Logger.manager = Manager(Logger.root)
#---------------------------------------------------------------------------
# Configuration classes and functions
#---------------------------------------------------------------------------
BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s"
def basicConfig(**kwargs):
"""
Do basic configuration for the logging system.
This function does nothing if the root logger already has handlers
configured. It is a convenience method intended for use by simple scripts
to do one-shot configuration of the logging package.
The default behaviour is to create a StreamHandler which writes to
sys.stderr, set a formatter using the BASIC_FORMAT format string, and
add the handler to the root logger.
A number of optional keyword arguments may be specified, which can alter
the default behaviour.
filename Specifies that a FileHandler be created, using the specified
filename, rather than a StreamHandler.
filemode Specifies the mode to open the file, if filename is specified
(if filemode is unspecified, it defaults to "a").
format Use the specified format string for the handler.
datefmt Use the specified date/time format.
level Set the root logger level to the specified level.
stream Use the specified stream to initialize the StreamHandler. Note
that this argument is incompatible with 'filename' - if both
are present, 'stream' is ignored.
Note that you could specify a stream created using open(filename, mode)
rather than passing the filename and mode in. However, it should be
remembered that StreamHandler does not close its stream (since it may be
using sys.stdout or sys.stderr), whereas FileHandler closes its stream
when the handler is closed.
"""
if len(root.handlers) == 0:
filename = kwargs.get("filename")
if filename:
mode = kwargs.get("filemode", "a")
hdlr = FileHandler(filename, mode)
else:
stream = kwargs.get("stream")
hdlr = StreamHandler(stream)
fs = kwargs.get("format", BASIC_FORMAT)
dfs = kwargs.get("datefmt", None)
fmt = Formatter(fs, dfs)
hdlr.setFormatter(fmt)
root.addHandler(hdlr)
level = kwargs.get("level")
if level:
root.setLevel(level)
#---------------------------------------------------------------------------
# Utility functions at module level.
# Basically delegate everything to the root logger.
#---------------------------------------------------------------------------
def getLogger(name=None):
"""
Return a logger with the specified name, creating it if necessary.
If no name is specified, return the root logger.
"""
if name:
return Logger.manager.getLogger(name)
else:
return root
#def getRootLogger():
# """
# Return the root logger.
#
# Note that getLogger('') now does the same thing, so this function is
# deprecated and may disappear in the future.
# """
# return root
def critical(msg, *args, **kwargs):
"""
Log a message with severity 'CRITICAL' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.critical, (msg,)+args, kwargs)
fatal = critical
def error(msg, *args, **kwargs):
"""
Log a message with severity 'ERROR' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.error, (msg,)+args, kwargs)
def exception(msg, *args):
"""
Log a message with severity 'ERROR' on the root logger,
with exception information.
"""
apply(error, (msg,)+args, {'exc_info': 1})
def warning(msg, *args, **kwargs):
"""
Log a message with severity 'WARNING' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.warning, (msg,)+args, kwargs)
warn = warning
def info(msg, *args, **kwargs):
"""
Log a message with severity 'INFO' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.info, (msg,)+args, kwargs)
def debug(msg, *args, **kwargs):
"""
Log a message with severity 'DEBUG' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.debug, (msg,)+args, kwargs)
def log(level, msg, *args, **kwargs):
"""
Log 'msg % args' with the integer severity 'level' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.log, (level, msg)+args, kwargs)
def disable(level):
"""
Disable all logging calls less severe than 'level'.
"""
root.manager.disable = level
def shutdown():
"""
Perform any cleanup actions in the logging system (e.g. flushing
buffers).
Should be called at application exit.
"""
for h in _handlers.keys():
#errors might occur, for example, if files are locked
#we just ignore them
try:
h.flush()
h.close()
except:
pass
#Let's try and shutdown automatically on application exit...
try:
import atexit
atexit.register(shutdown)
except ImportError: # for Python versions < 2.0
def exithook(status, old_exit=sys.exit):
try:
shutdown()
finally:
old_exit(status)
sys.exit = exithook
| Python |
#! /usr/bin/env python
"""Keywords (from "graminit.c")
This file is automatically generated; please don't muck it up!
To update the symbols in this file, 'cd' to the top directory of
the python source tree after building the interpreter and run:
python Lib/keyword.py
"""
__all__ = ["iskeyword", "kwlist"]
kwlist = [
#--start keywords--
'and',
'assert',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'exec',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'not',
'or',
'pass',
'print',
'raise',
'return',
'try',
'while',
'yield',
#--end keywords--
]
iskeyword = frozenset(kwlist).__contains__
def main():
import sys, re
args = sys.argv[1:]
iptfile = args and args[0] or "Python/graminit.c"
if len(args) > 1: optfile = args[1]
else: optfile = "Lib/keyword.py"
# scan the source file for keywords
fp = open(iptfile)
strprog = re.compile('"([^"]+)"')
lines = []
while 1:
line = fp.readline()
if not line: break
if '{1, "' in line:
match = strprog.search(line)
if match:
lines.append(" '" + match.group(1) + "',\n")
fp.close()
lines.sort()
# load the output skeleton from the target
fp = open(optfile)
format = fp.readlines()
fp.close()
# insert the lines of keywords
try:
start = format.index("#--start keywords--\n") + 1
end = format.index("#--end keywords--\n")
format[start:end] = lines
except ValueError:
sys.stderr.write("target does not contain format markers\n")
sys.exit(1)
# write the output file
fp = open(optfile, 'w')
fp.write(''.join(format))
fp.close()
if __name__ == "__main__":
main()
| Python |
"""A parser for SGML, using the derived class as a static DTD."""
# XXX This only supports those SGML features used by HTML.
# XXX There should be a way to distinguish between PCDATA (parsed
# character data -- the normal case), RCDATA (replaceable character
# data -- only char and entity references and end tags are special)
# and CDATA (character data -- only end tags are special). RCDATA is
# not supported at all.
import markupbase
import re
__all__ = ["SGMLParser", "SGMLParseError"]
# Regular expressions used for parsing
interesting = re.compile('[&<]')
incomplete = re.compile('&([a-zA-Z][a-zA-Z0-9]*|#[0-9]*)?|'
'<([a-zA-Z][^<>]*|'
'/([a-zA-Z][^<>]*)?|'
'![^<>]*)?')
entityref = re.compile('&([a-zA-Z][-.a-zA-Z0-9]*)[^a-zA-Z0-9]')
charref = re.compile('&#([0-9]+)[^0-9]')
starttagopen = re.compile('<[>a-zA-Z]')
shorttagopen = re.compile('<[a-zA-Z][-.a-zA-Z0-9]*/')
shorttag = re.compile('<([a-zA-Z][-.a-zA-Z0-9]*)/([^/]*)/')
piclose = re.compile('>')
endbracket = re.compile('[<>]')
tagfind = re.compile('[a-zA-Z][-_.a-zA-Z0-9]*')
attrfind = re.compile(
r'\s*([a-zA-Z_][-:.a-zA-Z_0-9]*)(\s*=\s*'
r'(\'[^\']*\'|"[^"]*"|[-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~\'"@]*))?')
class SGMLParseError(RuntimeError):
"""Exception raised for all parse errors."""
pass
# SGML parser base class -- find tags and call handler functions.
# Usage: p = SGMLParser(); p.feed(data); ...; p.close().
# The dtd is defined by deriving a class which defines methods
# with special names to handle tags: start_foo and end_foo to handle
# <foo> and </foo>, respectively, or do_foo to handle <foo> by itself.
# (Tags are converted to lower case for this purpose.) The data
# between tags is passed to the parser by calling self.handle_data()
# with some data as argument (the data may be split up in arbitrary
# chunks). Entity references are passed by calling
# self.handle_entityref() with the entity reference as argument.
class SGMLParser(markupbase.ParserBase):
def __init__(self, verbose=0):
"""Initialize and reset this instance."""
self.verbose = verbose
self.reset()
def reset(self):
"""Reset this instance. Loses all unprocessed data."""
self.__starttag_text = None
self.rawdata = ''
self.stack = []
self.lasttag = '???'
self.nomoretags = 0
self.literal = 0
markupbase.ParserBase.reset(self)
def setnomoretags(self):
"""Enter literal mode (CDATA) till EOF.
Intended for derived classes only.
"""
self.nomoretags = self.literal = 1
def setliteral(self, *args):
"""Enter literal mode (CDATA).
Intended for derived classes only.
"""
self.literal = 1
def feed(self, data):
"""Feed some data to the parser.
Call this as often as you want, with as little or as much text
as you want (may include '\n'). (This just saves the text,
all the processing is done by goahead().)
"""
self.rawdata = self.rawdata + data
self.goahead(0)
def close(self):
"""Handle the remaining data."""
self.goahead(1)
def error(self, message):
raise SGMLParseError(message)
# Internal -- handle data as far as reasonable. May leave state
# and data to be processed by a subsequent call. If 'end' is
# true, force handling all data as if followed by EOF marker.
def goahead(self, end):
rawdata = self.rawdata
i = 0
n = len(rawdata)
while i < n:
if self.nomoretags:
self.handle_data(rawdata[i:n])
i = n
break
match = interesting.search(rawdata, i)
if match: j = match.start()
else: j = n
if i < j:
self.handle_data(rawdata[i:j])
i = j
if i == n: break
if rawdata[i] == '<':
if starttagopen.match(rawdata, i):
if self.literal:
self.handle_data(rawdata[i])
i = i+1
continue
k = self.parse_starttag(i)
if k < 0: break
i = k
continue
if rawdata.startswith("</", i):
k = self.parse_endtag(i)
if k < 0: break
i = k
self.literal = 0
continue
if self.literal:
if n > (i + 1):
self.handle_data("<")
i = i+1
else:
# incomplete
break
continue
if rawdata.startswith("<!--", i):
# Strictly speaking, a comment is --.*--
# within a declaration tag <!...>.
# This should be removed,
# and comments handled only in parse_declaration.
k = self.parse_comment(i)
if k < 0: break
i = k
continue
if rawdata.startswith("<?", i):
k = self.parse_pi(i)
if k < 0: break
i = i+k
continue
if rawdata.startswith("<!", i):
# This is some sort of declaration; in "HTML as
# deployed," this should only be the document type
# declaration ("<!DOCTYPE html...>").
k = self.parse_declaration(i)
if k < 0: break
i = k
continue
elif rawdata[i] == '&':
if self.literal:
self.handle_data(rawdata[i])
i = i+1
continue
match = charref.match(rawdata, i)
if match:
name = match.group(1)
self.handle_charref(name)
i = match.end(0)
if rawdata[i-1] != ';': i = i-1
continue
match = entityref.match(rawdata, i)
if match:
name = match.group(1)
self.handle_entityref(name)
i = match.end(0)
if rawdata[i-1] != ';': i = i-1
continue
else:
self.error('neither < nor & ??')
# We get here only if incomplete matches but
# nothing else
match = incomplete.match(rawdata, i)
if not match:
self.handle_data(rawdata[i])
i = i+1
continue
j = match.end(0)
if j == n:
break # Really incomplete
self.handle_data(rawdata[i:j])
i = j
# end while
if end and i < n:
self.handle_data(rawdata[i:n])
i = n
self.rawdata = rawdata[i:]
# XXX if end: check for empty stack
# Extensions for the DOCTYPE scanner:
_decl_otherchars = '='
# Internal -- parse processing instr, return length or -1 if not terminated
def parse_pi(self, i):
rawdata = self.rawdata
if rawdata[i:i+2] != '<?':
self.error('unexpected call to parse_pi()')
match = piclose.search(rawdata, i+2)
if not match:
return -1
j = match.start(0)
self.handle_pi(rawdata[i+2: j])
j = match.end(0)
return j-i
def get_starttag_text(self):
return self.__starttag_text
# Internal -- handle starttag, return length or -1 if not terminated
def parse_starttag(self, i):
self.__starttag_text = None
start_pos = i
rawdata = self.rawdata
if shorttagopen.match(rawdata, i):
# SGML shorthand: <tag/data/ == <tag>data</tag>
# XXX Can data contain &... (entity or char refs)?
# XXX Can data contain < or > (tag characters)?
# XXX Can there be whitespace before the first /?
match = shorttag.match(rawdata, i)
if not match:
return -1
tag, data = match.group(1, 2)
self.__starttag_text = '<%s/' % tag
tag = tag.lower()
k = match.end(0)
self.finish_shorttag(tag, data)
self.__starttag_text = rawdata[start_pos:match.end(1) + 1]
return k
# XXX The following should skip matching quotes (' or ")
match = endbracket.search(rawdata, i+1)
if not match:
return -1
j = match.start(0)
# Now parse the data between i+1 and j into a tag and attrs
attrs = []
if rawdata[i:i+2] == '<>':
# SGML shorthand: <> == <last open tag seen>
k = j
tag = self.lasttag
else:
match = tagfind.match(rawdata, i+1)
if not match:
self.error('unexpected call to parse_starttag')
k = match.end(0)
tag = rawdata[i+1:k].lower()
self.lasttag = tag
while k < j:
match = attrfind.match(rawdata, k)
if not match: break
attrname, rest, attrvalue = match.group(1, 2, 3)
if not rest:
attrvalue = attrname
elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
attrvalue[:1] == '"' == attrvalue[-1:]:
attrvalue = attrvalue[1:-1]
attrs.append((attrname.lower(), attrvalue))
k = match.end(0)
if rawdata[j] == '>':
j = j+1
self.__starttag_text = rawdata[start_pos:j]
self.finish_starttag(tag, attrs)
return j
# Internal -- parse endtag
def parse_endtag(self, i):
rawdata = self.rawdata
match = endbracket.search(rawdata, i+1)
if not match:
return -1
j = match.start(0)
tag = rawdata[i+2:j].strip().lower()
if rawdata[j] == '>':
j = j+1
self.finish_endtag(tag)
return j
# Internal -- finish parsing of <tag/data/ (same as <tag>data</tag>)
def finish_shorttag(self, tag, data):
self.finish_starttag(tag, [])
self.handle_data(data)
self.finish_endtag(tag)
# Internal -- finish processing of start tag
# Return -1 for unknown tag, 0 for open-only tag, 1 for balanced tag
def finish_starttag(self, tag, attrs):
try:
method = getattr(self, 'start_' + tag)
except AttributeError:
try:
method = getattr(self, 'do_' + tag)
except AttributeError:
self.unknown_starttag(tag, attrs)
return -1
else:
self.handle_starttag(tag, method, attrs)
return 0
else:
self.stack.append(tag)
self.handle_starttag(tag, method, attrs)
return 1
# Internal -- finish processing of end tag
def finish_endtag(self, tag):
if not tag:
found = len(self.stack) - 1
if found < 0:
self.unknown_endtag(tag)
return
else:
if tag not in self.stack:
try:
method = getattr(self, 'end_' + tag)
except AttributeError:
self.unknown_endtag(tag)
else:
self.report_unbalanced(tag)
return
found = len(self.stack)
for i in range(found):
if self.stack[i] == tag: found = i
while len(self.stack) > found:
tag = self.stack[-1]
try:
method = getattr(self, 'end_' + tag)
except AttributeError:
method = None
if method:
self.handle_endtag(tag, method)
else:
self.unknown_endtag(tag)
del self.stack[-1]
# Overridable -- handle start tag
def handle_starttag(self, tag, method, attrs):
method(attrs)
# Overridable -- handle end tag
def handle_endtag(self, tag, method):
method()
# Example -- report an unbalanced </...> tag.
def report_unbalanced(self, tag):
if self.verbose:
print '*** Unbalanced </' + tag + '>'
print '*** Stack:', self.stack
def handle_charref(self, name):
"""Handle character reference, no need to override."""
try:
n = int(name)
except ValueError:
self.unknown_charref(name)
return
if not 0 <= n <= 255:
self.unknown_charref(name)
return
self.handle_data(chr(n))
# Definition of entities -- derived classes may override
entitydefs = \
{'lt': '<', 'gt': '>', 'amp': '&', 'quot': '"', 'apos': '\''}
def handle_entityref(self, name):
"""Handle entity references.
There should be no need to override this method; it can be
tailored by setting up the self.entitydefs mapping appropriately.
"""
table = self.entitydefs
if name in table:
self.handle_data(table[name])
else:
self.unknown_entityref(name)
return
# Example -- handle data, should be overridden
def handle_data(self, data):
pass
# Example -- handle comment, could be overridden
def handle_comment(self, data):
pass
# Example -- handle declaration, could be overridden
def handle_decl(self, decl):
pass
# Example -- handle processing instruction, could be overridden
def handle_pi(self, data):
pass
# To be overridden -- handlers for unknown objects
def unknown_starttag(self, tag, attrs): pass
def unknown_endtag(self, tag): pass
def unknown_charref(self, ref): pass
def unknown_entityref(self, ref): pass
class TestSGMLParser(SGMLParser):
def __init__(self, verbose=0):
self.testdata = ""
SGMLParser.__init__(self, verbose)
def handle_data(self, data):
self.testdata = self.testdata + data
if len(repr(self.testdata)) >= 70:
self.flush()
def flush(self):
data = self.testdata
if data:
self.testdata = ""
print 'data:', repr(data)
def handle_comment(self, data):
self.flush()
r = repr(data)
if len(r) > 68:
r = r[:32] + '...' + r[-32:]
print 'comment:', r
def unknown_starttag(self, tag, attrs):
self.flush()
if not attrs:
print 'start tag: <' + tag + '>'
else:
print 'start tag: <' + tag,
for name, value in attrs:
print name + '=' + '"' + value + '"',
print '>'
def unknown_endtag(self, tag):
self.flush()
print 'end tag: </' + tag + '>'
def unknown_entityref(self, ref):
self.flush()
print '*** unknown entity ref: &' + ref + ';'
def unknown_charref(self, ref):
self.flush()
print '*** unknown char ref: &#' + ref + ';'
def unknown_decl(self, data):
self.flush()
print '*** unknown decl: [' + data + ']'
def close(self):
SGMLParser.close(self)
self.flush()
def test(args = None):
import sys
if args is None:
args = sys.argv[1:]
if args and args[0] == '-s':
args = args[1:]
klass = SGMLParser
else:
klass = TestSGMLParser
if args:
file = args[0]
else:
file = 'test.html'
if file == '-':
f = sys.stdin
else:
try:
f = open(file, 'r')
except IOError, msg:
print file, ":", msg
sys.exit(1)
data = f.read()
if f is not sys.stdin:
f.close()
x = klass()
for c in data:
x.feed(c)
x.close()
if __name__ == '__main__':
test()
| Python |
"""Constants for interpreting the results of os.statvfs() and os.fstatvfs()."""
# Indices for statvfs struct members in the tuple returned by
# os.statvfs() and os.fstatvfs().
F_BSIZE = 0 # Preferred file system block size
F_FRSIZE = 1 # Fundamental file system block size
F_BLOCKS = 2 # Total number of file system blocks (FRSIZE)
F_BFREE = 3 # Total number of free blocks
F_BAVAIL = 4 # Free blocks available to non-superuser
F_FILES = 5 # Total number of file nodes
F_FFREE = 6 # Total number of free file nodes
F_FAVAIL = 7 # Free nodes available to non-superuser
F_FLAG = 8 # Flags (see your local statvfs man page)
F_NAMEMAX = 9 # Maximum file name length
| Python |
"""Generic (shallow and deep) copying operations.
Interface summary:
import copy
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
For module specific errors, copy.Error is raised.
The difference between shallow and deep copying is only relevant for
compound objects (objects that contain other objects, like lists or
class instances).
- A shallow copy constructs a new compound object and then (to the
extent possible) inserts *the same objects* into in that the
original contains.
- A deep copy constructs a new compound object and then, recursively,
inserts *copies* into it of the objects found in the original.
Two problems often exist with deep copy operations that don't exist
with shallow copy operations:
a) recursive objects (compound objects that, directly or indirectly,
contain a reference to themselves) may cause a recursive loop
b) because deep copy copies *everything* it may copy too much, e.g.
administrative data structures that should be shared even between
copies
Python's deep copy operation avoids these problems by:
a) keeping a table of objects already copied during the current
copying pass
b) letting user-defined classes override the copying operation or the
set of components copied
This version does not copy types like module, class, function, method,
nor stack trace, stack frame, nor file, socket, window, nor array, nor
any similar types.
Classes can use the same interfaces to control copying that they use
to control pickling: they can define methods called __getinitargs__(),
__getstate__() and __setstate__(). See the documentation for module
"pickle" for information on these methods.
"""
import types
from copy_reg import dispatch_table
class Error(Exception):
pass
error = Error # backward compatibility
try:
from org.python.core import PyStringMap
except ImportError:
PyStringMap = None
__all__ = ["Error", "copy", "deepcopy"]
import inspect
def _getspecial(cls, name):
for basecls in inspect.getmro(cls):
try:
return basecls.__dict__[name]
except:
pass
else:
return None
def copy(x):
"""Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
cls = type(x)
copier = _copy_dispatch.get(cls)
if copier:
return copier(x)
copier = _getspecial(cls, "__copy__")
if copier:
return copier(x)
reductor = dispatch_table.get(cls)
if reductor:
rv = reductor(x)
else:
reductor = getattr(x, "__reduce_ex__", None)
if reductor:
rv = reductor(2)
else:
reductor = getattr(x, "__reduce__", None)
if reductor:
rv = reductor()
else:
copier = getattr(x, "__copy__", None)
if copier:
return copier()
raise Error("un(shallow)copyable object of type %s" % cls)
return _reconstruct(x, rv, 0)
_copy_dispatch = d = {}
def _copy_immutable(x):
return x
for t in (types.NoneType, int, long, float, bool, str, tuple,
frozenset, type, xrange, types.ClassType,
types.BuiltinFunctionType):
d[t] = _copy_immutable
for name in ("ComplexType", "UnicodeType", "CodeType"):
t = getattr(types, name, None)
if t is not None:
d[t] = _copy_immutable
def _copy_with_constructor(x):
return type(x)(x)
for t in (list, dict, set):
d[t] = _copy_with_constructor
def _copy_with_copy_method(x):
return x.copy()
if PyStringMap is not None:
d[PyStringMap] = _copy_with_copy_method
def _copy_inst(x):
if hasattr(x, '__copy__'):
return x.__copy__()
if hasattr(x, '__getinitargs__'):
args = x.__getinitargs__()
y = x.__class__(*args)
else:
y = _EmptyClass()
y.__class__ = x.__class__
if hasattr(x, '__getstate__'):
state = x.__getstate__()
else:
state = x.__dict__
if hasattr(y, '__setstate__'):
y.__setstate__(state)
else:
y.__dict__.update(state)
return y
d[types.InstanceType] = _copy_inst
del d
def deepcopy(x, memo=None, _nil=[]):
"""Deep copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
if memo is None:
memo = {}
d = id(x)
y = memo.get(d, _nil)
if y is not _nil:
return y
cls = type(x)
copier = _deepcopy_dispatch.get(cls)
if copier:
y = copier(x, memo)
else:
try:
issc = issubclass(cls, type)
except TypeError: # cls is not a class (old Boost; see SF #502085)
issc = 0
if issc:
y = _deepcopy_atomic(x, memo)
else:
copier = _getspecial(cls, "__deepcopy__")
if copier:
y = copier(x, memo)
else:
reductor = dispatch_table.get(cls)
if reductor:
rv = reductor(x)
else:
reductor = getattr(x, "__reduce_ex__", None)
if reductor:
rv = reductor(2)
else:
reductor = getattr(x, "__reduce__", None)
if reductor:
rv = reductor()
else:
copier = getattr(x, "__deepcopy__", None)
if copier:
return copier(memo)
raise Error(
"un(deep)copyable object of type %s" % cls)
y = _reconstruct(x, rv, 1, memo)
memo[d] = y
_keep_alive(x, memo) # Make sure x lives at least as long as d
return y
_deepcopy_dispatch = d = {}
def _deepcopy_atomic(x, memo):
return x
d[types.NoneType] = _deepcopy_atomic
d[types.IntType] = _deepcopy_atomic
d[types.LongType] = _deepcopy_atomic
d[types.FloatType] = _deepcopy_atomic
d[types.BooleanType] = _deepcopy_atomic
try:
d[types.ComplexType] = _deepcopy_atomic
except AttributeError:
pass
d[types.StringType] = _deepcopy_atomic
try:
d[types.UnicodeType] = _deepcopy_atomic
except AttributeError:
pass
try:
d[types.CodeType] = _deepcopy_atomic
except AttributeError:
pass
d[types.TypeType] = _deepcopy_atomic
d[types.XRangeType] = _deepcopy_atomic
d[types.ClassType] = _deepcopy_atomic
d[types.BuiltinFunctionType] = _deepcopy_atomic
def _deepcopy_list(x, memo):
y = []
memo[id(x)] = y
for a in x:
y.append(deepcopy(a, memo))
return y
d[types.ListType] = _deepcopy_list
def _deepcopy_tuple(x, memo):
y = []
for a in x:
y.append(deepcopy(a, memo))
d = id(x)
try:
return memo[d]
except KeyError:
pass
for i in range(len(x)):
if x[i] is not y[i]:
y = tuple(y)
break
else:
y = x
memo[d] = y
return y
d[types.TupleType] = _deepcopy_tuple
def _deepcopy_dict(x, memo):
y = {}
memo[id(x)] = y
for key, value in x.iteritems():
y[deepcopy(key, memo)] = deepcopy(value, memo)
return y
d[types.DictionaryType] = _deepcopy_dict
if PyStringMap is not None:
d[PyStringMap] = _deepcopy_dict
def _keep_alive(x, memo):
"""Keeps a reference to the object x in the memo.
Because we remember objects by their id, we have
to assure that possibly temporary objects are kept
alive by referencing them.
We store a reference at the id of the memo, which should
normally not be used unless someone tries to deepcopy
the memo itself...
"""
try:
memo[id(memo)].append(x)
except KeyError:
# aha, this is the first one :-)
memo[id(memo)]=[x]
def _deepcopy_inst(x, memo):
if hasattr(x, '__deepcopy__'):
return x.__deepcopy__(memo)
if hasattr(x, '__getinitargs__'):
args = x.__getinitargs__()
args = deepcopy(args, memo)
y = x.__class__(*args)
else:
y = _EmptyClass()
y.__class__ = x.__class__
memo[id(x)] = y
if hasattr(x, '__getstate__'):
state = x.__getstate__()
else:
state = x.__dict__
state = deepcopy(state, memo)
if hasattr(y, '__setstate__'):
y.__setstate__(state)
else:
y.__dict__.update(state)
return y
d[types.InstanceType] = _deepcopy_inst
def _reconstruct(x, info, deep, memo=None):
if isinstance(info, str):
return x
assert isinstance(info, tuple)
if memo is None:
memo = {}
n = len(info)
assert n in (2, 3, 4, 5)
callable, args = info[:2]
if n > 2:
state = info[2]
else:
state = {}
if n > 3:
listiter = info[3]
else:
listiter = None
if n > 4:
dictiter = info[4]
else:
dictiter = None
if deep:
args = deepcopy(args, memo)
y = callable(*args)
memo[id(x)] = y
if listiter is not None:
for item in listiter:
if deep:
item = deepcopy(item, memo)
y.append(item)
if dictiter is not None:
for key, value in dictiter:
if deep:
key = deepcopy(key, memo)
value = deepcopy(value, memo)
y[key] = value
if state:
if deep:
state = deepcopy(state, memo)
if hasattr(y, '__setstate__'):
y.__setstate__(state)
else:
if isinstance(state, tuple) and len(state) == 2:
state, slotstate = state
else:
slotstate = None
if state is not None:
y.__dict__.update(state)
if slotstate is not None:
for key, value in slotstate.iteritems():
setattr(y, key, value)
return y
del d
del types
# Helper for instance creation without calling __init__
class _EmptyClass:
pass
def _test():
l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'],
{'abc': 'ABC'}, (), [], {}]
l1 = copy(l)
print l1==l
l1 = map(copy, l)
print l1==l
l1 = deepcopy(l)
print l1==l
class C:
def __init__(self, arg=None):
self.a = 1
self.arg = arg
if __name__ == '__main__':
import sys
file = sys.argv[0]
else:
file = __file__
self.fp = open(file)
self.fp.close()
def __getstate__(self):
return {'a': self.a, 'arg': self.arg}
def __setstate__(self, state):
for key, value in state.iteritems():
setattr(self, key, value)
def __deepcopy__(self, memo=None):
new = self.__class__(deepcopy(self.arg, memo))
new.a = self.a
return new
c = C('argument sketch')
l.append(c)
l2 = copy(l)
print l == l2
print l
print l2
l2 = deepcopy(l)
print l == l2
print l
print l2
l.append({l[1]: l, 'xyz': l[2]})
l3 = copy(l)
import repr
print map(repr.repr, l)
print map(repr.repr, l1)
print map(repr.repr, l2)
print map(repr.repr, l3)
l3 = deepcopy(l)
import repr
print map(repr.repr, l)
print map(repr.repr, l1)
print map(repr.repr, l2)
print map(repr.repr, l3)
if __name__ == '__main__':
_test()
| Python |
#
# XML-RPC CLIENT LIBRARY
# $Id: xmlrpclib.py,v 1.36.2.1 2005/02/11 17:59:58 fdrake Exp $
#
# an XML-RPC client interface for Python.
#
# the marshalling and response parser code can also be used to
# implement XML-RPC servers.
#
# Notes:
# this version is designed to work with Python 2.1 or newer.
#
# History:
# 1999-01-14 fl Created
# 1999-01-15 fl Changed dateTime to use localtime
# 1999-01-16 fl Added Binary/base64 element, default to RPC2 service
# 1999-01-19 fl Fixed array data element (from Skip Montanaro)
# 1999-01-21 fl Fixed dateTime constructor, etc.
# 1999-02-02 fl Added fault handling, handle empty sequences, etc.
# 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro)
# 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8)
# 2000-11-28 fl Changed boolean to check the truth value of its argument
# 2001-02-24 fl Added encoding/Unicode/SafeTransport patches
# 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1)
# 2001-03-28 fl Make sure response tuple is a singleton
# 2001-03-29 fl Don't require empty params element (from Nicholas Riley)
# 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2)
# 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod)
# 2001-09-03 fl Allow Transport subclass to override getparser
# 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup)
# 2001-10-01 fl Remove containers from memo cache when done with them
# 2001-10-01 fl Use faster escape method (80% dumps speedup)
# 2001-10-02 fl More dumps microtuning
# 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
# 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
# 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
# 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
# 2002-03-17 fl Avoid buffered read when possible (from James Rucker)
# 2002-04-07 fl Added pythondoc comments
# 2002-04-16 fl Added __str__ methods to datetime/binary wrappers
# 2002-05-15 fl Added error constants (from Andrew Kuchling)
# 2002-06-27 fl Merged with Python CVS version
# 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
# 2003-01-22 sm Add support for the bool type
# 2003-02-27 gvr Remove apply calls
# 2003-04-24 sm Use cStringIO if available
# 2003-04-25 ak Add support for nil
# 2003-06-15 gn Add support for time.struct_time
# 2003-07-12 gp Correct marshalling of Faults
# 2003-10-31 mvl Add multicall support
# 2004-08-20 mvl Bump minimum supported Python version to 2.1
#
# Copyright (c) 1999-2002 by Secret Labs AB.
# Copyright (c) 1999-2002 by Fredrik Lundh.
#
# info@pythonware.com
# http://www.pythonware.com
#
# --------------------------------------------------------------------
# The XML-RPC client interface is
#
# Copyright (c) 1999-2002 by Secret Labs AB
# Copyright (c) 1999-2002 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# 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.
# --------------------------------------------------------------------
#
# things to look into some day:
# TODO: sort out True/False/boolean issues for Python 2.3
"""
An XML-RPC client interface for Python.
The marshalling and response parser code can also be used to
implement XML-RPC servers.
Exported exceptions:
Error Base class for client errors
ProtocolError Indicates an HTTP protocol error
ResponseError Indicates a broken response package
Fault Indicates an XML-RPC fault package
Exported classes:
ServerProxy Represents a logical connection to an XML-RPC server
MultiCall Executor of boxcared xmlrpc requests
Boolean boolean wrapper to generate a "boolean" XML-RPC value
DateTime dateTime wrapper for an ISO 8601 string or time tuple or
localtime integer value to generate a "dateTime.iso8601"
XML-RPC value
Binary binary data wrapper
SlowParser Slow but safe standard parser (based on xmllib)
Marshaller Generate an XML-RPC params chunk from a Python data structure
Unmarshaller Unmarshal an XML-RPC response from incoming XML event message
Transport Handles an HTTP transaction to an XML-RPC server
SafeTransport Handles an HTTPS transaction to an XML-RPC server
Exported constants:
True
False
Exported functions:
boolean Convert any Python value to an XML-RPC boolean
getparser Create instance of the fastest available parser & attach
to an unmarshalling object
dumps Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
loads Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
"""
import re, string, time, operator
from types import *
# --------------------------------------------------------------------
# Internal stuff
try:
unicode
except NameError:
unicode = None # unicode support not available
try:
_bool_is_builtin = False.__class__.__name__ == "bool"
except NameError:
_bool_is_builtin = 0
def _decode(data, encoding, is8bit=re.compile("[\x80-\xff]").search):
# decode non-ascii string (if possible)
if unicode and encoding and is8bit(data):
data = unicode(data, encoding)
return data
def escape(s, replace=string.replace):
s = replace(s, "&", "&")
s = replace(s, "<", "<")
return replace(s, ">", ">",)
if unicode:
def _stringify(string):
# convert to 7-bit ascii if possible
try:
return string.encode("ascii")
except UnicodeError:
return string
else:
def _stringify(string):
return string
__version__ = "1.0.1"
# xmlrpc integer limits
MAXINT = 2L**31-1
MININT = -2L**31
# --------------------------------------------------------------------
# Error constants (from Dan Libby's specification at
# http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php)
# Ranges of errors
PARSE_ERROR = -32700
SERVER_ERROR = -32600
APPLICATION_ERROR = -32500
SYSTEM_ERROR = -32400
TRANSPORT_ERROR = -32300
# Specific errors
NOT_WELLFORMED_ERROR = -32700
UNSUPPORTED_ENCODING = -32701
INVALID_ENCODING_CHAR = -32702
INVALID_XMLRPC = -32600
METHOD_NOT_FOUND = -32601
INVALID_METHOD_PARAMS = -32602
INTERNAL_ERROR = -32603
# --------------------------------------------------------------------
# Exceptions
##
# Base class for all kinds of client-side errors.
class Error(Exception):
"""Base class for client errors."""
def __str__(self):
return repr(self)
##
# Indicates an HTTP-level protocol error. This is raised by the HTTP
# transport layer, if the server returns an error code other than 200
# (OK).
#
# @param url The target URL.
# @param errcode The HTTP error code.
# @param errmsg The HTTP error message.
# @param headers The HTTP header dictionary.
class ProtocolError(Error):
"""Indicates an HTTP protocol error."""
def __init__(self, url, errcode, errmsg, headers):
Error.__init__(self)
self.url = url
self.errcode = errcode
self.errmsg = errmsg
self.headers = headers
def __repr__(self):
return (
"<ProtocolError for %s: %s %s>" %
(self.url, self.errcode, self.errmsg)
)
##
# Indicates a broken XML-RPC response package. This exception is
# raised by the unmarshalling layer, if the XML-RPC response is
# malformed.
class ResponseError(Error):
"""Indicates a broken response package."""
pass
##
# Indicates an XML-RPC fault response package. This exception is
# raised by the unmarshalling layer, if the XML-RPC response contains
# a fault string. This exception can also used as a class, to
# generate a fault XML-RPC message.
#
# @param faultCode The XML-RPC fault code.
# @param faultString The XML-RPC fault string.
class Fault(Error):
"""Indicates an XML-RPC fault package."""
def __init__(self, faultCode, faultString, **extra):
Error.__init__(self)
self.faultCode = faultCode
self.faultString = faultString
def __repr__(self):
return (
"<Fault %s: %s>" %
(self.faultCode, repr(self.faultString))
)
# --------------------------------------------------------------------
# Special values
##
# Wrapper for XML-RPC boolean values. Use the xmlrpclib.True and
# xmlrpclib.False constants, or the xmlrpclib.boolean() function, to
# generate boolean XML-RPC values.
#
# @param value A boolean value. Any true value is interpreted as True,
# all other values are interpreted as False.
if _bool_is_builtin:
boolean = Boolean = bool
# to avoid breaking code which references xmlrpclib.{True,False}
True, False = True, False
else:
class Boolean:
"""Boolean-value wrapper.
Use True or False to generate a "boolean" XML-RPC value.
"""
def __init__(self, value = 0):
self.value = operator.truth(value)
def encode(self, out):
out.write("<value><boolean>%d</boolean></value>\n" % self.value)
def __cmp__(self, other):
if isinstance(other, Boolean):
other = other.value
return cmp(self.value, other)
def __repr__(self):
if self.value:
return "<Boolean True at %x>" % id(self)
else:
return "<Boolean False at %x>" % id(self)
def __int__(self):
return self.value
def __nonzero__(self):
return self.value
True, False = Boolean(1), Boolean(0)
##
# Map true or false value to XML-RPC boolean values.
#
# @def boolean(value)
# @param value A boolean value. Any true value is mapped to True,
# all other values are mapped to False.
# @return xmlrpclib.True or xmlrpclib.False.
# @see Boolean
# @see True
# @see False
def boolean(value, _truefalse=(False, True)):
"""Convert any Python value to XML-RPC 'boolean'."""
return _truefalse[operator.truth(value)]
##
# Wrapper for XML-RPC DateTime values. This converts a time value to
# the format used by XML-RPC.
# <p>
# The value can be given as a string in the format
# "yyyymmddThh:mm:ss", as a 9-item time tuple (as returned by
# time.localtime()), or an integer value (as returned by time.time()).
# The wrapper uses time.localtime() to convert an integer to a time
# tuple.
#
# @param value The time, given as an ISO 8601 string, a time
# tuple, or a integer time value.
class DateTime:
"""DateTime wrapper for an ISO 8601 string or time tuple or
localtime integer value to generate 'dateTime.iso8601' XML-RPC
value.
"""
def __init__(self, value=0):
if not isinstance(value, StringType):
if not isinstance(value, (TupleType, time.struct_time)):
if value == 0:
value = time.time()
value = time.localtime(value)
value = time.strftime("%Y%m%dT%H:%M:%S", value)
self.value = value
def __cmp__(self, other):
if isinstance(other, DateTime):
other = other.value
return cmp(self.value, other)
##
# Get date/time value.
#
# @return Date/time value, as an ISO 8601 string.
def __str__(self):
return self.value
def __repr__(self):
return "<DateTime %s at %x>" % (repr(self.value), id(self))
def decode(self, data):
self.value = string.strip(data)
def encode(self, out):
out.write("<value><dateTime.iso8601>")
out.write(self.value)
out.write("</dateTime.iso8601></value>\n")
def _datetime(data):
# decode xml element contents into a DateTime structure.
value = DateTime()
value.decode(data)
return value
##
# Wrapper for binary data. This can be used to transport any kind
# of binary data over XML-RPC, using BASE64 encoding.
#
# @param data An 8-bit string containing arbitrary data.
import base64
try:
import cStringIO as StringIO
except ImportError:
import StringIO
class Binary:
"""Wrapper for binary data."""
def __init__(self, data=None):
self.data = data
##
# Get buffer contents.
#
# @return Buffer contents, as an 8-bit string.
def __str__(self):
return self.data or ""
def __cmp__(self, other):
if isinstance(other, Binary):
other = other.data
return cmp(self.data, other)
def decode(self, data):
self.data = base64.decodestring(data)
def encode(self, out):
out.write("<value><base64>\n")
base64.encode(StringIO.StringIO(self.data), out)
out.write("</base64></value>\n")
def _binary(data):
# decode xml element contents into a Binary structure
value = Binary()
value.decode(data)
return value
WRAPPERS = (DateTime, Binary)
if not _bool_is_builtin:
WRAPPERS = WRAPPERS + (Boolean,)
# --------------------------------------------------------------------
# XML parsers
try:
# optional xmlrpclib accelerator
import _xmlrpclib
FastParser = _xmlrpclib.Parser
FastUnmarshaller = _xmlrpclib.Unmarshaller
except (AttributeError, ImportError):
FastParser = FastUnmarshaller = None
try:
import _xmlrpclib
FastMarshaller = _xmlrpclib.Marshaller
except (AttributeError, ImportError):
FastMarshaller = None
#
# the SGMLOP parser is about 15x faster than Python's builtin
# XML parser. SGMLOP sources can be downloaded from:
#
# http://www.pythonware.com/products/xml/sgmlop.htm
#
try:
import sgmlop
if not hasattr(sgmlop, "XMLParser"):
raise ImportError
except ImportError:
SgmlopParser = None # sgmlop accelerator not available
else:
class SgmlopParser:
def __init__(self, target):
# setup callbacks
self.finish_starttag = target.start
self.finish_endtag = target.end
self.handle_data = target.data
self.handle_xml = target.xml
# activate parser
self.parser = sgmlop.XMLParser()
self.parser.register(self)
self.feed = self.parser.feed
self.entity = {
"amp": "&", "gt": ">", "lt": "<",
"apos": "'", "quot": '"'
}
def close(self):
try:
self.parser.close()
finally:
self.parser = self.feed = None # nuke circular reference
def handle_proc(self, tag, attr):
m = re.search("encoding\s*=\s*['\"]([^\"']+)[\"']", attr)
if m:
self.handle_xml(m.group(1), 1)
def handle_entityref(self, entity):
# <string> entity
try:
self.handle_data(self.entity[entity])
except KeyError:
self.handle_data("&%s;" % entity)
try:
from xml.parsers import expat
if not hasattr(expat, "ParserCreate"):
raise ImportError
except ImportError:
ExpatParser = None # expat not available
else:
class ExpatParser:
# fast expat parser for Python 2.0 and later. this is about
# 50% slower than sgmlop, on roundtrip testing
def __init__(self, target):
self._parser = parser = expat.ParserCreate(None, None)
self._target = target
parser.StartElementHandler = target.start
parser.EndElementHandler = target.end
parser.CharacterDataHandler = target.data
encoding = None
if not parser.returns_unicode:
encoding = "utf-8"
target.xml(encoding, None)
def feed(self, data):
self._parser.Parse(data, 0)
def close(self):
self._parser.Parse("", 1) # end of data
del self._target, self._parser # get rid of circular references
class SlowParser:
"""Default XML parser (based on xmllib.XMLParser)."""
# this is about 10 times slower than sgmlop, on roundtrip
# testing.
def __init__(self, target):
import xmllib # lazy subclassing (!)
if xmllib.XMLParser not in SlowParser.__bases__:
SlowParser.__bases__ = (xmllib.XMLParser,)
self.handle_xml = target.xml
self.unknown_starttag = target.start
self.handle_data = target.data
self.handle_cdata = target.data
self.unknown_endtag = target.end
try:
xmllib.XMLParser.__init__(self, accept_utf8=1)
except TypeError:
xmllib.XMLParser.__init__(self) # pre-2.0
# --------------------------------------------------------------------
# XML-RPC marshalling and unmarshalling code
##
# XML-RPC marshaller.
#
# @param encoding Default encoding for 8-bit strings. The default
# value is None (interpreted as UTF-8).
# @see dumps
class Marshaller:
"""Generate an XML-RPC params chunk from a Python data structure.
Create a Marshaller instance for each set of parameters, and use
the "dumps" method to convert your data (represented as a tuple)
to an XML-RPC params chunk. To write a fault response, pass a
Fault instance instead. You may prefer to use the "dumps" module
function for this purpose.
"""
# by the way, if you don't understand what's going on in here,
# that's perfectly ok.
def __init__(self, encoding=None, allow_none=0):
self.memo = {}
self.data = None
self.encoding = encoding
self.allow_none = allow_none
dispatch = {}
def dumps(self, values):
out = []
write = out.append
dump = self.__dump
if isinstance(values, Fault):
# fault instance
write("<fault>\n")
dump({'faultCode': values.faultCode,
'faultString': values.faultString},
write)
write("</fault>\n")
else:
# parameter block
# FIXME: the xml-rpc specification allows us to leave out
# the entire <params> block if there are no parameters.
# however, changing this may break older code (including
# old versions of xmlrpclib.py), so this is better left as
# is for now. See @XMLRPC3 for more information. /F
write("<params>\n")
for v in values:
write("<param>\n")
dump(v, write)
write("</param>\n")
write("</params>\n")
result = string.join(out, "")
return result
def __dump(self, value, write):
try:
f = self.dispatch[type(value)]
except KeyError:
raise TypeError, "cannot marshal %s objects" % type(value)
else:
f(self, value, write)
def dump_nil (self, value, write):
if not self.allow_none:
raise TypeError, "cannot marshal None unless allow_none is enabled"
write("<value><nil/></value>")
dispatch[NoneType] = dump_nil
def dump_int(self, value, write):
# in case ints are > 32 bits
if value > MAXINT or value < MININT:
raise OverflowError, "int exceeds XML-RPC limits"
write("<value><int>")
write(str(value))
write("</int></value>\n")
dispatch[IntType] = dump_int
if _bool_is_builtin:
def dump_bool(self, value, write):
write("<value><boolean>")
write(value and "1" or "0")
write("</boolean></value>\n")
dispatch[bool] = dump_bool
def dump_long(self, value, write):
if value > MAXINT or value < MININT:
raise OverflowError, "long int exceeds XML-RPC limits"
write("<value><int>")
write(str(int(value)))
write("</int></value>\n")
dispatch[LongType] = dump_long
def dump_double(self, value, write):
write("<value><double>")
write(repr(value))
write("</double></value>\n")
dispatch[FloatType] = dump_double
def dump_string(self, value, write, escape=escape):
write("<value><string>")
write(escape(value))
write("</string></value>\n")
dispatch[StringType] = dump_string
if unicode:
def dump_unicode(self, value, write, escape=escape):
value = value.encode(self.encoding)
write("<value><string>")
write(escape(value))
write("</string></value>\n")
dispatch[UnicodeType] = dump_unicode
def dump_array(self, value, write):
i = id(value)
if self.memo.has_key(i):
raise TypeError, "cannot marshal recursive sequences"
self.memo[i] = None
dump = self.__dump
write("<value><array><data>\n")
for v in value:
dump(v, write)
write("</data></array></value>\n")
del self.memo[i]
dispatch[TupleType] = dump_array
dispatch[ListType] = dump_array
def dump_struct(self, value, write, escape=escape):
i = id(value)
if self.memo.has_key(i):
raise TypeError, "cannot marshal recursive dictionaries"
self.memo[i] = None
dump = self.__dump
write("<value><struct>\n")
for k, v in value.items():
write("<member>\n")
if type(k) is not StringType:
if unicode and type(k) is UnicodeType:
k = k.encode(self.encoding)
else:
raise TypeError, "dictionary key must be string"
write("<name>%s</name>\n" % escape(k))
dump(v, write)
write("</member>\n")
write("</struct></value>\n")
del self.memo[i]
dispatch[DictType] = dump_struct
def dump_instance(self, value, write):
# check for special wrappers
if value.__class__ in WRAPPERS:
self.write = write
value.encode(self)
del self.write
else:
# store instance attributes as a struct (really?)
self.dump_struct(value.__dict__, write)
dispatch[InstanceType] = dump_instance
##
# XML-RPC unmarshaller.
#
# @see loads
class Unmarshaller:
"""Unmarshal an XML-RPC response, based on incoming XML event
messages (start, data, end). Call close() to get the resulting
data structure.
Note that this reader is fairly tolerant, and gladly accepts bogus
XML-RPC data without complaining (but not bogus XML).
"""
# and again, if you don't understand what's going on in here,
# that's perfectly ok.
def __init__(self):
self._type = None
self._stack = []
self._marks = []
self._data = []
self._methodname = None
self._encoding = "utf-8"
self.append = self._stack.append
def close(self):
# return response tuple and target method
if self._type is None or self._marks:
raise ResponseError()
if self._type == "fault":
raise Fault(**self._stack[0])
return tuple(self._stack)
def getmethodname(self):
return self._methodname
#
# event handlers
def xml(self, encoding, standalone):
self._encoding = encoding
# FIXME: assert standalone == 1 ???
def start(self, tag, attrs):
# prepare to handle this element
if tag == "array" or tag == "struct":
self._marks.append(len(self._stack))
self._data = []
self._value = (tag == "value")
def data(self, text):
self._data.append(text)
def end(self, tag, join=string.join):
# call the appropriate end tag handler
try:
f = self.dispatch[tag]
except KeyError:
pass # unknown tag ?
else:
return f(self, join(self._data, ""))
#
# accelerator support
def end_dispatch(self, tag, data):
# dispatch data
try:
f = self.dispatch[tag]
except KeyError:
pass # unknown tag ?
else:
return f(self, data)
#
# element decoders
dispatch = {}
def end_nil (self, data):
self.append(None)
self._value = 0
dispatch["nil"] = end_nil
def end_boolean(self, data):
if data == "0":
self.append(False)
elif data == "1":
self.append(True)
else:
raise TypeError, "bad boolean value"
self._value = 0
dispatch["boolean"] = end_boolean
def end_int(self, data):
self.append(int(data))
self._value = 0
dispatch["i4"] = end_int
dispatch["int"] = end_int
def end_double(self, data):
self.append(float(data))
self._value = 0
dispatch["double"] = end_double
def end_string(self, data):
if self._encoding:
data = _decode(data, self._encoding)
self.append(_stringify(data))
self._value = 0
dispatch["string"] = end_string
dispatch["name"] = end_string # struct keys are always strings
def end_array(self, data):
mark = self._marks.pop()
# map arrays to Python lists
self._stack[mark:] = [self._stack[mark:]]
self._value = 0
dispatch["array"] = end_array
def end_struct(self, data):
mark = self._marks.pop()
# map structs to Python dictionaries
dict = {}
items = self._stack[mark:]
for i in range(0, len(items), 2):
dict[_stringify(items[i])] = items[i+1]
self._stack[mark:] = [dict]
self._value = 0
dispatch["struct"] = end_struct
def end_base64(self, data):
value = Binary()
value.decode(data)
self.append(value)
self._value = 0
dispatch["base64"] = end_base64
def end_dateTime(self, data):
value = DateTime()
value.decode(data)
self.append(value)
dispatch["dateTime.iso8601"] = end_dateTime
def end_value(self, data):
# if we stumble upon a value element with no internal
# elements, treat it as a string element
if self._value:
self.end_string(data)
dispatch["value"] = end_value
def end_params(self, data):
self._type = "params"
dispatch["params"] = end_params
def end_fault(self, data):
self._type = "fault"
dispatch["fault"] = end_fault
def end_methodName(self, data):
if self._encoding:
data = _decode(data, self._encoding)
self._methodname = data
self._type = "methodName" # no params
dispatch["methodName"] = end_methodName
## Multicall support
#
class _MultiCallMethod:
# some lesser magic to store calls made to a MultiCall object
# for batch execution
def __init__(self, call_list, name):
self.__call_list = call_list
self.__name = name
def __getattr__(self, name):
return _MultiCallMethod(self.__call_list, "%s.%s" % (self.__name, name))
def __call__(self, *args):
self.__call_list.append((self.__name, args))
class MultiCallIterator:
"""Iterates over the results of a multicall. Exceptions are
thrown in response to xmlrpc faults."""
def __init__(self, results):
self.results = results
def __getitem__(self, i):
item = self.results[i]
if type(item) == type({}):
raise Fault(item['faultCode'], item['faultString'])
elif type(item) == type([]):
return item[0]
else:
raise ValueError,\
"unexpected type in multicall result"
class MultiCall:
"""server -> a object used to boxcar method calls
server should be a ServerProxy object.
Methods can be added to the MultiCall using normal
method call syntax e.g.:
multicall = MultiCall(server_proxy)
multicall.add(2,3)
multicall.get_address("Guido")
To execute the multicall, call the MultiCall object e.g.:
add_result, address = multicall()
"""
def __init__(self, server):
self.__server = server
self.__call_list = []
def __repr__(self):
return "<MultiCall at %x>" % id(self)
__str__ = __repr__
def __getattr__(self, name):
return _MultiCallMethod(self.__call_list, name)
def __call__(self):
marshalled_list = []
for name, args in self.__call_list:
marshalled_list.append({'methodName' : name, 'params' : args})
return MultiCallIterator(self.__server.system.multicall(marshalled_list))
# --------------------------------------------------------------------
# convenience functions
##
# Create a parser object, and connect it to an unmarshalling instance.
# This function picks the fastest available XML parser.
#
# return A (parser, unmarshaller) tuple.
def getparser():
"""getparser() -> parser, unmarshaller
Create an instance of the fastest available parser, and attach it
to an unmarshalling object. Return both objects.
"""
if FastParser and FastUnmarshaller:
target = FastUnmarshaller(True, False, _binary, _datetime, Fault)
parser = FastParser(target)
else:
target = Unmarshaller()
if FastParser:
parser = FastParser(target)
elif SgmlopParser:
parser = SgmlopParser(target)
elif ExpatParser:
parser = ExpatParser(target)
else:
parser = SlowParser(target)
return parser, target
##
# Convert a Python tuple or a Fault instance to an XML-RPC packet.
#
# @def dumps(params, **options)
# @param params A tuple or Fault instance.
# @keyparam methodname If given, create a methodCall request for
# this method name.
# @keyparam methodresponse If given, create a methodResponse packet.
# If used with a tuple, the tuple must be a singleton (that is,
# it must contain exactly one element).
# @keyparam encoding The packet encoding.
# @return A string containing marshalled data.
def dumps(params, methodname=None, methodresponse=None, encoding=None,
allow_none=0):
"""data [,options] -> marshalled data
Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
In addition to the data object, the following options can be given
as keyword arguments:
methodname: the method name for a methodCall packet
methodresponse: true to create a methodResponse packet.
If this option is used with a tuple, the tuple must be
a singleton (i.e. it can contain only one element).
encoding: the packet encoding (default is UTF-8)
All 8-bit strings in the data structure are assumed to use the
packet encoding. Unicode strings are automatically converted,
where necessary.
"""
assert isinstance(params, TupleType) or isinstance(params, Fault),\
"argument must be tuple or Fault instance"
if isinstance(params, Fault):
methodresponse = 1
elif methodresponse and isinstance(params, TupleType):
assert len(params) == 1, "response tuple must be a singleton"
if not encoding:
encoding = "utf-8"
if FastMarshaller:
m = FastMarshaller(encoding)
else:
m = Marshaller(encoding, allow_none)
data = m.dumps(params)
if encoding != "utf-8":
xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding)
else:
xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default
# standard XML-RPC wrappings
if methodname:
# a method call
if not isinstance(methodname, StringType):
methodname = methodname.encode(encoding)
data = (
xmlheader,
"<methodCall>\n"
"<methodName>", methodname, "</methodName>\n",
data,
"</methodCall>\n"
)
elif methodresponse:
# a method response, or a fault structure
data = (
xmlheader,
"<methodResponse>\n",
data,
"</methodResponse>\n"
)
else:
return data # return as is
return string.join(data, "")
##
# Convert an XML-RPC packet to a Python object. If the XML-RPC packet
# represents a fault condition, this function raises a Fault exception.
#
# @param data An XML-RPC packet, given as an 8-bit string.
# @return A tuple containing the unpacked data, and the method name
# (None if not present).
# @see Fault
def loads(data):
"""data -> unmarshalled data, method name
Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
If the XML-RPC packet represents a fault condition, this function
raises a Fault exception.
"""
p, u = getparser()
p.feed(data)
p.close()
return u.close(), u.getmethodname()
# --------------------------------------------------------------------
# request dispatcher
class _Method:
# some magic to bind an XML-RPC method to an RPC server.
# supports "nested" methods (e.g. examples.getStateName)
def __init__(self, send, name):
self.__send = send
self.__name = name
def __getattr__(self, name):
return _Method(self.__send, "%s.%s" % (self.__name, name))
def __call__(self, *args):
return self.__send(self.__name, args)
##
# Standard transport class for XML-RPC over HTTP.
# <p>
# You can create custom transports by subclassing this method, and
# overriding selected methods.
class Transport:
"""Handles an HTTP transaction to an XML-RPC server."""
# client identifier (may be overridden)
user_agent = "xmlrpclib.py/%s (by www.pythonware.com)" % __version__
##
# Send a complete request, and parse the response.
#
# @param host Target host.
# @param handler Target PRC handler.
# @param request_body XML-RPC request body.
# @param verbose Debugging flag.
# @return Parsed response.
def request(self, host, handler, request_body, verbose=0):
# issue XML-RPC request
h = self.make_connection(host)
if verbose:
h.set_debuglevel(1)
self.send_request(h, handler, request_body)
self.send_host(h, host)
self.send_user_agent(h)
self.send_content(h, request_body)
errcode, errmsg, headers = h.getreply()
if errcode != 200:
raise ProtocolError(
host + handler,
errcode, errmsg,
headers
)
self.verbose = verbose
try:
sock = h._conn.sock
except AttributeError:
sock = None
return self._parse_response(h.getfile(), sock)
##
# Create parser.
#
# @return A 2-tuple containing a parser and a unmarshaller.
def getparser(self):
# get parser and unmarshaller
return getparser()
##
# Get authorization info from host parameter
# Host may be a string, or a (host, x509-dict) tuple; if a string,
# it is checked for a "user:pw@host" format, and a "Basic
# Authentication" header is added if appropriate.
#
# @param host Host descriptor (URL or (URL, x509 info) tuple).
# @return A 3-tuple containing (actual host, extra headers,
# x509 info). The header and x509 fields may be None.
def get_host_info(self, host):
x509 = {}
if isinstance(host, TupleType):
host, x509 = host
import urllib
auth, host = urllib.splituser(host)
if auth:
import base64
auth = base64.encodestring(urllib.unquote(auth))
auth = string.join(string.split(auth), "") # get rid of whitespace
extra_headers = [
("Authorization", "Basic " + auth)
]
else:
extra_headers = None
return host, extra_headers, x509
##
# Connect to server.
#
# @param host Target host.
# @return A connection handle.
def make_connection(self, host):
# create a HTTP connection object from a host descriptor
import httplib
host, extra_headers, x509 = self.get_host_info(host)
return httplib.HTTP(host)
##
# Send request header.
#
# @param connection Connection handle.
# @param handler Target RPC handler.
# @param request_body XML-RPC body.
def send_request(self, connection, handler, request_body):
connection.putrequest("POST", handler)
##
# Send host name.
#
# @param connection Connection handle.
# @param host Host name.
def send_host(self, connection, host):
host, extra_headers, x509 = self.get_host_info(host)
connection.putheader("Host", host)
if extra_headers:
if isinstance(extra_headers, DictType):
extra_headers = extra_headers.items()
for key, value in extra_headers:
connection.putheader(key, value)
##
# Send user-agent identifier.
#
# @param connection Connection handle.
def send_user_agent(self, connection):
connection.putheader("User-Agent", self.user_agent)
##
# Send request body.
#
# @param connection Connection handle.
# @param request_body XML-RPC request body.
def send_content(self, connection, request_body):
connection.putheader("Content-Type", "text/xml")
connection.putheader("Content-Length", str(len(request_body)))
connection.endheaders()
if request_body:
connection.send(request_body)
##
# Parse response.
#
# @param file Stream.
# @return Response tuple and target method.
def parse_response(self, file):
# compatibility interface
return self._parse_response(file, None)
##
# Parse response (alternate interface). This is similar to the
# parse_response method, but also provides direct access to the
# underlying socket object (where available).
#
# @param file Stream.
# @param sock Socket handle (or None, if the socket object
# could not be accessed).
# @return Response tuple and target method.
def _parse_response(self, file, sock):
# read response from input file/socket, and parse it
p, u = self.getparser()
while 1:
if sock:
response = sock.recv(1024)
else:
response = file.read(1024)
if not response:
break
if self.verbose:
print "body:", repr(response)
p.feed(response)
file.close()
p.close()
return u.close()
##
# Standard transport class for XML-RPC over HTTPS.
class SafeTransport(Transport):
"""Handles an HTTPS transaction to an XML-RPC server."""
# FIXME: mostly untested
def make_connection(self, host):
# create a HTTPS connection object from a host descriptor
# host may be a string, or a (host, x509-dict) tuple
import httplib
host, extra_headers, x509 = self.get_host_info(host)
try:
HTTPS = httplib.HTTPS
except AttributeError:
raise NotImplementedError(
"your version of httplib doesn't support HTTPS"
)
else:
return HTTPS(host, None, **(x509 or {}))
##
# Standard server proxy. This class establishes a virtual connection
# to an XML-RPC server.
# <p>
# This class is available as ServerProxy and Server. New code should
# use ServerProxy, to avoid confusion.
#
# @def ServerProxy(uri, **options)
# @param uri The connection point on the server.
# @keyparam transport A transport factory, compatible with the
# standard transport class.
# @keyparam encoding The default encoding used for 8-bit strings
# (default is UTF-8).
# @keyparam verbose Use a true value to enable debugging output.
# (printed to standard output).
# @see Transport
class ServerProxy:
"""uri [,options] -> a logical connection to an XML-RPC server
uri is the connection point on the server, given as
scheme://host/target.
The standard implementation always supports the "http" scheme. If
SSL socket support is available (Python 2.0), it also supports
"https".
If the target part and the slash preceding it are both omitted,
"/RPC2" is assumed.
The following options can be given as keyword arguments:
transport: a transport factory
encoding: the request encoding (default is UTF-8)
All 8-bit strings passed to the server proxy are assumed to use
the given encoding.
"""
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=0):
# establish a "logical" server connection
# get the url
import urllib
type, uri = urllib.splittype(uri)
if type not in ("http", "https"):
raise IOError, "unsupported XML-RPC protocol"
self.__host, self.__handler = urllib.splithost(uri)
if not self.__handler:
self.__handler = "/RPC2"
if transport is None:
if type == "https":
transport = SafeTransport()
else:
transport = Transport()
self.__transport = transport
self.__encoding = encoding
self.__verbose = verbose
self.__allow_none = allow_none
def __request(self, methodname, params):
# call a method on the remote server
request = dumps(params, methodname, encoding=self.__encoding,
allow_none=self.__allow_none)
response = self.__transport.request(
self.__host,
self.__handler,
request,
verbose=self.__verbose
)
if len(response) == 1:
response = response[0]
return response
def __repr__(self):
return (
"<ServerProxy for %s%s>" %
(self.__host, self.__handler)
)
__str__ = __repr__
def __getattr__(self, name):
# magic method dispatcher
return _Method(self.__request, name)
# note: to call a remote object with an non-standard name, use
# result getattr(server, "strange-python-name")(args)
# compatibility
Server = ServerProxy
# --------------------------------------------------------------------
# test code
if __name__ == "__main__":
# simple test program (from the XML-RPC specification)
# server = ServerProxy("http://localhost:8000") # local server
server = ServerProxy("http://time.xmlrpc.com/RPC2")
print server
try:
print server.currentTime.getCurrentTime()
except Error, v:
print "ERROR", v
multi = MultiCall(server)
multi.currentTime.getCurrentTime()
multi.currentTime.getCurrentTime()
try:
for response in multi():
print response
except Error, v:
print "ERROR", v
| Python |
"""HTTP server base class.
Note: the class in this module doesn't implement any HTTP request; see
SimpleHTTPServer for simple implementations of GET, HEAD and POST
(including CGI scripts). It does, however, optionally implement HTTP/1.1
persistent connections, as of version 0.3.
Contents:
- BaseHTTPRequestHandler: HTTP request handler base class
- test: test function
XXX To do:
- log requests even later (to capture byte count)
- log user-agent header and other interesting goodies
- send error log to separate file
"""
# See also:
#
# HTTP Working Group T. Berners-Lee
# INTERNET-DRAFT R. T. Fielding
# <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen
# Expires September 8, 1995 March 8, 1995
#
# URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
#
# and
#
# Network Working Group R. Fielding
# Request for Comments: 2616 et al
# Obsoletes: 2068 June 1999
# Category: Standards Track
#
# URL: http://www.faqs.org/rfcs/rfc2616.html
# Log files
# ---------
#
# Here's a quote from the NCSA httpd docs about log file format.
#
# | The logfile format is as follows. Each line consists of:
# |
# | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb
# |
# | host: Either the DNS name or the IP number of the remote client
# | rfc931: Any information returned by identd for this person,
# | - otherwise.
# | authuser: If user sent a userid for authentication, the user name,
# | - otherwise.
# | DD: Day
# | Mon: Month (calendar name)
# | YYYY: Year
# | hh: hour (24-hour format, the machine's timezone)
# | mm: minutes
# | ss: seconds
# | request: The first line of the HTTP request as sent by the client.
# | ddd: the status code returned by the server, - if not available.
# | bbbb: the total number of bytes sent,
# | *not including the HTTP/1.0 header*, - if not available
# |
# | You can determine the name of the file accessed through request.
#
# (Actually, the latter is only true if you know the server configuration
# at the time the request was made!)
__version__ = "0.3"
__all__ = ["HTTPServer", "BaseHTTPRequestHandler"]
import sys
import time
import socket # For gethostbyaddr()
import mimetools
import SocketServer
# Default error message
DEFAULT_ERROR_MESSAGE = """\
<head>
<title>Error response</title>
</head>
<body>
<h1>Error response</h1>
<p>Error code %(code)d.
<p>Message: %(message)s.
<p>Error code explanation: %(code)s = %(explain)s.
</body>
"""
class HTTPServer(SocketServer.TCPServer):
allow_reuse_address = 1 # Seems to make sense in testing environment
def server_bind(self):
"""Override server_bind to store the server name."""
SocketServer.TCPServer.server_bind(self)
host, port = self.socket.getsockname()[:2]
self.server_name = socket.getfqdn(host)
self.server_port = port
class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
"""HTTP request handler base class.
The following explanation of HTTP serves to guide you through the
code as well as to expose any misunderstandings I may have about
HTTP (so you don't need to read the code to figure out I'm wrong
:-).
HTTP (HyperText Transfer Protocol) is an extensible protocol on
top of a reliable stream transport (e.g. TCP/IP). The protocol
recognizes three parts to a request:
1. One line identifying the request type and path
2. An optional set of RFC-822-style headers
3. An optional data part
The headers and data are separated by a blank line.
The first line of the request has the form
<command> <path> <version>
where <command> is a (case-sensitive) keyword such as GET or POST,
<path> is a string containing path information for the request,
and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
<path> is encoded using the URL encoding scheme (using %xx to signify
the ASCII character with hex code xx).
The specification specifies that lines are separated by CRLF but
for compatibility with the widest range of clients recommends
servers also handle LF. Similarly, whitespace in the request line
is treated sensibly (allowing multiple spaces between components
and allowing trailing whitespace).
Similarly, for output, lines ought to be separated by CRLF pairs
but most clients grok LF characters just fine.
If the first line of the request has the form
<command> <path>
(i.e. <version> is left out) then this is assumed to be an HTTP
0.9 request; this form has no optional headers and data part and
the reply consists of just the data.
The reply form of the HTTP 1.x protocol again has three parts:
1. One line giving the response code
2. An optional set of RFC-822-style headers
3. The data
Again, the headers and data are separated by a blank line.
The response code line has the form
<version> <responsecode> <responsestring>
where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
<responsecode> is a 3-digit response code indicating success or
failure of the request, and <responsestring> is an optional
human-readable string explaining what the response code means.
This server parses the request and the headers, and then calls a
function specific to the request type (<command>). Specifically,
a request SPAM will be handled by a method do_SPAM(). If no
such method exists the server sends an error response to the
client. If it exists, it is called with no arguments:
do_SPAM()
Note that the request name is case sensitive (i.e. SPAM and spam
are different requests).
The various request details are stored in instance variables:
- client_address is the client IP address in the form (host,
port);
- command, path and version are the broken-down request line;
- headers is an instance of mimetools.Message (or a derived
class) containing the header information;
- rfile is a file object open for reading positioned at the
start of the optional input data part;
- wfile is a file object open for writing.
IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
The first thing to be written must be the response line. Then
follow 0 or more header lines, then a blank line, and then the
actual data (if any). The meaning of the header lines depends on
the command executed by the server; in most cases, when data is
returned, there should be at least one header line of the form
Content-type: <type>/<subtype>
where <type> and <subtype> should be registered MIME types,
e.g. "text/html" or "text/plain".
"""
# The Python system version, truncated to its first component.
sys_version = "Python/" + sys.version.split()[0]
# The server software version. You may want to override this.
# The format is multiple whitespace-separated strings,
# where each string is of the form name[/version].
server_version = "BaseHTTP/" + __version__
def parse_request(self):
"""Parse a request (internal).
The request should be stored in self.raw_requestline; the results
are in self.command, self.path, self.request_version and
self.headers.
Return True for success, False for failure; on failure, an
error is sent back.
"""
self.command = None # set in case of error on the first line
self.request_version = version = "HTTP/0.9" # Default
self.close_connection = 1
requestline = self.raw_requestline
if requestline[-2:] == '\r\n':
requestline = requestline[:-2]
elif requestline[-1:] == '\n':
requestline = requestline[:-1]
self.requestline = requestline
words = requestline.split()
if len(words) == 3:
[command, path, version] = words
if version[:5] != 'HTTP/':
self.send_error(400, "Bad request version (%r)" % version)
return False
try:
base_version_number = version.split('/', 1)[1]
version_number = base_version_number.split(".")
# RFC 2145 section 3.1 says there can be only one "." and
# - major and minor numbers MUST be treated as
# separate integers;
# - HTTP/2.4 is a lower version than HTTP/2.13, which in
# turn is lower than HTTP/12.3;
# - Leading zeros MUST be ignored by recipients.
if len(version_number) != 2:
raise ValueError
version_number = int(version_number[0]), int(version_number[1])
except (ValueError, IndexError):
self.send_error(400, "Bad request version (%r)" % version)
return False
if version_number >= (1, 1) and self.protocol_version >= "HTTP/1.1":
self.close_connection = 0
if version_number >= (2, 0):
self.send_error(505,
"Invalid HTTP Version (%s)" % base_version_number)
return False
elif len(words) == 2:
[command, path] = words
self.close_connection = 1
if command != 'GET':
self.send_error(400,
"Bad HTTP/0.9 request type (%r)" % command)
return False
elif not words:
return False
else:
self.send_error(400, "Bad request syntax (%r)" % requestline)
return False
self.command, self.path, self.request_version = command, path, version
# Examine the headers and look for a Connection directive
self.headers = self.MessageClass(self.rfile, 0)
conntype = self.headers.get('Connection', "")
if conntype.lower() == 'close':
self.close_connection = 1
elif (conntype.lower() == 'keep-alive' and
self.protocol_version >= "HTTP/1.1"):
self.close_connection = 0
return True
def handle_one_request(self):
"""Handle a single HTTP request.
You normally don't need to override this method; see the class
__doc__ string for information on how to handle specific HTTP
commands such as GET and POST.
"""
self.raw_requestline = self.rfile.readline()
if not self.raw_requestline:
self.close_connection = 1
return
if not self.parse_request(): # An error code has been sent, just exit
return
mname = 'do_' + self.command
if not hasattr(self, mname):
self.send_error(501, "Unsupported method (%r)" % self.command)
return
method = getattr(self, mname)
method()
def handle(self):
"""Handle multiple requests if necessary."""
self.close_connection = 1
self.handle_one_request()
while not self.close_connection:
self.handle_one_request()
def send_error(self, code, message=None):
"""Send and log an error reply.
Arguments are the error code, and a detailed message.
The detailed message defaults to the short entry matching the
response code.
This sends an error response (so it must be called before any
output has been generated), logs the error, and finally sends
a piece of HTML explaining the error to the user.
"""
try:
short, long = self.responses[code]
except KeyError:
short, long = '???', '???'
if message is None:
message = short
explain = long
self.log_error("code %d, message %s", code, message)
content = (self.error_message_format %
{'code': code, 'message': message, 'explain': explain})
self.send_response(code, message)
self.send_header("Content-Type", "text/html")
self.send_header('Connection', 'close')
self.end_headers()
if self.command != 'HEAD' and code >= 200 and code not in (204, 304):
self.wfile.write(content)
error_message_format = DEFAULT_ERROR_MESSAGE
def send_response(self, code, message=None):
"""Send the response header and log the response code.
Also send two standard headers with the server software
version and the current date.
"""
self.log_request(code)
if message is None:
if code in self.responses:
message = self.responses[code][0]
else:
message = ''
if self.request_version != 'HTTP/0.9':
self.wfile.write("%s %d %s\r\n" %
(self.protocol_version, code, message))
# print (self.protocol_version, code, message)
self.send_header('Server', self.version_string())
self.send_header('Date', self.date_time_string())
def send_header(self, keyword, value):
"""Send a MIME header."""
if self.request_version != 'HTTP/0.9':
self.wfile.write("%s: %s\r\n" % (keyword, value))
if keyword.lower() == 'connection':
if value.lower() == 'close':
self.close_connection = 1
elif value.lower() == 'keep-alive':
self.close_connection = 0
def end_headers(self):
"""Send the blank line ending the MIME headers."""
if self.request_version != 'HTTP/0.9':
self.wfile.write("\r\n")
def log_request(self, code='-', size='-'):
"""Log an accepted request.
This is called by send_reponse().
"""
self.log_message('"%s" %s %s',
self.requestline, str(code), str(size))
def log_error(self, *args):
"""Log an error.
This is called when a request cannot be fulfilled. By
default it passes the message on to log_message().
Arguments are the same as for log_message().
XXX This should go to the separate error log.
"""
self.log_message(*args)
def log_message(self, format, *args):
"""Log an arbitrary message.
This is used by all other logging functions. Override
it if you have specific logging wishes.
The first argument, FORMAT, is a format string for the
message to be logged. If the format string contains
any % escapes requiring parameters, they should be
specified as subsequent arguments (it's just like
printf!).
The client host and current date/time are prefixed to
every message.
"""
sys.stderr.write("%s - - [%s] %s\n" %
(self.address_string(),
self.log_date_time_string(),
format%args))
def version_string(self):
"""Return the server software version string."""
return self.server_version + ' ' + self.sys_version
def date_time_string(self):
"""Return the current date and time formatted for a message header."""
now = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
self.weekdayname[wd],
day, self.monthname[month], year,
hh, mm, ss)
return s
def log_date_time_string(self):
"""Return the current time formatted for logging."""
now = time.time()
year, month, day, hh, mm, ss, x, y, z = time.localtime(now)
s = "%02d/%3s/%04d %02d:%02d:%02d" % (
day, self.monthname[month], year, hh, mm, ss)
return s
weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
monthname = [None,
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
def address_string(self):
"""Return the client address formatted for logging.
This version looks up the full hostname using gethostbyaddr(),
and tries to find a name that contains at least one dot.
"""
host, port = self.client_address[:2]
return socket.getfqdn(host)
# Essentially static class variables
# The version of the HTTP protocol we support.
# Set this to HTTP/1.1 to enable automatic keepalive
protocol_version = "HTTP/1.0"
# The Message-like class used to parse headers
MessageClass = mimetools.Message
# Table mapping response codes to messages; entries have the
# form {code: (shortmessage, longmessage)}.
# See http://www.w3.org/hypertext/WWW/Protocols/HTTP/HTRESP.html
responses = {
100: ('Continue', 'Request received, please continue'),
101: ('Switching Protocols',
'Switching to new protocol; obey Upgrade header'),
200: ('OK', 'Request fulfilled, document follows'),
201: ('Created', 'Document created, URL follows'),
202: ('Accepted',
'Request accepted, processing continues off-line'),
203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
204: ('No response', 'Request fulfilled, nothing follows'),
205: ('Reset Content', 'Clear input form for further input.'),
206: ('Partial Content', 'Partial content follows.'),
300: ('Multiple Choices',
'Object has several resources -- see URI list'),
301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
302: ('Found', 'Object moved temporarily -- see URI list'),
303: ('See Other', 'Object moved -- see Method and URL list'),
304: ('Not modified',
'Document has not changed since given time'),
305: ('Use Proxy',
'You must use proxy specified in Location to access this '
'resource.'),
307: ('Temporary Redirect',
'Object moved temporarily -- see URI list'),
400: ('Bad request',
'Bad request syntax or unsupported method'),
401: ('Unauthorized',
'No permission -- see authorization schemes'),
402: ('Payment required',
'No payment -- see charging schemes'),
403: ('Forbidden',
'Request forbidden -- authorization will not help'),
404: ('Not Found', 'Nothing matches the given URI'),
405: ('Method Not Allowed',
'Specified method is invalid for this server.'),
406: ('Not Acceptable', 'URI not available in preferred format.'),
407: ('Proxy Authentication Required', 'You must authenticate with '
'this proxy before proceeding.'),
408: ('Request Time-out', 'Request timed out; try again later.'),
409: ('Conflict', 'Request conflict.'),
410: ('Gone',
'URI no longer exists and has been permanently removed.'),
411: ('Length Required', 'Client must specify Content-Length.'),
412: ('Precondition Failed', 'Precondition in headers is false.'),
413: ('Request Entity Too Large', 'Entity is too large.'),
414: ('Request-URI Too Long', 'URI is too long.'),
415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
416: ('Requested Range Not Satisfiable',
'Cannot satisfy request range.'),
417: ('Expectation Failed',
'Expect condition could not be satisfied.'),
500: ('Internal error', 'Server got itself in trouble'),
501: ('Not Implemented',
'Server does not support this operation'),
502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
503: ('Service temporarily overloaded',
'The server cannot process the request due to a high load'),
504: ('Gateway timeout',
'The gateway server did not receive a timely response'),
505: ('HTTP Version not supported', 'Cannot fulfill request.'),
}
def test(HandlerClass = BaseHTTPRequestHandler,
ServerClass = HTTPServer, protocol="HTTP/1.0"):
"""Test the HTTP request handler class.
This runs an HTTP server on port 8000 (or the first command line
argument).
"""
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
server_address = ('', port)
HandlerClass.protocol_version = protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
test()
| Python |
"""Constants/functions for interpreting results of os.stat() and os.lstat().
Suggested usage: from stat import *
"""
# XXX Strictly spoken, this module may have to be adapted for each POSIX
# implementation; in practice, however, the numeric constants used by
# stat() are almost universal (even for stat() emulations on non-UNIX
# systems like MS-DOS).
# Indices for stat struct members in tuple returned by os.stat()
ST_MODE = 0
ST_INO = 1
ST_DEV = 2
ST_NLINK = 3
ST_UID = 4
ST_GID = 5
ST_SIZE = 6
ST_ATIME = 7
ST_MTIME = 8
ST_CTIME = 9
# Extract bits from the mode
def S_IMODE(mode):
return mode & 07777
def S_IFMT(mode):
return mode & 0170000
# Constants used as S_IFMT() for various file types
# (not all are implemented on all systems)
S_IFDIR = 0040000
S_IFCHR = 0020000
S_IFBLK = 0060000
S_IFREG = 0100000
S_IFIFO = 0010000
S_IFLNK = 0120000
S_IFSOCK = 0140000
# Functions to test for each file type
def S_ISDIR(mode):
return S_IFMT(mode) == S_IFDIR
def S_ISCHR(mode):
return S_IFMT(mode) == S_IFCHR
def S_ISBLK(mode):
return S_IFMT(mode) == S_IFBLK
def S_ISREG(mode):
return S_IFMT(mode) == S_IFREG
def S_ISFIFO(mode):
return S_IFMT(mode) == S_IFIFO
def S_ISLNK(mode):
return S_IFMT(mode) == S_IFLNK
def S_ISSOCK(mode):
return S_IFMT(mode) == S_IFSOCK
# Names for permission bits
S_ISUID = 04000
S_ISGID = 02000
S_ENFMT = S_ISGID
S_ISVTX = 01000
S_IREAD = 00400
S_IWRITE = 00200
S_IEXEC = 00100
S_IRWXU = 00700
S_IRUSR = 00400
S_IWUSR = 00200
S_IXUSR = 00100
S_IRWXG = 00070
S_IRGRP = 00040
S_IWGRP = 00020
S_IXGRP = 00010
S_IRWXO = 00007
S_IROTH = 00004
S_IWOTH = 00002
S_IXOTH = 00001
| Python |
"""Temporary files.
This module provides generic, low- and high-level interfaces for
creating temporary files and directories. The interfaces listed
as "safe" just below can be used without fear of race conditions.
Those listed as "unsafe" cannot, and are provided for backward
compatibility only.
This module also provides some data items to the user:
TMP_MAX - maximum number of names that will be tried before
giving up.
template - the default prefix for all temporary names.
You may change this to control the default prefix.
tempdir - If this is set to a string before the first use of
any routine from this module, it will be considered as
another candidate location to store temporary files.
"""
__all__ = [
"NamedTemporaryFile", "TemporaryFile", # high level safe interfaces
"mkstemp", "mkdtemp", # low level safe interfaces
"mktemp", # deprecated unsafe interface
"TMP_MAX", "gettempprefix", # constants
"tempdir", "gettempdir"
]
# Imports.
import os as _os
import errno as _errno
from random import Random as _Random
if _os.name == 'mac':
import Carbon.Folder as _Folder
import Carbon.Folders as _Folders
try:
import fcntl as _fcntl
except ImportError:
def _set_cloexec(fd):
pass
else:
def _set_cloexec(fd):
try:
flags = _fcntl.fcntl(fd, _fcntl.F_GETFD, 0)
except IOError:
pass
else:
# flags read successfully, modify
flags |= _fcntl.FD_CLOEXEC
_fcntl.fcntl(fd, _fcntl.F_SETFD, flags)
try:
import thread as _thread
except ImportError:
import dummy_thread as _thread
_allocate_lock = _thread.allocate_lock
_text_openflags = _os.O_RDWR | _os.O_CREAT | _os.O_EXCL
if hasattr(_os, 'O_NOINHERIT'):
_text_openflags |= _os.O_NOINHERIT
if hasattr(_os, 'O_NOFOLLOW'):
_text_openflags |= _os.O_NOFOLLOW
_bin_openflags = _text_openflags
if hasattr(_os, 'O_BINARY'):
_bin_openflags |= _os.O_BINARY
if hasattr(_os, 'TMP_MAX'):
TMP_MAX = _os.TMP_MAX
else:
TMP_MAX = 10000
template = "tmp"
tempdir = None
# Internal routines.
_once_lock = _allocate_lock()
if hasattr(_os, "lstat"):
_stat = _os.lstat
elif hasattr(_os, "stat"):
_stat = _os.stat
else:
# Fallback. All we need is something that raises os.error if the
# file doesn't exist.
def _stat(fn):
try:
f = open(fn)
except IOError:
raise _os.error
f.close()
def _exists(fn):
try:
_stat(fn)
except _os.error:
return False
else:
return True
class _RandomNameSequence:
"""An instance of _RandomNameSequence generates an endless
sequence of unpredictable strings which can safely be incorporated
into file names. Each string is six characters long. Multiple
threads can safely use the same instance at the same time.
_RandomNameSequence is an iterator."""
characters = ("abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"0123456789-_")
def __init__(self):
self.mutex = _allocate_lock()
self.rng = _Random()
self.normcase = _os.path.normcase
def __iter__(self):
return self
def next(self):
m = self.mutex
c = self.characters
choose = self.rng.choice
m.acquire()
try:
letters = [choose(c) for dummy in "123456"]
finally:
m.release()
return self.normcase(''.join(letters))
def _candidate_tempdir_list():
"""Generate a list of candidate temporary directories which
_get_default_tempdir will try."""
dirlist = []
# First, try the environment.
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = _os.getenv(envname)
if dirname: dirlist.append(dirname)
# Failing that, try OS-specific locations.
if _os.name == 'mac':
try:
fsr = _Folder.FSFindFolder(_Folders.kOnSystemDisk,
_Folders.kTemporaryFolderType, 1)
dirname = fsr.as_pathname()
dirlist.append(dirname)
except _Folder.error:
pass
elif _os.name == 'riscos':
dirname = _os.getenv('Wimp$ScrapDir')
if dirname: dirlist.append(dirname)
elif _os.name == 'nt':
dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
else:
dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])
# As a last resort, the current directory.
try:
dirlist.append(_os.getcwd())
except (AttributeError, _os.error):
dirlist.append(_os.curdir)
return dirlist
def _get_default_tempdir():
"""Calculate the default directory to use for temporary files.
This routine should be called exactly once.
We determine whether or not a candidate temp dir is usable by
trying to create and write to a file in that directory. If this
is successful, the test file is deleted. To prevent denial of
service, the name of the test file must be randomized."""
namer = _RandomNameSequence()
dirlist = _candidate_tempdir_list()
flags = _text_openflags
for dir in dirlist:
if dir != _os.curdir:
dir = _os.path.normcase(_os.path.abspath(dir))
# Try only a few names per directory.
for seq in xrange(100):
name = namer.next()
filename = _os.path.join(dir, name)
try:
fd = _os.open(filename, flags, 0600)
fp = _os.fdopen(fd, 'w')
fp.write('blat')
fp.close()
_os.unlink(filename)
del fp, fd
return dir
except (OSError, IOError), e:
if e[0] != _errno.EEXIST:
break # no point trying more names in this directory
pass
raise IOError, (_errno.ENOENT,
("No usable temporary directory found in %s" % dirlist))
_name_sequence = None
def _get_candidate_names():
"""Common setup sequence for all user-callable interfaces."""
global _name_sequence
if _name_sequence is None:
_once_lock.acquire()
try:
if _name_sequence is None:
_name_sequence = _RandomNameSequence()
finally:
_once_lock.release()
return _name_sequence
def _mkstemp_inner(dir, pre, suf, flags):
"""Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""
names = _get_candidate_names()
for seq in xrange(TMP_MAX):
name = names.next()
file = _os.path.join(dir, pre + name + suf)
try:
fd = _os.open(file, flags, 0600)
_set_cloexec(fd)
return (fd, _os.path.abspath(file))
except OSError, e:
if e.errno == _errno.EEXIST:
continue # try again
raise
raise IOError, (_errno.EEXIST, "No usable temporary file name found")
# User visible interfaces.
def gettempprefix():
"""Accessor for tempdir.template."""
return template
tempdir = None
def gettempdir():
"""Accessor for tempdir.tempdir."""
global tempdir
if tempdir is None:
_once_lock.acquire()
try:
if tempdir is None:
tempdir = _get_default_tempdir()
finally:
_once_lock.release()
return tempdir
def mkstemp(suffix="", prefix=template, dir=None, text=False):
"""mkstemp([suffix, [prefix, [dir, [text]]]])
User-callable function to create and return a unique temporary
file. The return value is a pair (fd, name) where fd is the
file descriptor returned by os.open, and name is the filename.
If 'suffix' is specified, the file name will end with that suffix,
otherwise there will be no suffix.
If 'prefix' is specified, the file name will begin with that prefix,
otherwise a default prefix is used.
If 'dir' is specified, the file will be created in that directory,
otherwise a default directory is used.
If 'text' is specified and true, the file is opened in text
mode. Else (the default) the file is opened in binary mode. On
some operating systems, this makes no difference.
The file is readable and writable only by the creating user ID.
If the operating system uses permission bits to indicate whether a
file is executable, the file is executable by no one. The file
descriptor is not inherited by children of this process.
Caller is responsible for deleting the file when done with it.
"""
if dir is None:
dir = gettempdir()
if text:
flags = _text_openflags
else:
flags = _bin_openflags
return _mkstemp_inner(dir, prefix, suffix, flags)
def mkdtemp(suffix="", prefix=template, dir=None):
"""mkdtemp([suffix, [prefix, [dir]]])
User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
The directory is readable, writable, and searchable only by the
creating user.
Caller is responsible for deleting the directory when done with it.
"""
if dir is None:
dir = gettempdir()
names = _get_candidate_names()
for seq in xrange(TMP_MAX):
name = names.next()
file = _os.path.join(dir, prefix + name + suffix)
try:
_os.mkdir(file, 0700)
return file
except OSError, e:
if e.errno == _errno.EEXIST:
continue # try again
raise
raise IOError, (_errno.EEXIST, "No usable temporary directory name found")
def mktemp(suffix="", prefix=template, dir=None):
"""mktemp([suffix, [prefix, [dir]]])
User-callable function to return a unique temporary file name. The
file is not created.
Arguments are as for mkstemp, except that the 'text' argument is
not accepted.
This function is unsafe and should not be used. The file name
refers to a file that did not exist at some point, but by the time
you get around to creating it, someone else may have beaten you to
the punch.
"""
## from warnings import warn as _warn
## _warn("mktemp is a potential security risk to your program",
## RuntimeWarning, stacklevel=2)
if dir is None:
dir = gettempdir()
names = _get_candidate_names()
for seq in xrange(TMP_MAX):
name = names.next()
file = _os.path.join(dir, prefix + name + suffix)
if not _exists(file):
return file
raise IOError, (_errno.EEXIST, "No usable temporary filename found")
class _TemporaryFileWrapper:
"""Temporary file wrapper
This class provides a wrapper around files opened for
temporary use. In particular, it seeks to automatically
remove the file when it is no longer needed.
"""
def __init__(self, file, name):
self.file = file
self.name = name
self.close_called = False
def __getattr__(self, name):
file = self.__dict__['file']
a = getattr(file, name)
if type(a) != type(0):
setattr(self, name, a)
return a
# NT provides delete-on-close as a primitive, so we don't need
# the wrapper to do anything special. We still use it so that
# file.name is useful (i.e. not "(fdopen)") with NamedTemporaryFile.
if _os.name != 'nt':
# Cache the unlinker so we don't get spurious errors at
# shutdown when the module-level "os" is None'd out. Note
# that this must be referenced as self.unlink, because the
# name TemporaryFileWrapper may also get None'd out before
# __del__ is called.
unlink = _os.unlink
def close(self):
if not self.close_called:
self.close_called = True
self.file.close()
self.unlink(self.name)
def __del__(self):
self.close()
def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
prefix=template, dir=None):
"""Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to os.fdopen (default "w+b").
'bufsize' -- the buffer size argument to os.fdopen (default -1).
The file is created as mkstemp() would do it.
Returns an object with a file-like interface; the name of the file
is accessible as file.name. The file will be automatically deleted
when it is closed.
"""
if dir is None:
dir = gettempdir()
if 'b' in mode:
flags = _bin_openflags
else:
flags = _text_openflags
# Setting O_TEMPORARY in the flags causes the OS to delete
# the file when it is closed. This is only supported by Windows.
if _os.name == 'nt':
flags |= _os.O_TEMPORARY
(fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
file = _os.fdopen(fd, mode, bufsize)
return _TemporaryFileWrapper(file, name)
if _os.name != 'posix' or _os.sys.platform == 'cygwin':
# On non-POSIX and Cygwin systems, assume that we cannot unlink a file
# while it is open.
TemporaryFile = NamedTemporaryFile
else:
def TemporaryFile(mode='w+b', bufsize=-1, suffix="",
prefix=template, dir=None):
"""Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'directory' -- as for mkstemp.
'mode' -- the mode argument to os.fdopen (default "w+b").
'bufsize' -- the buffer size argument to os.fdopen (default -1).
The file is created as mkstemp() would do it.
Returns an object with a file-like interface. The file has no
name, and will cease to exist when it is closed.
"""
if dir is None:
dir = gettempdir()
if 'b' in mode:
flags = _bin_openflags
else:
flags = _text_openflags
(fd, name) = _mkstemp_inner(dir, prefix, suffix, flags)
try:
_os.unlink(name)
return _os.fdopen(fd, mode, bufsize)
except:
_os.close(fd)
raise
| Python |
"""Utilities to get a password and/or the current user name.
getpass(prompt) - prompt for a password, with echo turned off
getuser() - get the user name from the environment or password database
On Windows, the msvcrt module will be used.
On the Mac EasyDialogs.AskPassword is used, if available.
"""
# Authors: Piers Lauder (original)
# Guido van Rossum (Windows support and cleanup)
import sys
__all__ = ["getpass","getuser"]
def unix_getpass(prompt='Password: '):
"""Prompt for a password, with echo turned off.
Restore terminal settings at end.
"""
try:
fd = sys.stdin.fileno()
except:
return default_getpass(prompt)
old = termios.tcgetattr(fd) # a copy to save
new = old[:]
new[3] = new[3] & ~termios.ECHO # 3 == 'lflags'
try:
termios.tcsetattr(fd, termios.TCSADRAIN, new)
passwd = _raw_input(prompt)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old)
sys.stdout.write('\n')
return passwd
def win_getpass(prompt='Password: '):
"""Prompt for password with echo off, using Windows getch()."""
if sys.stdin is not sys.__stdin__:
return default_getpass(prompt)
import msvcrt
for c in prompt:
msvcrt.putch(c)
pw = ""
while 1:
c = msvcrt.getch()
if c == '\r' or c == '\n':
break
if c == '\003':
raise KeyboardInterrupt
if c == '\b':
pw = pw[:-1]
else:
pw = pw + c
msvcrt.putch('\r')
msvcrt.putch('\n')
return pw
def default_getpass(prompt='Password: '):
print "Warning: Problem with getpass. Passwords may be echoed."
return _raw_input(prompt)
def _raw_input(prompt=""):
# A raw_input() replacement that doesn't save the string in the
# GNU readline history.
prompt = str(prompt)
if prompt:
sys.stdout.write(prompt)
line = sys.stdin.readline()
if not line:
raise EOFError
if line[-1] == '\n':
line = line[:-1]
return line
def getuser():
"""Get the username from the environment or password database.
First try various environment variables, then the password
database. This works on Windows as long as USERNAME is set.
"""
import os
for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
user = os.environ.get(name)
if user:
return user
# If this fails, the exception will "explain" why
import pwd
return pwd.getpwuid(os.getuid())[0]
# Bind the name getpass to the appropriate function
try:
import termios
# it's possible there is an incompatible termios from the
# McMillan Installer, make sure we have a UNIX-compatible termios
termios.tcgetattr, termios.tcsetattr
except (ImportError, AttributeError):
try:
import msvcrt
except ImportError:
try:
from EasyDialogs import AskPassword
except ImportError:
getpass = default_getpass
else:
getpass = AskPassword
else:
getpass = win_getpass
else:
getpass = unix_getpass
| Python |
""" codecs -- Python Codec Registry, API and helpers.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""#"
import __builtin__, sys
### Registry and builtin stateless codec functions
try:
from _codecs import *
except ImportError, why:
raise SystemError,\
'Failed to load the builtin codecs: %s' % why
__all__ = ["register", "lookup", "open", "EncodedFile", "BOM", "BOM_BE",
"BOM_LE", "BOM32_BE", "BOM32_LE", "BOM64_BE", "BOM64_LE",
"BOM_UTF8", "BOM_UTF16", "BOM_UTF16_LE", "BOM_UTF16_BE",
"BOM_UTF32", "BOM_UTF32_LE", "BOM_UTF32_BE",
"strict_errors", "ignore_errors", "replace_errors",
"xmlcharrefreplace_errors",
"register_error", "lookup_error"]
### Constants
#
# Byte Order Mark (BOM = ZERO WIDTH NO-BREAK SPACE = U+FEFF)
# and its possible byte string values
# for UTF8/UTF16/UTF32 output and little/big endian machines
#
# UTF-8
BOM_UTF8 = '\xef\xbb\xbf'
# UTF-16, little endian
BOM_LE = BOM_UTF16_LE = '\xff\xfe'
# UTF-16, big endian
BOM_BE = BOM_UTF16_BE = '\xfe\xff'
# UTF-32, little endian
BOM_UTF32_LE = '\xff\xfe\x00\x00'
# UTF-32, big endian
BOM_UTF32_BE = '\x00\x00\xfe\xff'
if sys.byteorder == 'little':
# UTF-16, native endianness
BOM = BOM_UTF16 = BOM_UTF16_LE
# UTF-32, native endianness
BOM_UTF32 = BOM_UTF32_LE
else:
# UTF-16, native endianness
BOM = BOM_UTF16 = BOM_UTF16_BE
# UTF-32, native endianness
BOM_UTF32 = BOM_UTF32_BE
# Old broken names (don't use in new code)
BOM32_LE = BOM_UTF16_LE
BOM32_BE = BOM_UTF16_BE
BOM64_LE = BOM_UTF32_LE
BOM64_BE = BOM_UTF32_BE
### Codec base classes (defining the API)
class Codec:
""" Defines the interface for stateless encoders/decoders.
The .encode()/.decode() methods may use different error
handling schemes by providing the errors argument. These
string values are predefined:
'strict' - raise a ValueError error (or a subclass)
'ignore' - ignore the character and continue with the next
'replace' - replace with a suitable replacement character;
Python will use the official U+FFFD REPLACEMENT
CHARACTER for the builtin Unicode codecs on
decoding and '?' on encoding.
'xmlcharrefreplace' - Replace with the appropriate XML
character reference (only for encoding).
'backslashreplace' - Replace with backslashed escape sequences
(only for encoding).
The set of allowed values can be extended via register_error.
"""
def encode(self, input, errors='strict'):
""" Encodes the object input and returns a tuple (output
object, length consumed).
errors defines the error handling to apply. It defaults to
'strict' handling.
The method may not store state in the Codec instance. Use
StreamCodec for codecs which have to keep state in order to
make encoding/decoding efficient.
The encoder must be able to handle zero length input and
return an empty object of the output object type in this
situation.
"""
raise NotImplementedError
def decode(self, input, errors='strict'):
""" Decodes the object input and returns a tuple (output
object, length consumed).
input must be an object which provides the bf_getreadbuf
buffer slot. Python strings, buffer objects and memory
mapped files are examples of objects providing this slot.
errors defines the error handling to apply. It defaults to
'strict' handling.
The method may not store state in the Codec instance. Use
StreamCodec for codecs which have to keep state in order to
make encoding/decoding efficient.
The decoder must be able to handle zero length input and
return an empty object of the output object type in this
situation.
"""
raise NotImplementedError
#
# The StreamWriter and StreamReader class provide generic working
# interfaces which can be used to implement new encoding submodules
# very easily. See encodings/utf_8.py for an example on how this is
# done.
#
class StreamWriter(Codec):
def __init__(self, stream, errors='strict'):
""" Creates a StreamWriter instance.
stream must be a file-like object open for writing
(binary) data.
The StreamWriter may use different error handling
schemes by providing the errors keyword argument. These
parameters are predefined:
'strict' - raise a ValueError (or a subclass)
'ignore' - ignore the character and continue with the next
'replace'- replace with a suitable replacement character
'xmlcharrefreplace' - Replace with the appropriate XML
character reference.
'backslashreplace' - Replace with backslashed escape
sequences (only for encoding).
The set of allowed parameter values can be extended via
register_error.
"""
self.stream = stream
self.errors = errors
def write(self, object):
""" Writes the object's contents encoded to self.stream.
"""
data, consumed = self.encode(object, self.errors)
self.stream.write(data)
def writelines(self, list):
""" Writes the concatenated list of strings to the stream
using .write().
"""
self.write(''.join(list))
def reset(self):
""" Flushes and resets the codec buffers used for keeping state.
Calling this method should ensure that the data on the
output is put into a clean state, that allows appending
of new fresh data without having to rescan the whole
stream to recover state.
"""
pass
def __getattr__(self, name,
getattr=getattr):
""" Inherit all other methods from the underlying stream.
"""
return getattr(self.stream, name)
###
class StreamReader(Codec):
def __init__(self, stream, errors='strict'):
""" Creates a StreamReader instance.
stream must be a file-like object open for reading
(binary) data.
The StreamReader may use different error handling
schemes by providing the errors keyword argument. These
parameters are predefined:
'strict' - raise a ValueError (or a subclass)
'ignore' - ignore the character and continue with the next
'replace'- replace with a suitable replacement character;
The set of allowed parameter values can be extended via
register_error.
"""
self.stream = stream
self.errors = errors
self.bytebuffer = ""
self.charbuffer = u""
self.atcr = False
def decode(self, input, errors='strict'):
raise NotImplementedError
def read(self, size=-1, chars=-1):
""" Decodes data from the stream self.stream and returns the
resulting object.
chars indicates the number of characters to read from the
stream. read() will never return more than chars
characters, but it might return less, if there are not enough
characters available.
size indicates the approximate maximum number of bytes to
read from the stream for decoding purposes. The decoder
can modify this setting as appropriate. The default value
-1 indicates to read and decode as much as possible. size
is intended to prevent having to decode huge files in one
step.
The method should use a greedy read strategy meaning that
it should read as much data as is allowed within the
definition of the encoding and the given size, e.g. if
optional encoding endings or state markers are available
on the stream, these should be read too.
"""
# read until we get the required number of characters (if available)
while True:
# can the request can be satisfied from the character buffer?
if chars < 0:
if self.charbuffer:
break
else:
if len(self.charbuffer) >= chars:
break
# we need more data
if size < 0:
newdata = self.stream.read()
else:
newdata = self.stream.read(size)
# decode bytes (those remaining from the last call included)
data = self.bytebuffer + newdata
newchars, decodedbytes = self.decode(data, self.errors)
# keep undecoded bytes until the next call
self.bytebuffer = data[decodedbytes:]
# put new characters in the character buffer
self.charbuffer += newchars
# there was no data available
if not newdata:
break
if chars < 0:
# Return everything we've got
result = self.charbuffer
self.charbuffer = u""
else:
# Return the first chars characters
result = self.charbuffer[:chars]
self.charbuffer = self.charbuffer[chars:]
return result
def readline(self, size=None, keepends=True):
""" Read one line from the input stream and return the
decoded data.
size, if given, is passed as size argument to the
read() method.
"""
readsize = size or 72
line = u""
# If size is given, we call read() only once
while True:
data = self.read(readsize)
if self.atcr and data.startswith(u"\n"):
data = data[1:]
if data:
self.atcr = data.endswith(u"\r")
line += data
lines = line.splitlines(True)
if lines:
line0withend = lines[0]
line0withoutend = lines[0].splitlines(False)[0]
if line0withend != line0withoutend: # We really have a line end
# Put the rest back together and keep it until the next call
self.charbuffer = u"".join(lines[1:]) + self.charbuffer
if keepends:
line = line0withend
else:
line = line0withoutend
break
# we didn't get anything or this was our only try
if not data or size is not None:
if line and not keepends:
line = line.splitlines(False)[0]
break
if readsize<8000:
readsize *= 2
return line
def readlines(self, sizehint=None, keepends=True):
""" Read all lines available on the input stream
and return them as list of lines.
Line breaks are implemented using the codec's decoder
method and are included in the list entries.
sizehint, if given, is ignored since there is no efficient
way to finding the true end-of-line.
"""
data = self.read()
return data.splitlines(keepends)
def reset(self):
""" Resets the codec buffers used for keeping state.
Note that no stream repositioning should take place.
This method is primarily intended to be able to recover
from decoding errors.
"""
self.bytebuffer = ""
self.charbuffer = u""
self.atcr = False
def seek(self, offset, whence=0):
""" Set the input stream's current position.
Resets the codec buffers used for keeping state.
"""
self.reset()
self.stream.seek(offset, whence)
def next(self):
""" Return the next decoded line from the input stream."""
line = self.readline()
if line:
return line
raise StopIteration
def __iter__(self):
return self
def __getattr__(self, name,
getattr=getattr):
""" Inherit all other methods from the underlying stream.
"""
return getattr(self.stream, name)
###
class StreamReaderWriter:
""" StreamReaderWriter instances allow wrapping streams which
work in both read and write modes.
The design is such that one can use the factory functions
returned by the codec.lookup() function to construct the
instance.
"""
# Optional attributes set by the file wrappers below
encoding = 'unknown'
def __init__(self, stream, Reader, Writer, errors='strict'):
""" Creates a StreamReaderWriter instance.
stream must be a Stream-like object.
Reader, Writer must be factory functions or classes
providing the StreamReader, StreamWriter interface resp.
Error handling is done in the same way as defined for the
StreamWriter/Readers.
"""
self.stream = stream
self.reader = Reader(stream, errors)
self.writer = Writer(stream, errors)
self.errors = errors
def read(self, size=-1):
return self.reader.read(size)
def readline(self, size=None):
return self.reader.readline(size)
def readlines(self, sizehint=None):
return self.reader.readlines(sizehint)
def next(self):
""" Return the next decoded line from the input stream."""
return self.reader.next()
def __iter__(self):
return self
def write(self, data):
return self.writer.write(data)
def writelines(self, list):
return self.writer.writelines(list)
def reset(self):
self.reader.reset()
self.writer.reset()
def __getattr__(self, name,
getattr=getattr):
""" Inherit all other methods from the underlying stream.
"""
return getattr(self.stream, name)
###
class StreamRecoder:
""" StreamRecoder instances provide a frontend - backend
view of encoding data.
They use the complete set of APIs returned by the
codecs.lookup() function to implement their task.
Data written to the stream is first decoded into an
intermediate format (which is dependent on the given codec
combination) and then written to the stream using an instance
of the provided Writer class.
In the other direction, data is read from the stream using a
Reader instance and then return encoded data to the caller.
"""
# Optional attributes set by the file wrappers below
data_encoding = 'unknown'
file_encoding = 'unknown'
def __init__(self, stream, encode, decode, Reader, Writer,
errors='strict'):
""" Creates a StreamRecoder instance which implements a two-way
conversion: encode and decode work on the frontend (the
input to .read() and output of .write()) while
Reader and Writer work on the backend (reading and
writing to the stream).
You can use these objects to do transparent direct
recodings from e.g. latin-1 to utf-8 and back.
stream must be a file-like object.
encode, decode must adhere to the Codec interface, Reader,
Writer must be factory functions or classes providing the
StreamReader, StreamWriter interface resp.
encode and decode are needed for the frontend translation,
Reader and Writer for the backend translation. Unicode is
used as intermediate encoding.
Error handling is done in the same way as defined for the
StreamWriter/Readers.
"""
self.stream = stream
self.encode = encode
self.decode = decode
self.reader = Reader(stream, errors)
self.writer = Writer(stream, errors)
self.errors = errors
def read(self, size=-1):
data = self.reader.read(size)
data, bytesencoded = self.encode(data, self.errors)
return data
def readline(self, size=None):
if size is None:
data = self.reader.readline()
else:
data = self.reader.readline(size)
data, bytesencoded = self.encode(data, self.errors)
return data
def readlines(self, sizehint=None):
data = self.reader.read()
data, bytesencoded = self.encode(data, self.errors)
return data.splitlines(1)
def next(self):
""" Return the next decoded line from the input stream."""
return self.reader.next()
def __iter__(self):
return self
def write(self, data):
data, bytesdecoded = self.decode(data, self.errors)
return self.writer.write(data)
def writelines(self, list):
data = ''.join(list)
data, bytesdecoded = self.decode(data, self.errors)
return self.writer.write(data)
def reset(self):
self.reader.reset()
self.writer.reset()
def __getattr__(self, name,
getattr=getattr):
""" Inherit all other methods from the underlying stream.
"""
return getattr(self.stream, name)
### Shortcuts
def open(filename, mode='rb', encoding=None, errors='strict', buffering=1):
""" Open an encoded file using the given mode and return
a wrapped version providing transparent encoding/decoding.
Note: The wrapped version will only accept the object format
defined by the codecs, i.e. Unicode objects for most builtin
codecs. Output is also codec dependent and will usually by
Unicode as well.
Files are always opened in binary mode, even if no binary mode
was specified. This is done to avoid data loss due to encodings
using 8-bit values. The default file mode is 'rb' meaning to
open the file in binary read mode.
encoding specifies the encoding which is to be used for the
file.
errors may be given to define the error handling. It defaults
to 'strict' which causes ValueErrors to be raised in case an
encoding error occurs.
buffering has the same meaning as for the builtin open() API.
It defaults to line buffered.
The returned wrapped file object provides an extra attribute
.encoding which allows querying the used encoding. This
attribute is only available if an encoding was specified as
parameter.
"""
if encoding is not None and \
'b' not in mode:
# Force opening of the file in binary mode
mode = mode + 'b'
file = __builtin__.open(filename, mode, buffering)
if encoding is None:
return file
(e, d, sr, sw) = lookup(encoding)
srw = StreamReaderWriter(file, sr, sw, errors)
# Add attributes to simplify introspection
srw.encoding = encoding
return srw
def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):
""" Return a wrapped version of file which provides transparent
encoding translation.
Strings written to the wrapped file are interpreted according
to the given data_encoding and then written to the original
file as string using file_encoding. The intermediate encoding
will usually be Unicode but depends on the specified codecs.
Strings are read from the file using file_encoding and then
passed back to the caller as string using data_encoding.
If file_encoding is not given, it defaults to data_encoding.
errors may be given to define the error handling. It defaults
to 'strict' which causes ValueErrors to be raised in case an
encoding error occurs.
The returned wrapped file object provides two extra attributes
.data_encoding and .file_encoding which reflect the given
parameters of the same name. The attributes can be used for
introspection by Python programs.
"""
if file_encoding is None:
file_encoding = data_encoding
encode, decode = lookup(data_encoding)[:2]
Reader, Writer = lookup(file_encoding)[2:]
sr = StreamRecoder(file,
encode, decode, Reader, Writer,
errors)
# Add attributes to simplify introspection
sr.data_encoding = data_encoding
sr.file_encoding = file_encoding
return sr
### Helpers for codec lookup
def getencoder(encoding):
""" Lookup up the codec for the given encoding and return
its encoder function.
Raises a LookupError in case the encoding cannot be found.
"""
return lookup(encoding)[0]
def getdecoder(encoding):
""" Lookup up the codec for the given encoding and return
its decoder function.
Raises a LookupError in case the encoding cannot be found.
"""
return lookup(encoding)[1]
def getreader(encoding):
""" Lookup up the codec for the given encoding and return
its StreamReader class or factory function.
Raises a LookupError in case the encoding cannot be found.
"""
return lookup(encoding)[2]
def getwriter(encoding):
""" Lookup up the codec for the given encoding and return
its StreamWriter class or factory function.
Raises a LookupError in case the encoding cannot be found.
"""
return lookup(encoding)[3]
### Helpers for charmap-based codecs
def make_identity_dict(rng):
""" make_identity_dict(rng) -> dict
Return a dictionary where elements of the rng sequence are
mapped to themselves.
"""
res = {}
for i in rng:
res[i]=i
return res
def make_encoding_map(decoding_map):
""" Creates an encoding map from a decoding map.
If a target mapping in the decoding map occurs multiple
times, then that target is mapped to None (undefined mapping),
causing an exception when encountered by the charmap codec
during translation.
One example where this happens is cp875.py which decodes
multiple character to \u001a.
"""
m = {}
for k,v in decoding_map.items():
if not v in m:
m[v] = k
else:
m[v] = None
return m
### error handlers
try:
strict_errors = lookup_error("strict")
ignore_errors = lookup_error("ignore")
replace_errors = lookup_error("replace")
xmlcharrefreplace_errors = lookup_error("xmlcharrefreplace")
backslashreplace_errors = lookup_error("backslashreplace")
except LookupError:
# In --disable-unicode builds, these error handler are missing
strict_errors = None
ignore_errors = None
replace_errors = None
xmlcharrefreplace_errors = None
backslashreplace_errors = None
# Tell modulefinder that using codecs probably needs the encodings
# package
_false = 0
if _false:
import encodings
### Tests
if __name__ == '__main__':
# Make stdout translate Latin-1 output into UTF-8 output
sys.stdout = EncodedFile(sys.stdout, 'latin-1', 'utf-8')
# Have stdin translate Latin-1 input into UTF-8 input
sys.stdin = EncodedFile(sys.stdin, 'utf-8', 'latin-1')
| Python |
'''"Executable documentation" for the pickle module.
Extensive comments about the pickle protocols and pickle-machine opcodes
can be found here. Some functions meant for external use:
genops(pickle)
Generate all the opcodes in a pickle, as (opcode, arg, position) triples.
dis(pickle, out=None, memo=None, indentlevel=4)
Print a symbolic disassembly of a pickle.
'''
__all__ = ['dis',
'genops',
]
# Other ideas:
#
# - A pickle verifier: read a pickle and check it exhaustively for
# well-formedness. dis() does a lot of this already.
#
# - A protocol identifier: examine a pickle and return its protocol number
# (== the highest .proto attr value among all the opcodes in the pickle).
# dis() already prints this info at the end.
#
# - A pickle optimizer: for example, tuple-building code is sometimes more
# elaborate than necessary, catering for the possibility that the tuple
# is recursive. Or lots of times a PUT is generated that's never accessed
# by a later GET.
"""
"A pickle" is a program for a virtual pickle machine (PM, but more accurately
called an unpickling machine). It's a sequence of opcodes, interpreted by the
PM, building an arbitrarily complex Python object.
For the most part, the PM is very simple: there are no looping, testing, or
conditional instructions, no arithmetic and no function calls. Opcodes are
executed once each, from first to last, until a STOP opcode is reached.
The PM has two data areas, "the stack" and "the memo".
Many opcodes push Python objects onto the stack; e.g., INT pushes a Python
integer object on the stack, whose value is gotten from a decimal string
literal immediately following the INT opcode in the pickle bytestream. Other
opcodes take Python objects off the stack. The result of unpickling is
whatever object is left on the stack when the final STOP opcode is executed.
The memo is simply an array of objects, or it can be implemented as a dict
mapping little integers to objects. The memo serves as the PM's "long term
memory", and the little integers indexing the memo are akin to variable
names. Some opcodes pop a stack object into the memo at a given index,
and others push a memo object at a given index onto the stack again.
At heart, that's all the PM has. Subtleties arise for these reasons:
+ Object identity. Objects can be arbitrarily complex, and subobjects
may be shared (for example, the list [a, a] refers to the same object a
twice). It can be vital that unpickling recreate an isomorphic object
graph, faithfully reproducing sharing.
+ Recursive objects. For example, after "L = []; L.append(L)", L is a
list, and L[0] is the same list. This is related to the object identity
point, and some sequences of pickle opcodes are subtle in order to
get the right result in all cases.
+ Things pickle doesn't know everything about. Examples of things pickle
does know everything about are Python's builtin scalar and container
types, like ints and tuples. They generally have opcodes dedicated to
them. For things like module references and instances of user-defined
classes, pickle's knowledge is limited. Historically, many enhancements
have been made to the pickle protocol in order to do a better (faster,
and/or more compact) job on those.
+ Backward compatibility and micro-optimization. As explained below,
pickle opcodes never go away, not even when better ways to do a thing
get invented. The repertoire of the PM just keeps growing over time.
For example, protocol 0 had two opcodes for building Python integers (INT
and LONG), protocol 1 added three more for more-efficient pickling of short
integers, and protocol 2 added two more for more-efficient pickling of
long integers (before protocol 2, the only ways to pickle a Python long
took time quadratic in the number of digits, for both pickling and
unpickling). "Opcode bloat" isn't so much a subtlety as a source of
wearying complication.
Pickle protocols:
For compatibility, the meaning of a pickle opcode never changes. Instead new
pickle opcodes get added, and each version's unpickler can handle all the
pickle opcodes in all protocol versions to date. So old pickles continue to
be readable forever. The pickler can generally be told to restrict itself to
the subset of opcodes available under previous protocol versions too, so that
users can create pickles under the current version readable by older
versions. However, a pickle does not contain its version number embedded
within it. If an older unpickler tries to read a pickle using a later
protocol, the result is most likely an exception due to seeing an unknown (in
the older unpickler) opcode.
The original pickle used what's now called "protocol 0", and what was called
"text mode" before Python 2.3. The entire pickle bytestream is made up of
printable 7-bit ASCII characters, plus the newline character, in protocol 0.
That's why it was called text mode. Protocol 0 is small and elegant, but
sometimes painfully inefficient.
The second major set of additions is now called "protocol 1", and was called
"binary mode" before Python 2.3. This added many opcodes with arguments
consisting of arbitrary bytes, including NUL bytes and unprintable "high bit"
bytes. Binary mode pickles can be substantially smaller than equivalent
text mode pickles, and sometimes faster too; e.g., BININT represents a 4-byte
int as 4 bytes following the opcode, which is cheaper to unpickle than the
(perhaps) 11-character decimal string attached to INT. Protocol 1 also added
a number of opcodes that operate on many stack elements at once (like APPENDS
and SETITEMS), and "shortcut" opcodes (like EMPTY_DICT and EMPTY_TUPLE).
The third major set of additions came in Python 2.3, and is called "protocol
2". This added:
- A better way to pickle instances of new-style classes (NEWOBJ).
- A way for a pickle to identify its protocol (PROTO).
- Time- and space- efficient pickling of long ints (LONG{1,4}).
- Shortcuts for small tuples (TUPLE{1,2,3}}.
- Dedicated opcodes for bools (NEWTRUE, NEWFALSE).
- The "extension registry", a vector of popular objects that can be pushed
efficiently by index (EXT{1,2,4}). This is akin to the memo and GET, but
the registry contents are predefined (there's nothing akin to the memo's
PUT).
Another independent change with Python 2.3 is the abandonment of any
pretense that it might be safe to load pickles received from untrusted
parties -- no sufficient security analysis has been done to guarantee
this and there isn't a use case that warrants the expense of such an
analysis.
To this end, all tests for __safe_for_unpickling__ or for
copy_reg.safe_constructors are removed from the unpickling code.
References to these variables in the descriptions below are to be seen
as describing unpickling in Python 2.2 and before.
"""
# Meta-rule: Descriptions are stored in instances of descriptor objects,
# with plain constructors. No meta-language is defined from which
# descriptors could be constructed. If you want, e.g., XML, write a little
# program to generate XML from the objects.
##############################################################################
# Some pickle opcodes have an argument, following the opcode in the
# bytestream. An argument is of a specific type, described by an instance
# of ArgumentDescriptor. These are not to be confused with arguments taken
# off the stack -- ArgumentDescriptor applies only to arguments embedded in
# the opcode stream, immediately following an opcode.
# Represents the number of bytes consumed by an argument delimited by the
# next newline character.
UP_TO_NEWLINE = -1
# Represents the number of bytes consumed by a two-argument opcode where
# the first argument gives the number of bytes in the second argument.
TAKEN_FROM_ARGUMENT1 = -2 # num bytes is 1-byte unsigned int
TAKEN_FROM_ARGUMENT4 = -3 # num bytes is 4-byte signed little-endian int
class ArgumentDescriptor(object):
__slots__ = (
# name of descriptor record, also a module global name; a string
'name',
# length of argument, in bytes; an int; UP_TO_NEWLINE and
# TAKEN_FROM_ARGUMENT{1,4} are negative values for variable-length
# cases
'n',
# a function taking a file-like object, reading this kind of argument
# from the object at the current position, advancing the current
# position by n bytes, and returning the value of the argument
'reader',
# human-readable docs for this arg descriptor; a string
'doc',
)
def __init__(self, name, n, reader, doc):
assert isinstance(name, str)
self.name = name
assert isinstance(n, int) and (n >= 0 or
n in (UP_TO_NEWLINE,
TAKEN_FROM_ARGUMENT1,
TAKEN_FROM_ARGUMENT4))
self.n = n
self.reader = reader
assert isinstance(doc, str)
self.doc = doc
from struct import unpack as _unpack
def read_uint1(f):
r"""
>>> import StringIO
>>> read_uint1(StringIO.StringIO('\xff'))
255
"""
data = f.read(1)
if data:
return ord(data)
raise ValueError("not enough data in stream to read uint1")
uint1 = ArgumentDescriptor(
name='uint1',
n=1,
reader=read_uint1,
doc="One-byte unsigned integer.")
def read_uint2(f):
r"""
>>> import StringIO
>>> read_uint2(StringIO.StringIO('\xff\x00'))
255
>>> read_uint2(StringIO.StringIO('\xff\xff'))
65535
"""
data = f.read(2)
if len(data) == 2:
return _unpack("<H", data)[0]
raise ValueError("not enough data in stream to read uint2")
uint2 = ArgumentDescriptor(
name='uint2',
n=2,
reader=read_uint2,
doc="Two-byte unsigned integer, little-endian.")
def read_int4(f):
r"""
>>> import StringIO
>>> read_int4(StringIO.StringIO('\xff\x00\x00\x00'))
255
>>> read_int4(StringIO.StringIO('\x00\x00\x00\x80')) == -(2**31)
True
"""
data = f.read(4)
if len(data) == 4:
return _unpack("<i", data)[0]
raise ValueError("not enough data in stream to read int4")
int4 = ArgumentDescriptor(
name='int4',
n=4,
reader=read_int4,
doc="Four-byte signed integer, little-endian, 2's complement.")
def read_stringnl(f, decode=True, stripquotes=True):
r"""
>>> import StringIO
>>> read_stringnl(StringIO.StringIO("'abcd'\nefg\n"))
'abcd'
>>> read_stringnl(StringIO.StringIO("\n"))
Traceback (most recent call last):
...
ValueError: no string quotes around ''
>>> read_stringnl(StringIO.StringIO("\n"), stripquotes=False)
''
>>> read_stringnl(StringIO.StringIO("''\n"))
''
>>> read_stringnl(StringIO.StringIO('"abcd"'))
Traceback (most recent call last):
...
ValueError: no newline found when trying to read stringnl
Embedded escapes are undone in the result.
>>> read_stringnl(StringIO.StringIO(r"'a\n\\b\x00c\td'" + "\n'e'"))
'a\n\\b\x00c\td'
"""
data = f.readline()
if not data.endswith('\n'):
raise ValueError("no newline found when trying to read stringnl")
data = data[:-1] # lose the newline
if stripquotes:
for q in "'\"":
if data.startswith(q):
if not data.endswith(q):
raise ValueError("strinq quote %r not found at both "
"ends of %r" % (q, data))
data = data[1:-1]
break
else:
raise ValueError("no string quotes around %r" % data)
# I'm not sure when 'string_escape' was added to the std codecs; it's
# crazy not to use it if it's there.
if decode:
data = data.decode('string_escape')
return data
stringnl = ArgumentDescriptor(
name='stringnl',
n=UP_TO_NEWLINE,
reader=read_stringnl,
doc="""A newline-terminated string.
This is a repr-style string, with embedded escapes, and
bracketing quotes.
""")
def read_stringnl_noescape(f):
return read_stringnl(f, decode=False, stripquotes=False)
stringnl_noescape = ArgumentDescriptor(
name='stringnl_noescape',
n=UP_TO_NEWLINE,
reader=read_stringnl_noescape,
doc="""A newline-terminated string.
This is a str-style string, without embedded escapes,
or bracketing quotes. It should consist solely of
printable ASCII characters.
""")
def read_stringnl_noescape_pair(f):
r"""
>>> import StringIO
>>> read_stringnl_noescape_pair(StringIO.StringIO("Queue\nEmpty\njunk"))
'Queue Empty'
"""
return "%s %s" % (read_stringnl_noescape(f), read_stringnl_noescape(f))
stringnl_noescape_pair = ArgumentDescriptor(
name='stringnl_noescape_pair',
n=UP_TO_NEWLINE,
reader=read_stringnl_noescape_pair,
doc="""A pair of newline-terminated strings.
These are str-style strings, without embedded
escapes, or bracketing quotes. They should
consist solely of printable ASCII characters.
The pair is returned as a single string, with
a single blank separating the two strings.
""")
def read_string4(f):
r"""
>>> import StringIO
>>> read_string4(StringIO.StringIO("\x00\x00\x00\x00abc"))
''
>>> read_string4(StringIO.StringIO("\x03\x00\x00\x00abcdef"))
'abc'
>>> read_string4(StringIO.StringIO("\x00\x00\x00\x03abcdef"))
Traceback (most recent call last):
...
ValueError: expected 50331648 bytes in a string4, but only 6 remain
"""
n = read_int4(f)
if n < 0:
raise ValueError("string4 byte count < 0: %d" % n)
data = f.read(n)
if len(data) == n:
return data
raise ValueError("expected %d bytes in a string4, but only %d remain" %
(n, len(data)))
string4 = ArgumentDescriptor(
name="string4",
n=TAKEN_FROM_ARGUMENT4,
reader=read_string4,
doc="""A counted string.
The first argument is a 4-byte little-endian signed int giving
the number of bytes in the string, and the second argument is
that many bytes.
""")
def read_string1(f):
r"""
>>> import StringIO
>>> read_string1(StringIO.StringIO("\x00"))
''
>>> read_string1(StringIO.StringIO("\x03abcdef"))
'abc'
"""
n = read_uint1(f)
assert n >= 0
data = f.read(n)
if len(data) == n:
return data
raise ValueError("expected %d bytes in a string1, but only %d remain" %
(n, len(data)))
string1 = ArgumentDescriptor(
name="string1",
n=TAKEN_FROM_ARGUMENT1,
reader=read_string1,
doc="""A counted string.
The first argument is a 1-byte unsigned int giving the number
of bytes in the string, and the second argument is that many
bytes.
""")
def read_unicodestringnl(f):
r"""
>>> import StringIO
>>> read_unicodestringnl(StringIO.StringIO("abc\uabcd\njunk"))
u'abc\uabcd'
"""
data = f.readline()
if not data.endswith('\n'):
raise ValueError("no newline found when trying to read "
"unicodestringnl")
data = data[:-1] # lose the newline
return unicode(data, 'raw-unicode-escape')
unicodestringnl = ArgumentDescriptor(
name='unicodestringnl',
n=UP_TO_NEWLINE,
reader=read_unicodestringnl,
doc="""A newline-terminated Unicode string.
This is raw-unicode-escape encoded, so consists of
printable ASCII characters, and may contain embedded
escape sequences.
""")
def read_unicodestring4(f):
r"""
>>> import StringIO
>>> s = u'abcd\uabcd'
>>> enc = s.encode('utf-8')
>>> enc
'abcd\xea\xaf\x8d'
>>> n = chr(len(enc)) + chr(0) * 3 # little-endian 4-byte length
>>> t = read_unicodestring4(StringIO.StringIO(n + enc + 'junk'))
>>> s == t
True
>>> read_unicodestring4(StringIO.StringIO(n + enc[:-1]))
Traceback (most recent call last):
...
ValueError: expected 7 bytes in a unicodestring4, but only 6 remain
"""
n = read_int4(f)
if n < 0:
raise ValueError("unicodestring4 byte count < 0: %d" % n)
data = f.read(n)
if len(data) == n:
return unicode(data, 'utf-8')
raise ValueError("expected %d bytes in a unicodestring4, but only %d "
"remain" % (n, len(data)))
unicodestring4 = ArgumentDescriptor(
name="unicodestring4",
n=TAKEN_FROM_ARGUMENT4,
reader=read_unicodestring4,
doc="""A counted Unicode string.
The first argument is a 4-byte little-endian signed int
giving the number of bytes in the string, and the second
argument-- the UTF-8 encoding of the Unicode string --
contains that many bytes.
""")
def read_decimalnl_short(f):
r"""
>>> import StringIO
>>> read_decimalnl_short(StringIO.StringIO("1234\n56"))
1234
>>> read_decimalnl_short(StringIO.StringIO("1234L\n56"))
Traceback (most recent call last):
...
ValueError: trailing 'L' not allowed in '1234L'
"""
s = read_stringnl(f, decode=False, stripquotes=False)
if s.endswith("L"):
raise ValueError("trailing 'L' not allowed in %r" % s)
# It's not necessarily true that the result fits in a Python short int:
# the pickle may have been written on a 64-bit box. There's also a hack
# for True and False here.
if s == "00":
return False
elif s == "01":
return True
try:
return int(s)
except OverflowError:
return long(s)
def read_decimalnl_long(f):
r"""
>>> import StringIO
>>> read_decimalnl_long(StringIO.StringIO("1234\n56"))
Traceback (most recent call last):
...
ValueError: trailing 'L' required in '1234'
Someday the trailing 'L' will probably go away from this output.
>>> read_decimalnl_long(StringIO.StringIO("1234L\n56"))
1234L
>>> read_decimalnl_long(StringIO.StringIO("123456789012345678901234L\n6"))
123456789012345678901234L
"""
s = read_stringnl(f, decode=False, stripquotes=False)
if not s.endswith("L"):
raise ValueError("trailing 'L' required in %r" % s)
return long(s)
decimalnl_short = ArgumentDescriptor(
name='decimalnl_short',
n=UP_TO_NEWLINE,
reader=read_decimalnl_short,
doc="""A newline-terminated decimal integer literal.
This never has a trailing 'L', and the integer fit
in a short Python int on the box where the pickle
was written -- but there's no guarantee it will fit
in a short Python int on the box where the pickle
is read.
""")
decimalnl_long = ArgumentDescriptor(
name='decimalnl_long',
n=UP_TO_NEWLINE,
reader=read_decimalnl_long,
doc="""A newline-terminated decimal integer literal.
This has a trailing 'L', and can represent integers
of any size.
""")
def read_floatnl(f):
r"""
>>> import StringIO
>>> read_floatnl(StringIO.StringIO("-1.25\n6"))
-1.25
"""
s = read_stringnl(f, decode=False, stripquotes=False)
return float(s)
floatnl = ArgumentDescriptor(
name='floatnl',
n=UP_TO_NEWLINE,
reader=read_floatnl,
doc="""A newline-terminated decimal floating literal.
In general this requires 17 significant digits for roundtrip
identity, and pickling then unpickling infinities, NaNs, and
minus zero doesn't work across boxes, or on some boxes even
on itself (e.g., Windows can't read the strings it produces
for infinities or NaNs).
""")
def read_float8(f):
r"""
>>> import StringIO, struct
>>> raw = struct.pack(">d", -1.25)
>>> raw
'\xbf\xf4\x00\x00\x00\x00\x00\x00'
>>> read_float8(StringIO.StringIO(raw + "\n"))
-1.25
"""
data = f.read(8)
if len(data) == 8:
return _unpack(">d", data)[0]
raise ValueError("not enough data in stream to read float8")
float8 = ArgumentDescriptor(
name='float8',
n=8,
reader=read_float8,
doc="""An 8-byte binary representation of a float, big-endian.
The format is unique to Python, and shared with the struct
module (format string '>d') "in theory" (the struct and cPickle
implementations don't share the code -- they should). It's
strongly related to the IEEE-754 double format, and, in normal
cases, is in fact identical to the big-endian 754 double format.
On other boxes the dynamic range is limited to that of a 754
double, and "add a half and chop" rounding is used to reduce
the precision to 53 bits. However, even on a 754 box,
infinities, NaNs, and minus zero may not be handled correctly
(may not survive roundtrip pickling intact).
""")
# Protocol 2 formats
from pickle import decode_long
def read_long1(f):
r"""
>>> import StringIO
>>> read_long1(StringIO.StringIO("\x00"))
0L
>>> read_long1(StringIO.StringIO("\x02\xff\x00"))
255L
>>> read_long1(StringIO.StringIO("\x02\xff\x7f"))
32767L
>>> read_long1(StringIO.StringIO("\x02\x00\xff"))
-256L
>>> read_long1(StringIO.StringIO("\x02\x00\x80"))
-32768L
"""
n = read_uint1(f)
data = f.read(n)
if len(data) != n:
raise ValueError("not enough data in stream to read long1")
return decode_long(data)
long1 = ArgumentDescriptor(
name="long1",
n=TAKEN_FROM_ARGUMENT1,
reader=read_long1,
doc="""A binary long, little-endian, using 1-byte size.
This first reads one byte as an unsigned size, then reads that
many bytes and interprets them as a little-endian 2's-complement long.
If the size is 0, that's taken as a shortcut for the long 0L.
""")
def read_long4(f):
r"""
>>> import StringIO
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00"))
255L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f"))
32767L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff"))
-256L
>>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80"))
-32768L
>>> read_long1(StringIO.StringIO("\x00\x00\x00\x00"))
0L
"""
n = read_int4(f)
if n < 0:
raise ValueError("long4 byte count < 0: %d" % n)
data = f.read(n)
if len(data) != n:
raise ValueError("not enough data in stream to read long4")
return decode_long(data)
long4 = ArgumentDescriptor(
name="long4",
n=TAKEN_FROM_ARGUMENT4,
reader=read_long4,
doc="""A binary representation of a long, little-endian.
This first reads four bytes as a signed size (but requires the
size to be >= 0), then reads that many bytes and interprets them
as a little-endian 2's-complement long. If the size is 0, that's taken
as a shortcut for the long 0L, although LONG1 should really be used
then instead (and in any case where # of bytes < 256).
""")
##############################################################################
# Object descriptors. The stack used by the pickle machine holds objects,
# and in the stack_before and stack_after attributes of OpcodeInfo
# descriptors we need names to describe the various types of objects that can
# appear on the stack.
class StackObject(object):
__slots__ = (
# name of descriptor record, for info only
'name',
# type of object, or tuple of type objects (meaning the object can
# be of any type in the tuple)
'obtype',
# human-readable docs for this kind of stack object; a string
'doc',
)
def __init__(self, name, obtype, doc):
assert isinstance(name, str)
self.name = name
assert isinstance(obtype, type) or isinstance(obtype, tuple)
if isinstance(obtype, tuple):
for contained in obtype:
assert isinstance(contained, type)
self.obtype = obtype
assert isinstance(doc, str)
self.doc = doc
def __repr__(self):
return self.name
pyint = StackObject(
name='int',
obtype=int,
doc="A short (as opposed to long) Python integer object.")
pylong = StackObject(
name='long',
obtype=long,
doc="A long (as opposed to short) Python integer object.")
pyinteger_or_bool = StackObject(
name='int_or_bool',
obtype=(int, long, bool),
doc="A Python integer object (short or long), or "
"a Python bool.")
pybool = StackObject(
name='bool',
obtype=(bool,),
doc="A Python bool object.")
pyfloat = StackObject(
name='float',
obtype=float,
doc="A Python float object.")
pystring = StackObject(
name='str',
obtype=str,
doc="A Python string object.")
pyunicode = StackObject(
name='unicode',
obtype=unicode,
doc="A Python Unicode string object.")
pynone = StackObject(
name="None",
obtype=type(None),
doc="The Python None object.")
pytuple = StackObject(
name="tuple",
obtype=tuple,
doc="A Python tuple object.")
pylist = StackObject(
name="list",
obtype=list,
doc="A Python list object.")
pydict = StackObject(
name="dict",
obtype=dict,
doc="A Python dict object.")
anyobject = StackObject(
name='any',
obtype=object,
doc="Any kind of object whatsoever.")
markobject = StackObject(
name="mark",
obtype=StackObject,
doc="""'The mark' is a unique object.
Opcodes that operate on a variable number of objects
generally don't embed the count of objects in the opcode,
or pull it off the stack. Instead the MARK opcode is used
to push a special marker object on the stack, and then
some other opcodes grab all the objects from the top of
the stack down to (but not including) the topmost marker
object.
""")
stackslice = StackObject(
name="stackslice",
obtype=StackObject,
doc="""An object representing a contiguous slice of the stack.
This is used in conjuction with markobject, to represent all
of the stack following the topmost markobject. For example,
the POP_MARK opcode changes the stack from
[..., markobject, stackslice]
to
[...]
No matter how many object are on the stack after the topmost
markobject, POP_MARK gets rid of all of them (including the
topmost markobject too).
""")
##############################################################################
# Descriptors for pickle opcodes.
class OpcodeInfo(object):
__slots__ = (
# symbolic name of opcode; a string
'name',
# the code used in a bytestream to represent the opcode; a
# one-character string
'code',
# If the opcode has an argument embedded in the byte string, an
# instance of ArgumentDescriptor specifying its type. Note that
# arg.reader(s) can be used to read and decode the argument from
# the bytestream s, and arg.doc documents the format of the raw
# argument bytes. If the opcode doesn't have an argument embedded
# in the bytestream, arg should be None.
'arg',
# what the stack looks like before this opcode runs; a list
'stack_before',
# what the stack looks like after this opcode runs; a list
'stack_after',
# the protocol number in which this opcode was introduced; an int
'proto',
# human-readable docs for this opcode; a string
'doc',
)
def __init__(self, name, code, arg,
stack_before, stack_after, proto, doc):
assert isinstance(name, str)
self.name = name
assert isinstance(code, str)
assert len(code) == 1
self.code = code
assert arg is None or isinstance(arg, ArgumentDescriptor)
self.arg = arg
assert isinstance(stack_before, list)
for x in stack_before:
assert isinstance(x, StackObject)
self.stack_before = stack_before
assert isinstance(stack_after, list)
for x in stack_after:
assert isinstance(x, StackObject)
self.stack_after = stack_after
assert isinstance(proto, int) and 0 <= proto <= 2
self.proto = proto
assert isinstance(doc, str)
self.doc = doc
I = OpcodeInfo
opcodes = [
# Ways to spell integers.
I(name='INT',
code='I',
arg=decimalnl_short,
stack_before=[],
stack_after=[pyinteger_or_bool],
proto=0,
doc="""Push an integer or bool.
The argument is a newline-terminated decimal literal string.
The intent may have been that this always fit in a short Python int,
but INT can be generated in pickles written on a 64-bit box that
require a Python long on a 32-bit box. The difference between this
and LONG then is that INT skips a trailing 'L', and produces a short
int whenever possible.
Another difference is due to that, when bool was introduced as a
distinct type in 2.3, builtin names True and False were also added to
2.2.2, mapping to ints 1 and 0. For compatibility in both directions,
True gets pickled as INT + "I01\\n", and False as INT + "I00\\n".
Leading zeroes are never produced for a genuine integer. The 2.3
(and later) unpicklers special-case these and return bool instead;
earlier unpicklers ignore the leading "0" and return the int.
"""),
I(name='BININT',
code='J',
arg=int4,
stack_before=[],
stack_after=[pyint],
proto=1,
doc="""Push a four-byte signed integer.
This handles the full range of Python (short) integers on a 32-bit
box, directly as binary bytes (1 for the opcode and 4 for the integer).
If the integer is non-negative and fits in 1 or 2 bytes, pickling via
BININT1 or BININT2 saves space.
"""),
I(name='BININT1',
code='K',
arg=uint1,
stack_before=[],
stack_after=[pyint],
proto=1,
doc="""Push a one-byte unsigned integer.
This is a space optimization for pickling very small non-negative ints,
in range(256).
"""),
I(name='BININT2',
code='M',
arg=uint2,
stack_before=[],
stack_after=[pyint],
proto=1,
doc="""Push a two-byte unsigned integer.
This is a space optimization for pickling small positive ints, in
range(256, 2**16). Integers in range(256) can also be pickled via
BININT2, but BININT1 instead saves a byte.
"""),
I(name='LONG',
code='L',
arg=decimalnl_long,
stack_before=[],
stack_after=[pylong],
proto=0,
doc="""Push a long integer.
The same as INT, except that the literal ends with 'L', and always
unpickles to a Python long. There doesn't seem a real purpose to the
trailing 'L'.
Note that LONG takes time quadratic in the number of digits when
unpickling (this is simply due to the nature of decimal->binary
conversion). Proto 2 added linear-time (in C; still quadratic-time
in Python) LONG1 and LONG4 opcodes.
"""),
I(name="LONG1",
code='\x8a',
arg=long1,
stack_before=[],
stack_after=[pylong],
proto=2,
doc="""Long integer using one-byte length.
A more efficient encoding of a Python long; the long1 encoding
says it all."""),
I(name="LONG4",
code='\x8b',
arg=long4,
stack_before=[],
stack_after=[pylong],
proto=2,
doc="""Long integer using found-byte length.
A more efficient encoding of a Python long; the long4 encoding
says it all."""),
# Ways to spell strings (8-bit, not Unicode).
I(name='STRING',
code='S',
arg=stringnl,
stack_before=[],
stack_after=[pystring],
proto=0,
doc="""Push a Python string object.
The argument is a repr-style string, with bracketing quote characters,
and perhaps embedded escapes. The argument extends until the next
newline character.
"""),
I(name='BINSTRING',
code='T',
arg=string4,
stack_before=[],
stack_after=[pystring],
proto=1,
doc="""Push a Python string object.
There are two arguments: the first is a 4-byte little-endian signed int
giving the number of bytes in the string, and the second is that many
bytes, which are taken literally as the string content.
"""),
I(name='SHORT_BINSTRING',
code='U',
arg=string1,
stack_before=[],
stack_after=[pystring],
proto=1,
doc="""Push a Python string object.
There are two arguments: the first is a 1-byte unsigned int giving
the number of bytes in the string, and the second is that many bytes,
which are taken literally as the string content.
"""),
# Ways to spell None.
I(name='NONE',
code='N',
arg=None,
stack_before=[],
stack_after=[pynone],
proto=0,
doc="Push None on the stack."),
# Ways to spell bools, starting with proto 2. See INT for how this was
# done before proto 2.
I(name='NEWTRUE',
code='\x88',
arg=None,
stack_before=[],
stack_after=[pybool],
proto=2,
doc="""True.
Push True onto the stack."""),
I(name='NEWFALSE',
code='\x89',
arg=None,
stack_before=[],
stack_after=[pybool],
proto=2,
doc="""True.
Push False onto the stack."""),
# Ways to spell Unicode strings.
I(name='UNICODE',
code='V',
arg=unicodestringnl,
stack_before=[],
stack_after=[pyunicode],
proto=0, # this may be pure-text, but it's a later addition
doc="""Push a Python Unicode string object.
The argument is a raw-unicode-escape encoding of a Unicode string,
and so may contain embedded escape sequences. The argument extends
until the next newline character.
"""),
I(name='BINUNICODE',
code='X',
arg=unicodestring4,
stack_before=[],
stack_after=[pyunicode],
proto=1,
doc="""Push a Python Unicode string object.
There are two arguments: the first is a 4-byte little-endian signed int
giving the number of bytes in the string. The second is that many
bytes, and is the UTF-8 encoding of the Unicode string.
"""),
# Ways to spell floats.
I(name='FLOAT',
code='F',
arg=floatnl,
stack_before=[],
stack_after=[pyfloat],
proto=0,
doc="""Newline-terminated decimal float literal.
The argument is repr(a_float), and in general requires 17 significant
digits for roundtrip conversion to be an identity (this is so for
IEEE-754 double precision values, which is what Python float maps to
on most boxes).
In general, FLOAT cannot be used to transport infinities, NaNs, or
minus zero across boxes (or even on a single box, if the platform C
library can't read the strings it produces for such things -- Windows
is like that), but may do less damage than BINFLOAT on boxes with
greater precision or dynamic range than IEEE-754 double.
"""),
I(name='BINFLOAT',
code='G',
arg=float8,
stack_before=[],
stack_after=[pyfloat],
proto=1,
doc="""Float stored in binary form, with 8 bytes of data.
This generally requires less than half the space of FLOAT encoding.
In general, BINFLOAT cannot be used to transport infinities, NaNs, or
minus zero, raises an exception if the exponent exceeds the range of
an IEEE-754 double, and retains no more than 53 bits of precision (if
there are more than that, "add a half and chop" rounding is used to
cut it back to 53 significant bits).
"""),
# Ways to build lists.
I(name='EMPTY_LIST',
code=']',
arg=None,
stack_before=[],
stack_after=[pylist],
proto=1,
doc="Push an empty list."),
I(name='APPEND',
code='a',
arg=None,
stack_before=[pylist, anyobject],
stack_after=[pylist],
proto=0,
doc="""Append an object to a list.
Stack before: ... pylist anyobject
Stack after: ... pylist+[anyobject]
although pylist is really extended in-place.
"""),
I(name='APPENDS',
code='e',
arg=None,
stack_before=[pylist, markobject, stackslice],
stack_after=[pylist],
proto=1,
doc="""Extend a list by a slice of stack objects.
Stack before: ... pylist markobject stackslice
Stack after: ... pylist+stackslice
although pylist is really extended in-place.
"""),
I(name='LIST',
code='l',
arg=None,
stack_before=[markobject, stackslice],
stack_after=[pylist],
proto=0,
doc="""Build a list out of the topmost stack slice, after markobject.
All the stack entries following the topmost markobject are placed into
a single Python list, which single list object replaces all of the
stack from the topmost markobject onward. For example,
Stack before: ... markobject 1 2 3 'abc'
Stack after: ... [1, 2, 3, 'abc']
"""),
# Ways to build tuples.
I(name='EMPTY_TUPLE',
code=')',
arg=None,
stack_before=[],
stack_after=[pytuple],
proto=1,
doc="Push an empty tuple."),
I(name='TUPLE',
code='t',
arg=None,
stack_before=[markobject, stackslice],
stack_after=[pytuple],
proto=0,
doc="""Build a tuple out of the topmost stack slice, after markobject.
All the stack entries following the topmost markobject are placed into
a single Python tuple, which single tuple object replaces all of the
stack from the topmost markobject onward. For example,
Stack before: ... markobject 1 2 3 'abc'
Stack after: ... (1, 2, 3, 'abc')
"""),
I(name='TUPLE1',
code='\x85',
arg=None,
stack_before=[anyobject],
stack_after=[pytuple],
proto=2,
doc="""One-tuple.
This code pops one value off the stack and pushes a tuple of
length 1 whose one item is that value back onto it. IOW:
stack[-1] = tuple(stack[-1:])
"""),
I(name='TUPLE2',
code='\x86',
arg=None,
stack_before=[anyobject, anyobject],
stack_after=[pytuple],
proto=2,
doc="""One-tuple.
This code pops two values off the stack and pushes a tuple
of length 2 whose items are those values back onto it. IOW:
stack[-2:] = [tuple(stack[-2:])]
"""),
I(name='TUPLE3',
code='\x87',
arg=None,
stack_before=[anyobject, anyobject, anyobject],
stack_after=[pytuple],
proto=2,
doc="""One-tuple.
This code pops three values off the stack and pushes a tuple
of length 3 whose items are those values back onto it. IOW:
stack[-3:] = [tuple(stack[-3:])]
"""),
# Ways to build dicts.
I(name='EMPTY_DICT',
code='}',
arg=None,
stack_before=[],
stack_after=[pydict],
proto=1,
doc="Push an empty dict."),
I(name='DICT',
code='d',
arg=None,
stack_before=[markobject, stackslice],
stack_after=[pydict],
proto=0,
doc="""Build a dict out of the topmost stack slice, after markobject.
All the stack entries following the topmost markobject are placed into
a single Python dict, which single dict object replaces all of the
stack from the topmost markobject onward. The stack slice alternates
key, value, key, value, .... For example,
Stack before: ... markobject 1 2 3 'abc'
Stack after: ... {1: 2, 3: 'abc'}
"""),
I(name='SETITEM',
code='s',
arg=None,
stack_before=[pydict, anyobject, anyobject],
stack_after=[pydict],
proto=0,
doc="""Add a key+value pair to an existing dict.
Stack before: ... pydict key value
Stack after: ... pydict
where pydict has been modified via pydict[key] = value.
"""),
I(name='SETITEMS',
code='u',
arg=None,
stack_before=[pydict, markobject, stackslice],
stack_after=[pydict],
proto=1,
doc="""Add an arbitrary number of key+value pairs to an existing dict.
The slice of the stack following the topmost markobject is taken as
an alternating sequence of keys and values, added to the dict
immediately under the topmost markobject. Everything at and after the
topmost markobject is popped, leaving the mutated dict at the top
of the stack.
Stack before: ... pydict markobject key_1 value_1 ... key_n value_n
Stack after: ... pydict
where pydict has been modified via pydict[key_i] = value_i for i in
1, 2, ..., n, and in that order.
"""),
# Stack manipulation.
I(name='POP',
code='0',
arg=None,
stack_before=[anyobject],
stack_after=[],
proto=0,
doc="Discard the top stack item, shrinking the stack by one item."),
I(name='DUP',
code='2',
arg=None,
stack_before=[anyobject],
stack_after=[anyobject, anyobject],
proto=0,
doc="Push the top stack item onto the stack again, duplicating it."),
I(name='MARK',
code='(',
arg=None,
stack_before=[],
stack_after=[markobject],
proto=0,
doc="""Push markobject onto the stack.
markobject is a unique object, used by other opcodes to identify a
region of the stack containing a variable number of objects for them
to work on. See markobject.doc for more detail.
"""),
I(name='POP_MARK',
code='1',
arg=None,
stack_before=[markobject, stackslice],
stack_after=[],
proto=0,
doc="""Pop all the stack objects at and above the topmost markobject.
When an opcode using a variable number of stack objects is done,
POP_MARK is used to remove those objects, and to remove the markobject
that delimited their starting position on the stack.
"""),
# Memo manipulation. There are really only two operations (get and put),
# each in all-text, "short binary", and "long binary" flavors.
I(name='GET',
code='g',
arg=decimalnl_short,
stack_before=[],
stack_after=[anyobject],
proto=0,
doc="""Read an object from the memo and push it on the stack.
The index of the memo object to push is given by the newline-teriminated
decimal string following. BINGET and LONG_BINGET are space-optimized
versions.
"""),
I(name='BINGET',
code='h',
arg=uint1,
stack_before=[],
stack_after=[anyobject],
proto=1,
doc="""Read an object from the memo and push it on the stack.
The index of the memo object to push is given by the 1-byte unsigned
integer following.
"""),
I(name='LONG_BINGET',
code='j',
arg=int4,
stack_before=[],
stack_after=[anyobject],
proto=1,
doc="""Read an object from the memo and push it on the stack.
The index of the memo object to push is given by the 4-byte signed
little-endian integer following.
"""),
I(name='PUT',
code='p',
arg=decimalnl_short,
stack_before=[],
stack_after=[],
proto=0,
doc="""Store the stack top into the memo. The stack is not popped.
The index of the memo location to write into is given by the newline-
terminated decimal string following. BINPUT and LONG_BINPUT are
space-optimized versions.
"""),
I(name='BINPUT',
code='q',
arg=uint1,
stack_before=[],
stack_after=[],
proto=1,
doc="""Store the stack top into the memo. The stack is not popped.
The index of the memo location to write into is given by the 1-byte
unsigned integer following.
"""),
I(name='LONG_BINPUT',
code='r',
arg=int4,
stack_before=[],
stack_after=[],
proto=1,
doc="""Store the stack top into the memo. The stack is not popped.
The index of the memo location to write into is given by the 4-byte
signed little-endian integer following.
"""),
# Access the extension registry (predefined objects). Akin to the GET
# family.
I(name='EXT1',
code='\x82',
arg=uint1,
stack_before=[],
stack_after=[anyobject],
proto=2,
doc="""Extension code.
This code and the similar EXT2 and EXT4 allow using a registry
of popular objects that are pickled by name, typically classes.
It is envisioned that through a global negotiation and
registration process, third parties can set up a mapping between
ints and object names.
In order to guarantee pickle interchangeability, the extension
code registry ought to be global, although a range of codes may
be reserved for private use.
EXT1 has a 1-byte integer argument. This is used to index into the
extension registry, and the object at that index is pushed on the stack.
"""),
I(name='EXT2',
code='\x83',
arg=uint2,
stack_before=[],
stack_after=[anyobject],
proto=2,
doc="""Extension code.
See EXT1. EXT2 has a two-byte integer argument.
"""),
I(name='EXT4',
code='\x84',
arg=int4,
stack_before=[],
stack_after=[anyobject],
proto=2,
doc="""Extension code.
See EXT1. EXT4 has a four-byte integer argument.
"""),
# Push a class object, or module function, on the stack, via its module
# and name.
I(name='GLOBAL',
code='c',
arg=stringnl_noescape_pair,
stack_before=[],
stack_after=[anyobject],
proto=0,
doc="""Push a global object (module.attr) on the stack.
Two newline-terminated strings follow the GLOBAL opcode. The first is
taken as a module name, and the second as a class name. The class
object module.class is pushed on the stack. More accurately, the
object returned by self.find_class(module, class) is pushed on the
stack, so unpickling subclasses can override this form of lookup.
"""),
# Ways to build objects of classes pickle doesn't know about directly
# (user-defined classes). I despair of documenting this accurately
# and comprehensibly -- you really have to read the pickle code to
# find all the special cases.
I(name='REDUCE',
code='R',
arg=None,
stack_before=[anyobject, anyobject],
stack_after=[anyobject],
proto=0,
doc="""Push an object built from a callable and an argument tuple.
The opcode is named to remind of the __reduce__() method.
Stack before: ... callable pytuple
Stack after: ... callable(*pytuple)
The callable and the argument tuple are the first two items returned
by a __reduce__ method. Applying the callable to the argtuple is
supposed to reproduce the original object, or at least get it started.
If the __reduce__ method returns a 3-tuple, the last component is an
argument to be passed to the object's __setstate__, and then the REDUCE
opcode is followed by code to create setstate's argument, and then a
BUILD opcode to apply __setstate__ to that argument.
There are lots of special cases here. The argtuple can be None, in
which case callable.__basicnew__() is called instead to produce the
object to be pushed on the stack. This appears to be a trick unique
to ExtensionClasses, and is deprecated regardless.
If type(callable) is not ClassType, REDUCE complains unless the
callable has been registered with the copy_reg module's
safe_constructors dict, or the callable has a magic
'__safe_for_unpickling__' attribute with a true value. I'm not sure
why it does this, but I've sure seen this complaint often enough when
I didn't want to <wink>.
"""),
I(name='BUILD',
code='b',
arg=None,
stack_before=[anyobject, anyobject],
stack_after=[anyobject],
proto=0,
doc="""Finish building an object, via __setstate__ or dict update.
Stack before: ... anyobject argument
Stack after: ... anyobject
where anyobject may have been mutated, as follows:
If the object has a __setstate__ method,
anyobject.__setstate__(argument)
is called.
Else the argument must be a dict, the object must have a __dict__, and
the object is updated via
anyobject.__dict__.update(argument)
This may raise RuntimeError in restricted execution mode (which
disallows access to __dict__ directly); in that case, the object
is updated instead via
for k, v in argument.items():
anyobject[k] = v
"""),
I(name='INST',
code='i',
arg=stringnl_noescape_pair,
stack_before=[markobject, stackslice],
stack_after=[anyobject],
proto=0,
doc="""Build a class instance.
This is the protocol 0 version of protocol 1's OBJ opcode.
INST is followed by two newline-terminated strings, giving a
module and class name, just as for the GLOBAL opcode (and see
GLOBAL for more details about that). self.find_class(module, name)
is used to get a class object.
In addition, all the objects on the stack following the topmost
markobject are gathered into a tuple and popped (along with the
topmost markobject), just as for the TUPLE opcode.
Now it gets complicated. If all of these are true:
+ The argtuple is empty (markobject was at the top of the stack
at the start).
+ It's an old-style class object (the type of the class object is
ClassType).
+ The class object does not have a __getinitargs__ attribute.
then we want to create an old-style class instance without invoking
its __init__() method (pickle has waffled on this over the years; not
calling __init__() is current wisdom). In this case, an instance of
an old-style dummy class is created, and then we try to rebind its
__class__ attribute to the desired class object. If this succeeds,
the new instance object is pushed on the stack, and we're done. In
restricted execution mode it can fail (assignment to __class__ is
disallowed), and I'm not really sure what happens then -- it looks
like the code ends up calling the class object's __init__ anyway,
via falling into the next case.
Else (the argtuple is not empty, it's not an old-style class object,
or the class object does have a __getinitargs__ attribute), the code
first insists that the class object have a __safe_for_unpickling__
attribute. Unlike as for the __safe_for_unpickling__ check in REDUCE,
it doesn't matter whether this attribute has a true or false value, it
only matters whether it exists (XXX this is a bug; cPickle
requires the attribute to be true). If __safe_for_unpickling__
doesn't exist, UnpicklingError is raised.
Else (the class object does have a __safe_for_unpickling__ attr),
the class object obtained from INST's arguments is applied to the
argtuple obtained from the stack, and the resulting instance object
is pushed on the stack.
NOTE: checks for __safe_for_unpickling__ went away in Python 2.3.
"""),
I(name='OBJ',
code='o',
arg=None,
stack_before=[markobject, anyobject, stackslice],
stack_after=[anyobject],
proto=1,
doc="""Build a class instance.
This is the protocol 1 version of protocol 0's INST opcode, and is
very much like it. The major difference is that the class object
is taken off the stack, allowing it to be retrieved from the memo
repeatedly if several instances of the same class are created. This
can be much more efficient (in both time and space) than repeatedly
embedding the module and class names in INST opcodes.
Unlike INST, OBJ takes no arguments from the opcode stream. Instead
the class object is taken off the stack, immediately above the
topmost markobject:
Stack before: ... markobject classobject stackslice
Stack after: ... new_instance_object
As for INST, the remainder of the stack above the markobject is
gathered into an argument tuple, and then the logic seems identical,
except that no __safe_for_unpickling__ check is done (XXX this is
a bug; cPickle does test __safe_for_unpickling__). See INST for
the gory details.
NOTE: In Python 2.3, INST and OBJ are identical except for how they
get the class object. That was always the intent; the implementations
had diverged for accidental reasons.
"""),
I(name='NEWOBJ',
code='\x81',
arg=None,
stack_before=[anyobject, anyobject],
stack_after=[anyobject],
proto=2,
doc="""Build an object instance.
The stack before should be thought of as containing a class
object followed by an argument tuple (the tuple being the stack
top). Call these cls and args. They are popped off the stack,
and the value returned by cls.__new__(cls, *args) is pushed back
onto the stack.
"""),
# Machine control.
I(name='PROTO',
code='\x80',
arg=uint1,
stack_before=[],
stack_after=[],
proto=2,
doc="""Protocol version indicator.
For protocol 2 and above, a pickle must start with this opcode.
The argument is the protocol version, an int in range(2, 256).
"""),
I(name='STOP',
code='.',
arg=None,
stack_before=[anyobject],
stack_after=[],
proto=0,
doc="""Stop the unpickling machine.
Every pickle ends with this opcode. The object at the top of the stack
is popped, and that's the result of unpickling. The stack should be
empty then.
"""),
# Ways to deal with persistent IDs.
I(name='PERSID',
code='P',
arg=stringnl_noescape,
stack_before=[],
stack_after=[anyobject],
proto=0,
doc="""Push an object identified by a persistent ID.
The pickle module doesn't define what a persistent ID means. PERSID's
argument is a newline-terminated str-style (no embedded escapes, no
bracketing quote characters) string, which *is* "the persistent ID".
The unpickler passes this string to self.persistent_load(). Whatever
object that returns is pushed on the stack. There is no implementation
of persistent_load() in Python's unpickler: it must be supplied by an
unpickler subclass.
"""),
I(name='BINPERSID',
code='Q',
arg=None,
stack_before=[anyobject],
stack_after=[anyobject],
proto=1,
doc="""Push an object identified by a persistent ID.
Like PERSID, except the persistent ID is popped off the stack (instead
of being a string embedded in the opcode bytestream). The persistent
ID is passed to self.persistent_load(), and whatever object that
returns is pushed on the stack. See PERSID for more detail.
"""),
]
del I
# Verify uniqueness of .name and .code members.
name2i = {}
code2i = {}
for i, d in enumerate(opcodes):
if d.name in name2i:
raise ValueError("repeated name %r at indices %d and %d" %
(d.name, name2i[d.name], i))
if d.code in code2i:
raise ValueError("repeated code %r at indices %d and %d" %
(d.code, code2i[d.code], i))
name2i[d.name] = i
code2i[d.code] = i
del name2i, code2i, i, d
##############################################################################
# Build a code2op dict, mapping opcode characters to OpcodeInfo records.
# Also ensure we've got the same stuff as pickle.py, although the
# introspection here is dicey.
code2op = {}
for d in opcodes:
code2op[d.code] = d
del d
def assure_pickle_consistency(verbose=False):
import pickle, re
copy = code2op.copy()
for name in pickle.__all__:
if not re.match("[A-Z][A-Z0-9_]+$", name):
if verbose:
print "skipping %r: it doesn't look like an opcode name" % name
continue
picklecode = getattr(pickle, name)
if not isinstance(picklecode, str) or len(picklecode) != 1:
if verbose:
print ("skipping %r: value %r doesn't look like a pickle "
"code" % (name, picklecode))
continue
if picklecode in copy:
if verbose:
print "checking name %r w/ code %r for consistency" % (
name, picklecode)
d = copy[picklecode]
if d.name != name:
raise ValueError("for pickle code %r, pickle.py uses name %r "
"but we're using name %r" % (picklecode,
name,
d.name))
# Forget this one. Any left over in copy at the end are a problem
# of a different kind.
del copy[picklecode]
else:
raise ValueError("pickle.py appears to have a pickle opcode with "
"name %r and code %r, but we don't" %
(name, picklecode))
if copy:
msg = ["we appear to have pickle opcodes that pickle.py doesn't have:"]
for code, d in copy.items():
msg.append(" name %r with code %r" % (d.name, code))
raise ValueError("\n".join(msg))
assure_pickle_consistency()
del assure_pickle_consistency
##############################################################################
# A pickle opcode generator.
def genops(pickle):
"""Generate all the opcodes in a pickle.
'pickle' is a file-like object, or string, containing the pickle.
Each opcode in the pickle is generated, from the current pickle position,
stopping after a STOP opcode is delivered. A triple is generated for
each opcode:
opcode, arg, pos
opcode is an OpcodeInfo record, describing the current opcode.
If the opcode has an argument embedded in the pickle, arg is its decoded
value, as a Python object. If the opcode doesn't have an argument, arg
is None.
If the pickle has a tell() method, pos was the value of pickle.tell()
before reading the current opcode. If the pickle is a string object,
it's wrapped in a StringIO object, and the latter's tell() result is
used. Else (the pickle doesn't have a tell(), and it's not obvious how
to query its current position) pos is None.
"""
import cStringIO as StringIO
if isinstance(pickle, str):
pickle = StringIO.StringIO(pickle)
if hasattr(pickle, "tell"):
getpos = pickle.tell
else:
getpos = lambda: None
while True:
pos = getpos()
code = pickle.read(1)
opcode = code2op.get(code)
if opcode is None:
if code == "":
raise ValueError("pickle exhausted before seeing STOP")
else:
raise ValueError("at position %s, opcode %r unknown" % (
pos is None and "<unknown>" or pos,
code))
if opcode.arg is None:
arg = None
else:
arg = opcode.arg.reader(pickle)
yield opcode, arg, pos
if code == '.':
assert opcode.name == 'STOP'
break
##############################################################################
# A symbolic pickle disassembler.
def dis(pickle, out=None, memo=None, indentlevel=4):
"""Produce a symbolic disassembly of a pickle.
'pickle' is a file-like object, or string, containing a (at least one)
pickle. The pickle is disassembled from the current position, through
the first STOP opcode encountered.
Optional arg 'out' is a file-like object to which the disassembly is
printed. It defaults to sys.stdout.
Optional arg 'memo' is a Python dict, used as the pickle's memo. It
may be mutated by dis(), if the pickle contains PUT or BINPUT opcodes.
Passing the same memo object to another dis() call then allows disassembly
to proceed across multiple pickles that were all created by the same
pickler with the same memo. Ordinarily you don't need to worry about this.
Optional arg indentlevel is the number of blanks by which to indent
a new MARK level. It defaults to 4.
In addition to printing the disassembly, some sanity checks are made:
+ All embedded opcode arguments "make sense".
+ Explicit and implicit pop operations have enough items on the stack.
+ When an opcode implicitly refers to a markobject, a markobject is
actually on the stack.
+ A memo entry isn't referenced before it's defined.
+ The markobject isn't stored in the memo.
+ A memo entry isn't redefined.
"""
# Most of the hair here is for sanity checks, but most of it is needed
# anyway to detect when a protocol 0 POP takes a MARK off the stack
# (which in turn is needed to indent MARK blocks correctly).
stack = [] # crude emulation of unpickler stack
if memo is None:
memo = {} # crude emulation of unpicker memo
maxproto = -1 # max protocol number seen
markstack = [] # bytecode positions of MARK opcodes
indentchunk = ' ' * indentlevel
errormsg = None
for opcode, arg, pos in genops(pickle):
if pos is not None:
print >> out, "%5d:" % pos,
line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
indentchunk * len(markstack),
opcode.name)
maxproto = max(maxproto, opcode.proto)
before = opcode.stack_before # don't mutate
after = opcode.stack_after # don't mutate
numtopop = len(before)
# See whether a MARK should be popped.
markmsg = None
if markobject in before or (opcode.name == "POP" and
stack and
stack[-1] is markobject):
assert markobject not in after
if __debug__:
if markobject in before:
assert before[-1] is stackslice
if markstack:
markpos = markstack.pop()
if markpos is None:
markmsg = "(MARK at unknown opcode offset)"
else:
markmsg = "(MARK at %d)" % markpos
# Pop everything at and after the topmost markobject.
while stack[-1] is not markobject:
stack.pop()
stack.pop()
# Stop later code from popping too much.
try:
numtopop = before.index(markobject)
except ValueError:
assert opcode.name == "POP"
numtopop = 0
else:
errormsg = markmsg = "no MARK exists on stack"
# Check for correct memo usage.
if opcode.name in ("PUT", "BINPUT", "LONG_BINPUT"):
assert arg is not None
if arg in memo:
errormsg = "memo key %r already defined" % arg
elif not stack:
errormsg = "stack is empty -- can't store into memo"
elif stack[-1] is markobject:
errormsg = "can't store markobject in the memo"
else:
memo[arg] = stack[-1]
elif opcode.name in ("GET", "BINGET", "LONG_BINGET"):
if arg in memo:
assert len(after) == 1
after = [memo[arg]] # for better stack emulation
else:
errormsg = "memo key %r has never been stored into" % arg
if arg is not None or markmsg:
# make a mild effort to align arguments
line += ' ' * (10 - len(opcode.name))
if arg is not None:
line += ' ' + repr(arg)
if markmsg:
line += ' ' + markmsg
print >> out, line
if errormsg:
# Note that we delayed complaining until the offending opcode
# was printed.
raise ValueError(errormsg)
# Emulate the stack effects.
if len(stack) < numtopop:
raise ValueError("tries to pop %d items from stack with "
"only %d items" % (numtopop, len(stack)))
if numtopop:
del stack[-numtopop:]
if markobject in after:
assert markobject not in before
markstack.append(pos)
stack.extend(after)
print >> out, "highest protocol among opcodes =", maxproto
if stack:
raise ValueError("stack not empty after STOP: %r" % stack)
_dis_test = r"""
>>> import pickle
>>> x = [1, 2, (3, 4), {'abc': u"def"}]
>>> pkl = pickle.dumps(x, 0)
>>> dis(pkl)
0: ( MARK
1: l LIST (MARK at 0)
2: p PUT 0
5: I INT 1
8: a APPEND
9: I INT 2
12: a APPEND
13: ( MARK
14: I INT 3
17: I INT 4
20: t TUPLE (MARK at 13)
21: p PUT 1
24: a APPEND
25: ( MARK
26: d DICT (MARK at 25)
27: p PUT 2
30: S STRING 'abc'
37: p PUT 3
40: V UNICODE u'def'
45: p PUT 4
48: s SETITEM
49: a APPEND
50: . STOP
highest protocol among opcodes = 0
Try again with a "binary" pickle.
>>> pkl = pickle.dumps(x, 1)
>>> dis(pkl)
0: ] EMPTY_LIST
1: q BINPUT 0
3: ( MARK
4: K BININT1 1
6: K BININT1 2
8: ( MARK
9: K BININT1 3
11: K BININT1 4
13: t TUPLE (MARK at 8)
14: q BINPUT 1
16: } EMPTY_DICT
17: q BINPUT 2
19: U SHORT_BINSTRING 'abc'
24: q BINPUT 3
26: X BINUNICODE u'def'
34: q BINPUT 4
36: s SETITEM
37: e APPENDS (MARK at 3)
38: . STOP
highest protocol among opcodes = 1
Exercise the INST/OBJ/BUILD family.
>>> import random
>>> dis(pickle.dumps(random.random, 0))
0: c GLOBAL 'random random'
15: p PUT 0
18: . STOP
highest protocol among opcodes = 0
>>> x = [pickle.PicklingError()] * 2
>>> dis(pickle.dumps(x, 0))
0: ( MARK
1: l LIST (MARK at 0)
2: p PUT 0
5: ( MARK
6: i INST 'pickle PicklingError' (MARK at 5)
28: p PUT 1
31: ( MARK
32: d DICT (MARK at 31)
33: p PUT 2
36: S STRING 'args'
44: p PUT 3
47: ( MARK
48: t TUPLE (MARK at 47)
49: s SETITEM
50: b BUILD
51: a APPEND
52: g GET 1
55: a APPEND
56: . STOP
highest protocol among opcodes = 0
>>> dis(pickle.dumps(x, 1))
0: ] EMPTY_LIST
1: q BINPUT 0
3: ( MARK
4: ( MARK
5: c GLOBAL 'pickle PicklingError'
27: q BINPUT 1
29: o OBJ (MARK at 4)
30: q BINPUT 2
32: } EMPTY_DICT
33: q BINPUT 3
35: U SHORT_BINSTRING 'args'
41: q BINPUT 4
43: ) EMPTY_TUPLE
44: s SETITEM
45: b BUILD
46: h BINGET 2
48: e APPENDS (MARK at 3)
49: . STOP
highest protocol among opcodes = 1
Try "the canonical" recursive-object test.
>>> L = []
>>> T = L,
>>> L.append(T)
>>> L[0] is T
True
>>> T[0] is L
True
>>> L[0][0] is L
True
>>> T[0][0] is T
True
>>> dis(pickle.dumps(L, 0))
0: ( MARK
1: l LIST (MARK at 0)
2: p PUT 0
5: ( MARK
6: g GET 0
9: t TUPLE (MARK at 5)
10: p PUT 1
13: a APPEND
14: . STOP
highest protocol among opcodes = 0
>>> dis(pickle.dumps(L, 1))
0: ] EMPTY_LIST
1: q BINPUT 0
3: ( MARK
4: h BINGET 0
6: t TUPLE (MARK at 3)
7: q BINPUT 1
9: a APPEND
10: . STOP
highest protocol among opcodes = 1
Note that, in the protocol 0 pickle of the recursive tuple, the disassembler
has to emulate the stack in order to realize that the POP opcode at 16 gets
rid of the MARK at 0.
>>> dis(pickle.dumps(T, 0))
0: ( MARK
1: ( MARK
2: l LIST (MARK at 1)
3: p PUT 0
6: ( MARK
7: g GET 0
10: t TUPLE (MARK at 6)
11: p PUT 1
14: a APPEND
15: 0 POP
16: 0 POP (MARK at 0)
17: g GET 1
20: . STOP
highest protocol among opcodes = 0
>>> dis(pickle.dumps(T, 1))
0: ( MARK
1: ] EMPTY_LIST
2: q BINPUT 0
4: ( MARK
5: h BINGET 0
7: t TUPLE (MARK at 4)
8: q BINPUT 1
10: a APPEND
11: 1 POP_MARK (MARK at 0)
12: h BINGET 1
14: . STOP
highest protocol among opcodes = 1
Try protocol 2.
>>> dis(pickle.dumps(L, 2))
0: \x80 PROTO 2
2: ] EMPTY_LIST
3: q BINPUT 0
5: h BINGET 0
7: \x85 TUPLE1
8: q BINPUT 1
10: a APPEND
11: . STOP
highest protocol among opcodes = 2
>>> dis(pickle.dumps(T, 2))
0: \x80 PROTO 2
2: ] EMPTY_LIST
3: q BINPUT 0
5: h BINGET 0
7: \x85 TUPLE1
8: q BINPUT 1
10: a APPEND
11: 0 POP
12: h BINGET 1
14: . STOP
highest protocol among opcodes = 2
"""
_memo_test = r"""
>>> import pickle
>>> from StringIO import StringIO
>>> f = StringIO()
>>> p = pickle.Pickler(f, 2)
>>> x = [1, 2, 3]
>>> p.dump(x)
>>> p.dump(x)
>>> f.seek(0)
>>> memo = {}
>>> dis(f, memo=memo)
0: \x80 PROTO 2
2: ] EMPTY_LIST
3: q BINPUT 0
5: ( MARK
6: K BININT1 1
8: K BININT1 2
10: K BININT1 3
12: e APPENDS (MARK at 5)
13: . STOP
highest protocol among opcodes = 2
>>> dis(f, memo=memo)
14: \x80 PROTO 2
16: h BINGET 0
18: . STOP
highest protocol among opcodes = 2
"""
__test__ = {'disassembler_test': _dis_test,
'disassembler_memo_test': _memo_test,
}
def _test():
import doctest
return doctest.testmod()
if __name__ == "__main__":
_test()
| Python |
"""A more or less complete user-defined wrapper around list objects."""
class UserList:
def __init__(self, initlist=None):
self.data = []
if initlist is not None:
# XXX should this accept an arbitrary sequence?
if type(initlist) == type(self.data):
self.data[:] = initlist
elif isinstance(initlist, UserList):
self.data[:] = initlist.data[:]
else:
self.data = list(initlist)
def __repr__(self): return repr(self.data)
def __lt__(self, other): return self.data < self.__cast(other)
def __le__(self, other): return self.data <= self.__cast(other)
def __eq__(self, other): return self.data == self.__cast(other)
def __ne__(self, other): return self.data != self.__cast(other)
def __gt__(self, other): return self.data > self.__cast(other)
def __ge__(self, other): return self.data >= self.__cast(other)
def __cast(self, other):
if isinstance(other, UserList): return other.data
else: return other
def __cmp__(self, other):
return cmp(self.data, self.__cast(other))
def __contains__(self, item): return item in self.data
def __len__(self): return len(self.data)
def __getitem__(self, i): return self.data[i]
def __setitem__(self, i, item): self.data[i] = item
def __delitem__(self, i): del self.data[i]
def __getslice__(self, i, j):
i = max(i, 0); j = max(j, 0)
return self.__class__(self.data[i:j])
def __setslice__(self, i, j, other):
i = max(i, 0); j = max(j, 0)
if isinstance(other, UserList):
self.data[i:j] = other.data
elif isinstance(other, type(self.data)):
self.data[i:j] = other
else:
self.data[i:j] = list(other)
def __delslice__(self, i, j):
i = max(i, 0); j = max(j, 0)
del self.data[i:j]
def __add__(self, other):
if isinstance(other, UserList):
return self.__class__(self.data + other.data)
elif isinstance(other, type(self.data)):
return self.__class__(self.data + other)
else:
return self.__class__(self.data + list(other))
def __radd__(self, other):
if isinstance(other, UserList):
return self.__class__(other.data + self.data)
elif isinstance(other, type(self.data)):
return self.__class__(other + self.data)
else:
return self.__class__(list(other) + self.data)
def __iadd__(self, other):
if isinstance(other, UserList):
self.data += other.data
elif isinstance(other, type(self.data)):
self.data += other
else:
self.data += list(other)
return self
def __mul__(self, n):
return self.__class__(self.data*n)
__rmul__ = __mul__
def __imul__(self, n):
self.data *= n
return self
def append(self, item): self.data.append(item)
def insert(self, i, item): self.data.insert(i, item)
def pop(self, i=-1): return self.data.pop(i)
def remove(self, item): self.data.remove(item)
def count(self, item): return self.data.count(item)
def index(self, item, *args): return self.data.index(item, *args)
def reverse(self): self.data.reverse()
def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
def extend(self, other):
if isinstance(other, UserList):
self.data.extend(other.data)
else:
self.data.extend(other)
| Python |
"""Self documenting XML-RPC Server.
This module can be used to create XML-RPC servers that
serve pydoc-style documentation in response to HTTP
GET requests. This documentation is dynamically generated
based on the functions and methods registered with the
server.
This module is built upon the pydoc and SimpleXMLRPCServer
modules.
"""
import pydoc
import inspect
import types
import re
import sys
from SimpleXMLRPCServer import (SimpleXMLRPCServer,
SimpleXMLRPCRequestHandler,
CGIXMLRPCRequestHandler,
resolve_dotted_attribute)
class ServerHTMLDoc(pydoc.HTMLDoc):
"""Class used to generate pydoc HTML document for a server"""
def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
"""Mark up some plain text, given a context of symbols to look for.
Each context dictionary maps object names to anchor names."""
escape = escape or self.escape
results = []
here = 0
# XXX Note that this regular expressions does not allow for the
# hyperlinking of arbitrary strings being used as method
# names. Only methods with names consisting of word characters
# and '.'s are hyperlinked.
pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
r'RFC[- ]?(\d+)|'
r'PEP[- ]?(\d+)|'
r'(self\.)?((?:\w|\.)+))\b')
while 1:
match = pattern.search(text, here)
if not match: break
start, end = match.span()
results.append(escape(text[here:start]))
all, scheme, rfc, pep, selfdot, name = match.groups()
if scheme:
url = escape(all).replace('"', '"')
results.append('<a href="%s">%s</a>' % (url, url))
elif rfc:
url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif pep:
url = 'http://www.python.org/peps/pep-%04d.html' % int(pep)
results.append('<a href="%s">%s</a>' % (url, escape(all)))
elif text[end:end+1] == '(':
results.append(self.namelink(name, methods, funcs, classes))
elif selfdot:
results.append('self.<strong>%s</strong>' % name)
else:
results.append(self.namelink(name, classes))
here = end
results.append(escape(text[here:]))
return ''.join(results)
def docroutine(self, object, name=None, mod=None,
funcs={}, classes={}, methods={}, cl=None):
"""Produce HTML documentation for a function or method object."""
anchor = (cl and cl.__name__ or '') + '-' + name
note = ''
title = '<a name="%s"><strong>%s</strong></a>' % (anchor, name)
if inspect.ismethod(object):
args, varargs, varkw, defaults = inspect.getargspec(object.im_func)
# exclude the argument bound to the instance, it will be
# confusing to the non-Python user
argspec = inspect.formatargspec (
args[1:],
varargs,
varkw,
defaults,
formatvalue=self.formatvalue
)
elif inspect.isfunction(object):
args, varargs, varkw, defaults = inspect.getargspec(object)
argspec = inspect.formatargspec(
args, varargs, varkw, defaults, formatvalue=self.formatvalue)
else:
argspec = '(...)'
if isinstance(object, types.TupleType):
argspec = object[0] or argspec
docstring = object[1] or ""
else:
docstring = pydoc.getdoc(object)
decl = title + argspec + (note and self.grey(
'<font face="helvetica, arial">%s</font>' % note))
doc = self.markup(
docstring, self.preformat, funcs, classes, methods)
doc = doc and '<dd><tt>%s</tt></dd>' % doc
return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
def docserver(self, server_name, package_documentation, methods):
"""Produce HTML documentation for an XML-RPC server."""
fdict = {}
for key, value in methods.items():
fdict[key] = '#-' + key
fdict[value] = fdict[key]
head = '<big><big><strong>%s</strong></big></big>' % server_name
result = self.heading(head, '#ffffff', '#7799ee')
doc = self.markup(package_documentation, self.preformat, fdict)
doc = doc and '<tt>%s</tt>' % doc
result = result + '<p>%s</p>\n' % doc
contents = []
method_items = methods.items()
method_items.sort()
for key, value in method_items:
contents.append(self.docroutine(value, key, funcs=fdict))
result = result + self.bigsection(
'Methods', '#ffffff', '#eeaa77', pydoc.join(contents))
return result
class XMLRPCDocGenerator:
"""Generates documentation for an XML-RPC server.
This class is designed as mix-in and should not
be constructed directly.
"""
def __init__(self):
# setup variables used for HTML documentation
self.server_name = 'XML-RPC Server Documentation'
self.server_documentation = \
"This server exports the following methods through the XML-RPC "\
"protocol."
self.server_title = 'XML-RPC Server Documentation'
def set_server_title(self, server_title):
"""Set the HTML title of the generated server documentation"""
self.server_title = server_title
def set_server_name(self, server_name):
"""Set the name of the generated HTML server documentation"""
self.server_name = server_name
def set_server_documentation(self, server_documentation):
"""Set the documentation string for the entire server."""
self.server_documentation = server_documentation
def generate_html_documentation(self):
"""generate_html_documentation() => html documentation for the server
Generates HTML documentation for the server using introspection for
installed functions and instances that do not implement the
_dispatch method. Alternatively, instances can choose to implement
the _get_method_argstring(method_name) method to provide the
argument string used in the documentation and the
_methodHelp(method_name) method to provide the help text used
in the documentation."""
methods = {}
for method_name in self.system_listMethods():
if self.funcs.has_key(method_name):
method = self.funcs[method_name]
elif self.instance is not None:
method_info = [None, None] # argspec, documentation
if hasattr(self.instance, '_get_method_argstring'):
method_info[0] = self.instance._get_method_argstring(method_name)
if hasattr(self.instance, '_methodHelp'):
method_info[1] = self.instance._methodHelp(method_name)
method_info = tuple(method_info)
if method_info != (None, None):
method = method_info
elif not hasattr(self.instance, '_dispatch'):
try:
method = resolve_dotted_attribute(
self.instance,
method_name
)
except AttributeError:
method = method_info
else:
method = method_info
else:
assert 0, "Could not find method in self.functions and no "\
"instance installed"
methods[method_name] = method
documenter = ServerHTMLDoc()
documentation = documenter.docserver(
self.server_name,
self.server_documentation,
methods
)
return documenter.page(self.server_title, documentation)
class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
"""XML-RPC and documentation request handler class.
Handles all HTTP POST requests and attempts to decode them as
XML-RPC requests.
Handles all HTTP GET requests and interprets them as requests
for documentation.
"""
def do_GET(self):
"""Handles the HTTP GET request.
Interpret all HTTP GET requests as requests for server
documentation.
"""
response = self.server.generate_html_documentation()
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
# shut down the connection
self.wfile.flush()
self.connection.shutdown(1)
class DocXMLRPCServer( SimpleXMLRPCServer,
XMLRPCDocGenerator):
"""XML-RPC and HTML documentation server.
Adds the ability to serve server documentation to the capabilities
of SimpleXMLRPCServer.
"""
def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler,
logRequests=1):
SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests)
XMLRPCDocGenerator.__init__(self)
class DocCGIXMLRPCRequestHandler( CGIXMLRPCRequestHandler,
XMLRPCDocGenerator):
"""Handler for XML-RPC data and documentation requests passed through
CGI"""
def handle_get(self):
"""Handles the HTTP GET request.
Interpret all HTTP GET requests as requests for server
documentation.
"""
response = self.generate_html_documentation()
print 'Content-Type: text/html'
print 'Content-Length: %d' % len(response)
print
sys.stdout.write(response)
def __init__(self):
CGIXMLRPCRequestHandler.__init__(self)
XMLRPCDocGenerator.__init__(self)
if __name__ == '__main__':
def deg_to_rad(deg):
"""deg_to_rad(90) => 1.5707963267948966
Converts an angle in degrees to an angle in radians"""
import math
return deg * math.pi / 180
server = DocXMLRPCServer(("localhost", 8000))
server.set_server_title("Math Server")
server.set_server_name("Math XML-RPC Server")
server.set_server_documentation("""This server supports various mathematical functions.
You can use it from Python as follows:
>>> from xmlrpclib import ServerProxy
>>> s = ServerProxy("http://localhost:8000")
>>> s.deg_to_rad(90.0)
1.5707963267948966""")
server.register_function(deg_to_rad)
server.register_introspection_functions()
server.serve_forever()
| Python |
"""Module/script to "compile" all .py files to .pyc (or .pyo) file.
When called as a script with arguments, this compiles the directories
given as arguments recursively; the -l option prevents it from
recursing into directories.
Without arguments, if compiles all modules on sys.path, without
recursing into subdirectories. (Even though it should do so for
packages -- for now, you'll have to deal with packages separately.)
See module py_compile for details of the actual byte-compilation.
"""
import os
import sys
import py_compile
__all__ = ["compile_dir","compile_path"]
def compile_dir(dir, maxlevels=10, ddir=None,
force=0, rx=None, quiet=0):
"""Byte-compile all modules in the given directory tree.
Arguments (only dir is required):
dir: the directory to byte-compile
maxlevels: maximum recursion level (default 10)
ddir: if given, purported directory name (this is the
directory name that will show up in error messages)
force: if 1, force compilation, even if timestamps are up-to-date
quiet: if 1, be quiet during compilation
"""
if not quiet:
print 'Listing', dir, '...'
try:
names = os.listdir(dir)
except os.error:
print "Can't list", dir
names = []
names.sort()
success = 1
for name in names:
fullname = os.path.join(dir, name)
if ddir is not None:
dfile = os.path.join(ddir, name)
else:
dfile = None
if rx is not None:
mo = rx.search(fullname)
if mo:
continue
if os.path.isfile(fullname):
head, tail = name[:-3], name[-3:]
if tail == '.py':
cfile = fullname + (__debug__ and 'c' or 'o')
ftime = os.stat(fullname).st_mtime
try: ctime = os.stat(cfile).st_mtime
except os.error: ctime = 0
if (ctime > ftime) and not force: continue
if not quiet:
print 'Compiling', fullname, '...'
try:
ok = py_compile.compile(fullname, None, dfile, True)
except KeyboardInterrupt:
raise KeyboardInterrupt
except py_compile.PyCompileError,err:
if quiet:
print 'Compiling', fullname, '...'
print err.msg
success = 0
except IOError, e:
print "Sorry", e
success = 0
else:
if ok == 0:
success = 0
elif maxlevels > 0 and \
name != os.curdir and name != os.pardir and \
os.path.isdir(fullname) and \
not os.path.islink(fullname):
if not compile_dir(fullname, maxlevels - 1, dfile, force, rx, quiet):
success = 0
return success
def compile_path(skip_curdir=1, maxlevels=0, force=0, quiet=0):
"""Byte-compile all module on sys.path.
Arguments (all optional):
skip_curdir: if true, skip current directory (default true)
maxlevels: max recursion level (default 0)
force: as for compile_dir() (default 0)
quiet: as for compile_dir() (default 0)
"""
success = 1
for dir in sys.path:
if (not dir or dir == os.curdir) and skip_curdir:
print 'Skipping current directory'
else:
success = success and compile_dir(dir, maxlevels, None,
force, quiet=quiet)
return success
def main():
"""Script main program."""
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:')
except getopt.error, msg:
print msg
print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
"[-x regexp] [directory ...]"
print "-l: don't recurse down"
print "-f: force rebuild even if timestamps are up-to-date"
print "-q: quiet operation"
print "-d destdir: purported directory name for error messages"
print " if no directory arguments, -l sys.path is assumed"
print "-x regexp: skip files matching the regular expression regexp"
print " the regexp is search for in the full path of the file"
sys.exit(2)
maxlevels = 10
ddir = None
force = 0
quiet = 0
rx = None
for o, a in opts:
if o == '-l': maxlevels = 0
if o == '-d': ddir = a
if o == '-f': force = 1
if o == '-q': quiet = 1
if o == '-x':
import re
rx = re.compile(a)
if ddir:
if len(args) != 1:
print "-d destdir require exactly one directory argument"
sys.exit(2)
success = 1
try:
if args:
for dir in args:
if not compile_dir(dir, maxlevels, ddir,
force, rx, quiet):
success = 0
else:
success = compile_path()
except KeyboardInterrupt:
print "\n[interrupt]"
success = 0
return success
if __name__ == '__main__':
exit_status = int(not main())
sys.exit(exit_status)
| Python |
# Module doctest.
# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
# Major enhancements and refactoring by:
# Jim Fulton
# Edward Loper
# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
r"""Module doctest -- a framework for running examples in docstrings.
In simplest use, end each module M to be tested with:
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
Then running the module as a script will cause the examples in the
docstrings to get executed and verified:
python M.py
This won't display anything unless an example fails, in which case the
failing example(s) and the cause(s) of the failure(s) are printed to stdout
(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
line of output is "Test failed.".
Run it with the -v switch instead:
python M.py -v
and a detailed report of all examples tried is printed to stdout, along
with assorted summaries at the end.
You can force verbose mode by passing "verbose=True" to testmod, or prohibit
it by passing "verbose=False". In either of those cases, sys.argv is not
examined by testmod.
There are a variety of other ways to run doctests, including integration
with the unittest framework, and support for running non-Python text
files containing doctests. There are also many ways to override parts
of doctest's default behaviors. See the Library Reference Manual for
details.
"""
__docformat__ = 'reStructuredText en'
__all__ = [
# 0, Option Flags
'register_optionflag',
'DONT_ACCEPT_TRUE_FOR_1',
'DONT_ACCEPT_BLANKLINE',
'NORMALIZE_WHITESPACE',
'ELLIPSIS',
'IGNORE_EXCEPTION_DETAIL',
'COMPARISON_FLAGS',
'REPORT_UDIFF',
'REPORT_CDIFF',
'REPORT_NDIFF',
'REPORT_ONLY_FIRST_FAILURE',
'REPORTING_FLAGS',
# 1. Utility Functions
'is_private',
# 2. Example & DocTest
'Example',
'DocTest',
# 3. Doctest Parser
'DocTestParser',
# 4. Doctest Finder
'DocTestFinder',
# 5. Doctest Runner
'DocTestRunner',
'OutputChecker',
'DocTestFailure',
'UnexpectedException',
'DebugRunner',
# 6. Test Functions
'testmod',
'testfile',
'run_docstring_examples',
# 7. Tester
'Tester',
# 8. Unittest Support
'DocTestSuite',
'DocFileSuite',
'set_unittest_reportflags',
# 9. Debugging Support
'script_from_examples',
'testsource',
'debug_src',
'debug',
]
import __future__
import sys, traceback, inspect, linecache, os, re, types
import unittest, difflib, pdb, tempfile
import warnings
from StringIO import StringIO
# Don't whine about the deprecated is_private function in this
# module's tests.
warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
__name__, 0)
# There are 4 basic classes:
# - Example: a <source, want> pair, plus an intra-docstring line number.
# - DocTest: a collection of examples, parsed from a docstring, plus
# info about where the docstring came from (name, filename, lineno).
# - DocTestFinder: extracts DocTests from a given object's docstring and
# its contained objects' docstrings.
# - DocTestRunner: runs DocTest cases, and accumulates statistics.
#
# So the basic picture is:
#
# list of:
# +------+ +---------+ +-------+
# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
# +------+ +---------+ +-------+
# | Example |
# | ... |
# | Example |
# +---------+
# Option constants.
OPTIONFLAGS_BY_NAME = {}
def register_optionflag(name):
flag = 1 << len(OPTIONFLAGS_BY_NAME)
OPTIONFLAGS_BY_NAME[name] = flag
return flag
DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
ELLIPSIS = register_optionflag('ELLIPSIS')
IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
DONT_ACCEPT_BLANKLINE |
NORMALIZE_WHITESPACE |
ELLIPSIS |
IGNORE_EXCEPTION_DETAIL)
REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
REPORTING_FLAGS = (REPORT_UDIFF |
REPORT_CDIFF |
REPORT_NDIFF |
REPORT_ONLY_FIRST_FAILURE)
# Special string markers for use in `want` strings:
BLANKLINE_MARKER = '<BLANKLINE>'
ELLIPSIS_MARKER = '...'
######################################################################
## Table of Contents
######################################################################
# 1. Utility Functions
# 2. Example & DocTest -- store test cases
# 3. DocTest Parser -- extracts examples from strings
# 4. DocTest Finder -- extracts test cases from objects
# 5. DocTest Runner -- runs test cases
# 6. Test Functions -- convenient wrappers for testing
# 7. Tester Class -- for backwards compatibility
# 8. Unittest Support
# 9. Debugging Support
# 10. Example Usage
######################################################################
## 1. Utility Functions
######################################################################
def is_private(prefix, base):
"""prefix, base -> true iff name prefix + "." + base is "private".
Prefix may be an empty string, and base does not contain a period.
Prefix is ignored (although functions you write conforming to this
protocol may make use of it).
Return true iff base begins with an (at least one) underscore, but
does not both begin and end with (at least) two underscores.
>>> is_private("a.b", "my_func")
False
>>> is_private("____", "_my_func")
True
>>> is_private("someclass", "__init__")
False
>>> is_private("sometypo", "__init_")
True
>>> is_private("x.y.z", "_")
True
>>> is_private("_x.y.z", "__")
False
>>> is_private("", "") # senseless but consistent
False
"""
warnings.warn("is_private is deprecated; it wasn't useful; "
"examine DocTestFinder.find() lists instead",
DeprecationWarning, stacklevel=2)
return base[:1] == "_" and not base[:2] == "__" == base[-2:]
def _extract_future_flags(globs):
"""
Return the compiler-flags associated with the future features that
have been imported into the given namespace (globs).
"""
flags = 0
for fname in __future__.all_feature_names:
feature = globs.get(fname, None)
if feature is getattr(__future__, fname):
flags |= feature.compiler_flag
return flags
def _normalize_module(module, depth=2):
"""
Return the module specified by `module`. In particular:
- If `module` is a module, then return module.
- If `module` is a string, then import and return the
module with that name.
- If `module` is None, then return the calling module.
The calling module is assumed to be the module of
the stack frame at the given depth in the call stack.
"""
if inspect.ismodule(module):
return module
elif isinstance(module, (str, unicode)):
return __import__(module, globals(), locals(), ["*"])
elif module is None:
return sys.modules[sys._getframe(depth).f_globals['__name__']]
else:
raise TypeError("Expected a module, string, or None")
def _indent(s, indent=4):
"""
Add the given number of space characters to the beginning every
non-blank line in `s`, and return the result.
"""
# This regexp matches the start of non-blank lines:
return re.sub('(?m)^(?!$)', indent*' ', s)
def _exception_traceback(exc_info):
"""
Return a string containing a traceback message for the given
exc_info tuple (as returned by sys.exc_info()).
"""
# Get a traceback message.
excout = StringIO()
exc_type, exc_val, exc_tb = exc_info
traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
return excout.getvalue()
# Override some StringIO methods.
class _SpoofOut(StringIO):
def getvalue(self):
result = StringIO.getvalue(self)
# If anything at all was written, make sure there's a trailing
# newline. There's no way for the expected output to indicate
# that a trailing newline is missing.
if result and not result.endswith("\n"):
result += "\n"
# Prevent softspace from screwing up the next test case, in
# case they used print with a trailing comma in an example.
if hasattr(self, "softspace"):
del self.softspace
return result
def truncate(self, size=None):
StringIO.truncate(self, size)
if hasattr(self, "softspace"):
del self.softspace
# Worst-case linear-time ellipsis matching.
def _ellipsis_match(want, got):
"""
Essentially the only subtle case:
>>> _ellipsis_match('aa...aa', 'aaa')
False
"""
if ELLIPSIS_MARKER not in want:
return want == got
# Find "the real" strings.
ws = want.split(ELLIPSIS_MARKER)
assert len(ws) >= 2
# Deal with exact matches possibly needed at one or both ends.
startpos, endpos = 0, len(got)
w = ws[0]
if w: # starts with exact match
if got.startswith(w):
startpos = len(w)
del ws[0]
else:
return False
w = ws[-1]
if w: # ends with exact match
if got.endswith(w):
endpos -= len(w)
del ws[-1]
else:
return False
if startpos > endpos:
# Exact end matches required more characters than we have, as in
# _ellipsis_match('aa...aa', 'aaa')
return False
# For the rest, we only need to find the leftmost non-overlapping
# match for each piece. If there's no overall match that way alone,
# there's no overall match period.
for w in ws:
# w may be '' at times, if there are consecutive ellipses, or
# due to an ellipsis at the start or end of `want`. That's OK.
# Search for an empty string succeeds, and doesn't change startpos.
startpos = got.find(w, startpos, endpos)
if startpos < 0:
return False
startpos += len(w)
return True
def _comment_line(line):
"Return a commented form of the given line"
line = line.rstrip()
if line:
return '# '+line
else:
return '#'
class _OutputRedirectingPdb(pdb.Pdb):
"""
A specialized version of the python debugger that redirects stdout
to a given stream when interacting with the user. Stdout is *not*
redirected when traced code is executed.
"""
def __init__(self, out):
self.__out = out
pdb.Pdb.__init__(self)
def trace_dispatch(self, *args):
# Redirect stdout to the given stream.
save_stdout = sys.stdout
sys.stdout = self.__out
# Call Pdb's trace dispatch method.
try:
return pdb.Pdb.trace_dispatch(self, *args)
finally:
sys.stdout = save_stdout
# [XX] Normalize with respect to os.path.pardir?
def _module_relative_path(module, path):
if not inspect.ismodule(module):
raise TypeError, 'Expected a module: %r' % module
if path.startswith('/'):
raise ValueError, 'Module-relative files may not have absolute paths'
# Find the base directory for the path.
if hasattr(module, '__file__'):
# A normal module/package
basedir = os.path.split(module.__file__)[0]
elif module.__name__ == '__main__':
# An interactive session.
if len(sys.argv)>0 and sys.argv[0] != '':
basedir = os.path.split(sys.argv[0])[0]
else:
basedir = os.curdir
else:
# A module w/o __file__ (this includes builtins)
raise ValueError("Can't resolve paths relative to the module " +
module + " (it has no __file__)")
# Combine the base directory and the path.
return os.path.join(basedir, *(path.split('/')))
######################################################################
## 2. Example & DocTest
######################################################################
## - An "example" is a <source, want> pair, where "source" is a
## fragment of source code, and "want" is the expected output for
## "source." The Example class also includes information about
## where the example was extracted from.
##
## - A "doctest" is a collection of examples, typically extracted from
## a string (such as an object's docstring). The DocTest class also
## includes information about where the string was extracted from.
class Example:
"""
A single doctest example, consisting of source code and expected
output. `Example` defines the following attributes:
- source: A single Python statement, always ending with a newline.
The constructor adds a newline if needed.
- want: The expected output from running the source code (either
from stdout, or a traceback in case of exception). `want` ends
with a newline unless it's empty, in which case it's an empty
string. The constructor adds a newline if needed.
- exc_msg: The exception message generated by the example, if
the example is expected to generate an exception; or `None` if
it is not expected to generate an exception. This exception
message is compared against the return value of
`traceback.format_exception_only()`. `exc_msg` ends with a
newline unless it's `None`. The constructor adds a newline
if needed.
- lineno: The line number within the DocTest string containing
this Example where the Example begins. This line number is
zero-based, with respect to the beginning of the DocTest.
- indent: The example's indentation in the DocTest string.
I.e., the number of space characters that preceed the
example's first prompt.
- options: A dictionary mapping from option flags to True or
False, which is used to override default options for this
example. Any option flags not contained in this dictionary
are left at their default value (as specified by the
DocTestRunner's optionflags). By default, no options are set.
"""
def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
options=None):
# Normalize inputs.
if not source.endswith('\n'):
source += '\n'
if want and not want.endswith('\n'):
want += '\n'
if exc_msg is not None and not exc_msg.endswith('\n'):
exc_msg += '\n'
# Store properties.
self.source = source
self.want = want
self.lineno = lineno
self.indent = indent
if options is None: options = {}
self.options = options
self.exc_msg = exc_msg
class DocTest:
"""
A collection of doctest examples that should be run in a single
namespace. Each `DocTest` defines the following attributes:
- examples: the list of examples.
- globs: The namespace (aka globals) that the examples should
be run in.
- name: A name identifying the DocTest (typically, the name of
the object whose docstring this DocTest was extracted from).
- filename: The name of the file that this DocTest was extracted
from, or `None` if the filename is unknown.
- lineno: The line number within filename where this DocTest
begins, or `None` if the line number is unavailable. This
line number is zero-based, with respect to the beginning of
the file.
- docstring: The string that the examples were extracted from,
or `None` if the string is unavailable.
"""
def __init__(self, examples, globs, name, filename, lineno, docstring):
"""
Create a new DocTest containing the given examples. The
DocTest's globals are initialized with a copy of `globs`.
"""
assert not isinstance(examples, basestring), \
"DocTest no longer accepts str; use DocTestParser instead"
self.examples = examples
self.docstring = docstring
self.globs = globs.copy()
self.name = name
self.filename = filename
self.lineno = lineno
def __repr__(self):
if len(self.examples) == 0:
examples = 'no examples'
elif len(self.examples) == 1:
examples = '1 example'
else:
examples = '%d examples' % len(self.examples)
return ('<DocTest %s from %s:%s (%s)>' %
(self.name, self.filename, self.lineno, examples))
# This lets us sort tests by name:
def __cmp__(self, other):
if not isinstance(other, DocTest):
return -1
return cmp((self.name, self.filename, self.lineno, id(self)),
(other.name, other.filename, other.lineno, id(other)))
######################################################################
## 3. DocTestParser
######################################################################
class DocTestParser:
"""
A class used to parse strings containing doctest examples.
"""
# This regular expression is used to find doctest examples in a
# string. It defines three groups: `source` is the source code
# (including leading indentation and prompts); `indent` is the
# indentation of the first (PS1) line of the source code; and
# `want` is the expected output (including leading indentation).
_EXAMPLE_RE = re.compile(r'''
# Source consists of a PS1 line followed by zero or more PS2 lines.
(?P<source>
(?:^(?P<indent> [ ]*) >>> .*) # PS1 line
(?:\n [ ]* \.\.\. .*)*) # PS2 lines
\n?
# Want consists of any non-blank lines that do not start with PS1.
(?P<want> (?:(?![ ]*$) # Not a blank line
(?![ ]*>>>) # Not a line starting with PS1
.*$\n? # But any other line
)*)
''', re.MULTILINE | re.VERBOSE)
# A regular expression for handling `want` strings that contain
# expected exceptions. It divides `want` into three pieces:
# - the traceback header line (`hdr`)
# - the traceback stack (`stack`)
# - the exception message (`msg`), as generated by
# traceback.format_exception_only()
# `msg` may have multiple lines. We assume/require that the
# exception message is the first non-indented line starting with a word
# character following the traceback header line.
_EXCEPTION_RE = re.compile(r"""
# Grab the traceback header. Different versions of Python have
# said different things on the first traceback line.
^(?P<hdr> Traceback\ \(
(?: most\ recent\ call\ last
| innermost\ last
) \) :
)
\s* $ # toss trailing whitespace on the header.
(?P<stack> .*?) # don't blink: absorb stuff until...
^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
""", re.VERBOSE | re.MULTILINE | re.DOTALL)
# A callable returning a true value iff its argument is a blank line
# or contains a single comment.
_IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
def parse(self, string, name='<string>'):
"""
Divide the given string into examples and intervening text,
and return them as a list of alternating Examples and strings.
Line numbers for the Examples are 0-based. The optional
argument `name` is a name identifying this string, and is only
used for error messages.
"""
string = string.expandtabs()
# If all lines begin with the same indentation, then strip it.
min_indent = self._min_indent(string)
if min_indent > 0:
string = '\n'.join([l[min_indent:] for l in string.split('\n')])
output = []
charno, lineno = 0, 0
# Find all doctest examples in the string:
for m in self._EXAMPLE_RE.finditer(string):
# Add the pre-example text to `output`.
output.append(string[charno:m.start()])
# Update lineno (lines before this example)
lineno += string.count('\n', charno, m.start())
# Extract info from the regexp match.
(source, options, want, exc_msg) = \
self._parse_example(m, name, lineno)
# Create an Example, and add it to the list.
if not self._IS_BLANK_OR_COMMENT(source):
output.append( Example(source, want, exc_msg,
lineno=lineno,
indent=min_indent+len(m.group('indent')),
options=options) )
# Update lineno (lines inside this example)
lineno += string.count('\n', m.start(), m.end())
# Update charno.
charno = m.end()
# Add any remaining post-example text to `output`.
output.append(string[charno:])
return output
def get_doctest(self, string, globs, name, filename, lineno):
"""
Extract all doctest examples from the given string, and
collect them into a `DocTest` object.
`globs`, `name`, `filename`, and `lineno` are attributes for
the new `DocTest` object. See the documentation for `DocTest`
for more information.
"""
return DocTest(self.get_examples(string, name), globs,
name, filename, lineno, string)
def get_examples(self, string, name='<string>'):
"""
Extract all doctest examples from the given string, and return
them as a list of `Example` objects. Line numbers are
0-based, because it's most common in doctests that nothing
interesting appears on the same line as opening triple-quote,
and so the first interesting line is called \"line 1\" then.
The optional argument `name` is a name identifying this
string, and is only used for error messages.
"""
return [x for x in self.parse(string, name)
if isinstance(x, Example)]
def _parse_example(self, m, name, lineno):
"""
Given a regular expression match from `_EXAMPLE_RE` (`m`),
return a pair `(source, want)`, where `source` is the matched
example's source code (with prompts and indentation stripped);
and `want` is the example's expected output (with indentation
stripped).
`name` is the string's name, and `lineno` is the line number
where the example starts; both are used for error messages.
"""
# Get the example's indentation level.
indent = len(m.group('indent'))
# Divide source into lines; check that they're properly
# indented; and then strip their indentation & prompts.
source_lines = m.group('source').split('\n')
self._check_prompt_blank(source_lines, indent, name, lineno)
self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
source = '\n'.join([sl[indent+4:] for sl in source_lines])
# Divide want into lines; check that it's properly indented; and
# then strip the indentation. Spaces before the last newline should
# be preserved, so plain rstrip() isn't good enough.
want = m.group('want')
want_lines = want.split('\n')
if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
del want_lines[-1] # forget final newline & spaces after it
self._check_prefix(want_lines, ' '*indent, name,
lineno + len(source_lines))
want = '\n'.join([wl[indent:] for wl in want_lines])
# If `want` contains a traceback message, then extract it.
m = self._EXCEPTION_RE.match(want)
if m:
exc_msg = m.group('msg')
else:
exc_msg = None
# Extract options from the source.
options = self._find_options(source, name, lineno)
return source, options, want, exc_msg
# This regular expression looks for option directives in the
# source code of an example. Option directives are comments
# starting with "doctest:". Warning: this may give false
# positives for string-literals that contain the string
# "#doctest:". Eliminating these false positives would require
# actually parsing the string; but we limit them by ignoring any
# line containing "#doctest:" that is *followed* by a quote mark.
_OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
re.MULTILINE)
def _find_options(self, source, name, lineno):
"""
Return a dictionary containing option overrides extracted from
option directives in the given source string.
`name` is the string's name, and `lineno` is the line number
where the example starts; both are used for error messages.
"""
options = {}
# (note: with the current regexp, this will match at most once:)
for m in self._OPTION_DIRECTIVE_RE.finditer(source):
option_strings = m.group(1).replace(',', ' ').split()
for option in option_strings:
if (option[0] not in '+-' or
option[1:] not in OPTIONFLAGS_BY_NAME):
raise ValueError('line %r of the doctest for %s '
'has an invalid option: %r' %
(lineno+1, name, option))
flag = OPTIONFLAGS_BY_NAME[option[1:]]
options[flag] = (option[0] == '+')
if options and self._IS_BLANK_OR_COMMENT(source):
raise ValueError('line %r of the doctest for %s has an option '
'directive on a line with no example: %r' %
(lineno, name, source))
return options
# This regular expression finds the indentation of every non-blank
# line in a string.
_INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
def _min_indent(self, s):
"Return the minimum indentation of any non-blank line in `s`"
indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
if len(indents) > 0:
return min(indents)
else:
return 0
def _check_prompt_blank(self, lines, indent, name, lineno):
"""
Given the lines of a source string (including prompts and
leading indentation), check to make sure that every prompt is
followed by a space character. If any line is not followed by
a space character, then raise ValueError.
"""
for i, line in enumerate(lines):
if len(line) >= indent+4 and line[indent+3] != ' ':
raise ValueError('line %r of the docstring for %s '
'lacks blank after %s: %r' %
(lineno+i+1, name,
line[indent:indent+3], line))
def _check_prefix(self, lines, prefix, name, lineno):
"""
Check that every line in the given list starts with the given
prefix; if any line does not, then raise a ValueError.
"""
for i, line in enumerate(lines):
if line and not line.startswith(prefix):
raise ValueError('line %r of the docstring for %s has '
'inconsistent leading whitespace: %r' %
(lineno+i+1, name, line))
######################################################################
## 4. DocTest Finder
######################################################################
class DocTestFinder:
"""
A class used to extract the DocTests that are relevant to a given
object, from its docstring and the docstrings of its contained
objects. Doctests can currently be extracted from the following
object types: modules, functions, classes, methods, staticmethods,
classmethods, and properties.
"""
def __init__(self, verbose=False, parser=DocTestParser(),
recurse=True, _namefilter=None, exclude_empty=True):
"""
Create a new doctest finder.
The optional argument `parser` specifies a class or
function that should be used to create new DocTest objects (or
objects that implement the same interface as DocTest). The
signature for this factory function should match the signature
of the DocTest constructor.
If the optional argument `recurse` is false, then `find` will
only examine the given object, and not any contained objects.
If the optional argument `exclude_empty` is false, then `find`
will include tests for objects with empty docstrings.
"""
self._parser = parser
self._verbose = verbose
self._recurse = recurse
self._exclude_empty = exclude_empty
# _namefilter is undocumented, and exists only for temporary backward-
# compatibility support of testmod's deprecated isprivate mess.
self._namefilter = _namefilter
def find(self, obj, name=None, module=None, globs=None,
extraglobs=None):
"""
Return a list of the DocTests that are defined by the given
object's docstring, or by any of its contained objects'
docstrings.
The optional parameter `module` is the module that contains
the given object. If the module is not specified or is None, then
the test finder will attempt to automatically determine the
correct module. The object's module is used:
- As a default namespace, if `globs` is not specified.
- To prevent the DocTestFinder from extracting DocTests
from objects that are imported from other modules.
- To find the name of the file containing the object.
- To help find the line number of the object within its
file.
Contained objects whose module does not match `module` are ignored.
If `module` is False, no attempt to find the module will be made.
This is obscure, of use mostly in tests: if `module` is False, or
is None but cannot be found automatically, then all objects are
considered to belong to the (non-existent) module, so all contained
objects will (recursively) be searched for doctests.
The globals for each DocTest is formed by combining `globs`
and `extraglobs` (bindings in `extraglobs` override bindings
in `globs`). A new copy of the globals dictionary is created
for each DocTest. If `globs` is not specified, then it
defaults to the module's `__dict__`, if specified, or {}
otherwise. If `extraglobs` is not specified, then it defaults
to {}.
"""
# If name was not specified, then extract it from the object.
if name is None:
name = getattr(obj, '__name__', None)
if name is None:
raise ValueError("DocTestFinder.find: name must be given "
"when obj.__name__ doesn't exist: %r" %
(type(obj),))
# Find the module that contains the given object (if obj is
# a module, then module=obj.). Note: this may fail, in which
# case module will be None.
if module is False:
module = None
elif module is None:
module = inspect.getmodule(obj)
# Read the module's source code. This is used by
# DocTestFinder._find_lineno to find the line number for a
# given object's docstring.
try:
file = inspect.getsourcefile(obj) or inspect.getfile(obj)
source_lines = linecache.getlines(file)
if not source_lines:
source_lines = None
except TypeError:
source_lines = None
# Initialize globals, and merge in extraglobs.
if globs is None:
if module is None:
globs = {}
else:
globs = module.__dict__.copy()
else:
globs = globs.copy()
if extraglobs is not None:
globs.update(extraglobs)
# Recursively expore `obj`, extracting DocTests.
tests = []
self._find(tests, obj, name, module, source_lines, globs, {})
return tests
def _filter(self, obj, prefix, base):
"""
Return true if the given object should not be examined.
"""
return (self._namefilter is not None and
self._namefilter(prefix, base))
def _from_module(self, module, object):
"""
Return true if the given object is defined in the given
module.
"""
if module is None:
return True
elif inspect.isfunction(object):
return module.__dict__ is object.func_globals
elif inspect.isclass(object):
return module.__name__ == object.__module__
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif hasattr(object, '__module__'):
return module.__name__ == object.__module__
elif isinstance(object, property):
return True # [XX] no way not be sure.
else:
raise ValueError("object must be a class or function")
def _find(self, tests, obj, name, module, source_lines, globs, seen):
"""
Find tests for the given object and any contained objects, and
add them to `tests`.
"""
if self._verbose:
print 'Finding tests in %s' % name
# If we've already processed this object, then ignore it.
if id(obj) in seen:
return
seen[id(obj)] = 1
# Find a test for this object, and add it to the list of tests.
test = self._get_test(obj, name, module, globs, source_lines)
if test is not None:
tests.append(test)
# Look for tests in a module's contained objects.
if inspect.ismodule(obj) and self._recurse:
for valname, val in obj.__dict__.items():
# Check if this contained object should be ignored.
if self._filter(val, name, valname):
continue
valname = '%s.%s' % (name, valname)
# Recurse to functions & classes.
if ((inspect.isfunction(val) or inspect.isclass(val)) and
self._from_module(module, val)):
self._find(tests, val, valname, module, source_lines,
globs, seen)
# Look for tests in a module's __test__ dictionary.
if inspect.ismodule(obj) and self._recurse:
for valname, val in getattr(obj, '__test__', {}).items():
if not isinstance(valname, basestring):
raise ValueError("DocTestFinder.find: __test__ keys "
"must be strings: %r" %
(type(valname),))
if not (inspect.isfunction(val) or inspect.isclass(val) or
inspect.ismethod(val) or inspect.ismodule(val) or
isinstance(val, basestring)):
raise ValueError("DocTestFinder.find: __test__ values "
"must be strings, functions, methods, "
"classes, or modules: %r" %
(type(val),))
valname = '%s.__test__.%s' % (name, valname)
self._find(tests, val, valname, module, source_lines,
globs, seen)
# Look for tests in a class's contained objects.
if inspect.isclass(obj) and self._recurse:
for valname, val in obj.__dict__.items():
# Check if this contained object should be ignored.
if self._filter(val, name, valname):
continue
# Special handling for staticmethod/classmethod.
if isinstance(val, staticmethod):
val = getattr(obj, valname)
if isinstance(val, classmethod):
val = getattr(obj, valname).im_func
# Recurse to methods, properties, and nested classes.
if ((inspect.isfunction(val) or inspect.isclass(val) or
isinstance(val, property)) and
self._from_module(module, val)):
valname = '%s.%s' % (name, valname)
self._find(tests, val, valname, module, source_lines,
globs, seen)
def _get_test(self, obj, name, module, globs, source_lines):
"""
Return a DocTest for the given object, if it defines a docstring;
otherwise, return None.
"""
# Extract the object's docstring. If it doesn't have one,
# then return None (no test for this object).
if isinstance(obj, basestring):
docstring = obj
else:
try:
if obj.__doc__ is None:
docstring = ''
else:
docstring = obj.__doc__
if not isinstance(docstring, basestring):
docstring = str(docstring)
except (TypeError, AttributeError):
docstring = ''
# Find the docstring's location in the file.
lineno = self._find_lineno(obj, source_lines)
# Don't bother if the docstring is empty.
if self._exclude_empty and not docstring:
return None
# Return a DocTest for this object.
if module is None:
filename = None
else:
filename = getattr(module, '__file__', module.__name__)
if filename[-4:] in (".pyc", ".pyo"):
filename = filename[:-1]
return self._parser.get_doctest(docstring, globs, name,
filename, lineno)
def _find_lineno(self, obj, source_lines):
"""
Return a line number of the given object's docstring. Note:
this method assumes that the object has a docstring.
"""
lineno = None
# Find the line number for modules.
if inspect.ismodule(obj):
lineno = 0
# Find the line number for classes.
# Note: this could be fooled if a class is defined multiple
# times in a single file.
if inspect.isclass(obj):
if source_lines is None:
return None
pat = re.compile(r'^\s*class\s*%s\b' %
getattr(obj, '__name__', '-'))
for i, line in enumerate(source_lines):
if pat.match(line):
lineno = i
break
# Find the line number for functions & methods.
if inspect.ismethod(obj): obj = obj.im_func
if inspect.isfunction(obj): obj = obj.func_code
if inspect.istraceback(obj): obj = obj.tb_frame
if inspect.isframe(obj): obj = obj.f_code
if inspect.iscode(obj):
lineno = getattr(obj, 'co_firstlineno', None)-1
# Find the line number where the docstring starts. Assume
# that it's the first line that begins with a quote mark.
# Note: this could be fooled by a multiline function
# signature, where a continuation line begins with a quote
# mark.
if lineno is not None:
if source_lines is None:
return lineno+1
pat = re.compile('(^|.*:)\s*\w*("|\')')
for lineno in range(lineno, len(source_lines)):
if pat.match(source_lines[lineno]):
return lineno
# We couldn't find the line number.
return None
######################################################################
## 5. DocTest Runner
######################################################################
class DocTestRunner:
"""
A class used to run DocTest test cases, and accumulate statistics.
The `run` method is used to process a single DocTest case. It
returns a tuple `(f, t)`, where `t` is the number of test cases
tried, and `f` is the number of test cases that failed.
>>> tests = DocTestFinder().find(_TestClass)
>>> runner = DocTestRunner(verbose=False)
>>> for test in tests:
... print runner.run(test)
(0, 2)
(0, 1)
(0, 2)
(0, 2)
The `summarize` method prints a summary of all the test cases that
have been run by the runner, and returns an aggregated `(f, t)`
tuple:
>>> runner.summarize(verbose=1)
4 items passed all tests:
2 tests in _TestClass
2 tests in _TestClass.__init__
2 tests in _TestClass.get
1 tests in _TestClass.square
7 tests in 4 items.
7 passed and 0 failed.
Test passed.
(0, 7)
The aggregated number of tried examples and failed examples is
also available via the `tries` and `failures` attributes:
>>> runner.tries
7
>>> runner.failures
0
The comparison between expected outputs and actual outputs is done
by an `OutputChecker`. This comparison may be customized with a
number of option flags; see the documentation for `testmod` for
more information. If the option flags are insufficient, then the
comparison may also be customized by passing a subclass of
`OutputChecker` to the constructor.
The test runner's display output can be controlled in two ways.
First, an output function (`out) can be passed to
`TestRunner.run`; this function will be called with strings that
should be displayed. It defaults to `sys.stdout.write`. If
capturing the output is not sufficient, then the display output
can be also customized by subclassing DocTestRunner, and
overriding the methods `report_start`, `report_success`,
`report_unexpected_exception`, and `report_failure`.
"""
# This divider string is used to separate failure messages, and to
# separate sections of the summary.
DIVIDER = "*" * 70
def __init__(self, checker=None, verbose=None, optionflags=0):
"""
Create a new test runner.
Optional keyword arg `checker` is the `OutputChecker` that
should be used to compare the expected outputs and actual
outputs of doctest examples.
Optional keyword arg 'verbose' prints lots of stuff if true,
only failures if false; by default, it's true iff '-v' is in
sys.argv.
Optional argument `optionflags` can be used to control how the
test runner compares expected output to actual output, and how
it displays failures. See the documentation for `testmod` for
more information.
"""
self._checker = checker or OutputChecker()
if verbose is None:
verbose = '-v' in sys.argv
self._verbose = verbose
self.optionflags = optionflags
self.original_optionflags = optionflags
# Keep track of the examples we've run.
self.tries = 0
self.failures = 0
self._name2ft = {}
# Create a fake output target for capturing doctest output.
self._fakeout = _SpoofOut()
#/////////////////////////////////////////////////////////////////
# Reporting methods
#/////////////////////////////////////////////////////////////////
def report_start(self, out, test, example):
"""
Report that the test runner is about to process the given
example. (Only displays a message if verbose=True)
"""
if self._verbose:
if example.want:
out('Trying:\n' + _indent(example.source) +
'Expecting:\n' + _indent(example.want))
else:
out('Trying:\n' + _indent(example.source) +
'Expecting nothing\n')
def report_success(self, out, test, example, got):
"""
Report that the given example ran successfully. (Only
displays a message if verbose=True)
"""
if self._verbose:
out("ok\n")
def report_failure(self, out, test, example, got):
"""
Report that the given example failed.
"""
out(self._failure_header(test, example) +
self._checker.output_difference(example, got, self.optionflags))
def report_unexpected_exception(self, out, test, example, exc_info):
"""
Report that the given example raised an unexpected exception.
"""
out(self._failure_header(test, example) +
'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
def _failure_header(self, test, example):
out = [self.DIVIDER]
if test.filename:
if test.lineno is not None and example.lineno is not None:
lineno = test.lineno + example.lineno + 1
else:
lineno = '?'
out.append('File "%s", line %s, in %s' %
(test.filename, lineno, test.name))
else:
out.append('Line %s, in %s' % (example.lineno+1, test.name))
out.append('Failed example:')
source = example.source
out.append(_indent(source))
return '\n'.join(out)
#/////////////////////////////////////////////////////////////////
# DocTest Running
#/////////////////////////////////////////////////////////////////
def __run(self, test, compileflags, out):
"""
Run the examples in `test`. Write the outcome of each example
with one of the `DocTestRunner.report_*` methods, using the
writer function `out`. `compileflags` is the set of compiler
flags that should be used to execute examples. Return a tuple
`(f, t)`, where `t` is the number of examples tried, and `f`
is the number of examples that failed. The examples are run
in the namespace `test.globs`.
"""
# Keep track of the number of failures and tries.
failures = tries = 0
# Save the option flags (since option directives can be used
# to modify them).
original_optionflags = self.optionflags
SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
check = self._checker.check_output
# Process each example.
for examplenum, example in enumerate(test.examples):
# If REPORT_ONLY_FIRST_FAILURE is set, then supress
# reporting after the first failure.
quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
failures > 0)
# Merge in the example's options.
self.optionflags = original_optionflags
if example.options:
for (optionflag, val) in example.options.items():
if val:
self.optionflags |= optionflag
else:
self.optionflags &= ~optionflag
# Record that we started this example.
tries += 1
if not quiet:
self.report_start(out, test, example)
# Use a special filename for compile(), so we can retrieve
# the source code during interactive debugging (see
# __patched_linecache_getlines).
filename = '<doctest %s[%d]>' % (test.name, examplenum)
# Run the example in the given context (globs), and record
# any exception that gets raised. (But don't intercept
# keyboard interrupts.)
try:
# Don't blink! This is where the user's code gets run.
exec compile(example.source, filename, "single",
compileflags, 1) in test.globs
self.debugger.set_continue() # ==== Example Finished ====
exception = None
except KeyboardInterrupt:
raise
except:
exception = sys.exc_info()
self.debugger.set_continue() # ==== Example Finished ====
got = self._fakeout.getvalue() # the actual output
self._fakeout.truncate(0)
outcome = FAILURE # guilty until proved innocent or insane
# If the example executed without raising any exceptions,
# verify its output.
if exception is None:
if check(example.want, got, self.optionflags):
outcome = SUCCESS
# The example raised an exception: check if it was expected.
else:
exc_info = sys.exc_info()
exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
if not quiet:
got += _exception_traceback(exc_info)
# If `example.exc_msg` is None, then we weren't expecting
# an exception.
if example.exc_msg is None:
outcome = BOOM
# We expected an exception: see whether it matches.
elif check(example.exc_msg, exc_msg, self.optionflags):
outcome = SUCCESS
# Another chance if they didn't care about the detail.
elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
m1 = re.match(r'[^:]*:', example.exc_msg)
m2 = re.match(r'[^:]*:', exc_msg)
if m1 and m2 and check(m1.group(0), m2.group(0),
self.optionflags):
outcome = SUCCESS
# Report the outcome.
if outcome is SUCCESS:
if not quiet:
self.report_success(out, test, example, got)
elif outcome is FAILURE:
if not quiet:
self.report_failure(out, test, example, got)
failures += 1
elif outcome is BOOM:
if not quiet:
self.report_unexpected_exception(out, test, example,
exc_info)
failures += 1
else:
assert False, ("unknown outcome", outcome)
# Restore the option flags (in case they were modified)
self.optionflags = original_optionflags
# Record and return the number of failures and tries.
self.__record_outcome(test, failures, tries)
return failures, tries
def __record_outcome(self, test, f, t):
"""
Record the fact that the given DocTest (`test`) generated `f`
failures out of `t` tried examples.
"""
f2, t2 = self._name2ft.get(test.name, (0,0))
self._name2ft[test.name] = (f+f2, t+t2)
self.failures += f
self.tries += t
__LINECACHE_FILENAME_RE = re.compile(r'<doctest '
r'(?P<name>[\w\.]+)'
r'\[(?P<examplenum>\d+)\]>$')
def __patched_linecache_getlines(self, filename):
m = self.__LINECACHE_FILENAME_RE.match(filename)
if m and m.group('name') == self.test.name:
example = self.test.examples[int(m.group('examplenum'))]
return example.source.splitlines(True)
else:
return self.save_linecache_getlines(filename)
def run(self, test, compileflags=None, out=None, clear_globs=True):
"""
Run the examples in `test`, and display the results using the
writer function `out`.
The examples are run in the namespace `test.globs`. If
`clear_globs` is true (the default), then this namespace will
be cleared after the test runs, to help with garbage
collection. If you would like to examine the namespace after
the test completes, then use `clear_globs=False`.
`compileflags` gives the set of flags that should be used by
the Python compiler when running the examples. If not
specified, then it will default to the set of future-import
flags that apply to `globs`.
The output of each example is checked using
`DocTestRunner.check_output`, and the results are formatted by
the `DocTestRunner.report_*` methods.
"""
self.test = test
if compileflags is None:
compileflags = _extract_future_flags(test.globs)
save_stdout = sys.stdout
if out is None:
out = save_stdout.write
sys.stdout = self._fakeout
# Patch pdb.set_trace to restore sys.stdout during interactive
# debugging (so it's not still redirected to self._fakeout).
# Note that the interactive output will go to *our*
# save_stdout, even if that's not the real sys.stdout; this
# allows us to write test cases for the set_trace behavior.
save_set_trace = pdb.set_trace
self.debugger = _OutputRedirectingPdb(save_stdout)
self.debugger.reset()
pdb.set_trace = self.debugger.set_trace
# Patch linecache.getlines, so we can see the example's source
# when we're inside the debugger.
self.save_linecache_getlines = linecache.getlines
linecache.getlines = self.__patched_linecache_getlines
try:
return self.__run(test, compileflags, out)
finally:
sys.stdout = save_stdout
pdb.set_trace = save_set_trace
linecache.getlines = self.save_linecache_getlines
if clear_globs:
test.globs.clear()
#/////////////////////////////////////////////////////////////////
# Summarization
#/////////////////////////////////////////////////////////////////
def summarize(self, verbose=None):
"""
Print a summary of all the test cases that have been run by
this DocTestRunner, and return a tuple `(f, t)`, where `f` is
the total number of failed examples, and `t` is the total
number of tried examples.
The optional `verbose` argument controls how detailed the
summary is. If the verbosity is not specified, then the
DocTestRunner's verbosity is used.
"""
if verbose is None:
verbose = self._verbose
notests = []
passed = []
failed = []
totalt = totalf = 0
for x in self._name2ft.items():
name, (f, t) = x
assert f <= t
totalt += t
totalf += f
if t == 0:
notests.append(name)
elif f == 0:
passed.append( (name, t) )
else:
failed.append(x)
if verbose:
if notests:
print len(notests), "items had no tests:"
notests.sort()
for thing in notests:
print " ", thing
if passed:
print len(passed), "items passed all tests:"
passed.sort()
for thing, count in passed:
print " %3d tests in %s" % (count, thing)
if failed:
print self.DIVIDER
print len(failed), "items had failures:"
failed.sort()
for thing, (f, t) in failed:
print " %3d of %3d in %s" % (f, t, thing)
if verbose:
print totalt, "tests in", len(self._name2ft), "items."
print totalt - totalf, "passed and", totalf, "failed."
if totalf:
print "***Test Failed***", totalf, "failures."
elif verbose:
print "Test passed."
return totalf, totalt
#/////////////////////////////////////////////////////////////////
# Backward compatibility cruft to maintain doctest.master.
#/////////////////////////////////////////////////////////////////
def merge(self, other):
d = self._name2ft
for name, (f, t) in other._name2ft.items():
if name in d:
print "*** DocTestRunner.merge: '" + name + "' in both" \
" testers; summing outcomes."
f2, t2 = d[name]
f = f + f2
t = t + t2
d[name] = f, t
class OutputChecker:
"""
A class used to check the whether the actual output from a doctest
example matches the expected output. `OutputChecker` defines two
methods: `check_output`, which compares a given pair of outputs,
and returns true if they match; and `output_difference`, which
returns a string describing the differences between two outputs.
"""
def check_output(self, want, got, optionflags):
"""
Return True iff the actual output from an example (`got`)
matches the expected output (`want`). These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
several non-exact match types are also possible. See the
documentation for `TestRunner` for more information about
option flags.
"""
# Handle the common case first, for efficiency:
# if they're string-identical, always return true.
if got == want:
return True
# The values True and False replaced 1 and 0 as the return
# value for boolean comparisons in Python 2.3.
if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
if (got,want) == ("True\n", "1\n"):
return True
if (got,want) == ("False\n", "0\n"):
return True
# <BLANKLINE> can be used as a special sequence to signify a
# blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
if not (optionflags & DONT_ACCEPT_BLANKLINE):
# Replace <BLANKLINE> in want with a blank line.
want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
'', want)
# If a line in got contains only spaces, then remove the
# spaces.
got = re.sub('(?m)^\s*?$', '', got)
if got == want:
return True
# This flag causes doctest to ignore any differences in the
# contents of whitespace strings. Note that this can be used
# in conjunction with the ELLIPSIS flag.
if optionflags & NORMALIZE_WHITESPACE:
got = ' '.join(got.split())
want = ' '.join(want.split())
if got == want:
return True
# The ELLIPSIS flag says to let the sequence "..." in `want`
# match any substring in `got`.
if optionflags & ELLIPSIS:
if _ellipsis_match(want, got):
return True
# We didn't find any match; return false.
return False
# Should we do a fancy diff?
def _do_a_fancy_diff(self, want, got, optionflags):
# Not unless they asked for a fancy diff.
if not optionflags & (REPORT_UDIFF |
REPORT_CDIFF |
REPORT_NDIFF):
return False
# If expected output uses ellipsis, a meaningful fancy diff is
# too hard ... or maybe not. In two real-life failures Tim saw,
# a diff was a major help anyway, so this is commented out.
# [todo] _ellipsis_match() knows which pieces do and don't match,
# and could be the basis for a kick-ass diff in this case.
##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
## return False
# ndiff does intraline difference marking, so can be useful even
# for 1-line differences.
if optionflags & REPORT_NDIFF:
return True
# The other diff types need at least a few lines to be helpful.
return want.count('\n') > 2 and got.count('\n') > 2
def output_difference(self, example, got, optionflags):
"""
Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`). `optionflags` is the set of option flags used
to compare `want` and `got`.
"""
want = example.want
# If <BLANKLINE>s are being used, then replace blank lines
# with <BLANKLINE> in the actual output string.
if not (optionflags & DONT_ACCEPT_BLANKLINE):
got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
# Check if we should use diff.
if self._do_a_fancy_diff(want, got, optionflags):
# Split want & got into lines.
want_lines = want.splitlines(True) # True == keep line ends
got_lines = got.splitlines(True)
# Use difflib to find their differences.
if optionflags & REPORT_UDIFF:
diff = difflib.unified_diff(want_lines, got_lines, n=2)
diff = list(diff)[2:] # strip the diff header
kind = 'unified diff with -expected +actual'
elif optionflags & REPORT_CDIFF:
diff = difflib.context_diff(want_lines, got_lines, n=2)
diff = list(diff)[2:] # strip the diff header
kind = 'context diff with expected followed by actual'
elif optionflags & REPORT_NDIFF:
engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
diff = list(engine.compare(want_lines, got_lines))
kind = 'ndiff with -expected +actual'
else:
assert 0, 'Bad diff option'
# Remove trailing whitespace on diff output.
diff = [line.rstrip() + '\n' for line in diff]
return 'Differences (%s):\n' % kind + _indent(''.join(diff))
# If we're not using diff, then simply list the expected
# output followed by the actual output.
if want and got:
return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
elif want:
return 'Expected:\n%sGot nothing\n' % _indent(want)
elif got:
return 'Expected nothing\nGot:\n%s' % _indent(got)
else:
return 'Expected nothing\nGot nothing\n'
class DocTestFailure(Exception):
"""A DocTest example has failed in debugging mode.
The exception instance has variables:
- test: the DocTest object being run
- excample: the Example object that failed
- got: the actual output
"""
def __init__(self, test, example, got):
self.test = test
self.example = example
self.got = got
def __str__(self):
return str(self.test)
class UnexpectedException(Exception):
"""A DocTest example has encountered an unexpected exception
The exception instance has variables:
- test: the DocTest object being run
- excample: the Example object that failed
- exc_info: the exception info
"""
def __init__(self, test, example, exc_info):
self.test = test
self.example = example
self.exc_info = exc_info
def __str__(self):
return str(self.test)
class DebugRunner(DocTestRunner):
r"""Run doc tests but raise an exception as soon as there is a failure.
If an unexpected exception occurs, an UnexpectedException is raised.
It contains the test, the example, and the original exception:
>>> runner = DebugRunner(verbose=False)
>>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
... {}, 'foo', 'foo.py', 0)
>>> try:
... runner.run(test)
... except UnexpectedException, failure:
... pass
>>> failure.test is test
True
>>> failure.example.want
'42\n'
>>> exc_info = failure.exc_info
>>> raise exc_info[0], exc_info[1], exc_info[2]
Traceback (most recent call last):
...
KeyError
We wrap the original exception to give the calling application
access to the test and example information.
If the output doesn't match, then a DocTestFailure is raised:
>>> test = DocTestParser().get_doctest('''
... >>> x = 1
... >>> x
... 2
... ''', {}, 'foo', 'foo.py', 0)
>>> try:
... runner.run(test)
... except DocTestFailure, failure:
... pass
DocTestFailure objects provide access to the test:
>>> failure.test is test
True
As well as to the example:
>>> failure.example.want
'2\n'
and the actual output:
>>> failure.got
'1\n'
If a failure or error occurs, the globals are left intact:
>>> del test.globs['__builtins__']
>>> test.globs
{'x': 1}
>>> test = DocTestParser().get_doctest('''
... >>> x = 2
... >>> raise KeyError
... ''', {}, 'foo', 'foo.py', 0)
>>> runner.run(test)
Traceback (most recent call last):
...
UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
>>> del test.globs['__builtins__']
>>> test.globs
{'x': 2}
But the globals are cleared if there is no error:
>>> test = DocTestParser().get_doctest('''
... >>> x = 2
... ''', {}, 'foo', 'foo.py', 0)
>>> runner.run(test)
(0, 1)
>>> test.globs
{}
"""
def run(self, test, compileflags=None, out=None, clear_globs=True):
r = DocTestRunner.run(self, test, compileflags, out, False)
if clear_globs:
test.globs.clear()
return r
def report_unexpected_exception(self, out, test, example, exc_info):
raise UnexpectedException(test, example, exc_info)
def report_failure(self, out, test, example, got):
raise DocTestFailure(test, example, got)
######################################################################
## 6. Test Functions
######################################################################
# These should be backwards compatible.
# For backward compatibility, a global instance of a DocTestRunner
# class, updated by testmod.
master = None
def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
report=True, optionflags=0, extraglobs=None,
raise_on_error=False, exclude_empty=False):
"""m=None, name=None, globs=None, verbose=None, isprivate=None,
report=True, optionflags=0, extraglobs=None, raise_on_error=False,
exclude_empty=False
Test examples in docstrings in functions and classes reachable
from module m (or the current module if m is not supplied), starting
with m.__doc__. Unless isprivate is specified, private names
are not skipped.
Also test examples reachable from dict m.__test__ if it exists and is
not None. m.__test__ maps names to functions, classes and strings;
function and class docstrings are tested even if the name is private;
strings are tested directly, as if they were docstrings.
Return (#failures, #tests).
See doctest.__doc__ for an overview.
Optional keyword arg "name" gives the name of the module; by default
use m.__name__.
Optional keyword arg "globs" gives a dict to be used as the globals
when executing examples; by default, use m.__dict__. A copy of this
dict is actually used for each docstring, so that each docstring's
examples start with a clean slate.
Optional keyword arg "extraglobs" gives a dictionary that should be
merged into the globals that are used to execute examples. By
default, no extra globals are used. This is new in 2.4.
Optional keyword arg "verbose" prints lots of stuff if true, prints
only failures if false; by default, it's true iff "-v" is in sys.argv.
Optional keyword arg "report" prints a summary at the end when true,
else prints nothing at the end. In verbose mode, the summary is
detailed, else very brief (in fact, empty if all tests passed).
Optional keyword arg "optionflags" or's together module constants,
and defaults to 0. This is new in 2.3. Possible values (see the
docs for details):
DONT_ACCEPT_TRUE_FOR_1
DONT_ACCEPT_BLANKLINE
NORMALIZE_WHITESPACE
ELLIPSIS
IGNORE_EXCEPTION_DETAIL
REPORT_UDIFF
REPORT_CDIFF
REPORT_NDIFF
REPORT_ONLY_FIRST_FAILURE
Optional keyword arg "raise_on_error" raises an exception on the
first unexpected exception or failure. This allows failures to be
post-mortem debugged.
Deprecated in Python 2.4:
Optional keyword arg "isprivate" specifies a function used to
determine whether a name is private. The default function is
treat all functions as public. Optionally, "isprivate" can be
set to doctest.is_private to skip over functions marked as private
using the underscore naming convention; see its docs for details.
Advanced tomfoolery: testmod runs methods of a local instance of
class doctest.Tester, then merges the results into (or creates)
global Tester instance doctest.master. Methods of doctest.master
can be called directly too, if you want to do something unusual.
Passing report=0 to testmod is especially useful then, to delay
displaying a summary. Invoke doctest.master.summarize(verbose)
when you're done fiddling.
"""
global master
if isprivate is not None:
warnings.warn("the isprivate argument is deprecated; "
"examine DocTestFinder.find() lists instead",
DeprecationWarning)
# If no module was given, then use __main__.
if m is None:
# DWA - m will still be None if this wasn't invoked from the command
# line, in which case the following TypeError is about as good an error
# as we should expect
m = sys.modules.get('__main__')
# Check that we were actually given a module.
if not inspect.ismodule(m):
raise TypeError("testmod: module required; %r" % (m,))
# If no name was given, then use the module's name.
if name is None:
name = m.__name__
# Find, parse, and run all tests in the given module.
finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty)
if raise_on_error:
runner = DebugRunner(verbose=verbose, optionflags=optionflags)
else:
runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
runner.run(test)
if report:
runner.summarize()
if master is None:
master = runner
else:
master.merge(runner)
return runner.failures, runner.tries
def testfile(filename, module_relative=True, name=None, package=None,
globs=None, verbose=None, report=True, optionflags=0,
extraglobs=None, raise_on_error=False, parser=DocTestParser()):
"""
Test examples in the given file. Return (#failures, #tests).
Optional keyword arg "module_relative" specifies how filenames
should be interpreted:
- If "module_relative" is True (the default), then "filename"
specifies a module-relative path. By default, this path is
relative to the calling module's directory; but if the
"package" argument is specified, then it is relative to that
package. To ensure os-independence, "filename" should use
"/" characters to separate path segments, and should not
be an absolute path (i.e., it may not begin with "/").
- If "module_relative" is False, then "filename" specifies an
os-specific path. The path may be absolute or relative (to
the current working directory).
Optional keyword arg "name" gives the name of the test; by default
use the file's basename.
Optional keyword argument "package" is a Python package or the
name of a Python package whose directory should be used as the
base directory for a module relative filename. If no package is
specified, then the calling module's directory is used as the base
directory for module relative filenames. It is an error to
specify "package" if "module_relative" is False.
Optional keyword arg "globs" gives a dict to be used as the globals
when executing examples; by default, use {}. A copy of this dict
is actually used for each docstring, so that each docstring's
examples start with a clean slate.
Optional keyword arg "extraglobs" gives a dictionary that should be
merged into the globals that are used to execute examples. By
default, no extra globals are used.
Optional keyword arg "verbose" prints lots of stuff if true, prints
only failures if false; by default, it's true iff "-v" is in sys.argv.
Optional keyword arg "report" prints a summary at the end when true,
else prints nothing at the end. In verbose mode, the summary is
detailed, else very brief (in fact, empty if all tests passed).
Optional keyword arg "optionflags" or's together module constants,
and defaults to 0. Possible values (see the docs for details):
DONT_ACCEPT_TRUE_FOR_1
DONT_ACCEPT_BLANKLINE
NORMALIZE_WHITESPACE
ELLIPSIS
IGNORE_EXCEPTION_DETAIL
REPORT_UDIFF
REPORT_CDIFF
REPORT_NDIFF
REPORT_ONLY_FIRST_FAILURE
Optional keyword arg "raise_on_error" raises an exception on the
first unexpected exception or failure. This allows failures to be
post-mortem debugged.
Optional keyword arg "parser" specifies a DocTestParser (or
subclass) that should be used to extract tests from the files.
Advanced tomfoolery: testmod runs methods of a local instance of
class doctest.Tester, then merges the results into (or creates)
global Tester instance doctest.master. Methods of doctest.master
can be called directly too, if you want to do something unusual.
Passing report=0 to testmod is especially useful then, to delay
displaying a summary. Invoke doctest.master.summarize(verbose)
when you're done fiddling.
"""
global master
if package and not module_relative:
raise ValueError("Package may only be specified for module-"
"relative paths.")
# Relativize the path
if module_relative:
package = _normalize_module(package)
filename = _module_relative_path(package, filename)
# If no name was given, then use the file's name.
if name is None:
name = os.path.basename(filename)
# Assemble the globals.
if globs is None:
globs = {}
else:
globs = globs.copy()
if extraglobs is not None:
globs.update(extraglobs)
if raise_on_error:
runner = DebugRunner(verbose=verbose, optionflags=optionflags)
else:
runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
# Read the file, convert it to a test, and run it.
s = open(filename).read()
test = parser.get_doctest(s, globs, name, filename, 0)
runner.run(test)
if report:
runner.summarize()
if master is None:
master = runner
else:
master.merge(runner)
return runner.failures, runner.tries
def run_docstring_examples(f, globs, verbose=False, name="NoName",
compileflags=None, optionflags=0):
"""
Test examples in the given object's docstring (`f`), using `globs`
as globals. Optional argument `name` is used in failure messages.
If the optional argument `verbose` is true, then generate output
even if there are no failures.
`compileflags` gives the set of flags that should be used by the
Python compiler when running the examples. If not specified, then
it will default to the set of future-import flags that apply to
`globs`.
Optional keyword arg `optionflags` specifies options for the
testing and output. See the documentation for `testmod` for more
information.
"""
# Find, parse, and run all tests in the given module.
finder = DocTestFinder(verbose=verbose, recurse=False)
runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
for test in finder.find(f, name, globs=globs):
runner.run(test, compileflags=compileflags)
######################################################################
## 7. Tester
######################################################################
# This is provided only for backwards compatibility. It's not
# actually used in any way.
class Tester:
def __init__(self, mod=None, globs=None, verbose=None,
isprivate=None, optionflags=0):
warnings.warn("class Tester is deprecated; "
"use class doctest.DocTestRunner instead",
DeprecationWarning, stacklevel=2)
if mod is None and globs is None:
raise TypeError("Tester.__init__: must specify mod or globs")
if mod is not None and not inspect.ismodule(mod):
raise TypeError("Tester.__init__: mod must be a module; %r" %
(mod,))
if globs is None:
globs = mod.__dict__
self.globs = globs
self.verbose = verbose
self.isprivate = isprivate
self.optionflags = optionflags
self.testfinder = DocTestFinder(_namefilter=isprivate)
self.testrunner = DocTestRunner(verbose=verbose,
optionflags=optionflags)
def runstring(self, s, name):
test = DocTestParser().get_doctest(s, self.globs, name, None, None)
if self.verbose:
print "Running string", name
(f,t) = self.testrunner.run(test)
if self.verbose:
print f, "of", t, "examples failed in string", name
return (f,t)
def rundoc(self, object, name=None, module=None):
f = t = 0
tests = self.testfinder.find(object, name, module=module,
globs=self.globs)
for test in tests:
(f2, t2) = self.testrunner.run(test)
(f,t) = (f+f2, t+t2)
return (f,t)
def rundict(self, d, name, module=None):
import new
m = new.module(name)
m.__dict__.update(d)
if module is None:
module = False
return self.rundoc(m, name, module)
def run__test__(self, d, name):
import new
m = new.module(name)
m.__test__ = d
return self.rundoc(m, name)
def summarize(self, verbose=None):
return self.testrunner.summarize(verbose)
def merge(self, other):
self.testrunner.merge(other.testrunner)
######################################################################
## 8. Unittest Support
######################################################################
_unittest_reportflags = 0
def set_unittest_reportflags(flags):
"""Sets the unittest option flags.
The old flag is returned so that a runner could restore the old
value if it wished to:
>>> import doctest
>>> old = doctest._unittest_reportflags
>>> doctest.set_unittest_reportflags(REPORT_NDIFF |
... REPORT_ONLY_FIRST_FAILURE) == old
True
>>> doctest._unittest_reportflags == (REPORT_NDIFF |
... REPORT_ONLY_FIRST_FAILURE)
True
Only reporting flags can be set:
>>> doctest.set_unittest_reportflags(ELLIPSIS)
Traceback (most recent call last):
...
ValueError: ('Only reporting flags allowed', 8)
>>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
... REPORT_ONLY_FIRST_FAILURE)
True
"""
global _unittest_reportflags
if (flags & REPORTING_FLAGS) != flags:
raise ValueError("Only reporting flags allowed", flags)
old = _unittest_reportflags
_unittest_reportflags = flags
return old
class DocTestCase(unittest.TestCase):
def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
checker=None):
unittest.TestCase.__init__(self)
self._dt_optionflags = optionflags
self._dt_checker = checker
self._dt_test = test
self._dt_setUp = setUp
self._dt_tearDown = tearDown
def setUp(self):
test = self._dt_test
if self._dt_setUp is not None:
self._dt_setUp(test)
def tearDown(self):
test = self._dt_test
if self._dt_tearDown is not None:
self._dt_tearDown(test)
test.globs.clear()
def runTest(self):
test = self._dt_test
old = sys.stdout
new = StringIO()
optionflags = self._dt_optionflags
if not (optionflags & REPORTING_FLAGS):
# The option flags don't include any reporting flags,
# so add the default reporting flags
optionflags |= _unittest_reportflags
runner = DocTestRunner(optionflags=optionflags,
checker=self._dt_checker, verbose=False)
try:
runner.DIVIDER = "-"*70
failures, tries = runner.run(
test, out=new.write, clear_globs=False)
finally:
sys.stdout = old
if failures:
raise self.failureException(self.format_failure(new.getvalue()))
def format_failure(self, err):
test = self._dt_test
if test.lineno is None:
lineno = 'unknown line number'
else:
lineno = '%s' % test.lineno
lname = '.'.join(test.name.split('.')[-1:])
return ('Failed doctest test for %s\n'
' File "%s", line %s, in %s\n\n%s'
% (test.name, test.filename, lineno, lname, err)
)
def debug(self):
r"""Run the test case without results and without catching exceptions
The unit test framework includes a debug method on test cases
and test suites to support post-mortem debugging. The test code
is run in such a way that errors are not caught. This way a
caller can catch the errors and initiate post-mortem debugging.
The DocTestCase provides a debug method that raises
UnexpectedException errors if there is an unexepcted
exception:
>>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
... {}, 'foo', 'foo.py', 0)
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except UnexpectedException, failure:
... pass
The UnexpectedException contains the test, the example, and
the original exception:
>>> failure.test is test
True
>>> failure.example.want
'42\n'
>>> exc_info = failure.exc_info
>>> raise exc_info[0], exc_info[1], exc_info[2]
Traceback (most recent call last):
...
KeyError
If the output doesn't match, then a DocTestFailure is raised:
>>> test = DocTestParser().get_doctest('''
... >>> x = 1
... >>> x
... 2
... ''', {}, 'foo', 'foo.py', 0)
>>> case = DocTestCase(test)
>>> try:
... case.debug()
... except DocTestFailure, failure:
... pass
DocTestFailure objects provide access to the test:
>>> failure.test is test
True
As well as to the example:
>>> failure.example.want
'2\n'
and the actual output:
>>> failure.got
'1\n'
"""
self.setUp()
runner = DebugRunner(optionflags=self._dt_optionflags,
checker=self._dt_checker, verbose=False)
runner.run(self._dt_test)
self.tearDown()
def id(self):
return self._dt_test.name
def __repr__(self):
name = self._dt_test.name.split('.')
return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
__str__ = __repr__
def shortDescription(self):
return "Doctest: " + self._dt_test.name
def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
**options):
"""
Convert doctest tests for a module to a unittest test suite.
This converts each documentation string in a module that
contains doctest tests to a unittest test case. If any of the
tests in a doc string fail, then the test case fails. An exception
is raised showing the name of the file containing the test and a
(sometimes approximate) line number.
The `module` argument provides the module to be tested. The argument
can be either a module or a module name.
If no argument is given, the calling module is used.
A number of options may be provided as keyword arguments:
setUp
A set-up function. This is called before running the
tests in each file. The setUp function will be passed a DocTest
object. The setUp function can access the test globals as the
globs attribute of the test passed.
tearDown
A tear-down function. This is called after running the
tests in each file. The tearDown function will be passed a DocTest
object. The tearDown function can access the test globals as the
globs attribute of the test passed.
globs
A dictionary containing initial global variables for the tests.
optionflags
A set of doctest option flags expressed as an integer.
"""
if test_finder is None:
test_finder = DocTestFinder()
module = _normalize_module(module)
tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
if globs is None:
globs = module.__dict__
if not tests:
# Why do we want to do this? Because it reveals a bug that might
# otherwise be hidden.
raise ValueError(module, "has no tests")
tests.sort()
suite = unittest.TestSuite()
for test in tests:
if len(test.examples) == 0:
continue
if not test.filename:
filename = module.__file__
if filename[-4:] in (".pyc", ".pyo"):
filename = filename[:-1]
test.filename = filename
suite.addTest(DocTestCase(test, **options))
return suite
class DocFileCase(DocTestCase):
def id(self):
return '_'.join(self._dt_test.name.split('.'))
def __repr__(self):
return self._dt_test.filename
__str__ = __repr__
def format_failure(self, err):
return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
% (self._dt_test.name, self._dt_test.filename, err)
)
def DocFileTest(path, module_relative=True, package=None,
globs=None, parser=DocTestParser(), **options):
if globs is None:
globs = {}
if package and not module_relative:
raise ValueError("Package may only be specified for module-"
"relative paths.")
# Relativize the path.
if module_relative:
package = _normalize_module(package)
path = _module_relative_path(package, path)
# Find the file and read it.
name = os.path.basename(path)
doc = open(path).read()
# Convert it to a test, and wrap it in a DocFileCase.
test = parser.get_doctest(doc, globs, name, path, 0)
return DocFileCase(test, **options)
def DocFileSuite(*paths, **kw):
"""A unittest suite for one or more doctest files.
The path to each doctest file is given as a string; the
interpretation of that string depends on the keyword argument
"module_relative".
A number of options may be provided as keyword arguments:
module_relative
If "module_relative" is True, then the given file paths are
interpreted as os-independent module-relative paths. By
default, these paths are relative to the calling module's
directory; but if the "package" argument is specified, then
they are relative to that package. To ensure os-independence,
"filename" should use "/" characters to separate path
segments, and may not be an absolute path (i.e., it may not
begin with "/").
If "module_relative" is False, then the given file paths are
interpreted as os-specific paths. These paths may be absolute
or relative (to the current working directory).
package
A Python package or the name of a Python package whose directory
should be used as the base directory for module relative paths.
If "package" is not specified, then the calling module's
directory is used as the base directory for module relative
filenames. It is an error to specify "package" if
"module_relative" is False.
setUp
A set-up function. This is called before running the
tests in each file. The setUp function will be passed a DocTest
object. The setUp function can access the test globals as the
globs attribute of the test passed.
tearDown
A tear-down function. This is called after running the
tests in each file. The tearDown function will be passed a DocTest
object. The tearDown function can access the test globals as the
globs attribute of the test passed.
globs
A dictionary containing initial global variables for the tests.
optionflags
A set of doctest option flags expressed as an integer.
parser
A DocTestParser (or subclass) that should be used to extract
tests from the files.
"""
suite = unittest.TestSuite()
# We do this here so that _normalize_module is called at the right
# level. If it were called in DocFileTest, then this function
# would be the caller and we might guess the package incorrectly.
if kw.get('module_relative', True):
kw['package'] = _normalize_module(kw.get('package'))
for path in paths:
suite.addTest(DocFileTest(path, **kw))
return suite
######################################################################
## 9. Debugging Support
######################################################################
def script_from_examples(s):
r"""Extract script from text with examples.
Converts text with examples to a Python script. Example input is
converted to regular code. Example output and all other words
are converted to comments:
>>> text = '''
... Here are examples of simple math.
...
... Python has super accurate integer addition
...
... >>> 2 + 2
... 5
...
... And very friendly error messages:
...
... >>> 1/0
... To Infinity
... And
... Beyond
...
... You can use logic if you want:
...
... >>> if 0:
... ... blah
... ... blah
... ...
...
... Ho hum
... '''
>>> print script_from_examples(text)
# Here are examples of simple math.
#
# Python has super accurate integer addition
#
2 + 2
# Expected:
## 5
#
# And very friendly error messages:
#
1/0
# Expected:
## To Infinity
## And
## Beyond
#
# You can use logic if you want:
#
if 0:
blah
blah
#
# Ho hum
"""
output = []
for piece in DocTestParser().parse(s):
if isinstance(piece, Example):
# Add the example's source code (strip trailing NL)
output.append(piece.source[:-1])
# Add the expected output:
want = piece.want
if want:
output.append('# Expected:')
output += ['## '+l for l in want.split('\n')[:-1]]
else:
# Add non-example text.
output += [_comment_line(l)
for l in piece.split('\n')[:-1]]
# Trim junk on both ends.
while output and output[-1] == '#':
output.pop()
while output and output[0] == '#':
output.pop(0)
# Combine the output, and return it.
return '\n'.join(output)
def testsource(module, name):
"""Extract the test sources from a doctest docstring as a script.
Provide the module (or dotted name of the module) containing the
test to be debugged and the name (within the module) of the object
with the doc string with tests to be debugged.
"""
module = _normalize_module(module)
tests = DocTestFinder().find(module)
test = [t for t in tests if t.name == name]
if not test:
raise ValueError(name, "not found in tests")
test = test[0]
testsrc = script_from_examples(test.docstring)
return testsrc
def debug_src(src, pm=False, globs=None):
"""Debug a single doctest docstring, in argument `src`'"""
testsrc = script_from_examples(src)
debug_script(testsrc, pm, globs)
def debug_script(src, pm=False, globs=None):
"Debug a test script. `src` is the script, as a string."
import pdb
# Note that tempfile.NameTemporaryFile() cannot be used. As the
# docs say, a file so created cannot be opened by name a second time
# on modern Windows boxes, and execfile() needs to open it.
srcfilename = tempfile.mktemp(".py", "doctestdebug")
f = open(srcfilename, 'w')
f.write(src)
f.close()
try:
if globs:
globs = globs.copy()
else:
globs = {}
if pm:
try:
execfile(srcfilename, globs, globs)
except:
print sys.exc_info()[1]
pdb.post_mortem(sys.exc_info()[2])
else:
# Note that %r is vital here. '%s' instead can, e.g., cause
# backslashes to get treated as metacharacters on Windows.
pdb.run("execfile(%r)" % srcfilename, globs, globs)
finally:
os.remove(srcfilename)
def debug(module, name, pm=False):
"""Debug a single doctest docstring.
Provide the module (or dotted name of the module) containing the
test to be debugged and the name (within the module) of the object
with the docstring with tests to be debugged.
"""
module = _normalize_module(module)
testsrc = testsource(module, name)
debug_script(testsrc, pm, module.__dict__)
######################################################################
## 10. Example Usage
######################################################################
class _TestClass:
"""
A pointless class, for sanity-checking of docstring testing.
Methods:
square()
get()
>>> _TestClass(13).get() + _TestClass(-12).get()
1
>>> hex(_TestClass(13).square().get())
'0xa9'
"""
def __init__(self, val):
"""val -> _TestClass object with associated value val.
>>> t = _TestClass(123)
>>> print t.get()
123
"""
self.val = val
def square(self):
"""square() -> square TestClass's associated value
>>> _TestClass(13).square().get()
169
"""
self.val = self.val ** 2
return self
def get(self):
"""get() -> return TestClass's associated value.
>>> x = _TestClass(-42)
>>> print x.get()
-42
"""
return self.val
__test__ = {"_TestClass": _TestClass,
"string": r"""
Example of a string object, searched as-is.
>>> x = 1; y = 2
>>> x + y, x * y
(3, 2)
""",
"bool-int equivalence": r"""
In 2.2, boolean expressions displayed
0 or 1. By default, we still accept
them. This can be disabled by passing
DONT_ACCEPT_TRUE_FOR_1 to the new
optionflags argument.
>>> 4 == 4
1
>>> 4 == 4
True
>>> 4 > 4
0
>>> 4 > 4
False
""",
"blank lines": r"""
Blank lines can be marked with <BLANKLINE>:
>>> print 'foo\n\nbar\n'
foo
<BLANKLINE>
bar
<BLANKLINE>
""",
"ellipsis": r"""
If the ellipsis flag is used, then '...' can be used to
elide substrings in the desired output:
>>> print range(1000) #doctest: +ELLIPSIS
[0, 1, 2, ..., 999]
""",
"whitespace normalization": r"""
If the whitespace normalization flag is used, then
differences in whitespace are ignored.
>>> print range(30) #doctest: +NORMALIZE_WHITESPACE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29]
""",
}
def _test():
r = unittest.TextTestRunner()
r.run(DocTestSuite())
if __name__ == "__main__":
_test()
| Python |
"""Filename globbing utility."""
import os
import fnmatch
import re
__all__ = ["glob"]
def glob(pathname):
"""Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la fnmatch.
"""
if not has_magic(pathname):
if os.path.lexists(pathname):
return [pathname]
else:
return []
dirname, basename = os.path.split(pathname)
if not dirname:
return glob1(os.curdir, basename)
elif has_magic(dirname):
list = glob(dirname)
else:
list = [dirname]
if not has_magic(basename):
result = []
for dirname in list:
if basename or os.path.isdir(dirname):
name = os.path.join(dirname, basename)
if os.path.lexists(name):
result.append(name)
else:
result = []
for dirname in list:
sublist = glob1(dirname, basename)
for name in sublist:
result.append(os.path.join(dirname, name))
return result
def glob1(dirname, pattern):
if not dirname: dirname = os.curdir
try:
names = os.listdir(dirname)
except os.error:
return []
if pattern[0]!='.':
names=filter(lambda x: x[0]!='.',names)
return fnmatch.filter(names,pattern)
magic_check = re.compile('[*?[]')
def has_magic(s):
return magic_check.search(s) is not None
| Python |
""" Locale support.
The module provides low-level access to the C lib's locale APIs
and adds high level number formatting APIs as well as a locale
aliasing engine to complement these.
The aliasing engine includes support for many commonly used locale
names and maps them to values suitable for passing to the C lib's
setlocale() function. It also includes default encodings for all
supported locale names.
"""
import sys
# Try importing the _locale module.
#
# If this fails, fall back on a basic 'C' locale emulation.
# Yuck: LC_MESSAGES is non-standard: can't tell whether it exists before
# trying the import. So __all__ is also fiddled at the end of the file.
__all__ = ["setlocale","Error","localeconv","strcoll","strxfrm",
"format","str","atof","atoi","LC_CTYPE","LC_COLLATE",
"LC_TIME","LC_MONETARY","LC_NUMERIC", "LC_ALL","CHAR_MAX"]
try:
from _locale import *
except ImportError:
# Locale emulation
CHAR_MAX = 127
LC_ALL = 6
LC_COLLATE = 3
LC_CTYPE = 0
LC_MESSAGES = 5
LC_MONETARY = 4
LC_NUMERIC = 1
LC_TIME = 2
Error = ValueError
def localeconv():
""" localeconv() -> dict.
Returns numeric and monetary locale-specific parameters.
"""
# 'C' locale default values
return {'grouping': [127],
'currency_symbol': '',
'n_sign_posn': 127,
'p_cs_precedes': 127,
'n_cs_precedes': 127,
'mon_grouping': [],
'n_sep_by_space': 127,
'decimal_point': '.',
'negative_sign': '',
'positive_sign': '',
'p_sep_by_space': 127,
'int_curr_symbol': '',
'p_sign_posn': 127,
'thousands_sep': '',
'mon_thousands_sep': '',
'frac_digits': 127,
'mon_decimal_point': '',
'int_frac_digits': 127}
def setlocale(category, value=None):
""" setlocale(integer,string=None) -> string.
Activates/queries locale processing.
"""
if value not in (None, '', 'C'):
raise Error, '_locale emulation only supports "C" locale'
return 'C'
def strcoll(a,b):
""" strcoll(string,string) -> int.
Compares two strings according to the locale.
"""
return cmp(a,b)
def strxfrm(s):
""" strxfrm(string) -> string.
Returns a string that behaves for cmp locale-aware.
"""
return s
### Number formatting APIs
# Author: Martin von Loewis
#perform the grouping from right to left
def _group(s):
conv=localeconv()
grouping=conv['grouping']
if not grouping:return (s, 0)
result=""
seps = 0
spaces = ""
if s[-1] == ' ':
sp = s.find(' ')
spaces = s[sp:]
s = s[:sp]
while s and grouping:
# if grouping is -1, we are done
if grouping[0]==CHAR_MAX:
break
# 0: re-use last group ad infinitum
elif grouping[0]!=0:
#process last group
group=grouping[0]
grouping=grouping[1:]
if result:
result=s[-group:]+conv['thousands_sep']+result
seps += 1
else:
result=s[-group:]
s=s[:-group]
if s and s[-1] not in "0123456789":
# the leading string is only spaces and signs
return s+result+spaces,seps
if not result:
return s+spaces,seps
if s:
result=s+conv['thousands_sep']+result
seps += 1
return result+spaces,seps
def format(f,val,grouping=0):
"""Formats a value in the same way that the % formatting would use,
but takes the current locale into account.
Grouping is applied if the third parameter is true."""
result = f % val
fields = result.split(".")
seps = 0
if grouping:
fields[0],seps=_group(fields[0])
if len(fields)==2:
result = fields[0]+localeconv()['decimal_point']+fields[1]
elif len(fields)==1:
result = fields[0]
else:
raise Error, "Too many decimal points in result string"
while seps:
# If the number was formatted for a specific width, then it
# might have been filled with spaces to the left or right. If
# so, kill as much spaces as there where separators.
# Leading zeroes as fillers are not yet dealt with, as it is
# not clear how they should interact with grouping.
sp = result.find(" ")
if sp==-1:break
result = result[:sp]+result[sp+1:]
seps -= 1
return result
def str(val):
"""Convert float to integer, taking the locale into account."""
return format("%.12g",val)
def atof(string,func=float):
"Parses a string as a float according to the locale settings."
#First, get rid of the grouping
ts = localeconv()['thousands_sep']
if ts:
string = string.replace(ts, '')
#next, replace the decimal point with a dot
dd = localeconv()['decimal_point']
if dd:
string = string.replace(dd, '.')
#finally, parse the string
return func(string)
def atoi(str):
"Converts a string to an integer according to the locale settings."
return atof(str, int)
def _test():
setlocale(LC_ALL, "")
#do grouping
s1=format("%d", 123456789,1)
print s1, "is", atoi(s1)
#standard formatting
s1=str(3.14)
print s1, "is", atof(s1)
### Locale name aliasing engine
# Author: Marc-Andre Lemburg, mal@lemburg.com
# Various tweaks by Fredrik Lundh <fredrik@pythonware.com>
# store away the low-level version of setlocale (it's
# overridden below)
_setlocale = setlocale
def normalize(localename):
""" Returns a normalized locale code for the given locale
name.
The returned locale code is formatted for use with
setlocale().
If normalization fails, the original name is returned
unchanged.
If the given encoding is not known, the function defaults to
the default encoding for the locale code just like setlocale()
does.
"""
# Normalize the locale name and extract the encoding
fullname = localename.lower()
if ':' in fullname:
# ':' is sometimes used as encoding delimiter.
fullname = fullname.replace(':', '.')
if '.' in fullname:
langname, encoding = fullname.split('.')[:2]
fullname = langname + '.' + encoding
else:
langname = fullname
encoding = ''
# First lookup: fullname (possibly with encoding)
code = locale_alias.get(fullname, None)
if code is not None:
return code
# Second try: langname (without encoding)
code = locale_alias.get(langname, None)
if code is not None:
if '.' in code:
langname, defenc = code.split('.')
else:
langname = code
defenc = ''
if encoding:
encoding = encoding_alias.get(encoding, encoding)
else:
encoding = defenc
if encoding:
return langname + '.' + encoding
else:
return langname
else:
return localename
def _parse_localename(localename):
""" Parses the locale code for localename and returns the
result as tuple (language code, encoding).
The localename is normalized and passed through the locale
alias engine. A ValueError is raised in case the locale name
cannot be parsed.
The language code corresponds to RFC 1766. code and encoding
can be None in case the values cannot be determined or are
unknown to this implementation.
"""
code = normalize(localename)
if '@' in localename:
# Deal with locale modifiers
code, modifier = code.split('@')
if modifier == 'euro' and '.' not in code:
# Assume Latin-9 for @euro locales. This is bogus,
# since some systems may use other encodings for these
# locales. Also, we ignore other modifiers.
return code, 'iso-8859-15'
if '.' in code:
return tuple(code.split('.')[:2])
elif code == 'C':
return None, None
raise ValueError, 'unknown locale: %s' % localename
def _build_localename(localetuple):
""" Builds a locale code from the given tuple (language code,
encoding).
No aliasing or normalizing takes place.
"""
language, encoding = localetuple
if language is None:
language = 'C'
if encoding is None:
return language
else:
return language + '.' + encoding
def getdefaultlocale(envvars=('LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LANG')):
""" Tries to determine the default locale settings and returns
them as tuple (language code, encoding).
According to POSIX, a program which has not called
setlocale(LC_ALL, "") runs using the portable 'C' locale.
Calling setlocale(LC_ALL, "") lets it use the default locale as
defined by the LANG variable. Since we don't want to interfere
with the current locale setting we thus emulate the behavior
in the way described above.
To maintain compatibility with other platforms, not only the
LANG variable is tested, but a list of variables given as
envvars parameter. The first found to be defined will be
used. envvars defaults to the search path used in GNU gettext;
it must always contain the variable name 'LANG'.
Except for the code 'C', the language code corresponds to RFC
1766. code and encoding can be None in case the values cannot
be determined.
"""
try:
# check if it's supported by the _locale module
import _locale
code, encoding = _locale._getdefaultlocale()
except (ImportError, AttributeError):
pass
else:
# make sure the code/encoding values are valid
if sys.platform == "win32" and code and code[:2] == "0x":
# map windows language identifier to language name
code = windows_locale.get(int(code, 0))
# ...add other platform-specific processing here, if
# necessary...
return code, encoding
# fall back on POSIX behaviour
import os
lookup = os.environ.get
for variable in envvars:
localename = lookup(variable,None)
if localename:
break
else:
localename = 'C'
return _parse_localename(localename)
def getlocale(category=LC_CTYPE):
""" Returns the current setting for the given locale category as
tuple (language code, encoding).
category may be one of the LC_* value except LC_ALL. It
defaults to LC_CTYPE.
Except for the code 'C', the language code corresponds to RFC
1766. code and encoding can be None in case the values cannot
be determined.
"""
localename = _setlocale(category)
if category == LC_ALL and ';' in localename:
raise TypeError, 'category LC_ALL is not supported'
return _parse_localename(localename)
def setlocale(category, locale=None):
""" Set the locale for the given category. The locale can be
a string, a locale tuple (language code, encoding), or None.
Locale tuples are converted to strings the locale aliasing
engine. Locale strings are passed directly to the C lib.
category may be given as one of the LC_* values.
"""
if locale and type(locale) is not type(""):
# convert to string
locale = normalize(_build_localename(locale))
return _setlocale(category, locale)
def resetlocale(category=LC_ALL):
""" Sets the locale for category to the default setting.
The default setting is determined by calling
getdefaultlocale(). category defaults to LC_ALL.
"""
_setlocale(category, _build_localename(getdefaultlocale()))
if sys.platform in ('win32', 'darwin', 'mac'):
# On Win32, this will return the ANSI code page
# On the Mac, it should return the system encoding;
# it might return "ascii" instead
def getpreferredencoding(do_setlocale = True):
"""Return the charset that the user is likely using."""
import _locale
return _locale._getdefaultlocale()[1]
else:
# On Unix, if CODESET is available, use that.
try:
CODESET
except NameError:
# Fall back to parsing environment variables :-(
def getpreferredencoding(do_setlocale = True):
"""Return the charset that the user is likely using,
by looking at environment variables."""
return getdefaultlocale()[1]
else:
def getpreferredencoding(do_setlocale = True):
"""Return the charset that the user is likely using,
according to the system configuration."""
if do_setlocale:
oldloc = setlocale(LC_CTYPE)
setlocale(LC_CTYPE, "")
result = nl_langinfo(CODESET)
setlocale(LC_CTYPE, oldloc)
return result
else:
return nl_langinfo(CODESET)
### Database
#
# The following data was extracted from the locale.alias file which
# comes with X11 and then hand edited removing the explicit encoding
# definitions and adding some more aliases. The file is usually
# available as /usr/lib/X11/locale/locale.alias.
#
#
# The encoding_alias table maps lowercase encoding alias names to C
# locale encoding names (case-sensitive).
#
encoding_alias = {
'437': 'C',
'c': 'C',
'iso8859': 'ISO8859-1',
'8859': 'ISO8859-1',
'88591': 'ISO8859-1',
'ascii': 'ISO8859-1',
'en': 'ISO8859-1',
'iso88591': 'ISO8859-1',
'iso_8859-1': 'ISO8859-1',
'885915': 'ISO8859-15',
'iso885915': 'ISO8859-15',
'iso_8859-15': 'ISO8859-15',
'iso8859-2': 'ISO8859-2',
'iso88592': 'ISO8859-2',
'iso_8859-2': 'ISO8859-2',
'iso88595': 'ISO8859-5',
'iso88596': 'ISO8859-6',
'iso88597': 'ISO8859-7',
'iso88598': 'ISO8859-8',
'iso88599': 'ISO8859-9',
'iso-2022-jp': 'JIS7',
'jis': 'JIS7',
'jis7': 'JIS7',
'sjis': 'SJIS',
'tis620': 'TACTIS',
'ajec': 'eucJP',
'eucjp': 'eucJP',
'ujis': 'eucJP',
'utf-8': 'utf',
'utf8': 'utf',
'utf8@ucs4': 'utf',
}
#
# The locale_alias table maps lowercase alias names to C locale names
# (case-sensitive). Encodings are always separated from the locale
# name using a dot ('.'); they should only be given in case the
# language name is needed to interpret the given encoding alias
# correctly (CJK codes often have this need).
#
locale_alias = {
'american': 'en_US.ISO8859-1',
'ar': 'ar_AA.ISO8859-6',
'ar_aa': 'ar_AA.ISO8859-6',
'ar_sa': 'ar_SA.ISO8859-6',
'arabic': 'ar_AA.ISO8859-6',
'bg': 'bg_BG.ISO8859-5',
'bg_bg': 'bg_BG.ISO8859-5',
'bulgarian': 'bg_BG.ISO8859-5',
'c-french': 'fr_CA.ISO8859-1',
'c': 'C',
'c_c': 'C',
'cextend': 'en_US.ISO8859-1',
'chinese-s': 'zh_CN.eucCN',
'chinese-t': 'zh_TW.eucTW',
'croatian': 'hr_HR.ISO8859-2',
'cs': 'cs_CZ.ISO8859-2',
'cs_cs': 'cs_CZ.ISO8859-2',
'cs_cz': 'cs_CZ.ISO8859-2',
'cz': 'cz_CZ.ISO8859-2',
'cz_cz': 'cz_CZ.ISO8859-2',
'czech': 'cs_CS.ISO8859-2',
'da': 'da_DK.ISO8859-1',
'da_dk': 'da_DK.ISO8859-1',
'danish': 'da_DK.ISO8859-1',
'de': 'de_DE.ISO8859-1',
'de_at': 'de_AT.ISO8859-1',
'de_ch': 'de_CH.ISO8859-1',
'de_de': 'de_DE.ISO8859-1',
'dutch': 'nl_BE.ISO8859-1',
'ee': 'ee_EE.ISO8859-4',
'el': 'el_GR.ISO8859-7',
'el_gr': 'el_GR.ISO8859-7',
'en': 'en_US.ISO8859-1',
'en_au': 'en_AU.ISO8859-1',
'en_ca': 'en_CA.ISO8859-1',
'en_gb': 'en_GB.ISO8859-1',
'en_ie': 'en_IE.ISO8859-1',
'en_nz': 'en_NZ.ISO8859-1',
'en_uk': 'en_GB.ISO8859-1',
'en_us': 'en_US.ISO8859-1',
'eng_gb': 'en_GB.ISO8859-1',
'english': 'en_EN.ISO8859-1',
'english_uk': 'en_GB.ISO8859-1',
'english_united-states': 'en_US.ISO8859-1',
'english_us': 'en_US.ISO8859-1',
'es': 'es_ES.ISO8859-1',
'es_ar': 'es_AR.ISO8859-1',
'es_bo': 'es_BO.ISO8859-1',
'es_cl': 'es_CL.ISO8859-1',
'es_co': 'es_CO.ISO8859-1',
'es_cr': 'es_CR.ISO8859-1',
'es_ec': 'es_EC.ISO8859-1',
'es_es': 'es_ES.ISO8859-1',
'es_gt': 'es_GT.ISO8859-1',
'es_mx': 'es_MX.ISO8859-1',
'es_ni': 'es_NI.ISO8859-1',
'es_pa': 'es_PA.ISO8859-1',
'es_pe': 'es_PE.ISO8859-1',
'es_py': 'es_PY.ISO8859-1',
'es_sv': 'es_SV.ISO8859-1',
'es_uy': 'es_UY.ISO8859-1',
'es_ve': 'es_VE.ISO8859-1',
'et': 'et_EE.ISO8859-4',
'et_ee': 'et_EE.ISO8859-4',
'fi': 'fi_FI.ISO8859-1',
'fi_fi': 'fi_FI.ISO8859-1',
'finnish': 'fi_FI.ISO8859-1',
'fr': 'fr_FR.ISO8859-1',
'fr_be': 'fr_BE.ISO8859-1',
'fr_ca': 'fr_CA.ISO8859-1',
'fr_ch': 'fr_CH.ISO8859-1',
'fr_fr': 'fr_FR.ISO8859-1',
'fre_fr': 'fr_FR.ISO8859-1',
'french': 'fr_FR.ISO8859-1',
'french_france': 'fr_FR.ISO8859-1',
'ger_de': 'de_DE.ISO8859-1',
'german': 'de_DE.ISO8859-1',
'german_germany': 'de_DE.ISO8859-1',
'greek': 'el_GR.ISO8859-7',
'hebrew': 'iw_IL.ISO8859-8',
'hr': 'hr_HR.ISO8859-2',
'hr_hr': 'hr_HR.ISO8859-2',
'hu': 'hu_HU.ISO8859-2',
'hu_hu': 'hu_HU.ISO8859-2',
'hungarian': 'hu_HU.ISO8859-2',
'icelandic': 'is_IS.ISO8859-1',
'id': 'id_ID.ISO8859-1',
'id_id': 'id_ID.ISO8859-1',
'is': 'is_IS.ISO8859-1',
'is_is': 'is_IS.ISO8859-1',
'iso-8859-1': 'en_US.ISO8859-1',
'iso-8859-15': 'en_US.ISO8859-15',
'iso8859-1': 'en_US.ISO8859-1',
'iso8859-15': 'en_US.ISO8859-15',
'iso_8859_1': 'en_US.ISO8859-1',
'iso_8859_15': 'en_US.ISO8859-15',
'it': 'it_IT.ISO8859-1',
'it_ch': 'it_CH.ISO8859-1',
'it_it': 'it_IT.ISO8859-1',
'italian': 'it_IT.ISO8859-1',
'iw': 'iw_IL.ISO8859-8',
'iw_il': 'iw_IL.ISO8859-8',
'ja': 'ja_JP.eucJP',
'ja.jis': 'ja_JP.JIS7',
'ja.sjis': 'ja_JP.SJIS',
'ja_jp': 'ja_JP.eucJP',
'ja_jp.ajec': 'ja_JP.eucJP',
'ja_jp.euc': 'ja_JP.eucJP',
'ja_jp.eucjp': 'ja_JP.eucJP',
'ja_jp.iso-2022-jp': 'ja_JP.JIS7',
'ja_jp.jis': 'ja_JP.JIS7',
'ja_jp.jis7': 'ja_JP.JIS7',
'ja_jp.mscode': 'ja_JP.SJIS',
'ja_jp.sjis': 'ja_JP.SJIS',
'ja_jp.ujis': 'ja_JP.eucJP',
'japan': 'ja_JP.eucJP',
'japanese': 'ja_JP.SJIS',
'japanese-euc': 'ja_JP.eucJP',
'japanese.euc': 'ja_JP.eucJP',
'jp_jp': 'ja_JP.eucJP',
'ko': 'ko_KR.eucKR',
'ko_kr': 'ko_KR.eucKR',
'ko_kr.euc': 'ko_KR.eucKR',
'korean': 'ko_KR.eucKR',
'lt': 'lt_LT.ISO8859-4',
'lv': 'lv_LV.ISO8859-4',
'mk': 'mk_MK.ISO8859-5',
'mk_mk': 'mk_MK.ISO8859-5',
'nl': 'nl_NL.ISO8859-1',
'nl_be': 'nl_BE.ISO8859-1',
'nl_nl': 'nl_NL.ISO8859-1',
'no': 'no_NO.ISO8859-1',
'no_no': 'no_NO.ISO8859-1',
'norwegian': 'no_NO.ISO8859-1',
'pl': 'pl_PL.ISO8859-2',
'pl_pl': 'pl_PL.ISO8859-2',
'polish': 'pl_PL.ISO8859-2',
'portuguese': 'pt_PT.ISO8859-1',
'portuguese_brazil': 'pt_BR.ISO8859-1',
'posix': 'C',
'posix-utf2': 'C',
'pt': 'pt_PT.ISO8859-1',
'pt_br': 'pt_BR.ISO8859-1',
'pt_pt': 'pt_PT.ISO8859-1',
'ro': 'ro_RO.ISO8859-2',
'ro_ro': 'ro_RO.ISO8859-2',
'ru': 'ru_RU.ISO8859-5',
'ru_ru': 'ru_RU.ISO8859-5',
'rumanian': 'ro_RO.ISO8859-2',
'russian': 'ru_RU.ISO8859-5',
'serbocroatian': 'sh_YU.ISO8859-2',
'sh': 'sh_YU.ISO8859-2',
'sh_hr': 'sh_HR.ISO8859-2',
'sh_sp': 'sh_YU.ISO8859-2',
'sh_yu': 'sh_YU.ISO8859-2',
'sk': 'sk_SK.ISO8859-2',
'sk_sk': 'sk_SK.ISO8859-2',
'sl': 'sl_CS.ISO8859-2',
'sl_cs': 'sl_CS.ISO8859-2',
'sl_si': 'sl_SI.ISO8859-2',
'slovak': 'sk_SK.ISO8859-2',
'slovene': 'sl_CS.ISO8859-2',
'sp': 'sp_YU.ISO8859-5',
'sp_yu': 'sp_YU.ISO8859-5',
'spanish': 'es_ES.ISO8859-1',
'spanish_spain': 'es_ES.ISO8859-1',
'sr_sp': 'sr_SP.ISO8859-2',
'sv': 'sv_SE.ISO8859-1',
'sv_se': 'sv_SE.ISO8859-1',
'swedish': 'sv_SE.ISO8859-1',
'th_th': 'th_TH.TACTIS',
'tr': 'tr_TR.ISO8859-9',
'tr_tr': 'tr_TR.ISO8859-9',
'turkish': 'tr_TR.ISO8859-9',
'univ': 'en_US.utf',
'universal': 'en_US.utf',
'zh': 'zh_CN.eucCN',
'zh_cn': 'zh_CN.eucCN',
'zh_cn.big5': 'zh_TW.eucTW',
'zh_cn.euc': 'zh_CN.eucCN',
'zh_tw': 'zh_TW.eucTW',
'zh_tw.euc': 'zh_TW.eucTW',
}
#
# this maps windows language identifiers (as used on Windows 95 and
# earlier) to locale strings.
#
# NOTE: this mapping is incomplete. If your language is missing, please
# submit a bug report to Python bug manager, which you can find via:
# http://www.python.org/dev/
# Make sure you include the missing language identifier and the suggested
# locale code.
#
windows_locale = {
0x0404: "zh_TW", # Chinese (Taiwan)
0x0804: "zh_CN", # Chinese (PRC)
0x0406: "da_DK", # Danish
0x0413: "nl_NL", # Dutch (Netherlands)
0x0409: "en_US", # English (United States)
0x0809: "en_UK", # English (United Kingdom)
0x0c09: "en_AU", # English (Australian)
0x1009: "en_CA", # English (Canadian)
0x1409: "en_NZ", # English (New Zealand)
0x1809: "en_IE", # English (Ireland)
0x1c09: "en_ZA", # English (South Africa)
0x040b: "fi_FI", # Finnish
0x040c: "fr_FR", # French (Standard)
0x080c: "fr_BE", # French (Belgian)
0x0c0c: "fr_CA", # French (Canadian)
0x100c: "fr_CH", # French (Switzerland)
0x0407: "de_DE", # German (Standard)
0x0408: "el_GR", # Greek
0x040d: "iw_IL", # Hebrew
0x040f: "is_IS", # Icelandic
0x0410: "it_IT", # Italian (Standard)
0x0411: "ja_JA", # Japanese
0x0414: "no_NO", # Norwegian (Bokmal)
0x0816: "pt_PT", # Portuguese (Standard)
0x0c0a: "es_ES", # Spanish (Modern Sort)
0x0441: "sw_KE", # Swahili (Kenya)
0x041d: "sv_SE", # Swedish
0x081d: "sv_FI", # Swedish (Finland)
0x041f: "tr_TR", # Turkish
}
def _print_locale():
""" Test function.
"""
categories = {}
def _init_categories(categories=categories):
for k,v in globals().items():
if k[:3] == 'LC_':
categories[k] = v
_init_categories()
del categories['LC_ALL']
print 'Locale defaults as determined by getdefaultlocale():'
print '-'*72
lang, enc = getdefaultlocale()
print 'Language: ', lang or '(undefined)'
print 'Encoding: ', enc or '(undefined)'
print
print 'Locale settings on startup:'
print '-'*72
for name,category in categories.items():
print name, '...'
lang, enc = getlocale(category)
print ' Language: ', lang or '(undefined)'
print ' Encoding: ', enc or '(undefined)'
print
print
print 'Locale settings after calling resetlocale():'
print '-'*72
resetlocale()
for name,category in categories.items():
print name, '...'
lang, enc = getlocale(category)
print ' Language: ', lang or '(undefined)'
print ' Encoding: ', enc or '(undefined)'
print
try:
setlocale(LC_ALL, "")
except:
print 'NOTE:'
print 'setlocale(LC_ALL, "") does not support the default locale'
print 'given in the OS environment variables.'
else:
print
print 'Locale settings after calling setlocale(LC_ALL, ""):'
print '-'*72
for name,category in categories.items():
print name, '...'
lang, enc = getlocale(category)
print ' Language: ', lang or '(undefined)'
print ' Encoding: ', enc or '(undefined)'
print
###
try:
LC_MESSAGES
except NameError:
pass
else:
__all__.append("LC_MESSAGES")
if __name__=='__main__':
print 'Locale aliasing:'
print
_print_locale()
print
print 'Number formatting:'
print
_test()
| Python |
"""Recognize image file formats based on their first few bytes."""
__all__ = ["what"]
#-------------------------#
# Recognize image headers #
#-------------------------#
def what(file, h=None):
if h is None:
if type(file) == type(''):
f = open(file, 'rb')
h = f.read(32)
else:
location = file.tell()
h = file.read(32)
file.seek(location)
f = None
else:
f = None
try:
for tf in tests:
res = tf(h, f)
if res:
return res
finally:
if f: f.close()
return None
#---------------------------------#
# Subroutines per image file type #
#---------------------------------#
tests = []
def test_rgb(h, f):
"""SGI image library"""
if h[:2] == '\001\332':
return 'rgb'
tests.append(test_rgb)
def test_gif(h, f):
"""GIF ('87 and '89 variants)"""
if h[:6] in ('GIF87a', 'GIF89a'):
return 'gif'
tests.append(test_gif)
def test_pbm(h, f):
"""PBM (portable bitmap)"""
if len(h) >= 3 and \
h[0] == 'P' and h[1] in '14' and h[2] in ' \t\n\r':
return 'pbm'
tests.append(test_pbm)
def test_pgm(h, f):
"""PGM (portable graymap)"""
if len(h) >= 3 and \
h[0] == 'P' and h[1] in '25' and h[2] in ' \t\n\r':
return 'pgm'
tests.append(test_pgm)
def test_ppm(h, f):
"""PPM (portable pixmap)"""
if len(h) >= 3 and \
h[0] == 'P' and h[1] in '36' and h[2] in ' \t\n\r':
return 'ppm'
tests.append(test_ppm)
def test_tiff(h, f):
"""TIFF (can be in Motorola or Intel byte order)"""
if h[:2] in ('MM', 'II'):
return 'tiff'
tests.append(test_tiff)
def test_rast(h, f):
"""Sun raster file"""
if h[:4] == '\x59\xA6\x6A\x95':
return 'rast'
tests.append(test_rast)
def test_xbm(h, f):
"""X bitmap (X10 or X11)"""
s = '#define '
if h[:len(s)] == s:
return 'xbm'
tests.append(test_xbm)
def test_jpeg(h, f):
"""JPEG data in JFIF format"""
if h[6:10] == 'JFIF':
return 'jpeg'
tests.append(test_jpeg)
def test_bmp(h, f):
if h[:2] == 'BM':
return 'bmp'
tests.append(test_bmp)
def test_png(h, f):
if h[:8] == "\211PNG\r\n\032\n":
return 'png'
tests.append(test_png)
#--------------------#
# Small test program #
#--------------------#
def test():
import sys
recursive = 0
if sys.argv[1:] and sys.argv[1] == '-r':
del sys.argv[1:2]
recursive = 1
try:
if sys.argv[1:]:
testall(sys.argv[1:], recursive, 1)
else:
testall(['.'], recursive, 1)
except KeyboardInterrupt:
sys.stderr.write('\n[Interrupted]\n')
sys.exit(1)
def testall(list, recursive, toplevel):
import sys
import os
for filename in list:
if os.path.isdir(filename):
print filename + '/:',
if recursive or toplevel:
print 'recursing down:'
import glob
names = glob.glob(os.path.join(filename, '*'))
testall(names, recursive, 0)
else:
print '*** directory (use -r) ***'
else:
print filename + ':',
sys.stdout.flush()
try:
print what(filename)
except IOError:
print '*** not found ***'
| Python |
"""aetypes - Python objects representing various AE types."""
from Carbon.AppleEvents import *
import struct
from types import *
import string
#
# convoluted, since there are cyclic dependencies between this file and
# aetools_convert.
#
def pack(*args, **kwargs):
from aepack import pack
return pack( *args, **kwargs)
def nice(s):
"""'nice' representation of an object"""
if type(s) is StringType: return repr(s)
else: return str(s)
class Unknown:
"""An uninterpreted AE object"""
def __init__(self, type, data):
self.type = type
self.data = data
def __repr__(self):
return "Unknown(%r, %r)" % (self.type, self.data)
def __aepack__(self):
return pack(self.data, self.type)
class Enum:
"""An AE enumeration value"""
def __init__(self, enum):
self.enum = "%-4.4s" % str(enum)
def __repr__(self):
return "Enum(%r)" % (self.enum,)
def __str__(self):
return string.strip(self.enum)
def __aepack__(self):
return pack(self.enum, typeEnumeration)
def IsEnum(x):
return isinstance(x, Enum)
def mkenum(enum):
if IsEnum(enum): return enum
return Enum(enum)
# Jack changed the way this is done
class InsertionLoc:
def __init__(self, of, pos):
self.of = of
self.pos = pos
def __repr__(self):
return "InsertionLoc(%r, %r)" % (self.of, self.pos)
def __aepack__(self):
rec = {'kobj': self.of, 'kpos': self.pos}
return pack(rec, forcetype='insl')
# Convenience functions for dsp:
def beginning(of):
return InsertionLoc(of, Enum('bgng'))
def end(of):
return InsertionLoc(of, Enum('end '))
class Boolean:
"""An AE boolean value"""
def __init__(self, bool):
self.bool = (not not bool)
def __repr__(self):
return "Boolean(%r)" % (self.bool,)
def __str__(self):
if self.bool:
return "True"
else:
return "False"
def __aepack__(self):
return pack(struct.pack('b', self.bool), 'bool')
def IsBoolean(x):
return isinstance(x, Boolean)
def mkboolean(bool):
if IsBoolean(bool): return bool
return Boolean(bool)
class Type:
"""An AE 4-char typename object"""
def __init__(self, type):
self.type = "%-4.4s" % str(type)
def __repr__(self):
return "Type(%r)" % (self.type,)
def __str__(self):
return string.strip(self.type)
def __aepack__(self):
return pack(self.type, typeType)
def IsType(x):
return isinstance(x, Type)
def mktype(type):
if IsType(type): return type
return Type(type)
class Keyword:
"""An AE 4-char keyword object"""
def __init__(self, keyword):
self.keyword = "%-4.4s" % str(keyword)
def __repr__(self):
return "Keyword(%r)" % `self.keyword`
def __str__(self):
return string.strip(self.keyword)
def __aepack__(self):
return pack(self.keyword, typeKeyword)
def IsKeyword(x):
return isinstance(x, Keyword)
class Range:
"""An AE range object"""
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __repr__(self):
return "Range(%r, %r)" % (self.start, self.stop)
def __str__(self):
return "%s thru %s" % (nice(self.start), nice(self.stop))
def __aepack__(self):
return pack({'star': self.start, 'stop': self.stop}, 'rang')
def IsRange(x):
return isinstance(x, Range)
class Comparison:
"""An AE Comparison"""
def __init__(self, obj1, relo, obj2):
self.obj1 = obj1
self.relo = "%-4.4s" % str(relo)
self.obj2 = obj2
def __repr__(self):
return "Comparison(%r, %r, %r)" % (self.obj1, self.relo, self.obj2)
def __str__(self):
return "%s %s %s" % (nice(self.obj1), string.strip(self.relo), nice(self.obj2))
def __aepack__(self):
return pack({'obj1': self.obj1,
'relo': mkenum(self.relo),
'obj2': self.obj2},
'cmpd')
def IsComparison(x):
return isinstance(x, Comparison)
class NComparison(Comparison):
# The class attribute 'relo' must be set in a subclass
def __init__(self, obj1, obj2):
Comparison.__init__(obj1, self.relo, obj2)
class Ordinal:
"""An AE Ordinal"""
def __init__(self, abso):
# self.obj1 = obj1
self.abso = "%-4.4s" % str(abso)
def __repr__(self):
return "Ordinal(%r)" % (self.abso,)
def __str__(self):
return "%s" % (string.strip(self.abso))
def __aepack__(self):
return pack(self.abso, 'abso')
def IsOrdinal(x):
return isinstance(x, Ordinal)
class NOrdinal(Ordinal):
# The class attribute 'abso' must be set in a subclass
def __init__(self):
Ordinal.__init__(self, self.abso)
class Logical:
"""An AE logical expression object"""
def __init__(self, logc, term):
self.logc = "%-4.4s" % str(logc)
self.term = term
def __repr__(self):
return "Logical(%r, %r)" % (self.logc, self.term)
def __str__(self):
if type(self.term) == ListType and len(self.term) == 2:
return "%s %s %s" % (nice(self.term[0]),
string.strip(self.logc),
nice(self.term[1]))
else:
return "%s(%s)" % (string.strip(self.logc), nice(self.term))
def __aepack__(self):
return pack({'logc': mkenum(self.logc), 'term': self.term}, 'logi')
def IsLogical(x):
return isinstance(x, Logical)
class StyledText:
"""An AE object respresenting text in a certain style"""
def __init__(self, style, text):
self.style = style
self.text = text
def __repr__(self):
return "StyledText(%r, %r)" % (self.style, self.text)
def __str__(self):
return self.text
def __aepack__(self):
return pack({'ksty': self.style, 'ktxt': self.text}, 'STXT')
def IsStyledText(x):
return isinstance(x, StyledText)
class AEText:
"""An AE text object with style, script and language specified"""
def __init__(self, script, style, text):
self.script = script
self.style = style
self.text = text
def __repr__(self):
return "AEText(%r, %r, %r)" % (self.script, self.style, self.text)
def __str__(self):
return self.text
def __aepack__(self):
return pack({keyAEScriptTag: self.script, keyAEStyles: self.style,
keyAEText: self.text}, typeAEText)
def IsAEText(x):
return isinstance(x, AEText)
class IntlText:
"""A text object with script and language specified"""
def __init__(self, script, language, text):
self.script = script
self.language = language
self.text = text
def __repr__(self):
return "IntlText(%r, %r, %r)" % (self.script, self.language, self.text)
def __str__(self):
return self.text
def __aepack__(self):
return pack(struct.pack('hh', self.script, self.language)+self.text,
typeIntlText)
def IsIntlText(x):
return isinstance(x, IntlText)
class IntlWritingCode:
"""An object representing script and language"""
def __init__(self, script, language):
self.script = script
self.language = language
def __repr__(self):
return "IntlWritingCode(%r, %r)" % (self.script, self.language)
def __str__(self):
return "script system %d, language %d"%(self.script, self.language)
def __aepack__(self):
return pack(struct.pack('hh', self.script, self.language),
typeIntlWritingCode)
def IsIntlWritingCode(x):
return isinstance(x, IntlWritingCode)
class QDPoint:
"""A point"""
def __init__(self, v, h):
self.v = v
self.h = h
def __repr__(self):
return "QDPoint(%r, %r)" % (self.v, self.h)
def __str__(self):
return "(%d, %d)"%(self.v, self.h)
def __aepack__(self):
return pack(struct.pack('hh', self.v, self.h),
typeQDPoint)
def IsQDPoint(x):
return isinstance(x, QDPoint)
class QDRectangle:
"""A rectangle"""
def __init__(self, v0, h0, v1, h1):
self.v0 = v0
self.h0 = h0
self.v1 = v1
self.h1 = h1
def __repr__(self):
return "QDRectangle(%r, %r, %r, %r)" % (self.v0, self.h0, self.v1, self.h1)
def __str__(self):
return "(%d, %d)-(%d, %d)"%(self.v0, self.h0, self.v1, self.h1)
def __aepack__(self):
return pack(struct.pack('hhhh', self.v0, self.h0, self.v1, self.h1),
typeQDRectangle)
def IsQDRectangle(x):
return isinstance(x, QDRectangle)
class RGBColor:
"""An RGB color"""
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __repr__(self):
return "RGBColor(%r, %r, %r)" % (self.r, self.g, self.b)
def __str__(self):
return "0x%x red, 0x%x green, 0x%x blue"% (self.r, self.g, self.b)
def __aepack__(self):
return pack(struct.pack('hhh', self.r, self.g, self.b),
typeRGBColor)
def IsRGBColor(x):
return isinstance(x, RGBColor)
class ObjectSpecifier:
"""A class for constructing and manipulation AE object specifiers in python.
An object specifier is actually a record with four fields:
key type description
--- ---- -----------
'want' type 4-char class code of thing we want,
e.g. word, paragraph or property
'form' enum how we specify which 'want' thing(s) we want,
e.g. by index, by range, by name, or by property specifier
'seld' any which thing(s) we want,
e.g. its index, its name, or its property specifier
'from' object the object in which it is contained,
or null, meaning look for it in the application
Note that we don't call this class plain "Object", since that name
is likely to be used by the application.
"""
def __init__(self, want, form, seld, fr = None):
self.want = want
self.form = form
self.seld = seld
self.fr = fr
def __repr__(self):
s = "ObjectSpecifier(%r, %r, %r" % (self.want, self.form, self.seld)
if self.fr:
s = s + ", %r)" % (self.fr,)
else:
s = s + ")"
return s
def __aepack__(self):
return pack({'want': mktype(self.want),
'form': mkenum(self.form),
'seld': self.seld,
'from': self.fr},
'obj ')
def IsObjectSpecifier(x):
return isinstance(x, ObjectSpecifier)
# Backwards compatability, sigh...
class Property(ObjectSpecifier):
def __init__(self, which, fr = None, want='prop'):
ObjectSpecifier.__init__(self, want, 'prop', mktype(which), fr)
def __repr__(self):
if self.fr:
return "Property(%r, %r)" % (self.seld.type, self.fr)
else:
return "Property(%r)" % (self.seld.type,)
def __str__(self):
if self.fr:
return "Property %s of %s" % (str(self.seld), str(self.fr))
else:
return "Property %s" % str(self.seld)
class NProperty(ObjectSpecifier):
# Subclasses *must* self baseclass attributes:
# want is the type of this property
# which is the property name of this property
def __init__(self, fr = None):
#try:
# dummy = self.want
#except:
# self.want = 'prop'
self.want = 'prop'
ObjectSpecifier.__init__(self, self.want, 'prop',
mktype(self.which), fr)
def __repr__(self):
rv = "Property(%r" % (self.seld.type,)
if self.fr:
rv = rv + ", fr=%r" % (self.fr,)
if self.want != 'prop':
rv = rv + ", want=%r" % (self.want,)
return rv + ")"
def __str__(self):
if self.fr:
return "Property %s of %s" % (str(self.seld), str(self.fr))
else:
return "Property %s" % str(self.seld)
class SelectableItem(ObjectSpecifier):
def __init__(self, want, seld, fr = None):
t = type(seld)
if t == StringType:
form = 'name'
elif IsRange(seld):
form = 'rang'
elif IsComparison(seld) or IsLogical(seld):
form = 'test'
elif t == TupleType:
# Breakout: specify both form and seld in a tuple
# (if you want ID or rele or somesuch)
form, seld = seld
else:
form = 'indx'
ObjectSpecifier.__init__(self, want, form, seld, fr)
class ComponentItem(SelectableItem):
# Derived classes *must* set the *class attribute* 'want' to some constant
# Also, dictionaries _propdict and _elemdict must be set to map property
# and element names to the correct classes
_propdict = {}
_elemdict = {}
def __init__(self, which, fr = None):
SelectableItem.__init__(self, self.want, which, fr)
def __repr__(self):
if not self.fr:
return "%s(%r)" % (self.__class__.__name__, self.seld)
return "%s(%r, %r)" % (self.__class__.__name__, self.seld, self.fr)
def __str__(self):
seld = self.seld
if type(seld) == StringType:
ss = repr(seld)
elif IsRange(seld):
start, stop = seld.start, seld.stop
if type(start) == InstanceType == type(stop) and \
start.__class__ == self.__class__ == stop.__class__:
ss = str(start.seld) + " thru " + str(stop.seld)
else:
ss = str(seld)
else:
ss = str(seld)
s = "%s %s" % (self.__class__.__name__, ss)
if self.fr: s = s + " of %s" % str(self.fr)
return s
def __getattr__(self, name):
if self._elemdict.has_key(name):
cls = self._elemdict[name]
return DelayedComponentItem(cls, self)
if self._propdict.has_key(name):
cls = self._propdict[name]
return cls(self)
raise AttributeError, name
class DelayedComponentItem:
def __init__(self, compclass, fr):
self.compclass = compclass
self.fr = fr
def __call__(self, which):
return self.compclass(which, self.fr)
def __repr__(self):
return "%s(???, %r)" % (self.__class__.__name__, self.fr)
def __str__(self):
return "selector for element %s of %s"%(self.__class__.__name__, str(self.fr))
template = """
class %s(ComponentItem): want = '%s'
"""
exec template % ("Text", 'text')
exec template % ("Character", 'cha ')
exec template % ("Word", 'cwor')
exec template % ("Line", 'clin')
exec template % ("paragraph", 'cpar')
exec template % ("Window", 'cwin')
exec template % ("Document", 'docu')
exec template % ("File", 'file')
exec template % ("InsertionPoint", 'cins')
| Python |
"""argvemulator - create sys.argv from OSA events. Used by applets that
want unix-style arguments.
"""
import sys
import traceback
from Carbon import AE
from Carbon.AppleEvents import *
from Carbon import Evt
from Carbon.Events import *
import aetools
class ArgvCollector:
"""A minimal FrameWork.Application-like class"""
def __init__(self):
self.quitting = 0
self.ae_handlers = {}
# Remove the funny -psn_xxx_xxx argument
if len(sys.argv) > 1 and sys.argv[1][:4] == '-psn':
del sys.argv[1]
self.installaehandler('aevt', 'oapp', self.open_app)
self.installaehandler('aevt', 'odoc', self.open_file)
def installaehandler(self, classe, type, callback):
AE.AEInstallEventHandler(classe, type, self.callback_wrapper)
self.ae_handlers[(classe, type)] = callback
def close(self):
for classe, type in self.ae_handlers.keys():
AE.AERemoveEventHandler(classe, type)
def mainloop(self, mask = highLevelEventMask, timeout = 1*60):
stoptime = Evt.TickCount() + timeout
while not self.quitting and Evt.TickCount() < stoptime:
self.dooneevent(mask, timeout)
self.close()
def _quit(self):
self.quitting = 1
def dooneevent(self, mask = highLevelEventMask, timeout = 1*60):
got, event = Evt.WaitNextEvent(mask, timeout)
if got:
self.lowlevelhandler(event)
def lowlevelhandler(self, event):
what, message, when, where, modifiers = event
h, v = where
if what == kHighLevelEvent:
try:
AE.AEProcessAppleEvent(event)
except AE.Error, err:
msg = "High Level Event: %r %r" % (hex(message), hex(h | (v<<16)))
print 'AE error: ', err
print 'in', msg
traceback.print_exc()
return
else:
print "Unhandled event:", event
def callback_wrapper(self, _request, _reply):
_parameters, _attributes = aetools.unpackevent(_request)
_class = _attributes['evcl'].type
_type = _attributes['evid'].type
if self.ae_handlers.has_key((_class, _type)):
_function = self.ae_handlers[(_class, _type)]
elif self.ae_handlers.has_key((_class, '****')):
_function = self.ae_handlers[(_class, '****')]
elif self.ae_handlers.has_key(('****', '****')):
_function = self.ae_handlers[('****', '****')]
else:
raise 'Cannot happen: AE callback without handler', (_class, _type)
# XXXX Do key-to-name mapping here
_parameters['_attributes'] = _attributes
_parameters['_class'] = _class
_parameters['_type'] = _type
if _parameters.has_key('----'):
_object = _parameters['----']
del _parameters['----']
# The try/except that used to be here can mask programmer errors.
# Let the program crash, the programmer can always add a **args
# to the formal parameter list.
rv = _function(_object, **_parameters)
else:
#Same try/except comment as above
rv = _function(**_parameters)
if rv == None:
aetools.packevent(_reply, {})
else:
aetools.packevent(_reply, {'----':rv})
def open_app(self, **args):
self._quit()
def open_file(self, _object=None, **args):
for alias in _object:
fsr = alias.FSResolveAlias(None)[0]
pathname = fsr.as_pathname()
sys.argv.append(pathname)
self._quit()
def other(self, _object=None, _class=None, _type=None, **args):
print 'Ignore AppleEvent', (_class, _type), 'for', _object, 'Other args:', args
if __name__ == '__main__':
ArgvCollector().mainloop()
print "sys.argv=", sys.argv
| Python |
r"""Routines to decode AppleSingle files
"""
import struct
import sys
try:
import MacOS
import Carbon.File
except:
class MacOS:
def openrf(path, mode):
return open(path + '.rsrc', mode)
openrf = classmethod(openrf)
class Carbon:
class File:
class FSSpec:
pass
class FSRef:
pass
class Alias:
pass
# all of the errors in this module are really errors in the input
# so I think it should test positive against ValueError.
class Error(ValueError):
pass
# File header format: magic, version, unused, number of entries
AS_HEADER_FORMAT="LL16sh"
AS_HEADER_LENGTH=26
# The flag words for AppleSingle
AS_MAGIC=0x00051600
AS_VERSION=0x00020000
# Entry header format: id, offset, length
AS_ENTRY_FORMAT="lll"
AS_ENTRY_LENGTH=12
# The id values
AS_DATAFORK=1
AS_RESOURCEFORK=2
AS_IGNORE=(3,4,5,6,8,9,10,11,12,13,14,15)
class AppleSingle(object):
datafork = None
resourcefork = None
def __init__(self, fileobj, verbose=False):
header = fileobj.read(AS_HEADER_LENGTH)
try:
magic, version, ig, nentry = struct.unpack(AS_HEADER_FORMAT, header)
except ValueError, arg:
raise Error, "Unpack header error: %s" % (arg,)
if verbose:
print 'Magic: 0x%8.8x' % (magic,)
print 'Version: 0x%8.8x' % (version,)
print 'Entries: %d' % (nentry,)
if magic != AS_MAGIC:
raise Error, "Unknown AppleSingle magic number 0x%8.8x" % (magic,)
if version != AS_VERSION:
raise Error, "Unknown AppleSingle version number 0x%8.8x" % (version,)
if nentry <= 0:
raise Error, "AppleSingle file contains no forks"
headers = [fileobj.read(AS_ENTRY_LENGTH) for i in xrange(nentry)]
self.forks = []
for hdr in headers:
try:
restype, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr)
except ValueError, arg:
raise Error, "Unpack entry error: %s" % (arg,)
if verbose:
print "Fork %d, offset %d, length %d" % (restype, offset, length)
fileobj.seek(offset)
data = fileobj.read(length)
if len(data) != length:
raise Error, "Short read: expected %d bytes got %d" % (length, len(data))
self.forks.append((restype, data))
if restype == AS_DATAFORK:
self.datafork = data
elif restype == AS_RESOURCEFORK:
self.resourcefork = data
def tofile(self, path, resonly=False):
outfile = open(path, 'wb')
data = False
if resonly:
if self.resourcefork is None:
raise Error, "No resource fork found"
fp = open(path, 'wb')
fp.write(self.resourcefork)
fp.close()
elif (self.resourcefork is None and self.datafork is None):
raise Error, "No useful forks found"
else:
if self.datafork is not None:
fp = open(path, 'wb')
fp.write(self.datafork)
fp.close()
if self.resourcefork is not None:
fp = MacOS.openrf(path, '*wb')
fp.write(self.resourcefork)
fp.close()
def decode(infile, outpath, resonly=False, verbose=False):
"""decode(infile, outpath [, resonly=False, verbose=False])
Creates a decoded file from an AppleSingle encoded file.
If resonly is True, then it will create a regular file at
outpath containing only the resource fork from infile.
Otherwise it will create an AppleDouble file at outpath
with the data and resource forks from infile. On platforms
without the MacOS module, it will create inpath and inpath+'.rsrc'
with the data and resource forks respectively.
"""
if not hasattr(infile, 'read'):
if isinstance(infile, Carbon.File.Alias):
infile = infile.ResolveAlias()[0]
if isinstance(infile, (Carbon.File.FSSpec, Carbon.File.FSRef)):
infile = infile.as_pathname()
infile = open(infile, 'rb')
as = AppleSingle(infile, verbose=verbose)
as.tofile(outpath, resonly=resonly)
def _test():
if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4:
print 'Usage: applesingle.py [-r] applesinglefile decodedfile'
sys.exit(1)
if sys.argv[1] == '-r':
resonly = True
del sys.argv[1]
else:
resonly = False
decode(sys.argv[1], sys.argv[2], resonly=resonly)
if __name__ == '__main__':
_test()
| Python |
"""Utility routines depending on the finder,
a combination of code by Jack Jansen and erik@letterror.com.
Most events have been captured from
Lasso Capture AE and than translated to python code.
IMPORTANT
Note that the processes() function returns different values
depending on the OS version it is running on. On MacOS 9
the Finder returns the process *names* which can then be
used to find out more about them. On MacOS 8.6 and earlier
the Finder returns a code which does not seem to work.
So bottom line: the processes() stuff does not work on < MacOS9
Mostly written by erik@letterror.com
"""
import Finder
from Carbon import AppleEvents
import aetools
import MacOS
import sys
import Carbon.File
import Carbon.Folder
import aetypes
from types import *
__version__ = '1.1'
Error = 'findertools.Error'
_finder_talker = None
def _getfinder():
"""returns basic (recyclable) Finder AE interface object"""
global _finder_talker
if not _finder_talker:
_finder_talker = Finder.Finder()
_finder_talker.send_flags = ( _finder_talker.send_flags |
AppleEvents.kAECanInteract | AppleEvents.kAECanSwitchLayer)
return _finder_talker
def launch(file):
"""Open a file thru the finder. Specify file by name or fsspec"""
finder = _getfinder()
fss = Carbon.File.FSSpec(file)
return finder.open(fss)
def Print(file):
"""Print a file thru the finder. Specify file by name or fsspec"""
finder = _getfinder()
fss = Carbon.File.FSSpec(file)
return finder._print(fss)
def copy(src, dstdir):
"""Copy a file to a folder"""
finder = _getfinder()
if type(src) == type([]):
src_fss = []
for s in src:
src_fss.append(Carbon.File.FSSpec(s))
else:
src_fss = Carbon.File.FSSpec(src)
dst_fss = Carbon.File.FSSpec(dstdir)
return finder.duplicate(src_fss, to=dst_fss)
def move(src, dstdir):
"""Move a file to a folder"""
finder = _getfinder()
if type(src) == type([]):
src_fss = []
for s in src:
src_fss.append(Carbon.File.FSSpec(s))
else:
src_fss = Carbon.File.FSSpec(src)
dst_fss = Carbon.File.FSSpec(dstdir)
return finder.move(src_fss, to=dst_fss)
def sleep():
"""Put the mac to sleep"""
finder = _getfinder()
finder.sleep()
def shutdown():
"""Shut the mac down"""
finder = _getfinder()
finder.shut_down()
def restart():
"""Restart the mac"""
finder = _getfinder()
finder.restart()
#---------------------------------------------------
# Additional findertools
#
def reveal(file):
"""Reveal a file in the finder. Specify file by name, fsref or fsspec."""
finder = _getfinder()
fsr = Carbon.File.FSRef(file)
file_alias = fsr.FSNewAliasMinimal()
return finder.reveal(file_alias)
def select(file):
"""select a file in the finder. Specify file by name, fsref or fsspec."""
finder = _getfinder()
fsr = Carbon.File.FSRef(file)
file_alias = fsr.FSNewAliasMinimal()
return finder.select(file_alias)
def update(file):
"""Update the display of the specified object(s) to match
their on-disk representation. Specify file by name, fsref or fsspec."""
finder = _getfinder()
fsr = Carbon.File.FSRef(file)
file_alias = fsr.FSNewAliasMinimal()
return finder.update(file_alias)
#---------------------------------------------------
# More findertools
#
def comment(object, comment=None):
"""comment: get or set the Finder-comment of the item, displayed in the 'Get Info' window."""
object = Carbon.File.FSRef(object)
object_alias = object.FSNewAliasMonimal()
if comment == None:
return _getcomment(object_alias)
else:
return _setcomment(object_alias, comment)
def _setcomment(object_alias, comment):
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), form="alis", seld=object_alias, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('comt'), fr=aeobj_00)
args['----'] = aeobj_01
args["data"] = comment
_reply, args, attrs = finder.send("core", "setd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
def _getcomment(object_alias):
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), form="alis", seld=object_alias, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('comt'), fr=aeobj_00)
args['----'] = aeobj_01
_reply, args, attrs = finder.send("core", "getd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
#---------------------------------------------------
# Get information about current processes in the Finder.
def processes():
"""processes returns a list of all active processes running on this computer and their creators."""
finder = _getfinder()
args = {}
attrs = {}
processnames = []
processnumbers = []
creators = []
partitions = []
used = []
## get the processnames or else the processnumbers
args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="indx", seld=aetypes.Unknown('abso', "all "), fr=None)
_reply, args, attrs = finder.send('core', 'getd', args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
p = []
if args.has_key('----'):
p = args['----']
for proc in p:
if hasattr(proc, 'seld'):
# it has a real name
processnames.append(proc.seld)
elif hasattr(proc, 'type'):
if proc.type == "psn ":
# it has a process number
processnumbers.append(proc.data)
## get the creators
args = {}
attrs = {}
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="indx", seld=aetypes.Unknown('abso', "all "), fr=None)
args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fcrt'), fr=aeobj_0)
_reply, args, attrs = finder.send('core', 'getd', args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(_arg)
if args.has_key('----'):
p = args['----']
creators = p[:]
## concatenate in one dict
result = []
if len(processnames) > len(processnumbers):
data = processnames
else:
data = processnumbers
for i in range(len(creators)):
result.append((data[i], creators[i]))
return result
class _process:
pass
def isactiveprocess(processname):
"""Check of processname is active. MacOS9"""
all = processes()
ok = 0
for n, c in all:
if n == processname:
return 1
return 0
def processinfo(processname):
"""Return an object with all process properties as attributes for processname. MacOS9"""
p = _process()
if processname == "Finder":
p.partition = None
p.used = None
else:
p.partition = _processproperty(processname, 'appt')
p.used = _processproperty(processname, 'pusd')
p.visible = _processproperty(processname, 'pvis') #Is the process' layer visible?
p.frontmost = _processproperty(processname, 'pisf') #Is the process the frontmost process?
p.file = _processproperty(processname, 'file') #the file from which the process was launched
p.filetype = _processproperty(processname, 'asty') #the OSType of the file type of the process
p.creatortype = _processproperty(processname, 'fcrt') #the OSType of the creator of the process (the signature)
p.accepthighlevel = _processproperty(processname, 'revt') #Is the process high-level event aware (accepts open application, open document, print document, and quit)?
p.hasscripting = _processproperty(processname, 'hscr') #Does the process have a scripting terminology, i.e., can it be scripted?
return p
def _processproperty(processname, property):
"""return the partition size and memory used for processname"""
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="name", seld=processname, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type(property), fr=aeobj_00)
args['----'] = aeobj_01
_reply, args, attrs = finder.send("core", "getd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
#---------------------------------------------------
# Mess around with Finder windows.
def openwindow(object):
"""Open a Finder window for object, Specify object by name or fsspec."""
finder = _getfinder()
object = Carbon.File.FSRef(object)
object_alias = object.FSNewAliasMinimal()
args = {}
attrs = {}
_code = 'aevt'
_subcode = 'odoc'
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None)
args['----'] = aeobj_0
_reply, args, attrs = finder.send(_code, _subcode, args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
def closewindow(object):
"""Close a Finder window for folder, Specify by path."""
finder = _getfinder()
object = Carbon.File.FSRef(object)
object_alias = object.FSNewAliasMinimal()
args = {}
attrs = {}
_code = 'core'
_subcode = 'clos'
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None)
args['----'] = aeobj_0
_reply, args, attrs = finder.send(_code, _subcode, args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
def location(object, pos=None):
"""Set the position of a Finder window for folder to pos=(w, h). Specify file by name or fsspec.
If pos=None, location will return the current position of the object."""
object = Carbon.File.FSRef(object)
object_alias = object.FSNewAliasMinimal()
if not pos:
return _getlocation(object_alias)
return _setlocation(object_alias, pos)
def _setlocation(object_alias, (x, y)):
"""_setlocation: Set the location of the icon for the object."""
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('posn'), fr=aeobj_00)
args['----'] = aeobj_01
args["data"] = [x, y]
_reply, args, attrs = finder.send("core", "setd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
return (x,y)
def _getlocation(object_alias):
"""_getlocation: get the location of the icon for the object."""
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('posn'), fr=aeobj_00)
args['----'] = aeobj_01
_reply, args, attrs = finder.send("core", "getd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
pos = args['----']
return pos.h, pos.v
def label(object, index=None):
"""label: set or get the label of the item. Specify file by name or fsspec."""
object = Carbon.File.FSRef(object)
object_alias = object.FSNewAliasMinimal()
if index == None:
return _getlabel(object_alias)
if index < 0 or index > 7:
index = 0
return _setlabel(object_alias, index)
def _getlabel(object_alias):
"""label: Get the label for the object."""
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'), form="alis", seld=object_alias, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('labi'), fr=aeobj_00)
args['----'] = aeobj_01
_reply, args, attrs = finder.send("core", "getd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
def _setlabel(object_alias, index):
"""label: Set the label for the object."""
finder = _getfinder()
args = {}
attrs = {}
_code = 'core'
_subcode = 'setd'
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="alis", seld=object_alias, fr=None)
aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('labi'), fr=aeobj_0)
args['----'] = aeobj_1
args["data"] = index
_reply, args, attrs = finder.send(_code, _subcode, args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
return index
def windowview(folder, view=None):
"""windowview: Set the view of the window for the folder. Specify file by name or fsspec.
0 = by icon (default)
1 = by name
2 = by button
"""
fsr = Carbon.File.FSRef(folder)
folder_alias = fsr.FSNewAliasMinimal()
if view == None:
return _getwindowview(folder_alias)
return _setwindowview(folder_alias, view)
def _setwindowview(folder_alias, view=0):
"""set the windowview"""
attrs = {}
args = {}
if view == 1:
_v = aetypes.Type('pnam')
elif view == 2:
_v = aetypes.Type('lgbu')
else:
_v = aetypes.Type('iimg')
finder = _getfinder()
aeobj_0 = aetypes.ObjectSpecifier(want = aetypes.Type('cfol'),
form = 'alis', seld = folder_alias, fr=None)
aeobj_1 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'),
form = 'prop', seld = aetypes.Type('cwnd'), fr=aeobj_0)
aeobj_2 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'),
form = 'prop', seld = aetypes.Type('pvew'), fr=aeobj_1)
aeobj_3 = aetypes.ObjectSpecifier(want = aetypes.Type('prop'),
form = 'prop', seld = _v, fr=None)
_code = 'core'
_subcode = 'setd'
args['----'] = aeobj_2
args['data'] = aeobj_3
_reply, args, attrs = finder.send(_code, _subcode, args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
def _getwindowview(folder_alias):
"""get the windowview"""
attrs = {}
args = {}
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=folder_alias, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_00)
aeobj_02 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('pvew'), fr=aeobj_01)
args['----'] = aeobj_02
_reply, args, attrs = finder.send("core", "getd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
views = {'iimg':0, 'pnam':1, 'lgbu':2}
if args.has_key('----'):
return views[args['----'].enum]
def windowsize(folder, size=None):
"""Set the size of a Finder window for folder to size=(w, h), Specify by path.
If size=None, windowsize will return the current size of the window.
Specify file by name or fsspec.
"""
fsr = Carbon.File.FSRef(folder)
folder_alias = fsr.FSNewAliasMinimal()
openwindow(fsr)
if not size:
return _getwindowsize(folder_alias)
return _setwindowsize(folder_alias, size)
def _setwindowsize(folder_alias, (w, h)):
"""Set the size of a Finder window for folder to (w, h)"""
finder = _getfinder()
args = {}
attrs = {}
_code = 'core'
_subcode = 'setd'
aevar00 = [w, h]
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
form="alis", seld=folder_alias, fr=None)
aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0)
aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('ptsz'), fr=aeobj_1)
args['----'] = aeobj_2
args["data"] = aevar00
_reply, args, attrs = finder.send(_code, _subcode, args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
return (w, h)
def _getwindowsize(folder_alias):
"""Set the size of a Finder window for folder to (w, h)"""
finder = _getfinder()
args = {}
attrs = {}
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
form="alis", seld=folder_alias, fr=None)
aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0)
aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('posn'), fr=aeobj_1)
args['----'] = aeobj_2
_reply, args, attrs = finder.send('core', 'getd', args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
def windowposition(folder, pos=None):
"""Set the position of a Finder window for folder to pos=(w, h)."""
fsr = Carbon.File.FSRef(folder)
folder_alias = fsr.FSNewAliasMinimal()
openwindow(fsr)
if not pos:
return _getwindowposition(folder_alias)
if type(pos) == InstanceType:
# pos might be a QDPoint object as returned by _getwindowposition
pos = (pos.h, pos.v)
return _setwindowposition(folder_alias, pos)
def _setwindowposition(folder_alias, (x, y)):
"""Set the size of a Finder window for folder to (w, h)."""
finder = _getfinder()
args = {}
attrs = {}
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
form="alis", seld=folder_alias, fr=None)
aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0)
aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('posn'), fr=aeobj_1)
args['----'] = aeobj_2
args["data"] = [x, y]
_reply, args, attrs = finder.send('core', 'setd', args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
def _getwindowposition(folder_alias):
"""Get the size of a Finder window for folder, Specify by path."""
finder = _getfinder()
args = {}
attrs = {}
aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'),
form="alis", seld=folder_alias, fr=None)
aeobj_1 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('cwnd'), fr=aeobj_0)
aeobj_2 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('ptsz'), fr=aeobj_1)
args['----'] = aeobj_2
_reply, args, attrs = finder.send('core', 'getd', args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
def icon(object, icondata=None):
"""icon sets the icon of object, if no icondata is given,
icon will return an AE object with binary data for the current icon.
If left untouched, this data can be used to paste the icon on another file.
Development opportunity: get and set the data as PICT."""
fsr = Carbon.File.FSRef(object)
object_alias = fsr.FSNewAliasMinimal()
if icondata == None:
return _geticon(object_alias)
return _seticon(object_alias, icondata)
def _geticon(object_alias):
"""get the icondata for object. Binary data of some sort."""
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'),
form="alis", seld=object_alias, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('iimg'), fr=aeobj_00)
args['----'] = aeobj_01
_reply, args, attrs = finder.send("core", "getd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
def _seticon(object_alias, icondata):
"""set the icondata for object, formatted as produced by _geticon()"""
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('cobj'),
form="alis", seld=object_alias, fr=None)
aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'),
form="prop", seld=aetypes.Type('iimg'), fr=aeobj_00)
args['----'] = aeobj_01
args["data"] = icondata
_reply, args, attrs = finder.send("core", "setd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----'].data
#---------------------------------------------------
# Volumes and servers.
def mountvolume(volume, server=None, username=None, password=None):
"""mount a volume, local or on a server on AppleTalk.
Note: mounting a ASIP server requires a different operation.
server is the name of the server where the volume belongs
username, password belong to a registered user of the volume."""
finder = _getfinder()
args = {}
attrs = {}
if password:
args["PASS"] = password
if username:
args["USER"] = username
if server:
args["SRVR"] = server
args['----'] = volume
_reply, args, attrs = finder.send("aevt", "mvol", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
def unmountvolume(volume):
"""unmount a volume that's on the desktop"""
putaway(volume)
def putaway(object):
"""puth the object away, whereever it came from."""
finder = _getfinder()
args = {}
attrs = {}
args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('cdis'), form="name", seld=object, fr=None)
_reply, args, attrs = talker.send("fndr", "ptwy", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
#---------------------------------------------------
# Miscellaneous functions
#
def volumelevel(level):
"""set the audio output level, parameter between 0 (silent) and 7 (full blast)"""
finder = _getfinder()
args = {}
attrs = {}
if level < 0:
level = 0
elif level > 7:
level = 7
args['----'] = level
_reply, args, attrs = finder.send("aevt", "stvl", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
def OSversion():
"""return the version of the system software"""
finder = _getfinder()
args = {}
attrs = {}
aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('ver2'), fr=None)
args['----'] = aeobj_00
_reply, args, attrs = finder.send("core", "getd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
return args['----']
def filesharing():
"""return the current status of filesharing and whether it is starting up or not:
-1 file sharing is off and not starting up
0 file sharing is off and starting up
1 file sharing is on"""
status = -1
finder = _getfinder()
# see if it is on
args = {}
attrs = {}
args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fshr'), fr=None)
_reply, args, attrs = finder.send("core", "getd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
if args['----'] == 0:
status = -1
else:
status = 1
# is it starting up perchance?
args = {}
attrs = {}
args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fsup'), fr=None)
_reply, args, attrs = finder.send("core", "getd", args, attrs)
if args.has_key('errn'):
raise Error, aetools.decodeerror(args)
if args.has_key('----'):
if args['----'] == 1:
status = 0
return status
def movetotrash(path):
"""move the object to the trash"""
fss = Carbon.File.FSSpec(path)
trashfolder = Carbon.Folder.FSFindFolder(fss.as_tuple()[0], 'trsh', 0)
move(path, trashfolder)
def emptytrash():
"""empty the trash"""
finder = _getfinder()
args = {}
attrs = {}
args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('trsh'), fr=None)
_reply, args, attrs = finder.send("fndr", "empt", args, attrs)
if args.has_key('errn'):
raise aetools.Error, aetools.decodeerror(args)
def _test():
import EasyDialogs
print 'Original findertools functionality test...'
print 'Testing launch...'
pathname = EasyDialogs.AskFileForOpen('File to launch:')
if pathname:
result = launch(pathname)
if result:
print 'Result: ', result
print 'Press return-',
sys.stdin.readline()
print 'Testing print...'
pathname = EasyDialogs.AskFileForOpen('File to print:')
if pathname:
result = Print(pathname)
if result:
print 'Result: ', result
print 'Press return-',
sys.stdin.readline()
print 'Testing copy...'
pathname = EasyDialogs.AskFileForOpen('File to copy:')
if pathname:
destdir = EasyDialogs.AskFolder('Destination:')
if destdir:
result = copy(pathname, destdir)
if result:
print 'Result:', result
print 'Press return-',
sys.stdin.readline()
print 'Testing move...'
pathname = EasyDialogs.AskFileForOpen('File to move:')
if pathname:
destdir = EasyDialogs.AskFolder('Destination:')
if destdir:
result = move(pathname, destdir)
if result:
print 'Result:', result
print 'Press return-',
sys.stdin.readline()
print 'Testing sleep...'
if EasyDialogs.AskYesNoCancel('Sleep?') > 0:
result = sleep()
if result:
print 'Result:', result
print 'Press return-',
sys.stdin.readline()
print 'Testing shutdown...'
if EasyDialogs.AskYesNoCancel('Shut down?') > 0:
result = shutdown()
if result:
print 'Result:', result
print 'Press return-',
sys.stdin.readline()
print 'Testing restart...'
if EasyDialogs.AskYesNoCancel('Restart?') > 0:
result = restart()
if result:
print 'Result:', result
print 'Press return-',
sys.stdin.readline()
def _test2():
print '\nmorefindertools version %s\nTests coming up...' %__version__
import os
import random
# miscellaneous
print '\tfilesharing on?', filesharing() # is file sharing on, off, starting up?
print '\tOS version', OSversion() # the version of the system software
# set the soundvolume in a simple way
print '\tSystem beep volume'
for i in range(0, 7):
volumelevel(i)
MacOS.SysBeep()
# Finder's windows, file location, file attributes
open("@findertoolstest", "w")
f = "@findertoolstest"
reveal(f) # reveal this file in a Finder window
select(f) # select this file
base, file = os.path.split(f)
closewindow(base) # close the window this file is in (opened by reveal)
openwindow(base) # open it again
windowview(base, 1) # set the view by list
label(f, 2) # set the label of this file to something orange
print '\tlabel', label(f) # get the label of this file
# the file location only works in a window with icon view!
print 'Random locations for an icon'
windowview(base, 0) # set the view by icon
windowsize(base, (600, 600))
for i in range(50):
location(f, (random.randint(10, 590), random.randint(10, 590)))
windowsize(base, (200, 400))
windowview(base, 1) # set the view by icon
orgpos = windowposition(base)
print 'Animated window location'
for i in range(10):
pos = (100+i*10, 100+i*10)
windowposition(base, pos)
print '\twindow position', pos
windowposition(base, orgpos) # park it where it was before
print 'Put a comment in file', f, ':'
print '\t', comment(f) # print the Finder comment this file has
s = 'This is a comment no one reads!'
comment(f, s) # set the Finder comment
def _test3():
print 'MacOS9 or better specific functions'
# processes
pr = processes() # return a list of tuples with (active_processname, creatorcode)
print 'Return a list of current active processes:'
for p in pr:
print '\t', p
# get attributes of the first process in the list
print 'Attributes of the first process in the list:'
pinfo = processinfo(pr[0][0])
print '\t', pr[0][0]
print '\t\tmemory partition', pinfo.partition # the memory allocated to this process
print '\t\tmemory used', pinfo.used # the memory actuall used by this process
print '\t\tis visible', pinfo.visible # is the process visible to the user
print '\t\tis frontmost', pinfo.frontmost # is the process the front most one?
print '\t\thas scripting', pinfo.hasscripting # is the process scriptable?
print '\t\taccepts high level events', pinfo.accepthighlevel # does the process accept high level appleevents?
if __name__ == '__main__':
_test()
_test2()
_test3()
| Python |
from _AH import *
| Python |
# Generated from 'MacHelp.h'
def FOUR_CHAR_CODE(x): return x
kMacHelpVersion = 0x0003
kHMSupplyContent = 0
kHMDisposeContent = 1
kHMNoContent = FOUR_CHAR_CODE('none')
kHMCFStringContent = FOUR_CHAR_CODE('cfst')
kHMPascalStrContent = FOUR_CHAR_CODE('pstr')
kHMStringResContent = FOUR_CHAR_CODE('str#')
kHMTEHandleContent = FOUR_CHAR_CODE('txth')
kHMTextResContent = FOUR_CHAR_CODE('text')
kHMStrResContent = FOUR_CHAR_CODE('str ')
kHMDefaultSide = 0
kHMOutsideTopScriptAligned = 1
kHMOutsideLeftCenterAligned = 2
kHMOutsideBottomScriptAligned = 3
kHMOutsideRightCenterAligned = 4
kHMOutsideTopLeftAligned = 5
kHMOutsideTopRightAligned = 6
kHMOutsideLeftTopAligned = 7
kHMOutsideLeftBottomAligned = 8
kHMOutsideBottomLeftAligned = 9
kHMOutsideBottomRightAligned = 10
kHMOutsideRightTopAligned = 11
kHMOutsideRightBottomAligned = 12
kHMOutsideTopCenterAligned = 13
kHMOutsideBottomCenterAligned = 14
kHMInsideRightCenterAligned = 15
kHMInsideLeftCenterAligned = 16
kHMInsideBottomCenterAligned = 17
kHMInsideTopCenterAligned = 18
kHMInsideTopLeftCorner = 19
kHMInsideTopRightCorner = 20
kHMInsideBottomLeftCorner = 21
kHMInsideBottomRightCorner = 22
kHMAbsoluteCenterAligned = 23
kHMTopSide = kHMOutsideTopScriptAligned
kHMLeftSide = kHMOutsideLeftCenterAligned
kHMBottomSide = kHMOutsideBottomScriptAligned
kHMRightSide = kHMOutsideRightCenterAligned
kHMTopLeftCorner = kHMOutsideTopLeftAligned
kHMTopRightCorner = kHMOutsideTopRightAligned
kHMLeftTopCorner = kHMOutsideLeftTopAligned
kHMLeftBottomCorner = kHMOutsideLeftBottomAligned
kHMBottomLeftCorner = kHMOutsideBottomLeftAligned
kHMBottomRightCorner = kHMOutsideBottomRightAligned
kHMRightTopCorner = kHMOutsideRightTopAligned
kHMRightBottomCorner = kHMOutsideRightBottomAligned
kHMContentProvided = 0
kHMContentNotProvided = 1
kHMContentNotProvidedDontPropagate = 2
kHMMinimumContentIndex = 0
kHMMaximumContentIndex = 1
errHMIllegalContentForMinimumState = -10980
errHMIllegalContentForMaximumState = -10981
kHMIllegalContentForMinimumState = errHMIllegalContentForMinimumState
kHelpTagEventHandlerTag = FOUR_CHAR_CODE('hevt')
| Python |
# Generated from 'Lists.h'
def FOUR_CHAR_CODE(x): return x
listNotifyNothing = FOUR_CHAR_CODE('nada')
listNotifyClick = FOUR_CHAR_CODE('clik')
listNotifyDoubleClick = FOUR_CHAR_CODE('dblc')
listNotifyPreClick = FOUR_CHAR_CODE('pclk')
lDrawingModeOffBit = 3
lDoVAutoscrollBit = 1
lDoHAutoscrollBit = 0
lDrawingModeOff = 8
lDoVAutoscroll = 2
lDoHAutoscroll = 1
lOnlyOneBit = 7
lExtendDragBit = 6
lNoDisjointBit = 5
lNoExtendBit = 4
lNoRectBit = 3
lUseSenseBit = 2
lNoNilHiliteBit = 1
lOnlyOne = -128
lExtendDrag = 64
lNoDisjoint = 32
lNoExtend = 16
lNoRect = 8
lUseSense = 4
lNoNilHilite = 2
lInitMsg = 0
lDrawMsg = 1
lHiliteMsg = 2
lCloseMsg = 3
kListDefProcPtr = 0
kListDefUserProcType = kListDefProcPtr
kListDefStandardTextType = 1
kListDefStandardIconType = 2
| Python |
# Generated from 'Sound.h'
def FOUR_CHAR_CODE(x): return x
soundListRsrc = FOUR_CHAR_CODE('snd ')
kSimpleBeepID = 1
# rate48khz = (long)0xBB800000
# rate44khz = (long)0xAC440000
rate32khz = 0x7D000000
rate22050hz = 0x56220000
rate22khz = 0x56EE8BA3
rate16khz = 0x3E800000
rate11khz = 0x2B7745D1
rate11025hz = 0x2B110000
rate8khz = 0x1F400000
sampledSynth = 5
squareWaveSynth = 1
waveTableSynth = 3
MACE3snthID = 11
MACE6snthID = 13
kMiddleC = 60
kNoVolume = 0
kFullVolume = 0x0100
stdQLength = 128
dataOffsetFlag = 0x8000
kUseOptionalOutputDevice = -1
notCompressed = 0
fixedCompression = -1
variableCompression = -2
twoToOne = 1
eightToThree = 2
threeToOne = 3
sixToOne = 4
sixToOnePacketSize = 8
threeToOnePacketSize = 16
stateBlockSize = 64
leftOverBlockSize = 32
firstSoundFormat = 0x0001
secondSoundFormat = 0x0002
dbBufferReady = 0x00000001
dbLastBuffer = 0x00000004
sysBeepDisable = 0x0000
sysBeepEnable = (1 << 0)
sysBeepSynchronous = (1 << 1)
unitTypeNoSelection = 0xFFFF
unitTypeSeconds = 0x0000
stdSH = 0x00
extSH = 0xFF
cmpSH = 0xFE
nullCmd = 0
quietCmd = 3
flushCmd = 4
reInitCmd = 5
waitCmd = 10
pauseCmd = 11
resumeCmd = 12
callBackCmd = 13
syncCmd = 14
availableCmd = 24
versionCmd = 25
volumeCmd = 46
getVolumeCmd = 47
clockComponentCmd = 50
getClockComponentCmd = 51
scheduledSoundCmd = 52
linkSoundComponentsCmd = 53
soundCmd = 80
bufferCmd = 81
rateMultiplierCmd = 86
getRateMultiplierCmd = 87
initCmd = 1
freeCmd = 2
totalLoadCmd = 26
loadCmd = 27
freqDurationCmd = 40
restCmd = 41
freqCmd = 42
ampCmd = 43
timbreCmd = 44
getAmpCmd = 45
waveTableCmd = 60
phaseCmd = 61
rateCmd = 82
continueCmd = 83
doubleBufferCmd = 84
getRateCmd = 85
sizeCmd = 90
convertCmd = 91
waveInitChannelMask = 0x07
waveInitChannel0 = 0x04
waveInitChannel1 = 0x05
waveInitChannel2 = 0x06
waveInitChannel3 = 0x07
initChan0 = waveInitChannel0
initChan1 = waveInitChannel1
initChan2 = waveInitChannel2
initChan3 = waveInitChannel3
outsideCmpSH = 0
insideCmpSH = 1
aceSuccess = 0
aceMemFull = 1
aceNilBlock = 2
aceBadComp = 3
aceBadEncode = 4
aceBadDest = 5
aceBadCmd = 6
initChanLeft = 0x0002
initChanRight = 0x0003
initNoInterp = 0x0004
initNoDrop = 0x0008
initMono = 0x0080
initStereo = 0x00C0
initMACE3 = 0x0300
initMACE6 = 0x0400
initPanMask = 0x0003
initSRateMask = 0x0030
initStereoMask = 0x00C0
initCompMask = 0xFF00
siActiveChannels = FOUR_CHAR_CODE('chac')
siActiveLevels = FOUR_CHAR_CODE('lmac')
siAGCOnOff = FOUR_CHAR_CODE('agc ')
siAsync = FOUR_CHAR_CODE('asyn')
siAVDisplayBehavior = FOUR_CHAR_CODE('avdb')
siChannelAvailable = FOUR_CHAR_CODE('chav')
siCompressionAvailable = FOUR_CHAR_CODE('cmav')
siCompressionChannels = FOUR_CHAR_CODE('cpct')
siCompressionFactor = FOUR_CHAR_CODE('cmfa')
siCompressionHeader = FOUR_CHAR_CODE('cmhd')
siCompressionNames = FOUR_CHAR_CODE('cnam')
siCompressionParams = FOUR_CHAR_CODE('evaw')
siCompressionSampleRate = FOUR_CHAR_CODE('cprt')
siCompressionType = FOUR_CHAR_CODE('comp')
siContinuous = FOUR_CHAR_CODE('cont')
siDecompressionParams = FOUR_CHAR_CODE('wave')
siDeviceBufferInfo = FOUR_CHAR_CODE('dbin')
siDeviceConnected = FOUR_CHAR_CODE('dcon')
siDeviceIcon = FOUR_CHAR_CODE('icon')
siDeviceName = FOUR_CHAR_CODE('name')
siEQSpectrumBands = FOUR_CHAR_CODE('eqsb')
siEQSpectrumLevels = FOUR_CHAR_CODE('eqlv')
siEQSpectrumOnOff = FOUR_CHAR_CODE('eqlo')
siEQSpectrumResolution = FOUR_CHAR_CODE('eqrs')
siEQToneControlGain = FOUR_CHAR_CODE('eqtg')
siEQToneControlOnOff = FOUR_CHAR_CODE('eqtc')
siHardwareBalance = FOUR_CHAR_CODE('hbal')
siHardwareBalanceSteps = FOUR_CHAR_CODE('hbls')
siHardwareBass = FOUR_CHAR_CODE('hbas')
siHardwareBassSteps = FOUR_CHAR_CODE('hbst')
siHardwareBusy = FOUR_CHAR_CODE('hwbs')
siHardwareFormat = FOUR_CHAR_CODE('hwfm')
siHardwareMute = FOUR_CHAR_CODE('hmut')
siHardwareMuteNoPrefs = FOUR_CHAR_CODE('hmnp')
siHardwareTreble = FOUR_CHAR_CODE('htrb')
siHardwareTrebleSteps = FOUR_CHAR_CODE('hwts')
siHardwareVolume = FOUR_CHAR_CODE('hvol')
siHardwareVolumeSteps = FOUR_CHAR_CODE('hstp')
siHeadphoneMute = FOUR_CHAR_CODE('pmut')
siHeadphoneVolume = FOUR_CHAR_CODE('pvol')
siHeadphoneVolumeSteps = FOUR_CHAR_CODE('hdst')
siInputAvailable = FOUR_CHAR_CODE('inav')
siInputGain = FOUR_CHAR_CODE('gain')
siInputSource = FOUR_CHAR_CODE('sour')
siInputSourceNames = FOUR_CHAR_CODE('snam')
siLevelMeterOnOff = FOUR_CHAR_CODE('lmet')
siModemGain = FOUR_CHAR_CODE('mgai')
siMonitorAvailable = FOUR_CHAR_CODE('mnav')
siMonitorSource = FOUR_CHAR_CODE('mons')
siNumberChannels = FOUR_CHAR_CODE('chan')
siOptionsDialog = FOUR_CHAR_CODE('optd')
siOSTypeInputSource = FOUR_CHAR_CODE('inpt')
siOSTypeInputAvailable = FOUR_CHAR_CODE('inav')
siOutputDeviceName = FOUR_CHAR_CODE('onam')
siPlayThruOnOff = FOUR_CHAR_CODE('plth')
siPostMixerSoundComponent = FOUR_CHAR_CODE('psmx')
siPreMixerSoundComponent = FOUR_CHAR_CODE('prmx')
siQuality = FOUR_CHAR_CODE('qual')
siRateMultiplier = FOUR_CHAR_CODE('rmul')
siRecordingQuality = FOUR_CHAR_CODE('qual')
siSampleRate = FOUR_CHAR_CODE('srat')
siSampleRateAvailable = FOUR_CHAR_CODE('srav')
siSampleSize = FOUR_CHAR_CODE('ssiz')
siSampleSizeAvailable = FOUR_CHAR_CODE('ssav')
siSetupCDAudio = FOUR_CHAR_CODE('sucd')
siSetupModemAudio = FOUR_CHAR_CODE('sumd')
siSlopeAndIntercept = FOUR_CHAR_CODE('flap')
siSoundClock = FOUR_CHAR_CODE('sclk')
siUseThisSoundClock = FOUR_CHAR_CODE('sclc')
siSpeakerMute = FOUR_CHAR_CODE('smut')
siSpeakerVolume = FOUR_CHAR_CODE('svol')
siSSpCPULoadLimit = FOUR_CHAR_CODE('3dll')
siSSpLocalization = FOUR_CHAR_CODE('3dif')
siSSpSpeakerSetup = FOUR_CHAR_CODE('3dst')
siStereoInputGain = FOUR_CHAR_CODE('sgai')
siSubwooferMute = FOUR_CHAR_CODE('bmut')
siTerminalType = FOUR_CHAR_CODE('ttyp')
siTwosComplementOnOff = FOUR_CHAR_CODE('twos')
siVendorProduct = FOUR_CHAR_CODE('vpro')
siVolume = FOUR_CHAR_CODE('volu')
siVoxRecordInfo = FOUR_CHAR_CODE('voxr')
siVoxStopInfo = FOUR_CHAR_CODE('voxs')
siWideStereo = FOUR_CHAR_CODE('wide')
siSupportedExtendedFlags = FOUR_CHAR_CODE('exfl')
siRateConverterRollOffSlope = FOUR_CHAR_CODE('rcdb')
siOutputLatency = FOUR_CHAR_CODE('olte')
siCloseDriver = FOUR_CHAR_CODE('clos')
siInitializeDriver = FOUR_CHAR_CODE('init')
siPauseRecording = FOUR_CHAR_CODE('paus')
siUserInterruptProc = FOUR_CHAR_CODE('user')
# kInvalidSource = (long)0xFFFFFFFF
kNoSource = FOUR_CHAR_CODE('none')
kCDSource = FOUR_CHAR_CODE('cd ')
kExtMicSource = FOUR_CHAR_CODE('emic')
kSoundInSource = FOUR_CHAR_CODE('sinj')
kRCAInSource = FOUR_CHAR_CODE('irca')
kTVFMTunerSource = FOUR_CHAR_CODE('tvfm')
kDAVInSource = FOUR_CHAR_CODE('idav')
kIntMicSource = FOUR_CHAR_CODE('imic')
kMediaBaySource = FOUR_CHAR_CODE('mbay')
kModemSource = FOUR_CHAR_CODE('modm')
kPCCardSource = FOUR_CHAR_CODE('pcm ')
kZoomVideoSource = FOUR_CHAR_CODE('zvpc')
kDVDSource = FOUR_CHAR_CODE('dvda')
kMicrophoneArray = FOUR_CHAR_CODE('mica')
kNoSoundComponentType = FOUR_CHAR_CODE('****')
kSoundComponentType = FOUR_CHAR_CODE('sift')
kSoundComponentPPCType = FOUR_CHAR_CODE('nift')
kRate8SubType = FOUR_CHAR_CODE('ratb')
kRate16SubType = FOUR_CHAR_CODE('ratw')
kConverterSubType = FOUR_CHAR_CODE('conv')
kSndSourceSubType = FOUR_CHAR_CODE('sour')
kMixerType = FOUR_CHAR_CODE('mixr')
kMixer8SubType = FOUR_CHAR_CODE('mixb')
kMixer16SubType = FOUR_CHAR_CODE('mixw')
kSoundInputDeviceType = FOUR_CHAR_CODE('sinp')
kWaveInSubType = FOUR_CHAR_CODE('wavi')
kWaveInSnifferSubType = FOUR_CHAR_CODE('wisn')
kSoundOutputDeviceType = FOUR_CHAR_CODE('sdev')
kClassicSubType = FOUR_CHAR_CODE('clas')
kASCSubType = FOUR_CHAR_CODE('asc ')
kDSPSubType = FOUR_CHAR_CODE('dsp ')
kAwacsSubType = FOUR_CHAR_CODE('awac')
kGCAwacsSubType = FOUR_CHAR_CODE('awgc')
kSingerSubType = FOUR_CHAR_CODE('sing')
kSinger2SubType = FOUR_CHAR_CODE('sng2')
kWhitSubType = FOUR_CHAR_CODE('whit')
kSoundBlasterSubType = FOUR_CHAR_CODE('sbls')
kWaveOutSubType = FOUR_CHAR_CODE('wavo')
kWaveOutSnifferSubType = FOUR_CHAR_CODE('wosn')
kDirectSoundSubType = FOUR_CHAR_CODE('dsnd')
kDirectSoundSnifferSubType = FOUR_CHAR_CODE('dssn')
kUNIXsdevSubType = FOUR_CHAR_CODE('un1x')
kUSBSubType = FOUR_CHAR_CODE('usb ')
kBlueBoxSubType = FOUR_CHAR_CODE('bsnd')
kSoundCompressor = FOUR_CHAR_CODE('scom')
kSoundDecompressor = FOUR_CHAR_CODE('sdec')
kAudioComponentType = FOUR_CHAR_CODE('adio')
kAwacsPhoneSubType = FOUR_CHAR_CODE('hphn')
kAudioVisionSpeakerSubType = FOUR_CHAR_CODE('telc')
kAudioVisionHeadphoneSubType = FOUR_CHAR_CODE('telh')
kPhilipsFaderSubType = FOUR_CHAR_CODE('tvav')
kSGSToneSubType = FOUR_CHAR_CODE('sgs0')
kSoundEffectsType = FOUR_CHAR_CODE('snfx')
kEqualizerSubType = FOUR_CHAR_CODE('eqal')
kSSpLocalizationSubType = FOUR_CHAR_CODE('snd3')
kSoundNotCompressed = FOUR_CHAR_CODE('NONE')
k8BitOffsetBinaryFormat = FOUR_CHAR_CODE('raw ')
k16BitBigEndianFormat = FOUR_CHAR_CODE('twos')
k16BitLittleEndianFormat = FOUR_CHAR_CODE('sowt')
kFloat32Format = FOUR_CHAR_CODE('fl32')
kFloat64Format = FOUR_CHAR_CODE('fl64')
k24BitFormat = FOUR_CHAR_CODE('in24')
k32BitFormat = FOUR_CHAR_CODE('in32')
k32BitLittleEndianFormat = FOUR_CHAR_CODE('23ni')
kMACE3Compression = FOUR_CHAR_CODE('MAC3')
kMACE6Compression = FOUR_CHAR_CODE('MAC6')
kCDXA4Compression = FOUR_CHAR_CODE('cdx4')
kCDXA2Compression = FOUR_CHAR_CODE('cdx2')
kIMACompression = FOUR_CHAR_CODE('ima4')
kULawCompression = FOUR_CHAR_CODE('ulaw')
kALawCompression = FOUR_CHAR_CODE('alaw')
kMicrosoftADPCMFormat = 0x6D730002
kDVIIntelIMAFormat = 0x6D730011
kDVAudioFormat = FOUR_CHAR_CODE('dvca')
kQDesignCompression = FOUR_CHAR_CODE('QDMC')
kQDesign2Compression = FOUR_CHAR_CODE('QDM2')
kQUALCOMMCompression = FOUR_CHAR_CODE('Qclp')
kOffsetBinary = k8BitOffsetBinaryFormat
kTwosComplement = k16BitBigEndianFormat
kLittleEndianFormat = k16BitLittleEndianFormat
kMPEGLayer3Format = 0x6D730055
kFullMPEGLay3Format = FOUR_CHAR_CODE('.mp3')
k16BitNativeEndianFormat = k16BitLittleEndianFormat
k16BitNonNativeEndianFormat = k16BitBigEndianFormat
k16BitNativeEndianFormat = k16BitBigEndianFormat
k16BitNonNativeEndianFormat = k16BitLittleEndianFormat
k8BitRawIn = (1 << 0)
k8BitTwosIn = (1 << 1)
k16BitIn = (1 << 2)
kStereoIn = (1 << 3)
k8BitRawOut = (1 << 8)
k8BitTwosOut = (1 << 9)
k16BitOut = (1 << 10)
kStereoOut = (1 << 11)
kReverse = (1L << 16)
kRateConvert = (1L << 17)
kCreateSoundSource = (1L << 18)
kVMAwareness = (1L << 21)
kHighQuality = (1L << 22)
kNonRealTime = (1L << 23)
kSourcePaused = (1 << 0)
kPassThrough = (1L << 16)
kNoSoundComponentChain = (1L << 17)
kNoMixing = (1 << 0)
kNoSampleRateConversion = (1 << 1)
kNoSampleSizeConversion = (1 << 2)
kNoSampleFormatConversion = (1 << 3)
kNoChannelConversion = (1 << 4)
kNoDecompression = (1 << 5)
kNoVolumeConversion = (1 << 6)
kNoRealtimeProcessing = (1 << 7)
kScheduledSource = (1 << 8)
kNonInterleavedBuffer = (1 << 9)
kNonPagingMixer = (1 << 10)
kSoundConverterMixer = (1 << 11)
kPagingMixer = (1 << 12)
kVMAwareMixer = (1 << 13)
kExtendedSoundData = (1 << 14)
kBestQuality = (1 << 0)
kInputMask = 0x000000FF
kOutputMask = 0x0000FF00
kOutputShift = 8
kActionMask = 0x00FF0000
kSoundComponentBits = 0x00FFFFFF
kAudioFormatAtomType = FOUR_CHAR_CODE('frma')
kAudioEndianAtomType = FOUR_CHAR_CODE('enda')
kAudioVBRAtomType = FOUR_CHAR_CODE('vbra')
kAudioTerminatorAtomType = 0
kAVDisplayHeadphoneRemove = 0
kAVDisplayHeadphoneInsert = 1
kAVDisplayPlainTalkRemove = 2
kAVDisplayPlainTalkInsert = 3
audioAllChannels = 0
audioLeftChannel = 1
audioRightChannel = 2
audioUnmuted = 0
audioMuted = 1
audioDoesMono = (1L << 0)
audioDoesStereo = (1L << 1)
audioDoesIndependentChannels = (1L << 2)
siCDQuality = FOUR_CHAR_CODE('cd ')
siBestQuality = FOUR_CHAR_CODE('best')
siBetterQuality = FOUR_CHAR_CODE('betr')
siGoodQuality = FOUR_CHAR_CODE('good')
siNoneQuality = FOUR_CHAR_CODE('none')
siDeviceIsConnected = 1
siDeviceNotConnected = 0
siDontKnowIfConnected = -1
siReadPermission = 0
siWritePermission = 1
kSoundConverterDidntFillBuffer = (1 << 0)
kSoundConverterHasLeftOverData = (1 << 1)
kExtendedSoundSampleCountNotValid = 1L << 0
kExtendedSoundBufferSizeValid = 1L << 1
kScheduledSoundDoScheduled = 1 << 0
kScheduledSoundDoCallBack = 1 << 1
kScheduledSoundExtendedHdr = 1 << 2
kSoundComponentInitOutputDeviceSelect = 0x0001
kSoundComponentSetSourceSelect = 0x0002
kSoundComponentGetSourceSelect = 0x0003
kSoundComponentGetSourceDataSelect = 0x0004
kSoundComponentSetOutputSelect = 0x0005
kSoundComponentAddSourceSelect = 0x0101
kSoundComponentRemoveSourceSelect = 0x0102
kSoundComponentGetInfoSelect = 0x0103
kSoundComponentSetInfoSelect = 0x0104
kSoundComponentStartSourceSelect = 0x0105
kSoundComponentStopSourceSelect = 0x0106
kSoundComponentPauseSourceSelect = 0x0107
kSoundComponentPlaySourceBufferSelect = 0x0108
kAudioGetVolumeSelect = 0x0000
kAudioSetVolumeSelect = 0x0001
kAudioGetMuteSelect = 0x0002
kAudioSetMuteSelect = 0x0003
kAudioSetToDefaultsSelect = 0x0004
kAudioGetInfoSelect = 0x0005
kAudioGetBassSelect = 0x0006
kAudioSetBassSelect = 0x0007
kAudioGetTrebleSelect = 0x0008
kAudioSetTrebleSelect = 0x0009
kAudioGetOutputDeviceSelect = 0x000A
kAudioMuteOnEventSelect = 0x0081
kDelegatedSoundComponentSelectors = 0x0100
kSndInputReadAsyncSelect = 0x0001
kSndInputReadSyncSelect = 0x0002
kSndInputPauseRecordingSelect = 0x0003
kSndInputResumeRecordingSelect = 0x0004
kSndInputStopRecordingSelect = 0x0005
kSndInputGetStatusSelect = 0x0006
kSndInputGetDeviceInfoSelect = 0x0007
kSndInputSetDeviceInfoSelect = 0x0008
kSndInputInitHardwareSelect = 0x0009
| Python |
from _Qdoffs import *
| Python |
# Generated from 'QDOffscreen.h'
def FOUR_CHAR_CODE(x): return x
pixPurgeBit = 0
noNewDeviceBit = 1
useTempMemBit = 2
keepLocalBit = 3
useDistantHdwrMemBit = 4
useLocalHdwrMemBit = 5
pixelsPurgeableBit = 6
pixelsLockedBit = 7
mapPixBit = 16
newDepthBit = 17
alignPixBit = 18
newRowBytesBit = 19
reallocPixBit = 20
clipPixBit = 28
stretchPixBit = 29
ditherPixBit = 30
gwFlagErrBit = 31
pixPurge = 1L << pixPurgeBit
noNewDevice = 1L << noNewDeviceBit
useTempMem = 1L << useTempMemBit
keepLocal = 1L << keepLocalBit
useDistantHdwrMem = 1L << useDistantHdwrMemBit
useLocalHdwrMem = 1L << useLocalHdwrMemBit
pixelsPurgeable = 1L << pixelsPurgeableBit
pixelsLocked = 1L << pixelsLockedBit
kAllocDirectDrawSurface = 1L << 14
mapPix = 1L << mapPixBit
newDepth = 1L << newDepthBit
alignPix = 1L << alignPixBit
newRowBytes = 1L << newRowBytesBit
reallocPix = 1L << reallocPixBit
clipPix = 1L << clipPixBit
stretchPix = 1L << stretchPixBit
ditherPix = 1L << ditherPixBit
gwFlagErr = 1L << gwFlagErrBit
deviceIsIndirect = (1L << 0)
deviceNeedsLock = (1L << 1)
deviceIsStatic = (1L << 2)
deviceIsExternalBuffer = (1L << 3)
deviceIsDDSurface = (1L << 4)
deviceIsDCISurface = (1L << 5)
deviceIsGDISurface = (1L << 6)
deviceIsAScreen = (1L << 7)
deviceIsOverlaySurface = (1L << 8)
| Python |
from _AE import *
| Python |
# Generated from 'Events.h'
nullEvent = 0
mouseDown = 1
mouseUp = 2
keyDown = 3
keyUp = 4
autoKey = 5
updateEvt = 6
diskEvt = 7
activateEvt = 8
osEvt = 15
kHighLevelEvent = 23
mDownMask = 1 << mouseDown
mUpMask = 1 << mouseUp
keyDownMask = 1 << keyDown
keyUpMask = 1 << keyUp
autoKeyMask = 1 << autoKey
updateMask = 1 << updateEvt
diskMask = 1 << diskEvt
activMask = 1 << activateEvt
highLevelEventMask = 0x0400
osMask = 1 << osEvt
everyEvent = 0xFFFF
charCodeMask = 0x000000FF
keyCodeMask = 0x0000FF00
adbAddrMask = 0x00FF0000
# osEvtMessageMask = (unsigned long)0xFF000000
mouseMovedMessage = 0x00FA
suspendResumeMessage = 0x0001
resumeFlag = 1
convertClipboardFlag = 2
activeFlagBit = 0
btnStateBit = 7
cmdKeyBit = 8
shiftKeyBit = 9
alphaLockBit = 10
optionKeyBit = 11
controlKeyBit = 12
rightShiftKeyBit = 13
rightOptionKeyBit = 14
rightControlKeyBit = 15
activeFlag = 1 << activeFlagBit
btnState = 1 << btnStateBit
cmdKey = 1 << cmdKeyBit
shiftKey = 1 << shiftKeyBit
alphaLock = 1 << alphaLockBit
optionKey = 1 << optionKeyBit
controlKey = 1 << controlKeyBit
rightShiftKey = 1 << rightShiftKeyBit
rightOptionKey = 1 << rightOptionKeyBit
rightControlKey = 1 << rightControlKeyBit
kNullCharCode = 0
kHomeCharCode = 1
kEnterCharCode = 3
kEndCharCode = 4
kHelpCharCode = 5
kBellCharCode = 7
kBackspaceCharCode = 8
kTabCharCode = 9
kLineFeedCharCode = 10
kVerticalTabCharCode = 11
kPageUpCharCode = 11
kFormFeedCharCode = 12
kPageDownCharCode = 12
kReturnCharCode = 13
kFunctionKeyCharCode = 16
kCommandCharCode = 17
kCheckCharCode = 18
kDiamondCharCode = 19
kAppleLogoCharCode = 20
kEscapeCharCode = 27
kClearCharCode = 27
kLeftArrowCharCode = 28
kRightArrowCharCode = 29
kUpArrowCharCode = 30
kDownArrowCharCode = 31
kSpaceCharCode = 32
kDeleteCharCode = 127
kBulletCharCode = 165
kNonBreakingSpaceCharCode = 202
kShiftUnicode = 0x21E7
kControlUnicode = 0x2303
kOptionUnicode = 0x2325
kCommandUnicode = 0x2318
kPencilUnicode = 0x270E
kCheckUnicode = 0x2713
kDiamondUnicode = 0x25C6
kBulletUnicode = 0x2022
kAppleLogoUnicode = 0xF8FF
networkEvt = 10
driverEvt = 11
app1Evt = 12
app2Evt = 13
app3Evt = 14
app4Evt = 15
networkMask = 0x0400
driverMask = 0x0800
app1Mask = 0x1000
app2Mask = 0x2000
app3Mask = 0x4000
app4Mask = 0x8000
| Python |
from _IBCarbon import *
| Python |
from _Icn import *
| Python |
# Generated from 'QuickDraw.h'
def FOUR_CHAR_CODE(x): return x
normal = 0
bold = 1
italic = 2
underline = 4
outline = 8
shadow = 0x10
condense = 0x20
extend = 0x40
invalColReq = -1
srcCopy = 0
srcOr = 1
srcXor = 2
srcBic = 3
notSrcCopy = 4
notSrcOr = 5
notSrcXor = 6
notSrcBic = 7
patCopy = 8
patOr = 9
patXor = 10
patBic = 11
notPatCopy = 12
notPatOr = 13
notPatXor = 14
notPatBic = 15
grayishTextOr = 49
hilitetransfermode = 50
hilite = 50
blend = 32
addPin = 33
addOver = 34
subPin = 35
addMax = 37
adMax = 37
subOver = 38
adMin = 39
ditherCopy = 64
transparent = 36
italicBit = 1
ulineBit = 2
outlineBit = 3
shadowBit = 4
condenseBit = 5
extendBit = 6
normalBit = 0
inverseBit = 1
redBit = 4
greenBit = 3
blueBit = 2
cyanBit = 8
magentaBit = 7
yellowBit = 6
blackBit = 5
blackColor = 33
whiteColor = 30
redColor = 205
greenColor = 341
blueColor = 409
cyanColor = 273
magentaColor = 137
yellowColor = 69
picLParen = 0
picRParen = 1
clutType = 0
fixedType = 1
directType = 2
gdDevType = 0
interlacedDevice = 2
hwMirroredDevice = 4
roundedDevice = 5
hasAuxMenuBar = 6
burstDevice = 7
ext32Device = 8
ramInit = 10
mainScreen = 11
allInit = 12
screenDevice = 13
noDriver = 14
screenActive = 15
hiliteBit = 7
pHiliteBit = 0
defQDColors = 127
RGBDirect = 16
baseAddr32 = 4
sysPatListID = 0
iBeamCursor = 1
crossCursor = 2
plusCursor = 3
watchCursor = 4
kQDGrafVerbFrame = 0
kQDGrafVerbPaint = 1
kQDGrafVerbErase = 2
kQDGrafVerbInvert = 3
kQDGrafVerbFill = 4
frame = kQDGrafVerbFrame
paint = kQDGrafVerbPaint
erase = kQDGrafVerbErase
invert = kQDGrafVerbInvert
fill = kQDGrafVerbFill
chunky = 0
chunkyPlanar = 1
planar = 2
singleDevicesBit = 0
dontMatchSeedsBit = 1
allDevicesBit = 2
singleDevices = 1 << singleDevicesBit
dontMatchSeeds = 1 << dontMatchSeedsBit
allDevices = 1 << allDevicesBit
kPrinterFontStatus = 0
kPrinterScalingStatus = 1
kNoConstraint = 0
kVerticalConstraint = 1
kHorizontalConstraint = 2
k1MonochromePixelFormat = 0x00000001
k2IndexedPixelFormat = 0x00000002
k4IndexedPixelFormat = 0x00000004
k8IndexedPixelFormat = 0x00000008
k16BE555PixelFormat = 0x00000010
k24RGBPixelFormat = 0x00000018
k32ARGBPixelFormat = 0x00000020
k1IndexedGrayPixelFormat = 0x00000021
k2IndexedGrayPixelFormat = 0x00000022
k4IndexedGrayPixelFormat = 0x00000024
k8IndexedGrayPixelFormat = 0x00000028
k16LE555PixelFormat = FOUR_CHAR_CODE('L555')
k16LE5551PixelFormat = FOUR_CHAR_CODE('5551')
k16BE565PixelFormat = FOUR_CHAR_CODE('B565')
k16LE565PixelFormat = FOUR_CHAR_CODE('L565')
k24BGRPixelFormat = FOUR_CHAR_CODE('24BG')
k32BGRAPixelFormat = FOUR_CHAR_CODE('BGRA')
k32ABGRPixelFormat = FOUR_CHAR_CODE('ABGR')
k32RGBAPixelFormat = FOUR_CHAR_CODE('RGBA')
kYUVSPixelFormat = FOUR_CHAR_CODE('yuvs')
kYUVUPixelFormat = FOUR_CHAR_CODE('yuvu')
kYVU9PixelFormat = FOUR_CHAR_CODE('YVU9')
kYUV411PixelFormat = FOUR_CHAR_CODE('Y411')
kYVYU422PixelFormat = FOUR_CHAR_CODE('YVYU')
kUYVY422PixelFormat = FOUR_CHAR_CODE('UYVY')
kYUV211PixelFormat = FOUR_CHAR_CODE('Y211')
k2vuyPixelFormat = FOUR_CHAR_CODE('2vuy')
kCursorImageMajorVersion = 0x0001
kCursorImageMinorVersion = 0x0000
kQDParseRegionFromTop = (1 << 0)
kQDParseRegionFromBottom = (1 << 1)
kQDParseRegionFromLeft = (1 << 2)
kQDParseRegionFromRight = (1 << 3)
kQDParseRegionFromTopLeft = kQDParseRegionFromTop | kQDParseRegionFromLeft
kQDParseRegionFromBottomRight = kQDParseRegionFromBottom | kQDParseRegionFromRight
kQDRegionToRectsMsgInit = 1
kQDRegionToRectsMsgParse = 2
kQDRegionToRectsMsgTerminate = 3
colorXorXFer = 52
noiseXFer = 53
customXFer = 54
kXFer1PixelAtATime = 0x00000001
kXFerConvertPixelToRGB32 = 0x00000002
kCursorComponentsVersion = 0x00010001
kCursorComponentType = FOUR_CHAR_CODE('curs')
cursorDoesAnimate = 1L << 0
cursorDoesHardware = 1L << 1
cursorDoesUnreadableScreenBits = 1L << 2
kRenderCursorInHardware = 1L << 0
kRenderCursorInSoftware = 1L << 1
kCursorComponentInit = 0x0001
kCursorComponentGetInfo = 0x0002
kCursorComponentSetOutputMode = 0x0003
kCursorComponentSetData = 0x0004
kCursorComponentReconfigure = 0x0005
kCursorComponentDraw = 0x0006
kCursorComponentErase = 0x0007
kCursorComponentMove = 0x0008
kCursorComponentAnimate = 0x0009
kCursorComponentLastReserved = 0x0050
# Generated from 'QuickDrawText.h'
def FOUR_CHAR_CODE(x): return x
normal = 0
bold = 1
italic = 2
underline = 4
outline = 8
shadow = 0x10
condense = 0x20
extend = 0x40
leftCaret = 0
rightCaret = -1
kHilite = 1
smLeftCaret = 0
smRightCaret = -1
smHilite = 1
onlyStyleRun = 0
leftStyleRun = 1
rightStyleRun = 2
middleStyleRun = 3
smOnlyStyleRun = 0
smLeftStyleRun = 1
smRightStyleRun = 2
smMiddleStyleRun = 3
truncEnd = 0
truncMiddle = 0x4000
smTruncEnd = 0
smTruncMiddle = 0x4000
notTruncated = 0
truncated = 1
truncErr = -1
smNotTruncated = 0
smTruncated = 1
smTruncErr = -1
smBreakWord = 0
smBreakChar = 1
smBreakOverflow = 2
tfAntiAlias = 1 << 0
tfUnicode = 1 << 1
| Python |
# Generated from 'Icons.h'
def FOUR_CHAR_CODE(x): return x
from Carbon.Files import *
kGenericDocumentIconResource = -4000
kGenericStationeryIconResource = -3985
kGenericEditionFileIconResource = -3989
kGenericApplicationIconResource = -3996
kGenericDeskAccessoryIconResource = -3991
kGenericFolderIconResource = -3999
kPrivateFolderIconResource = -3994
kFloppyIconResource = -3998
kTrashIconResource = -3993
kGenericRAMDiskIconResource = -3988
kGenericCDROMIconResource = -3987
kDesktopIconResource = -3992
kOpenFolderIconResource = -3997
kGenericHardDiskIconResource = -3995
kGenericFileServerIconResource = -3972
kGenericSuitcaseIconResource = -3970
kGenericMoverObjectIconResource = -3969
kGenericPreferencesIconResource = -3971
kGenericQueryDocumentIconResource = -16506
kGenericExtensionIconResource = -16415
kSystemFolderIconResource = -3983
kHelpIconResource = -20271
kAppleMenuFolderIconResource = -3982
genericDocumentIconResource = kGenericDocumentIconResource
genericStationeryIconResource = kGenericStationeryIconResource
genericEditionFileIconResource = kGenericEditionFileIconResource
genericApplicationIconResource = kGenericApplicationIconResource
genericDeskAccessoryIconResource = kGenericDeskAccessoryIconResource
genericFolderIconResource = kGenericFolderIconResource
privateFolderIconResource = kPrivateFolderIconResource
floppyIconResource = kFloppyIconResource
trashIconResource = kTrashIconResource
genericRAMDiskIconResource = kGenericRAMDiskIconResource
genericCDROMIconResource = kGenericCDROMIconResource
desktopIconResource = kDesktopIconResource
openFolderIconResource = kOpenFolderIconResource
genericHardDiskIconResource = kGenericHardDiskIconResource
genericFileServerIconResource = kGenericFileServerIconResource
genericSuitcaseIconResource = kGenericSuitcaseIconResource
genericMoverObjectIconResource = kGenericMoverObjectIconResource
genericPreferencesIconResource = kGenericPreferencesIconResource
genericQueryDocumentIconResource = kGenericQueryDocumentIconResource
genericExtensionIconResource = kGenericExtensionIconResource
systemFolderIconResource = kSystemFolderIconResource
appleMenuFolderIconResource = kAppleMenuFolderIconResource
kStartupFolderIconResource = -3981
kOwnedFolderIconResource = -3980
kDropFolderIconResource = -3979
kSharedFolderIconResource = -3978
kMountedFolderIconResource = -3977
kControlPanelFolderIconResource = -3976
kPrintMonitorFolderIconResource = -3975
kPreferencesFolderIconResource = -3974
kExtensionsFolderIconResource = -3973
kFontsFolderIconResource = -3968
kFullTrashIconResource = -3984
startupFolderIconResource = kStartupFolderIconResource
ownedFolderIconResource = kOwnedFolderIconResource
dropFolderIconResource = kDropFolderIconResource
sharedFolderIconResource = kSharedFolderIconResource
mountedFolderIconResource = kMountedFolderIconResource
controlPanelFolderIconResource = kControlPanelFolderIconResource
printMonitorFolderIconResource = kPrintMonitorFolderIconResource
preferencesFolderIconResource = kPreferencesFolderIconResource
extensionsFolderIconResource = kExtensionsFolderIconResource
fontsFolderIconResource = kFontsFolderIconResource
fullTrashIconResource = kFullTrashIconResource
kThumbnail32BitData = FOUR_CHAR_CODE('it32')
kThumbnail8BitMask = FOUR_CHAR_CODE('t8mk')
kHuge1BitMask = FOUR_CHAR_CODE('ich#')
kHuge4BitData = FOUR_CHAR_CODE('ich4')
kHuge8BitData = FOUR_CHAR_CODE('ich8')
kHuge32BitData = FOUR_CHAR_CODE('ih32')
kHuge8BitMask = FOUR_CHAR_CODE('h8mk')
kLarge1BitMask = FOUR_CHAR_CODE('ICN#')
kLarge4BitData = FOUR_CHAR_CODE('icl4')
kLarge8BitData = FOUR_CHAR_CODE('icl8')
kLarge32BitData = FOUR_CHAR_CODE('il32')
kLarge8BitMask = FOUR_CHAR_CODE('l8mk')
kSmall1BitMask = FOUR_CHAR_CODE('ics#')
kSmall4BitData = FOUR_CHAR_CODE('ics4')
kSmall8BitData = FOUR_CHAR_CODE('ics8')
kSmall32BitData = FOUR_CHAR_CODE('is32')
kSmall8BitMask = FOUR_CHAR_CODE('s8mk')
kMini1BitMask = FOUR_CHAR_CODE('icm#')
kMini4BitData = FOUR_CHAR_CODE('icm4')
kMini8BitData = FOUR_CHAR_CODE('icm8')
kTileIconVariant = FOUR_CHAR_CODE('tile')
kRolloverIconVariant = FOUR_CHAR_CODE('over')
kDropIconVariant = FOUR_CHAR_CODE('drop')
kOpenIconVariant = FOUR_CHAR_CODE('open')
kOpenDropIconVariant = FOUR_CHAR_CODE('odrp')
large1BitMask = kLarge1BitMask
large4BitData = kLarge4BitData
large8BitData = kLarge8BitData
small1BitMask = kSmall1BitMask
small4BitData = kSmall4BitData
small8BitData = kSmall8BitData
mini1BitMask = kMini1BitMask
mini4BitData = kMini4BitData
mini8BitData = kMini8BitData
kAlignNone = 0x00
kAlignVerticalCenter = 0x01
kAlignTop = 0x02
kAlignBottom = 0x03
kAlignHorizontalCenter = 0x04
kAlignAbsoluteCenter = kAlignVerticalCenter | kAlignHorizontalCenter
kAlignCenterTop = kAlignTop | kAlignHorizontalCenter
kAlignCenterBottom = kAlignBottom | kAlignHorizontalCenter
kAlignLeft = 0x08
kAlignCenterLeft = kAlignVerticalCenter | kAlignLeft
kAlignTopLeft = kAlignTop | kAlignLeft
kAlignBottomLeft = kAlignBottom | kAlignLeft
kAlignRight = 0x0C
kAlignCenterRight = kAlignVerticalCenter | kAlignRight
kAlignTopRight = kAlignTop | kAlignRight
kAlignBottomRight = kAlignBottom | kAlignRight
atNone = kAlignNone
atVerticalCenter = kAlignVerticalCenter
atTop = kAlignTop
atBottom = kAlignBottom
atHorizontalCenter = kAlignHorizontalCenter
atAbsoluteCenter = kAlignAbsoluteCenter
atCenterTop = kAlignCenterTop
atCenterBottom = kAlignCenterBottom
atLeft = kAlignLeft
atCenterLeft = kAlignCenterLeft
atTopLeft = kAlignTopLeft
atBottomLeft = kAlignBottomLeft
atRight = kAlignRight
atCenterRight = kAlignCenterRight
atTopRight = kAlignTopRight
atBottomRight = kAlignBottomRight
kTransformNone = 0x00
kTransformDisabled = 0x01
kTransformOffline = 0x02
kTransformOpen = 0x03
kTransformLabel1 = 0x0100
kTransformLabel2 = 0x0200
kTransformLabel3 = 0x0300
kTransformLabel4 = 0x0400
kTransformLabel5 = 0x0500
kTransformLabel6 = 0x0600
kTransformLabel7 = 0x0700
kTransformSelected = 0x4000
kTransformSelectedDisabled = kTransformSelected | kTransformDisabled
kTransformSelectedOffline = kTransformSelected | kTransformOffline
kTransformSelectedOpen = kTransformSelected | kTransformOpen
ttNone = kTransformNone
ttDisabled = kTransformDisabled
ttOffline = kTransformOffline
ttOpen = kTransformOpen
ttLabel1 = kTransformLabel1
ttLabel2 = kTransformLabel2
ttLabel3 = kTransformLabel3
ttLabel4 = kTransformLabel4
ttLabel5 = kTransformLabel5
ttLabel6 = kTransformLabel6
ttLabel7 = kTransformLabel7
ttSelected = kTransformSelected
ttSelectedDisabled = kTransformSelectedDisabled
ttSelectedOffline = kTransformSelectedOffline
ttSelectedOpen = kTransformSelectedOpen
kSelectorLarge1Bit = 0x00000001
kSelectorLarge4Bit = 0x00000002
kSelectorLarge8Bit = 0x00000004
kSelectorLarge32Bit = 0x00000008
kSelectorLarge8BitMask = 0x00000010
kSelectorSmall1Bit = 0x00000100
kSelectorSmall4Bit = 0x00000200
kSelectorSmall8Bit = 0x00000400
kSelectorSmall32Bit = 0x00000800
kSelectorSmall8BitMask = 0x00001000
kSelectorMini1Bit = 0x00010000
kSelectorMini4Bit = 0x00020000
kSelectorMini8Bit = 0x00040000
kSelectorHuge1Bit = 0x01000000
kSelectorHuge4Bit = 0x02000000
kSelectorHuge8Bit = 0x04000000
kSelectorHuge32Bit = 0x08000000
kSelectorHuge8BitMask = 0x10000000
kSelectorAllLargeData = 0x000000FF
kSelectorAllSmallData = 0x0000FF00
kSelectorAllMiniData = 0x00FF0000
# kSelectorAllHugeData = (long)0xFF000000
kSelectorAll1BitData = kSelectorLarge1Bit | kSelectorSmall1Bit | kSelectorMini1Bit | kSelectorHuge1Bit
kSelectorAll4BitData = kSelectorLarge4Bit | kSelectorSmall4Bit | kSelectorMini4Bit | kSelectorHuge4Bit
kSelectorAll8BitData = kSelectorLarge8Bit | kSelectorSmall8Bit | kSelectorMini8Bit | kSelectorHuge8Bit
kSelectorAll32BitData = kSelectorLarge32Bit | kSelectorSmall32Bit | kSelectorHuge32Bit
# kSelectorAllAvailableData = (long)0xFFFFFFFF
svLarge1Bit = kSelectorLarge1Bit
svLarge4Bit = kSelectorLarge4Bit
svLarge8Bit = kSelectorLarge8Bit
svSmall1Bit = kSelectorSmall1Bit
svSmall4Bit = kSelectorSmall4Bit
svSmall8Bit = kSelectorSmall8Bit
svMini1Bit = kSelectorMini1Bit
svMini4Bit = kSelectorMini4Bit
svMini8Bit = kSelectorMini8Bit
svAllLargeData = kSelectorAllLargeData
svAllSmallData = kSelectorAllSmallData
svAllMiniData = kSelectorAllMiniData
svAll1BitData = kSelectorAll1BitData
svAll4BitData = kSelectorAll4BitData
svAll8BitData = kSelectorAll8BitData
# svAllAvailableData = kSelectorAllAvailableData
kSystemIconsCreator = FOUR_CHAR_CODE('macs')
# err = GetIconRef(kOnSystemDisk
kClipboardIcon = FOUR_CHAR_CODE('CLIP')
kClippingUnknownTypeIcon = FOUR_CHAR_CODE('clpu')
kClippingPictureTypeIcon = FOUR_CHAR_CODE('clpp')
kClippingTextTypeIcon = FOUR_CHAR_CODE('clpt')
kClippingSoundTypeIcon = FOUR_CHAR_CODE('clps')
kDesktopIcon = FOUR_CHAR_CODE('desk')
kFinderIcon = FOUR_CHAR_CODE('FNDR')
kFontSuitcaseIcon = FOUR_CHAR_CODE('FFIL')
kFullTrashIcon = FOUR_CHAR_CODE('ftrh')
kGenericApplicationIcon = FOUR_CHAR_CODE('APPL')
kGenericCDROMIcon = FOUR_CHAR_CODE('cddr')
kGenericControlPanelIcon = FOUR_CHAR_CODE('APPC')
kGenericControlStripModuleIcon = FOUR_CHAR_CODE('sdev')
kGenericComponentIcon = FOUR_CHAR_CODE('thng')
kGenericDeskAccessoryIcon = FOUR_CHAR_CODE('APPD')
kGenericDocumentIcon = FOUR_CHAR_CODE('docu')
kGenericEditionFileIcon = FOUR_CHAR_CODE('edtf')
kGenericExtensionIcon = FOUR_CHAR_CODE('INIT')
kGenericFileServerIcon = FOUR_CHAR_CODE('srvr')
kGenericFontIcon = FOUR_CHAR_CODE('ffil')
kGenericFontScalerIcon = FOUR_CHAR_CODE('sclr')
kGenericFloppyIcon = FOUR_CHAR_CODE('flpy')
kGenericHardDiskIcon = FOUR_CHAR_CODE('hdsk')
kGenericIDiskIcon = FOUR_CHAR_CODE('idsk')
kGenericRemovableMediaIcon = FOUR_CHAR_CODE('rmov')
kGenericMoverObjectIcon = FOUR_CHAR_CODE('movr')
kGenericPCCardIcon = FOUR_CHAR_CODE('pcmc')
kGenericPreferencesIcon = FOUR_CHAR_CODE('pref')
kGenericQueryDocumentIcon = FOUR_CHAR_CODE('qery')
kGenericRAMDiskIcon = FOUR_CHAR_CODE('ramd')
kGenericSharedLibaryIcon = FOUR_CHAR_CODE('shlb')
kGenericStationeryIcon = FOUR_CHAR_CODE('sdoc')
kGenericSuitcaseIcon = FOUR_CHAR_CODE('suit')
kGenericURLIcon = FOUR_CHAR_CODE('gurl')
kGenericWORMIcon = FOUR_CHAR_CODE('worm')
kInternationalResourcesIcon = FOUR_CHAR_CODE('ifil')
kKeyboardLayoutIcon = FOUR_CHAR_CODE('kfil')
kSoundFileIcon = FOUR_CHAR_CODE('sfil')
kSystemSuitcaseIcon = FOUR_CHAR_CODE('zsys')
kTrashIcon = FOUR_CHAR_CODE('trsh')
kTrueTypeFontIcon = FOUR_CHAR_CODE('tfil')
kTrueTypeFlatFontIcon = FOUR_CHAR_CODE('sfnt')
kTrueTypeMultiFlatFontIcon = FOUR_CHAR_CODE('ttcf')
kUserIDiskIcon = FOUR_CHAR_CODE('udsk')
kInternationResourcesIcon = kInternationalResourcesIcon
kInternetLocationHTTPIcon = FOUR_CHAR_CODE('ilht')
kInternetLocationFTPIcon = FOUR_CHAR_CODE('ilft')
kInternetLocationAppleShareIcon = FOUR_CHAR_CODE('ilaf')
kInternetLocationAppleTalkZoneIcon = FOUR_CHAR_CODE('ilat')
kInternetLocationFileIcon = FOUR_CHAR_CODE('ilfi')
kInternetLocationMailIcon = FOUR_CHAR_CODE('ilma')
kInternetLocationNewsIcon = FOUR_CHAR_CODE('ilnw')
kInternetLocationNSLNeighborhoodIcon = FOUR_CHAR_CODE('ilns')
kInternetLocationGenericIcon = FOUR_CHAR_CODE('ilge')
kGenericFolderIcon = FOUR_CHAR_CODE('fldr')
kDropFolderIcon = FOUR_CHAR_CODE('dbox')
kMountedFolderIcon = FOUR_CHAR_CODE('mntd')
kOpenFolderIcon = FOUR_CHAR_CODE('ofld')
kOwnedFolderIcon = FOUR_CHAR_CODE('ownd')
kPrivateFolderIcon = FOUR_CHAR_CODE('prvf')
kSharedFolderIcon = FOUR_CHAR_CODE('shfl')
kSharingPrivsNotApplicableIcon = FOUR_CHAR_CODE('shna')
kSharingPrivsReadOnlyIcon = FOUR_CHAR_CODE('shro')
kSharingPrivsReadWriteIcon = FOUR_CHAR_CODE('shrw')
kSharingPrivsUnknownIcon = FOUR_CHAR_CODE('shuk')
kSharingPrivsWritableIcon = FOUR_CHAR_CODE('writ')
kUserFolderIcon = FOUR_CHAR_CODE('ufld')
kWorkgroupFolderIcon = FOUR_CHAR_CODE('wfld')
kGuestUserIcon = FOUR_CHAR_CODE('gusr')
kUserIcon = FOUR_CHAR_CODE('user')
kOwnerIcon = FOUR_CHAR_CODE('susr')
kGroupIcon = FOUR_CHAR_CODE('grup')
kAppearanceFolderIcon = FOUR_CHAR_CODE('appr')
kAppleExtrasFolderIcon = FOUR_CHAR_CODE('aex\xc4')
kAppleMenuFolderIcon = FOUR_CHAR_CODE('amnu')
kApplicationsFolderIcon = FOUR_CHAR_CODE('apps')
kApplicationSupportFolderIcon = FOUR_CHAR_CODE('asup')
kAssistantsFolderIcon = FOUR_CHAR_CODE('ast\xc4')
kColorSyncFolderIcon = FOUR_CHAR_CODE('prof')
kContextualMenuItemsFolderIcon = FOUR_CHAR_CODE('cmnu')
kControlPanelDisabledFolderIcon = FOUR_CHAR_CODE('ctrD')
kControlPanelFolderIcon = FOUR_CHAR_CODE('ctrl')
kControlStripModulesFolderIcon = FOUR_CHAR_CODE('sdv\xc4')
kDocumentsFolderIcon = FOUR_CHAR_CODE('docs')
kExtensionsDisabledFolderIcon = FOUR_CHAR_CODE('extD')
kExtensionsFolderIcon = FOUR_CHAR_CODE('extn')
kFavoritesFolderIcon = FOUR_CHAR_CODE('favs')
kFontsFolderIcon = FOUR_CHAR_CODE('font')
kHelpFolderIcon = FOUR_CHAR_CODE('\xc4hlp')
kInternetFolderIcon = FOUR_CHAR_CODE('int\xc4')
kInternetPlugInFolderIcon = FOUR_CHAR_CODE('\xc4net')
kInternetSearchSitesFolderIcon = FOUR_CHAR_CODE('issf')
kLocalesFolderIcon = FOUR_CHAR_CODE('\xc4loc')
kMacOSReadMeFolderIcon = FOUR_CHAR_CODE('mor\xc4')
kPublicFolderIcon = FOUR_CHAR_CODE('pubf')
kPreferencesFolderIcon = FOUR_CHAR_CODE('prf\xc4')
kPrinterDescriptionFolderIcon = FOUR_CHAR_CODE('ppdf')
kPrinterDriverFolderIcon = FOUR_CHAR_CODE('\xc4prd')
kPrintMonitorFolderIcon = FOUR_CHAR_CODE('prnt')
kRecentApplicationsFolderIcon = FOUR_CHAR_CODE('rapp')
kRecentDocumentsFolderIcon = FOUR_CHAR_CODE('rdoc')
kRecentServersFolderIcon = FOUR_CHAR_CODE('rsrv')
kScriptingAdditionsFolderIcon = FOUR_CHAR_CODE('\xc4scr')
kSharedLibrariesFolderIcon = FOUR_CHAR_CODE('\xc4lib')
kScriptsFolderIcon = FOUR_CHAR_CODE('scr\xc4')
kShutdownItemsDisabledFolderIcon = FOUR_CHAR_CODE('shdD')
kShutdownItemsFolderIcon = FOUR_CHAR_CODE('shdf')
kSpeakableItemsFolder = FOUR_CHAR_CODE('spki')
kStartupItemsDisabledFolderIcon = FOUR_CHAR_CODE('strD')
kStartupItemsFolderIcon = FOUR_CHAR_CODE('strt')
kSystemExtensionDisabledFolderIcon = FOUR_CHAR_CODE('macD')
kSystemFolderIcon = FOUR_CHAR_CODE('macs')
kTextEncodingsFolderIcon = FOUR_CHAR_CODE('\xc4tex')
kUsersFolderIcon = FOUR_CHAR_CODE('usr\xc4')
kUtilitiesFolderIcon = FOUR_CHAR_CODE('uti\xc4')
kVoicesFolderIcon = FOUR_CHAR_CODE('fvoc')
kSystemFolderXIcon = FOUR_CHAR_CODE('macx')
kAppleScriptBadgeIcon = FOUR_CHAR_CODE('scrp')
kLockedBadgeIcon = FOUR_CHAR_CODE('lbdg')
kMountedBadgeIcon = FOUR_CHAR_CODE('mbdg')
kSharedBadgeIcon = FOUR_CHAR_CODE('sbdg')
kAliasBadgeIcon = FOUR_CHAR_CODE('abdg')
kAlertCautionBadgeIcon = FOUR_CHAR_CODE('cbdg')
kAlertNoteIcon = FOUR_CHAR_CODE('note')
kAlertCautionIcon = FOUR_CHAR_CODE('caut')
kAlertStopIcon = FOUR_CHAR_CODE('stop')
kAppleTalkIcon = FOUR_CHAR_CODE('atlk')
kAppleTalkZoneIcon = FOUR_CHAR_CODE('atzn')
kAFPServerIcon = FOUR_CHAR_CODE('afps')
kFTPServerIcon = FOUR_CHAR_CODE('ftps')
kHTTPServerIcon = FOUR_CHAR_CODE('htps')
kGenericNetworkIcon = FOUR_CHAR_CODE('gnet')
kIPFileServerIcon = FOUR_CHAR_CODE('isrv')
kToolbarCustomizeIcon = FOUR_CHAR_CODE('tcus')
kToolbarDeleteIcon = FOUR_CHAR_CODE('tdel')
kToolbarFavoritesIcon = FOUR_CHAR_CODE('tfav')
kToolbarHomeIcon = FOUR_CHAR_CODE('thom')
kAppleLogoIcon = FOUR_CHAR_CODE('capl')
kAppleMenuIcon = FOUR_CHAR_CODE('sapl')
kBackwardArrowIcon = FOUR_CHAR_CODE('baro')
kFavoriteItemsIcon = FOUR_CHAR_CODE('favr')
kForwardArrowIcon = FOUR_CHAR_CODE('faro')
kGridIcon = FOUR_CHAR_CODE('grid')
kHelpIcon = FOUR_CHAR_CODE('help')
kKeepArrangedIcon = FOUR_CHAR_CODE('arng')
kLockedIcon = FOUR_CHAR_CODE('lock')
kNoFilesIcon = FOUR_CHAR_CODE('nfil')
kNoFolderIcon = FOUR_CHAR_CODE('nfld')
kNoWriteIcon = FOUR_CHAR_CODE('nwrt')
kProtectedApplicationFolderIcon = FOUR_CHAR_CODE('papp')
kProtectedSystemFolderIcon = FOUR_CHAR_CODE('psys')
kRecentItemsIcon = FOUR_CHAR_CODE('rcnt')
kShortcutIcon = FOUR_CHAR_CODE('shrt')
kSortAscendingIcon = FOUR_CHAR_CODE('asnd')
kSortDescendingIcon = FOUR_CHAR_CODE('dsnd')
kUnlockedIcon = FOUR_CHAR_CODE('ulck')
kConnectToIcon = FOUR_CHAR_CODE('cnct')
kGenericWindowIcon = FOUR_CHAR_CODE('gwin')
kQuestionMarkIcon = FOUR_CHAR_CODE('ques')
kDeleteAliasIcon = FOUR_CHAR_CODE('dali')
kEjectMediaIcon = FOUR_CHAR_CODE('ejec')
kBurningIcon = FOUR_CHAR_CODE('burn')
kRightContainerArrowIcon = FOUR_CHAR_CODE('rcar')
kIconServicesNormalUsageFlag = 0
kIconServicesCatalogInfoMask = (kFSCatInfoNodeID | kFSCatInfoParentDirID | kFSCatInfoVolume | kFSCatInfoNodeFlags | kFSCatInfoFinderInfo | kFSCatInfoFinderXInfo | kFSCatInfoUserAccess)
kPlotIconRefNormalFlags = 0L
kPlotIconRefNoImage = (1 << 1)
kPlotIconRefNoMask = (1 << 2)
kIconFamilyType = FOUR_CHAR_CODE('icns')
| Python |
from _OSA import *
| Python |
# Generated from 'CFBase.h'
def FOUR_CHAR_CODE(x): return x
kCFCompareLessThan = -1
kCFCompareEqualTo = 0
kCFCompareGreaterThan = 1
kCFNotFound = -1
kCFPropertyListImmutable = 0
kCFPropertyListMutableContainers = 1
kCFPropertyListMutableContainersAndLeaves = 2
# kCFStringEncodingInvalidId = (long)0xFFFFFFFF
kCFStringEncodingMacRoman = 0
kCFStringEncodingWindowsLatin1 = 0x0500
kCFStringEncodingISOLatin1 = 0x0201
kCFStringEncodingNextStepLatin = 0x0B01
kCFStringEncodingASCII = 0x0600
kCFStringEncodingUnicode = 0x0100
kCFStringEncodingUTF8 = 0x08000100
kCFStringEncodingNonLossyASCII = 0x0BFF
kCFCompareCaseInsensitive = 1
kCFCompareBackwards = 4
kCFCompareAnchored = 8
kCFCompareNonliteral = 16
kCFCompareLocalized = 32
kCFCompareNumerically = 64
kCFURLPOSIXPathStyle = 0
kCFURLHFSPathStyle = 1
kCFURLWindowsPathStyle = 2
| Python |
from _Ctl import *
| Python |
# Generated from 'TextEdit.h'
teJustLeft = 0
teJustCenter = 1
teJustRight = -1
teForceLeft = -2
teFlushDefault = 0
teCenter = 1
teFlushRight = -1
teFlushLeft = -2
fontBit = 0
faceBit = 1
sizeBit = 2
clrBit = 3
addSizeBit = 4
toggleBit = 5
doFont = 1
doFace = 2
doSize = 4
doColor = 8
doAll = 15
addSize = 16
doToggle = 32
EOLHook = 0
DRAWHook = 4
WIDTHHook = 8
HITTESTHook = 12
nWIDTHHook = 24
TextWidthHook = 28
intEOLHook = 0
intDrawHook = 1
intWidthHook = 2
intHitTestHook = 3
intNWidthHook = 6
intTextWidthHook = 7
intInlineInputTSMTEPreUpdateHook = 8
intInlineInputTSMTEPostUpdateHook = 9
teFAutoScroll = 0
teFTextBuffering = 1
teFOutlineHilite = 2
teFInlineInput = 3
teFUseWhiteBackground = 4
teFUseInlineInput = 5
teFInlineInputAutoScroll = 6
teFIdleWithEventLoopTimer = 7
teBitClear = 0
teBitSet = 1
teBitTest = -1
teWordSelect = 4
teWordDrag = 8
teFromFind = 12
teFromRecal = 16
teFind = 0
teHighlight = 1
teDraw = -1
teCaret = -2
teFUseTextServices = 4
| Python |
# Generated from 'Drag.h'
def FOUR_CHAR_CODE(x): return x
from Carbon.TextEdit import *
from Carbon.QuickDraw import *
fkDragActionAll = -1
kDragHasLeftSenderWindow = (1 << 0)
kDragInsideSenderApplication = (1 << 1)
kDragInsideSenderWindow = (1 << 2)
kDragRegionAndImage = (1 << 4)
flavorSenderOnly = (1 << 0)
flavorSenderTranslated = (1 << 1)
flavorNotSaved = (1 << 2)
flavorSystemTranslated = (1 << 8)
kDragHasLeftSenderWindow = (1L << 0)
kDragInsideSenderApplication = (1L << 1)
kDragInsideSenderWindow = (1L << 2)
kDragBehaviorNone = 0
kDragBehaviorZoomBackAnimation = (1L << 0)
kDragRegionAndImage = (1L << 4)
kDragStandardTranslucency = 0L
kDragDarkTranslucency = 1L
kDragDarkerTranslucency = 2L
kDragOpaqueTranslucency = 3L
kDragRegionBegin = 1
kDragRegionDraw = 2
kDragRegionHide = 3
kDragRegionIdle = 4
kDragRegionEnd = 5
kZoomNoAcceleration = 0
kZoomAccelerate = 1
kZoomDecelerate = 2
flavorSenderOnly = (1 << 0)
flavorSenderTranslated = (1 << 1)
flavorNotSaved = (1 << 2)
flavorSystemTranslated = (1 << 8)
flavorDataPromised = (1 << 9)
kDragFlavorTypeHFS = FOUR_CHAR_CODE('hfs ')
kDragFlavorTypePromiseHFS = FOUR_CHAR_CODE('phfs')
flavorTypeHFS = kDragFlavorTypeHFS
flavorTypePromiseHFS = kDragFlavorTypePromiseHFS
kDragPromisedFlavorFindFile = FOUR_CHAR_CODE('rWm1')
kDragPromisedFlavor = FOUR_CHAR_CODE('fssP')
kDragPseudoCreatorVolumeOrDirectory = FOUR_CHAR_CODE('MACS')
kDragPseudoFileTypeVolume = FOUR_CHAR_CODE('disk')
kDragPseudoFileTypeDirectory = FOUR_CHAR_CODE('fold')
flavorTypeDirectory = FOUR_CHAR_CODE('diry')
kFlavorTypeClippingName = FOUR_CHAR_CODE('clnm')
kFlavorTypeClippingFilename = FOUR_CHAR_CODE('clfn')
kFlavorTypeDragToTrashOnly = FOUR_CHAR_CODE('fdtt')
kFlavorTypeFinderNoTrackingBehavior = FOUR_CHAR_CODE('fntb')
kDragTrackingEnterHandler = 1
kDragTrackingEnterWindow = 2
kDragTrackingInWindow = 3
kDragTrackingLeaveWindow = 4
kDragTrackingLeaveHandler = 5
kDragActionNothing = 0L
kDragActionCopy = 1L
kDragActionAlias = (1L << 1)
kDragActionGeneric = (1L << 2)
kDragActionPrivate = (1L << 3)
kDragActionMove = (1L << 4)
kDragActionDelete = (1L << 5)
# kDragActionAll = (long)0xFFFFFFFF
dragHasLeftSenderWindow = kDragHasLeftSenderWindow
dragInsideSenderApplication = kDragInsideSenderApplication
dragInsideSenderWindow = kDragInsideSenderWindow
dragTrackingEnterHandler = kDragTrackingEnterHandler
dragTrackingEnterWindow = kDragTrackingEnterWindow
dragTrackingInWindow = kDragTrackingInWindow
dragTrackingLeaveWindow = kDragTrackingLeaveWindow
dragTrackingLeaveHandler = kDragTrackingLeaveHandler
dragRegionBegin = kDragRegionBegin
dragRegionDraw = kDragRegionDraw
dragRegionHide = kDragRegionHide
dragRegionIdle = kDragRegionIdle
dragRegionEnd = kDragRegionEnd
zoomNoAcceleration = kZoomNoAcceleration
zoomAccelerate = kZoomAccelerate
zoomDecelerate = kZoomDecelerate
kDragStandardImage = kDragStandardTranslucency
kDragDarkImage = kDragDarkTranslucency
kDragDarkerImage = kDragDarkerTranslucency
kDragOpaqueImage = kDragOpaqueTranslucency
| Python |
# Generated from 'Dialogs.h'
def FOUR_CHAR_CODE(x): return x
kControlDialogItem = 4
kButtonDialogItem = kControlDialogItem | 0
kCheckBoxDialogItem = kControlDialogItem | 1
kRadioButtonDialogItem = kControlDialogItem | 2
kResourceControlDialogItem = kControlDialogItem | 3
kStaticTextDialogItem = 8
kEditTextDialogItem = 16
kIconDialogItem = 32
kPictureDialogItem = 64
kUserDialogItem = 0
kHelpDialogItem = 1
kItemDisableBit = 128
ctrlItem = 4
btnCtrl = 0
chkCtrl = 1
radCtrl = 2
resCtrl = 3
statText = 8
editText = 16
iconItem = 32
picItem = 64
userItem = 0
itemDisable = 128
kStdOkItemIndex = 1
kStdCancelItemIndex = 2
ok = kStdOkItemIndex
cancel = kStdCancelItemIndex
kStopIcon = 0
kNoteIcon = 1
kCautionIcon = 2
stopIcon = kStopIcon
noteIcon = kNoteIcon
cautionIcon = kCautionIcon
kOkItemIndex = 1
kCancelItemIndex = 2
overlayDITL = 0
appendDITLRight = 1
appendDITLBottom = 2
kAlertStopAlert = 0
kAlertNoteAlert = 1
kAlertCautionAlert = 2
kAlertPlainAlert = 3
kAlertDefaultOKText = -1
kAlertDefaultCancelText = -1
kAlertDefaultOtherText = -1
kAlertStdAlertOKButton = 1
kAlertStdAlertCancelButton = 2
kAlertStdAlertOtherButton = 3
kAlertStdAlertHelpButton = 4
kDialogFlagsUseThemeBackground = (1 << 0)
kDialogFlagsUseControlHierarchy = (1 << 1)
kDialogFlagsHandleMovableModal = (1 << 2)
kDialogFlagsUseThemeControls = (1 << 3)
kAlertFlagsUseThemeBackground = (1 << 0)
kAlertFlagsUseControlHierarchy = (1 << 1)
kAlertFlagsAlertIsMovable = (1 << 2)
kAlertFlagsUseThemeControls = (1 << 3)
kDialogFontNoFontStyle = 0
kDialogFontUseFontMask = 0x0001
kDialogFontUseFaceMask = 0x0002
kDialogFontUseSizeMask = 0x0004
kDialogFontUseForeColorMask = 0x0008
kDialogFontUseBackColorMask = 0x0010
kDialogFontUseModeMask = 0x0020
kDialogFontUseJustMask = 0x0040
kDialogFontUseAllMask = 0x00FF
kDialogFontAddFontSizeMask = 0x0100
kDialogFontUseFontNameMask = 0x0200
kDialogFontAddToMetaFontMask = 0x0400
kDialogFontUseThemeFontIDMask = 0x0080
kHICommandOther = FOUR_CHAR_CODE('othr')
kStdCFStringAlertVersionOne = 1
kStdAlertDoNotDisposeSheet = 1 << 0
kStdAlertDoNotAnimateOnDefault = 1 << 1
kStdAlertDoNotAnimateOnCancel = 1 << 2
kStdAlertDoNotAnimateOnOther = 1 << 3
| Python |
# Generated from 'AEDataModel.h'
def FOUR_CHAR_CODE(x): return x
typeBoolean = FOUR_CHAR_CODE('bool')
typeChar = FOUR_CHAR_CODE('TEXT')
typeSInt16 = FOUR_CHAR_CODE('shor')
typeSInt32 = FOUR_CHAR_CODE('long')
typeUInt32 = FOUR_CHAR_CODE('magn')
typeSInt64 = FOUR_CHAR_CODE('comp')
typeIEEE32BitFloatingPoint = FOUR_CHAR_CODE('sing')
typeIEEE64BitFloatingPoint = FOUR_CHAR_CODE('doub')
type128BitFloatingPoint = FOUR_CHAR_CODE('ldbl')
typeDecimalStruct = FOUR_CHAR_CODE('decm')
typeSMInt = typeSInt16
typeShortInteger = typeSInt16
typeInteger = typeSInt32
typeLongInteger = typeSInt32
typeMagnitude = typeUInt32
typeComp = typeSInt64
typeSMFloat = typeIEEE32BitFloatingPoint
typeShortFloat = typeIEEE32BitFloatingPoint
typeFloat = typeIEEE64BitFloatingPoint
typeLongFloat = typeIEEE64BitFloatingPoint
typeExtended = FOUR_CHAR_CODE('exte')
typeAEList = FOUR_CHAR_CODE('list')
typeAERecord = FOUR_CHAR_CODE('reco')
typeAppleEvent = FOUR_CHAR_CODE('aevt')
typeEventRecord = FOUR_CHAR_CODE('evrc')
typeTrue = FOUR_CHAR_CODE('true')
typeFalse = FOUR_CHAR_CODE('fals')
typeAlias = FOUR_CHAR_CODE('alis')
typeEnumerated = FOUR_CHAR_CODE('enum')
typeType = FOUR_CHAR_CODE('type')
typeAppParameters = FOUR_CHAR_CODE('appa')
typeProperty = FOUR_CHAR_CODE('prop')
typeFSS = FOUR_CHAR_CODE('fss ')
typeFSRef = FOUR_CHAR_CODE('fsrf')
typeFileURL = FOUR_CHAR_CODE('furl')
typeKeyword = FOUR_CHAR_CODE('keyw')
typeSectionH = FOUR_CHAR_CODE('sect')
typeWildCard = FOUR_CHAR_CODE('****')
typeApplSignature = FOUR_CHAR_CODE('sign')
typeQDRectangle = FOUR_CHAR_CODE('qdrt')
typeFixed = FOUR_CHAR_CODE('fixd')
typeProcessSerialNumber = FOUR_CHAR_CODE('psn ')
typeApplicationURL = FOUR_CHAR_CODE('aprl')
typeNull = FOUR_CHAR_CODE('null')
typeSessionID = FOUR_CHAR_CODE('ssid')
typeTargetID = FOUR_CHAR_CODE('targ')
typeDispatcherID = FOUR_CHAR_CODE('dspt')
keyTransactionIDAttr = FOUR_CHAR_CODE('tran')
keyReturnIDAttr = FOUR_CHAR_CODE('rtid')
keyEventClassAttr = FOUR_CHAR_CODE('evcl')
keyEventIDAttr = FOUR_CHAR_CODE('evid')
keyAddressAttr = FOUR_CHAR_CODE('addr')
keyOptionalKeywordAttr = FOUR_CHAR_CODE('optk')
keyTimeoutAttr = FOUR_CHAR_CODE('timo')
keyInteractLevelAttr = FOUR_CHAR_CODE('inte')
keyEventSourceAttr = FOUR_CHAR_CODE('esrc')
keyMissedKeywordAttr = FOUR_CHAR_CODE('miss')
keyOriginalAddressAttr = FOUR_CHAR_CODE('from')
keyAcceptTimeoutAttr = FOUR_CHAR_CODE('actm')
kAEDescListFactorNone = 0
kAEDescListFactorType = 4
kAEDescListFactorTypeAndSize = 8
kAutoGenerateReturnID = -1
kAnyTransactionID = 0
kAEDataArray = 0
kAEPackedArray = 1
kAEDescArray = 3
kAEKeyDescArray = 4
kAEHandleArray = 2
kAENormalPriority = 0x00000000
kAEHighPriority = 0x00000001
kAENoReply = 0x00000001
kAEQueueReply = 0x00000002
kAEWaitReply = 0x00000003
kAEDontReconnect = 0x00000080
kAEWantReceipt = 0x00000200
kAENeverInteract = 0x00000010
kAECanInteract = 0x00000020
kAEAlwaysInteract = 0x00000030
kAECanSwitchLayer = 0x00000040
kAEDontRecord = 0x00001000
kAEDontExecute = 0x00002000
kAEProcessNonReplyEvents = 0x00008000
kAEDefaultTimeout = -1
kNoTimeOut = -2
kAEInteractWithSelf = 0
kAEInteractWithLocal = 1
kAEInteractWithAll = 2
kAEDoNotIgnoreHandler = 0x00000000
kAEIgnoreAppPhacHandler = 0x00000001
kAEIgnoreAppEventHandler = 0x00000002
kAEIgnoreSysPhacHandler = 0x00000004
kAEIgnoreSysEventHandler = 0x00000008
kAEIngoreBuiltInEventHandler = 0x00000010
# kAEDontDisposeOnResume = (long)0x80000000
kAENoDispatch = 0
# kAEUseStandardDispatch = (long)0xFFFFFFFF
keyDirectObject = FOUR_CHAR_CODE('----')
keyErrorNumber = FOUR_CHAR_CODE('errn')
keyErrorString = FOUR_CHAR_CODE('errs')
keyProcessSerialNumber = FOUR_CHAR_CODE('psn ')
keyPreDispatch = FOUR_CHAR_CODE('phac')
keySelectProc = FOUR_CHAR_CODE('selh')
keyAERecorderCount = FOUR_CHAR_CODE('recr')
keyAEVersion = FOUR_CHAR_CODE('vers')
kCoreEventClass = FOUR_CHAR_CODE('aevt')
kAEOpenApplication = FOUR_CHAR_CODE('oapp')
kAEOpenDocuments = FOUR_CHAR_CODE('odoc')
kAEPrintDocuments = FOUR_CHAR_CODE('pdoc')
kAEQuitApplication = FOUR_CHAR_CODE('quit')
kAEAnswer = FOUR_CHAR_CODE('ansr')
kAEApplicationDied = FOUR_CHAR_CODE('obit')
kAEShowPreferences = FOUR_CHAR_CODE('pref')
kAEStartRecording = FOUR_CHAR_CODE('reca')
kAEStopRecording = FOUR_CHAR_CODE('recc')
kAENotifyStartRecording = FOUR_CHAR_CODE('rec1')
kAENotifyStopRecording = FOUR_CHAR_CODE('rec0')
kAENotifyRecording = FOUR_CHAR_CODE('recr')
kAEUnknownSource = 0
kAEDirectCall = 1
kAESameProcess = 2
kAELocalProcess = 3
kAERemoteProcess = 4
cAEList = FOUR_CHAR_CODE('list')
cApplication = FOUR_CHAR_CODE('capp')
cArc = FOUR_CHAR_CODE('carc')
cBoolean = FOUR_CHAR_CODE('bool')
cCell = FOUR_CHAR_CODE('ccel')
cChar = FOUR_CHAR_CODE('cha ')
cColorTable = FOUR_CHAR_CODE('clrt')
cColumn = FOUR_CHAR_CODE('ccol')
cDocument = FOUR_CHAR_CODE('docu')
cDrawingArea = FOUR_CHAR_CODE('cdrw')
cEnumeration = FOUR_CHAR_CODE('enum')
cFile = FOUR_CHAR_CODE('file')
cFixed = FOUR_CHAR_CODE('fixd')
cFixedPoint = FOUR_CHAR_CODE('fpnt')
cFixedRectangle = FOUR_CHAR_CODE('frct')
cGraphicLine = FOUR_CHAR_CODE('glin')
cGraphicObject = FOUR_CHAR_CODE('cgob')
cGraphicShape = FOUR_CHAR_CODE('cgsh')
cGraphicText = FOUR_CHAR_CODE('cgtx')
cGroupedGraphic = FOUR_CHAR_CODE('cpic')
cInsertionLoc = FOUR_CHAR_CODE('insl')
cInsertionPoint = FOUR_CHAR_CODE('cins')
cIntlText = FOUR_CHAR_CODE('itxt')
cIntlWritingCode = FOUR_CHAR_CODE('intl')
cItem = FOUR_CHAR_CODE('citm')
cLine = FOUR_CHAR_CODE('clin')
cLongDateTime = FOUR_CHAR_CODE('ldt ')
cLongFixed = FOUR_CHAR_CODE('lfxd')
cLongFixedPoint = FOUR_CHAR_CODE('lfpt')
cLongFixedRectangle = FOUR_CHAR_CODE('lfrc')
cLongInteger = FOUR_CHAR_CODE('long')
cLongPoint = FOUR_CHAR_CODE('lpnt')
cLongRectangle = FOUR_CHAR_CODE('lrct')
cMachineLoc = FOUR_CHAR_CODE('mLoc')
cMenu = FOUR_CHAR_CODE('cmnu')
cMenuItem = FOUR_CHAR_CODE('cmen')
cObject = FOUR_CHAR_CODE('cobj')
cObjectSpecifier = FOUR_CHAR_CODE('obj ')
cOpenableObject = FOUR_CHAR_CODE('coob')
cOval = FOUR_CHAR_CODE('covl')
cParagraph = FOUR_CHAR_CODE('cpar')
cPICT = FOUR_CHAR_CODE('PICT')
cPixel = FOUR_CHAR_CODE('cpxl')
cPixelMap = FOUR_CHAR_CODE('cpix')
cPolygon = FOUR_CHAR_CODE('cpgn')
cProperty = FOUR_CHAR_CODE('prop')
cQDPoint = FOUR_CHAR_CODE('QDpt')
cQDRectangle = FOUR_CHAR_CODE('qdrt')
cRectangle = FOUR_CHAR_CODE('crec')
cRGBColor = FOUR_CHAR_CODE('cRGB')
cRotation = FOUR_CHAR_CODE('trot')
cRoundedRectangle = FOUR_CHAR_CODE('crrc')
cRow = FOUR_CHAR_CODE('crow')
cSelection = FOUR_CHAR_CODE('csel')
cShortInteger = FOUR_CHAR_CODE('shor')
cTable = FOUR_CHAR_CODE('ctbl')
cText = FOUR_CHAR_CODE('ctxt')
cTextFlow = FOUR_CHAR_CODE('cflo')
cTextStyles = FOUR_CHAR_CODE('tsty')
cType = FOUR_CHAR_CODE('type')
cVersion = FOUR_CHAR_CODE('vers')
cWindow = FOUR_CHAR_CODE('cwin')
cWord = FOUR_CHAR_CODE('cwor')
enumArrows = FOUR_CHAR_CODE('arro')
enumJustification = FOUR_CHAR_CODE('just')
enumKeyForm = FOUR_CHAR_CODE('kfrm')
enumPosition = FOUR_CHAR_CODE('posi')
enumProtection = FOUR_CHAR_CODE('prtn')
enumQuality = FOUR_CHAR_CODE('qual')
enumSaveOptions = FOUR_CHAR_CODE('savo')
enumStyle = FOUR_CHAR_CODE('styl')
enumTransferMode = FOUR_CHAR_CODE('tran')
formUniqueID = FOUR_CHAR_CODE('ID ')
kAEAbout = FOUR_CHAR_CODE('abou')
kAEAfter = FOUR_CHAR_CODE('afte')
kAEAliasSelection = FOUR_CHAR_CODE('sali')
kAEAllCaps = FOUR_CHAR_CODE('alcp')
kAEArrowAtEnd = FOUR_CHAR_CODE('aren')
kAEArrowAtStart = FOUR_CHAR_CODE('arst')
kAEArrowBothEnds = FOUR_CHAR_CODE('arbo')
kAEAsk = FOUR_CHAR_CODE('ask ')
kAEBefore = FOUR_CHAR_CODE('befo')
kAEBeginning = FOUR_CHAR_CODE('bgng')
kAEBeginsWith = FOUR_CHAR_CODE('bgwt')
kAEBeginTransaction = FOUR_CHAR_CODE('begi')
kAEBold = FOUR_CHAR_CODE('bold')
kAECaseSensEquals = FOUR_CHAR_CODE('cseq')
kAECentered = FOUR_CHAR_CODE('cent')
kAEChangeView = FOUR_CHAR_CODE('view')
kAEClone = FOUR_CHAR_CODE('clon')
kAEClose = FOUR_CHAR_CODE('clos')
kAECondensed = FOUR_CHAR_CODE('cond')
kAEContains = FOUR_CHAR_CODE('cont')
kAECopy = FOUR_CHAR_CODE('copy')
kAECoreSuite = FOUR_CHAR_CODE('core')
kAECountElements = FOUR_CHAR_CODE('cnte')
kAECreateElement = FOUR_CHAR_CODE('crel')
kAECreatePublisher = FOUR_CHAR_CODE('cpub')
kAECut = FOUR_CHAR_CODE('cut ')
kAEDelete = FOUR_CHAR_CODE('delo')
kAEDoObjectsExist = FOUR_CHAR_CODE('doex')
kAEDoScript = FOUR_CHAR_CODE('dosc')
kAEDrag = FOUR_CHAR_CODE('drag')
kAEDuplicateSelection = FOUR_CHAR_CODE('sdup')
kAEEditGraphic = FOUR_CHAR_CODE('edit')
kAEEmptyTrash = FOUR_CHAR_CODE('empt')
kAEEnd = FOUR_CHAR_CODE('end ')
kAEEndsWith = FOUR_CHAR_CODE('ends')
kAEEndTransaction = FOUR_CHAR_CODE('endt')
kAEEquals = FOUR_CHAR_CODE('= ')
kAEExpanded = FOUR_CHAR_CODE('pexp')
kAEFast = FOUR_CHAR_CODE('fast')
kAEFinderEvents = FOUR_CHAR_CODE('FNDR')
kAEFormulaProtect = FOUR_CHAR_CODE('fpro')
kAEFullyJustified = FOUR_CHAR_CODE('full')
kAEGetClassInfo = FOUR_CHAR_CODE('qobj')
kAEGetData = FOUR_CHAR_CODE('getd')
kAEGetDataSize = FOUR_CHAR_CODE('dsiz')
kAEGetEventInfo = FOUR_CHAR_CODE('gtei')
kAEGetInfoSelection = FOUR_CHAR_CODE('sinf')
kAEGetPrivilegeSelection = FOUR_CHAR_CODE('sprv')
kAEGetSuiteInfo = FOUR_CHAR_CODE('gtsi')
kAEGreaterThan = FOUR_CHAR_CODE('> ')
kAEGreaterThanEquals = FOUR_CHAR_CODE('>= ')
kAEGrow = FOUR_CHAR_CODE('grow')
kAEHidden = FOUR_CHAR_CODE('hidn')
kAEHiQuality = FOUR_CHAR_CODE('hiqu')
kAEImageGraphic = FOUR_CHAR_CODE('imgr')
kAEIsUniform = FOUR_CHAR_CODE('isun')
kAEItalic = FOUR_CHAR_CODE('ital')
kAELeftJustified = FOUR_CHAR_CODE('left')
kAELessThan = FOUR_CHAR_CODE('< ')
kAELessThanEquals = FOUR_CHAR_CODE('<= ')
kAELowercase = FOUR_CHAR_CODE('lowc')
kAEMakeObjectsVisible = FOUR_CHAR_CODE('mvis')
kAEMiscStandards = FOUR_CHAR_CODE('misc')
kAEModifiable = FOUR_CHAR_CODE('modf')
kAEMove = FOUR_CHAR_CODE('move')
kAENo = FOUR_CHAR_CODE('no ')
kAENoArrow = FOUR_CHAR_CODE('arno')
kAENonmodifiable = FOUR_CHAR_CODE('nmod')
kAEOpen = FOUR_CHAR_CODE('odoc')
kAEOpenSelection = FOUR_CHAR_CODE('sope')
kAEOutline = FOUR_CHAR_CODE('outl')
kAEPageSetup = FOUR_CHAR_CODE('pgsu')
kAEPaste = FOUR_CHAR_CODE('past')
kAEPlain = FOUR_CHAR_CODE('plan')
kAEPrint = FOUR_CHAR_CODE('pdoc')
kAEPrintSelection = FOUR_CHAR_CODE('spri')
kAEPrintWindow = FOUR_CHAR_CODE('pwin')
kAEPutAwaySelection = FOUR_CHAR_CODE('sput')
kAEQDAddOver = FOUR_CHAR_CODE('addo')
kAEQDAddPin = FOUR_CHAR_CODE('addp')
kAEQDAdMax = FOUR_CHAR_CODE('admx')
kAEQDAdMin = FOUR_CHAR_CODE('admn')
kAEQDBic = FOUR_CHAR_CODE('bic ')
kAEQDBlend = FOUR_CHAR_CODE('blnd')
kAEQDCopy = FOUR_CHAR_CODE('cpy ')
kAEQDNotBic = FOUR_CHAR_CODE('nbic')
kAEQDNotCopy = FOUR_CHAR_CODE('ncpy')
kAEQDNotOr = FOUR_CHAR_CODE('ntor')
kAEQDNotXor = FOUR_CHAR_CODE('nxor')
kAEQDOr = FOUR_CHAR_CODE('or ')
kAEQDSubOver = FOUR_CHAR_CODE('subo')
kAEQDSubPin = FOUR_CHAR_CODE('subp')
kAEQDSupplementalSuite = FOUR_CHAR_CODE('qdsp')
kAEQDXor = FOUR_CHAR_CODE('xor ')
kAEQuickdrawSuite = FOUR_CHAR_CODE('qdrw')
kAEQuitAll = FOUR_CHAR_CODE('quia')
kAERedo = FOUR_CHAR_CODE('redo')
kAERegular = FOUR_CHAR_CODE('regl')
kAEReopenApplication = FOUR_CHAR_CODE('rapp')
kAEReplace = FOUR_CHAR_CODE('rplc')
kAERequiredSuite = FOUR_CHAR_CODE('reqd')
kAERestart = FOUR_CHAR_CODE('rest')
kAERevealSelection = FOUR_CHAR_CODE('srev')
kAERevert = FOUR_CHAR_CODE('rvrt')
kAERightJustified = FOUR_CHAR_CODE('rght')
kAESave = FOUR_CHAR_CODE('save')
kAESelect = FOUR_CHAR_CODE('slct')
kAESetData = FOUR_CHAR_CODE('setd')
kAESetPosition = FOUR_CHAR_CODE('posn')
kAEShadow = FOUR_CHAR_CODE('shad')
kAEShowClipboard = FOUR_CHAR_CODE('shcl')
kAEShutDown = FOUR_CHAR_CODE('shut')
kAESleep = FOUR_CHAR_CODE('slep')
kAESmallCaps = FOUR_CHAR_CODE('smcp')
kAESpecialClassProperties = FOUR_CHAR_CODE('c@#!')
kAEStrikethrough = FOUR_CHAR_CODE('strk')
kAESubscript = FOUR_CHAR_CODE('sbsc')
kAESuperscript = FOUR_CHAR_CODE('spsc')
kAETableSuite = FOUR_CHAR_CODE('tbls')
kAETextSuite = FOUR_CHAR_CODE('TEXT')
kAETransactionTerminated = FOUR_CHAR_CODE('ttrm')
kAEUnderline = FOUR_CHAR_CODE('undl')
kAEUndo = FOUR_CHAR_CODE('undo')
kAEWholeWordEquals = FOUR_CHAR_CODE('wweq')
kAEYes = FOUR_CHAR_CODE('yes ')
kAEZoom = FOUR_CHAR_CODE('zoom')
kAEMouseClass = FOUR_CHAR_CODE('mous')
kAEDown = FOUR_CHAR_CODE('down')
kAEUp = FOUR_CHAR_CODE('up ')
kAEMoved = FOUR_CHAR_CODE('move')
kAEStoppedMoving = FOUR_CHAR_CODE('stop')
kAEWindowClass = FOUR_CHAR_CODE('wind')
kAEUpdate = FOUR_CHAR_CODE('updt')
kAEActivate = FOUR_CHAR_CODE('actv')
kAEDeactivate = FOUR_CHAR_CODE('dact')
kAECommandClass = FOUR_CHAR_CODE('cmnd')
kAEKeyClass = FOUR_CHAR_CODE('keyc')
kAERawKey = FOUR_CHAR_CODE('rkey')
kAEVirtualKey = FOUR_CHAR_CODE('keyc')
kAENavigationKey = FOUR_CHAR_CODE('nave')
kAEAutoDown = FOUR_CHAR_CODE('auto')
kAEApplicationClass = FOUR_CHAR_CODE('appl')
kAESuspend = FOUR_CHAR_CODE('susp')
kAEResume = FOUR_CHAR_CODE('rsme')
kAEDiskEvent = FOUR_CHAR_CODE('disk')
kAENullEvent = FOUR_CHAR_CODE('null')
kAEWakeUpEvent = FOUR_CHAR_CODE('wake')
kAEScrapEvent = FOUR_CHAR_CODE('scrp')
kAEHighLevel = FOUR_CHAR_CODE('high')
keyAEAngle = FOUR_CHAR_CODE('kang')
keyAEArcAngle = FOUR_CHAR_CODE('parc')
keyAEBaseAddr = FOUR_CHAR_CODE('badd')
keyAEBestType = FOUR_CHAR_CODE('pbst')
keyAEBgndColor = FOUR_CHAR_CODE('kbcl')
keyAEBgndPattern = FOUR_CHAR_CODE('kbpt')
keyAEBounds = FOUR_CHAR_CODE('pbnd')
keyAECellList = FOUR_CHAR_CODE('kclt')
keyAEClassID = FOUR_CHAR_CODE('clID')
keyAEColor = FOUR_CHAR_CODE('colr')
keyAEColorTable = FOUR_CHAR_CODE('cltb')
keyAECurveHeight = FOUR_CHAR_CODE('kchd')
keyAECurveWidth = FOUR_CHAR_CODE('kcwd')
keyAEDashStyle = FOUR_CHAR_CODE('pdst')
keyAEData = FOUR_CHAR_CODE('data')
keyAEDefaultType = FOUR_CHAR_CODE('deft')
keyAEDefinitionRect = FOUR_CHAR_CODE('pdrt')
keyAEDescType = FOUR_CHAR_CODE('dstp')
keyAEDestination = FOUR_CHAR_CODE('dest')
keyAEDoAntiAlias = FOUR_CHAR_CODE('anta')
keyAEDoDithered = FOUR_CHAR_CODE('gdit')
keyAEDoRotate = FOUR_CHAR_CODE('kdrt')
keyAEDoScale = FOUR_CHAR_CODE('ksca')
keyAEDoTranslate = FOUR_CHAR_CODE('ktra')
keyAEEditionFileLoc = FOUR_CHAR_CODE('eloc')
keyAEElements = FOUR_CHAR_CODE('elms')
keyAEEndPoint = FOUR_CHAR_CODE('pend')
keyAEEventClass = FOUR_CHAR_CODE('evcl')
keyAEEventID = FOUR_CHAR_CODE('evti')
keyAEFile = FOUR_CHAR_CODE('kfil')
keyAEFileType = FOUR_CHAR_CODE('fltp')
keyAEFillColor = FOUR_CHAR_CODE('flcl')
keyAEFillPattern = FOUR_CHAR_CODE('flpt')
keyAEFlipHorizontal = FOUR_CHAR_CODE('kfho')
keyAEFlipVertical = FOUR_CHAR_CODE('kfvt')
keyAEFont = FOUR_CHAR_CODE('font')
keyAEFormula = FOUR_CHAR_CODE('pfor')
keyAEGraphicObjects = FOUR_CHAR_CODE('gobs')
keyAEID = FOUR_CHAR_CODE('ID ')
keyAEImageQuality = FOUR_CHAR_CODE('gqua')
keyAEInsertHere = FOUR_CHAR_CODE('insh')
keyAEKeyForms = FOUR_CHAR_CODE('keyf')
keyAEKeyword = FOUR_CHAR_CODE('kywd')
keyAELevel = FOUR_CHAR_CODE('levl')
keyAELineArrow = FOUR_CHAR_CODE('arro')
keyAEName = FOUR_CHAR_CODE('pnam')
keyAENewElementLoc = FOUR_CHAR_CODE('pnel')
keyAEObject = FOUR_CHAR_CODE('kobj')
keyAEObjectClass = FOUR_CHAR_CODE('kocl')
keyAEOffStyles = FOUR_CHAR_CODE('ofst')
keyAEOnStyles = FOUR_CHAR_CODE('onst')
keyAEParameters = FOUR_CHAR_CODE('prms')
keyAEParamFlags = FOUR_CHAR_CODE('pmfg')
keyAEPenColor = FOUR_CHAR_CODE('ppcl')
keyAEPenPattern = FOUR_CHAR_CODE('pppa')
keyAEPenWidth = FOUR_CHAR_CODE('ppwd')
keyAEPixelDepth = FOUR_CHAR_CODE('pdpt')
keyAEPixMapMinus = FOUR_CHAR_CODE('kpmm')
keyAEPMTable = FOUR_CHAR_CODE('kpmt')
keyAEPointList = FOUR_CHAR_CODE('ptlt')
keyAEPointSize = FOUR_CHAR_CODE('ptsz')
keyAEPosition = FOUR_CHAR_CODE('kpos')
keyAEPropData = FOUR_CHAR_CODE('prdt')
keyAEProperties = FOUR_CHAR_CODE('qpro')
keyAEProperty = FOUR_CHAR_CODE('kprp')
keyAEPropFlags = FOUR_CHAR_CODE('prfg')
keyAEPropID = FOUR_CHAR_CODE('prop')
keyAEProtection = FOUR_CHAR_CODE('ppro')
keyAERenderAs = FOUR_CHAR_CODE('kren')
keyAERequestedType = FOUR_CHAR_CODE('rtyp')
keyAEResult = FOUR_CHAR_CODE('----')
keyAEResultInfo = FOUR_CHAR_CODE('rsin')
keyAERotation = FOUR_CHAR_CODE('prot')
keyAERotPoint = FOUR_CHAR_CODE('krtp')
keyAERowList = FOUR_CHAR_CODE('krls')
keyAESaveOptions = FOUR_CHAR_CODE('savo')
keyAEScale = FOUR_CHAR_CODE('pscl')
keyAEScriptTag = FOUR_CHAR_CODE('psct')
keyAEShowWhere = FOUR_CHAR_CODE('show')
keyAEStartAngle = FOUR_CHAR_CODE('pang')
keyAEStartPoint = FOUR_CHAR_CODE('pstp')
keyAEStyles = FOUR_CHAR_CODE('ksty')
keyAESuiteID = FOUR_CHAR_CODE('suit')
keyAEText = FOUR_CHAR_CODE('ktxt')
keyAETextColor = FOUR_CHAR_CODE('ptxc')
keyAETextFont = FOUR_CHAR_CODE('ptxf')
keyAETextPointSize = FOUR_CHAR_CODE('ptps')
keyAETextStyles = FOUR_CHAR_CODE('txst')
keyAETextLineHeight = FOUR_CHAR_CODE('ktlh')
keyAETextLineAscent = FOUR_CHAR_CODE('ktas')
keyAETheText = FOUR_CHAR_CODE('thtx')
keyAETransferMode = FOUR_CHAR_CODE('pptm')
keyAETranslation = FOUR_CHAR_CODE('ptrs')
keyAETryAsStructGraf = FOUR_CHAR_CODE('toog')
keyAEUniformStyles = FOUR_CHAR_CODE('ustl')
keyAEUpdateOn = FOUR_CHAR_CODE('pupd')
keyAEUserTerm = FOUR_CHAR_CODE('utrm')
keyAEWindow = FOUR_CHAR_CODE('wndw')
keyAEWritingCode = FOUR_CHAR_CODE('wrcd')
keyMiscellaneous = FOUR_CHAR_CODE('fmsc')
keySelection = FOUR_CHAR_CODE('fsel')
keyWindow = FOUR_CHAR_CODE('kwnd')
keyWhen = FOUR_CHAR_CODE('when')
keyWhere = FOUR_CHAR_CODE('wher')
keyModifiers = FOUR_CHAR_CODE('mods')
keyKey = FOUR_CHAR_CODE('key ')
keyKeyCode = FOUR_CHAR_CODE('code')
keyKeyboard = FOUR_CHAR_CODE('keyb')
keyDriveNumber = FOUR_CHAR_CODE('drv#')
keyErrorCode = FOUR_CHAR_CODE('err#')
keyHighLevelClass = FOUR_CHAR_CODE('hcls')
keyHighLevelID = FOUR_CHAR_CODE('hid ')
pArcAngle = FOUR_CHAR_CODE('parc')
pBackgroundColor = FOUR_CHAR_CODE('pbcl')
pBackgroundPattern = FOUR_CHAR_CODE('pbpt')
pBestType = FOUR_CHAR_CODE('pbst')
pBounds = FOUR_CHAR_CODE('pbnd')
pClass = FOUR_CHAR_CODE('pcls')
pClipboard = FOUR_CHAR_CODE('pcli')
pColor = FOUR_CHAR_CODE('colr')
pColorTable = FOUR_CHAR_CODE('cltb')
pContents = FOUR_CHAR_CODE('pcnt')
pCornerCurveHeight = FOUR_CHAR_CODE('pchd')
pCornerCurveWidth = FOUR_CHAR_CODE('pcwd')
pDashStyle = FOUR_CHAR_CODE('pdst')
pDefaultType = FOUR_CHAR_CODE('deft')
pDefinitionRect = FOUR_CHAR_CODE('pdrt')
pEnabled = FOUR_CHAR_CODE('enbl')
pEndPoint = FOUR_CHAR_CODE('pend')
pFillColor = FOUR_CHAR_CODE('flcl')
pFillPattern = FOUR_CHAR_CODE('flpt')
pFont = FOUR_CHAR_CODE('font')
pFormula = FOUR_CHAR_CODE('pfor')
pGraphicObjects = FOUR_CHAR_CODE('gobs')
pHasCloseBox = FOUR_CHAR_CODE('hclb')
pHasTitleBar = FOUR_CHAR_CODE('ptit')
pID = FOUR_CHAR_CODE('ID ')
pIndex = FOUR_CHAR_CODE('pidx')
pInsertionLoc = FOUR_CHAR_CODE('pins')
pIsFloating = FOUR_CHAR_CODE('isfl')
pIsFrontProcess = FOUR_CHAR_CODE('pisf')
pIsModal = FOUR_CHAR_CODE('pmod')
pIsModified = FOUR_CHAR_CODE('imod')
pIsResizable = FOUR_CHAR_CODE('prsz')
pIsStationeryPad = FOUR_CHAR_CODE('pspd')
pIsZoomable = FOUR_CHAR_CODE('iszm')
pIsZoomed = FOUR_CHAR_CODE('pzum')
pItemNumber = FOUR_CHAR_CODE('itmn')
pJustification = FOUR_CHAR_CODE('pjst')
pLineArrow = FOUR_CHAR_CODE('arro')
pMenuID = FOUR_CHAR_CODE('mnid')
pName = FOUR_CHAR_CODE('pnam')
pNewElementLoc = FOUR_CHAR_CODE('pnel')
pPenColor = FOUR_CHAR_CODE('ppcl')
pPenPattern = FOUR_CHAR_CODE('pppa')
pPenWidth = FOUR_CHAR_CODE('ppwd')
pPixelDepth = FOUR_CHAR_CODE('pdpt')
pPointList = FOUR_CHAR_CODE('ptlt')
pPointSize = FOUR_CHAR_CODE('ptsz')
pProtection = FOUR_CHAR_CODE('ppro')
pRotation = FOUR_CHAR_CODE('prot')
pScale = FOUR_CHAR_CODE('pscl')
pScript = FOUR_CHAR_CODE('scpt')
pScriptTag = FOUR_CHAR_CODE('psct')
pSelected = FOUR_CHAR_CODE('selc')
pSelection = FOUR_CHAR_CODE('sele')
pStartAngle = FOUR_CHAR_CODE('pang')
pStartPoint = FOUR_CHAR_CODE('pstp')
pTextColor = FOUR_CHAR_CODE('ptxc')
pTextFont = FOUR_CHAR_CODE('ptxf')
pTextItemDelimiters = FOUR_CHAR_CODE('txdl')
pTextPointSize = FOUR_CHAR_CODE('ptps')
pTextStyles = FOUR_CHAR_CODE('txst')
pTransferMode = FOUR_CHAR_CODE('pptm')
pTranslation = FOUR_CHAR_CODE('ptrs')
pUniformStyles = FOUR_CHAR_CODE('ustl')
pUpdateOn = FOUR_CHAR_CODE('pupd')
pUserSelection = FOUR_CHAR_CODE('pusl')
pVersion = FOUR_CHAR_CODE('vers')
pVisible = FOUR_CHAR_CODE('pvis')
typeAEText = FOUR_CHAR_CODE('tTXT')
typeArc = FOUR_CHAR_CODE('carc')
typeBest = FOUR_CHAR_CODE('best')
typeCell = FOUR_CHAR_CODE('ccel')
typeClassInfo = FOUR_CHAR_CODE('gcli')
typeColorTable = FOUR_CHAR_CODE('clrt')
typeColumn = FOUR_CHAR_CODE('ccol')
typeDashStyle = FOUR_CHAR_CODE('tdas')
typeData = FOUR_CHAR_CODE('tdta')
typeDrawingArea = FOUR_CHAR_CODE('cdrw')
typeElemInfo = FOUR_CHAR_CODE('elin')
typeEnumeration = FOUR_CHAR_CODE('enum')
typeEPS = FOUR_CHAR_CODE('EPS ')
typeEventInfo = FOUR_CHAR_CODE('evin')
typeFinderWindow = FOUR_CHAR_CODE('fwin')
typeFixedPoint = FOUR_CHAR_CODE('fpnt')
typeFixedRectangle = FOUR_CHAR_CODE('frct')
typeGraphicLine = FOUR_CHAR_CODE('glin')
typeGraphicText = FOUR_CHAR_CODE('cgtx')
typeGroupedGraphic = FOUR_CHAR_CODE('cpic')
typeInsertionLoc = FOUR_CHAR_CODE('insl')
typeIntlText = FOUR_CHAR_CODE('itxt')
typeIntlWritingCode = FOUR_CHAR_CODE('intl')
typeLongDateTime = FOUR_CHAR_CODE('ldt ')
typeLongFixed = FOUR_CHAR_CODE('lfxd')
typeLongFixedPoint = FOUR_CHAR_CODE('lfpt')
typeLongFixedRectangle = FOUR_CHAR_CODE('lfrc')
typeLongPoint = FOUR_CHAR_CODE('lpnt')
typeLongRectangle = FOUR_CHAR_CODE('lrct')
typeMachineLoc = FOUR_CHAR_CODE('mLoc')
typeOval = FOUR_CHAR_CODE('covl')
typeParamInfo = FOUR_CHAR_CODE('pmin')
typePict = FOUR_CHAR_CODE('PICT')
typePixelMap = FOUR_CHAR_CODE('cpix')
typePixMapMinus = FOUR_CHAR_CODE('tpmm')
typePolygon = FOUR_CHAR_CODE('cpgn')
typePropInfo = FOUR_CHAR_CODE('pinf')
typePtr = FOUR_CHAR_CODE('ptr ')
typeQDPoint = FOUR_CHAR_CODE('QDpt')
typeQDRegion = FOUR_CHAR_CODE('Qrgn')
typeRectangle = FOUR_CHAR_CODE('crec')
typeRGB16 = FOUR_CHAR_CODE('tr16')
typeRGB96 = FOUR_CHAR_CODE('tr96')
typeRGBColor = FOUR_CHAR_CODE('cRGB')
typeRotation = FOUR_CHAR_CODE('trot')
typeRoundedRectangle = FOUR_CHAR_CODE('crrc')
typeRow = FOUR_CHAR_CODE('crow')
typeScrapStyles = FOUR_CHAR_CODE('styl')
typeScript = FOUR_CHAR_CODE('scpt')
typeStyledText = FOUR_CHAR_CODE('STXT')
typeSuiteInfo = FOUR_CHAR_CODE('suin')
typeTable = FOUR_CHAR_CODE('ctbl')
typeTextStyles = FOUR_CHAR_CODE('tsty')
typeTIFF = FOUR_CHAR_CODE('TIFF')
typeVersion = FOUR_CHAR_CODE('vers')
kAEMenuClass = FOUR_CHAR_CODE('menu')
kAEMenuSelect = FOUR_CHAR_CODE('mhit')
kAEMouseDown = FOUR_CHAR_CODE('mdwn')
kAEMouseDownInBack = FOUR_CHAR_CODE('mdbk')
kAEKeyDown = FOUR_CHAR_CODE('kdwn')
kAEResized = FOUR_CHAR_CODE('rsiz')
kAEPromise = FOUR_CHAR_CODE('prom')
keyMenuID = FOUR_CHAR_CODE('mid ')
keyMenuItem = FOUR_CHAR_CODE('mitm')
keyCloseAllWindows = FOUR_CHAR_CODE('caw ')
keyOriginalBounds = FOUR_CHAR_CODE('obnd')
keyNewBounds = FOUR_CHAR_CODE('nbnd')
keyLocalWhere = FOUR_CHAR_CODE('lwhr')
typeHIMenu = FOUR_CHAR_CODE('mobj')
typeHIWindow = FOUR_CHAR_CODE('wobj')
kBySmallIcon = 0
kByIconView = 1
kByNameView = 2
kByDateView = 3
kBySizeView = 4
kByKindView = 5
kByCommentView = 6
kByLabelView = 7
kByVersionView = 8
kAEInfo = 11
kAEMain = 0
kAESharing = 13
kAEZoomIn = 7
kAEZoomOut = 8
kTextServiceClass = FOUR_CHAR_CODE('tsvc')
kUpdateActiveInputArea = FOUR_CHAR_CODE('updt')
kShowHideInputWindow = FOUR_CHAR_CODE('shiw')
kPos2Offset = FOUR_CHAR_CODE('p2st')
kOffset2Pos = FOUR_CHAR_CODE('st2p')
kUnicodeNotFromInputMethod = FOUR_CHAR_CODE('unim')
kGetSelectedText = FOUR_CHAR_CODE('gtxt')
keyAETSMDocumentRefcon = FOUR_CHAR_CODE('refc')
keyAEServerInstance = FOUR_CHAR_CODE('srvi')
keyAETheData = FOUR_CHAR_CODE('kdat')
keyAEFixLength = FOUR_CHAR_CODE('fixl')
keyAEUpdateRange = FOUR_CHAR_CODE('udng')
keyAECurrentPoint = FOUR_CHAR_CODE('cpos')
keyAEBufferSize = FOUR_CHAR_CODE('buff')
keyAEMoveView = FOUR_CHAR_CODE('mvvw')
keyAENextBody = FOUR_CHAR_CODE('nxbd')
keyAETSMScriptTag = FOUR_CHAR_CODE('sclg')
keyAETSMTextFont = FOUR_CHAR_CODE('ktxf')
keyAETSMTextFMFont = FOUR_CHAR_CODE('ktxm')
keyAETSMTextPointSize = FOUR_CHAR_CODE('ktps')
keyAETSMEventRecord = FOUR_CHAR_CODE('tevt')
keyAETSMEventRef = FOUR_CHAR_CODE('tevr')
keyAETextServiceEncoding = FOUR_CHAR_CODE('tsen')
keyAETextServiceMacEncoding = FOUR_CHAR_CODE('tmen')
typeTextRange = FOUR_CHAR_CODE('txrn')
typeComponentInstance = FOUR_CHAR_CODE('cmpi')
typeOffsetArray = FOUR_CHAR_CODE('ofay')
typeTextRangeArray = FOUR_CHAR_CODE('tray')
typeLowLevelEventRecord = FOUR_CHAR_CODE('evtr')
typeEventRef = FOUR_CHAR_CODE('evrf')
typeText = typeChar
kTSMOutsideOfBody = 1
kTSMInsideOfBody = 2
kTSMInsideOfActiveInputArea = 3
kNextBody = 1
kPreviousBody = 2
kCaretPosition = 1
kRawText = 2
kSelectedRawText = 3
kConvertedText = 4
kSelectedConvertedText = 5
kBlockFillText = 6
kOutlineText = 7
kSelectedText = 8
keyAEHiliteRange = FOUR_CHAR_CODE('hrng')
keyAEPinRange = FOUR_CHAR_CODE('pnrg')
keyAEClauseOffsets = FOUR_CHAR_CODE('clau')
keyAEOffset = FOUR_CHAR_CODE('ofst')
keyAEPoint = FOUR_CHAR_CODE('gpos')
keyAELeftSide = FOUR_CHAR_CODE('klef')
keyAERegionClass = FOUR_CHAR_CODE('rgnc')
keyAEDragging = FOUR_CHAR_CODE('bool')
keyAELeadingEdge = keyAELeftSide
typeUnicodeText = FOUR_CHAR_CODE('utxt')
typeStyledUnicodeText = FOUR_CHAR_CODE('sutx')
typeEncodedString = FOUR_CHAR_CODE('encs')
typeCString = FOUR_CHAR_CODE('cstr')
typePString = FOUR_CHAR_CODE('pstr')
typeMeters = FOUR_CHAR_CODE('metr')
typeInches = FOUR_CHAR_CODE('inch')
typeFeet = FOUR_CHAR_CODE('feet')
typeYards = FOUR_CHAR_CODE('yard')
typeMiles = FOUR_CHAR_CODE('mile')
typeKilometers = FOUR_CHAR_CODE('kmtr')
typeCentimeters = FOUR_CHAR_CODE('cmtr')
typeSquareMeters = FOUR_CHAR_CODE('sqrm')
typeSquareFeet = FOUR_CHAR_CODE('sqft')
typeSquareYards = FOUR_CHAR_CODE('sqyd')
typeSquareMiles = FOUR_CHAR_CODE('sqmi')
typeSquareKilometers = FOUR_CHAR_CODE('sqkm')
typeLiters = FOUR_CHAR_CODE('litr')
typeQuarts = FOUR_CHAR_CODE('qrts')
typeGallons = FOUR_CHAR_CODE('galn')
typeCubicMeters = FOUR_CHAR_CODE('cmet')
typeCubicFeet = FOUR_CHAR_CODE('cfet')
typeCubicInches = FOUR_CHAR_CODE('cuin')
typeCubicCentimeter = FOUR_CHAR_CODE('ccmt')
typeCubicYards = FOUR_CHAR_CODE('cyrd')
typeKilograms = FOUR_CHAR_CODE('kgrm')
typeGrams = FOUR_CHAR_CODE('gram')
typeOunces = FOUR_CHAR_CODE('ozs ')
typePounds = FOUR_CHAR_CODE('lbs ')
typeDegreesC = FOUR_CHAR_CODE('degc')
typeDegreesF = FOUR_CHAR_CODE('degf')
typeDegreesK = FOUR_CHAR_CODE('degk')
kFAServerApp = FOUR_CHAR_CODE('ssrv')
kDoFolderActionEvent = FOUR_CHAR_CODE('fola')
kFolderActionCode = FOUR_CHAR_CODE('actn')
kFolderOpenedEvent = FOUR_CHAR_CODE('fopn')
kFolderClosedEvent = FOUR_CHAR_CODE('fclo')
kFolderWindowMovedEvent = FOUR_CHAR_CODE('fsiz')
kFolderItemsAddedEvent = FOUR_CHAR_CODE('fget')
kFolderItemsRemovedEvent = FOUR_CHAR_CODE('flos')
kItemList = FOUR_CHAR_CODE('flst')
kNewSizeParameter = FOUR_CHAR_CODE('fnsz')
kFASuiteCode = FOUR_CHAR_CODE('faco')
kFAAttachCommand = FOUR_CHAR_CODE('atfa')
kFARemoveCommand = FOUR_CHAR_CODE('rmfa')
kFAEditCommand = FOUR_CHAR_CODE('edfa')
kFAFileParam = FOUR_CHAR_CODE('faal')
kFAIndexParam = FOUR_CHAR_CODE('indx')
kAEInternetSuite = FOUR_CHAR_CODE('gurl')
kAEISWebStarSuite = FOUR_CHAR_CODE('WWW\xbd')
kAEISGetURL = FOUR_CHAR_CODE('gurl')
KAEISHandleCGI = FOUR_CHAR_CODE('sdoc')
cURL = FOUR_CHAR_CODE('url ')
cInternetAddress = FOUR_CHAR_CODE('IPAD')
cHTML = FOUR_CHAR_CODE('html')
cFTPItem = FOUR_CHAR_CODE('ftp ')
kAEISHTTPSearchArgs = FOUR_CHAR_CODE('kfor')
kAEISPostArgs = FOUR_CHAR_CODE('post')
kAEISMethod = FOUR_CHAR_CODE('meth')
kAEISClientAddress = FOUR_CHAR_CODE('addr')
kAEISUserName = FOUR_CHAR_CODE('user')
kAEISPassword = FOUR_CHAR_CODE('pass')
kAEISFromUser = FOUR_CHAR_CODE('frmu')
kAEISServerName = FOUR_CHAR_CODE('svnm')
kAEISServerPort = FOUR_CHAR_CODE('svpt')
kAEISScriptName = FOUR_CHAR_CODE('scnm')
kAEISContentType = FOUR_CHAR_CODE('ctyp')
kAEISReferrer = FOUR_CHAR_CODE('refr')
kAEISUserAgent = FOUR_CHAR_CODE('Agnt')
kAEISAction = FOUR_CHAR_CODE('Kact')
kAEISActionPath = FOUR_CHAR_CODE('Kapt')
kAEISClientIP = FOUR_CHAR_CODE('Kcip')
kAEISFullRequest = FOUR_CHAR_CODE('Kfrq')
pScheme = FOUR_CHAR_CODE('pusc')
pHost = FOUR_CHAR_CODE('HOST')
pPath = FOUR_CHAR_CODE('FTPc')
pUserName = FOUR_CHAR_CODE('RAun')
pUserPassword = FOUR_CHAR_CODE('RApw')
pDNSForm = FOUR_CHAR_CODE('pDNS')
pURL = FOUR_CHAR_CODE('pURL')
pTextEncoding = FOUR_CHAR_CODE('ptxe')
pFTPKind = FOUR_CHAR_CODE('kind')
eScheme = FOUR_CHAR_CODE('esch')
eurlHTTP = FOUR_CHAR_CODE('http')
eurlHTTPS = FOUR_CHAR_CODE('htps')
eurlFTP = FOUR_CHAR_CODE('ftp ')
eurlMail = FOUR_CHAR_CODE('mail')
eurlFile = FOUR_CHAR_CODE('file')
eurlGopher = FOUR_CHAR_CODE('gphr')
eurlTelnet = FOUR_CHAR_CODE('tlnt')
eurlNews = FOUR_CHAR_CODE('news')
eurlSNews = FOUR_CHAR_CODE('snws')
eurlNNTP = FOUR_CHAR_CODE('nntp')
eurlMessage = FOUR_CHAR_CODE('mess')
eurlMailbox = FOUR_CHAR_CODE('mbox')
eurlMulti = FOUR_CHAR_CODE('mult')
eurlLaunch = FOUR_CHAR_CODE('laun')
eurlAFP = FOUR_CHAR_CODE('afp ')
eurlAT = FOUR_CHAR_CODE('at ')
eurlEPPC = FOUR_CHAR_CODE('eppc')
eurlRTSP = FOUR_CHAR_CODE('rtsp')
eurlIMAP = FOUR_CHAR_CODE('imap')
eurlNFS = FOUR_CHAR_CODE('unfs')
eurlPOP = FOUR_CHAR_CODE('upop')
eurlLDAP = FOUR_CHAR_CODE('uldp')
eurlUnknown = FOUR_CHAR_CODE('url?')
kConnSuite = FOUR_CHAR_CODE('macc')
cDevSpec = FOUR_CHAR_CODE('cdev')
cAddressSpec = FOUR_CHAR_CODE('cadr')
cADBAddress = FOUR_CHAR_CODE('cadb')
cAppleTalkAddress = FOUR_CHAR_CODE('cat ')
cBusAddress = FOUR_CHAR_CODE('cbus')
cEthernetAddress = FOUR_CHAR_CODE('cen ')
cFireWireAddress = FOUR_CHAR_CODE('cfw ')
cIPAddress = FOUR_CHAR_CODE('cip ')
cLocalTalkAddress = FOUR_CHAR_CODE('clt ')
cSCSIAddress = FOUR_CHAR_CODE('cscs')
cTokenRingAddress = FOUR_CHAR_CODE('ctok')
cUSBAddress = FOUR_CHAR_CODE('cusb')
pDeviceType = FOUR_CHAR_CODE('pdvt')
pDeviceAddress = FOUR_CHAR_CODE('pdva')
pConduit = FOUR_CHAR_CODE('pcon')
pProtocol = FOUR_CHAR_CODE('pprt')
pATMachine = FOUR_CHAR_CODE('patm')
pATZone = FOUR_CHAR_CODE('patz')
pATType = FOUR_CHAR_CODE('patt')
pDottedDecimal = FOUR_CHAR_CODE('pipd')
pDNS = FOUR_CHAR_CODE('pdns')
pPort = FOUR_CHAR_CODE('ppor')
pNetwork = FOUR_CHAR_CODE('pnet')
pNode = FOUR_CHAR_CODE('pnod')
pSocket = FOUR_CHAR_CODE('psoc')
pSCSIBus = FOUR_CHAR_CODE('pscb')
pSCSILUN = FOUR_CHAR_CODE('pslu')
eDeviceType = FOUR_CHAR_CODE('edvt')
eAddressSpec = FOUR_CHAR_CODE('eads')
eConduit = FOUR_CHAR_CODE('econ')
eProtocol = FOUR_CHAR_CODE('epro')
eADB = FOUR_CHAR_CODE('eadb')
eAnalogAudio = FOUR_CHAR_CODE('epau')
eAppleTalk = FOUR_CHAR_CODE('epat')
eAudioLineIn = FOUR_CHAR_CODE('ecai')
eAudioLineOut = FOUR_CHAR_CODE('ecal')
eAudioOut = FOUR_CHAR_CODE('ecao')
eBus = FOUR_CHAR_CODE('ebus')
eCDROM = FOUR_CHAR_CODE('ecd ')
eCommSlot = FOUR_CHAR_CODE('eccm')
eDigitalAudio = FOUR_CHAR_CODE('epda')
eDisplay = FOUR_CHAR_CODE('edds')
eDVD = FOUR_CHAR_CODE('edvd')
eEthernet = FOUR_CHAR_CODE('ecen')
eFireWire = FOUR_CHAR_CODE('ecfw')
eFloppy = FOUR_CHAR_CODE('efd ')
eHD = FOUR_CHAR_CODE('ehd ')
eInfrared = FOUR_CHAR_CODE('ecir')
eIP = FOUR_CHAR_CODE('epip')
eIrDA = FOUR_CHAR_CODE('epir')
eIRTalk = FOUR_CHAR_CODE('epit')
eKeyboard = FOUR_CHAR_CODE('ekbd')
eLCD = FOUR_CHAR_CODE('edlc')
eLocalTalk = FOUR_CHAR_CODE('eclt')
eMacIP = FOUR_CHAR_CODE('epmi')
eMacVideo = FOUR_CHAR_CODE('epmv')
eMicrophone = FOUR_CHAR_CODE('ecmi')
eModemPort = FOUR_CHAR_CODE('ecmp')
eModemPrinterPort = FOUR_CHAR_CODE('empp')
eModem = FOUR_CHAR_CODE('edmm')
eMonitorOut = FOUR_CHAR_CODE('ecmn')
eMouse = FOUR_CHAR_CODE('emou')
eNuBusCard = FOUR_CHAR_CODE('ednb')
eNuBus = FOUR_CHAR_CODE('enub')
ePCcard = FOUR_CHAR_CODE('ecpc')
ePCIbus = FOUR_CHAR_CODE('ecpi')
ePCIcard = FOUR_CHAR_CODE('edpi')
ePDSslot = FOUR_CHAR_CODE('ecpd')
ePDScard = FOUR_CHAR_CODE('epds')
ePointingDevice = FOUR_CHAR_CODE('edpd')
ePostScript = FOUR_CHAR_CODE('epps')
ePPP = FOUR_CHAR_CODE('eppp')
ePrinterPort = FOUR_CHAR_CODE('ecpp')
ePrinter = FOUR_CHAR_CODE('edpr')
eSvideo = FOUR_CHAR_CODE('epsv')
eSCSI = FOUR_CHAR_CODE('ecsc')
eSerial = FOUR_CHAR_CODE('epsr')
eSpeakers = FOUR_CHAR_CODE('edsp')
eStorageDevice = FOUR_CHAR_CODE('edst')
eSVGA = FOUR_CHAR_CODE('epsg')
eTokenRing = FOUR_CHAR_CODE('etok')
eTrackball = FOUR_CHAR_CODE('etrk')
eTrackpad = FOUR_CHAR_CODE('edtp')
eUSB = FOUR_CHAR_CODE('ecus')
eVideoIn = FOUR_CHAR_CODE('ecvi')
eVideoMonitor = FOUR_CHAR_CODE('edvm')
eVideoOut = FOUR_CHAR_CODE('ecvo')
cKeystroke = FOUR_CHAR_CODE('kprs')
pKeystrokeKey = FOUR_CHAR_CODE('kMsg')
pModifiers = FOUR_CHAR_CODE('kMod')
pKeyKind = FOUR_CHAR_CODE('kknd')
eModifiers = FOUR_CHAR_CODE('eMds')
eOptionDown = FOUR_CHAR_CODE('Kopt')
eCommandDown = FOUR_CHAR_CODE('Kcmd')
eControlDown = FOUR_CHAR_CODE('Kctl')
eShiftDown = FOUR_CHAR_CODE('Ksft')
eCapsLockDown = FOUR_CHAR_CODE('Kclk')
eKeyKind = FOUR_CHAR_CODE('ekst')
eEscapeKey = 0x6B733500
eDeleteKey = 0x6B733300
eTabKey = 0x6B733000
eReturnKey = 0x6B732400
eClearKey = 0x6B734700
eEnterKey = 0x6B734C00
eUpArrowKey = 0x6B737E00
eDownArrowKey = 0x6B737D00
eLeftArrowKey = 0x6B737B00
eRightArrowKey = 0x6B737C00
eHelpKey = 0x6B737200
eHomeKey = 0x6B737300
ePageUpKey = 0x6B737400
ePageDownKey = 0x6B737900
eForwardDelKey = 0x6B737500
eEndKey = 0x6B737700
eF1Key = 0x6B737A00
eF2Key = 0x6B737800
eF3Key = 0x6B736300
eF4Key = 0x6B737600
eF5Key = 0x6B736000
eF6Key = 0x6B736100
eF7Key = 0x6B736200
eF8Key = 0x6B736400
eF9Key = 0x6B736500
eF10Key = 0x6B736D00
eF11Key = 0x6B736700
eF12Key = 0x6B736F00
eF13Key = 0x6B736900
eF14Key = 0x6B736B00
eF15Key = 0x6B737100
kAEAND = FOUR_CHAR_CODE('AND ')
kAEOR = FOUR_CHAR_CODE('OR ')
kAENOT = FOUR_CHAR_CODE('NOT ')
kAEFirst = FOUR_CHAR_CODE('firs')
kAELast = FOUR_CHAR_CODE('last')
kAEMiddle = FOUR_CHAR_CODE('midd')
kAEAny = FOUR_CHAR_CODE('any ')
kAEAll = FOUR_CHAR_CODE('all ')
kAENext = FOUR_CHAR_CODE('next')
kAEPrevious = FOUR_CHAR_CODE('prev')
keyAECompOperator = FOUR_CHAR_CODE('relo')
keyAELogicalTerms = FOUR_CHAR_CODE('term')
keyAELogicalOperator = FOUR_CHAR_CODE('logc')
keyAEObject1 = FOUR_CHAR_CODE('obj1')
keyAEObject2 = FOUR_CHAR_CODE('obj2')
keyAEDesiredClass = FOUR_CHAR_CODE('want')
keyAEContainer = FOUR_CHAR_CODE('from')
keyAEKeyForm = FOUR_CHAR_CODE('form')
keyAEKeyData = FOUR_CHAR_CODE('seld')
keyAERangeStart = FOUR_CHAR_CODE('star')
keyAERangeStop = FOUR_CHAR_CODE('stop')
keyDisposeTokenProc = FOUR_CHAR_CODE('xtok')
keyAECompareProc = FOUR_CHAR_CODE('cmpr')
keyAECountProc = FOUR_CHAR_CODE('cont')
keyAEMarkTokenProc = FOUR_CHAR_CODE('mkid')
keyAEMarkProc = FOUR_CHAR_CODE('mark')
keyAEAdjustMarksProc = FOUR_CHAR_CODE('adjm')
keyAEGetErrDescProc = FOUR_CHAR_CODE('indc')
formAbsolutePosition = FOUR_CHAR_CODE('indx')
formRelativePosition = FOUR_CHAR_CODE('rele')
formTest = FOUR_CHAR_CODE('test')
formRange = FOUR_CHAR_CODE('rang')
formPropertyID = FOUR_CHAR_CODE('prop')
formName = FOUR_CHAR_CODE('name')
typeObjectSpecifier = FOUR_CHAR_CODE('obj ')
typeObjectBeingExamined = FOUR_CHAR_CODE('exmn')
typeCurrentContainer = FOUR_CHAR_CODE('ccnt')
typeToken = FOUR_CHAR_CODE('toke')
typeRelativeDescriptor = FOUR_CHAR_CODE('rel ')
typeAbsoluteOrdinal = FOUR_CHAR_CODE('abso')
typeIndexDescriptor = FOUR_CHAR_CODE('inde')
typeRangeDescriptor = FOUR_CHAR_CODE('rang')
typeLogicalDescriptor = FOUR_CHAR_CODE('logi')
typeCompDescriptor = FOUR_CHAR_CODE('cmpd')
typeOSLTokenList = FOUR_CHAR_CODE('ostl')
kAEIDoMinimum = 0x0000
kAEIDoWhose = 0x0001
kAEIDoMarking = 0x0004
kAEPassSubDescs = 0x0008
kAEResolveNestedLists = 0x0010
kAEHandleSimpleRanges = 0x0020
kAEUseRelativeIterators = 0x0040
typeWhoseDescriptor = FOUR_CHAR_CODE('whos')
formWhose = FOUR_CHAR_CODE('whos')
typeWhoseRange = FOUR_CHAR_CODE('wrng')
keyAEWhoseRangeStart = FOUR_CHAR_CODE('wstr')
keyAEWhoseRangeStop = FOUR_CHAR_CODE('wstp')
keyAEIndex = FOUR_CHAR_CODE('kidx')
keyAETest = FOUR_CHAR_CODE('ktst')
| Python |
# Generated from 'Resources.h'
resSysHeap = 64
resPurgeable = 32
resLocked = 16
resProtected = 8
resPreload = 4
resChanged = 2
mapReadOnly = 128
mapCompact = 64
mapChanged = 32
resSysRefBit = 7
resSysHeapBit = 6
resPurgeableBit = 5
resLockedBit = 4
resProtectedBit = 3
resPreloadBit = 2
resChangedBit = 1
mapReadOnlyBit = 7
mapCompactBit = 6
mapChangedBit = 5
kResFileNotOpened = -1
kSystemResFile = 0
kRsrcChainBelowSystemMap = 0
kRsrcChainBelowApplicationMap = 1
kRsrcChainAboveApplicationMap = 2
kRsrcChainAboveAllMaps = 4
| Python |
# Generated from 'LaunchServices.h'
def FOUR_CHAR_CODE(x): return x
from Carbon.Files import *
kLSRequestAllInfo = -1
kLSRolesAll = -1
kLSUnknownType = FOUR_CHAR_CODE('\0\0\0\0')
kLSUnknownCreator = FOUR_CHAR_CODE('\0\0\0\0')
kLSInvalidExtensionIndex = -1
kLSUnknownErr = -10810
kLSNotAnApplicationErr = -10811
kLSNotInitializedErr = -10812
kLSDataUnavailableErr = -10813
kLSApplicationNotFoundErr = -10814
kLSUnknownTypeErr = -10815
kLSDataTooOldErr = -10816
kLSDataErr = -10817
kLSLaunchInProgressErr = -10818
kLSNotRegisteredErr = -10819
kLSAppDoesNotClaimTypeErr = -10820
kLSAppDoesNotSupportSchemeWarning = -10821
kLSServerCommunicationErr = -10822
kLSCannotSetInfoErr = -10823
kLSInitializeDefaults = 0x00000001
kLSMinCatInfoBitmap = (kFSCatInfoNodeFlags | kFSCatInfoParentDirID | kFSCatInfoFinderInfo | kFSCatInfoFinderXInfo)
# kLSInvalidExtensionIndex = (unsigned long)0xFFFFFFFF
kLSRequestExtension = 0x00000001
kLSRequestTypeCreator = 0x00000002
kLSRequestBasicFlagsOnly = 0x00000004
kLSRequestAppTypeFlags = 0x00000008
kLSRequestAllFlags = 0x00000010
kLSRequestIconAndKind = 0x00000020
kLSRequestExtensionFlagsOnly = 0x00000040
# kLSRequestAllInfo = (unsigned long)0xFFFFFFFF
kLSItemInfoIsPlainFile = 0x00000001
kLSItemInfoIsPackage = 0x00000002
kLSItemInfoIsApplication = 0x00000004
kLSItemInfoIsContainer = 0x00000008
kLSItemInfoIsAliasFile = 0x00000010
kLSItemInfoIsSymlink = 0x00000020
kLSItemInfoIsInvisible = 0x00000040
kLSItemInfoIsNativeApp = 0x00000080
kLSItemInfoIsClassicApp = 0x00000100
kLSItemInfoAppPrefersNative = 0x00000200
kLSItemInfoAppPrefersClassic = 0x00000400
kLSItemInfoAppIsScriptable = 0x00000800
kLSItemInfoIsVolume = 0x00001000
kLSItemInfoExtensionIsHidden = 0x00100000
kLSRolesNone = 0x00000001
kLSRolesViewer = 0x00000002
kLSRolesEditor = 0x00000004
# kLSRolesAll = (unsigned long)0xFFFFFFFF
kLSUnknownKindID = 0
# kLSUnknownType = 0
# kLSUnknownCreator = 0
kLSAcceptDefault = 0x00000001
kLSAcceptAllowLoginUI = 0x00000002
kLSLaunchDefaults = 0x00000001
kLSLaunchAndPrint = 0x00000002
kLSLaunchReserved2 = 0x00000004
kLSLaunchReserved3 = 0x00000008
kLSLaunchReserved4 = 0x00000010
kLSLaunchReserved5 = 0x00000020
kLSLaunchReserved6 = 0x00000040
kLSLaunchInhibitBGOnly = 0x00000080
kLSLaunchDontAddToRecents = 0x00000100
kLSLaunchDontSwitch = 0x00000200
kLSLaunchNoParams = 0x00000800
kLSLaunchAsync = 0x00010000
kLSLaunchStartClassic = 0x00020000
kLSLaunchInClassic = 0x00040000
kLSLaunchNewInstance = 0x00080000
kLSLaunchAndHide = 0x00100000
kLSLaunchAndHideOthers = 0x00200000
| Python |
# Generated from 'Files.h'
def FOUR_CHAR_CODE(x): return x
true = True
false = False
fsCurPerm = 0x00
fsRdPerm = 0x01
fsWrPerm = 0x02
fsRdWrPerm = 0x03
fsRdWrShPerm = 0x04
fsRdDenyPerm = 0x10
fsWrDenyPerm = 0x20
fsRtParID = 1
fsRtDirID = 2
fsAtMark = 0
fsFromStart = 1
fsFromLEOF = 2
fsFromMark = 3
pleaseCacheBit = 4
pleaseCacheMask = 0x0010
noCacheBit = 5
noCacheMask = 0x0020
rdVerifyBit = 6
rdVerifyMask = 0x0040
rdVerify = 64
forceReadBit = 6
forceReadMask = 0x0040
newLineBit = 7
newLineMask = 0x0080
newLineCharMask = 0xFF00
fsSBPartialName = 1
fsSBFullName = 2
fsSBFlAttrib = 4
fsSBFlFndrInfo = 8
fsSBFlLgLen = 32
fsSBFlPyLen = 64
fsSBFlRLgLen = 128
fsSBFlRPyLen = 256
fsSBFlCrDat = 512
fsSBFlMdDat = 1024
fsSBFlBkDat = 2048
fsSBFlXFndrInfo = 4096
fsSBFlParID = 8192
fsSBNegate = 16384
fsSBDrUsrWds = 8
fsSBDrNmFls = 16
fsSBDrCrDat = 512
fsSBDrMdDat = 1024
fsSBDrBkDat = 2048
fsSBDrFndrInfo = 4096
fsSBDrParID = 8192
fsSBPartialNameBit = 0
fsSBFullNameBit = 1
fsSBFlAttribBit = 2
fsSBFlFndrInfoBit = 3
fsSBFlLgLenBit = 5
fsSBFlPyLenBit = 6
fsSBFlRLgLenBit = 7
fsSBFlRPyLenBit = 8
fsSBFlCrDatBit = 9
fsSBFlMdDatBit = 10
fsSBFlBkDatBit = 11
fsSBFlXFndrInfoBit = 12
fsSBFlParIDBit = 13
fsSBNegateBit = 14
fsSBDrUsrWdsBit = 3
fsSBDrNmFlsBit = 4
fsSBDrCrDatBit = 9
fsSBDrMdDatBit = 10
fsSBDrBkDatBit = 11
fsSBDrFndrInfoBit = 12
fsSBDrParIDBit = 13
bLimitFCBs = 31
bLocalWList = 30
bNoMiniFndr = 29
bNoVNEdit = 28
bNoLclSync = 27
bTrshOffLine = 26
bNoSwitchTo = 25
bDontShareIt = 21
bNoDeskItems = 20
bNoBootBlks = 19
bAccessCntl = 18
bNoSysDir = 17
bHasExtFSVol = 16
bHasOpenDeny = 15
bHasCopyFile = 14
bHasMoveRename = 13
bHasDesktopMgr = 12
bHasShortName = 11
bHasFolderLock = 10
bHasPersonalAccessPrivileges = 9
bHasUserGroupList = 8
bHasCatSearch = 7
bHasFileIDs = 6
bHasBTreeMgr = 5
bHasBlankAccessPrivileges = 4
bSupportsAsyncRequests = 3
bSupportsTrashVolumeCache = 2
bIsEjectable = 0
bSupportsHFSPlusAPIs = 1
bSupportsFSCatalogSearch = 2
bSupportsFSExchangeObjects = 3
bSupports2TBFiles = 4
bSupportsLongNames = 5
bSupportsMultiScriptNames = 6
bSupportsNamedForks = 7
bSupportsSubtreeIterators = 8
bL2PCanMapFileBlocks = 9
bParentModDateChanges = 10
bAncestorModDateChanges = 11
bSupportsSymbolicLinks = 13
bIsAutoMounted = 14
bAllowCDiDataHandler = 17
kLargeIcon = 1
kLarge4BitIcon = 2
kLarge8BitIcon = 3
kSmallIcon = 4
kSmall4BitIcon = 5
kSmall8BitIcon = 6
kicnsIconFamily = 239
kLargeIconSize = 256
kLarge4BitIconSize = 512
kLarge8BitIconSize = 1024
kSmallIconSize = 64
kSmall4BitIconSize = 128
kSmall8BitIconSize = 256
kWidePosOffsetBit = 8
kUseWidePositioning = (1 << kWidePosOffsetBit)
kMaximumBlocksIn4GB = 0x007FFFFF
fsUnixPriv = 1
kNoUserAuthentication = 1
kPassword = 2
kEncryptPassword = 3
kTwoWayEncryptPassword = 6
kOwnerID2Name = 1
kGroupID2Name = 2
kOwnerName2ID = 3
kGroupName2ID = 4
kReturnNextUser = 1
kReturnNextGroup = 2
kReturnNextUG = 3
kVCBFlagsIdleFlushBit = 3
kVCBFlagsIdleFlushMask = 0x0008
kVCBFlagsHFSPlusAPIsBit = 4
kVCBFlagsHFSPlusAPIsMask = 0x0010
kVCBFlagsHardwareGoneBit = 5
kVCBFlagsHardwareGoneMask = 0x0020
kVCBFlagsVolumeDirtyBit = 15
kVCBFlagsVolumeDirtyMask = 0x8000
kioVAtrbDefaultVolumeBit = 5
kioVAtrbDefaultVolumeMask = 0x0020
kioVAtrbFilesOpenBit = 6
kioVAtrbFilesOpenMask = 0x0040
kioVAtrbHardwareLockedBit = 7
kioVAtrbHardwareLockedMask = 0x0080
kioVAtrbSoftwareLockedBit = 15
kioVAtrbSoftwareLockedMask = 0x8000
kioFlAttribLockedBit = 0
kioFlAttribLockedMask = 0x01
kioFlAttribResOpenBit = 2
kioFlAttribResOpenMask = 0x04
kioFlAttribDataOpenBit = 3
kioFlAttribDataOpenMask = 0x08
kioFlAttribDirBit = 4
kioFlAttribDirMask = 0x10
ioDirFlg = 4
ioDirMask = 0x10
kioFlAttribCopyProtBit = 6
kioFlAttribCopyProtMask = 0x40
kioFlAttribFileOpenBit = 7
kioFlAttribFileOpenMask = 0x80
kioFlAttribInSharedBit = 2
kioFlAttribInSharedMask = 0x04
kioFlAttribMountedBit = 3
kioFlAttribMountedMask = 0x08
kioFlAttribSharePointBit = 5
kioFlAttribSharePointMask = 0x20
kioFCBWriteBit = 8
kioFCBWriteMask = 0x0100
kioFCBResourceBit = 9
kioFCBResourceMask = 0x0200
kioFCBWriteLockedBit = 10
kioFCBWriteLockedMask = 0x0400
kioFCBLargeFileBit = 11
kioFCBLargeFileMask = 0x0800
kioFCBSharedWriteBit = 12
kioFCBSharedWriteMask = 0x1000
kioFCBFileLockedBit = 13
kioFCBFileLockedMask = 0x2000
kioFCBOwnClumpBit = 14
kioFCBOwnClumpMask = 0x4000
kioFCBModifiedBit = 15
kioFCBModifiedMask = 0x8000
kioACUserNoSeeFolderBit = 0
kioACUserNoSeeFolderMask = 0x01
kioACUserNoSeeFilesBit = 1
kioACUserNoSeeFilesMask = 0x02
kioACUserNoMakeChangesBit = 2
kioACUserNoMakeChangesMask = 0x04
kioACUserNotOwnerBit = 7
kioACUserNotOwnerMask = 0x80
kioACAccessOwnerBit = 31
# kioACAccessOwnerMask = (long)0x80000000
kioACAccessBlankAccessBit = 28
kioACAccessBlankAccessMask = 0x10000000
kioACAccessUserWriteBit = 26
kioACAccessUserWriteMask = 0x04000000
kioACAccessUserReadBit = 25
kioACAccessUserReadMask = 0x02000000
kioACAccessUserSearchBit = 24
kioACAccessUserSearchMask = 0x01000000
kioACAccessEveryoneWriteBit = 18
kioACAccessEveryoneWriteMask = 0x00040000
kioACAccessEveryoneReadBit = 17
kioACAccessEveryoneReadMask = 0x00020000
kioACAccessEveryoneSearchBit = 16
kioACAccessEveryoneSearchMask = 0x00010000
kioACAccessGroupWriteBit = 10
kioACAccessGroupWriteMask = 0x00000400
kioACAccessGroupReadBit = 9
kioACAccessGroupReadMask = 0x00000200
kioACAccessGroupSearchBit = 8
kioACAccessGroupSearchMask = 0x00000100
kioACAccessOwnerWriteBit = 2
kioACAccessOwnerWriteMask = 0x00000004
kioACAccessOwnerReadBit = 1
kioACAccessOwnerReadMask = 0x00000002
kioACAccessOwnerSearchBit = 0
kioACAccessOwnerSearchMask = 0x00000001
kfullPrivileges = 0x00070007
kownerPrivileges = 0x00000007
knoUser = 0
kadministratorUser = 1
knoGroup = 0
AppleShareMediaType = FOUR_CHAR_CODE('afpm')
volMountNoLoginMsgFlagBit = 0
volMountNoLoginMsgFlagMask = 0x0001
volMountExtendedFlagsBit = 7
volMountExtendedFlagsMask = 0x0080
volMountInteractBit = 15
volMountInteractMask = 0x8000
volMountChangedBit = 14
volMountChangedMask = 0x4000
volMountFSReservedMask = 0x00FF
volMountSysReservedMask = 0xFF00
kAFPExtendedFlagsAlternateAddressMask = 1
kAFPTagTypeIP = 0x01
kAFPTagTypeIPPort = 0x02
kAFPTagTypeDDP = 0x03
kAFPTagTypeDNS = 0x04
kAFPTagLengthIP = 0x06
kAFPTagLengthIPPort = 0x08
kAFPTagLengthDDP = 0x06
kFSInvalidVolumeRefNum = 0
kFSCatInfoNone = 0x00000000
kFSCatInfoTextEncoding = 0x00000001
kFSCatInfoNodeFlags = 0x00000002
kFSCatInfoVolume = 0x00000004
kFSCatInfoParentDirID = 0x00000008
kFSCatInfoNodeID = 0x00000010
kFSCatInfoCreateDate = 0x00000020
kFSCatInfoContentMod = 0x00000040
kFSCatInfoAttrMod = 0x00000080
kFSCatInfoAccessDate = 0x00000100
kFSCatInfoBackupDate = 0x00000200
kFSCatInfoPermissions = 0x00000400
kFSCatInfoFinderInfo = 0x00000800
kFSCatInfoFinderXInfo = 0x00001000
kFSCatInfoValence = 0x00002000
kFSCatInfoDataSizes = 0x00004000
kFSCatInfoRsrcSizes = 0x00008000
kFSCatInfoSharingFlags = 0x00010000
kFSCatInfoUserPrivs = 0x00020000
kFSCatInfoUserAccess = 0x00080000
kFSCatInfoAllDates = 0x000003E0
kFSCatInfoGettableInfo = 0x0003FFFF
kFSCatInfoSettableInfo = 0x00001FE3
# kFSCatInfoReserved = (long)0xFFFC0000
kFSNodeLockedBit = 0
kFSNodeLockedMask = 0x0001
kFSNodeResOpenBit = 2
kFSNodeResOpenMask = 0x0004
kFSNodeDataOpenBit = 3
kFSNodeDataOpenMask = 0x0008
kFSNodeIsDirectoryBit = 4
kFSNodeIsDirectoryMask = 0x0010
kFSNodeCopyProtectBit = 6
kFSNodeCopyProtectMask = 0x0040
kFSNodeForkOpenBit = 7
kFSNodeForkOpenMask = 0x0080
kFSNodeInSharedBit = 2
kFSNodeInSharedMask = 0x0004
kFSNodeIsMountedBit = 3
kFSNodeIsMountedMask = 0x0008
kFSNodeIsSharePointBit = 5
kFSNodeIsSharePointMask = 0x0020
kFSIterateFlat = 0
kFSIterateSubtree = 1
kFSIterateDelete = 2
# kFSIterateReserved = (long)0xFFFFFFFC
fsSBNodeID = 0x00008000
fsSBAttributeModDate = 0x00010000
fsSBAccessDate = 0x00020000
fsSBPermissions = 0x00040000
fsSBNodeIDBit = 15
fsSBAttributeModDateBit = 16
fsSBAccessDateBit = 17
fsSBPermissionsBit = 18
kFSAllocDefaultFlags = 0x0000
kFSAllocAllOrNothingMask = 0x0001
kFSAllocContiguousMask = 0x0002
kFSAllocNoRoundUpMask = 0x0004
kFSAllocReservedMask = 0xFFF8
kFSVolInfoNone = 0x0000
kFSVolInfoCreateDate = 0x0001
kFSVolInfoModDate = 0x0002
kFSVolInfoBackupDate = 0x0004
kFSVolInfoCheckedDate = 0x0008
kFSVolInfoFileCount = 0x0010
kFSVolInfoDirCount = 0x0020
kFSVolInfoSizes = 0x0040
kFSVolInfoBlocks = 0x0080
kFSVolInfoNextAlloc = 0x0100
kFSVolInfoRsrcClump = 0x0200
kFSVolInfoDataClump = 0x0400
kFSVolInfoNextID = 0x0800
kFSVolInfoFinderInfo = 0x1000
kFSVolInfoFlags = 0x2000
kFSVolInfoFSInfo = 0x4000
kFSVolInfoDriveInfo = 0x8000
kFSVolInfoGettableInfo = 0xFFFF
kFSVolInfoSettableInfo = 0x3004
kFSVolFlagDefaultVolumeBit = 5
kFSVolFlagDefaultVolumeMask = 0x0020
kFSVolFlagFilesOpenBit = 6
kFSVolFlagFilesOpenMask = 0x0040
kFSVolFlagHardwareLockedBit = 7
kFSVolFlagHardwareLockedMask = 0x0080
kFSVolFlagSoftwareLockedBit = 15
kFSVolFlagSoftwareLockedMask = 0x8000
kFNDirectoryModifiedMessage = 1
kFNNoImplicitAllSubscription = (1 << 0)
rAliasType = FOUR_CHAR_CODE('alis')
kARMMountVol = 0x00000001
kARMNoUI = 0x00000002
kARMMultVols = 0x00000008
kARMSearch = 0x00000100
kARMSearchMore = 0x00000200
kARMSearchRelFirst = 0x00000400
asiZoneName = -3
asiServerName = -2
asiVolumeName = -1
asiAliasName = 0
asiParentName = 1
kResolveAliasFileNoUI = 0x00000001
kClippingCreator = FOUR_CHAR_CODE('drag')
kClippingPictureType = FOUR_CHAR_CODE('clpp')
kClippingTextType = FOUR_CHAR_CODE('clpt')
kClippingSoundType = FOUR_CHAR_CODE('clps')
kClippingUnknownType = FOUR_CHAR_CODE('clpu')
kInternetLocationCreator = FOUR_CHAR_CODE('drag')
kInternetLocationHTTP = FOUR_CHAR_CODE('ilht')
kInternetLocationFTP = FOUR_CHAR_CODE('ilft')
kInternetLocationFile = FOUR_CHAR_CODE('ilfi')
kInternetLocationMail = FOUR_CHAR_CODE('ilma')
kInternetLocationNNTP = FOUR_CHAR_CODE('ilnw')
kInternetLocationAFP = FOUR_CHAR_CODE('ilaf')
kInternetLocationAppleTalk = FOUR_CHAR_CODE('ilat')
kInternetLocationNSL = FOUR_CHAR_CODE('ilns')
kInternetLocationGeneric = FOUR_CHAR_CODE('ilge')
kCustomIconResource = -16455
kCustomBadgeResourceType = FOUR_CHAR_CODE('badg')
kCustomBadgeResourceID = kCustomIconResource
kCustomBadgeResourceVersion = 0
# kSystemFolderType = 'macs'.
kRoutingResourceType = FOUR_CHAR_CODE('rout')
kRoutingResourceID = 0
kContainerFolderAliasType = FOUR_CHAR_CODE('fdrp')
kContainerTrashAliasType = FOUR_CHAR_CODE('trsh')
kContainerHardDiskAliasType = FOUR_CHAR_CODE('hdsk')
kContainerFloppyAliasType = FOUR_CHAR_CODE('flpy')
kContainerServerAliasType = FOUR_CHAR_CODE('srvr')
kApplicationAliasType = FOUR_CHAR_CODE('adrp')
kContainerAliasType = FOUR_CHAR_CODE('drop')
kDesktopPrinterAliasType = FOUR_CHAR_CODE('dtpa')
kContainerCDROMAliasType = FOUR_CHAR_CODE('cddr')
kApplicationCPAliasType = FOUR_CHAR_CODE('acdp')
kApplicationDAAliasType = FOUR_CHAR_CODE('addp')
kPackageAliasType = FOUR_CHAR_CODE('fpka')
kAppPackageAliasType = FOUR_CHAR_CODE('fapa')
kSystemFolderAliasType = FOUR_CHAR_CODE('fasy')
kAppleMenuFolderAliasType = FOUR_CHAR_CODE('faam')
kStartupFolderAliasType = FOUR_CHAR_CODE('fast')
kPrintMonitorDocsFolderAliasType = FOUR_CHAR_CODE('fapn')
kPreferencesFolderAliasType = FOUR_CHAR_CODE('fapf')
kControlPanelFolderAliasType = FOUR_CHAR_CODE('fact')
kExtensionFolderAliasType = FOUR_CHAR_CODE('faex')
kExportedFolderAliasType = FOUR_CHAR_CODE('faet')
kDropFolderAliasType = FOUR_CHAR_CODE('fadr')
kSharedFolderAliasType = FOUR_CHAR_CODE('fash')
kMountedFolderAliasType = FOUR_CHAR_CODE('famn')
kIsOnDesk = 0x0001
kColor = 0x000E
kIsShared = 0x0040
kHasNoINITs = 0x0080
kHasBeenInited = 0x0100
kHasCustomIcon = 0x0400
kIsStationery = 0x0800
kNameLocked = 0x1000
kHasBundle = 0x2000
kIsInvisible = 0x4000
kIsAlias = 0x8000
fOnDesk = kIsOnDesk
fHasBundle = kHasBundle
fInvisible = kIsInvisible
fTrash = -3
fDesktop = -2
fDisk = 0
kIsStationary = kIsStationery
kExtendedFlagsAreInvalid = 0x8000
kExtendedFlagHasCustomBadge = 0x0100
kExtendedFlagHasRoutingInfo = 0x0004
kFirstMagicBusyFiletype = FOUR_CHAR_CODE('bzy ')
kLastMagicBusyFiletype = FOUR_CHAR_CODE('bzy?')
kMagicBusyCreationDate = 0x4F3AFDB0
| Python |
from _Evt import *
| Python |
# Generated from 'MacWindows.h'
def FOUR_CHAR_CODE(x): return x
false = 0
true = 1
kWindowNoConstrainAttribute = 0x80000000
kAlertWindowClass = 1
kMovableAlertWindowClass = 2
kModalWindowClass = 3
kMovableModalWindowClass = 4
kFloatingWindowClass = 5
kDocumentWindowClass = 6
kUtilityWindowClass = 8
kHelpWindowClass = 10
kSheetWindowClass = 11
kToolbarWindowClass = 12
kPlainWindowClass = 13
kOverlayWindowClass = 14
kSheetAlertWindowClass = 15
kAltPlainWindowClass = 16
kDrawerWindowClass = 20
# kAllWindowClasses = (unsigned long)0xFFFFFFFF
kWindowNoAttributes = 0L
kWindowCloseBoxAttribute = (1L << 0)
kWindowHorizontalZoomAttribute = (1L << 1)
kWindowVerticalZoomAttribute = (1L << 2)
kWindowFullZoomAttribute = (kWindowVerticalZoomAttribute | kWindowHorizontalZoomAttribute)
kWindowCollapseBoxAttribute = (1L << 3)
kWindowResizableAttribute = (1L << 4)
kWindowSideTitlebarAttribute = (1L << 5)
kWindowToolbarButtonAttribute = (1L << 6)
kWindowNoUpdatesAttribute = (1L << 16)
kWindowNoActivatesAttribute = (1L << 17)
kWindowOpaqueForEventsAttribute = (1L << 18)
kWindowNoShadowAttribute = (1L << 21)
kWindowHideOnSuspendAttribute = (1L << 24)
kWindowStandardHandlerAttribute = (1L << 25)
kWindowHideOnFullScreenAttribute = (1L << 26)
kWindowInWindowMenuAttribute = (1L << 27)
kWindowLiveResizeAttribute = (1L << 28)
# kWindowNoConstrainAttribute = (unsigned long)((1L << 31))
kWindowStandardDocumentAttributes = (kWindowCloseBoxAttribute | kWindowFullZoomAttribute | kWindowCollapseBoxAttribute | kWindowResizableAttribute)
kWindowStandardFloatingAttributes = (kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute)
kWindowDefProcType = FOUR_CHAR_CODE('WDEF')
kStandardWindowDefinition = 0
kRoundWindowDefinition = 1
kFloatingWindowDefinition = 124
kDocumentWindowVariantCode = 0
kModalDialogVariantCode = 1
kPlainDialogVariantCode = 2
kShadowDialogVariantCode = 3
kMovableModalDialogVariantCode = 5
kAlertVariantCode = 7
kMovableAlertVariantCode = 9
kSideFloaterVariantCode = 8
documentProc = 0
dBoxProc = 1
plainDBox = 2
altDBoxProc = 3
noGrowDocProc = 4
movableDBoxProc = 5
zoomDocProc = 8
zoomNoGrow = 12
floatProc = 1985
floatGrowProc = 1987
floatZoomProc = 1989
floatZoomGrowProc = 1991
floatSideProc = 1993
floatSideGrowProc = 1995
floatSideZoomProc = 1997
floatSideZoomGrowProc = 1999
rDocProc = 16
kWindowDocumentDefProcResID = 64
kWindowDialogDefProcResID = 65
kWindowUtilityDefProcResID = 66
kWindowUtilitySideTitleDefProcResID = 67
kWindowSheetDefProcResID = 68
kWindowSimpleDefProcResID = 69
kWindowSheetAlertDefProcResID = 70
kWindowDocumentProc = 1024
kWindowGrowDocumentProc = 1025
kWindowVertZoomDocumentProc = 1026
kWindowVertZoomGrowDocumentProc = 1027
kWindowHorizZoomDocumentProc = 1028
kWindowHorizZoomGrowDocumentProc = 1029
kWindowFullZoomDocumentProc = 1030
kWindowFullZoomGrowDocumentProc = 1031
kWindowPlainDialogProc = 1040
kWindowShadowDialogProc = 1041
kWindowModalDialogProc = 1042
kWindowMovableModalDialogProc = 1043
kWindowAlertProc = 1044
kWindowMovableAlertProc = 1045
kWindowMovableModalGrowProc = 1046
kWindowFloatProc = 1057
kWindowFloatGrowProc = 1059
kWindowFloatVertZoomProc = 1061
kWindowFloatVertZoomGrowProc = 1063
kWindowFloatHorizZoomProc = 1065
kWindowFloatHorizZoomGrowProc = 1067
kWindowFloatFullZoomProc = 1069
kWindowFloatFullZoomGrowProc = 1071
kWindowFloatSideProc = 1073
kWindowFloatSideGrowProc = 1075
kWindowFloatSideVertZoomProc = 1077
kWindowFloatSideVertZoomGrowProc = 1079
kWindowFloatSideHorizZoomProc = 1081
kWindowFloatSideHorizZoomGrowProc = 1083
kWindowFloatSideFullZoomProc = 1085
kWindowFloatSideFullZoomGrowProc = 1087
kWindowSheetProc = 1088
kWindowSheetAlertProc = 1120
kWindowSimpleProc = 1104
kWindowSimpleFrameProc = 1105
kWindowNoPosition = 0x0000
kWindowDefaultPosition = 0x0000
kWindowCenterMainScreen = 0x280A
kWindowAlertPositionMainScreen = 0x300A
kWindowStaggerMainScreen = 0x380A
kWindowCenterParentWindow = 0xA80A
kWindowAlertPositionParentWindow = 0xB00A
kWindowStaggerParentWindow = 0xB80A
kWindowCenterParentWindowScreen = 0x680A
kWindowAlertPositionParentWindowScreen = 0x700A
kWindowStaggerParentWindowScreen = 0x780A
kWindowCenterOnMainScreen = 1
kWindowCenterOnParentWindow = 2
kWindowCenterOnParentWindowScreen = 3
kWindowCascadeOnMainScreen = 4
kWindowCascadeOnParentWindow = 5
kWindowCascadeOnParentWindowScreen = 6
kWindowCascadeStartAtParentWindowScreen = 10
kWindowAlertPositionOnMainScreen = 7
kWindowAlertPositionOnParentWindow = 8
kWindowAlertPositionOnParentWindowScreen = 9
kWindowTitleBarRgn = 0
kWindowTitleTextRgn = 1
kWindowCloseBoxRgn = 2
kWindowZoomBoxRgn = 3
kWindowDragRgn = 5
kWindowGrowRgn = 6
kWindowCollapseBoxRgn = 7
kWindowTitleProxyIconRgn = 8
kWindowStructureRgn = 32
kWindowContentRgn = 33
kWindowUpdateRgn = 34
kWindowOpaqueRgn = 35
kWindowGlobalPortRgn = 40
dialogKind = 2
userKind = 8
kDialogWindowKind = 2
kApplicationWindowKind = 8
inDesk = 0
inNoWindow = 0
inMenuBar = 1
inSysWindow = 2
inContent = 3
inDrag = 4
inGrow = 5
inGoAway = 6
inZoomIn = 7
inZoomOut = 8
inCollapseBox = 11
inProxyIcon = 12
inToolbarButton = 13
inStructure = 15
wNoHit = 0
wInContent = 1
wInDrag = 2
wInGrow = 3
wInGoAway = 4
wInZoomIn = 5
wInZoomOut = 6
wInCollapseBox = 9
wInProxyIcon = 10
wInToolbarButton = 11
wInStructure = 13
kWindowMsgDraw = 0
kWindowMsgHitTest = 1
kWindowMsgCalculateShape = 2
kWindowMsgInitialize = 3
kWindowMsgCleanUp = 4
kWindowMsgDrawGrowOutline = 5
kWindowMsgDrawGrowBox = 6
kWindowMsgGetFeatures = 7
kWindowMsgGetRegion = 8
kWindowMsgDragHilite = 9
kWindowMsgModified = 10
kWindowMsgDrawInCurrentPort = 11
kWindowMsgSetupProxyDragImage = 12
kWindowMsgStateChanged = 13
kWindowMsgMeasureTitle = 14
kWindowMsgGetGrowImageRegion = 19
wDraw = 0
wHit = 1
wCalcRgns = 2
wNew = 3
wDispose = 4
wGrow = 5
wDrawGIcon = 6
kWindowStateTitleChanged = (1 << 0)
kWindowCanGrow = (1 << 0)
kWindowCanZoom = (1 << 1)
kWindowCanCollapse = (1 << 2)
kWindowIsModal = (1 << 3)
kWindowCanGetWindowRegion = (1 << 4)
kWindowIsAlert = (1 << 5)
kWindowHasTitleBar = (1 << 6)
kWindowSupportsDragHilite = (1 << 7)
kWindowSupportsModifiedBit = (1 << 8)
kWindowCanDrawInCurrentPort = (1 << 9)
kWindowCanSetupProxyDragImage = (1 << 10)
kWindowCanMeasureTitle = (1 << 11)
kWindowWantsDisposeAtProcessDeath = (1 << 12)
kWindowSupportsGetGrowImageRegion = (1 << 13)
kWindowDefSupportsColorGrafPort = 0x40000002
kWindowIsOpaque = (1 << 14)
kWindowSupportsSetGrowImageRegion = (1 << 13)
deskPatID = 16
wContentColor = 0
wFrameColor = 1
wTextColor = 2
wHiliteColor = 3
wTitleBarColor = 4
# kMouseUpOutOfSlop = (long)0x80008000
kWindowDefinitionVersionOne = 1
kWindowDefinitionVersionTwo = 2
kWindowIsCollapsedState = (1 << 0L)
kStoredWindowSystemTag = FOUR_CHAR_CODE('appl')
kStoredBasicWindowDescriptionID = FOUR_CHAR_CODE('sbas')
kStoredWindowPascalTitleID = FOUR_CHAR_CODE('s255')
kWindowDefProcPtr = 0
kWindowDefObjectClass = 1
kWindowDefProcID = 2
kWindowModalityNone = 0
kWindowModalitySystemModal = 1
kWindowModalityAppModal = 2
kWindowModalityWindowModal = 3
kWindowGroupAttrSelectAsLayer = 1 << 0
kWindowGroupAttrMoveTogether = 1 << 1
kWindowGroupAttrLayerTogether = 1 << 2
kWindowGroupAttrSharedActivation = 1 << 3
kWindowGroupAttrHideOnCollapse = 1 << 4
kWindowActivationScopeNone = 0
kWindowActivationScopeIndependent = 1
kWindowActivationScopeAll = 2
kNextWindowGroup = true
kPreviousWindowGroup = false
kWindowGroupContentsReturnWindows = 1 << 0
kWindowGroupContentsRecurse = 1 << 1
kWindowGroupContentsVisible = 1 << 2
kWindowPaintProcOptionsNone = 0
kScrollWindowNoOptions = 0
kScrollWindowInvalidate = (1L << 0)
kScrollWindowEraseToPortBackground = (1L << 1)
kWindowMenuIncludeRotate = 1 << 0
kWindowZoomTransitionEffect = 1
kWindowSheetTransitionEffect = 2
kWindowSlideTransitionEffect = 3
kWindowShowTransitionAction = 1
kWindowHideTransitionAction = 2
kWindowMoveTransitionAction = 3
kWindowResizeTransitionAction = 4
kWindowConstrainMayResize = (1L << 0)
kWindowConstrainMoveRegardlessOfFit = (1L << 1)
kWindowConstrainAllowPartial = (1L << 2)
kWindowConstrainCalcOnly = (1L << 3)
kWindowConstrainUseTransitionWindow = (1L << 4)
kWindowConstrainStandardOptions = kWindowConstrainMoveRegardlessOfFit
kWindowLatentVisibleFloater = 1 << 0
kWindowLatentVisibleSuspend = 1 << 1
kWindowLatentVisibleFullScreen = 1 << 2
kWindowLatentVisibleAppHidden = 1 << 3
kWindowLatentVisibleCollapsedOwner = 1 << 4
kWindowLatentVisibleCollapsedGroup = 1 << 5
kWindowPropertyPersistent = 0x00000001
kWindowGroupAttrSelectable = kWindowGroupAttrSelectAsLayer
kWindowGroupAttrPositionFixed = kWindowGroupAttrMoveTogether
kWindowGroupAttrZOrderFixed = kWindowGroupAttrLayerTogether
| Python |
from _Drag import *
| Python |
from _Folder import *
| Python |
from _Sndihooks import *
| Python |
# Generated from 'Movies.h'
def FOUR_CHAR_CODE(x): return x
xmlIdentifierUnrecognized = -1
kControllerMinimum = -0xf777
notImplementedMusicOSErr = -2071
cantSendToSynthesizerOSErr = -2072
cantReceiveFromSynthesizerOSErr = -2073
illegalVoiceAllocationOSErr = -2074
illegalPartOSErr = -2075
illegalChannelOSErr = -2076
illegalKnobOSErr = -2077
illegalKnobValueOSErr = -2078
illegalInstrumentOSErr = -2079
illegalControllerOSErr = -2080
midiManagerAbsentOSErr = -2081
synthesizerNotRespondingOSErr = -2082
synthesizerOSErr = -2083
illegalNoteChannelOSErr = -2084
noteChannelNotAllocatedOSErr = -2085
tunePlayerFullOSErr = -2086
tuneParseOSErr = -2087
MovieFileType = FOUR_CHAR_CODE('MooV')
MovieScrapType = FOUR_CHAR_CODE('moov')
MovieResourceType = FOUR_CHAR_CODE('moov')
MovieForwardPointerResourceType = FOUR_CHAR_CODE('fore')
MovieBackwardPointerResourceType = FOUR_CHAR_CODE('back')
MovieResourceAtomType = FOUR_CHAR_CODE('moov')
MovieDataAtomType = FOUR_CHAR_CODE('mdat')
FreeAtomType = FOUR_CHAR_CODE('free')
SkipAtomType = FOUR_CHAR_CODE('skip')
WideAtomPlaceholderType = FOUR_CHAR_CODE('wide')
MediaHandlerType = FOUR_CHAR_CODE('mhlr')
DataHandlerType = FOUR_CHAR_CODE('dhlr')
VideoMediaType = FOUR_CHAR_CODE('vide')
SoundMediaType = FOUR_CHAR_CODE('soun')
TextMediaType = FOUR_CHAR_CODE('text')
BaseMediaType = FOUR_CHAR_CODE('gnrc')
MPEGMediaType = FOUR_CHAR_CODE('MPEG')
MusicMediaType = FOUR_CHAR_CODE('musi')
TimeCodeMediaType = FOUR_CHAR_CODE('tmcd')
SpriteMediaType = FOUR_CHAR_CODE('sprt')
FlashMediaType = FOUR_CHAR_CODE('flsh')
MovieMediaType = FOUR_CHAR_CODE('moov')
TweenMediaType = FOUR_CHAR_CODE('twen')
ThreeDeeMediaType = FOUR_CHAR_CODE('qd3d')
SkinMediaType = FOUR_CHAR_CODE('skin')
HandleDataHandlerSubType = FOUR_CHAR_CODE('hndl')
PointerDataHandlerSubType = FOUR_CHAR_CODE('ptr ')
NullDataHandlerSubType = FOUR_CHAR_CODE('null')
ResourceDataHandlerSubType = FOUR_CHAR_CODE('rsrc')
URLDataHandlerSubType = FOUR_CHAR_CODE('url ')
WiredActionHandlerType = FOUR_CHAR_CODE('wire')
VisualMediaCharacteristic = FOUR_CHAR_CODE('eyes')
AudioMediaCharacteristic = FOUR_CHAR_CODE('ears')
kCharacteristicCanSendVideo = FOUR_CHAR_CODE('vsnd')
kCharacteristicProvidesActions = FOUR_CHAR_CODE('actn')
kCharacteristicNonLinear = FOUR_CHAR_CODE('nonl')
kCharacteristicCanStep = FOUR_CHAR_CODE('step')
kCharacteristicHasNoDuration = FOUR_CHAR_CODE('noti')
kCharacteristicHasSkinData = FOUR_CHAR_CODE('skin')
kCharacteristicProvidesKeyFocus = FOUR_CHAR_CODE('keyf')
kUserDataMovieControllerType = FOUR_CHAR_CODE('ctyp')
kUserDataName = FOUR_CHAR_CODE('name')
kUserDataTextAlbum = FOUR_CHAR_CODE('\xa9alb')
kUserDataTextArtist = FOUR_CHAR_CODE('\xa9ART')
kUserDataTextAuthor = FOUR_CHAR_CODE('\xa9aut')
kUserDataTextChapter = FOUR_CHAR_CODE('\xa9chp')
kUserDataTextComment = FOUR_CHAR_CODE('\xa9cmt')
kUserDataTextComposer = FOUR_CHAR_CODE('\xa9com')
kUserDataTextCopyright = FOUR_CHAR_CODE('\xa9cpy')
kUserDataTextCreationDate = FOUR_CHAR_CODE('\xa9day')
kUserDataTextDescription = FOUR_CHAR_CODE('\xa9des')
kUserDataTextDirector = FOUR_CHAR_CODE('\xa9dir')
kUserDataTextDisclaimer = FOUR_CHAR_CODE('\xa9dis')
kUserDataTextEncodedBy = FOUR_CHAR_CODE('\xa9enc')
kUserDataTextFullName = FOUR_CHAR_CODE('\xa9nam')
kUserDataTextGenre = FOUR_CHAR_CODE('\xa9gen')
kUserDataTextHostComputer = FOUR_CHAR_CODE('\xa9hst')
kUserDataTextInformation = FOUR_CHAR_CODE('\xa9inf')
kUserDataTextKeywords = FOUR_CHAR_CODE('\xa9key')
kUserDataTextMake = FOUR_CHAR_CODE('\xa9mak')
kUserDataTextModel = FOUR_CHAR_CODE('\xa9mod')
kUserDataTextOriginalArtist = FOUR_CHAR_CODE('\xa9ope')
kUserDataTextOriginalFormat = FOUR_CHAR_CODE('\xa9fmt')
kUserDataTextOriginalSource = FOUR_CHAR_CODE('\xa9src')
kUserDataTextPerformers = FOUR_CHAR_CODE('\xa9prf')
kUserDataTextProducer = FOUR_CHAR_CODE('\xa9prd')
kUserDataTextProduct = FOUR_CHAR_CODE('\xa9PRD')
kUserDataTextSoftware = FOUR_CHAR_CODE('\xa9swr')
kUserDataTextSpecialPlaybackRequirements = FOUR_CHAR_CODE('\xa9req')
kUserDataTextTrack = FOUR_CHAR_CODE('\xa9trk')
kUserDataTextWarning = FOUR_CHAR_CODE('\xa9wrn')
kUserDataTextWriter = FOUR_CHAR_CODE('\xa9wrt')
kUserDataTextURLLink = FOUR_CHAR_CODE('\xa9url')
kUserDataTextEditDate1 = FOUR_CHAR_CODE('\xa9ed1')
kUserDataUnicodeBit = 1L << 7
DoTheRightThing = 0
kQTNetworkStatusNoNetwork = -2
kQTNetworkStatusUncertain = -1
kQTNetworkStatusNotConnected = 0
kQTNetworkStatusConnected = 1
kMusicFlagDontPlay2Soft = 1L << 0
kMusicFlagDontSlaveToMovie = 1L << 1
dfDontDisplay = 1 << 0
dfDontAutoScale = 1 << 1
dfClipToTextBox = 1 << 2
dfUseMovieBGColor = 1 << 3
dfShrinkTextBoxToFit = 1 << 4
dfScrollIn = 1 << 5
dfScrollOut = 1 << 6
dfHorizScroll = 1 << 7
dfReverseScroll = 1 << 8
dfContinuousScroll = 1 << 9
dfFlowHoriz = 1 << 10
dfContinuousKaraoke = 1 << 11
dfDropShadow = 1 << 12
dfAntiAlias = 1 << 13
dfKeyedText = 1 << 14
dfInverseHilite = 1 << 15
dfTextColorHilite = 1 << 16
searchTextDontGoToFoundTime = 1L << 16
searchTextDontHiliteFoundText = 1L << 17
searchTextOneTrackOnly = 1L << 18
searchTextEnabledTracksOnly = 1L << 19
kTextTextHandle = 1
kTextTextPtr = 2
kTextTEStyle = 3
kTextSelection = 4
kTextBackColor = 5
kTextForeColor = 6
kTextFace = 7
kTextFont = 8
kTextSize = 9
kTextAlignment = 10
kTextHilite = 11
kTextDropShadow = 12
kTextDisplayFlags = 13
kTextScroll = 14
kTextRelativeScroll = 15
kTextHyperTextFace = 16
kTextHyperTextColor = 17
kTextKeyEntry = 18
kTextMouseDown = 19
kTextTextBox = 20
kTextEditState = 21
kTextLength = 22
k3DMediaRendererEntry = FOUR_CHAR_CODE('rend')
k3DMediaRendererName = FOUR_CHAR_CODE('name')
k3DMediaRendererCode = FOUR_CHAR_CODE('rcod')
movieProgressOpen = 0
movieProgressUpdatePercent = 1
movieProgressClose = 2
progressOpFlatten = 1
progressOpInsertTrackSegment = 2
progressOpInsertMovieSegment = 3
progressOpPaste = 4
progressOpAddMovieSelection = 5
progressOpCopy = 6
progressOpCut = 7
progressOpLoadMovieIntoRam = 8
progressOpLoadTrackIntoRam = 9
progressOpLoadMediaIntoRam = 10
progressOpImportMovie = 11
progressOpExportMovie = 12
mediaQualityDraft = 0x0000
mediaQualityNormal = 0x0040
mediaQualityBetter = 0x0080
mediaQualityBest = 0x00C0
kQTEventPayloadIsQTList = 1L << 0
kActionMovieSetVolume = 1024
kActionMovieSetRate = 1025
kActionMovieSetLoopingFlags = 1026
kActionMovieGoToTime = 1027
kActionMovieGoToTimeByName = 1028
kActionMovieGoToBeginning = 1029
kActionMovieGoToEnd = 1030
kActionMovieStepForward = 1031
kActionMovieStepBackward = 1032
kActionMovieSetSelection = 1033
kActionMovieSetSelectionByName = 1034
kActionMoviePlaySelection = 1035
kActionMovieSetLanguage = 1036
kActionMovieChanged = 1037
kActionMovieRestartAtTime = 1038
kActionMovieGotoNextChapter = 1039
kActionMovieGotoPreviousChapter = 1040
kActionMovieGotoFirstChapter = 1041
kActionMovieGotoLastChapter = 1042
kActionMovieGotoChapterByIndex = 1043
kActionMovieSetScale = 1044
kActionTrackSetVolume = 2048
kActionTrackSetBalance = 2049
kActionTrackSetEnabled = 2050
kActionTrackSetMatrix = 2051
kActionTrackSetLayer = 2052
kActionTrackSetClip = 2053
kActionTrackSetCursor = 2054
kActionTrackSetGraphicsMode = 2055
kActionTrackSetIdleFrequency = 2056
kActionTrackSetBassTreble = 2057
kActionSpriteSetMatrix = 3072
kActionSpriteSetImageIndex = 3073
kActionSpriteSetVisible = 3074
kActionSpriteSetLayer = 3075
kActionSpriteSetGraphicsMode = 3076
kActionSpritePassMouseToCodec = 3078
kActionSpriteClickOnCodec = 3079
kActionSpriteTranslate = 3080
kActionSpriteScale = 3081
kActionSpriteRotate = 3082
kActionSpriteStretch = 3083
kActionSpriteSetCanBeHitTested = 3094
kActionQTVRSetPanAngle = 4096
kActionQTVRSetTiltAngle = 4097
kActionQTVRSetFieldOfView = 4098
kActionQTVRShowDefaultView = 4099
kActionQTVRGoToNodeID = 4100
kActionQTVREnableHotSpot = 4101
kActionQTVRShowHotSpots = 4102
kActionQTVRTranslateObject = 4103
kActionQTVRSetViewState = 4109
kActionMusicPlayNote = 5120
kActionMusicSetController = 5121
kActionCase = 6144
kActionWhile = 6145
kActionGoToURL = 6146
kActionSendQTEventToSprite = 6147
kActionDebugStr = 6148
kActionPushCurrentTime = 6149
kActionPushCurrentTimeWithLabel = 6150
kActionPopAndGotoTopTime = 6151
kActionPopAndGotoLabeledTime = 6152
kActionStatusString = 6153
kActionSendQTEventToTrackObject = 6154
kActionAddChannelSubscription = 6155
kActionRemoveChannelSubscription = 6156
kActionOpenCustomActionHandler = 6157
kActionDoScript = 6158
kActionDoCompressedActions = 6159
kActionSendAppMessage = 6160
kActionLoadComponent = 6161
kActionSetFocus = 6162
kActionDontPassKeyEvent = 6163
kActionSetRandomSeed = 6164
kActionSpriteTrackSetVariable = 7168
kActionSpriteTrackNewSprite = 7169
kActionSpriteTrackDisposeSprite = 7170
kActionSpriteTrackSetVariableToString = 7171
kActionSpriteTrackConcatVariables = 7172
kActionSpriteTrackSetVariableToMovieURL = 7173
kActionSpriteTrackSetVariableToMovieBaseURL = 7174
kActionSpriteTrackSetAllSpritesHitTestingMode = 7181
kActionSpriteTrackNewImage = 7182
kActionSpriteTrackDisposeImage = 7183
kActionApplicationNumberAndString = 8192
kActionQD3DNamedObjectTranslateTo = 9216
kActionQD3DNamedObjectScaleTo = 9217
kActionQD3DNamedObjectRotateTo = 9218
kActionFlashTrackSetPan = 10240
kActionFlashTrackSetZoom = 10241
kActionFlashTrackSetZoomRect = 10242
kActionFlashTrackGotoFrameNumber = 10243
kActionFlashTrackGotoFrameLabel = 10244
kActionFlashTrackSetFlashVariable = 10245
kActionFlashTrackDoButtonActions = 10246
kActionMovieTrackAddChildMovie = 11264
kActionMovieTrackLoadChildMovie = 11265
kActionMovieTrackLoadChildMovieWithQTListParams = 11266
kActionTextTrackPasteText = 12288
kActionTextTrackSetTextBox = 12291
kActionTextTrackSetTextStyle = 12292
kActionTextTrackSetSelection = 12293
kActionTextTrackSetBackgroundColor = 12294
kActionTextTrackSetForegroundColor = 12295
kActionTextTrackSetFace = 12296
kActionTextTrackSetFont = 12297
kActionTextTrackSetSize = 12298
kActionTextTrackSetAlignment = 12299
kActionTextTrackSetHilite = 12300
kActionTextTrackSetDropShadow = 12301
kActionTextTrackSetDisplayFlags = 12302
kActionTextTrackSetScroll = 12303
kActionTextTrackRelativeScroll = 12304
kActionTextTrackFindText = 12305
kActionTextTrackSetHyperTextFace = 12306
kActionTextTrackSetHyperTextColor = 12307
kActionTextTrackKeyEntry = 12308
kActionTextTrackMouseDown = 12309
kActionTextTrackSetEditable = 12310
kActionListAddElement = 13312
kActionListRemoveElements = 13313
kActionListSetElementValue = 13314
kActionListPasteFromXML = 13315
kActionListSetMatchingFromXML = 13316
kActionListSetFromURL = 13317
kActionListExchangeLists = 13318
kActionListServerQuery = 13319
kOperandExpression = 1
kOperandConstant = 2
kOperandSubscribedToChannel = 3
kOperandUniqueCustomActionHandlerID = 4
kOperandCustomActionHandlerIDIsOpen = 5
kOperandConnectionSpeed = 6
kOperandGMTDay = 7
kOperandGMTMonth = 8
kOperandGMTYear = 9
kOperandGMTHours = 10
kOperandGMTMinutes = 11
kOperandGMTSeconds = 12
kOperandLocalDay = 13
kOperandLocalMonth = 14
kOperandLocalYear = 15
kOperandLocalHours = 16
kOperandLocalMinutes = 17
kOperandLocalSeconds = 18
kOperandRegisteredForQuickTimePro = 19
kOperandPlatformRunningOn = 20
kOperandQuickTimeVersion = 21
kOperandComponentVersion = 22
kOperandOriginalHandlerRefcon = 23
kOperandTicks = 24
kOperandMaxLoadedTimeInMovie = 25
kOperandEventParameter = 26
kOperandFreeMemory = 27
kOperandNetworkStatus = 28
kOperandQuickTimeVersionRegistered = 29
kOperandSystemVersion = 30
kOperandMovieVolume = 1024
kOperandMovieRate = 1025
kOperandMovieIsLooping = 1026
kOperandMovieLoopIsPalindrome = 1027
kOperandMovieTime = 1028
kOperandMovieDuration = 1029
kOperandMovieTimeScale = 1030
kOperandMovieWidth = 1031
kOperandMovieHeight = 1032
kOperandMovieLoadState = 1033
kOperandMovieTrackCount = 1034
kOperandMovieIsActive = 1035
kOperandMovieName = 1036
kOperandMovieID = 1037
kOperandMovieChapterCount = 1038
kOperandMovieChapterIndex = 1039
kOperandMovieChapterName = 1040
kOperandMovieChapterNameByIndex = 1041
kOperandMovieChapterIndexByName = 1042
kOperandMovieAnnotation = 1043
kOperandMovieConnectionFlags = 1044
kOperandMovieConnectionString = 1045
kOperandTrackVolume = 2048
kOperandTrackBalance = 2049
kOperandTrackEnabled = 2050
kOperandTrackLayer = 2051
kOperandTrackWidth = 2052
kOperandTrackHeight = 2053
kOperandTrackDuration = 2054
kOperandTrackName = 2055
kOperandTrackID = 2056
kOperandTrackIdleFrequency = 2057
kOperandTrackBass = 2058
kOperandTrackTreble = 2059
kOperandSpriteBoundsLeft = 3072
kOperandSpriteBoundsTop = 3073
kOperandSpriteBoundsRight = 3074
kOperandSpriteBoundsBottom = 3075
kOperandSpriteImageIndex = 3076
kOperandSpriteVisible = 3077
kOperandSpriteLayer = 3078
kOperandSpriteTrackVariable = 3079
kOperandSpriteTrackNumSprites = 3080
kOperandSpriteTrackNumImages = 3081
kOperandSpriteID = 3082
kOperandSpriteIndex = 3083
kOperandSpriteFirstCornerX = 3084
kOperandSpriteFirstCornerY = 3085
kOperandSpriteSecondCornerX = 3086
kOperandSpriteSecondCornerY = 3087
kOperandSpriteThirdCornerX = 3088
kOperandSpriteThirdCornerY = 3089
kOperandSpriteFourthCornerX = 3090
kOperandSpriteFourthCornerY = 3091
kOperandSpriteImageRegistrationPointX = 3092
kOperandSpriteImageRegistrationPointY = 3093
kOperandSpriteTrackSpriteIDAtPoint = 3094
kOperandSpriteName = 3095
kOperandSpriteCanBeHitTested = 3105
kOperandSpriteTrackAllSpritesHitTestingMode = 3106
kOperandSpriteTrackImageIDByIndex = 3107
kOperandSpriteTrackImageIndexByID = 3108
kOperandQTVRPanAngle = 4096
kOperandQTVRTiltAngle = 4097
kOperandQTVRFieldOfView = 4098
kOperandQTVRNodeID = 4099
kOperandQTVRHotSpotsVisible = 4100
kOperandQTVRViewCenterH = 4101
kOperandQTVRViewCenterV = 4102
kOperandQTVRViewStateCount = 4103
kOperandQTVRViewState = 4104
kOperandMouseLocalHLoc = 5120
kOperandMouseLocalVLoc = 5121
kOperandKeyIsDown = 5122
kOperandRandom = 5123
kOperandCanHaveFocus = 5124
kOperandHasFocus = 5125
kOperandTextTrackEditable = 6144
kOperandTextTrackCopyText = 6145
kOperandTextTrackStartSelection = 6146
kOperandTextTrackEndSelection = 6147
kOperandTextTrackTextBoxLeft = 6148
kOperandTextTrackTextBoxTop = 6149
kOperandTextTrackTextBoxRight = 6150
kOperandTextTrackTextBoxBottom = 6151
kOperandTextTrackTextLength = 6152
kOperandListCountElements = 7168
kOperandListGetElementPathByIndex = 7169
kOperandListGetElementValue = 7170
kOperandListCopyToXML = 7171
kOperandSin = 8192
kOperandCos = 8193
kOperandTan = 8194
kOperandATan = 8195
kOperandATan2 = 8196
kOperandDegreesToRadians = 8197
kOperandRadiansToDegrees = 8198
kOperandSquareRoot = 8199
kOperandExponent = 8200
kOperandLog = 8201
kOperandFlashTrackVariable = 9216
kOperandStringLength = 10240
kOperandStringCompare = 10241
kOperandStringSubString = 10242
kOperandStringConcat = 10243
kFirstMovieAction = kActionMovieSetVolume
kLastMovieAction = kActionMovieSetScale
kFirstTrackAction = kActionTrackSetVolume
kLastTrackAction = kActionTrackSetBassTreble
kFirstSpriteAction = kActionSpriteSetMatrix
kLastSpriteAction = kActionSpriteSetCanBeHitTested
kFirstQTVRAction = kActionQTVRSetPanAngle
kLastQTVRAction = kActionQTVRSetViewState
kFirstMusicAction = kActionMusicPlayNote
kLastMusicAction = kActionMusicSetController
kFirstSystemAction = kActionCase
kLastSystemAction = kActionSetRandomSeed
kFirstSpriteTrackAction = kActionSpriteTrackSetVariable
kLastSpriteTrackAction = kActionSpriteTrackDisposeImage
kFirstApplicationAction = kActionApplicationNumberAndString
kLastApplicationAction = kActionApplicationNumberAndString
kFirstQD3DNamedObjectAction = kActionQD3DNamedObjectTranslateTo
kLastQD3DNamedObjectAction = kActionQD3DNamedObjectRotateTo
kFirstFlashTrackAction = kActionFlashTrackSetPan
kLastFlashTrackAction = kActionFlashTrackDoButtonActions
kFirstMovieTrackAction = kActionMovieTrackAddChildMovie
kLastMovieTrackAction = kActionMovieTrackLoadChildMovieWithQTListParams
kFirstTextTrackAction = kActionTextTrackPasteText
kLastTextTrackAction = kActionTextTrackSetEditable
kFirstMultiTargetAction = kActionListAddElement
kLastMultiTargetAction = kActionListServerQuery
kFirstAction = kFirstMovieAction
kLastAction = kLastMultiTargetAction
kTargetMovie = FOUR_CHAR_CODE('moov')
kTargetMovieName = FOUR_CHAR_CODE('mona')
kTargetMovieID = FOUR_CHAR_CODE('moid')
kTargetRootMovie = FOUR_CHAR_CODE('moro')
kTargetParentMovie = FOUR_CHAR_CODE('mopa')
kTargetChildMovieTrackName = FOUR_CHAR_CODE('motn')
kTargetChildMovieTrackID = FOUR_CHAR_CODE('moti')
kTargetChildMovieTrackIndex = FOUR_CHAR_CODE('motx')
kTargetChildMovieMovieName = FOUR_CHAR_CODE('momn')
kTargetChildMovieMovieID = FOUR_CHAR_CODE('momi')
kTargetTrackName = FOUR_CHAR_CODE('trna')
kTargetTrackID = FOUR_CHAR_CODE('trid')
kTargetTrackType = FOUR_CHAR_CODE('trty')
kTargetTrackIndex = FOUR_CHAR_CODE('trin')
kTargetSpriteName = FOUR_CHAR_CODE('spna')
kTargetSpriteID = FOUR_CHAR_CODE('spid')
kTargetSpriteIndex = FOUR_CHAR_CODE('spin')
kTargetQD3DNamedObjectName = FOUR_CHAR_CODE('nana')
kTargetCurrentQTEventParams = FOUR_CHAR_CODE('evpa')
kQTEventType = FOUR_CHAR_CODE('evnt')
kAction = FOUR_CHAR_CODE('actn')
kWhichAction = FOUR_CHAR_CODE('whic')
kActionParameter = FOUR_CHAR_CODE('parm')
kActionTarget = FOUR_CHAR_CODE('targ')
kActionFlags = FOUR_CHAR_CODE('flag')
kActionParameterMinValue = FOUR_CHAR_CODE('minv')
kActionParameterMaxValue = FOUR_CHAR_CODE('maxv')
kActionListAtomType = FOUR_CHAR_CODE('list')
kExpressionContainerAtomType = FOUR_CHAR_CODE('expr')
kConditionalAtomType = FOUR_CHAR_CODE('test')
kOperatorAtomType = FOUR_CHAR_CODE('oper')
kOperandAtomType = FOUR_CHAR_CODE('oprn')
kCommentAtomType = FOUR_CHAR_CODE('why ')
kCustomActionHandler = FOUR_CHAR_CODE('cust')
kCustomHandlerID = FOUR_CHAR_CODE('id ')
kCustomHandlerDesc = FOUR_CHAR_CODE('desc')
kQTEventRecordAtomType = FOUR_CHAR_CODE('erec')
kQTEventMouseClick = FOUR_CHAR_CODE('clik')
kQTEventMouseClickEnd = FOUR_CHAR_CODE('cend')
kQTEventMouseClickEndTriggerButton = FOUR_CHAR_CODE('trig')
kQTEventMouseEnter = FOUR_CHAR_CODE('entr')
kQTEventMouseExit = FOUR_CHAR_CODE('exit')
kQTEventMouseMoved = FOUR_CHAR_CODE('move')
kQTEventFrameLoaded = FOUR_CHAR_CODE('fram')
kQTEventIdle = FOUR_CHAR_CODE('idle')
kQTEventKey = FOUR_CHAR_CODE('key ')
kQTEventMovieLoaded = FOUR_CHAR_CODE('load')
kQTEventRequestToModifyMovie = FOUR_CHAR_CODE('reqm')
kQTEventListReceived = FOUR_CHAR_CODE('list')
kQTEventKeyUp = FOUR_CHAR_CODE('keyU')
kActionFlagActionIsDelta = 1L << 1
kActionFlagParameterWrapsAround = 1L << 2
kActionFlagActionIsToggle = 1L << 3
kStatusStringIsURLLink = 1L << 1
kStatusStringIsStreamingStatus = 1L << 2
kStatusHasCodeNumber = 1L << 3
kStatusIsError = 1L << 4
kScriptIsUnknownType = 1L << 0
kScriptIsJavaScript = 1L << 1
kScriptIsLingoEvent = 1L << 2
kScriptIsVBEvent = 1L << 3
kScriptIsProjectorCommand = 1L << 4
kScriptIsAppleScript = 1L << 5
kQTRegistrationDialogTimeOutFlag = 1 << 0
kQTRegistrationDialogShowDialog = 1 << 1
kQTRegistrationDialogForceDialog = 1 << 2
kOperatorAdd = FOUR_CHAR_CODE('add ')
kOperatorSubtract = FOUR_CHAR_CODE('sub ')
kOperatorMultiply = FOUR_CHAR_CODE('mult')
kOperatorDivide = FOUR_CHAR_CODE('div ')
kOperatorOr = FOUR_CHAR_CODE('or ')
kOperatorAnd = FOUR_CHAR_CODE('and ')
kOperatorNot = FOUR_CHAR_CODE('not ')
kOperatorLessThan = FOUR_CHAR_CODE('< ')
kOperatorLessThanEqualTo = FOUR_CHAR_CODE('<= ')
kOperatorEqualTo = FOUR_CHAR_CODE('= ')
kOperatorNotEqualTo = FOUR_CHAR_CODE('!= ')
kOperatorGreaterThan = FOUR_CHAR_CODE('> ')
kOperatorGreaterThanEqualTo = FOUR_CHAR_CODE('>= ')
kOperatorModulo = FOUR_CHAR_CODE('mod ')
kOperatorIntegerDivide = FOUR_CHAR_CODE('idiv')
kOperatorAbsoluteValue = FOUR_CHAR_CODE('abs ')
kOperatorNegate = FOUR_CHAR_CODE('neg ')
kPlatformMacintosh = 1
kPlatformWindows = 2
kSystemIsWindows9x = 0x00010000
kSystemIsWindowsNT = 0x00020000
kMediaPropertyNonLinearAtomType = FOUR_CHAR_CODE('nonl')
kMediaPropertyHasActions = 105
loopTimeBase = 1
palindromeLoopTimeBase = 2
maintainTimeBaseZero = 4
triggerTimeFwd = 0x0001
triggerTimeBwd = 0x0002
triggerTimeEither = 0x0003
triggerRateLT = 0x0004
triggerRateGT = 0x0008
triggerRateEqual = 0x0010
triggerRateLTE = triggerRateLT | triggerRateEqual
triggerRateGTE = triggerRateGT | triggerRateEqual
triggerRateNotEqual = triggerRateGT | triggerRateEqual | triggerRateLT
triggerRateChange = 0
triggerAtStart = 0x0001
triggerAtStop = 0x0002
timeBaseBeforeStartTime = 1
timeBaseAfterStopTime = 2
callBackAtTime = 1
callBackAtRate = 2
callBackAtTimeJump = 3
callBackAtExtremes = 4
callBackAtTimeBaseDisposed = 5
callBackAtInterrupt = 0x8000
callBackAtDeferredTask = 0x4000
qtcbNeedsRateChanges = 1
qtcbNeedsTimeChanges = 2
qtcbNeedsStartStopChanges = 4
keepInRam = 1 << 0
unkeepInRam = 1 << 1
flushFromRam = 1 << 2
loadForwardTrackEdits = 1 << 3
loadBackwardTrackEdits = 1 << 4
newMovieActive = 1 << 0
newMovieDontResolveDataRefs = 1 << 1
newMovieDontAskUnresolvedDataRefs = 1 << 2
newMovieDontAutoAlternates = 1 << 3
newMovieDontUpdateForeBackPointers = 1 << 4
newMovieDontAutoUpdateClock = 1 << 5
newMovieAsyncOK = 1 << 8
newMovieIdleImportOK = 1 << 10
newMovieDontInteractWithUser = 1 << 11
trackUsageInMovie = 1 << 1
trackUsageInPreview = 1 << 2
trackUsageInPoster = 1 << 3
mediaSampleNotSync = 1 << 0
mediaSampleShadowSync = 1 << 1
pasteInParallel = 1 << 0
showUserSettingsDialog = 1 << 1
movieToFileOnlyExport = 1 << 2
movieFileSpecValid = 1 << 3
nextTimeMediaSample = 1 << 0
nextTimeMediaEdit = 1 << 1
nextTimeTrackEdit = 1 << 2
nextTimeSyncSample = 1 << 3
nextTimeStep = 1 << 4
nextTimeEdgeOK = 1 << 14
nextTimeIgnoreActiveSegment = 1 << 15
createMovieFileDeleteCurFile = 1L << 31
createMovieFileDontCreateMovie = 1L << 30
createMovieFileDontOpenFile = 1L << 29
createMovieFileDontCreateResFile = 1L << 28
flattenAddMovieToDataFork = 1L << 0
flattenActiveTracksOnly = 1L << 2
flattenDontInterleaveFlatten = 1L << 3
flattenFSSpecPtrIsDataRefRecordPtr = 1L << 4
flattenCompressMovieResource = 1L << 5
flattenForceMovieResourceBeforeMovieData = 1L << 6
movieInDataForkResID = -1
mcTopLeftMovie = 1 << 0
mcScaleMovieToFit = 1 << 1
mcWithBadge = 1 << 2
mcNotVisible = 1 << 3
mcWithFrame = 1 << 4
movieScrapDontZeroScrap = 1 << 0
movieScrapOnlyPutMovie = 1 << 1
dataRefSelfReference = 1 << 0
dataRefWasNotResolved = 1 << 1
kMovieAnchorDataRefIsDefault = 1 << 0
hintsScrubMode = 1 << 0
hintsLoop = 1 << 1
hintsDontPurge = 1 << 2
hintsUseScreenBuffer = 1 << 5
hintsAllowInterlace = 1 << 6
hintsUseSoundInterp = 1 << 7
hintsHighQuality = 1 << 8
hintsPalindrome = 1 << 9
hintsInactive = 1 << 11
hintsOffscreen = 1 << 12
hintsDontDraw = 1 << 13
hintsAllowBlacklining = 1 << 14
hintsDontUseVideoOverlaySurface = 1 << 16
hintsIgnoreBandwidthRestrictions = 1 << 17
hintsPlayingEveryFrame = 1 << 18
hintsAllowDynamicResize = 1 << 19
hintsSingleField = 1 << 20
hintsNoRenderingTimeOut = 1 << 21
hintsFlushVideoInsteadOfDirtying = 1 << 22
hintsEnableSubPixelPositioning = 1L << 23
mediaHandlerFlagBaseClient = 1
movieTrackMediaType = 1 << 0
movieTrackCharacteristic = 1 << 1
movieTrackEnabledOnly = 1 << 2
kMovieControlOptionHideController = (1L << 0)
kMovieControlOptionLocateTopLeft = (1L << 1)
kMovieControlOptionEnableEditing = (1L << 2)
kMovieControlOptionHandleEditingHI = (1L << 3)
kMovieControlOptionSetKeysEnabled = (1L << 4)
kMovieControlOptionManuallyIdled = (1L << 5)
kMovieControlDataMovieController = FOUR_CHAR_CODE('mc ')
kMovieControlDataMovie = FOUR_CHAR_CODE('moov')
kMovieControlDataManualIdling = FOUR_CHAR_CODE('manu')
movieDrawingCallWhenChanged = 0
movieDrawingCallAlways = 1
kQTCloneShareSamples = 1 << 0
kQTCloneDontCopyEdits = 1 << 1
kGetMovieImporterValidateToFind = 1L << 0
kGetMovieImporterAllowNewFile = 1L << 1
kGetMovieImporterDontConsiderGraphicsImporters = 1L << 2
kGetMovieImporterDontConsiderFileOnlyImporters = 1L << 6
kGetMovieImporterAutoImportOnly = 1L << 10
kQTGetMIMETypeInfoIsQuickTimeMovieType = FOUR_CHAR_CODE('moov')
kQTGetMIMETypeInfoIsUnhelpfulType = FOUR_CHAR_CODE('dumb')
kQTCopyUserDataReplace = FOUR_CHAR_CODE('rplc')
kQTCopyUserDataMerge = FOUR_CHAR_CODE('merg')
kMovieLoadStateError = -1L
kMovieLoadStateLoading = 1000
kMovieLoadStateLoaded = 2000
kMovieLoadStatePlayable = 10000
kMovieLoadStatePlaythroughOK = 20000
kMovieLoadStateComplete = 100000L
kQTDontUseDataToFindImporter = 1L << 0
kQTDontLookForMovieImporterIfGraphicsImporterFound = 1L << 1
kQTAllowOpeningStillImagesAsMovies = 1L << 2
kQTAllowImportersThatWouldCreateNewFile = 1L << 3
kQTAllowAggressiveImporters = 1L << 4
preloadAlways = 1L << 0
preloadOnlyIfEnabled = 1L << 1
fullScreenHideCursor = 1L << 0
fullScreenAllowEvents = 1L << 1
fullScreenDontChangeMenuBar = 1L << 2
fullScreenPreflightSize = 1L << 3
movieExecuteWiredActionDontExecute = 1L << 0
kRefConNavigationNext = 0
kRefConNavigationPrevious = 1
kRefConPropertyCanHaveFocus = 1
kRefConPropertyHasFocus = 2
kTrackFocusCanEditFlag = FOUR_CHAR_CODE('kedt')
kTrackDefaultFocusFlags = FOUR_CHAR_CODE('kfoc')
kTrackFocusDefaultRefcon = FOUR_CHAR_CODE('kref')
kTrackFocusOn = 1
kTrackHandlesTabs = 2
kFlashTrackPropertyAcceptAllClicks = FOUR_CHAR_CODE('clik')
kBackgroundSpriteLayerNum = 32767
kSpritePropertyMatrix = 1
kSpritePropertyImageDescription = 2
kSpritePropertyImageDataPtr = 3
kSpritePropertyVisible = 4
kSpritePropertyLayer = 5
kSpritePropertyGraphicsMode = 6
kSpritePropertyImageDataSize = 7
kSpritePropertyActionHandlingSpriteID = 8
kSpritePropertyCanBeHitTested = 9
kSpritePropertyImageIndex = 100
kSpriteTrackPropertyBackgroundColor = 101
kSpriteTrackPropertyOffscreenBitDepth = 102
kSpriteTrackPropertySampleFormat = 103
kSpriteTrackPropertyScaleSpritesToScaleWorld = 104
kSpriteTrackPropertyHasActions = 105
kSpriteTrackPropertyVisible = 106
kSpriteTrackPropertyQTIdleEventsFrequency = 107
kSpriteTrackPropertyAllSpritesHitTestingMode = 108
kSpriteTrackPropertyPreferredDepthInterpretationMode = 109
kSpriteImagePropertyRegistrationPoint = 1000
kSpriteImagePropertyGroupID = 1001
kSpriteTrackPreferredDepthCompatibilityMode = 0
kSpriteTrackPreferredDepthModernMode = 1
kSpriteHitTestUseSpritesOwnPropertiesMode = 0
kSpriteHitTestTreatAllSpritesAsHitTestableMode = 1
kSpriteHitTestTreatAllSpritesAsNotHitTestableMode = 2
kNoQTIdleEvents = -1
kGetSpriteWorldInvalidRegionAndLeaveIntact = -1L
kGetSpriteWorldInvalidRegionAndThenSetEmpty = -2L
kOnlyDrawToSpriteWorld = 1L << 0
kSpriteWorldPreflight = 1L << 1
kSpriteWorldDidDraw = 1L << 0
kSpriteWorldNeedsToDraw = 1L << 1
kKeyFrameAndSingleOverride = 1L << 1
kKeyFrameAndAllOverrides = 1L << 2
kScaleSpritesToScaleWorld = 1L << 1
kSpriteWorldHighQuality = 1L << 2
kSpriteWorldDontAutoInvalidate = 1L << 3
kSpriteWorldInvisible = 1L << 4
kSpriteWorldDirtyInsteadOfFlush = 1L << 5
kParentAtomIsContainer = 0
kTweenRecordNoFlags = 0
kTweenRecordIsAtInterruptTime = 0x00000001
kEffectNameAtom = FOUR_CHAR_CODE('name')
kEffectTypeAtom = FOUR_CHAR_CODE('type')
kEffectManufacturerAtom = FOUR_CHAR_CODE('manu')
pdActionConfirmDialog = 1
pdActionSetAppleMenu = 2
pdActionSetEditMenu = 3
pdActionGetDialogValues = 4
pdActionSetPreviewUserItem = 5
pdActionSetPreviewPicture = 6
pdActionSetColorPickerEventProc = 7
pdActionSetDialogTitle = 8
pdActionGetSubPanelMenu = 9
pdActionActivateSubPanel = 10
pdActionConductStopAlert = 11
pdActionModelessCallback = 12
pdActionFetchPreview = 13
pdActionSetDialogSettings = 14
pdActionGetDialogSettings = 15
pdActionGetNextSample = 16
pdActionGetPreviousSample = 17
pdActionCompactSample = 18
pdActionSetEditCallout = 19
pdActionSetSampleTime = 20
pdActionDoEditCommand = 21
pdActionGetSubPanelMenuValue = 22
pdActionCustomNewControl = 23
pdActionCustomDisposeControl = 24
pdActionCustomPositionControl = 25
pdActionCustomShowHideControl = 26
pdActionCustomHandleEvent = 27
pdActionCustomSetFocus = 28
pdActionCustomSetEditMenu = 29
pdActionCustomSetPreviewPicture = 30
pdActionCustomSetEditCallout = 31
pdActionCustomGetEnableValue = 32
pdActionCustomSetSampleTime = 33
pdActionCustomGetValue = 34
pdActionCustomDoEditCommand = 35
pdSampleTimeDisplayOptionsNone = 0x00000000
pdActionFocusOff = 0
pdActionFocusFirst = 1
pdActionFocusLast = 2
pdActionFocusForward = 3
pdActionFocusBackward = 4
elOptionsIncludeNoneInList = 0x00000001
pdOptionsCollectOneValue = 0x00000001
pdOptionsAllowOptionalInterpolations = 0x00000002
pdOptionsModalDialogBox = 0x00000004
pdOptionsEditCurrentEffectOnly = 0x00000008
pdOptionsHidePreview = 0x00000010
effectIsRealtime = 0
kAccessKeyAtomType = FOUR_CHAR_CODE('acky')
kAccessKeySystemFlag = 1L << 0
ConnectionSpeedPrefsType = FOUR_CHAR_CODE('cspd')
BandwidthManagementPrefsType = FOUR_CHAR_CODE('bwmg')
kQTIdlePriority = 10
kQTNonRealTimePriority = 20
kQTRealTimeSharedPriority = 25
kQTRealTimePriority = 30
kQTBandwidthNotifyNeedToStop = 1L << 0
kQTBandwidthNotifyGoodToGo = 1L << 1
kQTBandwidthChangeRequest = 1L << 2
kQTBandwidthQueueRequest = 1L << 3
kQTBandwidthScheduledRequest = 1L << 4
kQTBandwidthVoluntaryRelease = 1L << 5
kITextRemoveEverythingBut = 0 << 1
kITextRemoveLeaveSuggestedAlternate = 1 << 1
kITextAtomType = FOUR_CHAR_CODE('itxt')
kITextStringAtomType = FOUR_CHAR_CODE('text')
kQTParseTextHREFText = FOUR_CHAR_CODE('text')
kQTParseTextHREFBaseURL = FOUR_CHAR_CODE('burl')
kQTParseTextHREFClickPoint = FOUR_CHAR_CODE('clik')
kQTParseTextHREFUseAltDelim = FOUR_CHAR_CODE('altd')
kQTParseTextHREFDelimiter = FOUR_CHAR_CODE('delm')
kQTParseTextHREFRecomposeHREF = FOUR_CHAR_CODE('rhrf')
kQTParseTextHREFURL = FOUR_CHAR_CODE('url ')
kQTParseTextHREFTarget = FOUR_CHAR_CODE('targ')
kQTParseTextHREFChapter = FOUR_CHAR_CODE('chap')
kQTParseTextHREFIsAutoHREF = FOUR_CHAR_CODE('auto')
kQTParseTextHREFIsServerMap = FOUR_CHAR_CODE('smap')
kQTParseTextHREFHREF = FOUR_CHAR_CODE('href')
kQTParseTextHREFEMBEDArgs = FOUR_CHAR_CODE('mbed')
kTrackReferenceChapterList = FOUR_CHAR_CODE('chap')
kTrackReferenceTimeCode = FOUR_CHAR_CODE('tmcd')
kTrackReferenceModifier = FOUR_CHAR_CODE('ssrc')
kTrackModifierInput = 0x696E
kTrackModifierType = 0x7479
kTrackModifierReference = FOUR_CHAR_CODE('ssrc')
kTrackModifierObjectID = FOUR_CHAR_CODE('obid')
kTrackModifierInputName = FOUR_CHAR_CODE('name')
kInputMapSubInputID = FOUR_CHAR_CODE('subi')
kTrackModifierTypeMatrix = 1
kTrackModifierTypeClip = 2
kTrackModifierTypeGraphicsMode = 5
kTrackModifierTypeVolume = 3
kTrackModifierTypeBalance = 4
kTrackModifierTypeImage = FOUR_CHAR_CODE('vide')
kTrackModifierObjectMatrix = 6
kTrackModifierObjectGraphicsMode = 7
kTrackModifierType3d4x4Matrix = 8
kTrackModifierCameraData = 9
kTrackModifierSoundLocalizationData = 10
kTrackModifierObjectImageIndex = 11
kTrackModifierObjectLayer = 12
kTrackModifierObjectVisible = 13
kTrackModifierAngleAspectCamera = 14
kTrackModifierPanAngle = FOUR_CHAR_CODE('pan ')
kTrackModifierTiltAngle = FOUR_CHAR_CODE('tilt')
kTrackModifierVerticalFieldOfViewAngle = FOUR_CHAR_CODE('fov ')
kTrackModifierObjectQTEventSend = FOUR_CHAR_CODE('evnt')
kTrackModifierObjectCanBeHitTested = 15
kTweenTypeShort = 1
kTweenTypeLong = 2
kTweenTypeFixed = 3
kTweenTypePoint = 4
kTweenTypeQDRect = 5
kTweenTypeQDRegion = 6
kTweenTypeMatrix = 7
kTweenTypeRGBColor = 8
kTweenTypeGraphicsModeWithRGBColor = 9
kTweenTypeQTFloatSingle = 10
kTweenTypeQTFloatDouble = 11
kTweenTypeFixedPoint = 12
kTweenType3dScale = FOUR_CHAR_CODE('3sca')
kTweenType3dTranslate = FOUR_CHAR_CODE('3tra')
kTweenType3dRotate = FOUR_CHAR_CODE('3rot')
kTweenType3dRotateAboutPoint = FOUR_CHAR_CODE('3rap')
kTweenType3dRotateAboutAxis = FOUR_CHAR_CODE('3rax')
kTweenType3dRotateAboutVector = FOUR_CHAR_CODE('3rvc')
kTweenType3dQuaternion = FOUR_CHAR_CODE('3qua')
kTweenType3dMatrix = FOUR_CHAR_CODE('3mat')
kTweenType3dCameraData = FOUR_CHAR_CODE('3cam')
kTweenType3dAngleAspectCameraData = FOUR_CHAR_CODE('3caa')
kTweenType3dSoundLocalizationData = FOUR_CHAR_CODE('3slc')
kTweenTypePathToMatrixTranslation = FOUR_CHAR_CODE('gxmt')
kTweenTypePathToMatrixRotation = FOUR_CHAR_CODE('gxpr')
kTweenTypePathToMatrixTranslationAndRotation = FOUR_CHAR_CODE('gxmr')
kTweenTypePathToFixedPoint = FOUR_CHAR_CODE('gxfp')
kTweenTypePathXtoY = FOUR_CHAR_CODE('gxxy')
kTweenTypePathYtoX = FOUR_CHAR_CODE('gxyx')
kTweenTypeAtomList = FOUR_CHAR_CODE('atom')
kTweenTypePolygon = FOUR_CHAR_CODE('poly')
kTweenTypeMultiMatrix = FOUR_CHAR_CODE('mulm')
kTweenTypeSpin = FOUR_CHAR_CODE('spin')
kTweenType3dMatrixNonLinear = FOUR_CHAR_CODE('3nlr')
kTweenType3dVRObject = FOUR_CHAR_CODE('3vro')
kTweenEntry = FOUR_CHAR_CODE('twen')
kTweenData = FOUR_CHAR_CODE('data')
kTweenType = FOUR_CHAR_CODE('twnt')
kTweenStartOffset = FOUR_CHAR_CODE('twst')
kTweenDuration = FOUR_CHAR_CODE('twdu')
kTweenFlags = FOUR_CHAR_CODE('flag')
kTweenOutputMin = FOUR_CHAR_CODE('omin')
kTweenOutputMax = FOUR_CHAR_CODE('omax')
kTweenSequenceElement = FOUR_CHAR_CODE('seqe')
kTween3dInitialCondition = FOUR_CHAR_CODE('icnd')
kTweenInterpolationID = FOUR_CHAR_CODE('intr')
kTweenRegionData = FOUR_CHAR_CODE('qdrg')
kTweenPictureData = FOUR_CHAR_CODE('PICT')
kListElementType = FOUR_CHAR_CODE('type')
kListElementDataType = FOUR_CHAR_CODE('daty')
kNameAtom = FOUR_CHAR_CODE('name')
kInitialRotationAtom = FOUR_CHAR_CODE('inro')
kNonLinearTweenHeader = FOUR_CHAR_CODE('nlth')
kTweenReturnDelta = 1L << 0
kQTRestrictionClassSave = FOUR_CHAR_CODE('save')
kQTRestrictionSaveDontAddMovieResource = (1L << 0)
kQTRestrictionSaveDontFlatten = (1L << 1)
kQTRestrictionSaveDontExport = (1L << 2)
kQTRestrictionSaveDontExtract = (1L << 3)
kQTRestrictionClassEdit = FOUR_CHAR_CODE('edit')
kQTRestrictionEditDontCopy = (1L << 0)
kQTRestrictionEditDontCut = (1L << 1)
kQTRestrictionEditDontPaste = (1L << 2)
kQTRestrictionEditDontClear = (1L << 3)
kQTRestrictionEditDontModify = (1L << 4)
kQTRestrictionEditDontExtract = (1L << 5)
videoFlagDontLeanAhead = 1L << 0
txtProcDefaultDisplay = 0
txtProcDontDisplay = 1
txtProcDoDisplay = 2
findTextEdgeOK = 1 << 0
findTextCaseSensitive = 1 << 1
findTextReverseSearch = 1 << 2
findTextWrapAround = 1 << 3
findTextUseOffset = 1 << 4
dropShadowOffsetType = FOUR_CHAR_CODE('drpo')
dropShadowTranslucencyType = FOUR_CHAR_CODE('drpt')
spriteHitTestBounds = 1L << 0
spriteHitTestImage = 1L << 1
spriteHitTestInvisibleSprites = 1L << 2
spriteHitTestIsClick = 1L << 3
spriteHitTestLocInDisplayCoordinates = 1L << 4
spriteHitTestTreatAllSpritesAsHitTestable = 1L << 5
kSpriteAtomType = FOUR_CHAR_CODE('sprt')
kSpriteImagesContainerAtomType = FOUR_CHAR_CODE('imct')
kSpriteImageAtomType = FOUR_CHAR_CODE('imag')
kSpriteImageDataAtomType = FOUR_CHAR_CODE('imda')
kSpriteImageDataRefAtomType = FOUR_CHAR_CODE('imre')
kSpriteImageDataRefTypeAtomType = FOUR_CHAR_CODE('imrt')
kSpriteImageGroupIDAtomType = FOUR_CHAR_CODE('imgr')
kSpriteImageRegistrationAtomType = FOUR_CHAR_CODE('imrg')
kSpriteImageDefaultImageIndexAtomType = FOUR_CHAR_CODE('defi')
kSpriteSharedDataAtomType = FOUR_CHAR_CODE('dflt')
kSpriteNameAtomType = FOUR_CHAR_CODE('name')
kSpriteImageNameAtomType = FOUR_CHAR_CODE('name')
kSpriteUsesImageIDsAtomType = FOUR_CHAR_CODE('uses')
kSpriteBehaviorsAtomType = FOUR_CHAR_CODE('beha')
kSpriteImageBehaviorAtomType = FOUR_CHAR_CODE('imag')
kSpriteCursorBehaviorAtomType = FOUR_CHAR_CODE('crsr')
kSpriteStatusStringsBehaviorAtomType = FOUR_CHAR_CODE('sstr')
kSpriteVariablesContainerAtomType = FOUR_CHAR_CODE('vars')
kSpriteStringVariableAtomType = FOUR_CHAR_CODE('strv')
kSpriteFloatingPointVariableAtomType = FOUR_CHAR_CODE('flov')
kMovieMediaDataReference = FOUR_CHAR_CODE('mmdr')
kMovieMediaDefaultDataReferenceID = FOUR_CHAR_CODE('ddri')
kMovieMediaSlaveTime = FOUR_CHAR_CODE('slti')
kMovieMediaSlaveAudio = FOUR_CHAR_CODE('slau')
kMovieMediaSlaveGraphicsMode = FOUR_CHAR_CODE('slgr')
kMovieMediaAutoPlay = FOUR_CHAR_CODE('play')
kMovieMediaLoop = FOUR_CHAR_CODE('loop')
kMovieMediaUseMIMEType = FOUR_CHAR_CODE('mime')
kMovieMediaTitle = FOUR_CHAR_CODE('titl')
kMovieMediaAltText = FOUR_CHAR_CODE('altt')
kMovieMediaClipBegin = FOUR_CHAR_CODE('clpb')
kMovieMediaClipDuration = FOUR_CHAR_CODE('clpd')
kMovieMediaRegionAtom = FOUR_CHAR_CODE('regi')
kMovieMediaSlaveTrackDuration = FOUR_CHAR_CODE('sltr')
kMovieMediaEnableFrameStepping = FOUR_CHAR_CODE('enfs')
kMovieMediaBackgroundColor = FOUR_CHAR_CODE('bkcl')
kMovieMediaPrerollTime = FOUR_CHAR_CODE('prer')
kMovieMediaFitNone = 0
kMovieMediaFitScroll = FOUR_CHAR_CODE('scro')
kMovieMediaFitClipIfNecessary = FOUR_CHAR_CODE('hidd')
kMovieMediaFitFill = FOUR_CHAR_CODE('fill')
kMovieMediaFitMeet = FOUR_CHAR_CODE('meet')
kMovieMediaFitSlice = FOUR_CHAR_CODE('slic')
kMovieMediaSpatialAdjustment = FOUR_CHAR_CODE('fit ')
kMovieMediaRectangleAtom = FOUR_CHAR_CODE('rect')
kMovieMediaTop = FOUR_CHAR_CODE('top ')
kMovieMediaLeft = FOUR_CHAR_CODE('left')
kMovieMediaWidth = FOUR_CHAR_CODE('wd ')
kMovieMediaHeight = FOUR_CHAR_CODE('ht ')
kMoviePropertyDuration = FOUR_CHAR_CODE('dura')
kMoviePropertyTimeScale = FOUR_CHAR_CODE('tims')
kMoviePropertyTime = FOUR_CHAR_CODE('timv')
kMoviePropertyNaturalBounds = FOUR_CHAR_CODE('natb')
kMoviePropertyMatrix = FOUR_CHAR_CODE('mtrx')
kMoviePropertyTrackList = FOUR_CHAR_CODE('tlst')
kTrackPropertyMediaType = FOUR_CHAR_CODE('mtyp')
kTrackPropertyInstantiation = FOUR_CHAR_CODE('inst')
MovieControllerComponentType = FOUR_CHAR_CODE('play')
kMovieControllerQTVRFlag = 1 << 0
kMovieControllerDontDisplayToUser = 1 << 1
mcActionIdle = 1
mcActionDraw = 2
mcActionActivate = 3
mcActionDeactivate = 4
mcActionMouseDown = 5
mcActionKey = 6
mcActionPlay = 8
mcActionGoToTime = 12
mcActionSetVolume = 14
mcActionGetVolume = 15
mcActionStep = 18
mcActionSetLooping = 21
mcActionGetLooping = 22
mcActionSetLoopIsPalindrome = 23
mcActionGetLoopIsPalindrome = 24
mcActionSetGrowBoxBounds = 25
mcActionControllerSizeChanged = 26
mcActionSetSelectionBegin = 29
mcActionSetSelectionDuration = 30
mcActionSetKeysEnabled = 32
mcActionGetKeysEnabled = 33
mcActionSetPlaySelection = 34
mcActionGetPlaySelection = 35
mcActionSetUseBadge = 36
mcActionGetUseBadge = 37
mcActionSetFlags = 38
mcActionGetFlags = 39
mcActionSetPlayEveryFrame = 40
mcActionGetPlayEveryFrame = 41
mcActionGetPlayRate = 42
mcActionShowBalloon = 43
mcActionBadgeClick = 44
mcActionMovieClick = 45
mcActionSuspend = 46
mcActionResume = 47
mcActionSetControllerKeysEnabled = 48
mcActionGetTimeSliderRect = 49
mcActionMovieEdited = 50
mcActionGetDragEnabled = 51
mcActionSetDragEnabled = 52
mcActionGetSelectionBegin = 53
mcActionGetSelectionDuration = 54
mcActionPrerollAndPlay = 55
mcActionGetCursorSettingEnabled = 56
mcActionSetCursorSettingEnabled = 57
mcActionSetColorTable = 58
mcActionLinkToURL = 59
mcActionCustomButtonClick = 60
mcActionForceTimeTableUpdate = 61
mcActionSetControllerTimeLimits = 62
mcActionExecuteAllActionsForQTEvent = 63
mcActionExecuteOneActionForQTEvent = 64
mcActionAdjustCursor = 65
mcActionUseTrackForTimeTable = 66
mcActionClickAndHoldPoint = 67
mcActionShowMessageString = 68
mcActionShowStatusString = 69
mcActionGetExternalMovie = 70
mcActionGetChapterTime = 71
mcActionPerformActionList = 72
mcActionEvaluateExpression = 73
mcActionFetchParameterAs = 74
mcActionGetCursorByID = 75
mcActionGetNextURL = 76
mcActionMovieChanged = 77
mcActionDoScript = 78
mcActionRestartAtTime = 79
mcActionGetIndChapter = 80
mcActionLinkToURLExtended = 81
mcActionSetVolumeStep = 82
mcActionAutoPlay = 83
mcActionPauseToBuffer = 84
mcActionAppMessageReceived = 85
mcActionEvaluateExpressionWithType = 89
mcActionGetMovieName = 90
mcActionGetMovieID = 91
mcActionGetMovieActive = 92
mcFlagSuppressMovieFrame = 1 << 0
mcFlagSuppressStepButtons = 1 << 1
mcFlagSuppressSpeakerButton = 1 << 2
mcFlagsUseWindowPalette = 1 << 3
mcFlagsDontInvalidate = 1 << 4
mcFlagsUseCustomButton = 1 << 5
mcPositionDontInvalidate = 1 << 5
kMCIEEnabledButtonPicture = 1
kMCIEDisabledButtonPicture = 2
kMCIEDepressedButtonPicture = 3
kMCIEEnabledSizeBoxPicture = 4
kMCIEDisabledSizeBoxPicture = 5
kMCIEEnabledUnavailableButtonPicture = 6
kMCIEDisabledUnavailableButtonPicture = 7
kMCIESoundSlider = 128
kMCIESoundThumb = 129
kMCIEColorTable = 256
kMCIEIsFlatAppearance = 257
kMCIEDoButtonIconsDropOnDepress = 258
mcInfoUndoAvailable = 1 << 0
mcInfoCutAvailable = 1 << 1
mcInfoCopyAvailable = 1 << 2
mcInfoPasteAvailable = 1 << 3
mcInfoClearAvailable = 1 << 4
mcInfoHasSound = 1 << 5
mcInfoIsPlaying = 1 << 6
mcInfoIsLooping = 1 << 7
mcInfoIsInPalindrome = 1 << 8
mcInfoEditingEnabled = 1 << 9
mcInfoMovieIsInteractive = 1 << 10
mcMenuUndo = 1
mcMenuCut = 3
mcMenuCopy = 4
mcMenuPaste = 5
mcMenuClear = 6
kQTAppMessageSoftwareChanged = 1
kQTAppMessageWindowCloseRequested = 3
kQTAppMessageExitFullScreenRequested = 4
kQTAppMessageDisplayChannels = 5
kQTAppMessageEnterFullScreenRequested = 6
kFetchAsBooleanPtr = 1
kFetchAsShortPtr = 2
kFetchAsLongPtr = 3
kFetchAsMatrixRecordPtr = 4
kFetchAsModifierTrackGraphicsModeRecord = 5
kFetchAsHandle = 6
kFetchAsStr255 = 7
kFetchAsFloatPtr = 8
kFetchAsPointPtr = 9
kFetchAsNewAtomContainer = 10
kFetchAsQTEventRecordPtr = 11
kFetchAsFixedPtr = 12
kFetchAsSetControllerValuePtr = 13
kFetchAsRgnHandle = 14
kFetchAsComponentDescriptionPtr = 15
kFetchAsCString = 16
kQTCursorOpenHand = -19183
kQTCursorClosedHand = -19182
kQTCursorPointingHand = -19181
kQTCursorRightArrow = -19180
kQTCursorLeftArrow = -19179
kQTCursorDownArrow = -19178
kQTCursorUpArrow = -19177
kQTCursorIBeam = -19176
kControllerUnderstandsIdleManagers = 1 << 0
kVideoMediaResetStatisticsSelect = 0x0105
kVideoMediaGetStatisticsSelect = 0x0106
kVideoMediaGetStallCountSelect = 0x010E
kVideoMediaSetCodecParameterSelect = 0x010F
kVideoMediaGetCodecParameterSelect = 0x0110
kTextMediaSetTextProcSelect = 0x0101
kTextMediaAddTextSampleSelect = 0x0102
kTextMediaAddTESampleSelect = 0x0103
kTextMediaAddHiliteSampleSelect = 0x0104
kTextMediaDrawRawSelect = 0x0109
kTextMediaSetTextPropertySelect = 0x010A
kTextMediaRawSetupSelect = 0x010B
kTextMediaRawIdleSelect = 0x010C
kTextMediaGetTextPropertySelect = 0x010D
kTextMediaFindNextTextSelect = 0x0105
kTextMediaHiliteTextSampleSelect = 0x0106
kTextMediaSetTextSampleDataSelect = 0x0107
kSpriteMediaSetPropertySelect = 0x0101
kSpriteMediaGetPropertySelect = 0x0102
kSpriteMediaHitTestSpritesSelect = 0x0103
kSpriteMediaCountSpritesSelect = 0x0104
kSpriteMediaCountImagesSelect = 0x0105
kSpriteMediaGetIndImageDescriptionSelect = 0x0106
kSpriteMediaGetDisplayedSampleNumberSelect = 0x0107
kSpriteMediaGetSpriteNameSelect = 0x0108
kSpriteMediaGetImageNameSelect = 0x0109
kSpriteMediaSetSpritePropertySelect = 0x010A
kSpriteMediaGetSpritePropertySelect = 0x010B
kSpriteMediaHitTestAllSpritesSelect = 0x010C
kSpriteMediaHitTestOneSpriteSelect = 0x010D
kSpriteMediaSpriteIndexToIDSelect = 0x010E
kSpriteMediaSpriteIDToIndexSelect = 0x010F
kSpriteMediaGetSpriteActionsForQTEventSelect = 0x0110
kSpriteMediaSetActionVariableSelect = 0x0111
kSpriteMediaGetActionVariableSelect = 0x0112
kSpriteMediaGetIndImagePropertySelect = 0x0113
kSpriteMediaNewSpriteSelect = 0x0114
kSpriteMediaDisposeSpriteSelect = 0x0115
kSpriteMediaSetActionVariableToStringSelect = 0x0116
kSpriteMediaGetActionVariableAsStringSelect = 0x0117
kSpriteMediaNewImageSelect = 0x011B
kSpriteMediaDisposeImageSelect = 0x011C
kSpriteMediaImageIndexToIDSelect = 0x011D
kSpriteMediaImageIDToIndexSelect = 0x011E
kFlashMediaSetPanSelect = 0x0101
kFlashMediaSetZoomSelect = 0x0102
kFlashMediaSetZoomRectSelect = 0x0103
kFlashMediaGetRefConBoundsSelect = 0x0104
kFlashMediaGetRefConIDSelect = 0x0105
kFlashMediaIDToRefConSelect = 0x0106
kFlashMediaGetDisplayedFrameNumberSelect = 0x0107
kFlashMediaFrameNumberToMovieTimeSelect = 0x0108
kFlashMediaFrameLabelToMovieTimeSelect = 0x0109
kFlashMediaGetFlashVariableSelect = 0x010A
kFlashMediaSetFlashVariableSelect = 0x010B
kFlashMediaDoButtonActionsSelect = 0x010C
kFlashMediaGetSupportedSwfVersionSelect = 0x010D
kMovieMediaGetChildDoMCActionCallbackSelect = 0x0102
kMovieMediaGetDoMCActionCallbackSelect = 0x0103
kMovieMediaGetCurrentMoviePropertySelect = 0x0104
kMovieMediaGetCurrentTrackPropertySelect = 0x0105
kMovieMediaGetChildMovieDataReferenceSelect = 0x0106
kMovieMediaSetChildMovieDataReferenceSelect = 0x0107
kMovieMediaLoadChildMovieFromDataReferenceSelect = 0x0108
kMedia3DGetNamedObjectListSelect = 0x0101
kMedia3DGetRendererListSelect = 0x0102
kMedia3DGetCurrentGroupSelect = 0x0103
kMedia3DTranslateNamedObjectToSelect = 0x0104
kMedia3DScaleNamedObjectToSelect = 0x0105
kMedia3DRotateNamedObjectToSelect = 0x0106
kMedia3DSetCameraDataSelect = 0x0107
kMedia3DGetCameraDataSelect = 0x0108
kMedia3DSetCameraAngleAspectSelect = 0x0109
kMedia3DGetCameraAngleAspectSelect = 0x010A
kMedia3DSetCameraRangeSelect = 0x010D
kMedia3DGetCameraRangeSelect = 0x010E
kMedia3DGetViewObjectSelect = 0x010F
kMCSetMovieSelect = 0x0002
kMCGetIndMovieSelect = 0x0005
kMCRemoveAllMoviesSelect = 0x0006
kMCRemoveAMovieSelect = 0x0003
kMCRemoveMovieSelect = 0x0006
kMCIsPlayerEventSelect = 0x0007
kMCSetActionFilterSelect = 0x0008
kMCDoActionSelect = 0x0009
kMCSetControllerAttachedSelect = 0x000A
kMCIsControllerAttachedSelect = 0x000B
kMCSetControllerPortSelect = 0x000C
kMCGetControllerPortSelect = 0x000D
kMCSetVisibleSelect = 0x000E
kMCGetVisibleSelect = 0x000F
kMCGetControllerBoundsRectSelect = 0x0010
kMCSetControllerBoundsRectSelect = 0x0011
kMCGetControllerBoundsRgnSelect = 0x0012
kMCGetWindowRgnSelect = 0x0013
kMCMovieChangedSelect = 0x0014
kMCSetDurationSelect = 0x0015
kMCGetCurrentTimeSelect = 0x0016
kMCNewAttachedControllerSelect = 0x0017
kMCDrawSelect = 0x0018
kMCActivateSelect = 0x0019
kMCIdleSelect = 0x001A
kMCKeySelect = 0x001B
kMCClickSelect = 0x001C
kMCEnableEditingSelect = 0x001D
kMCIsEditingEnabledSelect = 0x001E
kMCCopySelect = 0x001F
kMCCutSelect = 0x0020
kMCPasteSelect = 0x0021
kMCClearSelect = 0x0022
kMCUndoSelect = 0x0023
kMCPositionControllerSelect = 0x0024
kMCGetControllerInfoSelect = 0x0025
kMCSetClipSelect = 0x0028
kMCGetClipSelect = 0x0029
kMCDrawBadgeSelect = 0x002A
kMCSetUpEditMenuSelect = 0x002B
kMCGetMenuStringSelect = 0x002C
kMCSetActionFilterWithRefConSelect = 0x002D
kMCPtInControllerSelect = 0x002E
kMCInvalidateSelect = 0x002F
kMCAdjustCursorSelect = 0x0030
kMCGetInterfaceElementSelect = 0x0031
kMCGetDoActionsProcSelect = 0x0032
kMCAddMovieSegmentSelect = 0x0033
kMCTrimMovieSegmentSelect = 0x0034
kMCSetIdleManagerSelect = 0x0035
kMCSetControllerCapabilitiesSelect = 0x0036
kMusicMediaGetIndexedTunePlayerSelect = 0x0101
kRawCodecType = FOUR_CHAR_CODE('raw ')
kCinepakCodecType = FOUR_CHAR_CODE('cvid')
kGraphicsCodecType = FOUR_CHAR_CODE('smc ')
kAnimationCodecType = FOUR_CHAR_CODE('rle ')
kVideoCodecType = FOUR_CHAR_CODE('rpza')
kComponentVideoCodecType = FOUR_CHAR_CODE('yuv2')
kJPEGCodecType = FOUR_CHAR_CODE('jpeg')
kMotionJPEGACodecType = FOUR_CHAR_CODE('mjpa')
kMotionJPEGBCodecType = FOUR_CHAR_CODE('mjpb')
kSGICodecType = FOUR_CHAR_CODE('.SGI')
kPlanarRGBCodecType = FOUR_CHAR_CODE('8BPS')
kMacPaintCodecType = FOUR_CHAR_CODE('PNTG')
kGIFCodecType = FOUR_CHAR_CODE('gif ')
kPhotoCDCodecType = FOUR_CHAR_CODE('kpcd')
kQuickDrawGXCodecType = FOUR_CHAR_CODE('qdgx')
kAVRJPEGCodecType = FOUR_CHAR_CODE('avr ')
kOpenDMLJPEGCodecType = FOUR_CHAR_CODE('dmb1')
kBMPCodecType = FOUR_CHAR_CODE('WRLE')
kWindowsRawCodecType = FOUR_CHAR_CODE('WRAW')
kVectorCodecType = FOUR_CHAR_CODE('path')
kQuickDrawCodecType = FOUR_CHAR_CODE('qdrw')
kWaterRippleCodecType = FOUR_CHAR_CODE('ripl')
kFireCodecType = FOUR_CHAR_CODE('fire')
kCloudCodecType = FOUR_CHAR_CODE('clou')
kH261CodecType = FOUR_CHAR_CODE('h261')
kH263CodecType = FOUR_CHAR_CODE('h263')
kDVCNTSCCodecType = FOUR_CHAR_CODE('dvc ')
kDVCPALCodecType = FOUR_CHAR_CODE('dvcp')
kDVCProPALCodecType = FOUR_CHAR_CODE('dvpp')
kBaseCodecType = FOUR_CHAR_CODE('base')
kFLCCodecType = FOUR_CHAR_CODE('flic')
kTargaCodecType = FOUR_CHAR_CODE('tga ')
kPNGCodecType = FOUR_CHAR_CODE('png ')
kTIFFCodecType = FOUR_CHAR_CODE('tiff')
kComponentVideoSigned = FOUR_CHAR_CODE('yuvu')
kComponentVideoUnsigned = FOUR_CHAR_CODE('yuvs')
kCMYKCodecType = FOUR_CHAR_CODE('cmyk')
kMicrosoftVideo1CodecType = FOUR_CHAR_CODE('msvc')
kSorensonCodecType = FOUR_CHAR_CODE('SVQ1')
kSorenson3CodecType = FOUR_CHAR_CODE('SVQ3')
kIndeo4CodecType = FOUR_CHAR_CODE('IV41')
kMPEG4VisualCodecType = FOUR_CHAR_CODE('mp4v')
k64ARGBCodecType = FOUR_CHAR_CODE('b64a')
k48RGBCodecType = FOUR_CHAR_CODE('b48r')
k32AlphaGrayCodecType = FOUR_CHAR_CODE('b32a')
k16GrayCodecType = FOUR_CHAR_CODE('b16g')
kMpegYUV420CodecType = FOUR_CHAR_CODE('myuv')
kYUV420CodecType = FOUR_CHAR_CODE('y420')
kSorensonYUV9CodecType = FOUR_CHAR_CODE('syv9')
k422YpCbCr8CodecType = FOUR_CHAR_CODE('2vuy')
k444YpCbCr8CodecType = FOUR_CHAR_CODE('v308')
k4444YpCbCrA8CodecType = FOUR_CHAR_CODE('v408')
k422YpCbCr16CodecType = FOUR_CHAR_CODE('v216')
k422YpCbCr10CodecType = FOUR_CHAR_CODE('v210')
k444YpCbCr10CodecType = FOUR_CHAR_CODE('v410')
k4444YpCbCrA8RCodecType = FOUR_CHAR_CODE('r408')
kBlurImageFilterType = FOUR_CHAR_CODE('blur')
kSharpenImageFilterType = FOUR_CHAR_CODE('shrp')
kEdgeDetectImageFilterType = FOUR_CHAR_CODE('edge')
kEmbossImageFilterType = FOUR_CHAR_CODE('embs')
kConvolveImageFilterType = FOUR_CHAR_CODE('genk')
kAlphaGainImageFilterType = FOUR_CHAR_CODE('gain')
kRGBColorBalanceImageFilterType = FOUR_CHAR_CODE('rgbb')
kHSLColorBalanceImageFilterType = FOUR_CHAR_CODE('hslb')
kColorSyncImageFilterType = FOUR_CHAR_CODE('sync')
kFilmNoiseImageFilterType = FOUR_CHAR_CODE('fmns')
kSolarizeImageFilterType = FOUR_CHAR_CODE('solr')
kColorTintImageFilterType = FOUR_CHAR_CODE('tint')
kLensFlareImageFilterType = FOUR_CHAR_CODE('lens')
kBrightnessContrastImageFilterType = FOUR_CHAR_CODE('brco')
kAlphaCompositorTransitionType = FOUR_CHAR_CODE('blnd')
kCrossFadeTransitionType = FOUR_CHAR_CODE('dslv')
kChannelCompositeEffectType = FOUR_CHAR_CODE('chan')
kChromaKeyTransitionType = FOUR_CHAR_CODE('ckey')
kImplodeTransitionType = FOUR_CHAR_CODE('mplo')
kExplodeTransitionType = FOUR_CHAR_CODE('xplo')
kGradientTransitionType = FOUR_CHAR_CODE('matt')
kPushTransitionType = FOUR_CHAR_CODE('push')
kSlideTransitionType = FOUR_CHAR_CODE('slid')
kWipeTransitionType = FOUR_CHAR_CODE('smpt')
kIrisTransitionType = FOUR_CHAR_CODE('smp2')
kRadialTransitionType = FOUR_CHAR_CODE('smp3')
kMatrixTransitionType = FOUR_CHAR_CODE('smp4')
kZoomTransitionType = FOUR_CHAR_CODE('zoom')
kTravellingMatteEffectType = FOUR_CHAR_CODE('trav')
kCMYKPixelFormat = FOUR_CHAR_CODE('cmyk')
k64ARGBPixelFormat = FOUR_CHAR_CODE('b64a')
k48RGBPixelFormat = FOUR_CHAR_CODE('b48r')
k32AlphaGrayPixelFormat = FOUR_CHAR_CODE('b32a')
k16GrayPixelFormat = FOUR_CHAR_CODE('b16g')
k422YpCbCr8PixelFormat = FOUR_CHAR_CODE('2vuy')
k4444YpCbCrA8PixelFormat = FOUR_CHAR_CODE('v408')
k4444YpCbCrA8RPixelFormat = FOUR_CHAR_CODE('r408')
kYUV420PixelFormat = FOUR_CHAR_CODE('y420')
codecInfoDoes1 = (1L << 0)
codecInfoDoes2 = (1L << 1)
codecInfoDoes4 = (1L << 2)
codecInfoDoes8 = (1L << 3)
codecInfoDoes16 = (1L << 4)
codecInfoDoes32 = (1L << 5)
codecInfoDoesDither = (1L << 6)
codecInfoDoesStretch = (1L << 7)
codecInfoDoesShrink = (1L << 8)
codecInfoDoesMask = (1L << 9)
codecInfoDoesTemporal = (1L << 10)
codecInfoDoesDouble = (1L << 11)
codecInfoDoesQuad = (1L << 12)
codecInfoDoesHalf = (1L << 13)
codecInfoDoesQuarter = (1L << 14)
codecInfoDoesRotate = (1L << 15)
codecInfoDoesHorizFlip = (1L << 16)
codecInfoDoesVertFlip = (1L << 17)
codecInfoHasEffectParameterList = (1L << 18)
codecInfoDoesBlend = (1L << 19)
codecInfoDoesWarp = (1L << 20)
codecInfoDoesRecompress = (1L << 21)
codecInfoDoesSpool = (1L << 22)
codecInfoDoesRateConstrain = (1L << 23)
codecInfoDepth1 = (1L << 0)
codecInfoDepth2 = (1L << 1)
codecInfoDepth4 = (1L << 2)
codecInfoDepth8 = (1L << 3)
codecInfoDepth16 = (1L << 4)
codecInfoDepth32 = (1L << 5)
codecInfoDepth24 = (1L << 6)
codecInfoDepth33 = (1L << 7)
codecInfoDepth34 = (1L << 8)
codecInfoDepth36 = (1L << 9)
codecInfoDepth40 = (1L << 10)
codecInfoStoresClut = (1L << 11)
codecInfoDoesLossless = (1L << 12)
codecInfoSequenceSensitive = (1L << 13)
codecFlagUseImageBuffer = (1L << 0)
codecFlagUseScreenBuffer = (1L << 1)
codecFlagUpdatePrevious = (1L << 2)
codecFlagNoScreenUpdate = (1L << 3)
codecFlagWasCompressed = (1L << 4)
codecFlagDontOffscreen = (1L << 5)
codecFlagUpdatePreviousComp = (1L << 6)
codecFlagForceKeyFrame = (1L << 7)
codecFlagOnlyScreenUpdate = (1L << 8)
codecFlagLiveGrab = (1L << 9)
codecFlagDiffFrame = (1L << 9)
codecFlagDontUseNewImageBuffer = (1L << 10)
codecFlagInterlaceUpdate = (1L << 11)
codecFlagCatchUpDiff = (1L << 12)
codecFlagSupportDisable = (1L << 13)
codecFlagReenable = (1L << 14)
codecFlagOutUpdateOnNextIdle = (1L << 9)
codecFlagOutUpdateOnDataSourceChange = (1L << 10)
codecFlagSequenceSensitive = (1L << 11)
codecFlagOutUpdateOnTimeChange = (1L << 12)
codecFlagImageBufferNotSourceImage = (1L << 13)
codecFlagUsedNewImageBuffer = (1L << 14)
codecFlagUsedImageBuffer = (1L << 15)
codecMinimumDataSize = 32768L
compressorComponentType = FOUR_CHAR_CODE('imco')
decompressorComponentType = FOUR_CHAR_CODE('imdc')
codecLosslessQuality = 0x00000400
codecMaxQuality = 0x000003FF
codecMinQuality = 0x00000000
codecLowQuality = 0x00000100
codecNormalQuality = 0x00000200
codecHighQuality = 0x00000300
codecLockBitsShieldCursor = (1 << 0)
codecCompletionSource = (1 << 0)
codecCompletionDest = (1 << 1)
codecCompletionDontUnshield = (1 << 2)
codecCompletionWentOffscreen = (1 << 3)
codecCompletionUnlockBits = (1 << 4)
codecCompletionForceChainFlush = (1 << 5)
codecCompletionDropped = (1 << 6)
codecProgressOpen = 0
codecProgressUpdatePercent = 1
codecProgressClose = 2
defaultDither = 0
forceDither = 1
suppressDither = 2
useColorMatching = 4
callStdBits = 1
callOldBits = 2
noDefaultOpcodes = 4
graphicsModeStraightAlpha = 256
graphicsModePreWhiteAlpha = 257
graphicsModePreBlackAlpha = 258
graphicsModeComposition = 259
graphicsModeStraightAlphaBlend = 260
graphicsModePreMulColorAlpha = 261
evenField1ToEvenFieldOut = 1 << 0
evenField1ToOddFieldOut = 1 << 1
oddField1ToEvenFieldOut = 1 << 2
oddField1ToOddFieldOut = 1 << 3
evenField2ToEvenFieldOut = 1 << 4
evenField2ToOddFieldOut = 1 << 5
oddField2ToEvenFieldOut = 1 << 6
oddField2ToOddFieldOut = 1 << 7
icmFrameTimeHasVirtualStartTimeAndDuration = 1 << 0
codecDSequenceDisableOverlaySurface = (1L << 5)
codecDSequenceSingleField = (1L << 6)
codecDSequenceBidirectionalPrediction = (1L << 7)
codecDSequenceFlushInsteadOfDirtying = (1L << 8)
codecDSequenceEnableSubPixelPositioning = (1L << 9)
kICMSequenceTaskWeight = FOUR_CHAR_CODE('twei')
kICMSequenceTaskName = FOUR_CHAR_CODE('tnam')
kICMSequenceUserPreferredCodecs = FOUR_CHAR_CODE('punt')
kImageDescriptionSampleFormat = FOUR_CHAR_CODE('idfm')
kImageDescriptionClassicAtomFormat = FOUR_CHAR_CODE('atom')
kImageDescriptionQTAtomFormat = FOUR_CHAR_CODE('qtat')
kImageDescriptionEffectDataFormat = FOUR_CHAR_CODE('fxat')
kImageDescriptionPrivateDataFormat = FOUR_CHAR_CODE('priv')
kImageDescriptionAlternateCodec = FOUR_CHAR_CODE('subs')
kImageDescriptionColorSpace = FOUR_CHAR_CODE('cspc')
sfpItemPreviewAreaUser = 11
sfpItemPreviewStaticText = 12
sfpItemPreviewDividerUser = 13
sfpItemCreatePreviewButton = 14
sfpItemShowPreviewButton = 15
kICMPixelFormatIsPlanarMask = 0x0F
kICMPixelFormatIsIndexed = (1L << 4)
kICMPixelFormatIsSupportedByQD = (1L << 5)
kICMPixelFormatIsMonochrome = (1L << 6)
kICMPixelFormatHasAlphaChannel = (1L << 7)
kICMGetChainUltimateParent = 0
kICMGetChainParent = 1
kICMGetChainChild = 2
kICMGetChainUltimateChild = 3
kDontUseValidateToFindGraphicsImporter = 1L << 0
kICMTempThenAppMemory = 1L << 12
kICMAppThenTempMemory = 1L << 13
kQTUsePlatformDefaultGammaLevel = 0
kQTUseSourceGammaLevel = -1L
kQTCCIR601VideoGammaLevel = 0x00023333
identityMatrixType = 0x00
translateMatrixType = 0x01
scaleMatrixType = 0x02
scaleTranslateMatrixType = 0x03
linearMatrixType = 0x04
linearTranslateMatrixType = 0x05
perspectiveMatrixType = 0x06
GraphicsImporterComponentType = FOUR_CHAR_CODE('grip')
graphicsImporterUsesImageDecompressor = 1L << 23
quickTimeImageFileImageDescriptionAtom = FOUR_CHAR_CODE('idsc')
quickTimeImageFileImageDataAtom = FOUR_CHAR_CODE('idat')
quickTimeImageFileMetaDataAtom = FOUR_CHAR_CODE('meta')
quickTimeImageFileColorSyncProfileAtom = FOUR_CHAR_CODE('iicc')
graphicsImporterDrawsAllPixels = 0
graphicsImporterDoesntDrawAllPixels = 1
graphicsImporterDontKnowIfDrawAllPixels = 2
kGraphicsImporterDontDoGammaCorrection = 1L << 0
kGraphicsImporterTrustResolutionFromFile = 1L << 1
kGraphicsImporterEnableSubPixelPositioning = 1L << 2
kGraphicsExportGroup = FOUR_CHAR_CODE('expo')
kGraphicsExportFileType = FOUR_CHAR_CODE('ftyp')
kGraphicsExportMIMEType = FOUR_CHAR_CODE('mime')
kGraphicsExportExtension = FOUR_CHAR_CODE('ext ')
kGraphicsExportDescription = FOUR_CHAR_CODE('desc')
kQTPhotoshopLayerMode = FOUR_CHAR_CODE('lmod')
kQTPhotoshopLayerOpacity = FOUR_CHAR_CODE('lopa')
kQTPhotoshopLayerClipping = FOUR_CHAR_CODE('lclp')
kQTPhotoshopLayerFlags = FOUR_CHAR_CODE('lflg')
kQTPhotoshopLayerName = FOUR_CHAR_CODE('\xa9lnm')
kQTPhotoshopLayerUnicodeName = FOUR_CHAR_CODE('luni')
kQTIndexedImageType = FOUR_CHAR_CODE('nth?')
kQTIndexedImageIsThumbnail = FOUR_CHAR_CODE('n=th')
kQTIndexedImageIsLayer = FOUR_CHAR_CODE('n=ly')
kQTIndexedImageIsPage = FOUR_CHAR_CODE('n=pg')
kQTIndexedImageIsMultiResolution = FOUR_CHAR_CODE('n=rs')
kQTTIFFUserDataPrefix = 0x74690000
kQTTIFFExifUserDataPrefix = 0x65780000
kQTTIFFExifGPSUserDataPrefix = 0x67700000
kQTAlphaMode = FOUR_CHAR_CODE('almo')
kQTAlphaModePreMulColor = FOUR_CHAR_CODE('almp')
kUserDataIPTC = FOUR_CHAR_CODE('iptc')
kQTTIFFUserDataOrientation = 0x74690112
kQTTIFFUserDataTransferFunction = 0x7469012D
kQTTIFFUserDataWhitePoint = 0x7469013E
kQTTIFFUserDataPrimaryChromaticities = 0x7469013F
kQTTIFFUserDataTransferRange = 0x74690156
kQTTIFFUserDataYCbCrPositioning = 0x74690213
kQTTIFFUserDataReferenceBlackWhite = 0x74690214
kQTTIFFUserDataModelPixelScale = 0x7469830E
kQTTIFFUserDataModelTransformation = 0x746985D8
kQTTIFFUserDataModelTiepoint = 0x74698482
kQTTIFFUserDataGeoKeyDirectory = 0x746987AF
kQTTIFFUserDataGeoDoubleParams = 0x746987B0
kQTTIFFUserDataGeoAsciiParams = 0x746987B1
kQTTIFFUserDataIntergraphMatrix = 0x74698480
kQTExifUserDataExifVersion = 0x65789000
kQTExifUserDataFlashPixVersion = 0x6578A000
kQTExifUserDataColorSpace = 0x6578A001
kQTExifUserDataComponentsConfiguration = 0x65789101
kQTExifUserDataCompressedBitsPerPixel = 0x65789102
kQTExifUserDataPixelXDimension = 0x6578A002
kQTExifUserDataPixelYDimension = 0x6578A003
kQTExifUserDataMakerNote = 0x6578927C
kQTExifUserDataUserComment = 0x6578928C
kQTExifUserDataRelatedSoundFile = 0x6578A004
kQTExifUserDataDateTimeOriginal = 0x65789003
kQTExifUserDataDateTimeDigitized = 0x65789004
kQTExifUserDataSubSecTime = 0x65789290
kQTExifUserDataSubSecTimeOriginal = 0x65789291
kQTExifUserDataSubSecTimeDigitized = 0x65789292
kQTExifUserDataExposureTime = 0x6578829A
kQTExifUserDataFNumber = 0x6578829D
kQTExifUserDataExposureProgram = 0x65788822
kQTExifUserDataSpectralSensitivity = 0x65788824
kQTExifUserDataISOSpeedRatings = 0x65788827
kQTExifUserDataShutterSpeedValue = 0x65789201
kQTExifUserDataApertureValue = 0x65789202
kQTExifUserDataBrightnessValue = 0x65789203
kQTExifUserDataExposureBiasValue = 0x65789204
kQTExifUserDataMaxApertureValue = 0x65789205
kQTExifUserDataSubjectDistance = 0x65789206
kQTExifUserDataMeteringMode = 0x65789207
kQTExifUserDataLightSource = 0x65789208
kQTExifUserDataFlash = 0x65789209
kQTExifUserDataFocalLength = 0x6578920A
kQTExifUserDataFlashEnergy = 0x6578A20B
kQTExifUserDataFocalPlaneXResolution = 0x6578A20E
kQTExifUserDataFocalPlaneYResolution = 0x6578A20F
kQTExifUserDataFocalPlaneResolutionUnit = 0x6578A210
kQTExifUserDataSubjectLocation = 0x6578A214
kQTExifUserDataExposureIndex = 0x6578A215
kQTExifUserDataSensingMethod = 0x6578A217
kQTExifUserDataFileSource = 0x6578A300
kQTExifUserDataSceneType = 0x6578A301
kQTExifUserDataGPSVersionID = 0x06770000
kQTExifUserDataGPSLatitudeRef = 0x06770001
kQTExifUserDataGPSLatitude = 0x06770002
kQTExifUserDataGPSLongitudeRef = 0x06770003
kQTExifUserDataGPSLongitude = 0x06770004
kQTExifUserDataGPSAltitudeRef = 0x06770005
kQTExifUserDataGPSAltitude = 0x06770006
kQTExifUserDataGPSTimeStamp = 0x06770007
kQTExifUserDataGPSSatellites = 0x06770008
kQTExifUserDataGPSStatus = 0x06770009
kQTExifUserDataGPSMeasureMode = 0x0677000A
kQTExifUserDataGPSDOP = 0x0677000B
kQTExifUserDataGPSSpeedRef = 0x0677000C
kQTExifUserDataGPSSpeed = 0x0677000D
kQTExifUserDataGPSTrackRef = 0x0677000E
kQTExifUserDataGPSTrack = 0x0677000F
kQTExifUserDataGPSImgDirectionRef = 0x06770010
kQTExifUserDataGPSImgDirection = 0x06770011
kQTExifUserDataGPSMapDatum = 0x06770012
kQTExifUserDataGPSDestLatitudeRef = 0x06770013
kQTExifUserDataGPSDestLatitude = 0x06770014
kQTExifUserDataGPSDestLongitudeRef = 0x06770015
kQTExifUserDataGPSDestLongitude = 0x06770016
kQTExifUserDataGPSDestBearingRef = 0x06770017
kQTExifUserDataGPSDestBearing = 0x06770018
kQTExifUserDataGPSDestDistanceRef = 0x06770019
kQTExifUserDataGPSDestDistance = 0x0677001A
GraphicsExporterComponentType = FOUR_CHAR_CODE('grex')
kBaseGraphicsExporterSubType = FOUR_CHAR_CODE('base')
graphicsExporterIsBaseExporter = 1L << 0
graphicsExporterCanTranscode = 1L << 1
graphicsExporterUsesImageCompressor = 1L << 2
kQTResolutionSettings = FOUR_CHAR_CODE('reso')
kQTTargetDataSize = FOUR_CHAR_CODE('dasz')
kQTDontRecompress = FOUR_CHAR_CODE('dntr')
kQTInterlaceStyle = FOUR_CHAR_CODE('ilac')
kQTColorSyncProfile = FOUR_CHAR_CODE('iccp')
kQTThumbnailSettings = FOUR_CHAR_CODE('thum')
kQTEnableExif = FOUR_CHAR_CODE('exif')
kQTMetaData = FOUR_CHAR_CODE('meta')
kQTTIFFCompressionMethod = FOUR_CHAR_CODE('tifc')
kQTTIFFCompression_None = 1
kQTTIFFCompression_PackBits = 32773L
kQTTIFFLittleEndian = FOUR_CHAR_CODE('tife')
kQTPNGFilterPreference = FOUR_CHAR_CODE('pngf')
kQTPNGFilterBestForColorType = FOUR_CHAR_CODE('bflt')
kQTPNGFilterNone = 0
kQTPNGFilterSub = 1
kQTPNGFilterUp = 2
kQTPNGFilterAverage = 3
kQTPNGFilterPaeth = 4
kQTPNGFilterAdaptivePerRow = FOUR_CHAR_CODE('aflt')
kQTPNGInterlaceStyle = FOUR_CHAR_CODE('ilac')
kQTPNGInterlaceNone = 0
kQTPNGInterlaceAdam7 = 1
ImageTranscodererComponentType = FOUR_CHAR_CODE('imtc')
kGraphicsImportSetDataReferenceSelect = 0x0001
kGraphicsImportGetDataReferenceSelect = 0x0002
kGraphicsImportSetDataFileSelect = 0x0003
kGraphicsImportGetDataFileSelect = 0x0004
kGraphicsImportSetDataHandleSelect = 0x0005
kGraphicsImportGetDataHandleSelect = 0x0006
kGraphicsImportGetImageDescriptionSelect = 0x0007
kGraphicsImportGetDataOffsetAndSizeSelect = 0x0008
kGraphicsImportReadDataSelect = 0x0009
kGraphicsImportSetClipSelect = 0x000A
kGraphicsImportGetClipSelect = 0x000B
kGraphicsImportSetSourceRectSelect = 0x000C
kGraphicsImportGetSourceRectSelect = 0x000D
kGraphicsImportGetNaturalBoundsSelect = 0x000E
kGraphicsImportDrawSelect = 0x000F
kGraphicsImportSetGWorldSelect = 0x0010
kGraphicsImportGetGWorldSelect = 0x0011
kGraphicsImportSetMatrixSelect = 0x0012
kGraphicsImportGetMatrixSelect = 0x0013
kGraphicsImportSetBoundsRectSelect = 0x0014
kGraphicsImportGetBoundsRectSelect = 0x0015
kGraphicsImportSaveAsPictureSelect = 0x0016
kGraphicsImportSetGraphicsModeSelect = 0x0017
kGraphicsImportGetGraphicsModeSelect = 0x0018
kGraphicsImportSetQualitySelect = 0x0019
kGraphicsImportGetQualitySelect = 0x001A
kGraphicsImportSaveAsQuickTimeImageFileSelect = 0x001B
kGraphicsImportSetDataReferenceOffsetAndLimitSelect = 0x001C
kGraphicsImportGetDataReferenceOffsetAndLimitSelect = 0x001D
kGraphicsImportGetAliasedDataReferenceSelect = 0x001E
kGraphicsImportValidateSelect = 0x001F
kGraphicsImportGetMetaDataSelect = 0x0020
kGraphicsImportGetMIMETypeListSelect = 0x0021
kGraphicsImportDoesDrawAllPixelsSelect = 0x0022
kGraphicsImportGetAsPictureSelect = 0x0023
kGraphicsImportExportImageFileSelect = 0x0024
kGraphicsImportGetExportImageTypeListSelect = 0x0025
kGraphicsImportDoExportImageFileDialogSelect = 0x0026
kGraphicsImportGetExportSettingsAsAtomContainerSelect = 0x0027
kGraphicsImportSetExportSettingsFromAtomContainerSelect = 0x0028
kGraphicsImportSetProgressProcSelect = 0x0029
kGraphicsImportGetProgressProcSelect = 0x002A
kGraphicsImportGetImageCountSelect = 0x002B
kGraphicsImportSetImageIndexSelect = 0x002C
kGraphicsImportGetImageIndexSelect = 0x002D
kGraphicsImportGetDataOffsetAndSize64Select = 0x002E
kGraphicsImportReadData64Select = 0x002F
kGraphicsImportSetDataReferenceOffsetAndLimit64Select = 0x0030
kGraphicsImportGetDataReferenceOffsetAndLimit64Select = 0x0031
kGraphicsImportGetDefaultMatrixSelect = 0x0032
kGraphicsImportGetDefaultClipSelect = 0x0033
kGraphicsImportGetDefaultGraphicsModeSelect = 0x0034
kGraphicsImportGetDefaultSourceRectSelect = 0x0035
kGraphicsImportGetColorSyncProfileSelect = 0x0036
kGraphicsImportSetDestRectSelect = 0x0037
kGraphicsImportGetDestRectSelect = 0x0038
kGraphicsImportSetFlagsSelect = 0x0039
kGraphicsImportGetFlagsSelect = 0x003A
kGraphicsImportGetBaseDataOffsetAndSize64Select = 0x003D
kGraphicsImportSetImageIndexToThumbnailSelect = 0x003E
kGraphicsExportDoExportSelect = 0x0001
kGraphicsExportCanTranscodeSelect = 0x0002
kGraphicsExportDoTranscodeSelect = 0x0003
kGraphicsExportCanUseCompressorSelect = 0x0004
kGraphicsExportDoUseCompressorSelect = 0x0005
kGraphicsExportDoStandaloneExportSelect = 0x0006
kGraphicsExportGetDefaultFileTypeAndCreatorSelect = 0x0007
kGraphicsExportGetDefaultFileNameExtensionSelect = 0x0008
kGraphicsExportGetMIMETypeListSelect = 0x0009
kGraphicsExportRequestSettingsSelect = 0x000B
kGraphicsExportSetSettingsFromAtomContainerSelect = 0x000C
kGraphicsExportGetSettingsAsAtomContainerSelect = 0x000D
kGraphicsExportGetSettingsAsTextSelect = 0x000E
kGraphicsExportSetDontRecompressSelect = 0x000F
kGraphicsExportGetDontRecompressSelect = 0x0010
kGraphicsExportSetInterlaceStyleSelect = 0x0011
kGraphicsExportGetInterlaceStyleSelect = 0x0012
kGraphicsExportSetMetaDataSelect = 0x0013
kGraphicsExportGetMetaDataSelect = 0x0014
kGraphicsExportSetTargetDataSizeSelect = 0x0015
kGraphicsExportGetTargetDataSizeSelect = 0x0016
kGraphicsExportSetCompressionMethodSelect = 0x0017
kGraphicsExportGetCompressionMethodSelect = 0x0018
kGraphicsExportSetCompressionQualitySelect = 0x0019
kGraphicsExportGetCompressionQualitySelect = 0x001A
kGraphicsExportSetResolutionSelect = 0x001B
kGraphicsExportGetResolutionSelect = 0x001C
kGraphicsExportSetDepthSelect = 0x001D
kGraphicsExportGetDepthSelect = 0x001E
kGraphicsExportSetColorSyncProfileSelect = 0x0021
kGraphicsExportGetColorSyncProfileSelect = 0x0022
kGraphicsExportSetProgressProcSelect = 0x0023
kGraphicsExportGetProgressProcSelect = 0x0024
kGraphicsExportSetInputDataReferenceSelect = 0x0025
kGraphicsExportGetInputDataReferenceSelect = 0x0026
kGraphicsExportSetInputFileSelect = 0x0027
kGraphicsExportGetInputFileSelect = 0x0028
kGraphicsExportSetInputHandleSelect = 0x0029
kGraphicsExportGetInputHandleSelect = 0x002A
kGraphicsExportSetInputPtrSelect = 0x002B
kGraphicsExportGetInputPtrSelect = 0x002C
kGraphicsExportSetInputGraphicsImporterSelect = 0x002D
kGraphicsExportGetInputGraphicsImporterSelect = 0x002E
kGraphicsExportSetInputPictureSelect = 0x002F
kGraphicsExportGetInputPictureSelect = 0x0030
kGraphicsExportSetInputGWorldSelect = 0x0031
kGraphicsExportGetInputGWorldSelect = 0x0032
kGraphicsExportSetInputPixmapSelect = 0x0033
kGraphicsExportGetInputPixmapSelect = 0x0034
kGraphicsExportSetInputOffsetAndLimitSelect = 0x0035
kGraphicsExportGetInputOffsetAndLimitSelect = 0x0036
kGraphicsExportMayExporterReadInputDataSelect = 0x0037
kGraphicsExportGetInputDataSizeSelect = 0x0038
kGraphicsExportReadInputDataSelect = 0x0039
kGraphicsExportGetInputImageDescriptionSelect = 0x003A
kGraphicsExportGetInputImageDimensionsSelect = 0x003B
kGraphicsExportGetInputImageDepthSelect = 0x003C
kGraphicsExportDrawInputImageSelect = 0x003D
kGraphicsExportSetOutputDataReferenceSelect = 0x003E
kGraphicsExportGetOutputDataReferenceSelect = 0x003F
kGraphicsExportSetOutputFileSelect = 0x0040
kGraphicsExportGetOutputFileSelect = 0x0041
kGraphicsExportSetOutputHandleSelect = 0x0042
kGraphicsExportGetOutputHandleSelect = 0x0043
kGraphicsExportSetOutputOffsetAndMaxSizeSelect = 0x0044
kGraphicsExportGetOutputOffsetAndMaxSizeSelect = 0x0045
kGraphicsExportSetOutputFileTypeAndCreatorSelect = 0x0046
kGraphicsExportGetOutputFileTypeAndCreatorSelect = 0x0047
kGraphicsExportWriteOutputDataSelect = 0x0048
kGraphicsExportSetOutputMarkSelect = 0x0049
kGraphicsExportGetOutputMarkSelect = 0x004A
kGraphicsExportReadOutputDataSelect = 0x004B
kGraphicsExportSetThumbnailEnabledSelect = 0x004C
kGraphicsExportGetThumbnailEnabledSelect = 0x004D
kGraphicsExportSetExifEnabledSelect = 0x004E
kGraphicsExportGetExifEnabledSelect = 0x004F
kImageTranscoderBeginSequenceSelect = 0x0001
kImageTranscoderConvertSelect = 0x0002
kImageTranscoderDisposeDataSelect = 0x0003
kImageTranscoderEndSequenceSelect = 0x0004
clockComponentType = FOUR_CHAR_CODE('clok')
systemTickClock = FOUR_CHAR_CODE('tick')
systemSecondClock = FOUR_CHAR_CODE('seco')
systemMillisecondClock = FOUR_CHAR_CODE('mill')
systemMicrosecondClock = FOUR_CHAR_CODE('micr')
kClockRateIsLinear = 1
kClockImplementsCallBacks = 2
kClockCanHandleIntermittentSound = 4
StandardCompressionType = FOUR_CHAR_CODE('scdi')
StandardCompressionSubType = FOUR_CHAR_CODE('imag')
StandardCompressionSubTypeSound = FOUR_CHAR_CODE('soun')
scListEveryCodec = 1L << 1
scAllowZeroFrameRate = 1L << 2
scAllowZeroKeyFrameRate = 1L << 3
scShowBestDepth = 1L << 4
scUseMovableModal = 1L << 5
scDisableFrameRateItem = 1L << 6
scShowDataRateAsKilobits = 1L << 7
scPreferCropping = 1 << 0
scPreferScaling = 1 << 1
scPreferScalingAndCropping = scPreferScaling | scPreferCropping
scDontDetermineSettingsFromTestImage = 1 << 2
scTestImageWidth = 80
scTestImageHeight = 80
scOKItem = 1
scCancelItem = 2
scCustomItem = 3
scUserCancelled = 1
scPositionRect = 2
scPositionDialog = 3
scSetTestImagePictHandle = 4
scSetTestImagePictFile = 5
scSetTestImagePixMap = 6
scGetBestDeviceRect = 7
scRequestImageSettings = 10
scCompressImage = 11
scCompressPicture = 12
scCompressPictureFile = 13
scRequestSequenceSettings = 14
scCompressSequenceBegin = 15
scCompressSequenceFrame = 16
scCompressSequenceEnd = 17
scDefaultPictHandleSettings = 18
scDefaultPictFileSettings = 19
scDefaultPixMapSettings = 20
scGetInfo = 21
scSetInfo = 22
scNewGWorld = 23
scSpatialSettingsType = FOUR_CHAR_CODE('sptl')
scTemporalSettingsType = FOUR_CHAR_CODE('tprl')
scDataRateSettingsType = FOUR_CHAR_CODE('drat')
scColorTableType = FOUR_CHAR_CODE('clut')
scProgressProcType = FOUR_CHAR_CODE('prog')
scExtendedProcsType = FOUR_CHAR_CODE('xprc')
scPreferenceFlagsType = FOUR_CHAR_CODE('pref')
scSettingsStateType = FOUR_CHAR_CODE('ssta')
scSequenceIDType = FOUR_CHAR_CODE('sequ')
scWindowPositionType = FOUR_CHAR_CODE('wndw')
scCodecFlagsType = FOUR_CHAR_CODE('cflg')
scCodecSettingsType = FOUR_CHAR_CODE('cdec')
scForceKeyValueType = FOUR_CHAR_CODE('ksim')
scSoundSampleRateType = FOUR_CHAR_CODE('ssrt')
scSoundSampleSizeType = FOUR_CHAR_CODE('ssss')
scSoundChannelCountType = FOUR_CHAR_CODE('sscc')
scSoundCompressionType = FOUR_CHAR_CODE('ssct')
scCompressionListType = FOUR_CHAR_CODE('ctyl')
scCodecManufacturerType = FOUR_CHAR_CODE('cmfr')
scSoundVBRCompressionOK = FOUR_CHAR_CODE('cvbr')
scSoundInputSampleRateType = FOUR_CHAR_CODE('ssir')
scSoundSampleRateChangeOK = FOUR_CHAR_CODE('rcok')
scAvailableCompressionListType = FOUR_CHAR_CODE('avai')
scGetCompression = 1
scShowMotionSettings = 1L << 0
scSettingsChangedItem = -1
scCompressFlagIgnoreIdenticalFrames = 1
kQTSettingsVideo = FOUR_CHAR_CODE('vide')
kQTSettingsSound = FOUR_CHAR_CODE('soun')
kQTSettingsComponentVersion = FOUR_CHAR_CODE('vers')
TweenComponentType = FOUR_CHAR_CODE('twen')
TCSourceRefNameType = FOUR_CHAR_CODE('name')
tcDropFrame = 1 << 0
tc24HourMax = 1 << 1
tcNegTimesOK = 1 << 2
tcCounter = 1 << 3
tctNegFlag = 0x80
tcdfShowTimeCode = 1 << 0
MovieImportType = FOUR_CHAR_CODE('eat ')
MovieExportType = FOUR_CHAR_CODE('spit')
canMovieImportHandles = 1 << 0
canMovieImportFiles = 1 << 1
hasMovieImportUserInterface = 1 << 2
canMovieExportHandles = 1 << 3
canMovieExportFiles = 1 << 4
hasMovieExportUserInterface = 1 << 5
movieImporterIsXMLBased = 1 << 5
dontAutoFileMovieImport = 1 << 6
canMovieExportAuxDataHandle = 1 << 7
canMovieImportValidateHandles = 1 << 8
canMovieImportValidateFile = 1 << 9
dontRegisterWithEasyOpen = 1 << 10
canMovieImportInPlace = 1 << 11
movieImportSubTypeIsFileExtension = 1 << 12
canMovieImportPartial = 1 << 13
hasMovieImportMIMEList = 1 << 14
canMovieImportAvoidBlocking = 1 << 15
canMovieExportFromProcedures = 1 << 15
canMovieExportValidateMovie = 1L << 16
movieImportMustGetDestinationMediaType = 1L << 16
movieExportNeedsResourceFork = 1L << 17
canMovieImportDataReferences = 1L << 18
movieExportMustGetSourceMediaType = 1L << 19
canMovieImportWithIdle = 1L << 20
canMovieImportValidateDataReferences = 1L << 21
reservedForUseByGraphicsImporters = 1L << 23
movieImportCreateTrack = 1
movieImportInParallel = 2
movieImportMustUseTrack = 4
movieImportWithIdle = 16
movieImportResultUsedMultipleTracks = 8
movieImportResultNeedIdles = 32
movieImportResultComplete = 64
kMovieExportTextOnly = 0
kMovieExportAbsoluteTime = 1
kMovieExportRelativeTime = 2
kMIDIImportSilenceBefore = 1 << 0
kMIDIImportSilenceAfter = 1 << 1
kMIDIImport20Playable = 1 << 2
kMIDIImportWantLyrics = 1 << 3
kQTMediaConfigResourceType = FOUR_CHAR_CODE('mcfg')
kQTMediaConfigResourceVersion = 2
kQTMediaGroupResourceType = FOUR_CHAR_CODE('mgrp')
kQTMediaGroupResourceVersion = 1
kQTBrowserInfoResourceType = FOUR_CHAR_CODE('brws')
kQTBrowserInfoResourceVersion = 1
kQTMediaMIMEInfoHasChanged = (1L << 1)
kQTMediaFileInfoHasChanged = (1L << 2)
kQTMediaConfigCanUseApp = (1L << 18)
kQTMediaConfigCanUsePlugin = (1L << 19)
kQTMediaConfigUNUSED = (1L << 20)
kQTMediaConfigBinaryFile = (1L << 23)
kQTMediaConfigTextFile = 0
kQTMediaConfigMacintoshFile = (1L << 24)
kQTMediaConfigAssociateByDefault = (1L << 27)
kQTMediaConfigUseAppByDefault = (1L << 28)
kQTMediaConfigUsePluginByDefault = (1L << 29)
kQTMediaConfigDefaultsMask = (kQTMediaConfigUseAppByDefault | kQTMediaConfigUsePluginByDefault)
kQTMediaConfigDefaultsShift = 12
kQTMediaConfigHasFileHasQTAtoms = (1L << 30)
kQTMediaConfigStreamGroupID = FOUR_CHAR_CODE('strm')
kQTMediaConfigInteractiveGroupID = FOUR_CHAR_CODE('intr')
kQTMediaConfigVideoGroupID = FOUR_CHAR_CODE('eyes')
kQTMediaConfigAudioGroupID = FOUR_CHAR_CODE('ears')
kQTMediaConfigMPEGGroupID = FOUR_CHAR_CODE('mpeg')
kQTMediaConfigMP3GroupID = FOUR_CHAR_CODE('mp3 ')
kQTMediaConfigImageGroupID = FOUR_CHAR_CODE('ogle')
kQTMediaConfigMiscGroupID = FOUR_CHAR_CODE('misc')
kQTMediaInfoNetGroup = FOUR_CHAR_CODE('net ')
kQTMediaInfoWinGroup = FOUR_CHAR_CODE('win ')
kQTMediaInfoMacGroup = FOUR_CHAR_CODE('mac ')
kQTMediaInfoMiscGroup = 0x3F3F3F3F
kMimeInfoMimeTypeTag = FOUR_CHAR_CODE('mime')
kMimeInfoFileExtensionTag = FOUR_CHAR_CODE('ext ')
kMimeInfoDescriptionTag = FOUR_CHAR_CODE('desc')
kMimeInfoGroupTag = FOUR_CHAR_CODE('grop')
kMimeInfoDoNotOverrideExistingFileTypeAssociation = FOUR_CHAR_CODE('nofa')
kQTFileTypeAIFF = FOUR_CHAR_CODE('AIFF')
kQTFileTypeAIFC = FOUR_CHAR_CODE('AIFC')
kQTFileTypeDVC = FOUR_CHAR_CODE('dvc!')
kQTFileTypeMIDI = FOUR_CHAR_CODE('Midi')
kQTFileTypePicture = FOUR_CHAR_CODE('PICT')
kQTFileTypeMovie = FOUR_CHAR_CODE('MooV')
kQTFileTypeText = FOUR_CHAR_CODE('TEXT')
kQTFileTypeWave = FOUR_CHAR_CODE('WAVE')
kQTFileTypeSystemSevenSound = FOUR_CHAR_CODE('sfil')
kQTFileTypeMuLaw = FOUR_CHAR_CODE('ULAW')
kQTFileTypeAVI = FOUR_CHAR_CODE('VfW ')
kQTFileTypeSoundDesignerII = FOUR_CHAR_CODE('Sd2f')
kQTFileTypeAudioCDTrack = FOUR_CHAR_CODE('trak')
kQTFileTypePICS = FOUR_CHAR_CODE('PICS')
kQTFileTypeGIF = FOUR_CHAR_CODE('GIFf')
kQTFileTypePNG = FOUR_CHAR_CODE('PNGf')
kQTFileTypeTIFF = FOUR_CHAR_CODE('TIFF')
kQTFileTypePhotoShop = FOUR_CHAR_CODE('8BPS')
kQTFileTypeSGIImage = FOUR_CHAR_CODE('.SGI')
kQTFileTypeBMP = FOUR_CHAR_CODE('BMPf')
kQTFileTypeJPEG = FOUR_CHAR_CODE('JPEG')
kQTFileTypeJFIF = FOUR_CHAR_CODE('JPEG')
kQTFileTypeMacPaint = FOUR_CHAR_CODE('PNTG')
kQTFileTypeTargaImage = FOUR_CHAR_CODE('TPIC')
kQTFileTypeQuickDrawGXPicture = FOUR_CHAR_CODE('qdgx')
kQTFileTypeQuickTimeImage = FOUR_CHAR_CODE('qtif')
kQTFileType3DMF = FOUR_CHAR_CODE('3DMF')
kQTFileTypeFLC = FOUR_CHAR_CODE('FLC ')
kQTFileTypeFlash = FOUR_CHAR_CODE('SWFL')
kQTFileTypeFlashPix = FOUR_CHAR_CODE('FPix')
kQTFileTypeMP4 = FOUR_CHAR_CODE('mpg4')
kQTSettingsDVExportNTSC = FOUR_CHAR_CODE('dvcv')
kQTSettingsDVExportLockedAudio = FOUR_CHAR_CODE('lock')
kQTSettingsEffect = FOUR_CHAR_CODE('effe')
kQTSettingsGraphicsFileImportSequence = FOUR_CHAR_CODE('sequ')
kQTSettingsGraphicsFileImportSequenceEnabled = FOUR_CHAR_CODE('enab')
kQTSettingsMovieExportEnableVideo = FOUR_CHAR_CODE('envi')
kQTSettingsMovieExportEnableSound = FOUR_CHAR_CODE('enso')
kQTSettingsMovieExportSaveOptions = FOUR_CHAR_CODE('save')
kQTSettingsMovieExportSaveForInternet = FOUR_CHAR_CODE('fast')
kQTSettingsMovieExportSaveCompressedMovie = FOUR_CHAR_CODE('cmpm')
kQTSettingsMIDI = FOUR_CHAR_CODE('MIDI')
kQTSettingsMIDISettingFlags = FOUR_CHAR_CODE('sttg')
kQTSettingsText = FOUR_CHAR_CODE('text')
kQTSettingsTextDescription = FOUR_CHAR_CODE('desc')
kQTSettingsTextSize = FOUR_CHAR_CODE('size')
kQTSettingsTextSettingFlags = FOUR_CHAR_CODE('sttg')
kQTSettingsTextTimeFraction = FOUR_CHAR_CODE('timf')
kQTSettingsTime = FOUR_CHAR_CODE('time')
kQTSettingsTimeDuration = FOUR_CHAR_CODE('dura')
kQTSettingsAudioCDTrack = FOUR_CHAR_CODE('trak')
kQTSettingsAudioCDTrackRateShift = FOUR_CHAR_CODE('rshf')
kQTSettingsDVExportDVFormat = FOUR_CHAR_CODE('dvcf')
kQTPresetsListResourceType = FOUR_CHAR_CODE('stg#')
kQTPresetsPlatformListResourceType = FOUR_CHAR_CODE('stgp')
kQTPresetInfoIsDivider = 1
kQTMovieExportSourceInfoResourceType = FOUR_CHAR_CODE('src#')
kQTMovieExportSourceInfoIsMediaType = 1L << 0
kQTMovieExportSourceInfoIsMediaCharacteristic = 1L << 1
kQTMovieExportSourceInfoIsSourceType = 1L << 2
movieExportUseConfiguredSettings = FOUR_CHAR_CODE('ucfg')
movieExportWidth = FOUR_CHAR_CODE('wdth')
movieExportHeight = FOUR_CHAR_CODE('hegt')
movieExportDuration = FOUR_CHAR_CODE('dura')
movieExportVideoFilter = FOUR_CHAR_CODE('iflt')
movieExportTimeScale = FOUR_CHAR_CODE('tmsc')
kQTBrowserInfoCanUseSystemFolderPlugin = (1L << 0)
kQTPreFlightOpenComponent = (1L << 1)
pnotComponentWantsEvents = 1
pnotComponentNeedsNoCache = 2
ShowFilePreviewComponentType = FOUR_CHAR_CODE('pnot')
CreateFilePreviewComponentType = FOUR_CHAR_CODE('pmak')
DataCompressorComponentType = FOUR_CHAR_CODE('dcom')
DataDecompressorComponentType = FOUR_CHAR_CODE('ddec')
AppleDataCompressorSubType = FOUR_CHAR_CODE('adec')
zlibDataCompressorSubType = FOUR_CHAR_CODE('zlib')
kDataHCanRead = 1L << 0
kDataHSpecialRead = 1L << 1
kDataHSpecialReadFile = 1L << 2
kDataHCanWrite = 1L << 3
kDataHSpecialWrite = 1 << 4
kDataHSpecialWriteFile = 1 << 5
kDataHCanStreamingWrite = 1 << 6
kDataHMustCheckDataRef = 1 << 7
kDataRefExtensionChokeSpeed = FOUR_CHAR_CODE('chok')
kDataRefExtensionFileName = FOUR_CHAR_CODE('fnam')
kDataRefExtensionMIMEType = FOUR_CHAR_CODE('mime')
kDataRefExtensionMacOSFileType = FOUR_CHAR_CODE('ftyp')
kDataRefExtensionInitializationData = FOUR_CHAR_CODE('data')
kDataRefExtensionQuickTimeMediaType = FOUR_CHAR_CODE('mtyp')
kDataHChokeToMovieDataRate = 1 << 0
kDataHChokeToParam = 1 << 1
kDataHExtendedSchedule = FOUR_CHAR_CODE('xtnd')
kDataHInfoFlagNeverStreams = 1 << 0
kDataHInfoFlagCanUpdateDataRefs = 1 << 1
kDataHInfoFlagNeedsNetworkBandwidth = 1 << 2
kDataHFileTypeMacOSFileType = FOUR_CHAR_CODE('ftyp')
kDataHFileTypeExtension = FOUR_CHAR_CODE('fext')
kDataHFileTypeMIME = FOUR_CHAR_CODE('mime')
kDataHCreateFileButDontCreateResFile = (1L << 0)
kDataHMovieUsageDoAppendMDAT = 1L << 0
kDataHTempUseSameDirectory = 1L << 0
kDataHTempUseSameVolume = 1L << 1
kDataHTempCreateFile = 1L << 2
kDataHTempOpenFile = 1L << 3
kDataHGetDataRateInfiniteRate = 0x7FFFFFFF
kDataHSetTimeHintsSkipBandwidthRequest = 1 << 0
videoDigitizerComponentType = FOUR_CHAR_CODE('vdig')
vdigInterfaceRev = 2
ntscIn = 0
currentIn = 0
palIn = 1
secamIn = 2
ntscReallyIn = 3
compositeIn = 0
sVideoIn = 1
rgbComponentIn = 2
rgbComponentSyncIn = 3
yuvComponentIn = 4
yuvComponentSyncIn = 5
tvTunerIn = 6
sdiIn = 7
vdPlayThruOff = 0
vdPlayThruOn = 1
vdDigitizerBW = 0
vdDigitizerRGB = 1
vdBroadcastMode = 0
vdVTRMode = 1
vdUseAnyField = 0
vdUseOddField = 1
vdUseEvenField = 2
vdTypeBasic = 0
vdTypeAlpha = 1
vdTypeMask = 2
vdTypeKey = 3
digiInDoesNTSC = 1L << 0
digiInDoesPAL = 1L << 1
digiInDoesSECAM = 1L << 2
digiInDoesGenLock = 1L << 7
digiInDoesComposite = 1L << 8
digiInDoesSVideo = 1L << 9
digiInDoesComponent = 1L << 10
digiInVTR_Broadcast = 1L << 11
digiInDoesColor = 1L << 12
digiInDoesBW = 1L << 13
digiInSignalLock = 1L << 31
digiOutDoes1 = 1L << 0
digiOutDoes2 = 1L << 1
digiOutDoes4 = 1L << 2
digiOutDoes8 = 1L << 3
digiOutDoes16 = 1L << 4
digiOutDoes32 = 1L << 5
digiOutDoesDither = 1L << 6
digiOutDoesStretch = 1L << 7
digiOutDoesShrink = 1L << 8
digiOutDoesMask = 1L << 9
digiOutDoesDouble = 1L << 11
digiOutDoesQuad = 1L << 12
digiOutDoesQuarter = 1L << 13
digiOutDoesSixteenth = 1L << 14
digiOutDoesRotate = 1L << 15
digiOutDoesHorizFlip = 1L << 16
digiOutDoesVertFlip = 1L << 17
digiOutDoesSkew = 1L << 18
digiOutDoesBlend = 1L << 19
digiOutDoesWarp = 1L << 20
digiOutDoesHW_DMA = 1L << 21
digiOutDoesHWPlayThru = 1L << 22
digiOutDoesILUT = 1L << 23
digiOutDoesKeyColor = 1L << 24
digiOutDoesAsyncGrabs = 1L << 25
digiOutDoesUnreadableScreenBits = 1L << 26
digiOutDoesCompress = 1L << 27
digiOutDoesCompressOnly = 1L << 28
digiOutDoesPlayThruDuringCompress = 1L << 29
digiOutDoesCompressPartiallyVisible = 1L << 30
digiOutDoesNotNeedCopyOfCompressData = 1L << 31
dmaDepth1 = 1
dmaDepth2 = 2
dmaDepth4 = 4
dmaDepth8 = 8
dmaDepth16 = 16
dmaDepth32 = 32
dmaDepth2Gray = 64
dmaDepth4Gray = 128
dmaDepth8Gray = 256
kVDIGControlledFrameRate = -1
vdDeviceFlagShowInputsAsDevices = (1 << 0)
vdDeviceFlagHideDevice = (1 << 1)
vdFlagCaptureStarting = (1 << 0)
vdFlagCaptureStopping = (1 << 1)
vdFlagCaptureIsForPreview = (1 << 2)
vdFlagCaptureIsForRecord = (1 << 3)
vdFlagCaptureLowLatency = (1 << 4)
vdFlagCaptureAlwaysUseTimeBase = (1 << 5)
vdFlagCaptureSetSettingsBegin = (1 << 6)
vdFlagCaptureSetSettingsEnd = (1 << 7)
xmlParseComponentType = FOUR_CHAR_CODE('pars')
xmlParseComponentSubType = FOUR_CHAR_CODE('xml ')
xmlIdentifierInvalid = 0
# xmlIdentifierUnrecognized = (long)0xFFFFFFFF
xmlContentTypeInvalid = 0
xmlContentTypeElement = 1
xmlContentTypeCharData = 2
elementFlagAlwaysSelfContained = 1L << 0
elementFlagPreserveWhiteSpace = 1L << 1
xmlParseFlagAllowUppercase = 1L << 0
xmlParseFlagAllowUnquotedAttributeValues = 1L << 1
xmlParseFlagEventParseOnly = 1L << 2
attributeValueKindCharString = 0
attributeValueKindInteger = 1L << 0
attributeValueKindPercent = 1L << 1
attributeValueKindBoolean = 1L << 2
attributeValueKindOnOff = 1L << 3
attributeValueKindColor = 1L << 4
attributeValueKindEnum = 1L << 5
attributeValueKindCaseSensEnum = 1L << 6
MAX_ATTRIBUTE_VALUE_KIND = attributeValueKindCaseSensEnum
nameSpaceIDNone = 0
element_xml = 1
attr_src = 1
SeqGrabComponentType = FOUR_CHAR_CODE('barg')
SeqGrabChannelType = FOUR_CHAR_CODE('sgch')
SeqGrabPanelType = FOUR_CHAR_CODE('sgpn')
SeqGrabCompressionPanelType = FOUR_CHAR_CODE('cmpr')
SeqGrabSourcePanelType = FOUR_CHAR_CODE('sour')
seqGrabToDisk = 1
seqGrabToMemory = 2
seqGrabDontUseTempMemory = 4
seqGrabAppendToFile = 8
seqGrabDontAddMovieResource = 16
seqGrabDontMakeMovie = 32
seqGrabPreExtendFile = 64
seqGrabDataProcIsInterruptSafe = 128
seqGrabDataProcDoesOverlappingReads = 256
seqGrabRecord = 1
seqGrabPreview = 2
seqGrabPlayDuringRecord = 4
seqGrabLowLatencyCapture = 8
seqGrabAlwaysUseTimeBase = 16
seqGrabHasBounds = 1
seqGrabHasVolume = 2
seqGrabHasDiscreteSamples = 4
seqGrabDoNotBufferizeData = 8
seqGrabCanMoveWindowWhileRecording = 16
grabPictOffScreen = 1
grabPictIgnoreClip = 2
grabPictCurrentImage = 4
sgFlagControlledGrab = (1 << 0)
sgFlagAllowNonRGBPixMaps = (1 << 1)
sgDeviceInputNameFlagInputUnavailable = (1 << 0)
sgDeviceNameFlagDeviceUnavailable = (1 << 0)
sgDeviceNameFlagShowInputsAsDevices = (1 << 1)
sgDeviceListWithIcons = (1 << 0)
sgDeviceListDontCheckAvailability = (1 << 1)
sgDeviceListIncludeInputs = (1 << 2)
seqGrabWriteAppend = 0
seqGrabWriteReserve = 1
seqGrabWriteFill = 2
seqGrabUnpause = 0
seqGrabPause = 1
seqGrabPauseForMenu = 3
channelFlagDontOpenResFile = 2
channelFlagHasDependency = 4
sgPanelFlagForPanel = 1
seqGrabSettingsPreviewOnly = 1
channelPlayNormal = 0
channelPlayFast = 1
channelPlayHighQuality = 2
channelPlayAllData = 4
sgSetSettingsBegin = (1 << 0)
sgSetSettingsEnd = (1 << 1)
kSGSmallestDITLSize = -1
kSGLargestDITLSize = -2
sgChannelAtom = FOUR_CHAR_CODE('chan')
sgChannelSettingsAtom = FOUR_CHAR_CODE('ctom')
sgChannelDescription = FOUR_CHAR_CODE('cdsc')
sgChannelSettings = FOUR_CHAR_CODE('cset')
sgDeviceNameType = FOUR_CHAR_CODE('name')
sgDeviceDisplayNameType = FOUR_CHAR_CODE('dnam')
sgDeviceUIDType = FOUR_CHAR_CODE('duid')
sgInputUIDType = FOUR_CHAR_CODE('iuid')
sgUsageType = FOUR_CHAR_CODE('use ')
sgPlayFlagsType = FOUR_CHAR_CODE('plyf')
sgClipType = FOUR_CHAR_CODE('clip')
sgMatrixType = FOUR_CHAR_CODE('mtrx')
sgVolumeType = FOUR_CHAR_CODE('volu')
sgPanelSettingsAtom = FOUR_CHAR_CODE('ptom')
sgPanelDescription = FOUR_CHAR_CODE('pdsc')
sgPanelSettings = FOUR_CHAR_CODE('pset')
sgcSoundCompressionType = FOUR_CHAR_CODE('scmp')
sgcSoundCodecSettingsType = FOUR_CHAR_CODE('cdec')
sgcSoundSampleRateType = FOUR_CHAR_CODE('srat')
sgcSoundChannelCountType = FOUR_CHAR_CODE('schn')
sgcSoundSampleSizeType = FOUR_CHAR_CODE('ssiz')
sgcSoundInputType = FOUR_CHAR_CODE('sinp')
sgcSoundGainType = FOUR_CHAR_CODE('gain')
sgcVideoHueType = FOUR_CHAR_CODE('hue ')
sgcVideoSaturationType = FOUR_CHAR_CODE('satr')
sgcVideoContrastType = FOUR_CHAR_CODE('trst')
sgcVideoSharpnessType = FOUR_CHAR_CODE('shrp')
sgcVideoBrigtnessType = FOUR_CHAR_CODE('brit')
sgcVideoBlackLevelType = FOUR_CHAR_CODE('blkl')
sgcVideoWhiteLevelType = FOUR_CHAR_CODE('whtl')
sgcVideoInputType = FOUR_CHAR_CODE('vinp')
sgcVideoFormatType = FOUR_CHAR_CODE('vstd')
sgcVideoFilterType = FOUR_CHAR_CODE('vflt')
sgcVideoRectType = FOUR_CHAR_CODE('vrct')
sgcVideoDigitizerType = FOUR_CHAR_CODE('vdig')
QTVideoOutputComponentType = FOUR_CHAR_CODE('vout')
QTVideoOutputComponentBaseSubType = FOUR_CHAR_CODE('base')
kQTVideoOutputDontDisplayToUser = 1L << 0
kQTVODisplayModeItem = FOUR_CHAR_CODE('qdmi')
kQTVODimensions = FOUR_CHAR_CODE('dimn')
kQTVOResolution = FOUR_CHAR_CODE('resl')
kQTVORefreshRate = FOUR_CHAR_CODE('refr')
kQTVOPixelType = FOUR_CHAR_CODE('pixl')
kQTVOName = FOUR_CHAR_CODE('name')
kQTVODecompressors = FOUR_CHAR_CODE('deco')
kQTVODecompressorType = FOUR_CHAR_CODE('dety')
kQTVODecompressorContinuous = FOUR_CHAR_CODE('cont')
kQTVODecompressorComponent = FOUR_CHAR_CODE('cmpt')
kClockGetTimeSelect = 0x0001
kClockNewCallBackSelect = 0x0002
kClockDisposeCallBackSelect = 0x0003
kClockCallMeWhenSelect = 0x0004
kClockCancelCallBackSelect = 0x0005
kClockRateChangedSelect = 0x0006
kClockTimeChangedSelect = 0x0007
kClockSetTimeBaseSelect = 0x0008
kClockStartStopChangedSelect = 0x0009
kClockGetRateSelect = 0x000A
kSCGetCompressionExtendedSelect = 0x0001
kSCPositionRectSelect = 0x0002
kSCPositionDialogSelect = 0x0003
kSCSetTestImagePictHandleSelect = 0x0004
kSCSetTestImagePictFileSelect = 0x0005
kSCSetTestImagePixMapSelect = 0x0006
kSCGetBestDeviceRectSelect = 0x0007
kSCRequestImageSettingsSelect = 0x000A
kSCCompressImageSelect = 0x000B
kSCCompressPictureSelect = 0x000C
kSCCompressPictureFileSelect = 0x000D
kSCRequestSequenceSettingsSelect = 0x000E
kSCCompressSequenceBeginSelect = 0x000F
kSCCompressSequenceFrameSelect = 0x0010
kSCCompressSequenceEndSelect = 0x0011
kSCDefaultPictHandleSettingsSelect = 0x0012
kSCDefaultPictFileSettingsSelect = 0x0013
kSCDefaultPixMapSettingsSelect = 0x0014
kSCGetInfoSelect = 0x0015
kSCSetInfoSelect = 0x0016
kSCNewGWorldSelect = 0x0017
kSCSetCompressFlagsSelect = 0x0018
kSCGetCompressFlagsSelect = 0x0019
kSCGetSettingsAsTextSelect = 0x001A
kSCGetSettingsAsAtomContainerSelect = 0x001B
kSCSetSettingsFromAtomContainerSelect = 0x001C
kSCCompressSequenceFrameAsyncSelect = 0x001D
kSCAsyncIdleSelect = 0x001E
kTweenerInitializeSelect = 0x0001
kTweenerDoTweenSelect = 0x0002
kTweenerResetSelect = 0x0003
kTCGetCurrentTimeCodeSelect = 0x0101
kTCGetTimeCodeAtTimeSelect = 0x0102
kTCTimeCodeToStringSelect = 0x0103
kTCTimeCodeToFrameNumberSelect = 0x0104
kTCFrameNumberToTimeCodeSelect = 0x0105
kTCGetSourceRefSelect = 0x0106
kTCSetSourceRefSelect = 0x0107
kTCSetTimeCodeFlagsSelect = 0x0108
kTCGetTimeCodeFlagsSelect = 0x0109
kTCSetDisplayOptionsSelect = 0x010A
kTCGetDisplayOptionsSelect = 0x010B
kMovieImportHandleSelect = 0x0001
kMovieImportFileSelect = 0x0002
kMovieImportSetSampleDurationSelect = 0x0003
kMovieImportSetSampleDescriptionSelect = 0x0004
kMovieImportSetMediaFileSelect = 0x0005
kMovieImportSetDimensionsSelect = 0x0006
kMovieImportSetChunkSizeSelect = 0x0007
kMovieImportSetProgressProcSelect = 0x0008
kMovieImportSetAuxiliaryDataSelect = 0x0009
kMovieImportSetFromScrapSelect = 0x000A
kMovieImportDoUserDialogSelect = 0x000B
kMovieImportSetDurationSelect = 0x000C
kMovieImportGetAuxiliaryDataTypeSelect = 0x000D
kMovieImportValidateSelect = 0x000E
kMovieImportGetFileTypeSelect = 0x000F
kMovieImportDataRefSelect = 0x0010
kMovieImportGetSampleDescriptionSelect = 0x0011
kMovieImportGetMIMETypeListSelect = 0x0012
kMovieImportSetOffsetAndLimitSelect = 0x0013
kMovieImportGetSettingsAsAtomContainerSelect = 0x0014
kMovieImportSetSettingsFromAtomContainerSelect = 0x0015
kMovieImportSetOffsetAndLimit64Select = 0x0016
kMovieImportIdleSelect = 0x0017
kMovieImportValidateDataRefSelect = 0x0018
kMovieImportGetLoadStateSelect = 0x0019
kMovieImportGetMaxLoadedTimeSelect = 0x001A
kMovieImportEstimateCompletionTimeSelect = 0x001B
kMovieImportSetDontBlockSelect = 0x001C
kMovieImportGetDontBlockSelect = 0x001D
kMovieImportSetIdleManagerSelect = 0x001E
kMovieImportSetNewMovieFlagsSelect = 0x001F
kMovieImportGetDestinationMediaTypeSelect = 0x0020
kMovieExportToHandleSelect = 0x0080
kMovieExportToFileSelect = 0x0081
kMovieExportGetAuxiliaryDataSelect = 0x0083
kMovieExportSetProgressProcSelect = 0x0084
kMovieExportSetSampleDescriptionSelect = 0x0085
kMovieExportDoUserDialogSelect = 0x0086
kMovieExportGetCreatorTypeSelect = 0x0087
kMovieExportToDataRefSelect = 0x0088
kMovieExportFromProceduresToDataRefSelect = 0x0089
kMovieExportAddDataSourceSelect = 0x008A
kMovieExportValidateSelect = 0x008B
kMovieExportGetSettingsAsAtomContainerSelect = 0x008C
kMovieExportSetSettingsFromAtomContainerSelect = 0x008D
kMovieExportGetFileNameExtensionSelect = 0x008E
kMovieExportGetShortFileTypeStringSelect = 0x008F
kMovieExportGetSourceMediaTypeSelect = 0x0090
kMovieExportSetGetMoviePropertyProcSelect = 0x0091
kTextExportGetDisplayDataSelect = 0x0100
kTextExportGetTimeFractionSelect = 0x0101
kTextExportSetTimeFractionSelect = 0x0102
kTextExportGetSettingsSelect = 0x0103
kTextExportSetSettingsSelect = 0x0104
kMIDIImportGetSettingsSelect = 0x0100
kMIDIImportSetSettingsSelect = 0x0101
kMovieExportNewGetDataAndPropertiesProcsSelect = 0x0100
kMovieExportDisposeGetDataAndPropertiesProcsSelect = 0x0101
kGraphicsImageImportSetSequenceEnabledSelect = 0x0100
kGraphicsImageImportGetSequenceEnabledSelect = 0x0101
kPreviewShowDataSelect = 0x0001
kPreviewMakePreviewSelect = 0x0002
kPreviewMakePreviewReferenceSelect = 0x0003
kPreviewEventSelect = 0x0004
kDataCodecDecompressSelect = 0x0001
kDataCodecGetCompressBufferSizeSelect = 0x0002
kDataCodecCompressSelect = 0x0003
kDataCodecBeginInterruptSafeSelect = 0x0004
kDataCodecEndInterruptSafeSelect = 0x0005
kDataCodecDecompressPartialSelect = 0x0006
kDataCodecCompressPartialSelect = 0x0007
kDataHGetDataSelect = 0x0002
kDataHPutDataSelect = 0x0003
kDataHFlushDataSelect = 0x0004
kDataHOpenForWriteSelect = 0x0005
kDataHCloseForWriteSelect = 0x0006
kDataHOpenForReadSelect = 0x0008
kDataHCloseForReadSelect = 0x0009
kDataHSetDataRefSelect = 0x000A
kDataHGetDataRefSelect = 0x000B
kDataHCompareDataRefSelect = 0x000C
kDataHTaskSelect = 0x000D
kDataHScheduleDataSelect = 0x000E
kDataHFinishDataSelect = 0x000F
kDataHFlushCacheSelect = 0x0010
kDataHResolveDataRefSelect = 0x0011
kDataHGetFileSizeSelect = 0x0012
kDataHCanUseDataRefSelect = 0x0013
kDataHGetVolumeListSelect = 0x0014
kDataHWriteSelect = 0x0015
kDataHPreextendSelect = 0x0016
kDataHSetFileSizeSelect = 0x0017
kDataHGetFreeSpaceSelect = 0x0018
kDataHCreateFileSelect = 0x0019
kDataHGetPreferredBlockSizeSelect = 0x001A
kDataHGetDeviceIndexSelect = 0x001B
kDataHIsStreamingDataHandlerSelect = 0x001C
kDataHGetDataInBufferSelect = 0x001D
kDataHGetScheduleAheadTimeSelect = 0x001E
kDataHSetCacheSizeLimitSelect = 0x001F
kDataHGetCacheSizeLimitSelect = 0x0020
kDataHGetMovieSelect = 0x0021
kDataHAddMovieSelect = 0x0022
kDataHUpdateMovieSelect = 0x0023
kDataHDoesBufferSelect = 0x0024
kDataHGetFileNameSelect = 0x0025
kDataHGetAvailableFileSizeSelect = 0x0026
kDataHGetMacOSFileTypeSelect = 0x0027
kDataHGetMIMETypeSelect = 0x0028
kDataHSetDataRefWithAnchorSelect = 0x0029
kDataHGetDataRefWithAnchorSelect = 0x002A
kDataHSetMacOSFileTypeSelect = 0x002B
kDataHSetTimeBaseSelect = 0x002C
kDataHGetInfoFlagsSelect = 0x002D
kDataHScheduleData64Select = 0x002E
kDataHWrite64Select = 0x002F
kDataHGetFileSize64Select = 0x0030
kDataHPreextend64Select = 0x0031
kDataHSetFileSize64Select = 0x0032
kDataHGetFreeSpace64Select = 0x0033
kDataHAppend64Select = 0x0034
kDataHReadAsyncSelect = 0x0035
kDataHPollReadSelect = 0x0036
kDataHGetDataAvailabilitySelect = 0x0037
kDataHGetFileSizeAsyncSelect = 0x003A
kDataHGetDataRefAsTypeSelect = 0x003B
kDataHSetDataRefExtensionSelect = 0x003C
kDataHGetDataRefExtensionSelect = 0x003D
kDataHGetMovieWithFlagsSelect = 0x003E
kDataHGetFileTypeOrderingSelect = 0x0040
kDataHCreateFileWithFlagsSelect = 0x0041
kDataHGetMIMETypeAsyncSelect = 0x0042
kDataHGetInfoSelect = 0x0043
kDataHSetIdleManagerSelect = 0x0044
kDataHDeleteFileSelect = 0x0045
kDataHSetMovieUsageFlagsSelect = 0x0046
kDataHUseTemporaryDataRefSelect = 0x0047
kDataHGetTemporaryDataRefCapabilitiesSelect = 0x0048
kDataHRenameFileSelect = 0x0049
kDataHPlaybackHintsSelect = 0x0103
kDataHPlaybackHints64Select = 0x010E
kDataHGetDataRateSelect = 0x0110
kDataHSetTimeHintsSelect = 0x0111
kVDGetMaxSrcRectSelect = 0x0001
kVDGetActiveSrcRectSelect = 0x0002
kVDSetDigitizerRectSelect = 0x0003
kVDGetDigitizerRectSelect = 0x0004
kVDGetVBlankRectSelect = 0x0005
kVDGetMaskPixMapSelect = 0x0006
kVDGetPlayThruDestinationSelect = 0x0008
kVDUseThisCLUTSelect = 0x0009
kVDSetInputGammaValueSelect = 0x000A
kVDGetInputGammaValueSelect = 0x000B
kVDSetBrightnessSelect = 0x000C
kVDGetBrightnessSelect = 0x000D
kVDSetContrastSelect = 0x000E
kVDSetHueSelect = 0x000F
kVDSetSharpnessSelect = 0x0010
kVDSetSaturationSelect = 0x0011
kVDGetContrastSelect = 0x0012
kVDGetHueSelect = 0x0013
kVDGetSharpnessSelect = 0x0014
kVDGetSaturationSelect = 0x0015
kVDGrabOneFrameSelect = 0x0016
kVDGetMaxAuxBufferSelect = 0x0017
kVDGetDigitizerInfoSelect = 0x0019
kVDGetCurrentFlagsSelect = 0x001A
kVDSetKeyColorSelect = 0x001B
kVDGetKeyColorSelect = 0x001C
kVDAddKeyColorSelect = 0x001D
kVDGetNextKeyColorSelect = 0x001E
kVDSetKeyColorRangeSelect = 0x001F
kVDGetKeyColorRangeSelect = 0x0020
kVDSetDigitizerUserInterruptSelect = 0x0021
kVDSetInputColorSpaceModeSelect = 0x0022
kVDGetInputColorSpaceModeSelect = 0x0023
kVDSetClipStateSelect = 0x0024
kVDGetClipStateSelect = 0x0025
kVDSetClipRgnSelect = 0x0026
kVDClearClipRgnSelect = 0x0027
kVDGetCLUTInUseSelect = 0x0028
kVDSetPLLFilterTypeSelect = 0x0029
kVDGetPLLFilterTypeSelect = 0x002A
kVDGetMaskandValueSelect = 0x002B
kVDSetMasterBlendLevelSelect = 0x002C
kVDSetPlayThruDestinationSelect = 0x002D
kVDSetPlayThruOnOffSelect = 0x002E
kVDSetFieldPreferenceSelect = 0x002F
kVDGetFieldPreferenceSelect = 0x0030
kVDPreflightDestinationSelect = 0x0032
kVDPreflightGlobalRectSelect = 0x0033
kVDSetPlayThruGlobalRectSelect = 0x0034
kVDSetInputGammaRecordSelect = 0x0035
kVDGetInputGammaRecordSelect = 0x0036
kVDSetBlackLevelValueSelect = 0x0037
kVDGetBlackLevelValueSelect = 0x0038
kVDSetWhiteLevelValueSelect = 0x0039
kVDGetWhiteLevelValueSelect = 0x003A
kVDGetVideoDefaultsSelect = 0x003B
kVDGetNumberOfInputsSelect = 0x003C
kVDGetInputFormatSelect = 0x003D
kVDSetInputSelect = 0x003E
kVDGetInputSelect = 0x003F
kVDSetInputStandardSelect = 0x0040
kVDSetupBuffersSelect = 0x0041
kVDGrabOneFrameAsyncSelect = 0x0042
kVDDoneSelect = 0x0043
kVDSetCompressionSelect = 0x0044
kVDCompressOneFrameAsyncSelect = 0x0045
kVDCompressDoneSelect = 0x0046
kVDReleaseCompressBufferSelect = 0x0047
kVDGetImageDescriptionSelect = 0x0048
kVDResetCompressSequenceSelect = 0x0049
kVDSetCompressionOnOffSelect = 0x004A
kVDGetCompressionTypesSelect = 0x004B
kVDSetTimeBaseSelect = 0x004C
kVDSetFrameRateSelect = 0x004D
kVDGetDataRateSelect = 0x004E
kVDGetSoundInputDriverSelect = 0x004F
kVDGetDMADepthsSelect = 0x0050
kVDGetPreferredTimeScaleSelect = 0x0051
kVDReleaseAsyncBuffersSelect = 0x0052
kVDSetDataRateSelect = 0x0054
kVDGetTimeCodeSelect = 0x0055
kVDUseSafeBuffersSelect = 0x0056
kVDGetSoundInputSourceSelect = 0x0057
kVDGetCompressionTimeSelect = 0x0058
kVDSetPreferredPacketSizeSelect = 0x0059
kVDSetPreferredImageDimensionsSelect = 0x005A
kVDGetPreferredImageDimensionsSelect = 0x005B
kVDGetInputNameSelect = 0x005C
kVDSetDestinationPortSelect = 0x005D
kVDGetDeviceNameAndFlagsSelect = 0x005E
kVDCaptureStateChangingSelect = 0x005F
kVDGetUniqueIDsSelect = 0x0060
kVDSelectUniqueIDsSelect = 0x0061
kXMLParseDataRefSelect = 0x0001
kXMLParseFileSelect = 0x0002
kXMLParseDisposeXMLDocSelect = 0x0003
kXMLParseGetDetailedParseErrorSelect = 0x0004
kXMLParseAddElementSelect = 0x0005
kXMLParseAddAttributeSelect = 0x0006
kXMLParseAddMultipleAttributesSelect = 0x0007
kXMLParseAddAttributeAndValueSelect = 0x0008
kXMLParseAddMultipleAttributesAndValuesSelect = 0x0009
kXMLParseAddAttributeValueKindSelect = 0x000A
kXMLParseAddNameSpaceSelect = 0x000B
kXMLParseSetOffsetAndLimitSelect = 0x000C
kXMLParseSetEventParseRefConSelect = 0x000D
kXMLParseSetStartDocumentHandlerSelect = 0x000E
kXMLParseSetEndDocumentHandlerSelect = 0x000F
kXMLParseSetStartElementHandlerSelect = 0x0010
kXMLParseSetEndElementHandlerSelect = 0x0011
kXMLParseSetCharDataHandlerSelect = 0x0012
kXMLParseSetPreprocessInstructionHandlerSelect = 0x0013
kXMLParseSetCommentHandlerSelect = 0x0014
kXMLParseSetCDataHandlerSelect = 0x0015
kSGInitializeSelect = 0x0001
kSGSetDataOutputSelect = 0x0002
kSGGetDataOutputSelect = 0x0003
kSGSetGWorldSelect = 0x0004
kSGGetGWorldSelect = 0x0005
kSGNewChannelSelect = 0x0006
kSGDisposeChannelSelect = 0x0007
kSGStartPreviewSelect = 0x0010
kSGStartRecordSelect = 0x0011
kSGIdleSelect = 0x0012
kSGStopSelect = 0x0013
kSGPauseSelect = 0x0014
kSGPrepareSelect = 0x0015
kSGReleaseSelect = 0x0016
kSGGetMovieSelect = 0x0017
kSGSetMaximumRecordTimeSelect = 0x0018
kSGGetMaximumRecordTimeSelect = 0x0019
kSGGetStorageSpaceRemainingSelect = 0x001A
kSGGetTimeRemainingSelect = 0x001B
kSGGrabPictSelect = 0x001C
kSGGetLastMovieResIDSelect = 0x001D
kSGSetFlagsSelect = 0x001E
kSGGetFlagsSelect = 0x001F
kSGSetDataProcSelect = 0x0020
kSGNewChannelFromComponentSelect = 0x0021
kSGDisposeDeviceListSelect = 0x0022
kSGAppendDeviceListToMenuSelect = 0x0023
kSGSetSettingsSelect = 0x0024
kSGGetSettingsSelect = 0x0025
kSGGetIndChannelSelect = 0x0026
kSGUpdateSelect = 0x0027
kSGGetPauseSelect = 0x0028
kSGSettingsDialogSelect = 0x0029
kSGGetAlignmentProcSelect = 0x002A
kSGSetChannelSettingsSelect = 0x002B
kSGGetChannelSettingsSelect = 0x002C
kSGGetModeSelect = 0x002D
kSGSetDataRefSelect = 0x002E
kSGGetDataRefSelect = 0x002F
kSGNewOutputSelect = 0x0030
kSGDisposeOutputSelect = 0x0031
kSGSetOutputFlagsSelect = 0x0032
kSGSetChannelOutputSelect = 0x0033
kSGGetDataOutputStorageSpaceRemainingSelect = 0x0034
kSGHandleUpdateEventSelect = 0x0035
kSGSetOutputNextOutputSelect = 0x0036
kSGGetOutputNextOutputSelect = 0x0037
kSGSetOutputMaximumOffsetSelect = 0x0038
kSGGetOutputMaximumOffsetSelect = 0x0039
kSGGetOutputDataReferenceSelect = 0x003A
kSGWriteExtendedMovieDataSelect = 0x003B
kSGGetStorageSpaceRemaining64Select = 0x003C
kSGGetDataOutputStorageSpaceRemaining64Select = 0x003D
kSGWriteMovieDataSelect = 0x0100
kSGAddFrameReferenceSelect = 0x0101
kSGGetNextFrameReferenceSelect = 0x0102
kSGGetTimeBaseSelect = 0x0103
kSGSortDeviceListSelect = 0x0104
kSGAddMovieDataSelect = 0x0105
kSGChangedSourceSelect = 0x0106
kSGAddExtendedFrameReferenceSelect = 0x0107
kSGGetNextExtendedFrameReferenceSelect = 0x0108
kSGAddExtendedMovieDataSelect = 0x0109
kSGAddOutputDataRefToMediaSelect = 0x010A
kSGSetSettingsSummarySelect = 0x010B
kSGSetChannelUsageSelect = 0x0080
kSGGetChannelUsageSelect = 0x0081
kSGSetChannelBoundsSelect = 0x0082
kSGGetChannelBoundsSelect = 0x0083
kSGSetChannelVolumeSelect = 0x0084
kSGGetChannelVolumeSelect = 0x0085
kSGGetChannelInfoSelect = 0x0086
kSGSetChannelPlayFlagsSelect = 0x0087
kSGGetChannelPlayFlagsSelect = 0x0088
kSGSetChannelMaxFramesSelect = 0x0089
kSGGetChannelMaxFramesSelect = 0x008A
kSGSetChannelRefConSelect = 0x008B
kSGSetChannelClipSelect = 0x008C
kSGGetChannelClipSelect = 0x008D
kSGGetChannelSampleDescriptionSelect = 0x008E
kSGGetChannelDeviceListSelect = 0x008F
kSGSetChannelDeviceSelect = 0x0090
kSGSetChannelMatrixSelect = 0x0091
kSGGetChannelMatrixSelect = 0x0092
kSGGetChannelTimeScaleSelect = 0x0093
kSGChannelPutPictureSelect = 0x0094
kSGChannelSetRequestedDataRateSelect = 0x0095
kSGChannelGetRequestedDataRateSelect = 0x0096
kSGChannelSetDataSourceNameSelect = 0x0097
kSGChannelGetDataSourceNameSelect = 0x0098
kSGChannelSetCodecSettingsSelect = 0x0099
kSGChannelGetCodecSettingsSelect = 0x009A
kSGGetChannelTimeBaseSelect = 0x009B
kSGGetChannelRefConSelect = 0x009C
kSGGetChannelDeviceAndInputNamesSelect = 0x009D
kSGSetChannelDeviceInputSelect = 0x009E
kSGSetChannelSettingsStateChangingSelect = 0x009F
kSGInitChannelSelect = 0x0180
kSGWriteSamplesSelect = 0x0181
kSGGetDataRateSelect = 0x0182
kSGAlignChannelRectSelect = 0x0183
kSGPanelGetDitlSelect = 0x0200
kSGPanelGetTitleSelect = 0x0201
kSGPanelCanRunSelect = 0x0202
kSGPanelInstallSelect = 0x0203
kSGPanelEventSelect = 0x0204
kSGPanelItemSelect = 0x0205
kSGPanelRemoveSelect = 0x0206
kSGPanelSetGrabberSelect = 0x0207
kSGPanelSetResFileSelect = 0x0208
kSGPanelGetSettingsSelect = 0x0209
kSGPanelSetSettingsSelect = 0x020A
kSGPanelValidateInputSelect = 0x020B
kSGPanelSetEventFilterSelect = 0x020C
kSGPanelGetDITLForSizeSelect = 0x020D
kSGGetSrcVideoBoundsSelect = 0x0100
kSGSetVideoRectSelect = 0x0101
kSGGetVideoRectSelect = 0x0102
kSGGetVideoCompressorTypeSelect = 0x0103
kSGSetVideoCompressorTypeSelect = 0x0104
kSGSetVideoCompressorSelect = 0x0105
kSGGetVideoCompressorSelect = 0x0106
kSGGetVideoDigitizerComponentSelect = 0x0107
kSGSetVideoDigitizerComponentSelect = 0x0108
kSGVideoDigitizerChangedSelect = 0x0109
kSGSetVideoBottlenecksSelect = 0x010A
kSGGetVideoBottlenecksSelect = 0x010B
kSGGrabFrameSelect = 0x010C
kSGGrabFrameCompleteSelect = 0x010D
kSGDisplayFrameSelect = 0x010E
kSGCompressFrameSelect = 0x010F
kSGCompressFrameCompleteSelect = 0x0110
kSGAddFrameSelect = 0x0111
kSGTransferFrameForCompressSelect = 0x0112
kSGSetCompressBufferSelect = 0x0113
kSGGetCompressBufferSelect = 0x0114
kSGGetBufferInfoSelect = 0x0115
kSGSetUseScreenBufferSelect = 0x0116
kSGGetUseScreenBufferSelect = 0x0117
kSGGrabCompressCompleteSelect = 0x0118
kSGDisplayCompressSelect = 0x0119
kSGSetFrameRateSelect = 0x011A
kSGGetFrameRateSelect = 0x011B
kSGSetPreferredPacketSizeSelect = 0x0121
kSGGetPreferredPacketSizeSelect = 0x0122
kSGSetUserVideoCompressorListSelect = 0x0123
kSGGetUserVideoCompressorListSelect = 0x0124
kSGSetSoundInputDriverSelect = 0x0100
kSGGetSoundInputDriverSelect = 0x0101
kSGSoundInputDriverChangedSelect = 0x0102
kSGSetSoundRecordChunkSizeSelect = 0x0103
kSGGetSoundRecordChunkSizeSelect = 0x0104
kSGSetSoundInputRateSelect = 0x0105
kSGGetSoundInputRateSelect = 0x0106
kSGSetSoundInputParametersSelect = 0x0107
kSGGetSoundInputParametersSelect = 0x0108
kSGSetAdditionalSoundRatesSelect = 0x0109
kSGGetAdditionalSoundRatesSelect = 0x010A
kSGSetFontNameSelect = 0x0100
kSGSetFontSizeSelect = 0x0101
kSGSetTextForeColorSelect = 0x0102
kSGSetTextBackColorSelect = 0x0103
kSGSetJustificationSelect = 0x0104
kSGGetTextReturnToSpaceValueSelect = 0x0105
kSGSetTextReturnToSpaceValueSelect = 0x0106
kSGGetInstrumentSelect = 0x0100
kSGSetInstrumentSelect = 0x0101
kQTVideoOutputGetDisplayModeListSelect = 0x0001
kQTVideoOutputGetCurrentClientNameSelect = 0x0002
kQTVideoOutputSetClientNameSelect = 0x0003
kQTVideoOutputGetClientNameSelect = 0x0004
kQTVideoOutputBeginSelect = 0x0005
kQTVideoOutputEndSelect = 0x0006
kQTVideoOutputSetDisplayModeSelect = 0x0007
kQTVideoOutputGetDisplayModeSelect = 0x0008
kQTVideoOutputCustomConfigureDisplaySelect = 0x0009
kQTVideoOutputSaveStateSelect = 0x000A
kQTVideoOutputRestoreStateSelect = 0x000B
kQTVideoOutputGetGWorldSelect = 0x000C
kQTVideoOutputGetGWorldParametersSelect = 0x000D
kQTVideoOutputGetIndSoundOutputSelect = 0x000E
kQTVideoOutputGetClockSelect = 0x000F
kQTVideoOutputSetEchoPortSelect = 0x0010
kQTVideoOutputGetIndImageDecompressorSelect = 0x0011
kQTVideoOutputBaseSetEchoPortSelect = 0x0012
handlerHasSpatial = 1 << 0
handlerCanClip = 1 << 1
handlerCanMatte = 1 << 2
handlerCanTransferMode = 1 << 3
handlerNeedsBuffer = 1 << 4
handlerNoIdle = 1 << 5
handlerNoScheduler = 1 << 6
handlerWantsTime = 1 << 7
handlerCGrafPortOnly = 1 << 8
handlerCanSend = 1 << 9
handlerCanHandleComplexMatrix = 1 << 10
handlerWantsDestinationPixels = 1 << 11
handlerCanSendImageData = 1 << 12
handlerCanPicSave = 1 << 13
mMustDraw = 1 << 3
mAtEnd = 1 << 4
mPreflightDraw = 1 << 5
mSyncDrawing = 1 << 6
mPrecompositeOnly = 1 << 9
mSoundOnly = 1 << 10
mDoIdleActionsBeforeDraws = 1 << 11
mDisableIdleActions = 1 << 12
mDidDraw = 1 << 0
mNeedsToDraw = 1 << 2
mDrawAgain = 1 << 3
mPartialDraw = 1 << 4
mWantIdleActions = 1 << 5
forceUpdateRedraw = 1 << 0
forceUpdateNewBuffer = 1 << 1
mHitTestBounds = 1L << 0
mHitTestImage = 1L << 1
mHitTestInvisible = 1L << 2
mHitTestIsClick = 1L << 3
mOpaque = 1L << 0
mInvisible = 1L << 1
kMediaQTIdleFrequencySelector = FOUR_CHAR_CODE('idfq')
kMediaVideoParamBrightness = 1
kMediaVideoParamContrast = 2
kMediaVideoParamHue = 3
kMediaVideoParamSharpness = 4
kMediaVideoParamSaturation = 5
kMediaVideoParamBlackLevel = 6
kMediaVideoParamWhiteLevel = 7
kMHInfoEncodedFrameRate = FOUR_CHAR_CODE('orat')
kEmptyPurgableChunksOverAllowance = 1
kCallComponentExecuteWiredActionSelect = -9
kMediaSetChunkManagementFlagsSelect = 0x0415
kMediaGetChunkManagementFlagsSelect = 0x0416
kMediaSetPurgeableChunkMemoryAllowanceSelect = 0x0417
kMediaGetPurgeableChunkMemoryAllowanceSelect = 0x0418
kMediaEmptyAllPurgeableChunksSelect = 0x0419
kMediaInitializeSelect = 0x0501
kMediaSetHandlerCapabilitiesSelect = 0x0502
kMediaIdleSelect = 0x0503
kMediaGetMediaInfoSelect = 0x0504
kMediaPutMediaInfoSelect = 0x0505
kMediaSetActiveSelect = 0x0506
kMediaSetRateSelect = 0x0507
kMediaGGetStatusSelect = 0x0508
kMediaTrackEditedSelect = 0x0509
kMediaSetMediaTimeScaleSelect = 0x050A
kMediaSetMovieTimeScaleSelect = 0x050B
kMediaSetGWorldSelect = 0x050C
kMediaSetDimensionsSelect = 0x050D
kMediaSetClipSelect = 0x050E
kMediaSetMatrixSelect = 0x050F
kMediaGetTrackOpaqueSelect = 0x0510
kMediaSetGraphicsModeSelect = 0x0511
kMediaGetGraphicsModeSelect = 0x0512
kMediaGSetVolumeSelect = 0x0513
kMediaSetSoundBalanceSelect = 0x0514
kMediaGetSoundBalanceSelect = 0x0515
kMediaGetNextBoundsChangeSelect = 0x0516
kMediaGetSrcRgnSelect = 0x0517
kMediaPrerollSelect = 0x0518
kMediaSampleDescriptionChangedSelect = 0x0519
kMediaHasCharacteristicSelect = 0x051A
kMediaGetOffscreenBufferSizeSelect = 0x051B
kMediaSetHintsSelect = 0x051C
kMediaGetNameSelect = 0x051D
kMediaForceUpdateSelect = 0x051E
kMediaGetDrawingRgnSelect = 0x051F
kMediaGSetActiveSegmentSelect = 0x0520
kMediaInvalidateRegionSelect = 0x0521
kMediaGetNextStepTimeSelect = 0x0522
kMediaSetNonPrimarySourceDataSelect = 0x0523
kMediaChangedNonPrimarySourceSelect = 0x0524
kMediaTrackReferencesChangedSelect = 0x0525
kMediaGetSampleDataPointerSelect = 0x0526
kMediaReleaseSampleDataPointerSelect = 0x0527
kMediaTrackPropertyAtomChangedSelect = 0x0528
kMediaSetTrackInputMapReferenceSelect = 0x0529
kMediaSetVideoParamSelect = 0x052B
kMediaGetVideoParamSelect = 0x052C
kMediaCompareSelect = 0x052D
kMediaGetClockSelect = 0x052E
kMediaSetSoundOutputComponentSelect = 0x052F
kMediaGetSoundOutputComponentSelect = 0x0530
kMediaSetSoundLocalizationDataSelect = 0x0531
kMediaGetInvalidRegionSelect = 0x053C
kMediaSampleDescriptionB2NSelect = 0x053E
kMediaSampleDescriptionN2BSelect = 0x053F
kMediaQueueNonPrimarySourceDataSelect = 0x0540
kMediaFlushNonPrimarySourceDataSelect = 0x0541
kMediaGetURLLinkSelect = 0x0543
kMediaMakeMediaTimeTableSelect = 0x0545
kMediaHitTestForTargetRefConSelect = 0x0546
kMediaHitTestTargetRefConSelect = 0x0547
kMediaGetActionsForQTEventSelect = 0x0548
kMediaDisposeTargetRefConSelect = 0x0549
kMediaTargetRefConsEqualSelect = 0x054A
kMediaSetActionsCallbackSelect = 0x054B
kMediaPrePrerollBeginSelect = 0x054C
kMediaPrePrerollCancelSelect = 0x054D
kMediaEnterEmptyEditSelect = 0x054F
kMediaCurrentMediaQueuedDataSelect = 0x0550
kMediaGetEffectiveVolumeSelect = 0x0551
kMediaResolveTargetRefConSelect = 0x0552
kMediaGetSoundLevelMeteringEnabledSelect = 0x0553
kMediaSetSoundLevelMeteringEnabledSelect = 0x0554
kMediaGetSoundLevelMeterInfoSelect = 0x0555
kMediaGetEffectiveSoundBalanceSelect = 0x0556
kMediaSetScreenLockSelect = 0x0557
kMediaSetDoMCActionCallbackSelect = 0x0558
kMediaGetErrorStringSelect = 0x0559
kMediaGetSoundEqualizerBandsSelect = 0x055A
kMediaSetSoundEqualizerBandsSelect = 0x055B
kMediaGetSoundEqualizerBandLevelsSelect = 0x055C
kMediaDoIdleActionsSelect = 0x055D
kMediaSetSoundBassAndTrebleSelect = 0x055E
kMediaGetSoundBassAndTrebleSelect = 0x055F
kMediaTimeBaseChangedSelect = 0x0560
kMediaMCIsPlayerEventSelect = 0x0561
kMediaGetMediaLoadStateSelect = 0x0562
kMediaVideoOutputChangedSelect = 0x0563
kMediaEmptySampleCacheSelect = 0x0564
kMediaGetPublicInfoSelect = 0x0565
kMediaSetPublicInfoSelect = 0x0566
kMediaGetUserPreferredCodecsSelect = 0x0567
kMediaSetUserPreferredCodecsSelect = 0x0568
kMediaRefConSetPropertySelect = 0x0569
kMediaRefConGetPropertySelect = 0x056A
kMediaNavigateTargetRefConSelect = 0x056B
kMediaGGetIdleManagerSelect = 0x056C
kMediaGSetIdleManagerSelect = 0x056D
kaiToneDescType = FOUR_CHAR_CODE('tone')
kaiNoteRequestInfoType = FOUR_CHAR_CODE('ntrq')
kaiKnobListType = FOUR_CHAR_CODE('knbl')
kaiKeyRangeInfoType = FOUR_CHAR_CODE('sinf')
kaiSampleDescType = FOUR_CHAR_CODE('sdsc')
kaiSampleInfoType = FOUR_CHAR_CODE('smin')
kaiSampleDataType = FOUR_CHAR_CODE('sdat')
kaiSampleDataQUIDType = FOUR_CHAR_CODE('quid')
kaiInstInfoType = FOUR_CHAR_CODE('iinf')
kaiPictType = FOUR_CHAR_CODE('pict')
kaiWriterType = FOUR_CHAR_CODE('\xa9wrt')
kaiCopyrightType = FOUR_CHAR_CODE('\xa9cpy')
kaiOtherStrType = FOUR_CHAR_CODE('str ')
kaiInstrumentRefType = FOUR_CHAR_CODE('iref')
kaiInstGMQualityType = FOUR_CHAR_CODE('qual')
kaiLibraryInfoType = FOUR_CHAR_CODE('linf')
kaiLibraryDescType = FOUR_CHAR_CODE('ldsc')
kInstKnobMissingUnknown = 0
kInstKnobMissingDefault = (1 << 0)
kMusicLoopTypeNormal = 0
kMusicLoopTypePalindrome = 1
instSamplePreProcessFlag = 1 << 0
kQTMIDIComponentType = FOUR_CHAR_CODE('midi')
kOMSComponentSubType = FOUR_CHAR_CODE('OMS ')
kFMSComponentSubType = FOUR_CHAR_CODE('FMS ')
kMIDIManagerComponentSubType = FOUR_CHAR_CODE('mmgr')
kOSXMIDIComponentSubType = FOUR_CHAR_CODE('osxm')
kMusicPacketPortLost = 1
kMusicPacketPortFound = 2
kMusicPacketTimeGap = 3
kAppleSysexID = 0x11
kAppleSysexCmdSampleSize = 0x0001
kAppleSysexCmdSampleBreak = 0x0002
kAppleSysexCmdAtomicInstrument = 0x0010
kAppleSysexCmdDeveloper = 0x7F00
kSynthesizerConnectionFMS = 1
kSynthesizerConnectionMMgr = 2
kSynthesizerConnectionOMS = 4
kSynthesizerConnectionQT = 8
kSynthesizerConnectionOSXMIDI = 16
kSynthesizerConnectionUnavailable = 256
kMusicComponentType = FOUR_CHAR_CODE('musi')
kInstrumentComponentType = FOUR_CHAR_CODE('inst')
kSoftSynthComponentSubType = FOUR_CHAR_CODE('ss ')
kGMSynthComponentSubType = FOUR_CHAR_CODE('gm ')
kSynthesizerDynamicVoice = 1 << 0
kSynthesizerUsesMIDIPort = 1 << 1
kSynthesizerMicrotone = 1 << 2
kSynthesizerHasSamples = 1 << 3
kSynthesizerMixedDrums = 1 << 4
kSynthesizerSoftware = 1 << 5
kSynthesizerHardware = 1 << 6
kSynthesizerDynamicChannel = 1 << 7
kSynthesizerHogsSystemChannel = 1 << 8
kSynthesizerHasSystemChannel = 1 << 9
kSynthesizerSlowSetPart = 1 << 10
kSynthesizerOffline = 1 << 12
kSynthesizerGM = 1 << 14
kSynthesizerDLS = 1 << 15
kSynthesizerSoundLocalization = 1 << 16
kControllerModulationWheel = 1
kControllerBreath = 2
kControllerFoot = 4
kControllerPortamentoTime = 5
kControllerVolume = 7
kControllerBalance = 8
kControllerPan = 10
kControllerExpression = 11
kControllerLever1 = 16
kControllerLever2 = 17
kControllerLever3 = 18
kControllerLever4 = 19
kControllerLever5 = 80
kControllerLever6 = 81
kControllerLever7 = 82
kControllerLever8 = 83
kControllerPitchBend = 32
kControllerAfterTouch = 33
kControllerPartTranspose = 40
kControllerTuneTranspose = 41
kControllerPartVolume = 42
kControllerTuneVolume = 43
kControllerSustain = 64
kControllerPortamento = 65
kControllerSostenuto = 66
kControllerSoftPedal = 67
kControllerReverb = 91
kControllerTremolo = 92
kControllerChorus = 93
kControllerCeleste = 94
kControllerPhaser = 95
kControllerEditPart = 113
kControllerMasterTune = 114
kControllerMasterTranspose = 114
kControllerMasterVolume = 115
kControllerMasterCPULoad = 116
kControllerMasterPolyphony = 117
kControllerMasterFeatures = 118
kQTMSKnobStartID = 0x02000000
kQTMSKnobVolumeAttackTimeID = 0x02000001
kQTMSKnobVolumeDecayTimeID = 0x02000002
kQTMSKnobVolumeSustainLevelID = 0x02000003
kQTMSKnobVolumeRelease1RateID = 0x02000004
kQTMSKnobVolumeDecayKeyScalingID = 0x02000005
kQTMSKnobVolumeReleaseTimeID = 0x02000006
kQTMSKnobVolumeLFODelayID = 0x02000007
kQTMSKnobVolumeLFORampTimeID = 0x02000008
kQTMSKnobVolumeLFOPeriodID = 0x02000009
kQTMSKnobVolumeLFOShapeID = 0x0200000A
kQTMSKnobVolumeLFODepthID = 0x0200000B
kQTMSKnobVolumeOverallID = 0x0200000C
kQTMSKnobVolumeVelocity127ID = 0x0200000D
kQTMSKnobVolumeVelocity96ID = 0x0200000E
kQTMSKnobVolumeVelocity64ID = 0x0200000F
kQTMSKnobVolumeVelocity32ID = 0x02000010
kQTMSKnobVolumeVelocity16ID = 0x02000011
kQTMSKnobPitchTransposeID = 0x02000012
kQTMSKnobPitchLFODelayID = 0x02000013
kQTMSKnobPitchLFORampTimeID = 0x02000014
kQTMSKnobPitchLFOPeriodID = 0x02000015
kQTMSKnobPitchLFOShapeID = 0x02000016
kQTMSKnobPitchLFODepthID = 0x02000017
kQTMSKnobPitchLFOQuantizeID = 0x02000018
kQTMSKnobStereoDefaultPanID = 0x02000019
kQTMSKnobStereoPositionKeyScalingID = 0x0200001A
kQTMSKnobPitchLFOOffsetID = 0x0200001B
kQTMSKnobExclusionGroupID = 0x0200001C
kQTMSKnobSustainTimeID = 0x0200001D
kQTMSKnobSustainInfiniteID = 0x0200001E
kQTMSKnobVolumeLFOStereoID = 0x0200001F
kQTMSKnobVelocityLowID = 0x02000020
kQTMSKnobVelocityHighID = 0x02000021
kQTMSKnobVelocitySensitivityID = 0x02000022
kQTMSKnobPitchSensitivityID = 0x02000023
kQTMSKnobVolumeLFODepthFromWheelID = 0x02000024
kQTMSKnobPitchLFODepthFromWheelID = 0x02000025
kQTMSKnobVolumeExpOptionsID = 0x02000026
kQTMSKnobEnv1AttackTimeID = 0x02000027
kQTMSKnobEnv1DecayTimeID = 0x02000028
kQTMSKnobEnv1SustainLevelID = 0x02000029
kQTMSKnobEnv1SustainTimeID = 0x0200002A
kQTMSKnobEnv1SustainInfiniteID = 0x0200002B
kQTMSKnobEnv1ReleaseTimeID = 0x0200002C
kQTMSKnobEnv1ExpOptionsID = 0x0200002D
kQTMSKnobEnv2AttackTimeID = 0x0200002E
kQTMSKnobEnv2DecayTimeID = 0x0200002F
kQTMSKnobEnv2SustainLevelID = 0x02000030
kQTMSKnobEnv2SustainTimeID = 0x02000031
kQTMSKnobEnv2SustainInfiniteID = 0x02000032
kQTMSKnobEnv2ReleaseTimeID = 0x02000033
kQTMSKnobEnv2ExpOptionsID = 0x02000034
kQTMSKnobPitchEnvelopeID = 0x02000035
kQTMSKnobPitchEnvelopeDepthID = 0x02000036
kQTMSKnobFilterKeyFollowID = 0x02000037
kQTMSKnobFilterTransposeID = 0x02000038
kQTMSKnobFilterQID = 0x02000039
kQTMSKnobFilterFrequencyEnvelopeID = 0x0200003A
kQTMSKnobFilterFrequencyEnvelopeDepthID = 0x0200003B
kQTMSKnobFilterQEnvelopeID = 0x0200003C
kQTMSKnobFilterQEnvelopeDepthID = 0x0200003D
kQTMSKnobReverbThresholdID = 0x0200003E
kQTMSKnobVolumeAttackVelScalingID = 0x0200003F
kQTMSKnobLastIDPlus1 = 0x02000040
kControllerMaximum = 0x00007FFF
# kControllerMinimum = (long)0xFFFF8000
kVoiceCountDynamic = -1
kFirstGMInstrument = 0x00000001
kLastGMInstrument = 0x00000080
kFirstGSInstrument = 0x00000081
kLastGSInstrument = 0x00003FFF
kFirstDrumkit = 0x00004000
kLastDrumkit = 0x00004080
kFirstROMInstrument = 0x00008000
kLastROMInstrument = 0x0000FFFF
kFirstUserInstrument = 0x00010000
kLastUserInstrument = 0x0001FFFF
kInstrumentMatchSynthesizerType = 1
kInstrumentMatchSynthesizerName = 2
kInstrumentMatchName = 4
kInstrumentMatchNumber = 8
kInstrumentMatchGMNumber = 16
kInstrumentMatchGSNumber = 32
kKnobBasic = 8
kKnobReadOnly = 16
kKnobInterruptUnsafe = 32
kKnobKeyrangeOverride = 64
kKnobGroupStart = 128
kKnobFixedPoint8 = 1024
kKnobFixedPoint16 = 2048
kKnobTypeNumber = 0 << 12
kKnobTypeGroupName = 1 << 12
kKnobTypeBoolean = 2 << 12
kKnobTypeNote = 3 << 12
kKnobTypePan = 4 << 12
kKnobTypeInstrument = 5 << 12
kKnobTypeSetting = 6 << 12
kKnobTypeMilliseconds = 7 << 12
kKnobTypePercentage = 8 << 12
kKnobTypeHertz = 9 << 12
kKnobTypeButton = 10 << 12
kUnknownKnobValue = 0x7FFFFFFF
kDefaultKnobValue = 0x7FFFFFFE
notImplementedMusicErr = (0x80000000 | (0xFFFF & (notImplementedMusicOSErr)))
cantSendToSynthesizerErr = (0x80000000 | (0xFFFF & (cantSendToSynthesizerOSErr)))
cantReceiveFromSynthesizerErr = (0x80000000 | (0xFFFF & (cantReceiveFromSynthesizerOSErr)))
illegalVoiceAllocationErr = (0x80000000 | (0xFFFF & (illegalVoiceAllocationOSErr)))
illegalPartErr = (0x80000000 | (0xFFFF & (illegalPartOSErr)))
illegalChannelErr = (0x80000000 | (0xFFFF & (illegalChannelOSErr)))
illegalKnobErr = (0x80000000 | (0xFFFF & (illegalKnobOSErr)))
illegalKnobValueErr = (0x80000000 | (0xFFFF & (illegalKnobValueOSErr)))
illegalInstrumentErr = (0x80000000 | (0xFFFF & (illegalInstrumentOSErr)))
illegalControllerErr = (0x80000000 | (0xFFFF & (illegalControllerOSErr)))
midiManagerAbsentErr = (0x80000000 | (0xFFFF & (midiManagerAbsentOSErr)))
synthesizerNotRespondingErr = (0x80000000 | (0xFFFF & (synthesizerNotRespondingOSErr)))
synthesizerErr = (0x80000000 | (0xFFFF & (synthesizerOSErr)))
illegalNoteChannelErr = (0x80000000 | (0xFFFF & (illegalNoteChannelOSErr)))
noteChannelNotAllocatedErr = (0x80000000 | (0xFFFF & (noteChannelNotAllocatedOSErr)))
tunePlayerFullErr = (0x80000000 | (0xFFFF & (tunePlayerFullOSErr)))
tuneParseErr = (0x80000000 | (0xFFFF & (tuneParseOSErr)))
kGetAtomicInstNoExpandedSamples = 1 << 0
kGetAtomicInstNoOriginalSamples = 1 << 1
kGetAtomicInstNoSamples = kGetAtomicInstNoExpandedSamples | kGetAtomicInstNoOriginalSamples
kGetAtomicInstNoKnobList = 1 << 2
kGetAtomicInstNoInstrumentInfo = 1 << 3
kGetAtomicInstOriginalKnobList = 1 << 4
kGetAtomicInstAllKnobs = 1 << 5
kSetAtomicInstKeepOriginalInstrument = 1 << 0
kSetAtomicInstShareAcrossParts = 1 << 1
kSetAtomicInstCallerTosses = 1 << 2
kSetAtomicInstCallerGuarantees = 1 << 3
kSetAtomicInstInterruptSafe = 1 << 4
kSetAtomicInstDontPreprocess = 1 << 7
kInstrumentNamesModifiable = 1
kInstrumentNamesBoth = 2
kGenericMusicComponentSubtype = FOUR_CHAR_CODE('gene')
kGenericMusicKnob = 1
kGenericMusicInstrumentKnob = 2
kGenericMusicDrumKnob = 3
kGenericMusicGlobalController = 4
kGenericMusicResFirst = 0
kGenericMusicResMiscStringList = 1
kGenericMusicResMiscLongList = 2
kGenericMusicResInstrumentList = 3
kGenericMusicResDrumList = 4
kGenericMusicResInstrumentKnobDescriptionList = 5
kGenericMusicResDrumKnobDescriptionList = 6
kGenericMusicResKnobDescriptionList = 7
kGenericMusicResBitsLongList = 8
kGenericMusicResModifiableInstrumentHW = 9
kGenericMusicResGMTranslation = 10
kGenericMusicResROMInstrumentData = 11
kGenericMusicResAboutPICT = 12
kGenericMusicResLast = 13
kGenericMusicMiscLongFirst = 0
kGenericMusicMiscLongVoiceCount = 1
kGenericMusicMiscLongPartCount = 2
kGenericMusicMiscLongModifiableInstrumentCount = 3
kGenericMusicMiscLongChannelMask = 4
kGenericMusicMiscLongDrumPartCount = 5
kGenericMusicMiscLongModifiableDrumCount = 6
kGenericMusicMiscLongDrumChannelMask = 7
kGenericMusicMiscLongOutputCount = 8
kGenericMusicMiscLongLatency = 9
kGenericMusicMiscLongFlags = 10
kGenericMusicMiscLongFirstGMHW = 11
kGenericMusicMiscLongFirstGMDrumHW = 12
kGenericMusicMiscLongFirstUserHW = 13
kGenericMusicMiscLongLast = 14
kMusicGenericRange = 0x0100
kMusicDerivedRange = 0x0200
kGenericMusicDoMIDI = 1 << 0
kGenericMusicBank0 = 1 << 1
kGenericMusicBank32 = 1 << 2
kGenericMusicErsatzMIDI = 1 << 3
kGenericMusicCallKnobs = 1 << 4
kGenericMusicCallParts = 1 << 5
kGenericMusicCallInstrument = 1 << 6
kGenericMusicCallNumber = 1 << 7
kGenericMusicCallROMInstrument = 1 << 8
kGenericMusicAllDefaults = 1 << 9
kGetInstrumentInfoNoBuiltIn = 1 << 0
kGetInstrumentInfoMidiUserInst = 1 << 1
kGetInstrumentInfoNoIText = 1 << 2
kNoteRequestNoGM = 1
kNoteRequestNoSynthType = 2
kNoteRequestSynthMustMatch = 4
kNoteRequestSpecifyMIDIChannel = 0x80
kPickDontMix = 1
kPickSameSynth = 2
kPickUserInsts = 4
kPickEditAllowEdit = 8
kPickEditAllowPick = 16
kPickEditSynthGlobal = 32
kPickEditControllers = 64
kNoteAllocatorComponentType = FOUR_CHAR_CODE('nota')
kNADummyOneSelect = 29
kNADummyTwoSelect = 30
kTuneQueueDepth = 8
kTunePlayerComponentType = FOUR_CHAR_CODE('tune')
kTuneStartNow = 1
kTuneDontClipNotes = 2
kTuneExcludeEdgeNotes = 4
kTuneQuickStart = 8
kTuneLoopUntil = 16
kTunePlayDifference = 32
kTunePlayConcurrent = 64
kTuneStartNewMaster = 16384
kTuneStopFade = 1
kTuneStopSustain = 2
kTuneStopInstant = 4
kTuneStopReleaseChannels = 8
kTuneMixMute = 1
kTuneMixSolo = 2
kRestEventType = 0x00000000
kNoteEventType = 0x00000001
kControlEventType = 0x00000002
kMarkerEventType = 0x00000003
kUndefined1EventType = 0x00000008
kXNoteEventType = 0x00000009
kXControlEventType = 0x0000000A
kKnobEventType = 0x0000000B
kUndefined2EventType = 0x0000000C
kUndefined3EventType = 0x0000000D
kUndefined4EventType = 0x0000000E
kGeneralEventType = 0x0000000F
kXEventLengthBits = 0x00000002
kGeneralEventLengthBits = 0x00000003
kEventLen = 1L
kXEventLen = 2L
kRestEventLen = kEventLen
kNoteEventLen = kEventLen
kControlEventLen = kEventLen
kMarkerEventLen = kEventLen
kXNoteEventLen = kXEventLen
kXControlEventLen = kXEventLen
kGeneralEventLen = kXEventLen
kEventLengthFieldPos = 30
kEventLengthFieldWidth = 2
kEventTypeFieldPos = 29
kEventTypeFieldWidth = 3
kXEventTypeFieldPos = 28
kXEventTypeFieldWidth = 4
kEventPartFieldPos = 24
kEventPartFieldWidth = 5
kXEventPartFieldPos = 16
kXEventPartFieldWidth = 12
kRestEventDurationFieldPos = 0
kRestEventDurationFieldWidth = 24
kRestEventDurationMax = ((1L << kRestEventDurationFieldWidth) - 1)
kNoteEventPitchFieldPos = 18
kNoteEventPitchFieldWidth = 6
kNoteEventPitchOffset = 32
kNoteEventVolumeFieldPos = 11
kNoteEventVolumeFieldWidth = 7
kNoteEventVolumeOffset = 0
kNoteEventDurationFieldPos = 0
kNoteEventDurationFieldWidth = 11
kNoteEventDurationMax = ((1L << kNoteEventDurationFieldWidth) - 1)
kXNoteEventPitchFieldPos = 0
kXNoteEventPitchFieldWidth = 16
kXNoteEventDurationFieldPos = 0
kXNoteEventDurationFieldWidth = 22
kXNoteEventDurationMax = ((1L << kXNoteEventDurationFieldWidth) - 1)
kXNoteEventVolumeFieldPos = 22
kXNoteEventVolumeFieldWidth = 7
kControlEventControllerFieldPos = 16
kControlEventControllerFieldWidth = 8
kControlEventValueFieldPos = 0
kControlEventValueFieldWidth = 16
kXControlEventControllerFieldPos = 0
kXControlEventControllerFieldWidth = 16
kXControlEventValueFieldPos = 0
kXControlEventValueFieldWidth = 16
kKnobEventValueHighFieldPos = 0
kKnobEventValueHighFieldWidth = 16
kKnobEventKnobFieldPos = 16
kKnobEventKnobFieldWidth = 14
kKnobEventValueLowFieldPos = 0
kKnobEventValueLowFieldWidth = 16
kMarkerEventSubtypeFieldPos = 16
kMarkerEventSubtypeFieldWidth = 8
kMarkerEventValueFieldPos = 0
kMarkerEventValueFieldWidth = 16
kGeneralEventSubtypeFieldPos = 16
kGeneralEventSubtypeFieldWidth = 14
kGeneralEventLengthFieldPos = 0
kGeneralEventLengthFieldWidth = 16
kEndMarkerValue = 0x00000060
kEndMarkerValue = 0x60000000
# _ext = qtma_EXT(*lP
# ulen = (_ext < 2) ? 1 : 2
# ulen = (unsigned short)qtma_EXT(*lP
# ulen = lP[1]
# _ext = qtma_EXT(*lP
# ulen = (_ext < 2) ? 1 : 2
# ulen = (unsigned short)qtma_EXT(*lP
# ulen = lP[-1]
# x = (kRestEventType << kEventTypeFieldPos) \
# x = EndianU32_NtoB(x) )
# x = (kNoteEventType << kEventTypeFieldPos) \
# x = EndianU32_NtoB(x) )
# x = (kControlEventType << kEventTypeFieldPos) \
# x = EndianU32_NtoB(x) )
# x = (kMarkerEventType << kEventTypeFieldPos) \
# x = EndianU32_NtoB(x) )
# w1 = (kXNoteEventType << kXEventTypeFieldPos) \
# w1 = EndianU32_NtoB(w1)
# w2 = (kXEventLengthBits << kEventLengthFieldPos) \
# w2 = EndianU32_NtoB(w2) )
# w1 = (kXControlEventType << kXEventTypeFieldPos) \
# w1 = EndianU32_NtoB(w1)
# w2 = (kXEventLengthBits << kEventLengthFieldPos) \
# w2 = EndianU32_NtoB(w2) )
# w1 = (kKnobEventType << kXEventTypeFieldPos) \
# w1 = EndianU32_NtoB(w1)
# w2 = (kXEventLengthBits << kEventLengthFieldPos) \
# w2 = EndianU32_NtoB(w2) )
# w1 = (kGeneralEventType << kXEventTypeFieldPos) \
# w1 = EndianU32_NtoB(w1)
# w2 = (kGeneralEventLengthBits << kEventLengthFieldPos) \
# w2 = EndianU32_NtoB(w2) )
kGeneralEventNoteRequest = 1
kGeneralEventPartKey = 4
kGeneralEventTuneDifference = 5
kGeneralEventAtomicInstrument = 6
kGeneralEventKnob = 7
kGeneralEventMIDIChannel = 8
kGeneralEventPartChange = 9
kGeneralEventNoOp = 10
kGeneralEventUsedNotes = 11
kGeneralEventPartMix = 12
kMarkerEventEnd = 0
kMarkerEventBeat = 1
kMarkerEventTempo = 2
kCurrentlyNativeEndian = 1
kCurrentlyNotNativeEndian = 2
kQTMIDIGetMIDIPortsSelect = 0x0001
kQTMIDIUseSendPortSelect = 0x0002
kQTMIDISendMIDISelect = 0x0003
kMusicGetDescriptionSelect = 0x0001
kMusicGetPartSelect = 0x0002
kMusicSetPartSelect = 0x0003
kMusicSetPartInstrumentNumberSelect = 0x0004
kMusicGetPartInstrumentNumberSelect = 0x0005
kMusicStorePartInstrumentSelect = 0x0006
kMusicGetPartAtomicInstrumentSelect = 0x0009
kMusicSetPartAtomicInstrumentSelect = 0x000A
kMusicGetPartKnobSelect = 0x0010
kMusicSetPartKnobSelect = 0x0011
kMusicGetKnobSelect = 0x0012
kMusicSetKnobSelect = 0x0013
kMusicGetPartNameSelect = 0x0014
kMusicSetPartNameSelect = 0x0015
kMusicFindToneSelect = 0x0016
kMusicPlayNoteSelect = 0x0017
kMusicResetPartSelect = 0x0018
kMusicSetPartControllerSelect = 0x0019
kMusicGetPartControllerSelect = 0x001A
kMusicGetMIDIProcSelect = 0x001B
kMusicSetMIDIProcSelect = 0x001C
kMusicGetInstrumentNamesSelect = 0x001D
kMusicGetDrumNamesSelect = 0x001E
kMusicGetMasterTuneSelect = 0x001F
kMusicSetMasterTuneSelect = 0x0020
kMusicGetInstrumentAboutInfoSelect = 0x0022
kMusicGetDeviceConnectionSelect = 0x0023
kMusicUseDeviceConnectionSelect = 0x0024
kMusicGetKnobSettingStringsSelect = 0x0025
kMusicGetMIDIPortsSelect = 0x0026
kMusicSendMIDISelect = 0x0027
kMusicStartOfflineSelect = 0x0029
kMusicSetOfflineTimeToSelect = 0x002A
kMusicGetInstrumentKnobDescriptionSelect = 0x002B
kMusicGetDrumKnobDescriptionSelect = 0x002C
kMusicGetKnobDescriptionSelect = 0x002D
kMusicGetInfoTextSelect = 0x002E
kMusicGetInstrumentInfoSelect = 0x002F
kMusicTaskSelect = 0x0031
kMusicSetPartInstrumentNumberInterruptSafeSelect = 0x0032
kMusicSetPartSoundLocalizationSelect = 0x0033
kMusicGenericConfigureSelect = 0x0100
kMusicGenericGetPartSelect = 0x0101
kMusicGenericGetKnobListSelect = 0x0102
kMusicGenericSetResourceNumbersSelect = 0x0103
kMusicDerivedMIDISendSelect = 0x0200
kMusicDerivedSetKnobSelect = 0x0201
kMusicDerivedSetPartSelect = 0x0202
kMusicDerivedSetInstrumentSelect = 0x0203
kMusicDerivedSetPartInstrumentNumberSelect = 0x0204
kMusicDerivedSetMIDISelect = 0x0205
kMusicDerivedStorePartInstrumentSelect = 0x0206
kMusicDerivedOpenResFileSelect = 0x0207
kMusicDerivedCloseResFileSelect = 0x0208
kNARegisterMusicDeviceSelect = 0x0000
kNAUnregisterMusicDeviceSelect = 0x0001
kNAGetRegisteredMusicDeviceSelect = 0x0002
kNASaveMusicConfigurationSelect = 0x0003
kNANewNoteChannelSelect = 0x0004
kNADisposeNoteChannelSelect = 0x0005
kNAGetNoteChannelInfoSelect = 0x0006
kNAPrerollNoteChannelSelect = 0x0007
kNAUnrollNoteChannelSelect = 0x0008
kNASetNoteChannelVolumeSelect = 0x000B
kNAResetNoteChannelSelect = 0x000C
kNAPlayNoteSelect = 0x000D
kNASetControllerSelect = 0x000E
kNASetKnobSelect = 0x000F
kNAFindNoteChannelToneSelect = 0x0010
kNASetInstrumentNumberSelect = 0x0011
kNAPickInstrumentSelect = 0x0012
kNAPickArrangementSelect = 0x0013
kNAStuffToneDescriptionSelect = 0x001B
kNACopyrightDialogSelect = 0x001C
kNAGetIndNoteChannelSelect = 0x001F
kNAGetMIDIPortsSelect = 0x0021
kNAGetNoteRequestSelect = 0x0022
kNASendMIDISelect = 0x0023
kNAPickEditInstrumentSelect = 0x0024
kNANewNoteChannelFromAtomicInstrumentSelect = 0x0025
kNASetAtomicInstrumentSelect = 0x0026
kNAGetKnobSelect = 0x0028
kNATaskSelect = 0x0029
kNASetNoteChannelBalanceSelect = 0x002A
kNASetInstrumentNumberInterruptSafeSelect = 0x002B
kNASetNoteChannelSoundLocalizationSelect = 0x002C
kNAGetControllerSelect = 0x002D
kTuneSetHeaderSelect = 0x0004
kTuneGetTimeBaseSelect = 0x0005
kTuneSetTimeScaleSelect = 0x0006
kTuneGetTimeScaleSelect = 0x0007
kTuneGetIndexedNoteChannelSelect = 0x0008
kTuneQueueSelect = 0x000A
kTuneInstantSelect = 0x000B
kTuneGetStatusSelect = 0x000C
kTuneStopSelect = 0x000D
kTuneSetVolumeSelect = 0x0010
kTuneGetVolumeSelect = 0x0011
kTunePrerollSelect = 0x0012
kTuneUnrollSelect = 0x0013
kTuneSetNoteChannelsSelect = 0x0014
kTuneSetPartTransposeSelect = 0x0015
kTuneGetNoteAllocatorSelect = 0x0017
kTuneSetSofterSelect = 0x0018
kTuneTaskSelect = 0x0019
kTuneSetBalanceSelect = 0x001A
kTuneSetSoundLocalizationSelect = 0x001B
kTuneSetHeaderWithSizeSelect = 0x001C
kTuneSetPartMixSelect = 0x001D
kTuneGetPartMixSelect = 0x001E
| Python |
# Generated from 'Menus.h'
def FOUR_CHAR_CODE(x): return x
noMark = 0
kMenuDrawMsg = 0
kMenuSizeMsg = 2
kMenuPopUpMsg = 3
kMenuCalcItemMsg = 5
kMenuThemeSavvyMsg = 7
mDrawMsg = 0
mSizeMsg = 2
mPopUpMsg = 3
mCalcItemMsg = 5
mChooseMsg = 1
mDrawItemMsg = 4
kMenuChooseMsg = 1
kMenuDrawItemMsg = 4
kThemeSavvyMenuResponse = 0x7473
kMenuInitMsg = 8
kMenuDisposeMsg = 9
kMenuFindItemMsg = 10
kMenuHiliteItemMsg = 11
kMenuDrawItemsMsg = 12
textMenuProc = 0
hMenuCmd = 27
hierMenu = -1
kInsertHierarchicalMenu = -1
mctAllItems = -98
mctLastIDIndic = -99
kMenuStdMenuProc = 63
kMenuStdMenuBarProc = 63
kMenuNoModifiers = 0
kMenuShiftModifier = (1 << 0)
kMenuOptionModifier = (1 << 1)
kMenuControlModifier = (1 << 2)
kMenuNoCommandModifier = (1 << 3)
kMenuNoIcon = 0
kMenuIconType = 1
kMenuShrinkIconType = 2
kMenuSmallIconType = 3
kMenuColorIconType = 4
kMenuIconSuiteType = 5
kMenuIconRefType = 6
kMenuCGImageRefType = 7
kMenuSystemIconSelectorType = 8
kMenuIconResourceType = 9
kMenuNullGlyph = 0x00
kMenuTabRightGlyph = 0x02
kMenuTabLeftGlyph = 0x03
kMenuEnterGlyph = 0x04
kMenuShiftGlyph = 0x05
kMenuControlGlyph = 0x06
kMenuOptionGlyph = 0x07
kMenuSpaceGlyph = 0x09
kMenuDeleteRightGlyph = 0x0A
kMenuReturnGlyph = 0x0B
kMenuReturnR2LGlyph = 0x0C
kMenuNonmarkingReturnGlyph = 0x0D
kMenuPencilGlyph = 0x0F
kMenuDownwardArrowDashedGlyph = 0x10
kMenuCommandGlyph = 0x11
kMenuCheckmarkGlyph = 0x12
kMenuDiamondGlyph = 0x13
kMenuAppleLogoFilledGlyph = 0x14
kMenuParagraphKoreanGlyph = 0x15
kMenuDeleteLeftGlyph = 0x17
kMenuLeftArrowDashedGlyph = 0x18
kMenuUpArrowDashedGlyph = 0x19
kMenuRightArrowDashedGlyph = 0x1A
kMenuEscapeGlyph = 0x1B
kMenuClearGlyph = 0x1C
kMenuLeftDoubleQuotesJapaneseGlyph = 0x1D
kMenuRightDoubleQuotesJapaneseGlyph = 0x1E
kMenuTrademarkJapaneseGlyph = 0x1F
kMenuBlankGlyph = 0x61
kMenuPageUpGlyph = 0x62
kMenuCapsLockGlyph = 0x63
kMenuLeftArrowGlyph = 0x64
kMenuRightArrowGlyph = 0x65
kMenuNorthwestArrowGlyph = 0x66
kMenuHelpGlyph = 0x67
kMenuUpArrowGlyph = 0x68
kMenuSoutheastArrowGlyph = 0x69
kMenuDownArrowGlyph = 0x6A
kMenuPageDownGlyph = 0x6B
kMenuAppleLogoOutlineGlyph = 0x6C
kMenuContextualMenuGlyph = 0x6D
kMenuPowerGlyph = 0x6E
kMenuF1Glyph = 0x6F
kMenuF2Glyph = 0x70
kMenuF3Glyph = 0x71
kMenuF4Glyph = 0x72
kMenuF5Glyph = 0x73
kMenuF6Glyph = 0x74
kMenuF7Glyph = 0x75
kMenuF8Glyph = 0x76
kMenuF9Glyph = 0x77
kMenuF10Glyph = 0x78
kMenuF11Glyph = 0x79
kMenuF12Glyph = 0x7A
kMenuF13Glyph = 0x87
kMenuF14Glyph = 0x88
kMenuF15Glyph = 0x89
kMenuControlISOGlyph = 0x8A
kMenuAttrExcludesMarkColumn = (1 << 0)
kMenuAttrAutoDisable = (1 << 2)
kMenuAttrUsePencilGlyph = (1 << 3)
kMenuAttrHidden = (1 << 4)
kMenuItemAttrDisabled = (1 << 0)
kMenuItemAttrIconDisabled = (1 << 1)
kMenuItemAttrSubmenuParentChoosable = (1 << 2)
kMenuItemAttrDynamic = (1 << 3)
kMenuItemAttrNotPreviousAlternate = (1 << 4)
kMenuItemAttrHidden = (1 << 5)
kMenuItemAttrSeparator = (1 << 6)
kMenuItemAttrSectionHeader = (1 << 7)
kMenuItemAttrIgnoreMeta = (1 << 8)
kMenuItemAttrAutoRepeat = (1 << 9)
kMenuItemAttrUseVirtualKey = (1 << 10)
kMenuItemAttrCustomDraw = (1 << 11)
kMenuItemAttrIncludeInCmdKeyMatching = (1 << 12)
kMenuTrackingModeMouse = 1
kMenuTrackingModeKeyboard = 2
kMenuEventIncludeDisabledItems = 0x0001
kMenuEventQueryOnly = 0x0002
kMenuEventDontCheckSubmenus = 0x0004
kMenuItemDataText = (1 << 0)
kMenuItemDataMark = (1 << 1)
kMenuItemDataCmdKey = (1 << 2)
kMenuItemDataCmdKeyGlyph = (1 << 3)
kMenuItemDataCmdKeyModifiers = (1 << 4)
kMenuItemDataStyle = (1 << 5)
kMenuItemDataEnabled = (1 << 6)
kMenuItemDataIconEnabled = (1 << 7)
kMenuItemDataIconID = (1 << 8)
kMenuItemDataIconHandle = (1 << 9)
kMenuItemDataCommandID = (1 << 10)
kMenuItemDataTextEncoding = (1 << 11)
kMenuItemDataSubmenuID = (1 << 12)
kMenuItemDataSubmenuHandle = (1 << 13)
kMenuItemDataFontID = (1 << 14)
kMenuItemDataRefcon = (1 << 15)
kMenuItemDataAttributes = (1 << 16)
kMenuItemDataCFString = (1 << 17)
kMenuItemDataProperties = (1 << 18)
kMenuItemDataIndent = (1 << 19)
kMenuItemDataCmdVirtualKey = (1 << 20)
kMenuItemDataAllDataVersionOne = 0x000FFFFF
kMenuItemDataAllDataVersionTwo = kMenuItemDataAllDataVersionOne | kMenuItemDataCmdVirtualKey
kMenuDefProcPtr = 0
kMenuPropertyPersistent = 0x00000001
kHierarchicalFontMenuOption = 0x00000001
gestaltContextualMenuAttr = FOUR_CHAR_CODE('cmnu')
gestaltContextualMenuUnusedBit = 0
gestaltContextualMenuTrapAvailable = 1
gestaltContextualMenuHasAttributeAndModifierKeys = 2
gestaltContextualMenuHasUnicodeSupport = 3
kCMHelpItemNoHelp = 0
kCMHelpItemAppleGuide = 1
kCMHelpItemOtherHelp = 2
kCMHelpItemRemoveHelp = 3
kCMNothingSelected = 0
kCMMenuItemSelected = 1
kCMShowHelpSelected = 3
keyContextualMenuName = FOUR_CHAR_CODE('pnam')
keyContextualMenuCommandID = FOUR_CHAR_CODE('cmcd')
keyContextualMenuSubmenu = FOUR_CHAR_CODE('cmsb')
keyContextualMenuAttributes = FOUR_CHAR_CODE('cmat')
keyContextualMenuModifiers = FOUR_CHAR_CODE('cmmd')
| Python |
from _File import *
| Python |
from _Scrap import *
| Python |
# Generated from 'MacTextEditor.h'
def FOUR_CHAR_CODE(x): return x
false = 0
true = 1
kTXNClearThisControl = 0xFFFFFFFF
kTXNClearTheseFontFeatures = 0x80000000
kTXNDontCareTypeSize = 0xFFFFFFFF
kTXNDecrementTypeSize = 0x80000000
kTXNUseCurrentSelection = 0xFFFFFFFF
kTXNStartOffset = 0
kTXNEndOffset = 0x7FFFFFFF
MovieFileType = FOUR_CHAR_CODE('moov')
kTXNUseEncodingWordRulesMask = 0x80000000
kTXNFontSizeAttributeSize = 4
normal = 0
kTXNWillDefaultToATSUIBit = 0
kTXNWillDefaultToCarbonEventBit = 1
kTXNWillDefaultToATSUIMask = 1L << kTXNWillDefaultToATSUIBit
kTXNWillDefaultToCarbonEventMask = 1L << kTXNWillDefaultToCarbonEventBit
kTXNWantMoviesBit = 0
kTXNWantSoundBit = 1
kTXNWantGraphicsBit = 2
kTXNAlwaysUseQuickDrawTextBit = 3
kTXNUseTemporaryMemoryBit = 4
kTXNWantMoviesMask = 1L << kTXNWantMoviesBit
kTXNWantSoundMask = 1L << kTXNWantSoundBit
kTXNWantGraphicsMask = 1L << kTXNWantGraphicsBit
kTXNAlwaysUseQuickDrawTextMask = 1L << kTXNAlwaysUseQuickDrawTextBit
kTXNUseTemporaryMemoryMask = 1L << kTXNUseTemporaryMemoryBit
kTXNDrawGrowIconBit = 0
kTXNShowWindowBit = 1
kTXNWantHScrollBarBit = 2
kTXNWantVScrollBarBit = 3
kTXNNoTSMEverBit = 4
kTXNReadOnlyBit = 5
kTXNNoKeyboardSyncBit = 6
kTXNNoSelectionBit = 7
kTXNSaveStylesAsSTYLResourceBit = 8
kOutputTextInUnicodeEncodingBit = 9
kTXNDoNotInstallDragProcsBit = 10
kTXNAlwaysWrapAtViewEdgeBit = 11
kTXNDontDrawCaretWhenInactiveBit = 12
kTXNDontDrawSelectionWhenInactiveBit = 13
kTXNSingleLineOnlyBit = 14
kTXNDisableDragAndDropBit = 15
kTXNUseQDforImagingBit = 16
kTXNDrawGrowIconMask = 1L << kTXNDrawGrowIconBit
kTXNShowWindowMask = 1L << kTXNShowWindowBit
kTXNWantHScrollBarMask = 1L << kTXNWantHScrollBarBit
kTXNWantVScrollBarMask = 1L << kTXNWantVScrollBarBit
kTXNNoTSMEverMask = 1L << kTXNNoTSMEverBit
kTXNReadOnlyMask = 1L << kTXNReadOnlyBit
kTXNNoKeyboardSyncMask = 1L << kTXNNoKeyboardSyncBit
kTXNNoSelectionMask = 1L << kTXNNoSelectionBit
kTXNSaveStylesAsSTYLResourceMask = 1L << kTXNSaveStylesAsSTYLResourceBit
kOutputTextInUnicodeEncodingMask = 1L << kOutputTextInUnicodeEncodingBit
kTXNDoNotInstallDragProcsMask = 1L << kTXNDoNotInstallDragProcsBit
kTXNAlwaysWrapAtViewEdgeMask = 1L << kTXNAlwaysWrapAtViewEdgeBit
kTXNDontDrawCaretWhenInactiveMask = 1L << kTXNDontDrawCaretWhenInactiveBit
kTXNDontDrawSelectionWhenInactiveMask = 1L << kTXNDontDrawSelectionWhenInactiveBit
kTXNSingleLineOnlyMask = 1L << kTXNSingleLineOnlyBit
kTXNDisableDragAndDropMask = 1L << kTXNDisableDragAndDropBit
kTXNUseQDforImagingMask = 1L << kTXNUseQDforImagingBit
kTXNSetFlushnessBit = 0
kTXNSetJustificationBit = 1
kTXNUseFontFallBackBit = 2
kTXNRotateTextBit = 3
kTXNUseVerticalTextBit = 4
kTXNDontUpdateBoxRectBit = 5
kTXNDontDrawTextBit = 6
kTXNUseCGContextRefBit = 7
kTXNImageWithQDBit = 8
kTXNDontWrapTextBit = 9
kTXNSetFlushnessMask = 1L << kTXNSetFlushnessBit
kTXNSetJustificationMask = 1L << kTXNSetJustificationBit
kTXNUseFontFallBackMask = 1L << kTXNUseFontFallBackBit
kTXNRotateTextMask = 1L << kTXNRotateTextBit
kTXNUseVerticalTextMask = 1L << kTXNUseVerticalTextBit
kTXNDontUpdateBoxRectMask = 1L << kTXNDontUpdateBoxRectBit
kTXNDontDrawTextMask = 1L << kTXNDontDrawTextBit
kTXNUseCGContextRefMask = 1L << kTXNUseCGContextRefBit
kTXNImageWithQDMask = 1L << kTXNImageWithQDBit
kTXNDontWrapTextMask = 1L << kTXNDontWrapTextBit
kTXNFontContinuousBit = 0
kTXNSizeContinuousBit = 1
kTXNStyleContinuousBit = 2
kTXNColorContinuousBit = 3
kTXNFontContinuousMask = 1L << kTXNFontContinuousBit
kTXNSizeContinuousMask = 1L << kTXNSizeContinuousBit
kTXNStyleContinuousMask = 1L << kTXNStyleContinuousBit
kTXNColorContinuousMask = 1L << kTXNColorContinuousBit
kTXNIgnoreCaseBit = 0
kTXNEntireWordBit = 1
kTXNUseEncodingWordRulesBit = 31
kTXNIgnoreCaseMask = 1L << kTXNIgnoreCaseBit
kTXNEntireWordMask = 1L << kTXNEntireWordBit
# kTXNUseEncodingWordRulesMask = (unsigned long)(1L << kTXNUseEncodingWordRulesBit)
kTXNTextensionFile = FOUR_CHAR_CODE('txtn')
kTXNTextFile = FOUR_CHAR_CODE('TEXT')
kTXNPictureFile = FOUR_CHAR_CODE('PICT')
kTXNMovieFile = FOUR_CHAR_CODE('MooV')
kTXNSoundFile = FOUR_CHAR_CODE('sfil')
kTXNAIFFFile = FOUR_CHAR_CODE('AIFF')
kTXNUnicodeTextFile = FOUR_CHAR_CODE('utxt')
kTXNTextEditStyleFrameType = 1
kTXNPageFrameType = 2
kTXNMultipleFrameType = 3
kTXNTextData = FOUR_CHAR_CODE('TEXT')
kTXNPictureData = FOUR_CHAR_CODE('PICT')
kTXNMovieData = FOUR_CHAR_CODE('moov')
kTXNSoundData = FOUR_CHAR_CODE('snd ')
kTXNUnicodeTextData = FOUR_CHAR_CODE('utxt')
kTXNLineDirectionTag = FOUR_CHAR_CODE('lndr')
kTXNJustificationTag = FOUR_CHAR_CODE('just')
kTXNIOPrivilegesTag = FOUR_CHAR_CODE('iopv')
kTXNSelectionStateTag = FOUR_CHAR_CODE('slst')
kTXNInlineStateTag = FOUR_CHAR_CODE('inst')
kTXNWordWrapStateTag = FOUR_CHAR_CODE('wwrs')
kTXNKeyboardSyncStateTag = FOUR_CHAR_CODE('kbsy')
kTXNAutoIndentStateTag = FOUR_CHAR_CODE('auin')
kTXNTabSettingsTag = FOUR_CHAR_CODE('tabs')
kTXNRefConTag = FOUR_CHAR_CODE('rfcn')
kTXNMarginsTag = FOUR_CHAR_CODE('marg')
kTXNFlattenMoviesTag = FOUR_CHAR_CODE('flat')
kTXNDoFontSubstitution = FOUR_CHAR_CODE('fSub')
kTXNNoUserIOTag = FOUR_CHAR_CODE('nuio')
kTXNUseCarbonEvents = FOUR_CHAR_CODE('cbcb')
kTXNDrawCaretWhenInactiveTag = FOUR_CHAR_CODE('dcrt')
kTXNDrawSelectionWhenInactiveTag = FOUR_CHAR_CODE('dsln')
kTXNDisableDragAndDropTag = FOUR_CHAR_CODE('drag')
kTXNTypingAction = 0
kTXNCutAction = 1
kTXNPasteAction = 2
kTXNClearAction = 3
kTXNChangeFontAction = 4
kTXNChangeFontColorAction = 5
kTXNChangeFontSizeAction = 6
kTXNChangeStyleAction = 7
kTXNAlignLeftAction = 8
kTXNAlignCenterAction = 9
kTXNAlignRightAction = 10
kTXNDropAction = 11
kTXNMoveAction = 12
kTXNFontFeatureAction = 13
kTXNFontVariationAction = 14
kTXNUndoLastAction = 1024
# kTXNClearThisControl = (long)0xFFFFFFFF
# kTXNClearTheseFontFeatures = (long)0x80000000
kTXNReadWrite = false
kTXNReadOnly = true
kTXNSelectionOn = true
kTXNSelectionOff = false
kTXNUseInline = false
kTXNUseBottomline = true
kTXNAutoWrap = false
kTXNNoAutoWrap = true
kTXNSyncKeyboard = false
kTXNNoSyncKeyboard = true
kTXNAutoIndentOff = false
kTXNAutoIndentOn = true
kTXNDontDrawCaretWhenInactive = false
kTXNDrawCaretWhenInactive = true
kTXNDontDrawSelectionWhenInactive = false
kTXNDrawSelectionWhenInactive = true
kTXNEnableDragAndDrop = false
kTXNDisableDragAndDrop = true
kTXNRightTab = -1
kTXNLeftTab = 0
kTXNCenterTab = 1
kTXNLeftToRight = 0
kTXNRightToLeft = 1
kTXNFlushDefault = 0
kTXNFlushLeft = 1
kTXNFlushRight = 2
kTXNCenter = 4
kTXNFullJust = 8
kTXNForceFullJust = 16
kScrollBarsAlwaysActive = true
kScrollBarsSyncWithFocus = false
# kTXNDontCareTypeSize = (long)0xFFFFFFFF
kTXNDontCareTypeStyle = 0xFF
kTXNIncrementTypeSize = 0x00000001
# kTXNDecrementTypeSize = (long)0x80000000
kTXNUseScriptDefaultValue = -1
kTXNNoFontVariations = 0x7FFF
# kTXNUseCurrentSelection = (unsigned long)0xFFFFFFFF
# kTXNStartOffset = 0
# kTXNEndOffset = 0x7FFFFFFF
kTXNSingleStylePerTextDocumentResType = FOUR_CHAR_CODE('MPSR')
kTXNMultipleStylesPerTextDocumentResType = FOUR_CHAR_CODE('styl')
kTXNShowStart = false
kTXNShowEnd = true
kTXNDefaultFontName = 0
kTXNDefaultFontSize = 0x000C0000
kTXNDefaultFontStyle = normal
kTXNQDFontNameAttribute = FOUR_CHAR_CODE('fntn')
kTXNQDFontFamilyIDAttribute = FOUR_CHAR_CODE('font')
kTXNQDFontSizeAttribute = FOUR_CHAR_CODE('size')
kTXNQDFontStyleAttribute = FOUR_CHAR_CODE('face')
kTXNQDFontColorAttribute = FOUR_CHAR_CODE('klor')
kTXNTextEncodingAttribute = FOUR_CHAR_CODE('encd')
kTXNATSUIFontFeaturesAttribute = FOUR_CHAR_CODE('atfe')
kTXNATSUIFontVariationsAttribute = FOUR_CHAR_CODE('atva')
# kTXNQDFontNameAttributeSize = sizeof(Str255)
# kTXNQDFontFamilyIDAttributeSize = sizeof(SInt16)
# kTXNQDFontSizeAttributeSize = sizeof(SInt16)
# kTXNQDFontStyleAttributeSize = sizeof(Style)
# kTXNQDFontColorAttributeSize = sizeof(RGBColor)
# kTXNTextEncodingAttributeSize = sizeof(TextEncoding)
# kTXNFontSizeAttributeSize = sizeof(Fixed)
kTXNSystemDefaultEncoding = 0
kTXNMacOSEncoding = 1
kTXNUnicodeEncoding = 2
kTXNBackgroundTypeRGB = 1
kTXNTextInputCountBit = 0
kTXNRunCountBit = 1
kTXNTextInputCountMask = 1L << kTXNTextInputCountBit
kTXNRunCountMask = 1L << kTXNRunCountBit
kTXNAllCountMask = kTXNTextInputCountMask | kTXNRunCountMask
kTXNNoAppleEventHandlersBit = 0
kTXNRestartAppleEventHandlersBit = 1
kTXNNoAppleEventHandlersMask = 1 << kTXNNoAppleEventHandlersBit
kTXNRestartAppleEventHandlersMask = 1 << kTXNRestartAppleEventHandlersBit
# status = TXNInitTextension( &defaults
| Python |
from _TE import *
| Python |
from _List import *
| Python |
# Accessor functions for control properties
from Controls import *
import struct
# These needn't go through this module, but are here for completeness
def SetControlData_Handle(control, part, selector, data):
control.SetControlData_Handle(part, selector, data)
def GetControlData_Handle(control, part, selector):
return control.GetControlData_Handle(part, selector)
_accessdict = {
kControlPopupButtonMenuHandleTag: (SetControlData_Handle, GetControlData_Handle),
}
_codingdict = {
kControlPushButtonDefaultTag : ("b", None, None),
kControlEditTextTextTag: (None, None, None),
kControlEditTextPasswordTag: (None, None, None),
kControlPopupButtonMenuIDTag: ("h", None, None),
kControlListBoxDoubleClickTag: ("b", None, None),
}
def SetControlData(control, part, selector, data):
if _accessdict.has_key(selector):
setfunc, getfunc = _accessdict[selector]
setfunc(control, part, selector, data)
return
if not _codingdict.has_key(selector):
raise KeyError, ('Unknown control selector', selector)
structfmt, coder, decoder = _codingdict[selector]
if coder:
data = coder(data)
if structfmt:
data = struct.pack(structfmt, data)
control.SetControlData(part, selector, data)
def GetControlData(control, part, selector):
if _accessdict.has_key(selector):
setfunc, getfunc = _accessdict[selector]
return getfunc(control, part, selector, data)
if not _codingdict.has_key(selector):
raise KeyError, ('Unknown control selector', selector)
structfmt, coder, decoder = _codingdict[selector]
data = control.GetControlData(part, selector)
if structfmt:
data = struct.unpack(structfmt, data)
if decoder:
data = decoder(data)
if type(data) == type(()) and len(data) == 1:
data = data[0]
return data
| Python |
# Generated from 'AppleHelp.h'
kAHInternalErr = -10790
kAHInternetConfigPrefErr = -10791
kAHTOCTypeUser = 0
kAHTOCTypeDeveloper = 1
| Python |
# Generated from 'Controls.h'
def FOUR_CHAR_CODE(x): return x
from Carbon.TextEdit import *
from Carbon.QuickDraw import *
from Carbon.Dragconst import *
from Carbon.CarbonEvents import *
from Carbon.Appearance import *
kDataBrowserItemAnyState = -1
kControlBevelButtonCenterPopupGlyphTag = -1
kDataBrowserClientPropertyFlagsMask = 0xFF000000
kControlDefProcType = FOUR_CHAR_CODE('CDEF')
kControlTemplateResourceType = FOUR_CHAR_CODE('CNTL')
kControlColorTableResourceType = FOUR_CHAR_CODE('cctb')
kControlDefProcResourceType = FOUR_CHAR_CODE('CDEF')
controlNotifyNothing = FOUR_CHAR_CODE('nada')
controlNotifyClick = FOUR_CHAR_CODE('clik')
controlNotifyFocus = FOUR_CHAR_CODE('focu')
controlNotifyKey = FOUR_CHAR_CODE('key ')
kControlCanAutoInvalidate = 1L << 0
staticTextProc = 256
editTextProc = 272
iconProc = 288
userItemProc = 304
pictItemProc = 320
cFrameColor = 0
cBodyColor = 1
cTextColor = 2
cThumbColor = 3
kNumberCtlCTabEntries = 4
kControlNoVariant = 0
kControlUsesOwningWindowsFontVariant = 1 << 3
kControlNoPart = 0
kControlIndicatorPart = 129
kControlDisabledPart = 254
kControlInactivePart = 255
kControlEntireControl = 0
kControlStructureMetaPart = -1
kControlContentMetaPart = -2
kControlFocusNoPart = 0
kControlFocusNextPart = -1
kControlFocusPrevPart = -2
kControlCollectionTagBounds = FOUR_CHAR_CODE('boun')
kControlCollectionTagValue = FOUR_CHAR_CODE('valu')
kControlCollectionTagMinimum = FOUR_CHAR_CODE('min ')
kControlCollectionTagMaximum = FOUR_CHAR_CODE('max ')
kControlCollectionTagViewSize = FOUR_CHAR_CODE('view')
kControlCollectionTagVisibility = FOUR_CHAR_CODE('visi')
kControlCollectionTagRefCon = FOUR_CHAR_CODE('refc')
kControlCollectionTagTitle = FOUR_CHAR_CODE('titl')
kControlCollectionTagUnicodeTitle = FOUR_CHAR_CODE('uttl')
kControlCollectionTagIDSignature = FOUR_CHAR_CODE('idsi')
kControlCollectionTagIDID = FOUR_CHAR_CODE('idid')
kControlCollectionTagCommand = FOUR_CHAR_CODE('cmd ')
kControlCollectionTagVarCode = FOUR_CHAR_CODE('varc')
kControlContentTextOnly = 0
kControlNoContent = 0
kControlContentIconSuiteRes = 1
kControlContentCIconRes = 2
kControlContentPictRes = 3
kControlContentICONRes = 4
kControlContentIconSuiteHandle = 129
kControlContentCIconHandle = 130
kControlContentPictHandle = 131
kControlContentIconRef = 132
kControlContentICON = 133
kControlKeyScriptBehaviorAllowAnyScript = FOUR_CHAR_CODE('any ')
kControlKeyScriptBehaviorPrefersRoman = FOUR_CHAR_CODE('prmn')
kControlKeyScriptBehaviorRequiresRoman = FOUR_CHAR_CODE('rrmn')
kControlFontBigSystemFont = -1
kControlFontSmallSystemFont = -2
kControlFontSmallBoldSystemFont = -3
kControlFontViewSystemFont = -4
kControlUseFontMask = 0x0001
kControlUseFaceMask = 0x0002
kControlUseSizeMask = 0x0004
kControlUseForeColorMask = 0x0008
kControlUseBackColorMask = 0x0010
kControlUseModeMask = 0x0020
kControlUseJustMask = 0x0040
kControlUseAllMask = 0x00FF
kControlAddFontSizeMask = 0x0100
kControlAddToMetaFontMask = 0x0200
kControlUseThemeFontIDMask = 0x0080
kDoNotActivateAndIgnoreClick = 0
kDoNotActivateAndHandleClick = 1
kActivateAndIgnoreClick = 2
kActivateAndHandleClick = 3
kControlFontStyleTag = FOUR_CHAR_CODE('font')
kControlKeyFilterTag = FOUR_CHAR_CODE('fltr')
kControlKindTag = FOUR_CHAR_CODE('kind')
kControlSizeTag = FOUR_CHAR_CODE('size')
kControlSupportsGhosting = 1 << 0
kControlSupportsEmbedding = 1 << 1
kControlSupportsFocus = 1 << 2
kControlWantsIdle = 1 << 3
kControlWantsActivate = 1 << 4
kControlHandlesTracking = 1 << 5
kControlSupportsDataAccess = 1 << 6
kControlHasSpecialBackground = 1 << 7
kControlGetsFocusOnClick = 1 << 8
kControlSupportsCalcBestRect = 1 << 9
kControlSupportsLiveFeedback = 1 << 10
kControlHasRadioBehavior = 1 << 11
kControlSupportsDragAndDrop = 1 << 12
kControlAutoToggles = 1 << 14
kControlSupportsGetRegion = 1 << 17
kControlSupportsFlattening = 1 << 19
kControlSupportsSetCursor = 1 << 20
kControlSupportsContextualMenus = 1 << 21
kControlSupportsClickActivation = 1 << 22
kControlIdlesWithTimer = 1 << 23
drawCntl = 0
testCntl = 1
calcCRgns = 2
initCntl = 3
dispCntl = 4
posCntl = 5
thumbCntl = 6
dragCntl = 7
autoTrack = 8
calcCntlRgn = 10
calcThumbRgn = 11
drawThumbOutline = 12
kControlMsgDrawGhost = 13
kControlMsgCalcBestRect = 14
kControlMsgHandleTracking = 15
kControlMsgFocus = 16
kControlMsgKeyDown = 17
kControlMsgIdle = 18
kControlMsgGetFeatures = 19
kControlMsgSetData = 20
kControlMsgGetData = 21
kControlMsgActivate = 22
kControlMsgSetUpBackground = 23
kControlMsgCalcValueFromPos = 26
kControlMsgTestNewMsgSupport = 27
kControlMsgSubValueChanged = 25
kControlMsgSubControlAdded = 28
kControlMsgSubControlRemoved = 29
kControlMsgApplyTextColor = 30
kControlMsgGetRegion = 31
kControlMsgFlatten = 32
kControlMsgSetCursor = 33
kControlMsgDragEnter = 38
kControlMsgDragLeave = 39
kControlMsgDragWithin = 40
kControlMsgDragReceive = 41
kControlMsgDisplayDebugInfo = 46
kControlMsgContextualMenuClick = 47
kControlMsgGetClickActivation = 48
kControlSizeNormal = 0
kControlSizeSmall = 1
kControlSizeLarge = 2
kControlSizeAuto = 0xFFFF
kDrawControlEntireControl = 0
kDrawControlIndicatorOnly = 129
kDragControlEntireControl = 0
kDragControlIndicator = 1
kControlSupportsNewMessages = FOUR_CHAR_CODE(' ok ')
kControlKeyFilterBlockKey = 0
kControlKeyFilterPassKey = 1
noConstraint = kNoConstraint
hAxisOnly = 1
vAxisOnly = 2
kControlDefProcPtr = 0
kControlDefObjectClass = 1
kControlKindSignatureApple = FOUR_CHAR_CODE('appl')
kControlPropertyPersistent = 0x00000001
kDragTrackingEnterControl = 2
kDragTrackingInControl = 3
kDragTrackingLeaveControl = 4
useWFont = kControlUsesOwningWindowsFontVariant
inThumb = kControlIndicatorPart
kNoHiliteControlPart = kControlNoPart
kInIndicatorControlPart = kControlIndicatorPart
kReservedControlPart = kControlDisabledPart
kControlInactiveControlPart = kControlInactivePart
kControlTabListResType = FOUR_CHAR_CODE('tab#')
kControlListDescResType = FOUR_CHAR_CODE('ldes')
kControlCheckBoxUncheckedValue = 0
kControlCheckBoxCheckedValue = 1
kControlCheckBoxMixedValue = 2
kControlRadioButtonUncheckedValue = 0
kControlRadioButtonCheckedValue = 1
kControlRadioButtonMixedValue = 2
popupFixedWidth = 1 << 0
popupVariableWidth = 1 << 1
popupUseAddResMenu = 1 << 2
popupUseWFont = 1 << 3
popupTitleBold = 1 << 8
popupTitleItalic = 1 << 9
popupTitleUnderline = 1 << 10
popupTitleOutline = 1 << 11
popupTitleShadow = 1 << 12
popupTitleCondense = 1 << 13
popupTitleExtend = 1 << 14
popupTitleNoStyle = 1 << 15
popupTitleLeftJust = 0x00000000
popupTitleCenterJust = 0x00000001
popupTitleRightJust = 0x000000FF
pushButProc = 0
checkBoxProc = 1
radioButProc = 2
scrollBarProc = 16
popupMenuProc = 1008
kControlLabelPart = 1
kControlMenuPart = 2
kControlTrianglePart = 4
kControlEditTextPart = 5
kControlPicturePart = 6
kControlIconPart = 7
kControlClockPart = 8
kControlListBoxPart = 24
kControlListBoxDoubleClickPart = 25
kControlImageWellPart = 26
kControlRadioGroupPart = 27
kControlButtonPart = 10
kControlCheckBoxPart = 11
kControlRadioButtonPart = 11
kControlUpButtonPart = 20
kControlDownButtonPart = 21
kControlPageUpPart = 22
kControlPageDownPart = 23
kControlClockHourDayPart = 9
kControlClockMinuteMonthPart = 10
kControlClockSecondYearPart = 11
kControlClockAMPMPart = 12
kControlDataBrowserPart = 24
kControlDataBrowserDraggedPart = 25
kControlBevelButtonSmallBevelProc = 32
kControlBevelButtonNormalBevelProc = 33
kControlBevelButtonLargeBevelProc = 34
kControlBevelButtonSmallBevelVariant = 0
kControlBevelButtonNormalBevelVariant = (1 << 0)
kControlBevelButtonLargeBevelVariant = (1 << 1)
kControlBevelButtonMenuOnRightVariant = (1 << 2)
kControlBevelButtonSmallBevel = 0
kControlBevelButtonNormalBevel = 1
kControlBevelButtonLargeBevel = 2
kControlBehaviorPushbutton = 0
kControlBehaviorToggles = 0x0100
kControlBehaviorSticky = 0x0200
kControlBehaviorSingleValueMenu = 0
kControlBehaviorMultiValueMenu = 0x4000
kControlBehaviorOffsetContents = 0x8000
kControlBehaviorCommandMenu = 0x2000
kControlBevelButtonMenuOnBottom = 0
kControlBevelButtonMenuOnRight = (1 << 2)
kControlKindBevelButton = FOUR_CHAR_CODE('bevl')
kControlBevelButtonAlignSysDirection = -1
kControlBevelButtonAlignCenter = 0
kControlBevelButtonAlignLeft = 1
kControlBevelButtonAlignRight = 2
kControlBevelButtonAlignTop = 3
kControlBevelButtonAlignBottom = 4
kControlBevelButtonAlignTopLeft = 5
kControlBevelButtonAlignBottomLeft = 6
kControlBevelButtonAlignTopRight = 7
kControlBevelButtonAlignBottomRight = 8
kControlBevelButtonAlignTextSysDirection = teFlushDefault
kControlBevelButtonAlignTextCenter = teCenter
kControlBevelButtonAlignTextFlushRight = teFlushRight
kControlBevelButtonAlignTextFlushLeft = teFlushLeft
kControlBevelButtonPlaceSysDirection = -1
kControlBevelButtonPlaceNormally = 0
kControlBevelButtonPlaceToRightOfGraphic = 1
kControlBevelButtonPlaceToLeftOfGraphic = 2
kControlBevelButtonPlaceBelowGraphic = 3
kControlBevelButtonPlaceAboveGraphic = 4
kControlBevelButtonContentTag = FOUR_CHAR_CODE('cont')
kControlBevelButtonTransformTag = FOUR_CHAR_CODE('tran')
kControlBevelButtonTextAlignTag = FOUR_CHAR_CODE('tali')
kControlBevelButtonTextOffsetTag = FOUR_CHAR_CODE('toff')
kControlBevelButtonGraphicAlignTag = FOUR_CHAR_CODE('gali')
kControlBevelButtonGraphicOffsetTag = FOUR_CHAR_CODE('goff')
kControlBevelButtonTextPlaceTag = FOUR_CHAR_CODE('tplc')
kControlBevelButtonMenuValueTag = FOUR_CHAR_CODE('mval')
kControlBevelButtonMenuHandleTag = FOUR_CHAR_CODE('mhnd')
kControlBevelButtonMenuRefTag = FOUR_CHAR_CODE('mhnd')
# kControlBevelButtonCenterPopupGlyphTag = FOUR_CHAR_CODE('pglc')
kControlBevelButtonLastMenuTag = FOUR_CHAR_CODE('lmnu')
kControlBevelButtonMenuDelayTag = FOUR_CHAR_CODE('mdly')
kControlBevelButtonScaleIconTag = FOUR_CHAR_CODE('scal')
kControlBevelButtonOwnedMenuRefTag = FOUR_CHAR_CODE('omrf')
kControlBevelButtonKindTag = FOUR_CHAR_CODE('bebk')
kControlSliderProc = 48
kControlSliderLiveFeedback = (1 << 0)
kControlSliderHasTickMarks = (1 << 1)
kControlSliderReverseDirection = (1 << 2)
kControlSliderNonDirectional = (1 << 3)
kControlSliderPointsDownOrRight = 0
kControlSliderPointsUpOrLeft = 1
kControlSliderDoesNotPoint = 2
kControlKindSlider = FOUR_CHAR_CODE('sldr')
kControlTriangleProc = 64
kControlTriangleLeftFacingProc = 65
kControlTriangleAutoToggleProc = 66
kControlTriangleLeftFacingAutoToggleProc = 67
kControlDisclosureTrianglePointDefault = 0
kControlDisclosureTrianglePointRight = 1
kControlDisclosureTrianglePointLeft = 2
kControlKindDisclosureTriangle = FOUR_CHAR_CODE('dist')
kControlTriangleLastValueTag = FOUR_CHAR_CODE('last')
kControlProgressBarProc = 80
kControlRelevanceBarProc = 81
kControlKindProgressBar = FOUR_CHAR_CODE('prgb')
kControlKindRelevanceBar = FOUR_CHAR_CODE('relb')
kControlProgressBarIndeterminateTag = FOUR_CHAR_CODE('inde')
kControlProgressBarAnimatingTag = FOUR_CHAR_CODE('anim')
kControlLittleArrowsProc = 96
kControlKindLittleArrows = FOUR_CHAR_CODE('larr')
kControlChasingArrowsProc = 112
kControlKindChasingArrows = FOUR_CHAR_CODE('carr')
kControlChasingArrowsAnimatingTag = FOUR_CHAR_CODE('anim')
kControlTabLargeProc = 128
kControlTabSmallProc = 129
kControlTabLargeNorthProc = 128
kControlTabSmallNorthProc = 129
kControlTabLargeSouthProc = 130
kControlTabSmallSouthProc = 131
kControlTabLargeEastProc = 132
kControlTabSmallEastProc = 133
kControlTabLargeWestProc = 134
kControlTabSmallWestProc = 135
kControlTabDirectionNorth = 0
kControlTabDirectionSouth = 1
kControlTabDirectionEast = 2
kControlTabDirectionWest = 3
kControlTabSizeLarge = kControlSizeNormal
kControlTabSizeSmall = kControlSizeSmall
kControlKindTabs = FOUR_CHAR_CODE('tabs')
kControlTabContentRectTag = FOUR_CHAR_CODE('rect')
kControlTabEnabledFlagTag = FOUR_CHAR_CODE('enab')
kControlTabFontStyleTag = kControlFontStyleTag
kControlTabInfoTag = FOUR_CHAR_CODE('tabi')
kControlTabImageContentTag = FOUR_CHAR_CODE('cont')
kControlTabInfoVersionZero = 0
kControlTabInfoVersionOne = 1
kControlSeparatorLineProc = 144
kControlKindSeparator = FOUR_CHAR_CODE('sepa')
kControlGroupBoxTextTitleProc = 160
kControlGroupBoxCheckBoxProc = 161
kControlGroupBoxPopupButtonProc = 162
kControlGroupBoxSecondaryTextTitleProc = 164
kControlGroupBoxSecondaryCheckBoxProc = 165
kControlGroupBoxSecondaryPopupButtonProc = 166
kControlKindGroupBox = FOUR_CHAR_CODE('grpb')
kControlKindCheckGroupBox = FOUR_CHAR_CODE('cgrp')
kControlKindPopupGroupBox = FOUR_CHAR_CODE('pgrp')
kControlGroupBoxMenuHandleTag = FOUR_CHAR_CODE('mhan')
kControlGroupBoxMenuRefTag = FOUR_CHAR_CODE('mhan')
kControlGroupBoxFontStyleTag = kControlFontStyleTag
kControlGroupBoxTitleRectTag = FOUR_CHAR_CODE('trec')
kControlImageWellProc = 176
kControlKindImageWell = FOUR_CHAR_CODE('well')
kControlImageWellContentTag = FOUR_CHAR_CODE('cont')
kControlImageWellTransformTag = FOUR_CHAR_CODE('tran')
kControlImageWellIsDragDestinationTag = FOUR_CHAR_CODE('drag')
kControlPopupArrowEastProc = 192
kControlPopupArrowWestProc = 193
kControlPopupArrowNorthProc = 194
kControlPopupArrowSouthProc = 195
kControlPopupArrowSmallEastProc = 196
kControlPopupArrowSmallWestProc = 197
kControlPopupArrowSmallNorthProc = 198
kControlPopupArrowSmallSouthProc = 199
kControlPopupArrowOrientationEast = 0
kControlPopupArrowOrientationWest = 1
kControlPopupArrowOrientationNorth = 2
kControlPopupArrowOrientationSouth = 3
kControlPopupArrowSizeNormal = 0
kControlPopupArrowSizeSmall = 1
kControlKindPopupArrow = FOUR_CHAR_CODE('parr')
kControlPlacardProc = 224
kControlKindPlacard = FOUR_CHAR_CODE('plac')
kControlClockTimeProc = 240
kControlClockTimeSecondsProc = 241
kControlClockDateProc = 242
kControlClockMonthYearProc = 243
kControlClockTypeHourMinute = 0
kControlClockTypeHourMinuteSecond = 1
kControlClockTypeMonthDayYear = 2
kControlClockTypeMonthYear = 3
kControlClockFlagStandard = 0
kControlClockNoFlags = 0
kControlClockFlagDisplayOnly = 1
kControlClockIsDisplayOnly = 1
kControlClockFlagLive = 2
kControlClockIsLive = 2
kControlKindClock = FOUR_CHAR_CODE('clck')
kControlClockLongDateTag = FOUR_CHAR_CODE('date')
kControlClockFontStyleTag = kControlFontStyleTag
kControlClockAnimatingTag = FOUR_CHAR_CODE('anim')
kControlUserPaneProc = 256
kControlKindUserPane = FOUR_CHAR_CODE('upan')
kControlUserItemDrawProcTag = FOUR_CHAR_CODE('uidp')
kControlUserPaneDrawProcTag = FOUR_CHAR_CODE('draw')
kControlUserPaneHitTestProcTag = FOUR_CHAR_CODE('hitt')
kControlUserPaneTrackingProcTag = FOUR_CHAR_CODE('trak')
kControlUserPaneIdleProcTag = FOUR_CHAR_CODE('idle')
kControlUserPaneKeyDownProcTag = FOUR_CHAR_CODE('keyd')
kControlUserPaneActivateProcTag = FOUR_CHAR_CODE('acti')
kControlUserPaneFocusProcTag = FOUR_CHAR_CODE('foci')
kControlUserPaneBackgroundProcTag = FOUR_CHAR_CODE('back')
kControlEditTextProc = 272
kControlEditTextPasswordProc = 274
kControlEditTextInlineInputProc = 276
kControlKindEditText = FOUR_CHAR_CODE('etxt')
kControlEditTextStyleTag = kControlFontStyleTag
kControlEditTextTextTag = FOUR_CHAR_CODE('text')
kControlEditTextTEHandleTag = FOUR_CHAR_CODE('than')
kControlEditTextKeyFilterTag = kControlKeyFilterTag
kControlEditTextSelectionTag = FOUR_CHAR_CODE('sele')
kControlEditTextPasswordTag = FOUR_CHAR_CODE('pass')
kControlEditTextKeyScriptBehaviorTag = FOUR_CHAR_CODE('kscr')
kControlEditTextLockedTag = FOUR_CHAR_CODE('lock')
kControlEditTextFixedTextTag = FOUR_CHAR_CODE('ftxt')
kControlEditTextValidationProcTag = FOUR_CHAR_CODE('vali')
kControlEditTextInlinePreUpdateProcTag = FOUR_CHAR_CODE('prup')
kControlEditTextInlinePostUpdateProcTag = FOUR_CHAR_CODE('poup')
kControlEditTextCFStringTag = FOUR_CHAR_CODE('cfst')
kControlEditTextPasswordCFStringTag = FOUR_CHAR_CODE('pwcf')
kControlStaticTextProc = 288
kControlKindStaticText = FOUR_CHAR_CODE('stxt')
kControlStaticTextStyleTag = kControlFontStyleTag
kControlStaticTextTextTag = FOUR_CHAR_CODE('text')
kControlStaticTextTextHeightTag = FOUR_CHAR_CODE('thei')
kControlStaticTextTruncTag = FOUR_CHAR_CODE('trun')
kControlStaticTextCFStringTag = FOUR_CHAR_CODE('cfst')
kControlPictureProc = 304
kControlPictureNoTrackProc = 305
kControlKindPicture = FOUR_CHAR_CODE('pict')
kControlPictureHandleTag = FOUR_CHAR_CODE('pich')
kControlIconProc = 320
kControlIconNoTrackProc = 321
kControlIconSuiteProc = 322
kControlIconSuiteNoTrackProc = 323
kControlIconRefProc = 324
kControlIconRefNoTrackProc = 325
kControlKindIcon = FOUR_CHAR_CODE('icon')
kControlIconTransformTag = FOUR_CHAR_CODE('trfm')
kControlIconAlignmentTag = FOUR_CHAR_CODE('algn')
kControlIconResourceIDTag = FOUR_CHAR_CODE('ires')
kControlIconContentTag = FOUR_CHAR_CODE('cont')
kControlWindowHeaderProc = 336
kControlWindowListViewHeaderProc = 337
kControlKindWindowHeader = FOUR_CHAR_CODE('whed')
kControlListBoxProc = 352
kControlListBoxAutoSizeProc = 353
kControlKindListBox = FOUR_CHAR_CODE('lbox')
kControlListBoxListHandleTag = FOUR_CHAR_CODE('lhan')
kControlListBoxKeyFilterTag = kControlKeyFilterTag
kControlListBoxFontStyleTag = kControlFontStyleTag
kControlListBoxDoubleClickTag = FOUR_CHAR_CODE('dblc')
kControlListBoxLDEFTag = FOUR_CHAR_CODE('ldef')
kControlPushButtonProc = 368
kControlCheckBoxProc = 369
kControlRadioButtonProc = 370
kControlPushButLeftIconProc = 374
kControlPushButRightIconProc = 375
kControlCheckBoxAutoToggleProc = 371
kControlRadioButtonAutoToggleProc = 372
kControlPushButtonIconOnLeft = 6
kControlPushButtonIconOnRight = 7
kControlKindPushButton = FOUR_CHAR_CODE('push')
kControlKindPushIconButton = FOUR_CHAR_CODE('picn')
kControlKindRadioButton = FOUR_CHAR_CODE('rdio')
kControlKindCheckBox = FOUR_CHAR_CODE('cbox')
kControlPushButtonDefaultTag = FOUR_CHAR_CODE('dflt')
kControlPushButtonCancelTag = FOUR_CHAR_CODE('cncl')
kControlScrollBarProc = 384
kControlScrollBarLiveProc = 386
kControlKindScrollBar = FOUR_CHAR_CODE('sbar')
kControlScrollBarShowsArrowsTag = FOUR_CHAR_CODE('arro')
kControlPopupButtonProc = 400
kControlPopupFixedWidthVariant = 1 << 0
kControlPopupVariableWidthVariant = 1 << 1
kControlPopupUseAddResMenuVariant = 1 << 2
kControlPopupUseWFontVariant = kControlUsesOwningWindowsFontVariant
kControlKindPopupButton = FOUR_CHAR_CODE('popb')
kControlPopupButtonMenuHandleTag = FOUR_CHAR_CODE('mhan')
kControlPopupButtonMenuRefTag = FOUR_CHAR_CODE('mhan')
kControlPopupButtonMenuIDTag = FOUR_CHAR_CODE('mnid')
kControlPopupButtonExtraHeightTag = FOUR_CHAR_CODE('exht')
kControlPopupButtonOwnedMenuRefTag = FOUR_CHAR_CODE('omrf')
kControlPopupButtonCheckCurrentTag = FOUR_CHAR_CODE('chck')
kControlRadioGroupProc = 416
kControlKindRadioGroup = FOUR_CHAR_CODE('rgrp')
kControlScrollTextBoxProc = 432
kControlScrollTextBoxAutoScrollProc = 433
kControlKindScrollingTextBox = FOUR_CHAR_CODE('stbx')
kControlScrollTextBoxDelayBeforeAutoScrollTag = FOUR_CHAR_CODE('stdl')
kControlScrollTextBoxDelayBetweenAutoScrollTag = FOUR_CHAR_CODE('scdl')
kControlScrollTextBoxAutoScrollAmountTag = FOUR_CHAR_CODE('samt')
kControlScrollTextBoxContentsTag = FOUR_CHAR_CODE('tres')
kControlScrollTextBoxAnimatingTag = FOUR_CHAR_CODE('anim')
kControlKindDisclosureButton = FOUR_CHAR_CODE('disb')
kControlDisclosureButtonClosed = 0
kControlDisclosureButtonDisclosed = 1
kControlRoundButtonNormalSize = kControlSizeNormal
kControlRoundButtonLargeSize = kControlSizeLarge
kControlRoundButtonContentTag = FOUR_CHAR_CODE('cont')
kControlRoundButtonSizeTag = kControlSizeTag
kControlKindRoundButton = FOUR_CHAR_CODE('rndb')
kControlKindDataBrowser = FOUR_CHAR_CODE('datb')
errDataBrowserNotConfigured = -4970
errDataBrowserItemNotFound = -4971
errDataBrowserItemNotAdded = -4975
errDataBrowserPropertyNotFound = -4972
errDataBrowserInvalidPropertyPart = -4973
errDataBrowserInvalidPropertyData = -4974
errDataBrowserPropertyNotSupported = -4979
kControlDataBrowserIncludesFrameAndFocusTag = FOUR_CHAR_CODE('brdr')
kControlDataBrowserKeyFilterTag = kControlEditTextKeyFilterTag
kControlDataBrowserEditTextKeyFilterTag = kControlDataBrowserKeyFilterTag
kControlDataBrowserEditTextValidationProcTag = kControlEditTextValidationProcTag
kDataBrowserNoView = 0x3F3F3F3F
kDataBrowserListView = FOUR_CHAR_CODE('lstv')
kDataBrowserColumnView = FOUR_CHAR_CODE('clmv')
kDataBrowserDragSelect = 1 << 0
kDataBrowserSelectOnlyOne = 1 << 1
kDataBrowserResetSelection = 1 << 2
kDataBrowserCmdTogglesSelection = 1 << 3
kDataBrowserNoDisjointSelection = 1 << 4
kDataBrowserAlwaysExtendSelection = 1 << 5
kDataBrowserNeverEmptySelectionSet = 1 << 6
kDataBrowserOrderUndefined = 0
kDataBrowserOrderIncreasing = 1
kDataBrowserOrderDecreasing = 2
kDataBrowserNoItem = 0L
kDataBrowserItemNoState = 0
# kDataBrowserItemAnyState = (unsigned long)(-1)
kDataBrowserItemIsSelected = 1 << 0
kDataBrowserContainerIsOpen = 1 << 1
kDataBrowserItemIsDragTarget = 1 << 2
kDataBrowserRevealOnly = 0
kDataBrowserRevealAndCenterInView = 1 << 0
kDataBrowserRevealWithoutSelecting = 1 << 1
kDataBrowserItemsAdd = 0
kDataBrowserItemsAssign = 1
kDataBrowserItemsToggle = 2
kDataBrowserItemsRemove = 3
kDataBrowserSelectionAnchorUp = 0
kDataBrowserSelectionAnchorDown = 1
kDataBrowserSelectionAnchorLeft = 2
kDataBrowserSelectionAnchorRight = 3
kDataBrowserEditMsgUndo = kHICommandUndo
kDataBrowserEditMsgRedo = kHICommandRedo
kDataBrowserEditMsgCut = kHICommandCut
kDataBrowserEditMsgCopy = kHICommandCopy
kDataBrowserEditMsgPaste = kHICommandPaste
kDataBrowserEditMsgClear = kHICommandClear
kDataBrowserEditMsgSelectAll = kHICommandSelectAll
kDataBrowserItemAdded = 1
kDataBrowserItemRemoved = 2
kDataBrowserEditStarted = 3
kDataBrowserEditStopped = 4
kDataBrowserItemSelected = 5
kDataBrowserItemDeselected = 6
kDataBrowserItemDoubleClicked = 7
kDataBrowserContainerOpened = 8
kDataBrowserContainerClosing = 9
kDataBrowserContainerClosed = 10
kDataBrowserContainerSorting = 11
kDataBrowserContainerSorted = 12
kDataBrowserUserToggledContainer = 16
kDataBrowserTargetChanged = 15
kDataBrowserUserStateChanged = 13
kDataBrowserSelectionSetChanged = 14
kDataBrowserItemNoProperty = 0L
kDataBrowserItemIsActiveProperty = 1L
kDataBrowserItemIsSelectableProperty = 2L
kDataBrowserItemIsEditableProperty = 3L
kDataBrowserItemIsContainerProperty = 4L
kDataBrowserContainerIsOpenableProperty = 5L
kDataBrowserContainerIsClosableProperty = 6L
kDataBrowserContainerIsSortableProperty = 7L
kDataBrowserItemSelfIdentityProperty = 8L
kDataBrowserContainerAliasIDProperty = 9L
kDataBrowserColumnViewPreviewProperty = 10L
kDataBrowserItemParentContainerProperty = 11L
kDataBrowserCustomType = 0x3F3F3F3F
kDataBrowserIconType = FOUR_CHAR_CODE('icnr')
kDataBrowserTextType = FOUR_CHAR_CODE('text')
kDataBrowserDateTimeType = FOUR_CHAR_CODE('date')
kDataBrowserSliderType = FOUR_CHAR_CODE('sldr')
kDataBrowserCheckboxType = FOUR_CHAR_CODE('chbx')
kDataBrowserProgressBarType = FOUR_CHAR_CODE('prog')
kDataBrowserRelevanceRankType = FOUR_CHAR_CODE('rank')
kDataBrowserPopupMenuType = FOUR_CHAR_CODE('menu')
kDataBrowserIconAndTextType = FOUR_CHAR_CODE('ticn')
kDataBrowserPropertyEnclosingPart = 0L
kDataBrowserPropertyContentPart = FOUR_CHAR_CODE('----')
kDataBrowserPropertyDisclosurePart = FOUR_CHAR_CODE('disc')
kDataBrowserPropertyTextPart = kDataBrowserTextType
kDataBrowserPropertyIconPart = kDataBrowserIconType
kDataBrowserPropertySliderPart = kDataBrowserSliderType
kDataBrowserPropertyCheckboxPart = kDataBrowserCheckboxType
kDataBrowserPropertyProgressBarPart = kDataBrowserProgressBarType
kDataBrowserPropertyRelevanceRankPart = kDataBrowserRelevanceRankType
kDataBrowserUniversalPropertyFlagsMask = 0xFF
kDataBrowserPropertyIsMutable = 1 << 0
kDataBrowserDefaultPropertyFlags = 0 << 0
kDataBrowserUniversalPropertyFlags = kDataBrowserUniversalPropertyFlagsMask
kDataBrowserPropertyIsEditable = kDataBrowserPropertyIsMutable
kDataBrowserPropertyFlagsOffset = 8
kDataBrowserPropertyFlagsMask = 0xFF << kDataBrowserPropertyFlagsOffset
kDataBrowserCheckboxTriState = 1 << kDataBrowserPropertyFlagsOffset
kDataBrowserDateTimeRelative = 1 << (kDataBrowserPropertyFlagsOffset)
kDataBrowserDateTimeDateOnly = 1 << (kDataBrowserPropertyFlagsOffset + 1)
kDataBrowserDateTimeTimeOnly = 1 << (kDataBrowserPropertyFlagsOffset + 2)
kDataBrowserDateTimeSecondsToo = 1 << (kDataBrowserPropertyFlagsOffset + 3)
kDataBrowserSliderPlainThumb = kThemeThumbPlain << kDataBrowserPropertyFlagsOffset
kDataBrowserSliderUpwardThumb = kThemeThumbUpward << kDataBrowserPropertyFlagsOffset
kDataBrowserSliderDownwardThumb = kThemeThumbDownward << kDataBrowserPropertyFlagsOffset
kDataBrowserDoNotTruncateText = 3 << kDataBrowserPropertyFlagsOffset
kDataBrowserTruncateTextAtEnd = 2 << kDataBrowserPropertyFlagsOffset
kDataBrowserTruncateTextMiddle = 0 << kDataBrowserPropertyFlagsOffset
kDataBrowserTruncateTextAtStart = 1 << kDataBrowserPropertyFlagsOffset
kDataBrowserPropertyModificationFlags = kDataBrowserPropertyFlagsMask
kDataBrowserRelativeDateTime = kDataBrowserDateTimeRelative
kDataBrowserViewSpecificFlagsOffset = 16
kDataBrowserViewSpecificFlagsMask = 0xFF << kDataBrowserViewSpecificFlagsOffset
kDataBrowserViewSpecificPropertyFlags = kDataBrowserViewSpecificFlagsMask
kDataBrowserClientPropertyFlagsOffset = 24
# kDataBrowserClientPropertyFlagsMask = (unsigned long)(0xFF << kDataBrowserClientPropertyFlagsOffset)
kDataBrowserLatestCallbacks = 0
kDataBrowserContentHit = 1
kDataBrowserNothingHit = 0
kDataBrowserStopTracking = -1
kDataBrowserLatestCustomCallbacks = 0
kDataBrowserTableViewMinimalHilite = 0
kDataBrowserTableViewFillHilite = 1
kDataBrowserTableViewSelectionColumn = 1 << kDataBrowserViewSpecificFlagsOffset
kDataBrowserTableViewLastColumn = -1
kDataBrowserListViewMovableColumn = 1 << (kDataBrowserViewSpecificFlagsOffset + 1)
kDataBrowserListViewSortableColumn = 1 << (kDataBrowserViewSpecificFlagsOffset + 2)
kDataBrowserListViewSelectionColumn = kDataBrowserTableViewSelectionColumn
kDataBrowserListViewDefaultColumnFlags = kDataBrowserListViewMovableColumn + kDataBrowserListViewSortableColumn
kDataBrowserListViewLatestHeaderDesc = 0
kDataBrowserListViewAppendColumn = kDataBrowserTableViewLastColumn
kControlEditUnicodeTextPostUpdateProcTag = FOUR_CHAR_CODE('upup')
kControlEditUnicodeTextProc = 912
kControlEditUnicodeTextPasswordProc = 914
kControlKindEditUnicodeText = FOUR_CHAR_CODE('eutx')
kControlCheckboxUncheckedValue = kControlCheckBoxUncheckedValue
kControlCheckboxCheckedValue = kControlCheckBoxCheckedValue
kControlCheckboxMixedValue = kControlCheckBoxMixedValue
inLabel = kControlLabelPart
inMenu = kControlMenuPart
inTriangle = kControlTrianglePart
inButton = kControlButtonPart
inCheckBox = kControlCheckBoxPart
inUpButton = kControlUpButtonPart
inDownButton = kControlDownButtonPart
inPageUp = kControlPageUpPart
inPageDown = kControlPageDownPart
kInLabelControlPart = kControlLabelPart
kInMenuControlPart = kControlMenuPart
kInTriangleControlPart = kControlTrianglePart
kInButtonControlPart = kControlButtonPart
kInCheckBoxControlPart = kControlCheckBoxPart
kInUpButtonControlPart = kControlUpButtonPart
kInDownButtonControlPart = kControlDownButtonPart
kInPageUpControlPart = kControlPageUpPart
kInPageDownControlPart = kControlPageDownPart
| Python |
# Generated from 'Folders.h'
def FOUR_CHAR_CODE(x): return x
true = True
false = False
kOnSystemDisk = -32768L
kOnAppropriateDisk = -32767
kSystemDomain = -32766
kLocalDomain = -32765
kNetworkDomain = -32764
kUserDomain = -32763
kClassicDomain = -32762
kCreateFolder = true
kDontCreateFolder = false
kSystemFolderType = FOUR_CHAR_CODE('macs')
kDesktopFolderType = FOUR_CHAR_CODE('desk')
kSystemDesktopFolderType = FOUR_CHAR_CODE('sdsk')
kTrashFolderType = FOUR_CHAR_CODE('trsh')
kSystemTrashFolderType = FOUR_CHAR_CODE('strs')
kWhereToEmptyTrashFolderType = FOUR_CHAR_CODE('empt')
kPrintMonitorDocsFolderType = FOUR_CHAR_CODE('prnt')
kStartupFolderType = FOUR_CHAR_CODE('strt')
kShutdownFolderType = FOUR_CHAR_CODE('shdf')
kAppleMenuFolderType = FOUR_CHAR_CODE('amnu')
kControlPanelFolderType = FOUR_CHAR_CODE('ctrl')
kSystemControlPanelFolderType = FOUR_CHAR_CODE('sctl')
kExtensionFolderType = FOUR_CHAR_CODE('extn')
kFontsFolderType = FOUR_CHAR_CODE('font')
kPreferencesFolderType = FOUR_CHAR_CODE('pref')
kSystemPreferencesFolderType = FOUR_CHAR_CODE('sprf')
kTemporaryFolderType = FOUR_CHAR_CODE('temp')
kExtensionDisabledFolderType = FOUR_CHAR_CODE('extD')
kControlPanelDisabledFolderType = FOUR_CHAR_CODE('ctrD')
kSystemExtensionDisabledFolderType = FOUR_CHAR_CODE('macD')
kStartupItemsDisabledFolderType = FOUR_CHAR_CODE('strD')
kShutdownItemsDisabledFolderType = FOUR_CHAR_CODE('shdD')
kApplicationsFolderType = FOUR_CHAR_CODE('apps')
kDocumentsFolderType = FOUR_CHAR_CODE('docs')
kVolumeRootFolderType = FOUR_CHAR_CODE('root')
kChewableItemsFolderType = FOUR_CHAR_CODE('flnt')
kApplicationSupportFolderType = FOUR_CHAR_CODE('asup')
kTextEncodingsFolderType = FOUR_CHAR_CODE('\xc4tex')
kStationeryFolderType = FOUR_CHAR_CODE('odst')
kOpenDocFolderType = FOUR_CHAR_CODE('odod')
kOpenDocShellPlugInsFolderType = FOUR_CHAR_CODE('odsp')
kEditorsFolderType = FOUR_CHAR_CODE('oded')
kOpenDocEditorsFolderType = FOUR_CHAR_CODE('\xc4odf')
kOpenDocLibrariesFolderType = FOUR_CHAR_CODE('odlb')
kGenEditorsFolderType = FOUR_CHAR_CODE('\xc4edi')
kHelpFolderType = FOUR_CHAR_CODE('\xc4hlp')
kInternetPlugInFolderType = FOUR_CHAR_CODE('\xc4net')
kModemScriptsFolderType = FOUR_CHAR_CODE('\xc4mod')
kPrinterDescriptionFolderType = FOUR_CHAR_CODE('ppdf')
kPrinterDriverFolderType = FOUR_CHAR_CODE('\xc4prd')
kScriptingAdditionsFolderType = FOUR_CHAR_CODE('\xc4scr')
kSharedLibrariesFolderType = FOUR_CHAR_CODE('\xc4lib')
kVoicesFolderType = FOUR_CHAR_CODE('fvoc')
kControlStripModulesFolderType = FOUR_CHAR_CODE('sdev')
kAssistantsFolderType = FOUR_CHAR_CODE('ast\xc4')
kUtilitiesFolderType = FOUR_CHAR_CODE('uti\xc4')
kAppleExtrasFolderType = FOUR_CHAR_CODE('aex\xc4')
kContextualMenuItemsFolderType = FOUR_CHAR_CODE('cmnu')
kMacOSReadMesFolderType = FOUR_CHAR_CODE('mor\xc4')
kALMModulesFolderType = FOUR_CHAR_CODE('walk')
kALMPreferencesFolderType = FOUR_CHAR_CODE('trip')
kALMLocationsFolderType = FOUR_CHAR_CODE('fall')
kColorSyncProfilesFolderType = FOUR_CHAR_CODE('prof')
kThemesFolderType = FOUR_CHAR_CODE('thme')
kFavoritesFolderType = FOUR_CHAR_CODE('favs')
kInternetFolderType = FOUR_CHAR_CODE('int\xc4')
kAppearanceFolderType = FOUR_CHAR_CODE('appr')
kSoundSetsFolderType = FOUR_CHAR_CODE('snds')
kDesktopPicturesFolderType = FOUR_CHAR_CODE('dtp\xc4')
kInternetSearchSitesFolderType = FOUR_CHAR_CODE('issf')
kFindSupportFolderType = FOUR_CHAR_CODE('fnds')
kFindByContentFolderType = FOUR_CHAR_CODE('fbcf')
kInstallerLogsFolderType = FOUR_CHAR_CODE('ilgf')
kScriptsFolderType = FOUR_CHAR_CODE('scr\xc4')
kFolderActionsFolderType = FOUR_CHAR_CODE('fasf')
kLauncherItemsFolderType = FOUR_CHAR_CODE('laun')
kRecentApplicationsFolderType = FOUR_CHAR_CODE('rapp')
kRecentDocumentsFolderType = FOUR_CHAR_CODE('rdoc')
kRecentServersFolderType = FOUR_CHAR_CODE('rsvr')
kSpeakableItemsFolderType = FOUR_CHAR_CODE('spki')
kKeychainFolderType = FOUR_CHAR_CODE('kchn')
kQuickTimeExtensionsFolderType = FOUR_CHAR_CODE('qtex')
kDisplayExtensionsFolderType = FOUR_CHAR_CODE('dspl')
kMultiprocessingFolderType = FOUR_CHAR_CODE('mpxf')
kPrintingPlugInsFolderType = FOUR_CHAR_CODE('pplg')
kDomainTopLevelFolderType = FOUR_CHAR_CODE('dtop')
kDomainLibraryFolderType = FOUR_CHAR_CODE('dlib')
kColorSyncFolderType = FOUR_CHAR_CODE('sync')
kColorSyncCMMFolderType = FOUR_CHAR_CODE('ccmm')
kColorSyncScriptingFolderType = FOUR_CHAR_CODE('cscr')
kPrintersFolderType = FOUR_CHAR_CODE('impr')
kSpeechFolderType = FOUR_CHAR_CODE('spch')
kCarbonLibraryFolderType = FOUR_CHAR_CODE('carb')
kDocumentationFolderType = FOUR_CHAR_CODE('info')
kDeveloperDocsFolderType = FOUR_CHAR_CODE('ddoc')
kDeveloperHelpFolderType = FOUR_CHAR_CODE('devh')
kISSDownloadsFolderType = FOUR_CHAR_CODE('issd')
kUserSpecificTmpFolderType = FOUR_CHAR_CODE('utmp')
kCachedDataFolderType = FOUR_CHAR_CODE('cach')
kFrameworksFolderType = FOUR_CHAR_CODE('fram')
kPrivateFrameworksFolderType = FOUR_CHAR_CODE('pfrm')
kClassicDesktopFolderType = FOUR_CHAR_CODE('sdsk')
kDeveloperFolderType = FOUR_CHAR_CODE('devf')
kSystemSoundsFolderType = FOUR_CHAR_CODE('ssnd')
kComponentsFolderType = FOUR_CHAR_CODE('cmpd')
kQuickTimeComponentsFolderType = FOUR_CHAR_CODE('wcmp')
kCoreServicesFolderType = FOUR_CHAR_CODE('csrv')
kPictureDocumentsFolderType = FOUR_CHAR_CODE('pdoc')
kMovieDocumentsFolderType = FOUR_CHAR_CODE('mdoc')
kMusicDocumentsFolderType = FOUR_CHAR_CODE('\xb5doc')
kInternetSitesFolderType = FOUR_CHAR_CODE('site')
kPublicFolderType = FOUR_CHAR_CODE('pubb')
kAudioSupportFolderType = FOUR_CHAR_CODE('adio')
kAudioSoundsFolderType = FOUR_CHAR_CODE('asnd')
kAudioSoundBanksFolderType = FOUR_CHAR_CODE('bank')
kAudioAlertSoundsFolderType = FOUR_CHAR_CODE('alrt')
kAudioPlugInsFolderType = FOUR_CHAR_CODE('aplg')
kAudioComponentsFolderType = FOUR_CHAR_CODE('acmp')
kKernelExtensionsFolderType = FOUR_CHAR_CODE('kext')
kDirectoryServicesFolderType = FOUR_CHAR_CODE('dsrv')
kDirectoryServicesPlugInsFolderType = FOUR_CHAR_CODE('dplg')
kInstallerReceiptsFolderType = FOUR_CHAR_CODE('rcpt')
kFileSystemSupportFolderType = FOUR_CHAR_CODE('fsys')
kAppleShareSupportFolderType = FOUR_CHAR_CODE('shar')
kAppleShareAuthenticationFolderType = FOUR_CHAR_CODE('auth')
kMIDIDriversFolderType = FOUR_CHAR_CODE('midi')
kLocalesFolderType = FOUR_CHAR_CODE('\xc4loc')
kFindByContentPluginsFolderType = FOUR_CHAR_CODE('fbcp')
kUsersFolderType = FOUR_CHAR_CODE('usrs')
kCurrentUserFolderType = FOUR_CHAR_CODE('cusr')
kCurrentUserRemoteFolderLocation = FOUR_CHAR_CODE('rusf')
kCurrentUserRemoteFolderType = FOUR_CHAR_CODE('rusr')
kSharedUserDataFolderType = FOUR_CHAR_CODE('sdat')
kVolumeSettingsFolderType = FOUR_CHAR_CODE('vsfd')
kAppleshareAutomountServerAliasesFolderType = FOUR_CHAR_CODE('srv\xc4')
kPreMacOS91ApplicationsFolderType = FOUR_CHAR_CODE('\x8cpps')
kPreMacOS91InstallerLogsFolderType = FOUR_CHAR_CODE('\x94lgf')
kPreMacOS91AssistantsFolderType = FOUR_CHAR_CODE('\x8cst\xc4')
kPreMacOS91UtilitiesFolderType = FOUR_CHAR_CODE('\x9fti\xc4')
kPreMacOS91AppleExtrasFolderType = FOUR_CHAR_CODE('\x8cex\xc4')
kPreMacOS91MacOSReadMesFolderType = FOUR_CHAR_CODE('\xb5or\xc4')
kPreMacOS91InternetFolderType = FOUR_CHAR_CODE('\x94nt\xc4')
kPreMacOS91AutomountedServersFolderType = FOUR_CHAR_CODE('\xa7rv\xc4')
kPreMacOS91StationeryFolderType = FOUR_CHAR_CODE('\xbfdst')
kCreateFolderAtBoot = 0x00000002
kCreateFolderAtBootBit = 1
kFolderCreatedInvisible = 0x00000004
kFolderCreatedInvisibleBit = 2
kFolderCreatedNameLocked = 0x00000008
kFolderCreatedNameLockedBit = 3
kFolderCreatedAdminPrivs = 0x00000010
kFolderCreatedAdminPrivsBit = 4
kFolderInUserFolder = 0x00000020
kFolderInUserFolderBit = 5
kFolderTrackedByAlias = 0x00000040
kFolderTrackedByAliasBit = 6
kFolderInRemoteUserFolderIfAvailable = 0x00000080
kFolderInRemoteUserFolderIfAvailableBit = 7
kFolderNeverMatchedInIdentifyFolder = 0x00000100
kFolderNeverMatchedInIdentifyFolderBit = 8
kFolderMustStayOnSameVolume = 0x00000200
kFolderMustStayOnSameVolumeBit = 9
kFolderManagerFolderInMacOS9FolderIfMacOSXIsInstalledMask = 0x00000400
kFolderManagerFolderInMacOS9FolderIfMacOSXIsInstalledBit = 10
kFolderInLocalOrRemoteUserFolder = kFolderInUserFolder | kFolderInRemoteUserFolderIfAvailable
kRelativeFolder = FOUR_CHAR_CODE('relf')
kSpecialFolder = FOUR_CHAR_CODE('spcf')
kBlessedFolder = FOUR_CHAR_CODE('blsf')
kRootFolder = FOUR_CHAR_CODE('rotf')
kCurrentUserFolderLocation = FOUR_CHAR_CODE('cusf')
kFindFolderRedirectionFlagUseDistinctUserFoldersBit = 0
kFindFolderRedirectionFlagUseGivenVRefAndDirIDAsUserFolderBit = 1
kFindFolderRedirectionFlagsUseGivenVRefNumAndDirIDAsRemoteUserFolderBit = 2
kFolderManagerUserRedirectionGlobalsCurrentVersion = 1
kFindFolderExtendedFlagsDoNotFollowAliasesBit = 0
kFindFolderExtendedFlagsDoNotUseUserFolderBit = 1
kFindFolderExtendedFlagsUseOtherUserRecord = 0x01000000
kFolderManagerNotificationMessageUserLogIn = FOUR_CHAR_CODE('log+')
kFolderManagerNotificationMessagePreUserLogIn = FOUR_CHAR_CODE('logj')
kFolderManagerNotificationMessageUserLogOut = FOUR_CHAR_CODE('log-')
kFolderManagerNotificationMessagePostUserLogOut = FOUR_CHAR_CODE('logp')
kFolderManagerNotificationDiscardCachedData = FOUR_CHAR_CODE('dche')
kFolderManagerNotificationMessageLoginStartup = FOUR_CHAR_CODE('stup')
kDoNotRemoveWhenCurrentApplicationQuitsBit = 0
kDoNotRemoveWheCurrentApplicationQuitsBit = kDoNotRemoveWhenCurrentApplicationQuitsBit
kStopIfAnyNotificationProcReturnsErrorBit = 31
| Python |
from _Dlg import *
| Python |
from _Win import *
| Python |
from _Cm import *
| Python |
# Generated from 'CarbonEvents.h'
def FOUR_CHAR_CODE(x): return x
def FOUR_CHAR_CODE(x): return x
false = 0
true = 1
keyAEEventClass = FOUR_CHAR_CODE('evcl')
keyAEEventID = FOUR_CHAR_CODE('evti')
eventAlreadyPostedErr = -9860
eventTargetBusyErr = -9861
eventClassInvalidErr = -9862
eventClassIncorrectErr = -9864
eventHandlerAlreadyInstalledErr = -9866
eventInternalErr = -9868
eventKindIncorrectErr = -9869
eventParameterNotFoundErr = -9870
eventNotHandledErr = -9874
eventLoopTimedOutErr = -9875
eventLoopQuitErr = -9876
eventNotInQueueErr = -9877
eventHotKeyExistsErr = -9878
eventHotKeyInvalidErr = -9879
kEventPriorityLow = 0
kEventPriorityStandard = 1
kEventPriorityHigh = 2
kEventLeaveInQueue = false
kEventRemoveFromQueue = true
kTrackMouseLocationOptionDontConsumeMouseUp = (1 << 0)
kMouseTrackingMouseDown = 1
kMouseTrackingMouseUp = 2
kMouseTrackingMouseExited = 3
kMouseTrackingMouseEntered = 4
kMouseTrackingMouseDragged = 5
kMouseTrackingKeyModifiersChanged = 6
kMouseTrackingUserCancelled = 7
kMouseTrackingTimedOut = 8
kMouseTrackingMouseMoved = 9
kEventAttributeNone = 0
kEventAttributeUserEvent = (1 << 0)
kEventClassMouse = FOUR_CHAR_CODE('mous')
kEventClassKeyboard = FOUR_CHAR_CODE('keyb')
kEventClassTextInput = FOUR_CHAR_CODE('text')
kEventClassApplication = FOUR_CHAR_CODE('appl')
kEventClassAppleEvent = FOUR_CHAR_CODE('eppc')
kEventClassMenu = FOUR_CHAR_CODE('menu')
kEventClassWindow = FOUR_CHAR_CODE('wind')
kEventClassControl = FOUR_CHAR_CODE('cntl')
kEventClassCommand = FOUR_CHAR_CODE('cmds')
kEventClassTablet = FOUR_CHAR_CODE('tblt')
kEventClassVolume = FOUR_CHAR_CODE('vol ')
kEventClassAppearance = FOUR_CHAR_CODE('appm')
kEventClassService = FOUR_CHAR_CODE('serv')
kEventMouseDown = 1
kEventMouseUp = 2
kEventMouseMoved = 5
kEventMouseDragged = 6
kEventMouseWheelMoved = 10
kEventMouseButtonPrimary = 1
kEventMouseButtonSecondary = 2
kEventMouseButtonTertiary = 3
kEventMouseWheelAxisX = 0
kEventMouseWheelAxisY = 1
kEventTextInputUpdateActiveInputArea = 1
kEventTextInputUnicodeForKeyEvent = 2
kEventTextInputOffsetToPos = 3
kEventTextInputPosToOffset = 4
kEventTextInputShowHideBottomWindow = 5
kEventTextInputGetSelectedText = 6
kEventRawKeyDown = 1
kEventRawKeyRepeat = 2
kEventRawKeyUp = 3
kEventRawKeyModifiersChanged = 4
kEventHotKeyPressed = 5
kEventHotKeyReleased = 6
kEventKeyModifierNumLockBit = 16
kEventKeyModifierFnBit = 17
kEventKeyModifierNumLockMask = 1L << kEventKeyModifierNumLockBit
kEventKeyModifierFnMask = 1L << kEventKeyModifierFnBit
kEventAppActivated = 1
kEventAppDeactivated = 2
kEventAppQuit = 3
kEventAppLaunchNotification = 4
kEventAppLaunched = 5
kEventAppTerminated = 6
kEventAppFrontSwitched = 7
kEventAppGetDockTileMenu = 20
kEventAppleEvent = 1
kEventWindowUpdate = 1
kEventWindowDrawContent = 2
kEventWindowActivated = 5
kEventWindowDeactivated = 6
kEventWindowGetClickActivation = 7
kEventWindowShowing = 22
kEventWindowHiding = 23
kEventWindowShown = 24
kEventWindowHidden = 25
kEventWindowCollapsing = 86
kEventWindowCollapsed = 67
kEventWindowExpanding = 87
kEventWindowExpanded = 70
kEventWindowZoomed = 76
kEventWindowBoundsChanging = 26
kEventWindowBoundsChanged = 27
kEventWindowResizeStarted = 28
kEventWindowResizeCompleted = 29
kEventWindowDragStarted = 30
kEventWindowDragCompleted = 31
kEventWindowClosed = 73
kWindowBoundsChangeUserDrag = (1 << 0)
kWindowBoundsChangeUserResize = (1 << 1)
kWindowBoundsChangeSizeChanged = (1 << 2)
kWindowBoundsChangeOriginChanged = (1 << 3)
kWindowBoundsChangeZoom = (1 << 4)
kEventWindowClickDragRgn = 32
kEventWindowClickResizeRgn = 33
kEventWindowClickCollapseRgn = 34
kEventWindowClickCloseRgn = 35
kEventWindowClickZoomRgn = 36
kEventWindowClickContentRgn = 37
kEventWindowClickProxyIconRgn = 38
kEventWindowClickToolbarButtonRgn = 41
kEventWindowClickStructureRgn = 42
kEventWindowCursorChange = 40
kEventWindowCollapse = 66
kEventWindowCollapseAll = 68
kEventWindowExpand = 69
kEventWindowExpandAll = 71
kEventWindowClose = 72
kEventWindowCloseAll = 74
kEventWindowZoom = 75
kEventWindowZoomAll = 77
kEventWindowContextualMenuSelect = 78
kEventWindowPathSelect = 79
kEventWindowGetIdealSize = 80
kEventWindowGetMinimumSize = 81
kEventWindowGetMaximumSize = 82
kEventWindowConstrain = 83
kEventWindowHandleContentClick = 85
kEventWindowProxyBeginDrag = 128
kEventWindowProxyEndDrag = 129
kEventWindowToolbarSwitchMode = 150
kDockChangedUser = 1
kDockChangedOrientation = 2
kDockChangedAutohide = 3
kDockChangedDisplay = 4
kDockChangedItems = 5
kDockChangedUnknown = 6
kEventWindowFocusAcquired = 200
kEventWindowFocusRelinquish = 201
kEventWindowDrawFrame = 1000
kEventWindowDrawPart = 1001
kEventWindowGetRegion = 1002
kEventWindowHitTest = 1003
kEventWindowInit = 1004
kEventWindowDispose = 1005
kEventWindowDragHilite = 1006
kEventWindowModified = 1007
kEventWindowSetupProxyDragImage = 1008
kEventWindowStateChanged = 1009
kEventWindowMeasureTitle = 1010
kEventWindowDrawGrowBox = 1011
kEventWindowGetGrowImageRegion = 1012
kEventWindowPaint = 1013
kEventMenuBeginTracking = 1
kEventMenuEndTracking = 2
kEventMenuChangeTrackingMode = 3
kEventMenuOpening = 4
kEventMenuClosed = 5
kEventMenuTargetItem = 6
kEventMenuMatchKey = 7
kEventMenuEnableItems = 8
kEventMenuPopulate = 9
kEventMenuMeasureItemWidth = 100
kEventMenuMeasureItemHeight = 101
kEventMenuDrawItem = 102
kEventMenuDrawItemContent = 103
kEventMenuDispose = 1001
kMenuContextMenuBar = 1 << 0
kMenuContextPullDown = 1 << 8
kMenuContextPopUp = 1 << 9
kMenuContextSubmenu = 1 << 10
kMenuContextMenuBarTracking = 1 << 16
kMenuContextPopUpTracking = 1 << 17
kMenuContextKeyMatching = 1 << 18
kMenuContextMenuEnabling = 1 << 19
kMenuContextCommandIDSearch = 1 << 20
kEventProcessCommand = 1
kEventCommandProcess = 1
kEventCommandUpdateStatus = 2
kHICommandOK = FOUR_CHAR_CODE('ok ')
kHICommandCancel = FOUR_CHAR_CODE('not!')
kHICommandQuit = FOUR_CHAR_CODE('quit')
kHICommandUndo = FOUR_CHAR_CODE('undo')
kHICommandRedo = FOUR_CHAR_CODE('redo')
kHICommandCut = FOUR_CHAR_CODE('cut ')
kHICommandCopy = FOUR_CHAR_CODE('copy')
kHICommandPaste = FOUR_CHAR_CODE('past')
kHICommandClear = FOUR_CHAR_CODE('clea')
kHICommandSelectAll = FOUR_CHAR_CODE('sall')
kHICommandHide = FOUR_CHAR_CODE('hide')
kHICommandHideOthers = FOUR_CHAR_CODE('hido')
kHICommandShowAll = FOUR_CHAR_CODE('shal')
kHICommandPreferences = FOUR_CHAR_CODE('pref')
kHICommandZoomWindow = FOUR_CHAR_CODE('zoom')
kHICommandMinimizeWindow = FOUR_CHAR_CODE('mini')
kHICommandMinimizeAll = FOUR_CHAR_CODE('mina')
kHICommandMaximizeWindow = FOUR_CHAR_CODE('maxi')
kHICommandMaximizeAll = FOUR_CHAR_CODE('maxa')
kHICommandArrangeInFront = FOUR_CHAR_CODE('frnt')
kHICommandBringAllToFront = FOUR_CHAR_CODE('bfrt')
kHICommandWindowListSeparator = FOUR_CHAR_CODE('wldv')
kHICommandWindowListTerminator = FOUR_CHAR_CODE('wlst')
kHICommandSelectWindow = FOUR_CHAR_CODE('swin')
kHICommandAbout = FOUR_CHAR_CODE('abou')
kHICommandNew = FOUR_CHAR_CODE('new ')
kHICommandOpen = FOUR_CHAR_CODE('open')
kHICommandClose = FOUR_CHAR_CODE('clos')
kHICommandSave = FOUR_CHAR_CODE('save')
kHICommandSaveAs = FOUR_CHAR_CODE('svas')
kHICommandRevert = FOUR_CHAR_CODE('rvrt')
kHICommandPrint = FOUR_CHAR_CODE('prnt')
kHICommandPageSetup = FOUR_CHAR_CODE('page')
kHICommandAppHelp = FOUR_CHAR_CODE('ahlp')
kHICommandFromMenu = (1L << 0)
kHICommandFromControl = (1L << 1)
kHICommandFromWindow = (1L << 2)
kEventControlInitialize = 1000
kEventControlDispose = 1001
kEventControlGetOptimalBounds = 1003
kEventControlDefInitialize = kEventControlInitialize
kEventControlDefDispose = kEventControlDispose
kEventControlHit = 1
kEventControlSimulateHit = 2
kEventControlHitTest = 3
kEventControlDraw = 4
kEventControlApplyBackground = 5
kEventControlApplyTextColor = 6
kEventControlSetFocusPart = 7
kEventControlGetFocusPart = 8
kEventControlActivate = 9
kEventControlDeactivate = 10
kEventControlSetCursor = 11
kEventControlContextualMenuClick = 12
kEventControlClick = 13
kEventControlTrack = 51
kEventControlGetScrollToHereStartPoint = 52
kEventControlGetIndicatorDragConstraint = 53
kEventControlIndicatorMoved = 54
kEventControlGhostingFinished = 55
kEventControlGetActionProcPart = 56
kEventControlGetPartRegion = 101
kEventControlGetPartBounds = 102
kEventControlSetData = 103
kEventControlGetData = 104
kEventControlValueFieldChanged = 151
kEventControlAddedSubControl = 152
kEventControlRemovingSubControl = 153
kEventControlBoundsChanged = 154
kEventControlOwningWindowChanged = 159
kEventControlArbitraryMessage = 201
kControlBoundsChangeSizeChanged = (1 << 2)
kControlBoundsChangePositionChanged = (1 << 3)
kEventTabletPoint = 1
kEventTabletProximity = 2
kEventTabletPointer = 1
kEventVolumeMounted = 1
kEventVolumeUnmounted = 2
typeFSVolumeRefNum = FOUR_CHAR_CODE('voln')
kEventAppearanceScrollBarVariantChanged = 1
kEventServiceCopy = 1
kEventServicePaste = 2
kEventServiceGetTypes = 3
kEventServicePerform = 4
kEventParamDirectObject = FOUR_CHAR_CODE('----')
kEventParamPostTarget = FOUR_CHAR_CODE('ptrg')
typeEventTargetRef = FOUR_CHAR_CODE('etrg')
kEventParamWindowRef = FOUR_CHAR_CODE('wind')
kEventParamGrafPort = FOUR_CHAR_CODE('graf')
kEventParamDragRef = FOUR_CHAR_CODE('drag')
kEventParamMenuRef = FOUR_CHAR_CODE('menu')
kEventParamEventRef = FOUR_CHAR_CODE('evnt')
kEventParamControlRef = FOUR_CHAR_CODE('ctrl')
kEventParamRgnHandle = FOUR_CHAR_CODE('rgnh')
kEventParamEnabled = FOUR_CHAR_CODE('enab')
kEventParamDimensions = FOUR_CHAR_CODE('dims')
kEventParamAvailableBounds = FOUR_CHAR_CODE('avlb')
kEventParamAEEventID = keyAEEventID
kEventParamAEEventClass = keyAEEventClass
kEventParamCGContextRef = FOUR_CHAR_CODE('cntx')
kEventParamDeviceDepth = FOUR_CHAR_CODE('devd')
kEventParamDeviceColor = FOUR_CHAR_CODE('devc')
typeWindowRef = FOUR_CHAR_CODE('wind')
typeGrafPtr = FOUR_CHAR_CODE('graf')
typeGWorldPtr = FOUR_CHAR_CODE('gwld')
typeDragRef = FOUR_CHAR_CODE('drag')
typeMenuRef = FOUR_CHAR_CODE('menu')
typeControlRef = FOUR_CHAR_CODE('ctrl')
typeCollection = FOUR_CHAR_CODE('cltn')
typeQDRgnHandle = FOUR_CHAR_CODE('rgnh')
typeOSStatus = FOUR_CHAR_CODE('osst')
typeCFStringRef = FOUR_CHAR_CODE('cfst')
typeCFIndex = FOUR_CHAR_CODE('cfix')
typeCFTypeRef = FOUR_CHAR_CODE('cfty')
typeCGContextRef = FOUR_CHAR_CODE('cntx')
typeHIPoint = FOUR_CHAR_CODE('hipt')
typeHISize = FOUR_CHAR_CODE('hisz')
typeHIRect = FOUR_CHAR_CODE('hirc')
kEventParamMouseLocation = FOUR_CHAR_CODE('mloc')
kEventParamMouseButton = FOUR_CHAR_CODE('mbtn')
kEventParamClickCount = FOUR_CHAR_CODE('ccnt')
kEventParamMouseWheelAxis = FOUR_CHAR_CODE('mwax')
kEventParamMouseWheelDelta = FOUR_CHAR_CODE('mwdl')
kEventParamMouseDelta = FOUR_CHAR_CODE('mdta')
kEventParamMouseChord = FOUR_CHAR_CODE('chor')
kEventParamTabletEventType = FOUR_CHAR_CODE('tblt')
typeMouseButton = FOUR_CHAR_CODE('mbtn')
typeMouseWheelAxis = FOUR_CHAR_CODE('mwax')
kEventParamKeyCode = FOUR_CHAR_CODE('kcod')
kEventParamKeyMacCharCodes = FOUR_CHAR_CODE('kchr')
kEventParamKeyModifiers = FOUR_CHAR_CODE('kmod')
kEventParamKeyUnicodes = FOUR_CHAR_CODE('kuni')
kEventParamKeyboardType = FOUR_CHAR_CODE('kbdt')
typeEventHotKeyID = FOUR_CHAR_CODE('hkid')
kEventParamTextInputSendRefCon = FOUR_CHAR_CODE('tsrc')
kEventParamTextInputSendComponentInstance = FOUR_CHAR_CODE('tsci')
kEventParamTextInputSendSLRec = FOUR_CHAR_CODE('tssl')
kEventParamTextInputReplySLRec = FOUR_CHAR_CODE('trsl')
kEventParamTextInputSendText = FOUR_CHAR_CODE('tstx')
kEventParamTextInputReplyText = FOUR_CHAR_CODE('trtx')
kEventParamTextInputSendUpdateRng = FOUR_CHAR_CODE('tsup')
kEventParamTextInputSendHiliteRng = FOUR_CHAR_CODE('tshi')
kEventParamTextInputSendClauseRng = FOUR_CHAR_CODE('tscl')
kEventParamTextInputSendPinRng = FOUR_CHAR_CODE('tspn')
kEventParamTextInputSendFixLen = FOUR_CHAR_CODE('tsfx')
kEventParamTextInputSendLeadingEdge = FOUR_CHAR_CODE('tsle')
kEventParamTextInputReplyLeadingEdge = FOUR_CHAR_CODE('trle')
kEventParamTextInputSendTextOffset = FOUR_CHAR_CODE('tsto')
kEventParamTextInputReplyTextOffset = FOUR_CHAR_CODE('trto')
kEventParamTextInputReplyRegionClass = FOUR_CHAR_CODE('trrg')
kEventParamTextInputSendCurrentPoint = FOUR_CHAR_CODE('tscp')
kEventParamTextInputSendDraggingMode = FOUR_CHAR_CODE('tsdm')
kEventParamTextInputReplyPoint = FOUR_CHAR_CODE('trpt')
kEventParamTextInputReplyFont = FOUR_CHAR_CODE('trft')
kEventParamTextInputReplyFMFont = FOUR_CHAR_CODE('trfm')
kEventParamTextInputReplyPointSize = FOUR_CHAR_CODE('trpz')
kEventParamTextInputReplyLineHeight = FOUR_CHAR_CODE('trlh')
kEventParamTextInputReplyLineAscent = FOUR_CHAR_CODE('trla')
kEventParamTextInputReplyTextAngle = FOUR_CHAR_CODE('trta')
kEventParamTextInputSendShowHide = FOUR_CHAR_CODE('tssh')
kEventParamTextInputReplyShowHide = FOUR_CHAR_CODE('trsh')
kEventParamTextInputSendKeyboardEvent = FOUR_CHAR_CODE('tske')
kEventParamTextInputSendTextServiceEncoding = FOUR_CHAR_CODE('tsse')
kEventParamTextInputSendTextServiceMacEncoding = FOUR_CHAR_CODE('tssm')
kEventParamHICommand = FOUR_CHAR_CODE('hcmd')
typeHICommand = FOUR_CHAR_CODE('hcmd')
kEventParamWindowFeatures = FOUR_CHAR_CODE('wftr')
kEventParamWindowDefPart = FOUR_CHAR_CODE('wdpc')
kEventParamCurrentBounds = FOUR_CHAR_CODE('crct')
kEventParamOriginalBounds = FOUR_CHAR_CODE('orct')
kEventParamPreviousBounds = FOUR_CHAR_CODE('prct')
kEventParamClickActivation = FOUR_CHAR_CODE('clac')
kEventParamWindowRegionCode = FOUR_CHAR_CODE('wshp')
kEventParamWindowDragHiliteFlag = FOUR_CHAR_CODE('wdhf')
kEventParamWindowModifiedFlag = FOUR_CHAR_CODE('wmff')
kEventParamWindowProxyGWorldPtr = FOUR_CHAR_CODE('wpgw')
kEventParamWindowProxyImageRgn = FOUR_CHAR_CODE('wpir')
kEventParamWindowProxyOutlineRgn = FOUR_CHAR_CODE('wpor')
kEventParamWindowStateChangedFlags = FOUR_CHAR_CODE('wscf')
kEventParamWindowTitleFullWidth = FOUR_CHAR_CODE('wtfw')
kEventParamWindowTitleTextWidth = FOUR_CHAR_CODE('wttw')
kEventParamWindowGrowRect = FOUR_CHAR_CODE('grct')
kEventParamAttributes = FOUR_CHAR_CODE('attr')
kEventParamDockChangedReason = FOUR_CHAR_CODE('dcrs')
kEventParamPreviousDockRect = FOUR_CHAR_CODE('pdrc')
kEventParamCurrentDockRect = FOUR_CHAR_CODE('cdrc')
typeWindowRegionCode = FOUR_CHAR_CODE('wshp')
typeWindowDefPartCode = FOUR_CHAR_CODE('wdpt')
typeClickActivationResult = FOUR_CHAR_CODE('clac')
kEventParamControlPart = FOUR_CHAR_CODE('cprt')
kEventParamInitCollection = FOUR_CHAR_CODE('icol')
kEventParamControlMessage = FOUR_CHAR_CODE('cmsg')
kEventParamControlParam = FOUR_CHAR_CODE('cprm')
kEventParamControlResult = FOUR_CHAR_CODE('crsl')
kEventParamControlRegion = FOUR_CHAR_CODE('crgn')
kEventParamControlAction = FOUR_CHAR_CODE('caup')
kEventParamControlIndicatorDragConstraint = FOUR_CHAR_CODE('cidc')
kEventParamControlIndicatorRegion = FOUR_CHAR_CODE('cirn')
kEventParamControlIsGhosting = FOUR_CHAR_CODE('cgst')
kEventParamControlIndicatorOffset = FOUR_CHAR_CODE('ciof')
kEventParamControlClickActivationResult = FOUR_CHAR_CODE('ccar')
kEventParamControlSubControl = FOUR_CHAR_CODE('csub')
kEventParamControlOptimalBounds = FOUR_CHAR_CODE('cobn')
kEventParamControlOptimalBaselineOffset = FOUR_CHAR_CODE('cobo')
kEventParamControlDataTag = FOUR_CHAR_CODE('cdtg')
kEventParamControlDataBuffer = FOUR_CHAR_CODE('cdbf')
kEventParamControlDataBufferSize = FOUR_CHAR_CODE('cdbs')
kEventParamControlDrawDepth = FOUR_CHAR_CODE('cddp')
kEventParamControlDrawInColor = FOUR_CHAR_CODE('cdic')
kEventParamControlFeatures = FOUR_CHAR_CODE('cftr')
kEventParamControlPartBounds = FOUR_CHAR_CODE('cpbd')
kEventParamControlOriginalOwningWindow = FOUR_CHAR_CODE('coow')
kEventParamControlCurrentOwningWindow = FOUR_CHAR_CODE('ccow')
typeControlActionUPP = FOUR_CHAR_CODE('caup')
typeIndicatorDragConstraint = FOUR_CHAR_CODE('cidc')
typeControlPartCode = FOUR_CHAR_CODE('cprt')
kEventParamCurrentMenuTrackingMode = FOUR_CHAR_CODE('cmtm')
kEventParamNewMenuTrackingMode = FOUR_CHAR_CODE('nmtm')
kEventParamMenuFirstOpen = FOUR_CHAR_CODE('1sto')
kEventParamMenuItemIndex = FOUR_CHAR_CODE('item')
kEventParamMenuCommand = FOUR_CHAR_CODE('mcmd')
kEventParamEnableMenuForKeyEvent = FOUR_CHAR_CODE('fork')
kEventParamMenuEventOptions = FOUR_CHAR_CODE('meop')
kEventParamMenuContext = FOUR_CHAR_CODE('mctx')
kEventParamMenuItemBounds = FOUR_CHAR_CODE('mitb')
kEventParamMenuMarkBounds = FOUR_CHAR_CODE('mmkb')
kEventParamMenuIconBounds = FOUR_CHAR_CODE('micb')
kEventParamMenuTextBounds = FOUR_CHAR_CODE('mtxb')
kEventParamMenuTextBaseline = FOUR_CHAR_CODE('mtbl')
kEventParamMenuCommandKeyBounds = FOUR_CHAR_CODE('mcmb')
kEventParamMenuVirtualTop = FOUR_CHAR_CODE('mvrt')
kEventParamMenuVirtualBottom = FOUR_CHAR_CODE('mvrb')
kEventParamMenuDrawState = FOUR_CHAR_CODE('mdrs')
kEventParamMenuItemType = FOUR_CHAR_CODE('mitp')
kEventParamMenuItemWidth = FOUR_CHAR_CODE('mitw')
kEventParamMenuItemHeight = FOUR_CHAR_CODE('mith')
typeMenuItemIndex = FOUR_CHAR_CODE('midx')
typeMenuCommand = FOUR_CHAR_CODE('mcmd')
typeMenuTrackingMode = FOUR_CHAR_CODE('mtmd')
typeMenuEventOptions = FOUR_CHAR_CODE('meop')
typeThemeMenuState = FOUR_CHAR_CODE('tmns')
typeThemeMenuItemType = FOUR_CHAR_CODE('tmit')
kEventParamProcessID = FOUR_CHAR_CODE('psn ')
kEventParamLaunchRefCon = FOUR_CHAR_CODE('lref')
kEventParamLaunchErr = FOUR_CHAR_CODE('err ')
kEventParamTabletPointRec = FOUR_CHAR_CODE('tbrc')
kEventParamTabletProximityRec = FOUR_CHAR_CODE('tbpx')
typeTabletPointRec = FOUR_CHAR_CODE('tbrc')
typeTabletProximityRec = FOUR_CHAR_CODE('tbpx')
kEventParamTabletPointerRec = FOUR_CHAR_CODE('tbrc')
typeTabletPointerRec = FOUR_CHAR_CODE('tbrc')
kEventParamNewScrollBarVariant = FOUR_CHAR_CODE('nsbv')
kEventParamScrapRef = FOUR_CHAR_CODE('scrp')
kEventParamServiceCopyTypes = FOUR_CHAR_CODE('svsd')
kEventParamServicePasteTypes = FOUR_CHAR_CODE('svpt')
kEventParamServiceMessageName = FOUR_CHAR_CODE('svmg')
kEventParamServiceUserData = FOUR_CHAR_CODE('svud')
typeScrapRef = FOUR_CHAR_CODE('scrp')
typeCFMutableArrayRef = FOUR_CHAR_CODE('cfma')
# sHandler = NewEventHandlerUPP( x )
kMouseTrackingMousePressed = kMouseTrackingMouseDown
kMouseTrackingMouseReleased = kMouseTrackingMouseUp
| Python |
# Parsers/generators for QuickTime media descriptions
import struct
Error = 'MediaDescr.Error'
class _MediaDescriptionCodec:
def __init__(self, trunc, size, names, fmt):
self.trunc = trunc
self.size = size
self.names = names
self.fmt = fmt
def decode(self, data):
if self.trunc:
data = data[:self.size]
values = struct.unpack(self.fmt, data)
if len(values) != len(self.names):
raise Error, ('Format length does not match number of names', descr)
rv = {}
for i in range(len(values)):
name = self.names[i]
value = values[i]
if type(name) == type(()):
name, cod, dec = name
value = dec(value)
rv[name] = value
return rv
def encode(dict):
list = [self.fmt]
for name in self.names:
if type(name) == type(()):
name, cod, dec = name
else:
cod = dec = None
value = dict[name]
if cod:
value = cod(value)
list.append(value)
rv = struct.pack(*list)
return rv
# Helper functions
def _tofixed(float):
hi = int(float)
lo = int(float*0x10000) & 0xffff
return (hi<<16)|lo
def _fromfixed(fixed):
hi = (fixed >> 16) & 0xffff
lo = (fixed & 0xffff)
return hi + (lo / float(0x10000))
def _tostr31(str):
return chr(len(str)) + str + '\0'*(31-len(str))
def _fromstr31(str31):
return str31[1:1+ord(str31[0])]
SampleDescription = _MediaDescriptionCodec(
1, # May be longer, truncate
16, # size
('descSize', 'dataFormat', 'resvd1', 'resvd2', 'dataRefIndex'), # Attributes
"l4slhh" # Format
)
SoundDescription = _MediaDescriptionCodec(
1,
36,
('descSize', 'dataFormat', 'resvd1', 'resvd2', 'dataRefIndex',
'version', 'revlevel', 'vendor', 'numChannels', 'sampleSize',
'compressionID', 'packetSize', ('sampleRate', _tofixed, _fromfixed)),
"l4slhhhh4shhhhl" # Format
)
SoundDescriptionV1 = _MediaDescriptionCodec(
1,
52,
('descSize', 'dataFormat', 'resvd1', 'resvd2', 'dataRefIndex',
'version', 'revlevel', 'vendor', 'numChannels', 'sampleSize',
'compressionID', 'packetSize', ('sampleRate', _tofixed, _fromfixed), 'samplesPerPacket',
'bytesPerPacket', 'bytesPerFrame', 'bytesPerSample'),
"l4slhhhh4shhhhlllll" # Format
)
ImageDescription = _MediaDescriptionCodec(
1, # May be longer, truncate
86, # size
('idSize', 'cType', 'resvd1', 'resvd2', 'dataRefIndex', 'version',
'revisionLevel', 'vendor', 'temporalQuality', 'spatialQuality',
'width', 'height', ('hRes', _tofixed, _fromfixed), ('vRes', _tofixed, _fromfixed),
'dataSize', 'frameCount', ('name', _tostr31, _fromstr31),
'depth', 'clutID'),
'l4slhhhh4sllhhlllh32shh',
)
# XXXX Others, like TextDescription and such, remain to be done.
| Python |
# Generated from 'CGContext.h'
def FOUR_CHAR_CODE(x): return x
kCGLineJoinMiter = 0
kCGLineJoinRound = 1
kCGLineJoinBevel = 2
kCGLineCapButt = 0
kCGLineCapRound = 1
kCGLineCapSquare = 2
kCGPathFill = 0
kCGPathEOFill = 1
kCGPathStroke = 2
kCGPathFillStroke = 3
kCGPathEOFillStroke = 4
kCGTextFill = 0
kCGTextStroke = 1
kCGTextFillStroke = 2
kCGTextInvisible = 3
kCGTextFillClip = 4
kCGTextStrokeClip = 5
kCGTextFillStrokeClip = 6
kCGTextClip = 7
kCGEncodingFontSpecific = 0
kCGEncodingMacRoman = 1
kCGInterpolationDefault = 0
kCGInterpolationNone = 1
kCGInterpolationLow = 2
kCGInterpolationHigh = 3
| Python |
from _App import *
| Python |
# Generated from 'Aliases.h'
def FOUR_CHAR_CODE(x): return x
true = True
false = False
rAliasType = FOUR_CHAR_CODE('alis')
kARMMountVol = 0x00000001
kARMNoUI = 0x00000002
kARMMultVols = 0x00000008
kARMSearch = 0x00000100
kARMSearchMore = 0x00000200
kARMSearchRelFirst = 0x00000400
asiZoneName = -3
asiServerName = -2
asiVolumeName = -1
asiAliasName = 0
asiParentName = 1
kResolveAliasFileNoUI = 0x00000001
| Python |
from _Qd import *
| Python |
from _Fm import *
| Python |
from _Snd import *
| Python |
from _CF import *
| Python |
# Generated from 'WASTE.h'
kPascalStackBased = None # workaround for header parsing
def FOUR_CHAR_CODE(x): return x
weCantUndoErr = -10015
weEmptySelectionErr = -10013
weUnknownObjectTypeErr = -9478
weObjectNotFoundErr = -9477
weReadOnlyErr = -9476
weTextNotFoundErr = -9474
weInvalidTextEncodingErr = -9473
weDuplicateAttributeErr = -9472
weInvalidAttributeSizeErr = -9471
weReadOnlyAttributeErr = -9470
weOddByteCountErr = -9469
weHandlerNotFoundErr = -1717
weNotHandledErr = -1708
weNewerVersionErr = -1706
weCorruptDataErr = -1702
weProtocolErr = -603
weUndefinedSelectorErr = -50
weFlushLeft = -2
weFlushRight = -1
weFlushDefault = 0
weCenter = 1
weJustify = 2
weDirDefault = 1
weDirRightToLeft = -1
weDirLeftToRight = 0
weDoFont = 0x0001
weDoFace = 0x0002
weDoSize = 0x0004
weDoColor = 0x0008
weDoAll = weDoFont | weDoFace | weDoSize | weDoColor
weDoAddSize = 0x0010
weDoToggleFace = 0x0020
weDoReplaceFace = 0x0040
weDoPreserveScript = 0x0080
weDoExtractSubscript = 0x0100
weDoFaceMask = 0x0200
weDoDirection = 0x00000001
weDoAlignment = 0x00000002
weDoLeftIndent = 0x00000004
weDoRightIndent = 0x00000008
weDoFirstLineIndent = 0x00000010
weDoLineSpacing = 0x00000020
weDoSpaceBefore = 0x00000040
weDoSpaceAfter = 0x00000080
weDoBottomBorderStyle = 0x00000400
kLeadingEdge = -1
kTrailingEdge = 0
kObjectEdge = 2
weFAutoScroll = 0
weFOutlineHilite = 2
weFReadOnly = 5
weFUndo = 6
weFIntCutAndPaste = 7
weFDragAndDrop = 8
weFInhibitRecal = 9
weFUseTempMem = 10
weFDrawOffscreen = 11
weFInhibitRedraw = 12
weFMonoStyled = 13
weFMultipleUndo = 14
weFNoKeyboardSync = 29
weFInhibitICSupport = 30
weFInhibitColor = 31
# weDoAutoScroll = 1UL << weFAutoScroll
# weDoOutlineHilite = 1UL << weFOutlineHilite
# weDoReadOnly = 1UL << weFReadOnly
# weDoUndo = 1UL << weFUndo
# weDoIntCutAndPaste = 1UL << weFIntCutAndPaste
# weDoDragAndDrop = 1UL << weFDragAndDrop
# weDoInhibitRecal = 1UL << weFInhibitRecal
# weDoUseTempMem = 1UL << weFUseTempMem
# weDoDrawOffscreen = 1UL << weFDrawOffscreen
# weDoInhibitRedraw = 1UL << weFInhibitRedraw
# weDoMonoStyled = 1UL << weFMonoStyled
# weDoMultipleUndo = 1UL << weFMultipleUndo
# weDoNoKeyboardSync = 1UL << weFNoKeyboardSync
# weDoInhibitICSupport = 1UL << weFInhibitICSupport
# weDoInhibitColor = 1UL << weFInhibitColor
weBitToggle = -2
weBitTest = -1
weBitClear = 0
weBitSet = 1
weLowerCase = 0
weUpperCase = 1
weFindWholeWords = 0x00000001
weFindCaseInsensitive = 0x00000002
weFindDiacriticalInsensitive = 0x00000004
wePutIntCutAndPaste = 0x00000001
wePutAddToTypingSequence = 0x00000002
wePutDetectUnicodeBOM = 0x00000200
weStreamDestinationKindMask = 0x000000FF
weStreamIncludeObjects = 0x00000100
weGetAddUnicodeBOM = 0x00000200
weGetLittleEndian = 0x00000400
weTagFontFamily = FOUR_CHAR_CODE('font')
weTagFontSize = FOUR_CHAR_CODE('ptsz')
weTagPlain = FOUR_CHAR_CODE('plan')
weTagBold = FOUR_CHAR_CODE('bold')
weTagItalic = FOUR_CHAR_CODE('ital')
weTagUnderline = FOUR_CHAR_CODE('undl')
weTagOutline = FOUR_CHAR_CODE('outl')
weTagShadow = FOUR_CHAR_CODE('shad')
weTagCondensed = FOUR_CHAR_CODE('cond')
weTagExtended = FOUR_CHAR_CODE('pexp')
weTagStrikethrough = FOUR_CHAR_CODE('strk')
weTagTextColor = FOUR_CHAR_CODE('colr')
weTagBackgroundColor = FOUR_CHAR_CODE('pbcl')
weTagTransferMode = FOUR_CHAR_CODE('pptm')
weTagVerticalShift = FOUR_CHAR_CODE('xshf')
weTagAlignment = FOUR_CHAR_CODE('pjst')
weTagDirection = FOUR_CHAR_CODE('LDIR')
weTagLineSpacing = FOUR_CHAR_CODE('ledg')
weTagLeftIndent = FOUR_CHAR_CODE('lein')
weTagRightIndent = FOUR_CHAR_CODE('riin')
weTagFirstLineIndent = FOUR_CHAR_CODE('fidt')
weTagSpaceBefore = FOUR_CHAR_CODE('spbe')
weTagSpaceAfter = FOUR_CHAR_CODE('spaf')
weTagBottomBorderStyle = FOUR_CHAR_CODE('BBRD')
weTagForceFontFamily = FOUR_CHAR_CODE('ffnt')
weTagAddFontSize = FOUR_CHAR_CODE('+siz')
weTagAddVerticalShift = FOUR_CHAR_CODE('+shf')
weTagTextEncoding = FOUR_CHAR_CODE('ptxe')
weTagQDStyles = FOUR_CHAR_CODE('qdst')
weTagTETextStyle = FOUR_CHAR_CODE('tets')
weTagAlignmentDefault = FOUR_CHAR_CODE('deft')
weTagAlignmentLeft = FOUR_CHAR_CODE('left')
weTagAlignmentCenter = FOUR_CHAR_CODE('cent')
weTagAlignmentRight = FOUR_CHAR_CODE('rght')
weTagAlignmentFull = FOUR_CHAR_CODE('full')
weTagDirectionDefault = FOUR_CHAR_CODE('deft')
weTagDirectionLeftToRight = FOUR_CHAR_CODE('L->R')
weTagDirectionRightToLeft = FOUR_CHAR_CODE('R->L')
weTagBorderStyleNone = FOUR_CHAR_CODE('NONE')
weTagBorderStyleThin = FOUR_CHAR_CODE('SLDL')
weTagBorderStyleDotted = FOUR_CHAR_CODE('DTDL')
weTagBorderStyleThick = FOUR_CHAR_CODE('THKL')
weLineSpacingSingle = 0x00000000
weLineSpacingOneAndHalf = 0x00008000
weLineSpacingDouble = 0x00010000
weCharByteHook = FOUR_CHAR_CODE('cbyt')
weCharToPixelHook = FOUR_CHAR_CODE('c2p ')
weCharTypeHook = FOUR_CHAR_CODE('ctyp')
weClickLoop = FOUR_CHAR_CODE('clik')
weCurrentDrag = FOUR_CHAR_CODE('drag')
weDrawTextHook = FOUR_CHAR_CODE('draw')
weDrawTSMHiliteHook = FOUR_CHAR_CODE('dtsm')
weEraseHook = FOUR_CHAR_CODE('eras')
weFontFamilyToNameHook = FOUR_CHAR_CODE('ff2n')
weFontNameToFamilyHook = FOUR_CHAR_CODE('fn2f')
weFluxProc = FOUR_CHAR_CODE('flux')
weHiliteDropAreaHook = FOUR_CHAR_CODE('hidr')
weLineBreakHook = FOUR_CHAR_CODE('lbrk')
wePixelToCharHook = FOUR_CHAR_CODE('p2c ')
wePort = FOUR_CHAR_CODE('port')
wePreTrackDragHook = FOUR_CHAR_CODE('ptrk')
weRefCon = FOUR_CHAR_CODE('refc')
weScrollProc = FOUR_CHAR_CODE('scrl')
weText = FOUR_CHAR_CODE('text')
weTranslateDragHook = FOUR_CHAR_CODE('xdrg')
weTranslucencyThreshold = FOUR_CHAR_CODE('tluc')
weTSMDocumentID = FOUR_CHAR_CODE('tsmd')
weTSMPreUpdate = FOUR_CHAR_CODE('pre ')
weTSMPostUpdate = FOUR_CHAR_CODE('post')
weURLHint = FOUR_CHAR_CODE('urlh')
weWordBreakHook = FOUR_CHAR_CODE('wbrk')
weNewHandler = FOUR_CHAR_CODE('new ')
weDisposeHandler = FOUR_CHAR_CODE('free')
weDrawHandler = FOUR_CHAR_CODE('draw')
weClickHandler = FOUR_CHAR_CODE('clik')
weStreamHandler = FOUR_CHAR_CODE('strm')
weHoverHandler = FOUR_CHAR_CODE('hovr')
kTypeText = FOUR_CHAR_CODE('TEXT')
kTypeStyles = FOUR_CHAR_CODE('styl')
kTypeSoup = FOUR_CHAR_CODE('SOUP')
kTypeFontTable = FOUR_CHAR_CODE('FISH')
kTypeParaFormat = FOUR_CHAR_CODE('WEpf')
kTypeRulerScrap = FOUR_CHAR_CODE('WEru')
kTypeCharFormat = FOUR_CHAR_CODE('WEcf')
kTypeStyleScrap = FOUR_CHAR_CODE('WEst')
kTypeUnicodeText = FOUR_CHAR_CODE('utxt')
kTypeUTF8Text = FOUR_CHAR_CODE('UTF8')
kTypeStyledText = FOUR_CHAR_CODE('STXT')
weAKNone = 0
weAKUnspecified = 1
weAKTyping = 2
weAKCut = 3
weAKPaste = 4
weAKClear = 5
weAKDrag = 6
weAKSetStyle = 7
weAKSetRuler = 8
weAKBackspace = 9
weAKFwdDelete = 10
weAKCaseChange = 11
weAKObjectChange = 12
weToScrap = 0
weToDrag = 1
weToSoup = 2
weMouseEnter = 0
weMouseWithin = 1
weMouseLeave = 2
kCurrentSelection = -1
kNullStyle = -2
| Python |
from _Qt import *
try:
_ = AddFilePreview
except:
raise ImportError, "Old (2.3) _Qt.so module loaded in stead of new (2.4) _Qt.so"
| Python |
# Generated from 'Appearance.h'
def FOUR_CHAR_CODE(x): return x
kAppearanceEventClass = FOUR_CHAR_CODE('appr')
kAEAppearanceChanged = FOUR_CHAR_CODE('thme')
kAESystemFontChanged = FOUR_CHAR_CODE('sysf')
kAESmallSystemFontChanged = FOUR_CHAR_CODE('ssfn')
kAEViewsFontChanged = FOUR_CHAR_CODE('vfnt')
kThemeDataFileType = FOUR_CHAR_CODE('thme')
kThemePlatinumFileType = FOUR_CHAR_CODE('pltn')
kThemeCustomThemesFileType = FOUR_CHAR_CODE('scen')
kThemeSoundTrackFileType = FOUR_CHAR_CODE('tsnd')
kThemeBrushDialogBackgroundActive = 1
kThemeBrushDialogBackgroundInactive = 2
kThemeBrushAlertBackgroundActive = 3
kThemeBrushAlertBackgroundInactive = 4
kThemeBrushModelessDialogBackgroundActive = 5
kThemeBrushModelessDialogBackgroundInactive = 6
kThemeBrushUtilityWindowBackgroundActive = 7
kThemeBrushUtilityWindowBackgroundInactive = 8
kThemeBrushListViewSortColumnBackground = 9
kThemeBrushListViewBackground = 10
kThemeBrushIconLabelBackground = 11
kThemeBrushListViewSeparator = 12
kThemeBrushChasingArrows = 13
kThemeBrushDragHilite = 14
kThemeBrushDocumentWindowBackground = 15
kThemeBrushFinderWindowBackground = 16
kThemeBrushScrollBarDelimiterActive = 17
kThemeBrushScrollBarDelimiterInactive = 18
kThemeBrushFocusHighlight = 19
kThemeBrushPopupArrowActive = 20
kThemeBrushPopupArrowPressed = 21
kThemeBrushPopupArrowInactive = 22
kThemeBrushAppleGuideCoachmark = 23
kThemeBrushIconLabelBackgroundSelected = 24
kThemeBrushStaticAreaFill = 25
kThemeBrushActiveAreaFill = 26
kThemeBrushButtonFrameActive = 27
kThemeBrushButtonFrameInactive = 28
kThemeBrushButtonFaceActive = 29
kThemeBrushButtonFaceInactive = 30
kThemeBrushButtonFacePressed = 31
kThemeBrushButtonActiveDarkShadow = 32
kThemeBrushButtonActiveDarkHighlight = 33
kThemeBrushButtonActiveLightShadow = 34
kThemeBrushButtonActiveLightHighlight = 35
kThemeBrushButtonInactiveDarkShadow = 36
kThemeBrushButtonInactiveDarkHighlight = 37
kThemeBrushButtonInactiveLightShadow = 38
kThemeBrushButtonInactiveLightHighlight = 39
kThemeBrushButtonPressedDarkShadow = 40
kThemeBrushButtonPressedDarkHighlight = 41
kThemeBrushButtonPressedLightShadow = 42
kThemeBrushButtonPressedLightHighlight = 43
kThemeBrushBevelActiveLight = 44
kThemeBrushBevelActiveDark = 45
kThemeBrushBevelInactiveLight = 46
kThemeBrushBevelInactiveDark = 47
kThemeBrushNotificationWindowBackground = 48
kThemeBrushMovableModalBackground = 49
kThemeBrushSheetBackgroundOpaque = 50
kThemeBrushDrawerBackground = 51
kThemeBrushToolbarBackground = 52
kThemeBrushSheetBackgroundTransparent = 53
kThemeBrushMenuBackground = 54
kThemeBrushMenuBackgroundSelected = 55
kThemeBrushSheetBackground = kThemeBrushSheetBackgroundOpaque
kThemeBrushBlack = -1
kThemeBrushWhite = -2
kThemeBrushPrimaryHighlightColor = -3
kThemeBrushSecondaryHighlightColor = -4
kThemeTextColorDialogActive = 1
kThemeTextColorDialogInactive = 2
kThemeTextColorAlertActive = 3
kThemeTextColorAlertInactive = 4
kThemeTextColorModelessDialogActive = 5
kThemeTextColorModelessDialogInactive = 6
kThemeTextColorWindowHeaderActive = 7
kThemeTextColorWindowHeaderInactive = 8
kThemeTextColorPlacardActive = 9
kThemeTextColorPlacardInactive = 10
kThemeTextColorPlacardPressed = 11
kThemeTextColorPushButtonActive = 12
kThemeTextColorPushButtonInactive = 13
kThemeTextColorPushButtonPressed = 14
kThemeTextColorBevelButtonActive = 15
kThemeTextColorBevelButtonInactive = 16
kThemeTextColorBevelButtonPressed = 17
kThemeTextColorPopupButtonActive = 18
kThemeTextColorPopupButtonInactive = 19
kThemeTextColorPopupButtonPressed = 20
kThemeTextColorIconLabel = 21
kThemeTextColorListView = 22
kThemeTextColorDocumentWindowTitleActive = 23
kThemeTextColorDocumentWindowTitleInactive = 24
kThemeTextColorMovableModalWindowTitleActive = 25
kThemeTextColorMovableModalWindowTitleInactive = 26
kThemeTextColorUtilityWindowTitleActive = 27
kThemeTextColorUtilityWindowTitleInactive = 28
kThemeTextColorPopupWindowTitleActive = 29
kThemeTextColorPopupWindowTitleInactive = 30
kThemeTextColorRootMenuActive = 31
kThemeTextColorRootMenuSelected = 32
kThemeTextColorRootMenuDisabled = 33
kThemeTextColorMenuItemActive = 34
kThemeTextColorMenuItemSelected = 35
kThemeTextColorMenuItemDisabled = 36
kThemeTextColorPopupLabelActive = 37
kThemeTextColorPopupLabelInactive = 38
kThemeTextColorTabFrontActive = 39
kThemeTextColorTabNonFrontActive = 40
kThemeTextColorTabNonFrontPressed = 41
kThemeTextColorTabFrontInactive = 42
kThemeTextColorTabNonFrontInactive = 43
kThemeTextColorIconLabelSelected = 44
kThemeTextColorBevelButtonStickyActive = 45
kThemeTextColorBevelButtonStickyInactive = 46
kThemeTextColorNotification = 47
kThemeTextColorBlack = -1
kThemeTextColorWhite = -2
kThemeStateInactive = 0
kThemeStateActive = 1
kThemeStatePressed = 2
kThemeStateRollover = 6
kThemeStateUnavailable = 7
kThemeStateUnavailableInactive = 8
kThemeStateDisabled = 0
kThemeStatePressedUp = 2
kThemeStatePressedDown = 3
kThemeArrowCursor = 0
kThemeCopyArrowCursor = 1
kThemeAliasArrowCursor = 2
kThemeContextualMenuArrowCursor = 3
kThemeIBeamCursor = 4
kThemeCrossCursor = 5
kThemePlusCursor = 6
kThemeWatchCursor = 7
kThemeClosedHandCursor = 8
kThemeOpenHandCursor = 9
kThemePointingHandCursor = 10
kThemeCountingUpHandCursor = 11
kThemeCountingDownHandCursor = 12
kThemeCountingUpAndDownHandCursor = 13
kThemeSpinningCursor = 14
kThemeResizeLeftCursor = 15
kThemeResizeRightCursor = 16
kThemeResizeLeftRightCursor = 17
kThemeMenuBarNormal = 0
kThemeMenuBarSelected = 1
kThemeMenuSquareMenuBar = (1 << 0)
kThemeMenuActive = 0
kThemeMenuSelected = 1
kThemeMenuDisabled = 3
kThemeMenuTypePullDown = 0
kThemeMenuTypePopUp = 1
kThemeMenuTypeHierarchical = 2
kThemeMenuTypeInactive = 0x0100
kThemeMenuItemPlain = 0
kThemeMenuItemHierarchical = 1
kThemeMenuItemScrollUpArrow = 2
kThemeMenuItemScrollDownArrow = 3
kThemeMenuItemAtTop = 0x0100
kThemeMenuItemAtBottom = 0x0200
kThemeMenuItemHierBackground = 0x0400
kThemeMenuItemPopUpBackground = 0x0800
kThemeMenuItemHasIcon = 0x8000
kThemeMenuItemNoBackground = 0x4000
kThemeBackgroundTabPane = 1
kThemeBackgroundPlacard = 2
kThemeBackgroundWindowHeader = 3
kThemeBackgroundListViewWindowHeader = 4
kThemeBackgroundSecondaryGroupBox = 5
kThemeNameTag = FOUR_CHAR_CODE('name')
kThemeVariantNameTag = FOUR_CHAR_CODE('varn')
kThemeVariantBaseTintTag = FOUR_CHAR_CODE('tint')
kThemeHighlightColorTag = FOUR_CHAR_CODE('hcol')
kThemeScrollBarArrowStyleTag = FOUR_CHAR_CODE('sbar')
kThemeScrollBarThumbStyleTag = FOUR_CHAR_CODE('sbth')
kThemeSoundsEnabledTag = FOUR_CHAR_CODE('snds')
kThemeDblClickCollapseTag = FOUR_CHAR_CODE('coll')
kThemeAppearanceFileNameTag = FOUR_CHAR_CODE('thme')
kThemeSystemFontTag = FOUR_CHAR_CODE('lgsf')
kThemeSmallSystemFontTag = FOUR_CHAR_CODE('smsf')
kThemeViewsFontTag = FOUR_CHAR_CODE('vfnt')
kThemeViewsFontSizeTag = FOUR_CHAR_CODE('vfsz')
kThemeDesktopPatternNameTag = FOUR_CHAR_CODE('patn')
kThemeDesktopPatternTag = FOUR_CHAR_CODE('patt')
kThemeDesktopPictureNameTag = FOUR_CHAR_CODE('dpnm')
kThemeDesktopPictureAliasTag = FOUR_CHAR_CODE('dpal')
kThemeDesktopPictureAlignmentTag = FOUR_CHAR_CODE('dpan')
kThemeHighlightColorNameTag = FOUR_CHAR_CODE('hcnm')
kThemeExamplePictureIDTag = FOUR_CHAR_CODE('epic')
kThemeSoundTrackNameTag = FOUR_CHAR_CODE('sndt')
kThemeSoundMaskTag = FOUR_CHAR_CODE('smsk')
kThemeUserDefinedTag = FOUR_CHAR_CODE('user')
kThemeSmoothFontEnabledTag = FOUR_CHAR_CODE('smoo')
kThemeSmoothFontMinSizeTag = FOUR_CHAR_CODE('smos')
kTiledOnScreen = 1
kCenterOnScreen = 2
kFitToScreen = 3
kFillScreen = 4
kUseBestGuess = 5
kThemeCheckBoxClassicX = 0
kThemeCheckBoxCheckMark = 1
kThemeScrollBarArrowsSingle = 0
kThemeScrollBarArrowsLowerRight = 1
kThemeScrollBarThumbNormal = 0
kThemeScrollBarThumbProportional = 1
kThemeSystemFont = 0
kThemeSmallSystemFont = 1
kThemeSmallEmphasizedSystemFont = 2
kThemeViewsFont = 3
kThemeEmphasizedSystemFont = 4
kThemeApplicationFont = 5
kThemeLabelFont = 6
kThemeMenuTitleFont = 100
kThemeMenuItemFont = 101
kThemeMenuItemMarkFont = 102
kThemeMenuItemCmdKeyFont = 103
kThemeWindowTitleFont = 104
kThemePushButtonFont = 105
kThemeUtilityWindowTitleFont = 106
kThemeAlertHeaderFont = 107
kThemeCurrentPortFont = 200
kThemeTabNonFront = 0
kThemeTabNonFrontPressed = 1
kThemeTabNonFrontInactive = 2
kThemeTabFront = 3
kThemeTabFrontInactive = 4
kThemeTabNonFrontUnavailable = 5
kThemeTabFrontUnavailable = 6
kThemeTabNorth = 0
kThemeTabSouth = 1
kThemeTabEast = 2
kThemeTabWest = 3
kThemeSmallTabHeight = 16
kThemeLargeTabHeight = 21
kThemeTabPaneOverlap = 3
kThemeSmallTabHeightMax = 19
kThemeLargeTabHeightMax = 24
kThemeMediumScrollBar = 0
kThemeSmallScrollBar = 1
kThemeMediumSlider = 2
kThemeMediumProgressBar = 3
kThemeMediumIndeterminateBar = 4
kThemeRelevanceBar = 5
kThemeSmallSlider = 6
kThemeLargeProgressBar = 7
kThemeLargeIndeterminateBar = 8
kThemeTrackActive = 0
kThemeTrackDisabled = 1
kThemeTrackNothingToScroll = 2
kThemeTrackInactive = 3
kThemeLeftOutsideArrowPressed = 0x01
kThemeLeftInsideArrowPressed = 0x02
kThemeLeftTrackPressed = 0x04
kThemeThumbPressed = 0x08
kThemeRightTrackPressed = 0x10
kThemeRightInsideArrowPressed = 0x20
kThemeRightOutsideArrowPressed = 0x40
kThemeTopOutsideArrowPressed = kThemeLeftOutsideArrowPressed
kThemeTopInsideArrowPressed = kThemeLeftInsideArrowPressed
kThemeTopTrackPressed = kThemeLeftTrackPressed
kThemeBottomTrackPressed = kThemeRightTrackPressed
kThemeBottomInsideArrowPressed = kThemeRightInsideArrowPressed
kThemeBottomOutsideArrowPressed = kThemeRightOutsideArrowPressed
kThemeThumbPlain = 0
kThemeThumbUpward = 1
kThemeThumbDownward = 2
kThemeTrackHorizontal = (1 << 0)
kThemeTrackRightToLeft = (1 << 1)
kThemeTrackShowThumb = (1 << 2)
kThemeTrackThumbRgnIsNotGhost = (1 << 3)
kThemeTrackNoScrollBarArrows = (1 << 4)
kThemeWindowHasGrow = (1 << 0)
kThemeWindowHasHorizontalZoom = (1 << 3)
kThemeWindowHasVerticalZoom = (1 << 4)
kThemeWindowHasFullZoom = kThemeWindowHasHorizontalZoom + kThemeWindowHasVerticalZoom
kThemeWindowHasCloseBox = (1 << 5)
kThemeWindowHasCollapseBox = (1 << 6)
kThemeWindowHasTitleText = (1 << 7)
kThemeWindowIsCollapsed = (1 << 8)
kThemeWindowHasDirty = (1 << 9)
kThemeDocumentWindow = 0
kThemeDialogWindow = 1
kThemeMovableDialogWindow = 2
kThemeAlertWindow = 3
kThemeMovableAlertWindow = 4
kThemePlainDialogWindow = 5
kThemeShadowDialogWindow = 6
kThemePopupWindow = 7
kThemeUtilityWindow = 8
kThemeUtilitySideWindow = 9
kThemeSheetWindow = 10
kThemeDrawerWindow = 11
kThemeWidgetCloseBox = 0
kThemeWidgetZoomBox = 1
kThemeWidgetCollapseBox = 2
kThemeWidgetDirtyCloseBox = 6
kThemeArrowLeft = 0
kThemeArrowDown = 1
kThemeArrowRight = 2
kThemeArrowUp = 3
kThemeArrow3pt = 0
kThemeArrow5pt = 1
kThemeArrow7pt = 2
kThemeArrow9pt = 3
kThemeGrowLeft = (1 << 0)
kThemeGrowRight = (1 << 1)
kThemeGrowUp = (1 << 2)
kThemeGrowDown = (1 << 3)
kThemePushButton = 0
kThemeCheckBox = 1
kThemeRadioButton = 2
kThemeBevelButton = 3
kThemeArrowButton = 4
kThemePopupButton = 5
kThemeDisclosureButton = 6
kThemeIncDecButton = 7
kThemeSmallBevelButton = 8
kThemeMediumBevelButton = 3
kThemeLargeBevelButton = 9
kThemeListHeaderButton = 10
kThemeRoundButton = 11
kThemeLargeRoundButton = 12
kThemeSmallCheckBox = 13
kThemeSmallRadioButton = 14
kThemeRoundedBevelButton = 15
kThemeNormalCheckBox = kThemeCheckBox
kThemeNormalRadioButton = kThemeRadioButton
kThemeButtonOff = 0
kThemeButtonOn = 1
kThemeButtonMixed = 2
kThemeDisclosureRight = 0
kThemeDisclosureDown = 1
kThemeDisclosureLeft = 2
kThemeAdornmentNone = 0
kThemeAdornmentDefault = (1 << 0)
kThemeAdornmentFocus = (1 << 2)
kThemeAdornmentRightToLeft = (1 << 4)
kThemeAdornmentDrawIndicatorOnly = (1 << 5)
kThemeAdornmentHeaderButtonLeftNeighborSelected = (1 << 6)
kThemeAdornmentHeaderButtonRightNeighborSelected = (1 << 7)
kThemeAdornmentHeaderButtonSortUp = (1 << 8)
kThemeAdornmentHeaderMenuButton = (1 << 9)
kThemeAdornmentHeaderButtonNoShadow = (1 << 10)
kThemeAdornmentHeaderButtonShadowOnly = (1 << 11)
kThemeAdornmentNoShadow = kThemeAdornmentHeaderButtonNoShadow
kThemeAdornmentShadowOnly = kThemeAdornmentHeaderButtonShadowOnly
kThemeAdornmentArrowLeftArrow = (1 << 6)
kThemeAdornmentArrowDownArrow = (1 << 7)
kThemeAdornmentArrowDoubleArrow = (1 << 8)
kThemeAdornmentArrowUpArrow = (1 << 9)
kThemeNoSounds = 0
kThemeWindowSoundsMask = (1 << 0)
kThemeMenuSoundsMask = (1 << 1)
kThemeControlSoundsMask = (1 << 2)
kThemeFinderSoundsMask = (1 << 3)
kThemeDragSoundNone = 0
kThemeDragSoundMoveWindow = FOUR_CHAR_CODE('wmov')
kThemeDragSoundGrowWindow = FOUR_CHAR_CODE('wgro')
kThemeDragSoundMoveUtilWindow = FOUR_CHAR_CODE('umov')
kThemeDragSoundGrowUtilWindow = FOUR_CHAR_CODE('ugro')
kThemeDragSoundMoveDialog = FOUR_CHAR_CODE('dmov')
kThemeDragSoundMoveAlert = FOUR_CHAR_CODE('amov')
kThemeDragSoundMoveIcon = FOUR_CHAR_CODE('imov')
kThemeDragSoundSliderThumb = FOUR_CHAR_CODE('slth')
kThemeDragSoundSliderGhost = FOUR_CHAR_CODE('slgh')
kThemeDragSoundScrollBarThumb = FOUR_CHAR_CODE('sbth')
kThemeDragSoundScrollBarGhost = FOUR_CHAR_CODE('sbgh')
kThemeDragSoundScrollBarArrowDecreasing = FOUR_CHAR_CODE('sbad')
kThemeDragSoundScrollBarArrowIncreasing = FOUR_CHAR_CODE('sbai')
kThemeDragSoundDragging = FOUR_CHAR_CODE('drag')
kThemeSoundNone = 0
kThemeSoundMenuOpen = FOUR_CHAR_CODE('mnuo')
kThemeSoundMenuClose = FOUR_CHAR_CODE('mnuc')
kThemeSoundMenuItemHilite = FOUR_CHAR_CODE('mnui')
kThemeSoundMenuItemRelease = FOUR_CHAR_CODE('mnus')
kThemeSoundWindowClosePress = FOUR_CHAR_CODE('wclp')
kThemeSoundWindowCloseEnter = FOUR_CHAR_CODE('wcle')
kThemeSoundWindowCloseExit = FOUR_CHAR_CODE('wclx')
kThemeSoundWindowCloseRelease = FOUR_CHAR_CODE('wclr')
kThemeSoundWindowZoomPress = FOUR_CHAR_CODE('wzmp')
kThemeSoundWindowZoomEnter = FOUR_CHAR_CODE('wzme')
kThemeSoundWindowZoomExit = FOUR_CHAR_CODE('wzmx')
kThemeSoundWindowZoomRelease = FOUR_CHAR_CODE('wzmr')
kThemeSoundWindowCollapsePress = FOUR_CHAR_CODE('wcop')
kThemeSoundWindowCollapseEnter = FOUR_CHAR_CODE('wcoe')
kThemeSoundWindowCollapseExit = FOUR_CHAR_CODE('wcox')
kThemeSoundWindowCollapseRelease = FOUR_CHAR_CODE('wcor')
kThemeSoundWindowDragBoundary = FOUR_CHAR_CODE('wdbd')
kThemeSoundUtilWinClosePress = FOUR_CHAR_CODE('uclp')
kThemeSoundUtilWinCloseEnter = FOUR_CHAR_CODE('ucle')
kThemeSoundUtilWinCloseExit = FOUR_CHAR_CODE('uclx')
kThemeSoundUtilWinCloseRelease = FOUR_CHAR_CODE('uclr')
kThemeSoundUtilWinZoomPress = FOUR_CHAR_CODE('uzmp')
kThemeSoundUtilWinZoomEnter = FOUR_CHAR_CODE('uzme')
kThemeSoundUtilWinZoomExit = FOUR_CHAR_CODE('uzmx')
kThemeSoundUtilWinZoomRelease = FOUR_CHAR_CODE('uzmr')
kThemeSoundUtilWinCollapsePress = FOUR_CHAR_CODE('ucop')
kThemeSoundUtilWinCollapseEnter = FOUR_CHAR_CODE('ucoe')
kThemeSoundUtilWinCollapseExit = FOUR_CHAR_CODE('ucox')
kThemeSoundUtilWinCollapseRelease = FOUR_CHAR_CODE('ucor')
kThemeSoundUtilWinDragBoundary = FOUR_CHAR_CODE('udbd')
kThemeSoundWindowOpen = FOUR_CHAR_CODE('wopn')
kThemeSoundWindowClose = FOUR_CHAR_CODE('wcls')
kThemeSoundWindowZoomIn = FOUR_CHAR_CODE('wzmi')
kThemeSoundWindowZoomOut = FOUR_CHAR_CODE('wzmo')
kThemeSoundWindowCollapseUp = FOUR_CHAR_CODE('wcol')
kThemeSoundWindowCollapseDown = FOUR_CHAR_CODE('wexp')
kThemeSoundWindowActivate = FOUR_CHAR_CODE('wact')
kThemeSoundUtilWindowOpen = FOUR_CHAR_CODE('uopn')
kThemeSoundUtilWindowClose = FOUR_CHAR_CODE('ucls')
kThemeSoundUtilWindowZoomIn = FOUR_CHAR_CODE('uzmi')
kThemeSoundUtilWindowZoomOut = FOUR_CHAR_CODE('uzmo')
kThemeSoundUtilWindowCollapseUp = FOUR_CHAR_CODE('ucol')
kThemeSoundUtilWindowCollapseDown = FOUR_CHAR_CODE('uexp')
kThemeSoundUtilWindowActivate = FOUR_CHAR_CODE('uact')
kThemeSoundDialogOpen = FOUR_CHAR_CODE('dopn')
kThemeSoundDialogClose = FOUR_CHAR_CODE('dlgc')
kThemeSoundAlertOpen = FOUR_CHAR_CODE('aopn')
kThemeSoundAlertClose = FOUR_CHAR_CODE('altc')
kThemeSoundPopupWindowOpen = FOUR_CHAR_CODE('pwop')
kThemeSoundPopupWindowClose = FOUR_CHAR_CODE('pwcl')
kThemeSoundButtonPress = FOUR_CHAR_CODE('btnp')
kThemeSoundButtonEnter = FOUR_CHAR_CODE('btne')
kThemeSoundButtonExit = FOUR_CHAR_CODE('btnx')
kThemeSoundButtonRelease = FOUR_CHAR_CODE('btnr')
kThemeSoundDefaultButtonPress = FOUR_CHAR_CODE('dbtp')
kThemeSoundDefaultButtonEnter = FOUR_CHAR_CODE('dbte')
kThemeSoundDefaultButtonExit = FOUR_CHAR_CODE('dbtx')
kThemeSoundDefaultButtonRelease = FOUR_CHAR_CODE('dbtr')
kThemeSoundCancelButtonPress = FOUR_CHAR_CODE('cbtp')
kThemeSoundCancelButtonEnter = FOUR_CHAR_CODE('cbte')
kThemeSoundCancelButtonExit = FOUR_CHAR_CODE('cbtx')
kThemeSoundCancelButtonRelease = FOUR_CHAR_CODE('cbtr')
kThemeSoundCheckboxPress = FOUR_CHAR_CODE('chkp')
kThemeSoundCheckboxEnter = FOUR_CHAR_CODE('chke')
kThemeSoundCheckboxExit = FOUR_CHAR_CODE('chkx')
kThemeSoundCheckboxRelease = FOUR_CHAR_CODE('chkr')
kThemeSoundRadioPress = FOUR_CHAR_CODE('radp')
kThemeSoundRadioEnter = FOUR_CHAR_CODE('rade')
kThemeSoundRadioExit = FOUR_CHAR_CODE('radx')
kThemeSoundRadioRelease = FOUR_CHAR_CODE('radr')
kThemeSoundScrollArrowPress = FOUR_CHAR_CODE('sbap')
kThemeSoundScrollArrowEnter = FOUR_CHAR_CODE('sbae')
kThemeSoundScrollArrowExit = FOUR_CHAR_CODE('sbax')
kThemeSoundScrollArrowRelease = FOUR_CHAR_CODE('sbar')
kThemeSoundScrollEndOfTrack = FOUR_CHAR_CODE('sbte')
kThemeSoundScrollTrackPress = FOUR_CHAR_CODE('sbtp')
kThemeSoundSliderEndOfTrack = FOUR_CHAR_CODE('slte')
kThemeSoundSliderTrackPress = FOUR_CHAR_CODE('sltp')
kThemeSoundBalloonOpen = FOUR_CHAR_CODE('blno')
kThemeSoundBalloonClose = FOUR_CHAR_CODE('blnc')
kThemeSoundBevelPress = FOUR_CHAR_CODE('bevp')
kThemeSoundBevelEnter = FOUR_CHAR_CODE('beve')
kThemeSoundBevelExit = FOUR_CHAR_CODE('bevx')
kThemeSoundBevelRelease = FOUR_CHAR_CODE('bevr')
kThemeSoundLittleArrowUpPress = FOUR_CHAR_CODE('laup')
kThemeSoundLittleArrowDnPress = FOUR_CHAR_CODE('ladp')
kThemeSoundLittleArrowEnter = FOUR_CHAR_CODE('lare')
kThemeSoundLittleArrowExit = FOUR_CHAR_CODE('larx')
kThemeSoundLittleArrowUpRelease = FOUR_CHAR_CODE('laur')
kThemeSoundLittleArrowDnRelease = FOUR_CHAR_CODE('ladr')
kThemeSoundPopupPress = FOUR_CHAR_CODE('popp')
kThemeSoundPopupEnter = FOUR_CHAR_CODE('pope')
kThemeSoundPopupExit = FOUR_CHAR_CODE('popx')
kThemeSoundPopupRelease = FOUR_CHAR_CODE('popr')
kThemeSoundDisclosurePress = FOUR_CHAR_CODE('dscp')
kThemeSoundDisclosureEnter = FOUR_CHAR_CODE('dsce')
kThemeSoundDisclosureExit = FOUR_CHAR_CODE('dscx')
kThemeSoundDisclosureRelease = FOUR_CHAR_CODE('dscr')
kThemeSoundTabPressed = FOUR_CHAR_CODE('tabp')
kThemeSoundTabEnter = FOUR_CHAR_CODE('tabe')
kThemeSoundTabExit = FOUR_CHAR_CODE('tabx')
kThemeSoundTabRelease = FOUR_CHAR_CODE('tabr')
kThemeSoundDragTargetHilite = FOUR_CHAR_CODE('dthi')
kThemeSoundDragTargetUnhilite = FOUR_CHAR_CODE('dtuh')
kThemeSoundDragTargetDrop = FOUR_CHAR_CODE('dtdr')
kThemeSoundEmptyTrash = FOUR_CHAR_CODE('ftrs')
kThemeSoundSelectItem = FOUR_CHAR_CODE('fsel')
kThemeSoundNewItem = FOUR_CHAR_CODE('fnew')
kThemeSoundReceiveDrop = FOUR_CHAR_CODE('fdrp')
kThemeSoundCopyDone = FOUR_CHAR_CODE('fcpd')
kThemeSoundResolveAlias = FOUR_CHAR_CODE('fral')
kThemeSoundLaunchApp = FOUR_CHAR_CODE('flap')
kThemeSoundDiskInsert = FOUR_CHAR_CODE('dski')
kThemeSoundDiskEject = FOUR_CHAR_CODE('dske')
kThemeSoundFinderDragOnIcon = FOUR_CHAR_CODE('fdon')
kThemeSoundFinderDragOffIcon = FOUR_CHAR_CODE('fdof')
kThemePopupTabNormalPosition = 0
kThemePopupTabCenterOnWindow = 1
kThemePopupTabCenterOnOffset = 2
kThemeMetricScrollBarWidth = 0
kThemeMetricSmallScrollBarWidth = 1
kThemeMetricCheckBoxHeight = 2
kThemeMetricRadioButtonHeight = 3
kThemeMetricEditTextWhitespace = 4
kThemeMetricEditTextFrameOutset = 5
kThemeMetricListBoxFrameOutset = 6
kThemeMetricFocusRectOutset = 7
kThemeMetricImageWellThickness = 8
kThemeMetricScrollBarOverlap = 9
kThemeMetricLargeTabHeight = 10
kThemeMetricLargeTabCapsWidth = 11
kThemeMetricTabFrameOverlap = 12
kThemeMetricTabIndentOrStyle = 13
kThemeMetricTabOverlap = 14
kThemeMetricSmallTabHeight = 15
kThemeMetricSmallTabCapsWidth = 16
kThemeMetricDisclosureButtonHeight = 17
kThemeMetricRoundButtonSize = 18
kThemeMetricPushButtonHeight = 19
kThemeMetricListHeaderHeight = 20
kThemeMetricSmallCheckBoxHeight = 21
kThemeMetricDisclosureButtonWidth = 22
kThemeMetricSmallDisclosureButtonHeight = 23
kThemeMetricSmallDisclosureButtonWidth = 24
kThemeMetricDisclosureTriangleHeight = 25
kThemeMetricDisclosureTriangleWidth = 26
kThemeMetricLittleArrowsHeight = 27
kThemeMetricLittleArrowsWidth = 28
kThemeMetricPaneSplitterHeight = 29
kThemeMetricPopupButtonHeight = 30
kThemeMetricSmallPopupButtonHeight = 31
kThemeMetricLargeProgressBarThickness = 32
kThemeMetricPullDownHeight = 33
kThemeMetricSmallPullDownHeight = 34
kThemeMetricSmallPushButtonHeight = 35
kThemeMetricSmallRadioButtonHeight = 36
kThemeMetricRelevanceIndicatorHeight = 37
kThemeMetricResizeControlHeight = 38
kThemeMetricSmallResizeControlHeight = 39
kThemeMetricLargeRoundButtonSize = 40
kThemeMetricHSliderHeight = 41
kThemeMetricHSliderTickHeight = 42
kThemeMetricSmallHSliderHeight = 43
kThemeMetricSmallHSliderTickHeight = 44
kThemeMetricVSliderWidth = 45
kThemeMetricVSliderTickWidth = 46
kThemeMetricSmallVSliderWidth = 47
kThemeMetricSmallVSliderTickWidth = 48
kThemeMetricTitleBarControlsHeight = 49
kThemeMetricCheckBoxWidth = 50
kThemeMetricSmallCheckBoxWidth = 51
kThemeMetricRadioButtonWidth = 52
kThemeMetricSmallRadioButtonWidth = 53
kThemeMetricSmallHSliderMinThumbWidth = 54
kThemeMetricSmallVSliderMinThumbHeight = 55
kThemeMetricSmallHSliderTickOffset = 56
kThemeMetricSmallVSliderTickOffset = 57
kThemeMetricNormalProgressBarThickness = 58
kThemeMetricProgressBarShadowOutset = 59
kThemeMetricSmallProgressBarShadowOutset = 60
kThemeMetricPrimaryGroupBoxContentInset = 61
kThemeMetricSecondaryGroupBoxContentInset = 62
kThemeMetricMenuMarkColumnWidth = 63
kThemeMetricMenuExcludedMarkColumnWidth = 64
kThemeMetricMenuMarkIndent = 65
kThemeMetricMenuTextLeadingEdgeMargin = 66
kThemeMetricMenuTextTrailingEdgeMargin = 67
kThemeMetricMenuIndentWidth = 68
kThemeMetricMenuIconTrailingEdgeMargin = 69
# appearanceBadBrushIndexErr = themeInvalidBrushErr
# appearanceProcessRegisteredErr = themeProcessRegisteredErr
# appearanceProcessNotRegisteredErr = themeProcessNotRegisteredErr
# appearanceBadTextColorIndexErr = themeBadTextColorErr
# appearanceThemeHasNoAccents = themeHasNoAccentsErr
# appearanceBadCursorIndexErr = themeBadCursorIndexErr
kThemeActiveDialogBackgroundBrush = kThemeBrushDialogBackgroundActive
kThemeInactiveDialogBackgroundBrush = kThemeBrushDialogBackgroundInactive
kThemeActiveAlertBackgroundBrush = kThemeBrushAlertBackgroundActive
kThemeInactiveAlertBackgroundBrush = kThemeBrushAlertBackgroundInactive
kThemeActiveModelessDialogBackgroundBrush = kThemeBrushModelessDialogBackgroundActive
kThemeInactiveModelessDialogBackgroundBrush = kThemeBrushModelessDialogBackgroundInactive
kThemeActiveUtilityWindowBackgroundBrush = kThemeBrushUtilityWindowBackgroundActive
kThemeInactiveUtilityWindowBackgroundBrush = kThemeBrushUtilityWindowBackgroundInactive
kThemeListViewSortColumnBackgroundBrush = kThemeBrushListViewSortColumnBackground
kThemeListViewBackgroundBrush = kThemeBrushListViewBackground
kThemeIconLabelBackgroundBrush = kThemeBrushIconLabelBackground
kThemeListViewSeparatorBrush = kThemeBrushListViewSeparator
kThemeChasingArrowsBrush = kThemeBrushChasingArrows
kThemeDragHiliteBrush = kThemeBrushDragHilite
kThemeDocumentWindowBackgroundBrush = kThemeBrushDocumentWindowBackground
kThemeFinderWindowBackgroundBrush = kThemeBrushFinderWindowBackground
kThemeActiveScrollBarDelimiterBrush = kThemeBrushScrollBarDelimiterActive
kThemeInactiveScrollBarDelimiterBrush = kThemeBrushScrollBarDelimiterInactive
kThemeFocusHighlightBrush = kThemeBrushFocusHighlight
kThemeActivePopupArrowBrush = kThemeBrushPopupArrowActive
kThemePressedPopupArrowBrush = kThemeBrushPopupArrowPressed
kThemeInactivePopupArrowBrush = kThemeBrushPopupArrowInactive
kThemeAppleGuideCoachmarkBrush = kThemeBrushAppleGuideCoachmark
kThemeActiveDialogTextColor = kThemeTextColorDialogActive
kThemeInactiveDialogTextColor = kThemeTextColorDialogInactive
kThemeActiveAlertTextColor = kThemeTextColorAlertActive
kThemeInactiveAlertTextColor = kThemeTextColorAlertInactive
kThemeActiveModelessDialogTextColor = kThemeTextColorModelessDialogActive
kThemeInactiveModelessDialogTextColor = kThemeTextColorModelessDialogInactive
kThemeActiveWindowHeaderTextColor = kThemeTextColorWindowHeaderActive
kThemeInactiveWindowHeaderTextColor = kThemeTextColorWindowHeaderInactive
kThemeActivePlacardTextColor = kThemeTextColorPlacardActive
kThemeInactivePlacardTextColor = kThemeTextColorPlacardInactive
kThemePressedPlacardTextColor = kThemeTextColorPlacardPressed
kThemeActivePushButtonTextColor = kThemeTextColorPushButtonActive
kThemeInactivePushButtonTextColor = kThemeTextColorPushButtonInactive
kThemePressedPushButtonTextColor = kThemeTextColorPushButtonPressed
kThemeActiveBevelButtonTextColor = kThemeTextColorBevelButtonActive
kThemeInactiveBevelButtonTextColor = kThemeTextColorBevelButtonInactive
kThemePressedBevelButtonTextColor = kThemeTextColorBevelButtonPressed
kThemeActivePopupButtonTextColor = kThemeTextColorPopupButtonActive
kThemeInactivePopupButtonTextColor = kThemeTextColorPopupButtonInactive
kThemePressedPopupButtonTextColor = kThemeTextColorPopupButtonPressed
kThemeIconLabelTextColor = kThemeTextColorIconLabel
kThemeListViewTextColor = kThemeTextColorListView
kThemeActiveDocumentWindowTitleTextColor = kThemeTextColorDocumentWindowTitleActive
kThemeInactiveDocumentWindowTitleTextColor = kThemeTextColorDocumentWindowTitleInactive
kThemeActiveMovableModalWindowTitleTextColor = kThemeTextColorMovableModalWindowTitleActive
kThemeInactiveMovableModalWindowTitleTextColor = kThemeTextColorMovableModalWindowTitleInactive
kThemeActiveUtilityWindowTitleTextColor = kThemeTextColorUtilityWindowTitleActive
kThemeInactiveUtilityWindowTitleTextColor = kThemeTextColorUtilityWindowTitleInactive
kThemeActivePopupWindowTitleColor = kThemeTextColorPopupWindowTitleActive
kThemeInactivePopupWindowTitleColor = kThemeTextColorPopupWindowTitleInactive
kThemeActiveRootMenuTextColor = kThemeTextColorRootMenuActive
kThemeSelectedRootMenuTextColor = kThemeTextColorRootMenuSelected
kThemeDisabledRootMenuTextColor = kThemeTextColorRootMenuDisabled
kThemeActiveMenuItemTextColor = kThemeTextColorMenuItemActive
kThemeSelectedMenuItemTextColor = kThemeTextColorMenuItemSelected
kThemeDisabledMenuItemTextColor = kThemeTextColorMenuItemDisabled
kThemeActivePopupLabelTextColor = kThemeTextColorPopupLabelActive
kThemeInactivePopupLabelTextColor = kThemeTextColorPopupLabelInactive
kAEThemeSwitch = kAEAppearanceChanged
kThemeNoAdornment = kThemeAdornmentNone
kThemeDefaultAdornment = kThemeAdornmentDefault
kThemeFocusAdornment = kThemeAdornmentFocus
kThemeRightToLeftAdornment = kThemeAdornmentRightToLeft
kThemeDrawIndicatorOnly = kThemeAdornmentDrawIndicatorOnly
kThemeBrushPassiveAreaFill = kThemeBrushStaticAreaFill
kThemeMetricCheckBoxGlyphHeight = kThemeMetricCheckBoxHeight
kThemeMetricRadioButtonGlyphHeight = kThemeMetricRadioButtonHeight
kThemeMetricDisclosureButtonSize = kThemeMetricDisclosureButtonHeight
kThemeMetricBestListHeaderHeight = kThemeMetricListHeaderHeight
kThemeMetricSmallProgressBarThickness = kThemeMetricNormalProgressBarThickness
kThemeMetricProgressBarThickness = kThemeMetricLargeProgressBarThickness
kThemeScrollBar = kThemeMediumScrollBar
kThemeSlider = kThemeMediumSlider
kThemeProgressBar = kThemeMediumProgressBar
kThemeIndeterminateBar = kThemeMediumIndeterminateBar
| Python |
# Generated from 'Fonts.h'
def FOUR_CHAR_CODE(x): return x
kNilOptions = 0
systemFont = 0
applFont = 1
kFMDefaultOptions = kNilOptions
kFMDefaultActivationContext = kFMDefaultOptions
kFMGlobalActivationContext = 0x00000001
kFMLocalActivationContext = kFMDefaultActivationContext
kFMDefaultIterationScope = kFMDefaultOptions
kFMGlobalIterationScope = 0x00000001
kFMLocalIterationScope = kFMDefaultIterationScope
kPlatformDefaultGuiFontID = applFont
kPlatformDefaultGuiFontID = -1
commandMark = 17
checkMark = 18
diamondMark = 19
appleMark = 20
propFont = 36864L
prpFntH = 36865L
prpFntW = 36866L
prpFntHW = 36867L
fixedFont = 45056L
fxdFntH = 45057L
fxdFntW = 45058L
fxdFntHW = 45059L
fontWid = 44208L
kFMUseGlobalScopeOption = 0x00000001
kFontIDNewYork = 2
kFontIDGeneva = 3
kFontIDMonaco = 4
kFontIDVenice = 5
kFontIDLondon = 6
kFontIDAthens = 7
kFontIDSanFrancisco = 8
kFontIDToronto = 9
kFontIDCairo = 11
kFontIDLosAngeles = 12
kFontIDTimes = 20
kFontIDHelvetica = 21
kFontIDCourier = 22
kFontIDSymbol = 23
kFontIDMobile = 24
newYork = kFontIDNewYork
geneva = kFontIDGeneva
monaco = kFontIDMonaco
venice = kFontIDVenice
london = kFontIDLondon
athens = kFontIDAthens
sanFran = kFontIDSanFrancisco
toronto = kFontIDToronto
cairo = kFontIDCairo
losAngeles = kFontIDLosAngeles
times = kFontIDTimes
helvetica = kFontIDHelvetica
courier = kFontIDCourier
symbol = kFontIDSymbol
mobile = kFontIDMobile
| Python |
# Filter out warnings about signed/unsigned constants
import warnings
warnings.filterwarnings("ignore", "", FutureWarning, ".*Controls")
warnings.filterwarnings("ignore", "", FutureWarning, ".*MacTextEditor")
| Python |
from _CarbonEvt import *
| Python |
from _CG import *
| Python |
from _Launch import *
| Python |
# Generated from 'Components.h'
def FOUR_CHAR_CODE(x): return x
kAppleManufacturer = FOUR_CHAR_CODE('appl')
kComponentResourceType = FOUR_CHAR_CODE('thng')
kComponentAliasResourceType = FOUR_CHAR_CODE('thga')
kAnyComponentType = 0
kAnyComponentSubType = 0
kAnyComponentManufacturer = 0
kAnyComponentFlagsMask = 0
cmpIsMissing = 1L << 29
cmpWantsRegisterMessage = 1L << 31
kComponentOpenSelect = -1
kComponentCloseSelect = -2
kComponentCanDoSelect = -3
kComponentVersionSelect = -4
kComponentRegisterSelect = -5
kComponentTargetSelect = -6
kComponentUnregisterSelect = -7
kComponentGetMPWorkFunctionSelect = -8
kComponentExecuteWiredActionSelect = -9
kComponentGetPublicResourceSelect = -10
componentDoAutoVersion = (1 << 0)
componentWantsUnregister = (1 << 1)
componentAutoVersionIncludeFlags = (1 << 2)
componentHasMultiplePlatforms = (1 << 3)
componentLoadResident = (1 << 4)
defaultComponentIdentical = 0
defaultComponentAnyFlags = 1
defaultComponentAnyManufacturer = 2
defaultComponentAnySubType = 4
defaultComponentAnyFlagsAnyManufacturer = (defaultComponentAnyFlags + defaultComponentAnyManufacturer)
defaultComponentAnyFlagsAnyManufacturerAnySubType = (defaultComponentAnyFlags + defaultComponentAnyManufacturer + defaultComponentAnySubType)
registerComponentGlobal = 1
registerComponentNoDuplicates = 2
registerComponentAfterExisting = 4
registerComponentAliasesOnly = 8
platform68k = 1
platformPowerPC = 2
platformInterpreted = 3
platformWin32 = 4
platformPowerPCNativeEntryPoint = 5
mpWorkFlagDoWork = (1 << 0)
mpWorkFlagDoCompletion = (1 << 1)
mpWorkFlagCopyWorkBlock = (1 << 2)
mpWorkFlagDontBlock = (1 << 3)
mpWorkFlagGetProcessorCount = (1 << 4)
mpWorkFlagGetIsRunning = (1 << 6)
cmpAliasNoFlags = 0
cmpAliasOnlyThisFile = 1
uppComponentFunctionImplementedProcInfo = 0x000002F0
uppGetComponentVersionProcInfo = 0x000000F0
uppComponentSetTargetProcInfo = 0x000003F0
uppCallComponentOpenProcInfo = 0x000003F0
uppCallComponentCloseProcInfo = 0x000003F0
uppCallComponentCanDoProcInfo = 0x000002F0
uppCallComponentVersionProcInfo = 0x000000F0
uppCallComponentRegisterProcInfo = 0x000000F0
uppCallComponentTargetProcInfo = 0x000003F0
uppCallComponentUnregisterProcInfo = 0x000000F0
uppCallComponentGetMPWorkFunctionProcInfo = 0x00000FF0
uppCallComponentGetPublicResourceProcInfo = 0x00003BF0
| Python |
from _Alias import *
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.