Pike 9.0 compatibility.
The symbols in this namespace will appear in programs that use #pike 9.0 or lower.
inherit 9.1:: :
Pike has a builtin C-style preprocessor. It works similar to the ANSI-C preprocessor but has a few extra features. These and the default set of preprocessor macros are described here.
The preprocessor is usually accessed via
MasterObject->compile_file() or MasterObject->compile_string(),
but may be accessed directly by calling cpp().
compile(), cpp(), CompilerEnvironment.CPP
constant __STDC_ISO_10646__
This macro expands to the year and date (6 digits) of the Unicode standard that the Pike runtime supports.
Note that this differs slightly from the corresponding macro
in the C23 standard in that it does NOT have an ending 'L'.
__UNICODE_VERSION__
constant __UNICODE_VERSION__
This macro expands to a decimal representation of the version of
the Unicode standard that the Pike runtime supports. It is
formated with the sprintf-format %d%02d%02d with
the values major, minor and revision in order. Version 12.1 thus
results in the value 120100.
__STDC_ISO_10646__
#embed
Include a file as a list of items.
By default the items are int(8bit).
#include, #string
bool __has_embed(mixed identifiers)
This macro checks whether the set of identifiers is a valid argument
to #embed or not.
__has_embed returns 1 if the set of identifiers given as
argument is valid as an argument to #embed and 0 otherwise.
Note that the set of identifiers may contain preprocessor parameters.
Not available prior to Pike 9.0.
#if, #ifdef, constant(), defined(), #embed,
__has_include()
bool __has_include(mixed identifiers)
This macro checks whether the set of identifiers is a valid argument
to #include or not.
__has_include returns 1 if the symbol given as argument
is valid as an argument to #include and 0 otherwise.
Not available prior to Pike 9.0.
#if, #ifdef, constant(), defined(), #include,
#string, __has_embed()
protected string parse_param_if_empty(string sym, string arg)
Parse the argument to if_empty() and/or __if_empty__().
#embed, C23 6.10.3.5
protected int(0..) parse_param_limit(string sym, string arg)
Parse the argument to limit() and/or __limit__().
#embed, C23 6.10.3.2
protected type parse_param_pike_charset(string sym, string arg)
Parse the argument for the #embed parameters pike::charset()
and/or __pike__::__charset__().
This #embed parameter is used to specify the character encoding for
the embedded file. If this is not specified, the default encoding
(ie iso-8859-1) will be used.
Some commonly used charsets here are:
16-bit quantities in big-endian byte order.
16-bit quantities in little-endian byte order.
32-bit quantities in big-endian byte order.
32-bit quantities in little-endian byte order.
Text in UTF-8.
Text in UTF-16.
Text in UTF-16le.
#embed
protected string parse_param_prefix(string sym, string arg)
Parse the argument to prefix() and/or __prefix__().
#embed, C23 6.10.3.4
protected string parse_param_suffix(string sym, string arg)
Parse the argument to suffix() and/or __suffix__().
#embed, C23 6.10.3.3
This is the default namespace and contains lots of global symbols.
typedef __attribute__("utf8_string", string(8bit)) utf8_string
String containing UTF-8 encoded data.
This is similar to a string(8bit), but allows the compiler
to keep track of whether strings are UTF-8 or not.
string_to_utf8(), utf8_to_string()
typedef int(0) zero
Zero datatype.
constant UNDEFINED
The undefined value; ie a zero for which zero_type() returns 1.
constant __null_program
Program used internally by the compiler to create objects that are later modified into instances of the compiled program by the compiler.
__placeholder_object
constant __placeholder_object
Object used internally by the compiler.
__null_program
constant sprintf_args
Type constant used for typing extra arguments that are
sent to sprintf().
strict_sprintf_format, sprintf_format, sprintf()
constant sprintf_format
Type constant used for typing arguments that are optionally
sent to sprintf() depending on the presence of extra arguments.
strict_sprintf_format, sprintf_args, sprintf()
constant sprintf_result
Type constant used for typing the return value from sprintf().
strict_sprintf_format, sprintf_format, sprintf()
constant strict_sprintf_format
Type constant used for typing arguments that are always
sent to sprintf() regardless of the presence of extra arguments.
sprintf_format, sprintf_args, sprintf()
constant this
Builtin read only variable that evaluates to the current object.
this_program, this_object()
constant this_function
Builtin constant that evaluates to the current function.
continue::this_function, this, this_object()
constant this_program
Builtin constant that evaluates to the current program.
this, this_object()
program ProxyFactory(program p)
Create a class that acts as a proxy for the specified program.
pProgram to generate a proxy for.
The generated class will have the same symbols (public and
private) with the same types as in p, where accesses to
these will proxy the access to the same symbol in the proxied
(aka wrapped) object. With the following exceptions:
protected void create(object(p) obj)
Initialize the object to act as a proxy for obj.
_sprintf(int c, mapping|void params)
Special case for c == 'O', where
it will return sprintf("%O(%O)", this_program, obj),
and otherwise proxy the call.
void _destruct()/void destroy()
These lfuns will not be present as the act of them being proxied would likely confuse the proxied object.
The same proxy class will be returned if this function is called with the same program multiple times.
void _Static_assert(int constant_expression, string constant_message)
Perform a compile-time assertion check.
If constant_expression is false, a compiler error message
containing constant_message will be generated.
Note that the function call compiles to the null statement, and thus does not affect the run-time.
cpp::static_assert
array __automap__(function(:void) fun, mixed ... args)
Automap execution function.
funFunction to call for each of the mapped arguments.
argsArguments for fun. Either
| Wrapper for an array to loop over. All of the arrays will be looped over in parallel. |
| All other arguments will be held constant during
the automap, and sent as is to |
This function is used by the compiler to implement the automap syntax, and should in normal circumstances never be used directly.
It may however show up during module dumping and in backtraces.
It is an error not to have any Builtin.automap_markers
in args.
Builtin.automap_marker, map()
mixed __cast(mixed val, string|type type_name)
Cast val to the type indicated by type_name.
lfun::cast()
program __empty_program(int|void line, string|void file)
lineOptional line number of file where the program to be compiled
definition starts.
fileOptional file name where the program to be compiled is defined.
Returns a virgin (ie empty) program suitable as the target
argument to PikeCompiler().
__null_program, PikeCompiler, compile_string()
type __handle_sprintf_format(string attr, string|zero fmt, type arg_type, type|zero cont_type, mapping state)
Type attribute handler for "sprintf_format".
attrAttribute to handle, either "sprintf_format"
or "strict_sprintf_format".
fmtSprintf-style formatting string to generate type information from.
arg_typeDeclared type of the fmt argument (typically string).
cont_typeContinuation function type after the fmt argument. This is
scanned for the type attribute "sprintf_args" to
determine where the remaining arguments to sprintf() will
come from.
stateState mapping.
This function is typically called from
PikeCompiler()->apply_attribute_constant() and is used to perform
stricter compile-time argument checking of sprintf()-style functions.
It currently implements two operating modes depending on the value of
attr:
| The formatting string |
| The formatting string |
Returns cont_type with "sprintf_args" replaced by the
arguments required by the fmt formatting string, and
"sprintf_result" replaced by the resulting string type.
PikeCompiler()->apply_attribute_constant(), sprintf()
string(8bit) __parse_pike_type(string(8bit) t)
void _gdb_breakpoint()
This function only exists so that it is possible to set a gdb breakpoint on the function pike_gdb_breakpoint.
float abs(float f)
int abs(int f)
object abs(object f)
Return the absolute value for f. If f is
an object it must implement lfun::`< and
unary lfun::`-.
float acos(int|float f)
Return the arcus cosine value for f.
The result will be in radians.
cos(), asin()
float acosh(int|float f)
Return the hyperbolic arcus cosine value for f.
cosh(), asinh()
void add_constant(string name, mixed value)
void add_constant(string name)
Add a new predefined constant.
This function is often used to add builtin functions.
All programs compiled after the add_constant() function has been
called can access value by the name name.
If there is a constant called name already, it will be replaced by
by the new definition. This will not affect already compiled programs.
Calling add_constant() without a value will remove that name from
the list of constants. As with replacing, this will not affect already
compiled programs.
all_constants()
void add_include_path(string tmp)
Add a directory to search for include files.
This is the same as the command line option -I.
Note that the added directory will only be searched when using < > to quote the included file.
remove_include_path()
void add_module_path(string path, string|void subpath)
Add a directory to search for modules.
This is the same as the command line option -M.
remove_module_path()
patha string containing a path to search for Pike modules. May be a directory, or a path to a ZIP archive. If a ZIP archive path is provided, modules will be loaded from a directory, "modules" within the ZIP archive (see the subpath argument).
subpathif path is a ZIP archive, this argument will determine the path within the archive to be searched.
void add_program_path(string tmp)
Add a directory to search for programs.
This is the same as the command line option -P.
remove_program_path()
array aggregate(mixed ... elements)
Construct an array with the arguments as indices.
This function could be written in Pike as:
array aggregate(mixed ... elems) { return elems; }
Arrays are dynamically allocated there is no need to declare them
like int a[10]=allocate(10); (and it isn't possible either) like
in C, just array(int) a=allocate(10); will do.
sizeof(), arrayp(), allocate()
mapping aggregate_mapping(mixed ... elems)
Construct a mapping.
Groups the arguments together two and two in key-index pairs and
creates a mapping of those pairs. Generally, the mapping literal
syntax is handier: ([ key1:val1, key2:val2, ... ])
sizeof(), mappingp(), mkmapping()
multiset aggregate_multiset(mixed ... elems)
Construct a multiset with the arguments as indices. The multiset
will not contain any values. This method is most useful when
constructing multisets with map or similar; generally, the
multiset literal syntax is handier: (<elem1, elem2, ...>)
With it, it's also possible to construct a multiset with values:
(<index1: value1, index2: value2, ...>)
sizeof(), multisetp(), mkmultiset()
mapping(string:mixed) all_constants()
Returns a mapping containing all global constants, indexed on the name of the constant, and with the value of the constant as value.
add_constant()
array allocate(int size)
array allocate(int size, mixed init)
Allocate an array of size elements. If init is specified
then each element is initialized by copying that value
recursively.
sizeof(), aggregate(), arrayp()
array array_sscanf(string data, string format)
This function works just like sscanf(), but returns the matched
results in an array instead of assigning them to lvalues. This is often
useful for user-defined sscanf strings.
sscanf(), `/()
float asin(int|float f)
Return the arcus sine value for f.
The result will be in radians.
sin(), acos()
float asinh(int|float f)
Return the hyperbolic arcus sine value for f.
sinh(), acosh()
float atan(int|float f)
Returns the arcus tangent value for f.
The result will be in radians.
tan(), asin(), acos(), atan2()
float atan2(float f1, float f2)
Returns the arcus tangent value for f1/f2, and uses
the signs of f1 and f2 to determine the quadrant.
The result will be in radians.
tan(), asin(), acos(), atan()
float atanh(int|float f)
Returns the hyperbolic arcus tangent value for f.
tanh(), asinh(), acosh()
mixed atomic_get_set(mapping|object map, mixed key, mixed val)
mixed atomic_get_set(array arr, int index, mixed val)
Replace atomically the value for a key in a mapping or array.
maparrMapping or array to alter.
keyindexKey or index to change the value for.
valValue to change to. If value is UNDEFINED and map is a mapping
this function function behaves exactly as m_delete(map, key).
Returns the previous value for key. If map is a mapping and
there was no previous value UNDEFINED is returned.
If map is an object lfun::_m_replace() will be called
in it.
m_delete()
mixed await(Concurrent.Future future)
Stop execution of the current restartable function for now. Resume when the future completes.
Evaluates to the result of the future if it succeeds.
Throws an error if the future failed.
Calling this special form is similar to the expression:
(future->on_await(continue::this_function), yield())
Use of this from a non-restartable functions causes
a compilation warning and falls back to calling
future->get(). This will thus then perform
a wait blocking the current thread.
No checks that the future has actually completed are
performed. It is assumed that nothing else will call
the restartable function during the wait.
Concurrent.Future()->get(), yield(),
continue::this_function, Restartable functions
string basetype(mixed x)
Same as sprintf("%t",x);
sprintf()
float ceil(int|float f)
Return the closest integer value greater or equal to f.
ceil() does not return an int, merely an integer value
stored in a float.
floor(), round()
object clone_to(object placeholder, program p, mixed ... p_args)
Coerce a placeholder object into a clone of a program.
placeholderClone of __null_program to alter.
pProgram to coerce the object to be a clone of.
p_argsArguments to pass to lfun::create() in p.
Returns placeholder after successful coercion.
placeholder may also already be a clone of [p], in which
case this operation is a no-op.
__null_program
array column(array data, mixed index)
Extract a column from a two-dimensional array.
This function is exactly equivalent to:
map(data, lambda(mixed x,mixed y) { return x[y]; }, index)
Except of course it is a lot shorter and faster. That is, it indices every index in the array data on the value of the argument index and returns an array with the results.
rows()
program compile(string source, CompilationHandler|void handler, int|void major, int|void minor, program|void target, object|void placeholder)
Compile a string to a program.
This function takes a piece of Pike code as a string and compiles it into a clonable program.
The optional argument handler is used to specify an alternative
error handler. If it is not specified the current master object will
be used.
The optional arguments major and minor are used to tell the
compiler to attempt to be compatible with Pike major.minor.
Note that source must contain the complete source for a program.
It is not possible to compile a single expression or statement.
Also note that compile() does not preprocess the program.
To preprocess the program you can use compile_string() or
call the preprocessor manually by calling cpp().
compile_string(), compile_file(), cpp(), master(),
CompilationHandler, DefaultCompilerEnvironment
program compile_file(string filename, CompilationHandler|void handler, void|program p, void|object o)
Compile the Pike code contained in the file filename into a program.
This function will compile the file filename to a Pike program that can
later be instantiated. It is the same as doing
.compile_string(Stdio.read_file(filename), filename)
compile(), compile_string(), cpp()
program compile_string(string source, string|void filename, CompilationHandler|void handler, void|program p, void|object o, int|void show_if_constant_errors)
Compile the Pike code in the string source into a program.
If filename is not specified, it will default to "-".
Functionally equal to .compile(cpp(source, filename))
compile(), cpp(), compile_file()
mixed copy_value(mixed value)
Copy a value recursively.
If the result value is changed destructively (only possible for multisets, arrays and mappings) the copied value will not be changed.
The resulting value will always be equal to the copied (as tested with
the function equal()), but they may not the the same value (as tested
with `==()).
equal()
float cos(int|float f)
Return the cosine value for f.
f should be specified in radians.
acos(), sin(), tan()
float cosh(int|float f)
Return the hyperbolic cosine value for f.
acosh(), sinh(), tanh()
string cpp(string data, mapping|string|void current_file, bool|string|void charset, object|void handler, void|int compat_major, void|int compat_minor, void|int picky_cpp)
Run a string through the preprocessor.
Preprocesses the string data with Pike's builtin ANSI-C look-alike
preprocessor. If the current_file argument has not been specified,
it will default to "-". charset defaults to "ISO-10646".
If the second argument is a mapping, no other arguments may follow. Instead, they have to be given as members of the mapping (if wanted). The following members are recognized:
| Name of the current file. It is used for generating #line directives and for locating include files. |
| Charset to use when processing |
| Compilation handler. |
| Sets the major pike version used for compat handling. |
| Sets the minor pike version used for compat handling. |
| Generate more warnings. |
| This option keeps |
| If a prefix is given, only prefixed directives will be
processed. For example, if the prefix is |
| Mapping of predefined macros in addition to those
returned by |
compile()
string ctime(int timestamp)
Convert the output from a previous call to time() into a readable
string containing the current year, month, day and time.
Like localtime, this function might throw an error if the
ctime(2) call failed on the system. It's platform dependent what
time ranges that function can handle, e.g. Windows doesn't handle
a negative timestamp.
strftime(), time(), localtime(), gmtime(), mktime()
mixed decode_value(string(8bit) coded_value, void|Codec|int(-1) codec)
Decode a value from the string coded_value.
coded_valueValue to decode.
codecCodec to use when encoding objects and programs.
traceString.Buffer to contain a readable dump of the value.
debugDebug level. Only available when the runtime has been compiled --with-rtl-debug.
This function takes a string created with encode_value() or
encode_value_canonic() and converts it back to the value that was
coded.
If codec is specified, it's used as the codec for the decode.
If none is specified, then one is instantiated through
master()->Decoder(). As a compatibility fallback, the
master itself is used if it has no Decoder class.
If codec is the special value -1, then decoding of
types, functions, programs and objects is disabled.
Decoding a coded_value that you have not generated yourself
is a security risk that can lead to execution of arbitrary
code, unless codec is specified as -1.
encode_value(), encode_value_canonic()
void delay(int|float s)
This function makes the thread stop for s seconds.
Only signal handlers can interrupt the sleep. Other callbacks are not called during delay. Beware that this function uses busy-waiting to achieve the highest possible accuracy.
signal(), sleep()
string describe_backtrace(mixed trace, void|int linewidth)
Return a readable message that describes where the backtrace
trace was made (by backtrace).
It may also be an error object or array (typically caught by a
catch), in which case the error message also is included in the
description.
Pass linewidth -1 to disable wrapping of the output.
backtrace(), describe_error(), catch(), throw()
string describe_error(mixed err)
Return the error message from an error object or array (typically
caught by a catch). The type of the error is checked, hence
err is declared as mixed and not object|array.
If an error message couldn't be obtained, a fallback message
describing the failure is returned. No errors due to incorrectness
in err are thrown.
describe_backtrace(), get_backtrace
bool destruct(void|object o)
Mark an object as destructed.
Calls o->_destruct(), and then clears all variables in the
object. If no argument is given, the current object is destructed.
All pointers and function pointers to this object will become zero. The destructed object will be freed from memory as soon as possible.
Returns 1 if o has an lfun::_destruct() that
returned 1 and inhibited destruction.
string(8bit) encode_value(mixed value, Codec|void codec)
string(8bit) encode_value(mixed value, Codec|void codec, String.Buffer trace)
string(8bit) encode_value(mixed value, Codec|void codec, int(0..) debug)
Code a value into a string.
valueValue to encode.
codecCodec to use when encoding objects and programs.
traceString.Buffer to contain a readable dump of the value.
debugDebug level. Only available when the runtime has been compiled --with-rtl-debug.
This function takes a value, and converts it to a string. This string
can then be saved, sent to another Pike process, packed or used in
any way you like. When you want your value back you simply send this
string to decode_value() and it will return the value you encoded.
Almost any value can be coded, mappings, floats, arrays, circular structures etc.
If codec is specified, it's used as the codec for the encode.
If none is specified, then one is instantiated through
master()->Encoder(). As a compatibility fallback, the
master itself is used if it has no Encoder class.
If returns UNDEFINED for an
object, codec->nameof(o)val = o->encode_object(o) will be called. The
returned value will be passed to o->decode_object(o, val)
when the object is decoded.
When only simple types like int, floats, strings, mappings, multisets and arrays are encoded, the produced string is very portable between pike versions. It can at least be read by any later version.
The portability when objects, programs and functions are involved depends mostly on the codec. If the byte code is encoded, i.e. when Pike programs are actually dumped in full, then the string can probably only be read by the same pike version.
decode_value(), sprintf(), encode_value_canonic()
string(8bit) encode_value_canonic(mixed value, object|void codec)
string(8bit) encode_value_canonic(mixed value, object|void codec, String.buffer trace)
string(8bit) encode_value_canonic(mixed value, object|void codec, int(0..) debug)
Code a value into a string on canonical form.
valueValue to encode.
codecCodec to use when encoding objects and programs.
traceString.Buffer to contain a readable dump of the value.
debugDebug level. Only available when the runtime has been compiled --with-rtl-debug.
Takes a value and converts it to a string on canonical form, much like
encode_value(). The canonical form means that if an identical value is
encoded, it will produce exactly the same string again, even if it's
done at a later time and/or in another Pike process. The produced
string is compatible with decode_value().
Note that this function is more restrictive than encode_value() with
respect to the types of values it can encode. It will throw an error
if it can't encode to a canonical form.
encode_value(), decode_value()
array(int) enumerate(int n)
array enumerate(int n, void|mixed step, void|mixed start, void|function(:void) operator)
Create an array with an enumeration, useful for initializing arrays
or as first argument to map() or foreach().
The defaults are: step = 1, start = 0, operator = `+
The resulting array is calculated like this:
array enumerate(int n, mixed step, mixed start, function operator)
{
array res = allocate(n);
for (int i=0; i < n; i++)
{
res[i] = start;
start = operator(start, step);
}
return res;
}
map(), foreach()
int equal(mixed a, mixed b)
This function checks if the values a and b are equivalent.
If either of the values is an object the (normalized) result
of calling lfun::_equal() will be returned.
Returns 1 if both values are false (zero, destructed objects,
prototype functions, etc).
Returns 0 (zero) if the values have different types.
Otherwise depending on the type of the values:
| Returns the same as |
| The contents of Note that for objects this case is only reached if neither
|
| Returns |
copy_value(), `==()
void error(sprintf_format f, sprintf_args ... args)
Throws an error. A more readable version of the code
throw( ({ sprintf(f, @args), backtrace() }) ).
float exp(float|int f)
Return the natural exponential of f.
log( exp( x ) ) == x as long as exp(x) doesn't overflow an int.
pow(), log()
mixed filter(mixed arr, void|mixed fun, mixed ... extra)
Filters the elements in arr through fun.
arrarr is treated as a set of elements to be filtered, as
follows:
| Each element is filtered with |
| The values are filtered with |
| The program is treated as a mapping containing the identifiers that are indexable from it and their values. |
| If there is a |
funUnless something else is mentioned above, fun is used as
filter like this:
| When both |
|
|
| The object is used as a |
|
|
| Each element that is callable is called with |
| Each element is indexed with the given string. If the result
of that is zero then the element is filtered out, otherwise
the result is called with This is typically used when |
The function is never destructive on arr.
map(), foreach()
float floor(int|float f)
Return the closest integer value less or equal to f.
floor() does not return an int, merely an integer value
stored in a float.
ceil(), round()
CompilationHandler get_active_compilation_handler()
Returns the currently active compilation compatibility handler, or 0 (zero) if none is active.
This function should only be used during a call of compile().
get_active_error_handler(), compile(),
master()->get_compilation_handler(), CompilationHandler
CompilerEnvironment.PikeCompiler|zero get_active_compiler()
Returns the most recent of the currently active pike compilers,
or UNDEFINED if none is active.
This function should only be used during a call of compile().
get_active_error_handler(), compile(),
master()->get_compilation_handler(), CompilationHandler
CompilationHandler get_active_error_handler()
Returns the currently active compilation error handler
(second argument to compile()), or 0 (zero) if none
is active.
This function should only be used during a call of compile().
get_active_compilation_handler(), compile(), CompilationHandler
array(array(int|string|array(string))) get_all_groups()
Returns an array of arrays with all groups in the system groups source.
Each element in the returned array has the same structure as in
getgrent function.
The groups source is system dependant. Refer to your system manuals for information about how to set the source.
| Array | |
| Array with info about the group |
getgrent()
array(array(int|string)) get_all_users()
Returns an array with all users in the system.
An array with arrays of userinfo as in getpwent.
getpwent()
getpwnam()
getpwuid()
array get_backtrace(object|array err)
Return the backtrace array from an error object or array
(typically caught by a catch), or zero if there is none. Errors
are thrown on if there are problems retrieving the backtrace.
describe_backtrace(), describe_error()
array(int) get_groups_for_user(int|string user)
Gets all groups which a given user is a member of.
userUID or loginname of the user
| Array | |
| Information about all the users groups |
get_all_groups()
getgrgid()
getgrnam()
getpwuid()
getpwnam()
Iterator get_iterator(function(:void)|object|array|mapping|multiset|string data, mixed ... args)
Creates and returns a canonical iterator for data.
data can have any of the following types: | If If The iterator object is then checked whether it has
|
| If |
| If |
| If |
| If |
| If |
This function is used by foreach to get an iterator for an
object.
Iterator, lfun::_get_iterator
mapping(string:string) getenv(void|int force_update)
Queries the environment variables.
force_updateA cached copy of the real environment is kept to make this
function quicker. If the optional flag force_update is nonzero
then the real environment is queried and the cache is updated from
it. That can be necessary if the environment changes through other
means than putenv, typically from a C-level library.
Returns the whole environment as a mapping. Destructive operations on the mapping will not affect the internal environment representation.
Variable names and values cannot be wide strings nor contain
'\0' characters. Variable names also cannot contain
'=' characters.
On NT the environment variable name is case insensitive.
putenv()
string getenv(string varname, void|int force_update)
Query the value of a specific environment variable.
varnameEnvironment variable to query.
force_updateA cached copy of the real environment is kept to make this
function quicker. If the optional flag force_update is nonzero
then the real environment is queried and the cache is updated from
it. That can be necessary if the environment changes through other
means than putenv, typically from a C-level library.
Returns the value of the environment variable varname
if it exists, and 0 (zero) otherwise.
Variable names and values cannot be wide strings nor contain
'\0' characters. Variable names also cannot contain
'=' characters.
On NT the environment variable name is case insensitive.
putenv()
array(int|string|array(string)) getgrgid(int gid)
Get the group entry for the group with the id gid using the systemfunction
getgrid(3).
gidThe id of the group
An array with the information about the group
| Array | |
| Group name |
| Group password (encrypted) |
| ID of the group |
| Array with UIDs of group members |
getgrent()
getgrnam()
array(int|string|array(string)) getgrnam(string str)
Get the group entry for the group with the name str using the
systemfunction getgrnam(3).
strThe name of the group
An array with the information about the group
| Array | |
| Group name |
| Group password (encrypted) |
| ID of the group |
| Array with UIDs of group members |
getgrent()
getgrgid()
int gethrdtime(void|int nsec)
Return the high resolution real time spent with threads disabled
since the Pike interpreter was started. The time is normally
returned in microseconds, but if the optional argument nsec
is nonzero it's returned in nanoseconds.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.REAL_TIME_RESOLUTION.
_disable_threads(), gethrtime()
int gethrtime(void|int nsec)
Return the high resolution real time since some arbitrary event in
the past. The time is normally returned in microseconds, but if
the optional argument nsec is nonzero it's returned in
nanoseconds.
It's system dependent whether or not this time is monotonic, i.e.
if it's unaffected by adjustments of the calendaric clock in the
system. System.REAL_TIME_IS_MONOTONIC tells what it is. Pike
tries to use monotonic time for this function if it's available.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.REAL_TIME_RESOLUTION.
System.REAL_TIME_IS_MONOTONIC, System.REAL_TIME_RESOLUTION,
time(), System.gettimeofday(), gethrvtime(),
Pike.implicit_gc_real_time
int gethrvtime(void|int nsec)
Return the CPU time that has been consumed by this process or
thread. -1 is returned if the system couldn't determine it. The
time is normally returned in microseconds, but if the optional
argument nsec is nonzero it's returned in nanoseconds.
The CPU time includes both user and system time, i.e. it's
approximately the same thing you would get by adding together the
"utime" and "stime" fields returned by System.getrusage (but
perhaps with better accuracy).
It's however system dependent whether or not it's the time
consumed in all threads or in the current one only;
System.CPU_TIME_IS_THREAD_LOCAL tells which. If both types are
available then thread local time is preferred.
The actual accuracy on many systems is significantly less than
microseconds or nanoseconds. See System.CPU_TIME_RESOLUTION.
The garbage collector might run automatically at any time. The
time it takes is not included in the figure returned by this
function, so that normal measurements aren't randomly clobbered
by it. Explicit calls to gc are still included, though.
The special function gauge is implemented with this function.
System.CPU_TIME_IS_THREAD_LOCAL, System.CPU_TIME_RESOLUTION,
gauge(), System.getrusage(), gethrtime()
int getpid()
Returns the process ID of this process.
System.getppid(), System.getpgrp()
array(int|string) getpwnam(string str)
Get the user entry for login str using the systemfunction getpwnam(3).
strThe login name of the user whos userrecord is requested.
An array with the information about the user
| Array | |
| Users username (loginname) |
| User password (encrypted) |
| Users ID |
| Users primary group ID |
| Users real name an possibly some other info |
| Users home directory |
| Users shell |
getpwuid()
getpwent()
array(int|string) getpwuid(int uid)
Get the user entry for UID uid using the systemfunction getpwuid(3).
uidThe uid of the user whos userrecord is requested.
An array with the information about the user
| Array | |
| Users username (loginname) |
| User password (encrypted) |
| Users ID |
| Users primary group ID |
| Users real name an possibly some other info |
| Users home directory |
| Users shell |
getpwnam()
getpwent()
string getxattr(string file, string attr, void|bool symlink)
Return the value of a specified attribute, or 0 if it does not exist.
bool glob(string glob, string str)
zero|string glob(array(string) glob, string str)
array(string) glob(string glob, array(string) str)
array(string) glob(array(string) glob, array(string) str)
Match strings against a glob pattern.
glob | The glob pattern. Some characters have special meanings. When a character range is not started the following characters have special meanings:
If a character range is started the following characters have special meanings:
All other characters only match themselves. | |||||||||||||||||
| An array of glob patterns (as above). The function returns the matching glob if any of the given
patterns match. Otherwise |
str |
|
| All strings in the array |
In Pike 8.0 and earlier only '?' and '*' had
special meanings. The old implementation is available as 8.0::glob().
In Pike 8.0 and earlier 1 was also returned when matching
an array of globs against a single string.
8.0::glob(), sscanf(), Regexp
mapping(string:int) gmtime(int timestamp)
Convert seconds since 00:00:00 UTC, Jan 1, 1970 into components.
This function works like localtime() but the result is
not adjusted for the local time zone.
Timestamps prior to 1970-01-01T00:00:00 (ie negative timestamps) were not supported on NT and AIX prior to Pike 9.0.
localtime(), time(), ctime(), mktime(),
strptime()
int has_index(string haystack, int index)
int has_index(array haystack, int index)
int has_index(mapping|multiset|object|program haystack, mixed index)
Search for index in haystack.
Returns 1 if index is in the index domain of haystack,
or 0 (zero) if not found.
This function is equivalent to (but sometimes faster than):
search(indices(haystack), index) != -1
A negative index in strings and arrays as recognized by the
index operators `[]() and `[]=() is not considered
a proper index by has_index()
has_value(), has_prefix(), has_suffix(), indices(),
search(), values(), zero_type()
int has_prefix(string|object s, string prefix)
Returns 1 if the string s starts with prefix,
returns 0 (zero) otherwise.
When s is an object, it needs to implement
lfun::_sizeof() and lfun::`[].
has_suffix(), has_value(), search()
int has_suffix(string s, string suffix)
Returns 1 if the string s ends with suffix,
returns 0 (zero) otherwise.
has_prefix(), has_value(), search()
int has_value(string haystack, string value)
int has_value(string haystack, int value)
int has_value(array|mapping|object|program haystack, mixed value)
Search for value in haystack.
Returns 1 if value is in the value domain of haystack,
or 0 (zero) if not found.
This function is in all cases except when both arguments are strings equivalent to (but sometimes faster than):
search(values(haystack), value) != -1If both arguments are strings, has_value() is equivalent to:
search(haystack, value) != -1
has_index(), indices(), search(), has_prefix(),
has_suffix(), values(), zero_type()
int hash(string s)
int hash(string s, int max)
Return an integer derived from the string s. The same string
always hashes to the same value, also between processes,
architectures, and Pike versions (see compatibility notes below,
though).
If max is given, the result will be >= 0 and < max,
otherwise the result will be >= 0 and <= 0x7fffffff.
The hash algorithm was changed in Pike 8.1. If you want a hash
that is compatible with Pike 8.0 and earlier, use hash_8_0().
The hash algorithm was also changed in Pike 7.5. If you want a hash
that is compatible with Pike 7.4 and earlier, use hash_7_4().
The difference with regards to hash_8_0() only affects wide strings.
The hash algorithm was also changed in Pike 7.1. If you want a hash
that is compatible with Pike 7.0 and earlier, use hash_7_0().
This hash function differs from the one provided by hash_value(),
in that hash_value() returns a process specific value.
hash_7_0(), hash_7_4(), hash_8_0(), hash_value
int hash_7_0(string s)
int hash_7_0(string s, int max)
Return an integer derived from the string s. The same string
always hashes to the same value, also between processes.
If max is given, the result will be >= 0 and < max,
otherwise the result will be >= 0 and <= 0x7fffffff.
This function is provided for backward compatibility with code written for Pike up and including version 7.0.
This function is not NUL-safe, and is byte-order dependant.
hash(), hash_7_4
int hash_7_4(string s)
int hash_7_4(string s, int max)
Return an integer derived from the string s. The same string
always hashes to the same value, also between processes.
If max is given, the result will be >= 0 and < max,
otherwise the result will be >= 0 and <= 0x7fffffff.
This function is provided for backward compatibility with code written for Pike up and including version 7.4.
This function is byte-order dependant for wide strings.
hash_7_6(), hash_7_0
int hash_8_0(string s)
int hash_8_0(string s, int max)
Return an integer derived from the string s. The same string
always hashes to the same value, also between processes,
architectures, and Pike versions (see compatibility notes below,
though).
If max is given, the result will be >= 0 and < max,
otherwise the result will be >= 0 and <= 0x7fffffff.
Use hash_value() for in-process hashing (eg, for implementing
lfun::_hash()) or one of the cryptographic hash functions.
This function is really bad at hashing strings. Similar string often return similar hash values.
It is especially bad for url:s, paths and similarly formatted strings.
The hash algorithm was changed in Pike 7.5. If you want a hash
that is compatible with Pike 7.4 and earlier, use hash_7_4().
The difference only affects wide strings.
The hash algorithm was also changed in Pike 7.1. If you want a hash
that is compatible with Pike 7.0 and earlier, use hash_7_0().
This hash function differs from the one provided by hash_value(),
in that hash_value() returns a process specific value.
hash(), hash_7_0(), hash_7_4(), hash_value
int hash_value(mixed value)
Return a hash value for the argument. It's an integer in the native integer range.
The hash will be the same for the same value in the running process only (the memory address is typically used as the basis for the hash value).
If the value is an object with an lfun::__hash, that function
is called and its result returned.
This is the hashing method used by mappings.
lfun::__hash()
int is_absolute_path(string p)
Check if a path p is fully qualified (ie not relative).
Returns 1 if the path is absolute, 0 otherwise.
mixed iterator_index(Iterator iter)
Get the current index for iter.
iterator_value(), lfun::_iterator_index(),
get_iterator()
mixed iterator_next(Iterator iter)
Advance iter one step.
Returns UNDEFINED if the iterator failed to
advance, and otherwise the value returned from
lfun::_iterator_next().
Zero values returned by lfun::_iterator_next() are
converted to UNDEFINED when lfun::_iterator_value()
is implemented.
iterator_prev(), lfun::_iterator_next(),
get_iterator()
mixed iterator_prev(Iterator iter)
Advance iter one step backward (if supported).
iterator_next(), lfun::_iterator_prev(),
get_iterator()
mixed iterator_value(Iterator iter)
Get the current value for iter.
iterator_index(), lfun::_iterator_value(),
get_iterator()
bool kill(int pid, int signal)
Send a signal to another process.
Some signals and their supposed purpose:
| Hang-up, sent to process when user logs out. |
| Interrupt, normally sent by ctrl-c. |
| Quit, sent by ctrl-\. |
| Illegal instruction. |
| Trap, mostly used by debuggers. |
| Aborts process, can be caught, used by Pike whenever something goes seriously wrong. |
| Emulation trap. |
| Floating point error (such as division by zero). |
| Really kill a process, cannot be caught. |
| Bus error. |
| Segmentation fault, caused by accessing memory where you shouldn't. Should never happen to Pike. |
| Bad system call. Should never happen to Pike. |
| Broken pipe. |
| Signal used for timer interrupts. |
| Termination signal. |
| Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library. |
| Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library. |
| Child process died. This signal is reserved for internal use by the Pike run-time. |
| Power failure or restart. |
| Window change signal. |
| Urgent socket data. |
| Pollable event. |
| Stop (suspend) process. |
| Stop (suspend) process. Sent by ctrl-z. |
| Continue suspended. |
| TTY input for background process. |
| TTY output for background process. |
| Virtual timer expired. |
| Profiling trap. |
| Out of CPU. |
| File size limit exceeded. |
| Stack fault |
| Success. |
| Failure. |
Note that you have to use signame to translate the name of a signal to its number.
Note that the kill function is not available on platforms that do not support signals. Some platforms may also have signals not listed here.
signal(), signum(), signame(), fork()
int|float|object limit(int|float|object minval, int|float|object x, int|float|object maxval)
Limits the value x so that it's between minval and maxval.
If x is an object, it must implement the lfun::`< method.
max() and min()
array(string) listxattr(string file, void|bool symlink)
Return an array of all extended attributes set on the file
program load_module(string module_name)
Load a binary module.
This function loads a module written in C or some other language into Pike. The module is initialized and any programs or constants defined will immediately be available.
When a module is loaded the C function pike_module_init() will be called to initialize it. When Pike exits pike_module_exit() will be called. These two functions must be available in the module.
The current working directory is normally not searched for
dynamic modules. Please use "./name.so" instead of just
"name.so" to load modules from the current directory.
mapping(string:int) localtime(int timestamp)
Convert seconds since 00:00:00 UTC, 1 Jan 1970 into components.
This function returns a mapping with the following components:
| Seconds over the minute. |
| Minutes over the hour. |
| Hour of the day. |
| Day of the month. |
| Month of the year. |
| Year since 1900. |
| Day of week (0 = Sunday). |
| Day of the year. |
| Is daylight-saving time active. |
| Offset from UTC, including daylight-saving time adjustment. |
An error is thrown if the localtime(2) call failed on the system.
It's platform dependent what time ranges that function can handle,
e.g. Windows doesn't handle a negative timestamp.
Prior to Pike 7.5 the field "timezone" was sometimes not
present, and was sometimes not adjusted for daylight-saving time.
Timestamps prior to 1970-01-01T00:00:00 (ie negative timestamps) were not supported on NT and AIX prior to Pike 9.0. Note also that dst-handling may be incorrect for such timestamps.
Calendar, gmtime(), time(), ctime(), mktime(),
strptime()
float log(int|float f)
Return the natural logarithm of f.
exp( log(x) ) == x for x > 0.
pow(), exp()
string lower_case(string s)
int lower_case(int c)
Convert a string or character to lower case.
Returns a copy of the string s with all upper case characters
converted to lower case, or the character c converted to lower
case.
Assumes the string or character to be coded according to
ISO-10646 (aka Unicode). If they are not, Charset.decoder can
do the initial conversion for you.
Prior to Pike 7.5 this function only accepted strings.
upper_case(), Charset.decoder
void m_add(multiset|object l, mixed val)
Add a member to a multiset.
m_delete()
void m_clear(mapping|multiset|object map)
Clear the contents of a mapping or multiset.
This function clears the content of the mapping
or multiset map so that it becomes empty.
This is an atomic operation.
If map is an object lfun::_m_clear() will be called
in it.
m_delete()
mixed m_delete(object|mapping|multiset map, mixed index, mixed|void expected)
If map is an object that implements lfun::_m_delete(),
that function will be called with index as its single argument.
Otherwise if map is a mapping or multiset the entry with
index index will be removed from map destructively.
If the mapping or multiset does not have an entry with
index index, nothing is done.
If expected has been specified, the entry will only be
removed if its value matches (with `==()).
The value that was removed will be returned,
and UNDEFINED otherwise.
Note that m_delete() changes map destructively.
The third argument (expected) was added in Pike 9.0,
and can be used for atomic test and unset.
mappingp()
mixed map(mixed arr, void|mixed fun, mixed ... extra)
Applies fun to the elements in arr and collects the results.
arrarr is treated as a set of elements, as follows:
|
|
|
|
| The program is treated as a mapping containing the identifiers that are indexable from it and their values. |
| If there is a |
funfun is applied in different ways depending on its type:
|
|
|
|
| Each element of the |
|
|
| Each element that is callable is called with |
| Each element is indexed with the given string. If the result
of that is zero then a zero is collected, otherwise it's
called with This is typically used when |
The function is never destructive on arr.
filter(), enumerate(), foreach()
object master()
Return the current master object.
May return UNDEFINED if no master has been loaded yet.
replace_master()
int|float|object max(int|float|object, int|float|object ... args)
string max(string, string ... args)
int(0) max()
Returns the largest value among args. Compared objects
must implement the lfun::`< method.
min() and limit()
int|float|object min(int|float|object, int|float|object ... args)
string min(string, string ... args)
int(0) min()
Returns the smallest value among args. Compared objects
must implement the lfun::`< method.
max() and limit()
mapping mkmapping(array ind, array val)
Make a mapping from two arrays.
Makes a mapping ind[x]:val[x], 0 <= x < sizeof(ind).
ind and val must have the same size.
This is the inverse operation of indices() and values().
indices(), values()
multiset mkmultiset(array a)
This function creates a multiset from an array.
aggregate_multiset()
int mktime(mapping(string:int) tm)
int mktime(int sec, int min, int hour, int mday, int mon, int year, int|void isdst, int|void tz)
This function converts information about date and time into an integer which contains the number of seconds since 00:00:00 UTC, Jan 1, 1970.
You can either call this function with a mapping containing the following elements:
| Seconds over the minute. |
| Minutes over the hour. |
| Hour of the day. |
| Day of the month. |
| Month of the year. |
| Year since 1900. |
| Is daylight-saving time active. If omitted or set to |
| The timezone offset from UTC in seconds. If omitted, the time will be calculated in the local timezone. |
Or you can just send them all on one line as the second syntax suggests.
For proper UTC calculations ensure that isdst = 0 and
timezone = 0; omitting either one of these parameters
will mess up the UTC calculation.
On some operating systems (notably AIX and Win32), dates before 00:00:00 UTC, Jan 1, 1970 were not supported prior to Pike 9.0.
On most 32-bit systems, the supported range of dates is from Dec 13, 1901 20:45:52 UTC through to Jan 19, 2038 03:14:07 UTC (inclusive).
On most 64-bit systems, the supported range of dates is expressed in 56 bits and is thus practically unlimited (at least up to 1141 milion years in the past and into the future).
time(), ctime(), localtime(), gmtime(), strftime()
string normalize_path(string path)
Replaces "\" with "/" if runing on MS Windows. It is
adviced to use System.normalize_path instead.
bool object_variablep(object o, string var)
Find out if an object identifier is a variable.
This function returns 1 if var exists as a
non-protected variable in o, and returns 0 (zero)
otherwise.
indices(), values()
int objectp(mixed arg)
Returns 1 if arg is an object, 0 (zero) otherwise.
mappingp(), programp(), arrayp(), stringp(), functionp(),
multisetp(), floatp(), intp()
int|float pow(float|int n, float|int x)
mixed pow(object n, float|int|object x)
Return n raised to the power of x. If both n
and x are integers the result will be an integer.
If n is an object its pow method will be called with
x as argument.
exp(), log()
void putenv(string varname, void|string value)
Sets the environment variable varname to value.
If value is omitted or zero, the environment variable
varname is removed.
varname and value cannot be wide strings nor contain
'\0' characters. varname also cannot contain
'=' characters.
On NT the environment variable name is case insensitive.
getenv()
array random(mapping m)
float random(float max)
int random(int max)
mixed random(object o)
mixed random(array|multiset x)
Get a random value generated by the default RandomSystem.
RandomSystem()->random(), random_string()
void random_seed(int seed)
This function sets the initial value for the random generator.
random()
Random.Deterministic
string random_string(int len)
Get a string of random characters 0..255 with the length len
from the default RandomSystem.
RandomSystem()->random_string(), random()
void remove_include_path(string tmp)
Remove a directory to search for include files.
This function performs the reverse operation of add_include_path().
add_include_path()
void remove_module_path(string tmp)
Remove a directory to search for modules.
This function performs the reverse operation of add_module_path().
add_module_path()
void remove_program_path(string tmp)
Remove a directory to search for programs.
This function performs the reverse operation of add_program_path().
add_program_path()
void removexattr(string file, string attr, void|bool symlink)
Remove the specified extended attribute.
array replace(array a, mixed from, mixed to)
mapping replace(mapping a, mixed from, mixed to)
Generic replace function (arrays and mappings).
If the first argument is an array or mapping, the values of a which
are `==() with from will be replaced with to destructively.
a will then be returned.
Note that replace() on arrays and mappings is a destructive operation.
string replace(string s, string from, string to)
string replace(string s, array(string) from, array(string) to)
string replace(string s, array(string) from, string to)
string replace(string s, mapping(string:string) replacements)
Generic replace function (strings).
sSource string to perform the replacements on.
fromSub-string or strings to match verbatim.
toString or strings that from in s should be replaced with.
replacementsInstead of the arrays from and to a mapping equivalent to
can be used.mkmapping(from, to)
Replaces all occurrances of from in s with the corresponding to.
If all the arguments are strings, a copy of s with every
occurrence of from replaced with to will be returned.
Special case: to will be inserted between every character in
s if from is the empty string.
If the first argument is a string, and the others array(string), a string
with every occurrance of from[i] in s replaced with
to[i] will be returned.
void replace_master(object o)
Replace the master object with o.
This will let you control many aspects of how Pike works, but beware that master.pike may be required to fill certain functions, so it is usually a good idea to have your master inherit the original master and only re-define certain functions.
FIXME: Tell how to inherit the master.
master()
string reverse(string s, int|void start, int|void end)
array reverse(array a, int|void start, int|void end)
int reverse(int i, int|void start, int|void end)
mixed reverse(object o, mixed ... options)
Reverses a string, array or int.
sString to reverse.
aArray to reverse.
iInteger to reverse.
oObject to reverse.
startOptional start index of the range to reverse.
Default: 0 (zero).
endOptional end index of the range to reverse.
Default for strings: sizeof(s)-1.
Default for arrays: sizeof(a)-1.
Default for integers: Pike.get_runtime_info()->int_size - 1.
optionsOptional arguments that are to be passed to lfun::_reverse().
This function reverses a string, char by char, an array, value
by value or an int, bit by bit and returns the result. It's not
destructive on the input value. For objects it simply calls
lfun::_reverse() in the object, and returns the result.
Reversing strings can be particularly useful for parsing difficult syntaxes which require scanning backwards.
sscanf()
float round(int|float f)
Return the closest integer value to f.
round() does not return an int, merely an integer value
stored in a float.
floor(), ceil()
array rows(mixed data, array index)
Select a set of rows from an array.
This function is en optimized equivalent to:
map(index, lambda(mixed x) { return data[x]; })
That is, it indices data on every index in the array index and returns an array with the results.
column()
int search(string haystack, string|int needle, int|void start, int|void end)
int search(array haystack, mixed needle, int|void start, int|void end)
mixed search(mapping haystack, mixed needle, mixed|void start)
mixed search(object haystack, mixed needle, mixed|void start, mixed ... extra_args)
Search for needle in haystack.
haystackItem to search in. This can be one of:
| When |
| When |
| When |
| When If |
startIf the optional argument start is present search is started at
this position. This has no effect on mappings.
endIf the optional argument end is present, the search will terminate
at this position (exclusive) if not found earlier.
Returns the position of needle in haystack if found.
If not found the returned value depends on the type of haystack:
|
|
|
|
| The value returned by |
If start is supplied to an iterator object without an
lfun::_search(), haystack will need to implement
Iterator()->set_index().
For mappings and object UNDEFINED will be returned when not found.
In all other cases -1 will be returned when not found.
indices(), values(), zero_type(), has_value(),
has_prefix(), has_suffix()
int set_priority(string level, int(0..)|void pid)
array|mapping|multiset set_weak_flag(array|mapping|multiset m, int state)
Set the value m to use weak or normal references in its
indices and/or values (whatever is applicable). state is a
bitfield built by using | between the following flags:
| Use weak references for indices. Only applicable for multisets and mappings. |
| Use weak references for values. Only applicable for arrays and mappings. |
| Shorthand for |
If a flag is absent, the corresponding field will use normal
references. state can also be 1 as a compatibility
measure; it's treated like Pike.WEAK.
m will be returned.
void setxattr(string file, string attr, string value, int flags, void|bool symlink)
Set the attribute attr to the value value.
The flags parameter can be used to refine the semantics of the operation.
Stdio.XATTR_CREATE specifies a pure create, which
fails if the named attribute exists already.
Stdio.XATTR_REPLACE specifies a pure replace operation, which
fails if the named attribute does not already exist.
By default (no flags), the extended attribute will be created if need be, or will simply replace the value if the attribute exists.
1 if successful, 0 otherwise, setting errno.
int sgn(mixed value)
int sgn(mixed value, mixed zero)
Check the sign of a value.
Returns -1 if value is less than zero,
1 if value is greater than zero and 0
(zero) otherwise.
abs()
function(int|void:void) signal(int sig, function(int|void:void) callback)
function(int|void:void) signal(int sig)
Trap signals.
This function allows you to trap a signal and have a function called when the process receives a signal. Although it IS possible to trap SIGBUS, SIGSEGV etc, I advise you not to; Pike should not receive any such signals, and if it does, it is because of bugs in the Pike interpreter. And all bugs should be reported, no matter how trifle.
The callback will receive the signal number as its only argument.
See the documentation for kill() for a list of signals.
If no second argument is given, the signal handler for that signal is restored to the default handler.
If the second argument is zero, the signal will be completely ignored.
Returns the previous signal function, or 0 if none had been registered.
kill(), signame(), signum()
string signame(int sig)
Returns a string describing the signal sig.
kill(), signum(), signal()
int signum(string sig)
Get a signal number given a descriptive string.
This function is the inverse of signame().
signame(), kill(), signal()
float sin(int|float f)
Returns the sine value for f.
f should be specified in radians.
asin(), cos(), tan()
float sinh(int|float f)
Returns the hyperbolic sine value for f.
asinh(), cosh(), tanh()
int(0..) sizeof(string arg)
int(0..) sizeof(array arg)
int(0..) sizeof(mapping arg)
int(0..) sizeof(multiset arg)
int(0..) sizeof(object arg)
Size query.
The result will be as follows:
arg can have any of the following types: | The number of characters in |
| The number of elements in |
| The number of key-value pairs in |
| If |
lfun::_sizeof()
void sleep(int|float s, void|int abort_on_signal)
This function makes the thread stop for s seconds.
Only signal handlers can interrupt the sleep, and only when
abort_on_signal is set. If more than one thread is running
the signal must be sent to the sleeping thread. Other callbacks
are not called during sleep.
If s is zero then this thread will yield to other threads but
not sleep otherwise. Note that Pike yields internally at regular
intervals so it's normally not necessary to do this.
signal(), delay()
array sort(array(mixed) index, array(mixed) ... data)
Sort arrays destructively.
This function sorts the array index destructively. That means
that the array itself is changed and returned, no copy is created.
If extra arguments are given, they are supposed to be arrays of the
same size as index. Each of these arrays will be modified in the
same way as index. I.e. if index 3 is moved to position 0 in index
index 3 will be moved to position 0 in all the other arrays as well.
The sort order is as follows:
Integers and floats are sorted in ascending order.
Strings are sorted primarily on the first characters that are different, and secondarily with shorter strings before longer. Different characters are sorted in ascending order on the character value. Thus the sort order is not locale dependent.
Arrays are sorted recursively on the first element. Empty arrays are sorted before nonempty ones.
Multisets are sorted recursively on the first index. Empty multisets are sorted before nonempty ones.
Objects are sorted in ascending order according to `<(),
`>() and `==().
Other types aren't reordered.
Different types are sorted in this order: Arrays, mappings,
multisets, objects, functions, programs, strings, types,
integers and floats. Note however that objects can control
their ordering wrt other types with `<, `> and `==,
so this ordering of types only applies to objects without
those functions.
The first argument is returned.
The sort is stable, i.e. elements that are compare-wise equal aren't reordered.
Array.sort_array, reverse()
string sprintf(strict_sprintf_format format, sprintf_args ... args)
Print formated output to string.
The format string is a string containing a description of how to
output the data in args. This string should generally speaking
have one %<modifiers><operator> format specifier
(examples: %s, %0d, %-=20s) for each of the arguments.
The following modifiers are supported:
| Zero pad numbers (implies right justification). | ||||||||
| Toggle truncation. | ||||||||
| Pad positive integers with a space. | ||||||||
| Pad positive integers with a plus sign. | ||||||||
| Left adjust within field size (default is right). | ||||||||
| Centered within field size. | ||||||||
| Column mode if strings are greater than field width. Breaks
between words (possibly skipping or adding spaces). Can not be
used together with | ||||||||
| Column mode with rough line break (break at exactly field width
instead of between words). Can not be used together with | ||||||||
| Table mode, print a list of | ||||||||
| Inverse table mode (left-to-right order). | ||||||||
| (Where n is a number or *) field width specifier. | ||||||||
| |||||||||
| Precision specifier. | ||||||||
| Column width specifier. | ||||||||
| If n is a * then next argument is used for precision/field
size. The argument may either be an integer, or a modifier mapping
as received by
| ||||||||
| Set a pad string. ' cannot be a part of the pad string (yet). | ||||||||
| Get pad string from argument list. | ||||||||
| Use same argument again. | ||||||||
| Repeat this on every line produced. | ||||||||
| Repeat this format for each element in the argument array. | ||||||||
| Put the string at the bottom end of column instead of top. | ||||||||
| Set width to the length of data. | ||||||||
| Select argument number n. Use * to use the next
argument as selector. The arguments are numbered starting from
|
The following operators are supported:
| Percent. |
| Signed binary integer. |
| Signed decimal integer. |
| Unsigned decimal integer. |
| Signed octal integer. |
| Lowercase signed hexadecimal integer or 8-bit string. |
| Uppercase signed hexadecimal integer or 8-bit string. |
| Character (integer). If a fieldsize has been specified this will output the low-order bytes of the integer in network (big endian) byte order. To get little endian byte order, negate the field size. |
| Float. (Locale dependent formatting.) |
| Heuristically chosen representation of float. (Locale dependent formatting.) |
| Like %g, but uses uppercase E for exponent. |
| Exponential notation float. (Locale dependent output.) |
| Like %e, but uses uppercase E for exponent. |
| Binary IEEE representation of float (%4F gives single precision, %8F gives double precision) in network (big endian) byte order. To get little endian byte order, negate the field size. |
| String. |
| Quoted string. Escapes all control and non-8-bit characters, as well as the quote characters '\\' and '\"'. |
| Any value, debug style. Do not rely on the exact formatting;
how the result looks can vary depending on locale, phase of
the moon or anything else the |
| Hexadecimal representation of the memory address of the object. Integers and floats have no address, and are printed as themselves. |
| Binary Hollerith string.
Equivalent to |
| No argument. Same as |
| Type of the argument. |
| Perform the enclosed format for every element of the argument array. |
|
Most modifiers and operators are combinable in any fashion, but some combinations may render strange results.
If an argument is an object that implements lfun::_sprintf(), that
callback will be called with the operator as the first argument, and
the current modifiers as the second. The callback is expected to return
a string.
sprintf-style formatting is applied by many formatting functions, such
write() and werror(). It is also possible to get sprintf-style
compile-time argument checking by using the type-attributes
sprintf_format or strict_sprintf_format in combination
with sprintf_args.
Most formats are available in all versions of Pike; the exceptions are:
| Format | Version | Availability constant | Notes |
'*' | Pike 7.8.238 | String.__HAVE_SPRINTF_STAR_MAPPING__ | Support for specifying modifiers via a mapping. |
'b' | Pike 0.7.62 | ||
'c' | Pike 0.7.3 | Support for wide characters. | |
'c' | Pike 0.7.64 | Support for little endian output. | |
'E' | Pike 0.6.38 | ||
'F' | Pike 0.6.38 | ||
'F' | Pike 7.8.242 | String.__HAVE_SPRINTF_NEGATIVE_F__ | Support for litte endian byte order. |
'G' | Pike 0.6.38 | ||
'H' | Pike 7.7.31 | ||
'p' | Pike 7.5.4 | Implemented but disabled (#if 0-block). | |
'p' | Pike 8.1.14 | Enabled. | |
'q' | Pike 7.7.28 | ||
'x' | Pike 8.1.5 | Support for hex-formatting strings. | |
'X' | Pike 8.1.5 | Support for hex-formatting strings. | |
'[n]' | Pike 7.1.5 |
Pike v7.8 release 263 running Hilfe v3.5 (Incremental Pike Frontend) > sprintf("The unicode character %c has character code %04X.", 'A', 'A'); (1) Result: "The unicode character A has character code 0041." > sprintf("#%@02X is the HTML code for purple.", Image.Color.purple->rgb()); (2) Result: "#A020F0 is the HTML code for purple." > int n=4711; > sprintf("%d = hexadecimal %x = octal %o = %b binary", n, n, n, n); (3) Result: "4711 = hexadecimal 1267 = octal 11147 = 1001001100111 binary" > write(#"Formatting examples: Left adjusted [%-10d] Centered [%|10d] Right adjusted [%10d] Zero padded [%010d] ", n, n, n, n);Formatting examples: Left adjusted [4711 ] Centered [ 4711 ] Right adjusted [ 4711] Zero padded [0000004711](5) Result: 142 int screen_width=70; > write("%-=*s\n", screen_width, >> "This will wordwrap the specified string within the "+ >> "specified field size, this is useful say, if you let "+ >> "users specify their screen size, then the room "+ >> "descriptions will automagically word-wrap as appropriate.\n"+ >> "slosh-n's will of course force a new-line when needed.\n");This will wordwrap the specified string within the specified field size, this is useful say, if you let users specify their screen size, then the room descriptions will automagically word-wrap as appropriate. slosh-n's will of course force a new-line when needed.(6) Result: 355 > write("%-=*s %-=*s\n", screen_width/2, >> "Two columns next to each other (any number of columns will "+ >> "of course work) independantly word-wrapped, can be useful.", >> screen_width/2-1, >> "The - is to specify justification, this is in addherence "+ >> "to std sprintf which defaults to right-justification, "+ >> "this version also supports centre and right justification.");Two columns next to each other (any The - is to specify justification, number of columns will of course this is in addherence to std work) independantly word-wrapped, sprintf which defaults to can be useful. right-justification, this version also supports centre and right justification.(7) Result: 426 > write("%-$*s\n", screen_width, >> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+ >> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+ >> "be forced\nby specifying a\npresision.\nThe most obvious\n"+ >> "use is for\nformatted\nls output.");Given a list of slosh-n separated 'words', this option creates a table out of them the number of columns be forced by specifying a presision. The most obvious use is for formatted ls output.(8) Result: 312 > write("%-#*s\n", screen_width, >> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+ >> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+ >> "be forced\nby specifying a\npresision.\nThe most obvious\n"+ >> "use is for\nformatted\nls output.");Given a creates a by specifying a list of table out presision. slosh-n of them The most obvious separated the number of use is for 'words', columns formatted this option be forced ls output.(9) Result: 312 > sample = ([ "align":"left", "valign":"middle" ]); (10) Result: ([ /* 2 elements */ "align":"left", "valign":"middle" ]) > write("<td%{ %s='%s'%}>\n", (array)sample);<td valign='middle' align='left'>(11) Result: 34 > write("Of course all the simple printf options "+ >> "are supported:\n %s: %d %x %o %c\n", >> "65 as decimal, hex, octal and a char", >> 65, 65, 65, 65);Of course all the simple printf options are supported: 65 as decimal, hex, octal and a char: 65 41 101 A(12) Result: 106 > write("%[0]d, %[0]x, %[0]X, %[0]o, %[0]c\n", 75);75, 4b, 4B, 113, K(13) Result: 19 > write("#%|*s\n#%|*s\n", screen_width, "THE END", >> ([ "width":screen_width ]), "ALTERNATIVE END");# THE END # ALTERNATIVE END(14) Result: 144
lfun::_sprintf(), strict_sprintf_format, sprintf_format,
sprintf_args, String.__HAVE_SPRINTF_STAR_MAPPING__,
String.__HAVE_SPRINTF_NEGATIVE_F__.
float sqrt(float f)
int(0..) sqrt(int(0..) i)
mixed sqrt(object o)
Returns the square root of f, or in the integer case, the square root
truncated to the closest lower integer. If the argument is an object,
the lfun _sqrt in the object will be called.
pow(), log(), exp(), floor(), lfun::_sqrt
int sscanf(string data, string format, mixed ... lvalues)
The purpose of sscanf is to match a string data against a format
string and place the matching results into a list of variables. The list
of lvalues are destructively modified (which is only possible because
sscanf really is a special form, rather than a pike function) with the values
extracted from the data according to the format specification. Only
the variables up to the last matching directive of the format string are
touched.
The format string may contain strings separated by special matching
directives like %d, %s %c and %f. Every such
directive corresponds to one of the lvalues, in the order they are listed.
An lvalue is the name of a variable, a name of a local variable, an index
into an array, mapping or object. It is because of these lvalues that sscanf
can not be implemented as a normal function.
Whenever a percent character is found in the format string, a match is performed, according to which operator and modifiers follow it:
| Reads a binary integer ( |
| Reads a decimal integer ( |
| Reads an octal integer ( |
| Reads a hexadecimal integer ( |
| Reads an integer that is either octal (leading zero),
hexadecimal (leading |
| Reads one character and returns it as an integer
( |
| Returns the current character offset in |
| Reads a float ("0101" makes 101.0). |
| Reads a float encoded according to the IEEE single precision
binary format ( |
| Reads a string. If followed by %d, %s will only read non-numerical characters. If followed by a %[], %s will only read characters not present in the set. If followed by normal text, %s will match all characters up to but not including the first occurrence of that text. |
| Reads a Hollerith-encoded string, i.e. first reads the length
of the string and then that number of characters. The size and
byte order of the length descriptor can be modified in the
same way as %c. As an example |
| Matches a string containing a given set of characters (those given
inside the brackets). Ranges of characters can be defined by using
a minus character between the first and the last character to be
included in the range. Example: |
| Repeatedly matches 'format' as many times as possible and assigns an array of arrays with the results to the lvalue. |
| Match a Pike constant, such as string or integer (currently only integer, string and character constants are functional). |
| Match a single percent character (hence this is how you quote the % character to just match, and not start an lvalue matcher directive). |
Similar to sprintf, you may supply modifiers between the % character
and the operator, to slightly change its behaviour from the default:
| The operator will only match its argument, without assigning any variable. |
| You may define a field width by supplying a numeric modifier.
This means that the format should match that number of
characters in the input data; be it a number characters
long string, integer or otherwise ( |
| Supplying a minus sign toggles the decoding to read the data encoded in little-endian byte order, rather than the default network (big-endian) byte order. |
| Interpret the data as a signed entity. In other words,
|
| Ignore the matched characters with respect to any following
|
Sscanf does not use backtracking. Sscanf simply looks at the format string up to the next % and tries to match that with the string. It then proceeds to look at the next part. If a part does not match, sscanf immediately returns how many % were matched. If this happens, the lvalues for % that were not matched will not be changed.
// a will be assigned "oo" and 1 will be returned sscanf("foo", "f%s", a); // a will be 4711 and b will be "bar", 2 will be returned sscanf("4711bar", "%d%s", a, b); // a will be 4711, 2 will be returned sscanf("bar4711foo", "%*s%d", a); // a will become "test", 2 will be returned sscanf(" \t test", "%*[ \t]%s", a); // Remove "the " from the beginning of a string // If 'str' does not begin with "the " it will not be changed sscanf(str, "the %s", str); // It is also possible to declare a variable directly in the sscanf call; // another reason for sscanf not to be an ordinary function: sscanf("abc def", "%s %s", string a, string b);
The number of directives matched in the format string. Note that a string directive (%s or %[]) counts as a match even when matching just the empty string (which either may do).
sprintf, array_sscanf
string(1..255) strftime(string(1..255) format, mapping(string:int) tm)
Convert the structure to a string.
The abbreviated weekday name according to the current locale
The full weekday name according to the current locale.
The abbreviated month name according to the current locale.
The full month name according to the current locale.
The preferred date and time representation for the current locale.
The century number (year/100) as a 2-digit integer.
The day of the month as a decimal number (range 01 to 31).
Equivalent to %m/%d/%y. (for Americans only.
Americans should note that in other countries %d/%m/%y
is rather common. This means that in international context
this format is ambiguous and should not be used.)
Like %d, the day of the month as a decimal number,
but a leading zero is replaced by a space.
Modifier: use alternative format, see below.
Equivalent to %Y-%m-%d (the ISO 8601 date format). (C99)
The ISO 8601 week-based year (see NOTES) with century as a
decimal number. The 4-digit year corresponding to the ISO
week number (see %V). This has the same format and
value as %Y, except that if the ISO week number
belongs to the previous or next year, that year is used instead.
Like %G, but without century, that is,
with a 2-digit year (00-99). (TZ)
Equivalent to %b.
The hour as a decimal number using a 24-hour clock (range 00 to 23).
The hour as a decimal number using a 12-hour clock (range 01 to 12).
The day of the year as a decimal number (range 001 to 366).
The month as a decimal number (range 01 to 12).
The minute as a decimal number (range 00 to 59).
A newline character. (SU)
Modifier: use alternative format, see below. (SU)
Either "AM" or "PM" according to the given time
value, or the corresponding strings for the current locale.
Noon is treated as "PM" and midnight as "AM".
Like %p but in lowercase: "am" or "pm"
or a corresponding string for the current locale.
The time in a.m. or p.m. notation. In the POSIX locale this is
equivalent to %I:%M:%S %p.
The time in 24-hour notation (%H:%M). (SU)
For a version including the seconds, see %T below.
The number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). (TZ)
The second as a decimal number (range 00 to 60). (The range is up to 60 to allow for occasional leap seconds.)
A tab character. (SU)
The time in 24-hour notation (%H:%M:%S). (SU)
The day of the week as a decimal, range 1 to 7, Monday being 1.
See also %w. (SU)
The week number of the current year as a decimal number,
range 00 to 53, starting with the first Sunday as the first
day of week 01. See also %V and %W.
The ISO 8601 week number of the current year as a decimal number,
range 01 to 53, where week 1 is the first week that has at least
4 days in the new year. See also %U and %W.
The day of the week as a decimal, range 0 to 6, Sunday being 0.
See also %u.
ctime(), mktime(), strptime(), Gettext.setlocale
string(1..) string_filter_non_unicode(string s)
Replace the most obviously non-unicode characters from s with
the unicode replacement character.
This will replace characters outside the ranges
0x00000000-0x0000d7ff and 0x0000e000-0x0010ffff
with 0xffea (the replacement character).
Charset.encoder(), string_to_unicode(),
unicode_to_string(), utf8_to_string(), string_to_utf8()
string(8bit) string_to_unicode(string s, int(0..2)|void byteorder)
Converts a string into an UTF16 compliant byte-stream.
sString to convert to UTF16.
byteorderByte-order for the output. One of:
| Network (aka big-endian) byte-order (default). |
| Little-endian byte-order. |
| Native byte-order. |
Throws an error if characters not legal in an UTF16 stream are encountered. Valid characters are in the range 0x00000 - 0x10ffff, except for characters 0xfffe and 0xffff.
Characters in range 0x010000 - 0x10ffff are encoded using surrogates.
Charset.decoder(), string_to_utf8(), unicode_to_string(),
utf8_to_string()
utf8_string string_to_utf8(string s)
utf8_string string_to_utf8(string s, int extended)
Convert a string into a UTF-8 compliant byte-stream.
sString to encode into UTF-8.
extendedBitmask with extension options.
| Accept and encode the characters outside the valid ranges using the same algorithm. Such encoded characters are however not UTF-8 compliant. |
| Encode characters outside the BMP with UTF-8 encoded UTF-16 (ie split them into surrogate pairs and encode). |
Throws an error if characters not valid in an UTF-8 stream are
encountered. Valid characters are in the ranges
0x00000000-0x0000d7ff and 0x0000e000-0x0010ffff.
Charset.encoder(), string_to_unicode(),
unicode_to_string(), utf8_to_string()
int stringp(mixed arg)
Returns 1 if arg is a string, 0 (zero) otherwise.
intp(), programp(), arrayp(), multisetp(), objectp(),
mappingp(), floatp(), functionp()
mapping(string:int) strptime(string(1..255) data, string(1..255) format)
Parse the given data using the format in format as a date.
The % character.
The weekday name according to the C locale, in abbreviated form or the full name.
The month name according to the C locale, in abbreviated form or the full name.
The date and time representation for the C locale.
The century number (0-99).
The day of month (1-31).
Equivalent to %m/%d/%y.
The hour (0-23).
The hour on a 12-hour clock (1-12).
The day number in the year (1-366).
The month number (1-12).
The minute (0-59).
Arbitrary whitespace.
The C locale's equivalent of AM or PM.
Equivalent to %H:%M.
The second (0-60; 60 may occur for leap seconds; earlier also 61 was allowed).
Arbitrary whitespace.
Equivalent to %H:%M:%S.
The week number with Sunday the first day of the week (0-53).
The weekday number (0-6) with Sunday = 0.
The week number with Monday the first day of the week (0-53).
The date, using the C locale's date format.
The time, using the C locale's time format.
The year within century (0-99). When a century is not otherwise specified, values in the range 69-99 refer to years in the twentieth century (1969-1999); values in the range 00-68 refer to years in the twenty-first century (2000-2068).
The year, including century (for example, 1991).
localtime(), gmtime(), strftime()
float tan(int|float f)
Returns the tangent value for f.
f should be specified in radians.
atan(), sin(), cos()
float tanh(int|float f)
Returns the hyperbolic tangent value for f.
atanh(), sinh(), cosh()
object this_object(void|int level)
Returns the object we are currently evaluating in.
levellevel may be used to access the object of a surrounding
class: The object at level 0 is the current object, the object
at level 1 is the one belonging to the class that surrounds
the class that the object comes from, and so on.
As opposed to a qualified this reference such as
global::this, this function doesn't always access the
objects belonging to the lexically surrounding classes. If the
class containing the call has been inherited then the objects
surrounding the inheriting class are accessed.
Thread.Local thread_local()
Returns Thread.Local().
This is primarily intended as a convenience function and detection symbol for use by the master before the module system has been fully initiated.
Thread.Local
mixed|void throw(mixed value)
Throw value to a waiting catch.
If no catch is waiting the global error handling will send the
value to master()->handle_error().
If you throw an array with where the first index contains an error
message and the second index is a backtrace, (the output from
backtrace()) then it will be treated exactly like a real error
by overlying functions.
catch
int time()
int time(int(1) one)
float time(int(2..) t)
This function returns the number of seconds since 00:00:00 UTC, 1 Jan 1970.
The second syntax does not query the system for the current
time, instead the last time value used by the pike process is returned
again. It avoids a system call, and thus is slightly faster,
but can be wildly inaccurate. Pike
queries the time internally when a thread has waited for
something, typically in sleep or in a backend (see
Pike.Backend).
The third syntax can be used to measure time more precisely than one
second. It returns how many seconds have passed since t. The precision
of this function varies from system to system.
ctime(), localtime(), mktime(), gmtime(),
System.gettimeofday(), gethrtime()
int ualarm(int useconds)
Set an alarm clock for delivery of a signal.
alarm() arranges for a SIGALRM signal to be delivered to the
process in useconds microseconds.
If useconds is 0 (zero), no new alarm will be scheduled.
Any previous alarms will in any case be canceled.
Returns the number of microseconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.
This function is only available on platforms that support signals.
alarm(), signal(), call_out()
string unicode_to_string(string(8bit) s, int(0..2)|void byteorder)
Converts an UTF16 byte-stream into a string.
sString to convert to UTF16.
byteorderDefault input byte-order. One of:
| Network (aka big-endian) byte-order (default). |
| Little-endian byte-order. |
| Native byte-order. |
Note that this argument is disregarded if s starts with a BOM.
Charset.decoder(), string_to_unicode(), string_to_utf8(),
utf8_to_string()
string upper_case(string s)
int upper_case(int c)
Convert a string or character to upper case.
Returns a copy of the string s with all lower case characters
converted to upper case, or the character c converted to upper
case.
Assumes the string or character to be coded according to
ISO-10646 (aka Unicode). If they are not, Charset.decoder can
do the initial conversion for you.
Prior to Pike 7.5 this function only accepted strings.
lower_case(), Charset.decoder
string utf8_to_string(utf8_string s)
string utf8_to_string(utf8_string s, int extended)
Converts an UTF-8 byte-stream into a string.
sString of UTF-8 encoded data to decode.
extendedBitmask with extension options.
| Accept and decode the extension used by |
| Accept and decode UTF-8 encoded UTF-16 (ie accept and decode valid surrogates). |
Throws an error if the stream is not a legal UTF-8 byte-stream.
In conformance with RFC 3629 and Unicode 3.1 and later, non-shortest forms are not decoded. An error is thrown instead.
Charset.encoder(), string_to_unicode(), string_to_utf8(),
unicode_to_string(), validate_utf8()
bool validate_utf8(utf8_string s)
bool validate_utf8(utf8_string s, int extended)
Checks whether a string is a valid UTF-8 byte-stream.
sString of UTF-8 encoded data to validate.
extendedBitmask with extension options.
| Accept the extension used by |
| Accept UTF-8 encoded UTF-16 (ie accept valid surrogate-pairs). |
Returns 0 (zero) if the stream is not a legal
UTF-8 byte-stream, and 1 if it is.
In conformance with RFC 3629 and Unicode 3.1 and later, non-shortest forms are considered invalid.
Charset.encoder(), string_to_unicode(), string_to_utf8(),
unicode_to_string(), utf8_to_string()
int werror(string fmt, mixed ... args)
Writes a string on stderr. Works just like Stdio.File.write
on Stdio.stderr.
int write(string fmt, mixed ... args)
Writes a string on stdout. Works just like Stdio.File.write
on Stdio.stdout.
mixed yield(mixed|void val)
Stop execution of the current restartable function for now,
and return the value val.
valValue to be returned from the restartable function.
May be omitted in functions returning void
(including asynchronous functions). For asynchronous
functions this means that Concurrent.Promise()->success()
in the implicit Concurrent.Promise will not be called.
Evaluates to the first argument passed to the restartable function on restart, or if it has already been called, the value passed at that time.
Calling this special form is similar to the statement:
continue return val;This syntax is however an expression and can thus be used to pass a value back.
Use of this function is only valid in restartable functions.
The second argument to a restartable function may be
a function that throws a value. That value will appear
to have been thrown via yield().
await(), Restartable functions
Boolean datatype.
constant false
constant true
An Encoder and a Decoder lumped into a single instance which
can be used for both encoding and decoding.
inherit Decoder : Decoder
inherit Encoder : Encoder
Objects used by the compiler to handle references to global symbols, modules, external files, etc.
There can be up to three compilation handlers active at the same time during a compilation. They are in order of precedence:
The error handler
This is the object passed to compile() as
the second argument (if any). This object is returned by
get_active_error_handler() during a compilation.
The compatibility handler
This is the object returned by
master()->get_compilation_handler() (if any), which
the compiler calls when it sees #pike-directives,
or expressions using the version scope
(eg 7.4::rusage). This object is returned by
get_active_compilation_handler() during a compilation.
The master object.
This is returned by master() at any time.
Any of the objects may implement a subset of the CompilationHandler
functions, and the first object that implements a function will be
used. The error handler object can thus be used to block certain
functionality (eg to restrict the number of available functions).
master()->get_compilation_handler(), get_active_error_handler(),
get_active_compilation_handler(), compile()
void compile_error(string filename, int line, string msg)
Called by compile() and cpp() when they encounter
errors in the code they compile.
filenameFile where the error was detected.
lineLine where the error was detected.
msgDescription of error.
compile_warning().
void compile_exception(mixed exception)
Called by compile() and cpp() if they trigger
exceptions.
void compile_warning(string filename, int line, string msg)
Called by compile() to report warnings.
filenameFile which triggered the warning.
lineLine which triggered the warning.
msgWarning message.
compile_error()
mapping(string:mixed)|object get_default_module()
Returns the default module from which global symbols will be fetched.
Returns the default module, or 0 (zero).
If 0 (zero) is returned the compiler use the mapping
returned by all_constants() as fallback.
get_predefines()
mapping(string:mixed) get_predefines()
Called by cpp() to get the set of global symbols.
Returns a mapping from symbol name to symbol value. Returns zero on failure.
resolv(), get_default_module()
mapping(string:mixed)|object|program|zero handle_import(string path, string filename, CompilationHandler handler)
Called by compile() and cpp() to handle import
directives specifying specific paths.
Returns the resolved value, or UNDEFINED on failure.
resolv()
string handle_include(string header_file, string current_file, bool is_local_ref)
Called by cpp() to resolv #include and #string
directives.
header_fileFile that was requested for inclusion.
current_fileFile where the directive was found.
is_local_refSpecifies reference method.
| Directive was |
| Directive was |
Returns the filename to pass to read_include() if found,
and 0 (zero) on failure.
read_include()
string read_include(string filename)
Called by cpp() to read included files.
filenameFilename as returned by handle_include().
Returns a string with the content of the header file on success,
and 0 (zero) on failure.
handle_include()
mixed resolv(string symbol, string filename, CompilationHandler handler)
Called by compile() and cpp() to resolv
module references.
Returns the resolved value, or UNDEFINED on failure.
get_predefines()
predef::CompilerEnvironment that supports handlers.
The compiler environment.
By inheriting this class and overloading the functions, it is possible to make a custom Pike compiler.
Prior to Pike 7.8 this sort of customization has to be done
either via custom master objects, or via CompilationHandlers.
CompilationHandler, MasterObject, master(), replace_master()
inherit predef::CompilerEnvironment : OrigCompilerEnvironment
inherit Reporter : Reporter
Implements the Reporter API.
Reporter()->report(), Reporter()->SeverityLevel
program compile(string source, CompilationHandler|void handler, int|void major, int|void minor, program|void target, object|void placeholder)
Compile a string to a program.
This function takes a piece of Pike code as a string and compiles it into a clonable program.
The optional argument handler is used to specify an alternative
error handler. If it is not specified the current master object will
be used.
The optional arguments major and minor are used to tell the
compiler to attempt to be compatible with Pike major.minor.
This function essentially performs
program compile(mixed ... args)
{
return PikeCompiler(@args)->compile();
}
Note that source must contain the complete source for a program.
It is not possible to compile a single expression or statement.
Also note that compile() does not preprocess the program.
To preprocess the program you can use compile_string() or
call the preprocessor manually by calling cpp().
compile_string(), compile_file(), cpp(), master(),
CompilationHandler
int compile_exception(mixed err)
string decode_charset(string data, string charset)
The default implementation calls the corresponding
function in master() with the same arguments
and returns its result.
string|zero format_exception(mixed err)
object get_compilation_handler(int major, int minor)
Get compatibility handler for Pike major.minor.
The default implementation calls the corresponding function in the master object.
This function is typically called by
PikeCompiler()->get_compilation_handler().
MasterObject()->get_compilation_handler().
mapping(string:mixed)|object get_default_module()
Get the default module for the current compatibility level
(ie typically the value returned by predef::all_constants()).
The default implementation calls the corresponding function in the master object.
| Constant table to use. |
| Use the builtin constant table. |
This function is typically called by
Pike_compiler()->get_default_module().
MasterObject()->get_default_module().
mapping(string:string|function(:void)|object) get_predefines()
Returns a mapping containing the set of predefined macros. These are typically the macros defined via the -D option when starting Pike.
After _take_over_initial_predefines() has been called, it
instead calls master()->get_predefines() and returns
its result.
cpp(), CompilationHandler->get_predefines(),
_take_over_initial_predefines()
program handle_import(string module, string current_file, object|void handler)
Look up an import module.
The default implementation calls the corresponding function in the master object.
MasterObject()->handle_import().
string handle_include(string header_file, string current_file, bool is_local_ref)
The default implementation calls the corresponding
function in master() with the same arguments
and returns its result.
program handle_inherit(string inh, string current_file, object|void handler)
Look up an inherit inh.
The default implementation calls the corresponding function in the master object.
MasterObject()->handle_inherit().
string read_include(string filename)
The default implementation calls the corresponding
function in master() with the same arguments
and returns its result.
mixed resolv(string identifier, string filename, object|void handler, object|void compat_handler)
Look up identifier in the current context.
The default implementation calls the corresponding function in the handlers (if any), falling back to the master object.
Returns the value of the identifier if found, and
UNDEFINED if not.
These flags affect the behavior of macro argument expansion,
and are used in the define()->parts array.
constant int CompilerEnvironment.CPP_DEF_ARG_MASK
Mask for converting a define()->parts entry into an argument number.
constant int CompilerEnvironment.CPP_DEF_ARG_NEED_COMMA
Insert a comma before the argument if it is not the empty varargs argument.
constant int CompilerEnvironment.CPP_DEF_ARG_NOPOSTSPACE
Inhibit insertion of whitespace after the argument expansion.
constant int CompilerEnvironment.CPP_DEF_ARG_NOPRESPACE
Inhibit insertion of whitespace before the argument expansion.
constant int CompilerEnvironment.CPP_DEF_ARG_STRINGIFY
Convert the argument to a quoted string (including initial
and ending '"').
Flags for CPP()->low_cpp() and directives.
constant int CompilerEnvironment.CPP_DO_IF
Enable cpp::defined() et al.
constant int CompilerEnvironment.CPP_END_AT_NEWLINE
Halt at end of line.
constant int CompilerEnvironment.CPP_EXPECT_ELSE
Expect #else/#elif/#elseif.
constant int CompilerEnvironment.CPP_EXPECT_ENDIF
Expect #endif.
constant int CompilerEnvironment.CPP_NO_DIRECTIVES
Disable parsing of #-directives.
constant int CompilerEnvironment.CPP_NO_EXPAND
Reserved.
constant int CompilerEnvironment.CPP_NO_OUTPUT
Inside false section of #if/#else.
constant int CompilerEnvironment.CPP_REALLY_NO_OUTPUT
Entire preprocessor is in false section.
Flags for define().
constant int CompilerEnvironment.CPP_MACRO_DISABLED
Flag indicating that the macro is temorarily disabled. Don't expand. This flag is used during preprocessing of the result from expansion of the macro.
constant int CompilerEnvironment.CPP_MACRO_IN_USE
In use. This flag is used during preprocessing of arguments to the macro.
constant int CompilerEnvironment.CPP_MACRO_KEEP_NL
Keep newlines.
constant int CompilerEnvironment.CPP_MACRO_USER_FLAGS
Mask for valid user flags (ie CPP_MACRO_VARARGS or
CPP_MACRO_KEEP_NL).
constant int CompilerEnvironment.CPP_MACRO_VARARGS
Macro is a function-style macro that accepts
more arguments than define()->num_args.
The state for an instance of the preprocessor.
The default set of supported directives and macros, etc
is documented in the cpp:: scope.
Custom directives may be added by inheriting this class and adding non-private
functions string directive_XXX(CppFlags flags, string rest_of_line),
or by adding the same to the directives mapping.
predef::cpp(), cpp(), cpp::
inherit ::this_program : this_program
CompilationHandler CompilerEnvironment.CPP.handler
CompilationHandler CompilerEnvironment.CPP.compat_handler
mapping(string:function(int(16bit), string:string|zero))|zero CompilerEnvironment.CPP.directives
Mapping containing the set of active dynamic custom preprocessor directives.
This mapping is only consulted if a corresponding directive_XXX
symbol is not present (or is private) in this.
protected mixed apply_handler(string fun, mixed ... args)
void change_cpp_compatibility(int major, int minor)
Change the pike compatibility level for this preprocessor to the specified version of Pike.
majorMajor version of Pike to attempt to be compatible with.
Specifying a major version of -1 is a short hand
for specifying __REAL_MAJOR__ and __REAL_MINOR__.
minorMinor version of Pike to attempt to be compatible with.
This function is called by the preprocessor to set the compatibility level.
The default implementation performs some normalization, and
then sets compat_major and compat_minor to their
respective values (which in turn affects symbols such as
__MAJOR__ and __MINOR__).
void clear_macros()
Clear the set of macros.
It is recomended to call this function when the CPP object
is no longer to be used.
define_macro()
int compile_exception(mixed err)
string cpp(string data, CppFlags|void flags)
Preprocess a string.
Returns the preprocessed result.
low_cpp(), high_cpp()
void cpp_error(sprintf_format msg, sprintf_args ... arguments)
Convenience function for reporting a cpp error at the current position.
This function calls report() with the same arguments,
but prefixed with suitable defaults.
report()
CompilerEnvironment.CPP CompilerEnvironment.CPP(string|void current_file, int|string|void charset, CompilationHandler|void handler, void|int compat_major, void|int compat_minor, void|int picky_cpp)
CompilerEnvironment.CPP CompilerEnvironment.CPP(mapping(string:mixed) options)
Initialize the preprocessor.
optionsIf the first argument is a mapping, no other arguments may follow. Instead, they have to be given as members of the mapping (if wanted). The following members are then recognized:
| Name of the current file. It is used for generating #line directives and for locating include files. |
| Charset to use when processing |
| Compilation handler. |
| Sets the major pike version used for compat handling. |
| Sets the minor pike version used for compat handling. |
| Generate more warnings. |
| This option keeps |
| If a prefix is given, only prefixed directives will be
processed. For example, if the prefix is |
current_fileIf the current_file argument has not been specified,
it will default to "-".
charsetTurn on automatic character set detection if 1, otherwise
specifies the character set used by the input.
Defaults to "ISO-10646".
compile()
CompilerEnvironment.CPP CompilerEnvironment.CPP(string|void current_file, bool|string|void charset, object|void handler, void|int compat_major, void|int compat_minor, void|int picky_cpp)
CompilerEnvironment.CPP CompilerEnvironment.CPP(mapping(string:mixed) options)
Initialize the preprocessor.
optionsIf the first argument is a mapping, no other arguments may follow. Instead, they have to be given as members of the mapping (if wanted). The following members are then recognized:
| Name of the current file. It is used for generating #line directives and for locating include files. |
| Charset to use when processing |
| Compilation handler. |
| Sets the major pike version used for compat handling. |
| Sets the minor pike version used for compat handling. |
| Generate more warnings. |
| This option keeps |
| If a prefix is given, only prefixed directives will be
processed. For example, if the prefix is |
| Mapping of predefined macros in addition to those
returned by |
current_fileIf the current_file argument has not been specified,
it will default to "-".
charsetTurn on automatic character set detection if 1, otherwise
specifies the character set used by the input.
Defaults to "ISO-10646".
compile()
string decode_charset(string data, string charset)
The default implementation is a proxy for the same function in the lexical parent class.
void define_ansi_macros()
Adds some cpp macros defined by the ANSI-C standards,
such as __FILE__, __LINE__, etc.
define_macro(), define_pike_macros()
void define_macro(string name, string|object|array|function(:void)|void value, int(-1..)|void numargs, CppMacroFlags|void flags)
Define a cpp macro.
nameName of macro to define. Ending the name with "()"
changes the defaults for numargs and flags to
0 and 3 respectively.
valueMacro definition. Defaults to "1".
numargsNumber of required arguments to a function-style macro.
-1 indicates not function-style.
Defaults to -1.
flagsBit-wise or of flags affecting the macro behavior:
| Function style macro with a variable number of arguments.
Invalid if |
| Keep newlines emitted by the macro. |
Defaults to 0.
define_multiple_macros()
void define_multiple_macros(mapping(string:string|function(:void)|object|array(string|CppDefArgFlags))|void predefs)
Define multiple macros in one operation.
predefsMacros to define.
The values predefs mapping may get updated by the function
in order to improve performance of a second call.
define_macro(), CompilationHandler()->get_predefines(),
_take_over_initial_predefines()
void define_pike_macros()
Adds some pike-specific cpp macros,
such as __DIR__, __VERSION__, __PIKE__, etc.
define_macro(), define_ansi_macros()
mapping(string:define) defines()
Mapping containing the set of active macros.
string drain()
Return the preprocessor output so far, and empties the buffer.
Returns the content of the output buffer.
low_cpp(), high_cpp()
string format_exception(mixed err)
Format an exception caught by cpp as a suitable cpp error message.
errCaught value.
Returns one of:
| Generate a cpp error using the default format (ie call
|
| Cpp error message to |
The default implementation just returns 0.
object get_compilation_handler(int major, int minor)
mapping(string:string|function(:void)|object|array(string|CppDefArgFlags)) get_predefines()
Get the predefined macros for this preprocessor.
This function is called by init_pike_cpp() to
retrieve the set of macros to define at initialization.
The default implementation returns the internal set of
predefined macros unless _take_over_initial_predefines()
has been called, in which case it instead calls the
corresponding function in the master.
This function does NOT return the set of currently defined macros.
init_pike_cpp(), define_multiple_macros(),
_take_over_initial_predefines(), defines
mapping|object|program handle_import(string module)
The default implementation is a proxy for the same function in the lexical parent class.
string handle_include(string header_file, string current_file, bool is_local_ref)
The default implementation is a proxy for the same function in the lexical parent class.
string|zero high_cpp(string data)
Preprocess a string.
Returns the preprocessed result, unless there was a
dependency failure in which case 0 (zero) is returned.
If the function has failed, the result so far may be
retrieved with drain().
Clears the set of defined macros on completion.
Throws error on preprocessor failure.
low_cpp(), cpp(), drain()
void init_pike_cpp()
Convenience function for initializing the preprocessor to Pike defaults.
The default implementation is essentially (disregarding error handling):
{
string save_file = current_file;
int save_line = current_line;
current_file = "<built-in>";
current_line = 0;
define_ansi_macros();
define_pike_macros();
current_file = "<command-line>";
define_multiple_macros(get_predefines());
current_file = save_current_file;
current_line = save_line;
}
void low_cpp(string data, CppFlags flags)
Preprocess a string fragment.
The preocessed result is appended to the current output buffer.
This is probably not the function you want.
cpp(), high_cpp(), drain()
string read_include(string filename)
The default implementation is a proxy for the same function in the lexical parent class.
void report(SeverityLevel severity, string filename, int(0..) linenumber, string subsystem, sprintf_format message, sprintf_args ... extra_args)
Report a diagnostic from the preprocessor.
severityThe severity of the diagnostic.
filenamelinenumberLocation which triggered the diagnostic.
linenumber 0 (zero) indicates that it is
not applicable (typically originating from command
line arguments or similar).
subsystemTypically "cpp".
messageString with the diagnostic message, with optional
sprintf()-style formatting (if any extra_args).
extra_argsExtra arguments to sprintf().
The default implementation does the following:
If there's a handler which implements Reporter()->report(),
call it with the same arguments.
Otherwise if there's a handler which implements
compile_warning() or compile_error() that matches
severity, call it with suitable arguments.
Otherwise if there's a compat handler, use it in the same manner as the handler.
Otherwise fall back to calling ::report() with the
same arguments.
In Pike 8.0 and earlier MasterObject()->report() was not called.
Reporter()->report()
void report(SeverityLevel severity, string filename, int(0..) linenumber, string subsystem, string message, mixed ... extra_args)
Report a diagnostic from the preprocessor.
severityThe severity of the diagnostic.
filenamelinenumberLocation which triggered the diagnostic.
linenumber 0 (zero) indicates that it is
not applicable (typically originating from command
line arguments or similar).
subsystemAlways "cpp".
messageString with the diagnostic message, with optional
sprintf()-style formatting (if any extra_args).
extra_argsExtra arguments to sprintf().
The default implementation just calls
CompilerEnviroment::report() in the parent with the
same arguments.
Reporter()->report(), cpp_error()
mixed resolv(string sym)
Attempt to resolve a symbol.
The default implementation calls CompilerEnvironment()->resolv()
in the parent object, with the remaining arguments taken from the
current CPP context.
Returns the value of sym if found, and UNDEFINED if not.
The Pike compiler.
An object of this class compiles a single string of Pike code.
inherit ::this_program : this_program
CompilationHandler CompilerEnvironment.PikeCompiler.handler
CompilationHandler CompilerEnvironment.PikeCompiler.compat_handler
string CompilerEnvironment.PikeCompiler.current_file
The name of the file currently being compiled (during an active compilation).
int CompilerEnvironment.PikeCompiler.current_line
The current line number (during an active compilation).
type apply_attribute_constant(string attr, mixed value, type arg_type, void cont_type, mapping state)
Handle constant arguments to attributed function argument types.
attrAttribute that arg_type had.
valueConstant value sent as parameter.
arg_typeDeclared type of the function argument.
cont_typeContinuation function type after the current argument.
stateMapping intended to hold state during checking of multiple arguments.
This function is called when a function is called
with the constant value value and it has been
successfully matched against arg_type,
and arg_type had the type attribute attr.
This function is typically used to perform specialized
argument checking and to allow for a strengthening
of the function type based on value.
The default implementation handles the following attributes:
sprintf_args
This marks the arguments to sprintf().
sprintf_format and strict_sprintf_format
These mark arguments that will be sent as the first argument
to sprintf().
sprintf_result
This marks the return value for sprintf().
sscanf_format and sscanf_76_format
These mark arguments that will be sent as the second argument
to sscanf().
sscanf_input
This is the input for sscanf().
Returns a continuation type if it succeeded in strengthening the type.
Returns UNDEFINED otherwise (this is not an error indication).
pop_type_attribute(), push_type_attribute()
protected mixed apply_handler(string fun, mixed ... args)
bool apply_type_attribute(string attribute, type a, mapping|void state)
Type attribute handler.
attributeAttribute that a had.
aContinuation of the function being called or UNDEFINED
indicating that there are no further arguments.
stateMapping intended to hold state during checking of multiple arguments.
Called during type checking when there has been successfull
partial evaluation of a function type that had the type
attribute attribute before the evaluation.
The default implementation implements the attributes:
__deprecated__
__experimental__
Returns 1 if the type check should be allowed
(ie __attribute__(attribute, a)(b)) is valid,
and 0 (zero) otherwise.
pop_type_attribute(), push_type_attribute()
void change_compiler_compatibility(int major, int minor)
Change compiler to attempt to be compatible with Pike major.minor.
program compile()
Compile the current source into a program.
This function compiles the current Pike source code into a clonable program.
compile_string(), compile_file(), cpp(), master(),
CompilationHandler, create()
CompilerEnvironment.PikeCompiler CompilerEnvironment.PikeCompiler(string|void source, CompilationHandler|void handler, int|void major, int|void minor, program|void target, object|void placeholder)
Create a PikeCompiler object for a source string.
This function takes a piece of Pike code as a string and initializes a compiler object accordingly.
sourceSource code to compile.
handlerThe optional argument handler is used to specify an alternative
error handler. If it is not specified the current master object
at compile time will be used.
majorminorThe optional arguments major and minor are used to tell the
compiler to attempt to be compatible with Pike major.minor.
target__empty_program() program to fill in. The virgin program
returned by __empty_program() will be modified and returned
by compile() on success.
placeholder__null_program() placeholder object to fill in. The object
will be modified into an instance of the resulting program
on successfull compile. Note that lfun::create() in the
program will be called without any arguments.
Note that source must contain the complete source for a program.
It is not possible to compile a single expression or statement.
Also note that no preprocessing is performed.
To preprocess the program you can use compile_string() or
call the preprocessor manually by calling cpp().
Note that all references to target and placeholder should
removed if compile() failes. On failure the placeholder
object will be destructed.
compile_string(), compile_file(), cpp(), master(),
CompilationHandler
type eval_type_attribute(string attribute, type t, mapping state)
object get_compilation_handler(int major, int minor)
Get compatibility handler for Pike major.minor.
This function is called by change_compiler_compatibility().
mapping(string:mixed)|object get_default_module()
Get the default module for the current compatibility level
(ie typically the value returned by predef::all_constants()).
The default implementation calls the corresponding function
in the current handler, the current compatibility handler
or in the parent CompilerEnvironment in that order.
| Constant table to use. |
| Use the builtin constant table. |
This function is called by change_compiler_compatibility().
program handle_import(string module)
Look up an import module.
program handle_inherit(string inh)
Look up an inherit inh in the current program.
bool index_type_attribute(string attribute, type a, type i)
Type attribute handler.
Called during type checking when a value of the type a is
indexed with a value of type i and a had the type
attribute attribute before the comparison.
The default implementation implements the "deprecated"
and "experimental" attributes.
Returns 1 if the type check should be allowed
(ie __attribute__(attribute, a)[i]), and
0 (zero) otherwise.
pop_type_attribute(), push_type_attribute()
bool|type pop_type_attribute(string attribute, type a, type b, mapping|void state)
Type attribute handler.
Called during type checking when a <= b and
a had the type attribute attribute before the
comparison.
The default implementation implements the "deprecated"
and "experimental" attributes.
Returns one of:
| An alternative type for |
| Allow the check (ie |
| Do not allow the check. |
push_type_attribute(), index_type_attribute()
bool|type push_type_attribute(string attribute, type a, type b, mapping|void state)
Type attribute handler.
Called during type checking when a <= b and
b had the type attribute attribute before the
comparison.
The default implementation implements the following attributes:
| Warns about use of deprecated functions and values. |
| Warns about use of experimental functions and values. |
| Used for type checking of |
| |
| |
| |
| Warns about passing non-UTF-8 string values to places that expect UTF-8 encoded strings. |
Returns one of:
| An alternative type for |
| Allow the check (ie |
| Do not allow the check. |
pop_type_attribute(), index_type_attribute(), utf8_string
void report(SeverityLevel severity, string filename, int linenumber, string subsystem, string message, mixed ... extra_args)
Report a diagnostic from the compiler.
The default implementation attempts to call the first corresponding function in the active handlers in priority order:
Call handler->report().
Call handler->compile_warning() or handler->compile_error()
depending on severity.
Call compat->report().
Call compat->compile_warning() or compat->compile_error()
depending on severity.
Fallback: Call CompilerEnvironment()->report()
in the parent object.
The arguments will be as follows:
The report() function will be called with the same arguments as this function.
Depending on the severity either compile_warning()
or compile_error() will be called.
They will be called with the filename, linenumber
and formatted message as arguments.
Note that these will not be called for the NOTICE severity,
and that compile_error() will be used for both ERROR and
FATAL.
In Pike 7.8 and earlier the report() function was not called in the handlers.
CompilerEnvironment()->report()
mixed resolv(string identifier)
Resolve the symbol identifier.
The default implementation calls CompilerEnvironment()->resolv()
in the parent object, with the remaining arguments taken from the
current PikeCompiler context.
Returns the value of sym if found, and UNDEFINED if not.
int(0..2) suppress_deprecation_warnings()
Allows to query whether (during an active compilation) deprecation and experimental warnings are supposed to be suppressed.
2 if deprecation and experimental warnings should be suppressed,
1 if experimental warnings should be suppressed,
0 otherwise.
Keeps the state of a single program/class during compilation.
Not in use yet!
CppMacroFlags CompilerEnvironment.define.flags
Read only
string CompilerEnvironment.define.name
Macro name.
int(-1..) CompilerEnvironment.define.num_args
Read only
array(string|CppDefArgFlags|function(mixed ... :string))|zero CompilerEnvironment.define.parts
Macro expansion rule.
string res = CompilerEnvironment.define()()
Apply the macro with the specified arguments.
argumentsArray of arguments to the macro. Zero if no parenthesis.
contextCPP context we are evaluating in.
Returns the expansion of the macro on success, and 0 (zero)
on failure (typically due to invalid arguments).
CompilerEnvironment.define CompilerEnvironment.define(string name, int num_args, array(string|CppDefArgFlags|function(mixed|void ... :string)) parts)
This class acts as a lock against other threads accessing the compiler.
The lock is released when the object is destructed.
Codec used by decode_value() to decode objects, functions and
programs which have been encoded by Encoder.nameof in the
corresponding Encoder object.
object __register_new_program(program p)
Called to register the program that is being decoded. Might get called repeatedly with several other programs that are being decoded recursively. The only safe assumption is that when the top level thing being decoded is a program, then the first call will be with the unfinished embryo that will later become that program.
Returns either zero or a placeholder object. A placeholder
object must be a clone of __null_program. When the program is
finished, the placeholder object will be converted to a clone of
it. This is used for pike module objects.
function(:void) functionof(string data)
Decode function encoded in data.
This function is called by decode_value() when it encounters
encoded functions.
dataEncoding of some function as returned by Encoder.nameof().
Returns the decoded function.
objectof(), programof()
object objectof(string data)
Decode object encoded in data.
This function is called by decode_value() when it encounters
encoded objects.
dataEncoding of some object as returned by Encoder.nameof().
Returns the decoded object.
functionof(), programof()
program programof(string data)
Decode program encoded in data.
This function is called by decode_value() when it encounters
encoded programs.
dataEncoding of some program as returned by Encoder.nameof().
Returns the decoded program.
functionof(), objectof()
Codec used by encode_value() to encode objects, functions and
programs. Its purpose is to look up some kind of identifier for
them, so they can be mapped back to the corresponding instance
by decode_value(), rather than creating a new copy.
mixed nameof(object|function(:void)|program x)
Called by encode_value() to encode objects, functions and programs.
Returns something encodable on success, typically a string.
The returned value will be passed to the corresponding
objectof(), functionof() or programof() by
decode_value().
If it returns UNDEFINED then encode_value starts to encode
the thing recursively, so that decode_value later will
rebuild a copy.
encode_value() has fallbacks for some classes of objects,
functions and programs.
Decoder.objectof(), Decoder.functionof(),
Decoder.objectof()
This is the interface for iterator objects. They implement an interface to a collection or stream of data items and a cursor that can be used to iterate over and examine individual items in the data set.
Iterators are typically created to access a data set in some
specific object, array, mapping, multiset or string. An object can
have several iterators that access different data sets in it, or
the same in different ways. E.g. strings have both an iterator for
access char-by-char (String.Iterator), and another for access
over splitted substrings (String.SplitIterator).
lfun::_get_iterator may be defined in an object to get an
instance of the canonical iterator type for it. It's used by e.g.
foreach to iterate over objects conveniently.
It's not an error to advance an iterator past the beginning or end
of the data set; _iterator_index and _iterator_value will
just return UNDEFINED then. An iterator in that state
need not keep track of positions, so it's undefined what happens
if it's "moved back" into the set of items.
Backward movement for iterators is currently not supported.
predef::get_iterator, lfun::_get_iterator,
Array.Iterator, Mapping.Iterator, Multiset.Iterator,
String.Iterator, String.SplitIterator, 8.0::Iterator.
optional protected mixed _iterator_index()
Returns the current index, or UNDEFINED if the iterator
doesn't point to any item.
If there's no obvious index set then the index is the current
position in the data set, counting from 0 (zero).
_iterator_value(), lfun::_iterator_index(),
iterator_index()
protected mixed _iterator_next()
This function advances the iterator one step.
This is the only function that is required in the Pike 9.0 and later iterator API. Presence of this function indicates that the iterator implements the Pike 9.0 API.
Returns UNDEFINED if there are no more values in the set
of elements. If [_iterator_value()] is implemented, 0
(zero) may also be returned if there are no more values. Any other
value may be returned if it succeeded in advancing to a new element.
The returned value is used as the result for _iterator_index()
and _iterator_value() if they are not implemented.
_iterator_prev(), lfun::_iterator_next(), iterator_next(),
_iterator_index(), _iterator_value()
optional protected mixed _iterator_prev()
This function advances the iterator one step backwards.
Returns UNDEFINED if there are no more values in the set
of elements. It may return any other value if it succeeded in
advancing to the previous element. The returned value may be used
as the result for _iterator_index() and _iterator_value() if
they are not implemented.
_iterator_next(), lfun::_iterator_prev(), iterator_prev(),
_iterator_index(), _iterator_value()
optional protected mixed _iterator_value()
Returns the current value, or UNDEFINED if the iterator
doesn't point to any item.
_iterator_index(), lfun::_iterator_value(),
iterator_value()
void random( Iterator arg )
If this function is defined then it sets the iterator to point
to before a random item in the accessible set. The random
distribution should be rectangular within that set, and the
pseudorandom sequence provided by random should be used.
random()
int sizeof( Iterator arg )
Returns the total number of items in the data set according to this iterator. If the size of the data set is unlimited or unknown then this function shouldn't be defined.
Iterator res = Iterator() + steps
Returns a clone of this iterator which is advanced the specified number of steps. The amount may be negative to move backwards.
If the iterator doesn't support backward movement it should throw an exception in that case.
_iterator_next, `-
Iterator res = Iterator() - steps
Returns a clone of this iterator which is backed up the specified number of steps. The amount may be negative to move forward.
_iterator_next, `+,
Iterator Iterator(void|mixed data)
Initialize this iterator to access a data set in data. The
type of data is specific to the iterator implementation. An
iterator may also access some implicit data set, in which case
data isn't specified at all.
The iterator initially points to before the first item in the data set, if there is any.
The iterator does not need to support being reused, so this
function is typically declared protected.
In the iterator API in Pike 8.0 and earlier the iterators initially pointed to the first element.
CompatIterator
optional bool first()
If this function is defined then it resets the iterator to point to before the first item.
Returns zero if there are no items at all in the data set, one otherwise.
It's not enough to set the iterator to the earliest accessible item. If the iterator doesn't support backing up to the original start position then this function should not be implemented.
optional void set_index(zero index)
If this function is defined it should set the iterator at the specified index.
It should be possible to set the index at the end of the iterator.
Wrapper for iterators implementing the Pike 8.0 and
earlier iterator API (8.0::Iterator). Used transparently by
predef::get_iterator() to provide an iterator suitable
for foreach().
This class provides only those functions that are required by the iterator API. It does not proxy any other functions.
get_iterator(), 8.0::Iterator
inherit Iterator : Iterator
Iterator.CompatIterator Iterator.CompatIterator(Iterator old_style_iterator)
Master control program for Pike.
predef::master(), predef::replace_master()
inherit Codec : Codec
inherit CompatResolver : CompatResolver
inherit CompilationHandler : CompilationHandler
The master object acts as fallback compilation handler for
compile() and cpp().
protected inherit Pike_9_0_master : Pike_9_0_master
Namespaces for compat masters.
This inherit is used to provide compatibility namespaces
for get_compat_master().
get_compat_master()
inherit Builtin.__master : __master
constant int MasterObject.bt_max_string_len
This constant contains the maximum length of a function entry in a backtrace. Defaults to 200 if no BT_MAX_STRING_LEN define has been given.
constant int MasterObject.out_of_date_warning
Should Pike complain about out of date compiled files. 1 means yes and 0 means no. Controlled by the OUT_OF_DATE_WARNING define.
program MasterObject.Decoder
This program in the master is cloned and used as codec by
decode_value if it wasn't given any codec. An instance is only
created on-demand the first time decode_value encounters
something for which it needs a codec, i.e. the result of a call to
Pike.Encoder.nameof.
Decoder, Pike.Decoder
program MasterObject.Encoder
This program in the master is cloned and used as codec by
encode_value if it wasn't given any codec. An instance is only
created on-demand the first time encode_value encounters
something for which it needs a codec, i.e. an object, program, or
function.
Encoder, Pike.Encoder
string MasterObject._pike_file_name
string MasterObject._master_file_name
These are useful if you want to start other Pike processes with the same options as this one was started with.
string MasterObject.cflags
Flags suitable for use when compiling Pike C modules
int MasterObject.compat_major
Major pike version to emulate.
This is typically set via the option "-V".
compat_minor
int MasterObject.compat_minor
Minor pike version to emulate.
This is typically set via the option "-V".
compat_major
Version MasterObject.currentversion
Version information about the current Pike version.
string MasterObject.doc_prefix
Prefix for autodoc files.
mapping(string:program|NoValue) MasterObject.programs
mapping(program:object) MasterObject.documentation
mapping(program:string) MasterObject.source_cache
Mapping containing the cache of currently compiled files.
This mapping currently has the following structure:
|
The filename path separator is / on both NT and UNIX.
Special cases: The current master program is available under the
name "/master", and the program containing the main
function under "/main".
string MasterObject.include_prefix
Prefix for Pike-related C header files.
int MasterObject.is_pike_master
This integer variable should exist in any object that aspires to be the master. It gets set to 1 when the master is installed, and is therefore set in any object that is or has been the master. That makes the Encoder class encode references to the master and all ex-masters as references to the current master object.
string MasterObject.ldflags
Flags suitable for use when linking Pike C modules
int MasterObject.no_precompile
Turn off loading of precompiled modules.
int MasterObject.show_if_constant_errors
Show compilation warnings from compilation of cpp()
#if constant() expressions.
This is typically set via the option "--picky-cpp".
int MasterObject.want_warnings
If not zero compilation warnings will be written out on stderr.
void _main(array(string(8bit)) orig_argv)
This function is called when all the driver is done with all setup of modules, efuns, tables etc. etc. and is ready to start executing _real_ programs. It receives the arguments not meant for the driver.
Filesystem.Base|zero add_filesystem_handler(string mountpoint, Filesystem.Base|zero filesystem)
Mount a filesystem handler to be used by the resolver. On its own does
nothing, but may be used with add_module_path() and friends to enable
modules to be loaded from Filesystem objects.
mountpointThe location in the filesystem to mount the handler
filesystemA filesystem object that will handle requests for the given mountpoint.
master()->add_filesystem_handler("/foo/bar.zip", Filesystem.Zip("/foo/bar.zip")); master()->add_module_path("/foo/bar.zip/lib");
find_handler_for_path()
bool asyncp()
Returns 1 if we're in async-mode, e.g. if the main method has returned a negative number.
object backend_thread()
The backend_thread() function is useful to determine if you are the backend thread - important when doing async/sync protocols. This method is only available if thread_create is present.
object cast_to_object(string oname, string current_file, CompilationHandler|void current_handler)
This function is called when the drivers wants to cast a string to an object because of an implict or explicit cast. This function may also receive more arguments in the future.
object cast_to_object(string str, string|void current_file)
Called by the Pike runtime to cast strings to objects.
strString to cast to object.
current_fileFilename of the file that attempts to perform the cast.
Returns the resulting object.
cast_to_program()
program cast_to_program(string pname, string current_file, CompilationHandler|void handler)
This function is called when the driver wants to cast a string to a program, this might be because of an explicit cast, an inherit or a implict cast. In the future it might receive more arguments, to aid the master finding the right program.
program cast_to_program(string str, string|void current_file)
Called by the Pike runtime to cast strings to programs.
strString to cast to object.
current_fileFilename of the file that attempts to perform the cast.
Returns the resulting program.
cast_to_object()
void compile_error(string file, int line, string err)
This function is called whenever a compile error occurs. line
is zero for errors that aren't associated with any specific line.
err is not newline terminated.
compile_warning(), compile_exception(),
get_inhibit_compile_errors(), set_inhibit_compile_errors(),
int compile_exception(array|object trace)
This function is called when an exception is caught during
compilation. Its message is also reported to compile_error if
this function returns zero.
compile_error(), compile_warning(),
get_inhibit_compile_errors(), set_inhibit_compile_errors(),
void compile_warning(string file, int line, string err)
This function is called whenever a compile warning occurs. line
is zero for warnings that aren't associated with any specific
line. err is not newline terminated.
compile_error(), compile_exception(),
get_inhibit_compile_errors(), set_inhibit_compile_errors(),
string decode_charset(string data, string charset)
This function is called by cpp() when it wants to do character code conversion.
string decode_charset(string raw, string charset)
Convert raw from encoding charset to UNICODE.
This function is called by cpp() when it encounters
#charset directives.
rawString to convert.
charsetName of encoding that raw uses.
raw decoded to UNICODE, or 0 (zero) if the decoding failed.
Charset
string describe_backtrace(mixed exception)
Called by various routines to format a readable description of an exception.
exceptionSomething that was thrown. Usually an Error.Generic object, or
an array with the following content:
| Array | |
| Error message. |
| Backtrace to the point where the exception occurred. |
Returns a string describing the exeception.
Usually added by the initialization code the global name space
with add_constant().
predef::describe_backtrace()
string|zero describe_function(function(:void) f)
Function called by describe_backtrace() to describe
functions in the backtrace.
string describe_module(object|program mod, array(object)|void ret_obj)
Describe the path to the module mod.
modIf mod is a program, attempt to describe the path
to a clone of mod.
ret_objIf an instance of mod is found, it will be returned
by changing element 0 of ret_obj.
The a description of the path.
The returned description will end with a proper indexing method
currently either "." or "->".
string|zero describe_object(object o)
Function called by sprintf("%O") for objects that don't
have an lfun::_sprintf(), or have one that returns UNDEFINED.
string|zero describe_program(program|function(:void) p)
Function called by sprintf("%O") for programs.
void enable_source_cache()
Enable caching of sources from compile_string()
string fc_reverse_lookup(object obj)
Returns the path for obj in fc, if it got any.
string|zero find_handler_for_path(string file)
Return the mountpoint for the filesystem handler handling the
file (if any).
add_filesystem_handler()
object get_compat_master(int major, int minor)
Return a master object compatible with the specified version of Pike.
This function is used to implement the various compatibility versions
of master().
get_compilation_handler(), master()
CompilationHandler get_compilation_handler(int major, int minor)
Get compilation handler for simulation of Pike vmajor.minor.
This function is called by cpp() when it encounters
#pike directives.
majorMajor version.
minorMinor version.
Returns a compilation handler for Pike >= major.minor.
bool|CompilationHandler|function(string, int, string:void) get_inhibit_compile_errors()
Get the current compile error, warning and exception behaviour.
See set_inhibit_compile_errors() for details.
set_inhibit_compile_errors()
int get_precompiled_mtime(string id)
Given an identifier returned by query_precompiled_names, returns the mtime of the precompiled entry. Returns -1 if there is no entry.
optional bool handle_attribute(mixed value, string attribute)
This function is called in runtime check_types mode (-rt), when encountering a soft cast to an attributed type.
valueValue that is about to receive the attribute.
attributeType attribute to validate.
Returns one of:
| If the attribute is valid for the value. |
| If the attribute is not valid for the value. |
| If the attribute is unsupported. |
The default master implements validation of the "utf8"
attribute.
void handle_error(mixed exception)
Called by the Pike runtime if an exception isn't caught.
exceptionValue that was throw()'n.
describe_backtrace()
void handle_error(array|object trace)
This function is called when an error occurs that is not caught with catch().
program handle_inherit(string pname, string current_file, CompilationHandler|void handler)
This function is called whenever a inherit is called for. It is supposed to return the program to inherit. The first argument is the argument given to inherit, and the second is the file name of the program currently compiling. Note that the file name can be changed with #line, or set by compile_string, so it can not be 100% trusted to be a filename. previous_object(), can be virtually anything in this function, as it is called from the compiler.
string|zero master_read_file(string file)
Read a file from the master filesystem.
The master filesystem defaults to the system filesystem,
but additional mountpoints may be added via
add_filesystem_handler().
All file I/O performed by the MasterObject is performed
via this function and its related functions.
add_filesystem_handler(), find_handler_for_path(),
master_get_dir(), master_file_stat()
array(string) module_defined(object|program mod)
Find the files in which mod is defined, as they may be hidden away in
joinnodes and dirnodes
modThe module we are looking for.
An array of strings with filenames. (one for each file in a joinnode, or just one otherwise)
program objects_reverse_lookup(object obj)
Returns the program for obj, if known to the master.
string program_path_to_name(string path, string|void module_prefix, string|void module_suffix, string|void object_suffix)
Converts a module path on the form "Foo.pmod/Bar.pmod" or
"/path/to/pike/lib/modules/Foo.pmod/Bar.pmod" to a module
identifier on the form "Foo.Bar".
If module_prefix or module_suffix are given, they are
prepended and appended, respectively, to the returned string if
it's a module file (i.e. ends with ".pmod" or
".so"). If object_suffix is given, it's appended to the
returned string if it's an object file (i.e. ends with
".pike").
string programs_reverse_lookup(program prog)
Returns the path for prog in programs, if it got any.
array(string) query_precompiled_names(string fname)
Returns identifiers (e.g. file names) of potentially precompiled files in priority order.
string read_precompiled(string id)
Given an identifier returned by query_precompiled_names, returns the precompiled entry. Can assume the entry exists.
void runtime_warning(string subsystem, string msg, mixed|void data)
Called by the Pike runtime to warn about data inconsistencies.
subsystemRuntime subsystem where the warning was generated. Currently the following subsystems may call this function:
| The garbage collector. |
| The runtime itself. |
msgWarning message.
dataOptional data that further describes the warning specified by msg.
Currently the following subsystems and messages are defined:
| subsystem | message | data |
"gc" | "bad_cycle" | array cycle |
A cycle where the destruction order isn't deterministic was detected by the garbage collector. cycle is an array of the elements in the cycle. | ||
"runtime" | "unsupported_compat" | Version
requested_version |
Compatibility with a version older than the oldest supported version was requested. requested_version is the requested version. | ||
void runtime_warning(string where, string what, mixed ... args)
Called for every runtime warning. The first argument identifies where the warning comes from, the second identifies the specific message, and the rest depends on that. See code below for currently implemented warnings.
void set_inhibit_compile_errors(bool|CompilationHandler|function(string, int, string:void) behaviour)
Set the compile error, warning and exception behaviour.
behaviourThe desired behaviour. One of:
| Output compilation errors and warnings to stderr. This is the default behaviour. |
| Inhibit output of compilator diagnostics. |
| Function to call for compilation errors. Compilation warnings and exceptions are inhibited. The function will be called with the same arguments
as those passed to |
| Compilation handler to use for diagnostics. |
Note that the behaviour is thread local, and is not copied to new threads when they are created.
get_inhibit_compile_errors()
object show_doc(program|object|function(:void) obj)
Show documentation for the item obj
objThe object for which the documentation should be shown
an AutoDoc object
void thread_quanta_exceeded(Thread.Thread thread, int ns)
Function called when a thread has exceeded the thread quanta.
threadThread that exceeded the thread quanta.
nsNumber of nanoseconds that the thread executed before allowing other threads to run.
The default master prints a diagnostic and the thread backtrace
to Stdio.stderr.
This function runs in a signal handler context, and should thus avoid handling of mutexes, etc.
get_thread_quanta(), set_thread_quanta()
void unregister(program p)
Unregister a program that was only partially compiled.
Called by compile() to clean up references to partially compiled
programs.
pPartially compiled program that should no longer be referenced.
Shouldn't this function be in the compilation handler?
void zap_all_caches()
Called by the runtime in clean up on exit mode in order to get a reasonable destruction order.
Encoder and Decoder rolled into one. This is for mainly
compatibility; there's typically no use combining encoding and
decoding into the same object.
inherit Decoder : Decoder
inherit Encoder : Encoder
MasterObject.Codec MasterObject.Codec(void|mixed encoded)
The optional argument is the thing to encode; it's passed on to
Encoder.
Resolver of symbols not located in the program being compiled.
CompatResolver MasterObject.CompatResolver.fallback_resolver
If we fail to resolv, try the fallback.
Typical configuration:
0.6->7.0->7.2-> ... ->master
mapping(CompilationHandler:joinnode) MasterObject.CompatResolver.handler_root_modules
Lookup from handler module to corresponding root_module.
array(string) MasterObject.CompatResolver.pike_include_path
The complete include search path
array(string) MasterObject.CompatResolver.pike_module_path
The complete module search path
array(string) MasterObject.CompatResolver.pike_program_path
The complete program search path
joinnode MasterObject.CompatResolver.root_module
Join node of the root modules for this resolver.
array(string) MasterObject.CompatResolver.system_module_path
The pike system module path, not including any set by the user.
void add_include_path(string tmp)
Add a directory to search for include files.
This is the same as the command line option -I.
Note that the added directory will only be searched when using < > to quote the included file.
remove_include_path()
void add_module_path(string path, string|void subpath)
Add a directory to search for modules.
This is the same as the command line option -M.
remove_module_path()
patha string containing a path to search for Pike modules. May be a directory, or a path to a ZIP archive. If a ZIP archive path is provided, modules will be loaded from a directory, "modules" within the ZIP archive (see the subpath argument).
subpathif path is a ZIP archive, this argument will determine the path within the archive to be searched.
void add_predefine(string name, mixed value)
Add a define (without arguments) which will be implicitly
defined in cpp calls.
void add_program_path(string tmp)
Add a directory to search for programs.
This is the same as the command line option -P.
remove_program_path()
MasterObject.CompatResolver MasterObject.CompatResolver(mixed version, CompatResolver|void fallback_resolver)
The CompatResolver is initialized with a value that can be casted into a "%d.%d" string, e.g. a version object.
It can also optionally be initialized with a fallback resolver.
mapping get_default_module()
Return the default module for the CompatResolver.
This is the mapping that corresponds to the predef::
name space for the compatibility level, and is the
value returned by all_constants() for the same.
mapping get_predefines()
Returns a mapping with the current predefines.
string|zero handle_include(string f, string current_file, int local_include)
This function is called whenever an #include directive is encountered. It receives the argument for #include and should return the file name of the file to include.
Returns a path suitable for read_include() if the file was
found and 0 if it was not found.
read_include()
protected mapping(string:mixed) instantiate_static_modules(object|mapping static_modules)
Instantiate static modules in the same way that dynamic modules are instantiated.
string read_include(string f)
Read the file specified by handle_include().
handle_include()
void remove_include_path(string tmp)
Remove a directory to search for include files.
This function performs the reverse operation of add_include_path().
add_include_path()
void remove_module_path(string tmp)
Remove a directory to search for modules.
This function performs the reverse operation of add_module_path().
add_module_path()
void remove_predefine(string name)
Remove a define from the set that are implicitly defined in
cpp calls.
void remove_program_path(string tmp)
Remove a directory to search for programs.
This function performs the reverse operation of add_program_path().
add_program_path()
mixed resolv(string identifier, string|void current_file, CompilationHandler|void current_handler, CompilationHandler|void current_compat_handler)
Resolve the identifier expression.
Returns the value of the identifier if it exists,
and UNDEFINED otherwise.
mixed resolv_base(string identifier, string|void current_file, CompilationHandler|void current_handler, CompilationHandler|void current_compat_handler)
Look up identifier in the root module.
mixed resolv_or_error(string identifier, string|void current_file, void|CompilationHandler current_handler)
Same as resolv, but throws an error instead of returning
UNDEFINED if the resolv failed.
Codec for use with decode_value. This is the decoder
corresponding to Encoder. See that one for more details.
fnameName of file being decoded.
placeholderMake a singleton object of the program being decoded. One of:
| Do not make an object. |
| Object to alter into the singleton.
MUST be a clone of |
| Old API: Generate a singleton object. |
handlerHandler object to use.
void|string MasterObject.Decoder.fname
void|__deprecated__(int)|object MasterObject.Decoder.placeholder
void|CompilationHandler MasterObject.Decoder.handler
protected local void __create__(void|string fname, void|__deprecated__(int)|object placeholder, void|CompilationHandler handler)
MasterObject.Decoder MasterObject.Decoder(void|string fname, void|__deprecated__(int)|object placeholder, void|CompilationHandler handler)
array(mixed)|zero decode_object(object o, mixed data)
Restore the state of an encoded object.
oObject to modify.
dataState information from Encoder()->encode_object().
The default implementation calls o->_decode(data)
if the object has an _decode(), otherwise if
data is an array, returns it to indicate that lfun::create()
should be called.
This function is called before lfun::create()
in the object has been called, but after lfun::__INIT()
has been called.
Returns an array to indicate to the caller that
lfun::create() should be called with the elements
of the array as arguments.
Returns 0 (zero) to inhibit calling of lfun::create().
Encoder()->encode_object()
Class used by describe_backtrace() to describe values in backtraces.
inherit _static_modules.Builtin.DestructImmediate : DestructImmediate
Codec for use with encode_value. It understands all the
standard references to builtin functions, pike modules, and the
main program script.
The format of the produced identifiers are documented here to allow extension of this class:
The produced names are either strings or arrays. The string variant specifies the thing to look up according to the first character:
'c' Look up in all_constants(). 's' Look up in _static_modules. 'r' Look up with resolv(). 'p' Look up in programs. 'o' Look up in programs, then look up the result in objects. 'f' Look up in fc.
In the array format, the first element is a string as above and the rest specify a series of things to do with the result:
A string Look up this string in the result. 'm' Get module object in dirnode. 'p' Do object_program(result).
All lowercase letters and the symbols ':', '/' and '.' are reserved for internal use in both cases where characters are used above.
MasterObject.Encoder MasterObject.Encoder(void|mixed encoded)
Creates an encoder instance. If encoded is specified, it's
encoded instead of being reverse resolved to a name. That's
necessary to encode programs.
string|array nameof(mixed what, void|array(object) module_object)
When module_object is set and the name would end with an
object_program step (i.e. 'p'), then drop that
step so that the name corresponds to the object instead.
will receive the found object.module_object[0]
Pike 7.8 master compatibility interface.
Most of the interface is implemented via mixin, or overloading by more recent masters.
This interface is used for compatibility with Pike 7.8.
Replaced by predef::MasterObject.
get_compat_master(), master(), predef::MasterObject
Pike 8.0 master compatibility interface.
Most of the interface is implemented via mixin, or overloading by more recent masters.
This interface is used for compatibility with Pike 8.0.
Replaced by predef::MasterObject.
get_compat_master(), master(), predef::MasterObject
inherit Pike_7_8_master : Pike_7_8_master
Pike 9.0 master compatibility interface.
Most of the interface is implemented via mixin, or overloading by more recent masters.
This interface is used for compatibility with Pike 9.0.
Replaced by predef::MasterObject.
get_compat_master(), master(), predef::MasterObject
inherit Pike_8_0_master : Pike_8_0_master
Contains version information about a Pike version.
int MasterObject.Version.major
int MasterObject.Version.minor
The major and minor parts of the version.
int res = MasterObject.Version() < v
int res = MasterObject.Version() > v
int res = MasterObject.Version() == v
int hash_value( MasterObject.Version arg )
Methods define so that version objects can be compared and ordered.
(int)MasterObject.Version()
(float)MasterObject.Version()
(string)MasterObject.Version()
(array)MasterObject.Version()
(mapping)MasterObject.Version()
(multiset)MasterObject.Version()
The version object can be casted into a string.
MasterObject.Version MasterObject.Version(int major, int minor)
Set the version in the object.
Module node representing a single directory.
joinnode
string MasterObject.dirnode.dirname
CompilationHandler|void MasterObject.dirnode.compilation_handler
string|void MasterObject.dirnode.name
protected local void __create__(string dirname, CompilationHandler|void compilation_handler, string|void name)
Module node holding possibly multiple directories, and optionally falling back to another level.
dirnode
array(object|mapping) MasterObject.joinnode.joined_modules
CompilationHandler|void MasterObject.joinnode.compilation_handler
joinnode|mapping(mixed:int(0))|void MasterObject.joinnode.fallback_module
string|void MasterObject.joinnode.name
protected local void __create__(array(object|mapping) joined_modules, CompilationHandler|void compilation_handler, joinnode|mapping(mixed:int(0))|void fallback_module, string|void name)
array random(mapping m)
Returns a random index-value pair from the mapping.
| Array | |
| The index of the mapping entry. |
| The value f the mapping entry. |
Throws an exception if the mapping is empty.
float random(float max)
This function returns a random number in the range
0 .. .max-É›
Random
int random(int max)
This function returns a random number in the range
0 .. .max-1
Random
mixed random(object o)
If random is called with an object, lfun::_random will be
called in the object.
Throws an exception if the object doesn't have a _random method.
lfun::_random()
mixed random(array|multiset x)
Returns a random element from x.
Throws an exception if the array or multiset is empty.
string(8bit) random_string(int(0..))
Prototype for the randomness generating function.
Override this symbol to implement a usable class.
inherit RandomInterface : RandomInterface
string(8bit) random_string(int(0..) len)
Return a string of random data from the system randomness pool.
On POSIX platforms this reads random data from /dev/urandom on other platforms it may use other methods.
May throw errors on unexpected state.
API for reporting parse errors and similar.
void report(SeverityLevel severity, string filename, int(0..) linenumber, string subsystem, string message, mixed ... extra_args)
Report a diagnostic from the compiler.
severityThe severity of the diagnostic.
filenamelinenumberLocation which triggered the diagnostic.
linenumber 0 (zero) indicates that it is
not applicable (typically originating from command
line arguments or similar).
subsystemCompiler subsystem that generated the diagnostic.
messagesprintf()-style formatting string with the diagnostic message.
extra_argsExtra arguments to sprintf().
The default implementation does the following:
If there's a MasterObject()->report(), call it
with the same arguments as ourselves.
Otherwise depending on severity:
| Ignored. |
| Calls |
| Calls |
|
If there's no master object yet, the diagnostic is UTF8-encoded
and output to Stdio.stderr.
In Pike 7.8 and earlier MasterObject()->report() was not called.
In Pike 8.0 the fallback output was not UTF8-encoded.
PikeCompiler()->report()
Message severity level. { NOTICE, WARNING, ERROR, FATAL }
report()
constant Reporter.NOTICE
constant Reporter.WARNING
constant Reporter.ERROR
constant Reporter.FATAL
inherit MasterObject.dirnode : dirnode
inherit MasterObject.joinnode : joinnode
mapping(string:array(array(Parser.C.Token))) parse(array(Parser.C.Token) tokens)
Returns a mapping from symbol to a tuple of return type and parameters.
array(string) mklibpike.C_Include_Handler.search_path
protected local void __create__(array(string) search_path)
mklibpike.C_Include_Handler mklibpike.C_Include_Handler(array(string) search_path)
int res = string_assignment()[ i ]
String index operator.
string_assignment()[ i ] = j
String assign index operator.
Argument parsing module
This module supports two rather different methods of argument parsing. The first is suitable quick argument parsing without much in the way of checking:
int main( int c, array(string) argv )
{
mapping arguments = Arg.parse(argv);
array files = arguments[Arg.REST];
if( arguments->help ) print_help();
...
}
The Arg.parse method will return a mapping from argument name
to the argument value, if any.
Non-option arguments will be placed in the index Arg.REST
The second way to use this module is to inherit the Options class and add supported arguments.
class MyArguments {
inherit Arg.Options;
string help_pre = "Usage: somecommand";
Opt verbose = NoOpt("-v")|NoOpt("--verbose");
string verbose_help = "Turn on verbose output";
Opt help = MaybeOpt("--help");
Opt output = HasOpt("--output")|HasOpt("-o");
string output_help = "Determine where output goes to";
string help_post = "Command aborted";
};
Then, in main:
MyArguments args = MyArguments(argv);See the documentation for OptLibrary for details about the various
Opt classes.
constant Arg.APP
Constant used to represent the name of the application from the
command line. Can be used when indexing an Options object.
constant Arg.PATH
Constant used to represent the full path of the application from
the command line. Can be used when indexing an Options object.
constant Arg.REST
Constant used to represent command line arguments not identified
as options. Can be used both in the response mapping from parse
and when indexing an Options object.
mapping(string:string|int(1..)) parse(array(string) argv)
Convenience function for simple argument parsing.
Handles the most common cases.
The return value is a mapping from option name to the option value.
The special index Arg.REST will be set to the remaining arguments after all options have been parsed.
The following argument syntaxes are supported:
--foo -> "foo":1
--foo=bar -> "foo":"bar"
-bar -> "b":1,"a":1,"r":1
-bar=foo -> "b":1,"a":1,"r":"foo" (?)
--foo --bar -> "foo":1,"bar":1
--foo - --bar -> "foo":1
--foo x --bar -> "foo":1 (?)
-foo -> "f":1,"o":2
-x -x -x -> "x":3
void main(int n, array argv) { mapping opts = Arg.parse(argv); argv = opts[Arg.REST]; if( opts->help ) /*... */ }
protected inherit OptLibrary : OptLibrary
protected string Arg.LowOptions.application
protected array(string) Arg.LowOptions.argv
protected mapping(string:Opt) Arg.LowOptions.opts
protected mapping(string:int(1)|string) Arg.LowOptions.values
(int)Arg.LowOptions()
(float)Arg.LowOptions()
(string)Arg.LowOptions()
(array)Arg.LowOptions()
(mapping)Arg.LowOptions()
(multiset)Arg.LowOptions()
Arg.LowOptions Arg.LowOptions(array(string) _argv, void|mapping(string:string) env)
protected bool unhandled_argument(array(string) argv, mapping(string:string) env)
This class contains a library of parser for different type of options.
Default value for a setting.
Opt output = HasOpt("-o")|Default("a.out");
inherit Opt : Opt
Environment fallback for an option. Can of course be used as only Opt source.
Opt debug = NoOpt("--debug")|Env("MY_DEBUG");
inherit Opt : Opt
Parses an option that has a parameter. --foo=bar, -x
bar and -x=bar will set the variable to bar.
Opt user = HasOpt("--user")|HasOpt("-u");
inherit NoOpt : NoOpt
Wrapper class that converts the option argument to an integer.
Opt foo = Int(HasOpt("--foo")|Default(4711));
inherit Opt : Opt
Opt Arg.OptLibrary.Int.opt
protected local void __create__(Opt opt)
Arg.OptLibrary.Int Arg.OptLibrary.Int(Opt opt)
Parses an option that may have a parameter. --foo,
-x and x in a sequence like -axb will set the
variable to 1. --foo=bar, -x bar and
-x=bar will set the variable to bar.
Opt debug = MaybeOpt("--debug");
inherit NoOpt : NoOpt
Wrapper class that allows multiple instances of an option.
Opt filter = Multiple(HasOpt("--filter"));
inherit Opt : Opt
Opt Arg.OptLibrary.Multiple.opt
protected local void __create__(Opt opt)
Arg.OptLibrary.Multiple Arg.OptLibrary.Multiple(Opt opt)
Parses an option without parameter, such as --help, -x or "x" from -axb.
Opt verbose = NoOpt("-v")|NoOpt("--verbose");
inherit Opt : Opt
Base class for parsing an argument. Inherit this class to create custom made option types.
protected string __sprintf()
This function will be called by _sprintf, which
handles formatting of chaining between objects.
array(string) get_opts()
Should return a list of options that are parsed. To properly
chain argument parsers, return your_opts +
::get_opts().
mixed get_value(array(string) argv, mapping(string:string) env, mixed previous)
The overloading method should calculate the value of the
option and return it. Methods processing argv should only
look at argv[0] and if it matches, set it to 0. Returning
UNDEFINED means the option was not set (or
matched). To properly chain arguments parsers, return
::get_value(argv, env, previous) instead of
UNDEFINED, unless you want to explicitly stop the
chain and not set this option.
The option parser class that contains all the argument objects.
inherit LowOptions : LowOptions
Opt Arg.Options.help
protected string Arg.Options.help_help
Options that trigger help output.
protected bool unhandled_argument(array(string) argv, mapping(string:string) env)
Options parser with a unhandled_argument implementation that parses most common argument formats.
inherit LowOptions : LowOptions
bool unhandled_argument(array(string) argv, mapping(string:string) env)
Handles arguments as described in Arg.parse
Decoder object.
It needs _Ffmpeg.ffmpeg module for real work.
Audio.Codec.decoder Audio.Codec.decoder(string|void codecname, object|void _codec)
Creates decoder object
codecnumSome of supported codec, like _Ffmpeg.CODEC_ID_*
_codecThe low level object will be used for decoder.
By default _Ffmpeg.ffmpeg object will be used.
Until additional library is implemented the second
parameter _codec hasn't effect.
_Ffmpeg.ffmpeg, _Ffmpeg.CODEC_ID_MP2
mapping|int decode(int|void partial)
Decodes audio data
partialOnly one frame will be decoded per call.
If successfull a mapping with decoded data and byte number of used input data is returned, 0 otherwise.
this_program|zero from_file(Audio.Format.ANY file)
Set codec type from file
It uses Audio.Format.ANY's method get_map()
to determine which codec should be used.
fileThe object Audio.Format.ANY.
mapping get_status()
Returns decoder status
Audio data format handling
API remains marked "unstable".
int check_format()
Check if data are correctly formated.
string get_data()
Returns data only.
The operation is destructive. Ie. current data cursor is moved over.
get_frame, get_sample
string get_frame()
Returns frame for current position and moves cursor forward.
The operation is destructive. Ie. current data cursor is moved over.
get_data, get_sample
mapping get_map()
mapping get_sample()
Returns sample for current position and moves cursor forward.
The operation is destructive. Ie. current data cursor is moved over.
get_frame, get_data
this_program read_file(string filename, int|void nocheck)
Reads data from file
read_streamed
this_program read_streamed(string filename, int|void nocheck)
Reads data from stream
Ie. for packetized data source the beggining of data is searched.
read_file
this_program read_string(string data, int|void nocheck)
Reads data from string
A MP3 file parser with ID3 tag support.
inherit .module.ANY : ANY
mapping|int get_frame()
Gets next frame from file
Frame is represented by the following mapping. It contains from parsed frame headers and frame data itself.
([ "bitrate": int "copyright": int(0..1), "data": frame_data, "emphasis": emphasis, "extension": "channels":0, "id":1, "layer":3, "original": int(0..1), "padding": int(0..1), "private": int(0..1), "sampling": int ])
CObj CreateObject(string prog_id)
mapping GetConstants(string typelib)
mapping GetConstants(CObj cobj)
object GetObject(string|void filename, string|void prog_id)
mixed GetTypeInfo(CObj cobj)
protected string _sprintf(int c, mapping opts)
Common Caching implementation
This module serves as a front-end to different kinds of caching systems. It uses two helper objects to actually store data, and to determine expiration policies.
To create a new cache, do Cache.cache( Cache.Storage.Base storage_type, Cache.Policy.Base expiration_policy )
The cache store instances of Cache.Data.
Base stored object for the cache system.
int Cache.Data.atime
last-access time.
float Cache.Data.cost
relative preciousness scale
int Cache.Data.ctime
creation-time
int Cache.Data.etime
expiry-time (if supplied). 0 otherwise
Cache.Data Cache.Data(void|mixed value, void|int expire_time, void|float preciousness)
expire_time is relative and in seconds.
mixed data()
A method in order to allow for lazy computation
int recursive_low_size(mixed whatfor)
Attempts a wild guess of an object's size. It's left here as a common utility. Some classes won't even need it.
int size()
A method in order to allow for lazy computation. Used by some Policy Managers
This module serves as a front-end to different kinds of caching systems. It uses two helper objects to actually store data, and to determine expiration policies. Mechanisms to allow for distributed caching systems will be added in time, or at least that is the plan.
void alookup(string key, function(string, mixed, mixed ... :void) callback, int|float timeout, mixed ... args)
Asynchronously look the cache up. The callback will be given as arguments the key, the value, and then any user-supplied arguments. If the timeout (in seconds) expires before any data could be retrieved, the callback is called anyways, with 0 as value.
void async_cleanup_cache()
Cache.cache Cache.cache(Cache.Storage.Base storage_mgr, Cache.Policy.Base policy_mgr, void|int cleanup_cycle_delay)
Creates a new cache object. Required are a storage manager, and an expiration policy object.
void delete(string key, void|bool hard)
Forcibly removes some key.
If the 'hard' parameter is supplied and true, deleted objects will also
have their lfun::_destruct method called upon removal by some
backends (i.e. memory)
mixed lookup(string key)
Looks in the cache for an element with the given key and, if available, returns it. Returns 0 if the element is not available
void start_cleanup_cycle()
void store(string key, mixed value, void|int max_life, void|float preciousness, void|multiset(string) dependants)
Sets some value in the cache. Notice that the actual set operation might even not happen at all if the set data doesn't make sense. For instance, storing an object or a program in an SQL-based backend will not be done, and no error will be given about the operation not being performed.
Notice that while max_life will most likely be respected (objects will be garbage-collected at pre-determined intervals anyways), the preciousness . is to be seen as advisory only for the garbage collector If some data was stored with the same key, it gets returned. Also notice that max_life is relative and in seconds. dependants are not fully implemented yet. They are implemented after a request by Martin Stjerrholm, and their purpose is to have some weak form of referential integrity. Simply speaking, they are a list of keys which (if present) will be deleted when the stored entry is deleted (either forcibly or not). They must be handled by the storage manager.
void threaded_cleanup_cycle()
Base class for cache expiration policies.
void expire(Cache.Storage.Base storage)
Expire callback.
This function is called to expire parts
of storage.
All Storage.Policy classes must MUST implement this method.
A multiple-policies expiration policy manager.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
inherit Cache.Policy.Base : Base
Cache.Policy.Multiple Cache.Policy.Multiple(Cache.Policy.Base ... policies)
void expire(Cache.Storage.Base storage)
This expire function calls the expire functions in all of the sub-policies in turn.
Null policy-manager for the generic Caching system
This is a policy manager that doesn't actually expire anything. It is useful in multilevel and/or network-based caches.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
inherit Cache.Policy.Base : Base
void expire(Cache.Storage.Base storage)
This is an expire function that does nothing.
An LRU, size-constrained expiration policy manager.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
inherit Cache.Policy.Base : Base
Cache.Policy.Sized Cache.Policy.Sized(int max, void|int min)
void expire(Cache.Storage.Base storage)
An access-time-based expiration policy manager.
inherit Cache.Policy.Base : Base
Base class for cache storage managers.
All Cache.Storage managers must provide these methods.
void aget(string key, function(string, int(0)|Cache.Data, mixed ... :void) callback, mixed ... extra_callback_args)
Fetch some data from the cache asynchronously.
callback() will get as first argument key, and as second
argument 0 (cache miss) or an Cache.Data object, plus any
additional argument that the user may have supplied.
mixed delete(string key, void|bool hard)
Delete the entry specified by key from the cache (if present).
If hard is 1, some backends may force a destruct()
on the deleted value.
Dependants (if present) are automatically deleted.
Returns the deleted entry.
int(0)|string first()
int(0)|string next()
These two functions are an iterator over the cache. There is an
internal cursor, which is reset by each call to first(). Subsequent
calls to next() will iterate over all the contents of the cache.
These functions are not meant to be exported to the user, but are solely for the policy managers' benefit.
int(0)|Cache.Data get(string key, void|bool notouch)
Fetch some data from the cache synchronously.
Be careful, as with some storage managers it might block the calling thread for some time.
void set(string key, mixed value, void|int max_life, void|float preciousness, void|multiset(string) dependants)
Data-object creation is performed here if necessary, or in get()
depending on the backend.
This allows the storage managers to have their own data class implementation.
A GBM-based storage manager.
This storage manager provides the means to save data to memory. In this manager I'll add reference documentation as comments to interfaces. It will be organized later in a more comprehensive format
Settings will be added later.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
inherit Cache.Storage.Base : Base
Cache.Storage.Gdbm Cache.Storage.Gdbm(string path)
A GDBM storage-manager must be hooked to a GDBM Database.
inherit Cache.Data : Data
A RAM-based storage manager.
This storage manager provides the means to save data to memory. In this manager I'll add reference documentation as comments to interfaces. It will be organized later in a more comprehensive format
Settings will be added later.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
inherit Cache.Storage.Base : Base
int(0)|Cache.Data get(string key, void|int notouch)
Fetches some data from the cache. If notouch is set, don't touch the data from the cache (meant to be used by the storage manager only)
inherit Cache.Data : Data
An SQL-based storage manager
This storage manager provides the means to save data to an SQL-based backend.
For now it's mysql only, dialectization will be added at a later time. Serialization should be taken care of by the low-level SQL drivers.
An administrator is supposed to create the database and give the user enough privileges to write to it. It will be care of this driver to create the database tables itself.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
inherit Cache.Storage.Base : Base
Cache.Storage.MySQL Cache.Storage.MySQL(string sql_url)
Database manipulation is done externally. This class only returns values, with some lazy decoding.
inherit Cache.Data : Data
A Yabu-based storage manager.
Settings will be added later.
Thanks to Francesco Chemolli <kinkie@roxen.com> for the contribution.
inherit Cache.Storage.Base : Base
Cache.Storage.Yabu Cache.Storage.Yabu(string path)
inherit Cache.Data : Data
constant int Cairo.ANTIALIAS_BEST
Hint that the backend should render at the highest quality, sacrificing speed if necessary
constant int Cairo.ANTIALIAS_DEFAULT
Use the default antialiasing for the subsystem and target device
constant int Cairo.ANTIALIAS_FAST
Hint that the backend should perform some antialiasing but prefer speed over quality
constant int Cairo.ANTIALIAS_GOOD
The backend should balance quality against performance
constant int Cairo.ANTIALIAS_GRAY
Perform single-color antialiasing (using shades of gray for black text on a white background, for example)
constant int Cairo.ANTIALIAS_NONE
Use a bilevel alpha mask
constant int Cairo.ANTIALIAS_SUBPIXEL
Perform antialiasing by taking advantage of the order of subpixel elements on devices such as LCD panels
constant int Cairo.CAIRO_VERSION
constant int Cairo.CAIRO_VERSION_MAJOR
constant int Cairo.CAIRO_VERSION_MINOR
constant int Cairo.CAIRO_VERSION_MICRO
constant string Cairo.CAIRO_VERSION_STRING
Compile-time version
constant int Cairo.COLOR_MODE_COLOR
Enable rendering color glyphs. If the font contains a color presentation for a glyph, and when supported by the font backend, the glyph will be rendered in color.
constant int Cairo.COLOR_MODE_DEFAULT
Use the default color mode for font backend and target device
constant int Cairo.COLOR_MODE_NO_COLOR
Disable rendering color glyphs. Glyphs are always rendered as outline glyphs.
constant int Cairo.COLOR_PALETTE_DEFAULT
The default color palette index.
constant int Cairo.CONTENT_ALPHA
The surface will hold alpha content only.
constant int Cairo.CONTENT_COLOR
The surface will hold color content only.
constant int Cairo.CONTENT_COLOR_ALPHA
The surface will hold color and alpha content.
constant int Cairo.DITHER_BEST
Best algorithm available in the backend
constant int Cairo.DITHER_DEFAULT
Default choice at cairo compile time. Currently DITHER_NONE.
constant int Cairo.DITHER_FAST
Fastest dithering algorithm supported by the backend
constant int Cairo.DITHER_GOOD
An algorithm with smoother dithering than DITHER_FAST
constant int Cairo.DITHER_NONE
No dithering.
constant int Cairo.EXTEND_NONE
pixels outside of the source pattern are fully transparent
constant int Cairo.EXTEND_PAD
pixels outside of the pattern copy the closest pixel from the source
constant int Cairo.EXTEND_REFLECT
the pattern is tiled by reflecting at the edges
constant int Cairo.EXTEND_REPEAT
the pattern is tiled by repeating
constant int Cairo.FILL_RULE_EVEN_ODD
Counts the total number of intersections, without regard to the orientation of the contour. If the total number of intersections is odd, the point will be filled.
constant int Cairo.FILL_RULE_WINDING
If the path crosses the ray from left-to-right, counts +1. If the path crosses the ray from right to left, counts -1. (Left and right are determined from the perspective of looking along the ray from the starting point.) If the total count is non-zero, the point will be filled.
constant int Cairo.FILTER_BEST
The highest-quality available, performance may not be suitable for interactive use.
constant int Cairo.FILTER_BILINEAR
Linear interpolation in two dimensions
constant int Cairo.FILTER_FAST
A high-performance filter, with quality similar to FILTER_NEAREST
constant int Cairo.FILTER_GAUSSIAN
This filter value is currently unimplemented, and should not be used in current code.
constant int Cairo.FILTER_GOOD
A reasonable-performance filter, with quality similar to
FILTER_BILINEAR
constant int Cairo.FILTER_NEAREST
Nearest-neighbor filtering
constant int Cairo.FONT_SLANT_ITALIC
Italic font style
constant int Cairo.FONT_SLANT_NORMAL
Upright font style
constant int Cairo.FONT_SLANT_OBLIQUE
Oblique font style
constant int Cairo.FONT_WEIGHT_BOLD
Bold font weight
constant int Cairo.FONT_WEIGHT_NORMAL
Normal font weight
constant int Cairo.FORMAT_A1
each pixel is a 1-bit quantity holding an alpha value. Pixels are packed together into 32-bit quantities. The ordering of the bits matches the endianness of the platform. On a big-endian machine, the first pixel is in the uppermost bit, on a little-endian machine the first pixel is in the least-significant bit.
constant int Cairo.FORMAT_A8
each pixel is a 8-bit quantity holding an alpha value.
constant int Cairo.FORMAT_ARGB32
each pixel is a 32-bit quantity, with alpha in the upper 8 bits, then red, then green, then blue. The 32-bit quantities are stored native-endian. Pre-multiplied alpha is used. (That is, 50% transparent red is 0x80800000, not 0x80ff0000.)
constant int Cairo.FORMAT_INVALID
no such format exists or is supported.
constant int Cairo.FORMAT_RGB16_565
each pixel is a 16-bit quantity with red in the upper 5 bits, then green in the middle 6 bits, and blue in the lower 5 bits.
constant int Cairo.FORMAT_RGB24
each pixel is a 32-bit quantity, with the upper 8 bits unused. Red, Green, and Blue are stored in the remaining 24 bits in that order.
constant int Cairo.FORMAT_RGB30
like RGB24 but with 10bpc.
constant int Cairo.FORMAT_RGB96F
3 floats, R, G, B.
constant int Cairo.FORMAT_RGBA128F
4 floats, R, G, B, A.
constant int Cairo.HINT_METRICS_DEFAULT
Hint metrics in the default manner for the font backend and target device
constant int Cairo.HINT_METRICS_OFF
Do not hint font metrics
constant int Cairo.HINT_METRICS_ON
Hint font metrics
constant int Cairo.HINT_STYLE_DEFAULT
Use the default hint style for font backend and target device
constant int Cairo.HINT_STYLE_FULL
Hint outlines to maximize contrast
constant int Cairo.HINT_STYLE_MEDIUM
Hint outlines with medium strength giving a compromise between fidelity to the original shapes and contrast
constant int Cairo.HINT_STYLE_NONE
Do not hint outlines
constant int Cairo.HINT_STYLE_SLIGHT
Hint outlines slightly to improve contrast while retaining good fidelity to the original shapes
constant int Cairo.LINE_CAP_BUTT
start(stop) the line exactly at the start(end) point
constant int Cairo.LINE_CAP_ROUND
use a round ending, the center of the circle is the end point
constant int Cairo.LINE_CAP_SQUARE
use squared ending, the center of the square is the end point
constant int Cairo.LINE_JOIN_BEVEL
use a cut-off join, the join is cut off at half the line width from the joint point
constant int Cairo.LINE_JOIN_MITER
use a sharp (angled) corner, see Context->set_miter_limit()
constant int Cairo.LINE_JOIN_ROUND
use a rounded join, the center of the circle is the joint point
constant string Cairo.MIME_TYPE_CCITT_FAX
Group 3 or Group 4 CCITT facsimile encoding (International Telecommunication Union, Recommendations T.4 and T.6.)
constant string Cairo.MIME_TYPE_CCITT_FAX_PARAMS
Decode parameters for Group 3 or Group 4 CCITT facsimile encoding. See CCITT Fax Images.
constant string Cairo.MIME_TYPE_EPS
Encapsulated PostScript file. Encapsulated PostScript File Format Specification
constant string Cairo.MIME_TYPE_EPS_PARAMS
Embedding parameters Encapsulated PostScript data. See Embedding EPS files.
constant string Cairo.MIME_TYPE_JBIG2
Joint Bi-level Image Experts Group image coding standard (ISO/IEC 11544).
constant string Cairo.MIME_TYPE_JBIG2_GLOBAL
Joint Bi-level Image Experts Group image coding standard (ISO/IEC 11544) global segment.
constant string Cairo.MIME_TYPE_JBIG2_GLOBAL_ID
An unique identifier shared by a JBIG2 global segment and all JBIG2 images that depend on the global segment.
constant string Cairo.MIME_TYPE_JP2
The Joint Photographic Experts Group (JPEG) 2000 image coding standard (ISO/IEC 15444-1).
constant string Cairo.MIME_TYPE_JPEG
The Joint Photographic Experts Group (JPEG) image coding standard (ISO/IEC 10918-1).
constant string Cairo.MIME_TYPE_PNG
The Portable Network Graphics image file format (ISO/IEC 15948).
constant string Cairo.MIME_TYPE_UNIQUE_ID
Unique identifier for a surface (cairo specific MIME type). All surfaces with the same unique identifier will only be embedded once.
constant string Cairo.MIME_TYPE_URI
URI for an image file (unofficial MIME type).
constant int Cairo.OPERATOR_ADD
source and destination layers are accumulated
constant int Cairo.OPERATOR_ATOP
draw source on top of destination content and only there
constant int Cairo.OPERATOR_CLEAR
clear destination layer (bounded)
constant int Cairo.OPERATOR_COLOR_BURN
darkens the destination color to reflect the source color.
constant int Cairo.OPERATOR_COLOR_DODGE
brightens the destination color to reflect the source color.
constant int Cairo.OPERATOR_DARKEN
replaces the destination with the source if it is darker, otherwise keeps the source.
constant int Cairo.OPERATOR_DEST
ignore the source
constant int Cairo.OPERATOR_DEST_ATOP
leave destination on top of source content and only there (unbounded)
constant int Cairo.OPERATOR_DEST_IN
leave destination only where there was source content (unbounded)
constant int Cairo.OPERATOR_DEST_OUT
leave destination only where there was no source content
constant int Cairo.OPERATOR_DEST_OVER
draw destination on top of source
constant int Cairo.OPERATOR_DIFFERENCE
Takes the difference of the source and destination color.
constant int Cairo.OPERATOR_EXCLUSION
Produces an effect similar to difference, but with lower contrast.
constant int Cairo.OPERATOR_HARD_LIGHT
Multiplies or screens, dependent on source color.
constant int Cairo.OPERATOR_HSL_COLOR
Creates a color with the hue and saturation of the source and the luminosity of the target. This preserves the gray levels of the target and is useful for coloring monochrome images or tinting color images.
constant int Cairo.OPERATOR_HSL_HUE
Creates a color with the hue of the source and the saturation and luminosity of the target.
constant int Cairo.OPERATOR_HSL_LUMINOSITY
Creates a color with the luminosity of the source and the hue and
saturation of the target. This produces an inverse effect to
OPERATOR_HSL_COLOR.
constant int Cairo.OPERATOR_HSL_SATURATION
Creates a color with the saturation of the source and the hue and luminosity of the target. Painting with this mode onto a gray area produces no change.
constant int Cairo.OPERATOR_IN
draw source where there was destination content (unbounded)
constant int Cairo.OPERATOR_LIGHTEN
replaces the destination with the source if it is lighter, otherwise keeps the source.
constant int Cairo.OPERATOR_MULTIPLY
source and destination layers are multiplied. This causes the result to be at least as dark as the darker inputs.
constant int Cairo.OPERATOR_OUT
draw source where there was no destination content (unbounded)
constant int Cairo.OPERATOR_OVER
draw source layer on top of destination layer (bounded)
constant int Cairo.OPERATOR_OVERLAY
multiplies or screens, depending on the lightness of the destination color.
constant int Cairo.OPERATOR_SATURATE
like over, but assuming source and dest are disjoint geometries
constant int Cairo.OPERATOR_SCREEN
source and destination are complemented and multiplied. This causes the result to be at least as light as the lighter inputs.
constant int Cairo.OPERATOR_SOFT_LIGHT
Darkens or lightens, dependent on source color.
constant int Cairo.OPERATOR_SOURCE
replace destination layer (bounded)
constant int Cairo.OPERATOR_XOR
source and destination are shown where there is only one of them
constant int Cairo.PATH_CLOSE_PATH
A close-path operation
constant int Cairo.PATH_CURVE_TO
A curve-to operation
constant int Cairo.PATH_LINE_TO
A line-to operation
constant int Cairo.PATH_MOVE_TO
A move-to operation
constant int Cairo.PDF_METADATA_AUTHOR
The document author
constant int Cairo.PDF_METADATA_CREATE_DATE
The document creation date
constant int Cairo.PDF_METADATA_CREATOR
The document creator
constant int Cairo.PDF_METADATA_KEYWORDS
The document keywords
constant int Cairo.PDF_METADATA_MOD_DATE
The document modification date
constant int Cairo.PDF_METADATA_SUBJECT
The document subject
constant int Cairo.PDF_METADATA_TITLE
The document title
constant int Cairo.PDF_OUTLINE_FLAG_BOLD
The outline item is displayed by the viewer in bold text
constant int Cairo.PDF_OUTLINE_FLAG_ITALIC
The outline item is displayed by the viewer in italic text
constant int Cairo.PDF_OUTLINE_FLAG_OPEN
The outline item defaults to open in the PDF viewer
constant int Cairo.PDF_OUTLINE_ROOT
The root outline item in PDFSurface->add_outline().
constant int Cairo.PDF_VERSION_1_4
The version 1.4 of the PDF specification.
constant int Cairo.PDF_VERSION_1_5
The version 1.5 of the PDF specification.
constant int Cairo.PDF_VERSION_1_6
The version 1.6 of the PDF specification.
constant int Cairo.PDF_VERSION_1_7
The version 1.7 of the PDF specification.
constant int Cairo.PS_LEVEL_2
The language level 2 of the PostScript specification.
constant int Cairo.PS_LEVEL_3
The language level 3 of the PostScript specification.
constant int Cairo.SCRIPT_MODE_ASCII
the output will be in readable text (default).
constant int Cairo.SCRIPT_MODE_BINARY
the output will use byte codes.
constant int Cairo.STATUS_CLIP_NOT_REPRESENTABLE
clip region not representable in desired format
constant int Cairo.STATUS_DEVICE_ERROR
an operation to the device caused an unspecified error
constant int Cairo.STATUS_DEVICE_FINISHED
target device has been finished
constant int Cairo.STATUS_DEVICE_TYPE_MISMATCH
the device type is not appropriate for the operation
constant int Cairo.STATUS_DWRITE_ERROR
error occurred in the Windows Direct Write API
constant int Cairo.STATUS_FILE_NOT_FOUND
file not found
constant int Cairo.STATUS_FONT_TYPE_MISMATCH
the font type is not appropriate for the operation
constant int Cairo.STATUS_FREETYPE_ERROR
error occurred in libfreetype
constant int Cairo.STATUS_INVALID_CLUSTERS
input clusters do not represent the accompanying text and glyph array
constant int Cairo.STATUS_INVALID_CONTENT
invalid value for an input content
constant int Cairo.STATUS_INVALID_DASH
invalid value for a dash setting
constant int Cairo.STATUS_INVALID_DSC_COMMENT
invalid value for a DSC comment
constant int Cairo.STATUS_INVALID_FORMAT
invalid value for an input format
constant int Cairo.STATUS_INVALID_INDEX
invalid index passed to getter
constant int Cairo.STATUS_INVALID_MATRIX
invalid matrix (not invertible)
constant int Cairo.STATUS_INVALID_MESH_CONSTRUCTION
a mesh pattern construction operation was used outside of a
MeshPattern->begin_patch()/MeshPattern->end_patch() pair
constant int Cairo.STATUS_INVALID_PATH_DATA
input path data not valid
constant int Cairo.STATUS_INVALID_POP_GROUP
no saved group to pop, i.e. Context->pop_group() without
matching Context->push_group()
constant int Cairo.STATUS_INVALID_RESTORE
Context->restore() called without matching Context->save()
constant int Cairo.STATUS_INVALID_SIZE
invalid value (typically too big) for the size of the input (surface, pattern, etc.)
constant int Cairo.STATUS_INVALID_SLANT
invalid value for an input slant
constant int Cairo.STATUS_INVALID_STATUS
invalid value for an input status
constant int Cairo.STATUS_INVALID_STRIDE
invalid value for stride
constant int Cairo.STATUS_INVALID_STRING
input string not valid UTF-8
constant int Cairo.STATUS_INVALID_VISUAL
invalid value for an input visual
constant int Cairo.STATUS_INVALID_WEIGHT
invalid value for an input weight
constant int Cairo.STATUS_JBIG2_GLOBAL_MISSING
MIME_TYPE_JBIG2_GLOBAL_ID has been used on at least one image
but no image provided MIME_TYPE_JBIG2_GLOBAL
constant int Cairo.STATUS_LAST_STATUS
this is a special value indicating the number of status values defined in this enumeration. When using this value, note that the version of cairo at run-time may have additional status values defined than the value of this symbol at compile-time.
constant int Cairo.STATUS_NEGATIVE_COUNT
negative number used where it is not allowed
constant int Cairo.STATUS_NO_CURRENT_POINT
no current point defined
constant int Cairo.STATUS_NO_MEMORY
out of memory
constant int Cairo.STATUS_NULL_POINTER
NULL pointer
constant int Cairo.STATUS_PATTERN_TYPE_MISMATCH
the pattern type is not appropriate for the operation
constant int Cairo.STATUS_PNG_ERROR
error occurred in libpng while reading from or writing to a PNG file
constant int Cairo.STATUS_READ_ERROR
error while reading from input stream
constant int Cairo.STATUS_SUCCESS
no error has occurred
constant int Cairo.STATUS_SURFACE_FINISHED
target surface has been finished
constant int Cairo.STATUS_SURFACE_TYPE_MISMATCH
the surface type is not appropriate for the operation
constant int Cairo.STATUS_SVG_FONT_ERROR
error occurred in OpenType-SVG font rendering
constant int Cairo.STATUS_TAG_ERROR
invalid tag name, attributes, or nesting
constant int Cairo.STATUS_TEMP_FILE_ERROR
error creating or writing to a temporary file
constant int Cairo.STATUS_USER_FONT_ERROR
error occurred in a user-font callback function
constant int Cairo.STATUS_USER_FONT_IMMUTABLE
the user-font is immutable
constant int Cairo.STATUS_USER_FONT_NOT_IMPLEMENTED
user-font method not implemented
constant int Cairo.STATUS_WIN32_GDI_ERROR
error occurred in the Windows Graphics Device Interface
constant int Cairo.STATUS_WRITE_ERROR
error while writing to output stream
constant int Cairo.SUBPIXEL_ORDER_BGR
Subpixel elements are arranged horizontally with blue at the left
constant int Cairo.SUBPIXEL_ORDER_DEFAULT
Use the default subpixel order for for the target device
constant int Cairo.SUBPIXEL_ORDER_RGB
Subpixel elements are arranged horizontally with red at the left
constant int Cairo.SUBPIXEL_ORDER_VBGR
Subpixel elements are arranged vertically with blue at the top
constant int Cairo.SUBPIXEL_ORDER_VRGB
Subpixel elements are arranged vertically with red at the top
constant int Cairo.SVG_UNIT_CM
Centimeters (1cm = 96px/2.54).
constant int Cairo.SVG_UNIT_EM
The size of the element's font.
constant int Cairo.SVG_UNIT_EX
The x-height of the element’s font.
constant int Cairo.SVG_UNIT_IN
Inches (1in = 2.54cm = 96px).
constant int Cairo.SVG_UNIT_MM
Millimeters (1mm = 1/10th of 1cm).
constant int Cairo.SVG_UNIT_PC
Picas (1pc = 1/6th of 1in).
constant int Cairo.SVG_UNIT_PERCENT
Percent, a value that is some fraction of another reference value.
constant int Cairo.SVG_UNIT_PT
Points (1pt = 1/72th of 1in).
constant int Cairo.SVG_UNIT_PX
Pixels (1px = 1/96th of 1in).
constant int Cairo.SVG_UNIT_USER
User unit, a value in the current coordinate system. If used in the root element for the initial coordinate systems it corresponds to pixels.
constant int Cairo.SVG_VERSION_1_1
The version 1.1 of the SVG specification.
constant int Cairo.SVG_VERSION_1_2
The version 1.2 of the SVG specification.
constant string Cairo.TAG_CONTENT
Create a content tag.
constant string Cairo.TAG_CONTENT_REF
Create a content reference tag.
constant string Cairo.TAG_DEST
Create a destination for a hyperlink.
constant string Cairo.TAG_LINK
Create hyperlink.
constant int Cairo.TEXT_CLUSTER_FLAG_BACKWARD
The clusters in the cluster array map to glyphs in the glyph array from end to start.
int cairo_version()
Returns the version of the cairo library encoded in a single integer
cairo_version_string()
string cairo_version_string()
Returns the version of the cairo library as a human-readable string
cairo_version()
int stride_for_width(int format, int width)
This function provides a stride value that will respect all alignment requirements of the accelerated image-rendering code within cairo.
formatA cairo format
widthThe desired width of an image surface to be created.
the appropriate stride to use given the desired format and width, or -1 if either the format is invalid or the width too large.
The cairo drawing context
void append_path(Path path)
Append the path onto the current path. The path may be either
the return value from one of copy_path() or
copy_path_flat() or it may be constructed manually.
pathpath to be appended
void arc(float|int xc, float|int yc, float|int radius, float angle1, float angle2)
Adds a circular arc of the given radius to the current path. The arc is centered at (xc, yc), begins at angle1 and proceeds in the direction of increasing angles to end at angle2. If angle2 is less than angle1 it will be progressively increased by 2*M_PI until it is greater than angle1.
If there is a current point, an initial line segment will be
added to the path to connect the current point to the beginning
of the arc. If this initial line is undesired, it can be avoided
by calling new_sub_path() before calling arc().
Angles are measured in radians. An angle of 0.0 is in the direction of the positive X axis (in user space). An angle of M_PI/2.0 radians (90 degrees) is in the direction of the positive Y axis (in user space). Angles increase in the direction from the positive X axis toward the positive Y axis. So with the default transformation matrix, angles increase in a clockwise direction.
This function gives the arc in the direction of increasing
angles; see arc_negative() to get the arc in the direction
of decreasing angles.
xcX position of the center of the arc
ycY position of the center of the arc
radiusthe radius of the arc
angle1the start angle, in radians
angle2the end angle, in radians
void arc_negative(float|int xc, float|int yc, float|int radius, float angle1, float angle2)
Adds a circular arc of the given radius to the current path. The arc is centered at (xc, yc), begins at angle1 and proceeds in the direction of decreasing angles to end at angle2. If angle2 is greater than angle1 it will be progressively decreased by 2*M_PI until it is less than angle1.
See arc() for more details. This function differs only in
the direction of the arc between the two angles.
xcX position of the center of the arc
ycY position of the center of the arc
radiusthe radius of the arc
angle1the start angle, in radians
angle2the end angle, in radians
void clip()
Establishes a new clip region by intersecting the current clip
region with the current path as it would be filled by fill()
and according to the current fill rule (see set_fill_rule()).
After clip(), the current path will be cleared from the cairo context.
The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.
Calling clip() can only make the clip region smaller, never
larger. But the current clip is part of the graphics state, so
a temporary restriction of the clip region can be achieved by
calling clip() within a save()/restore() pair. The only
other means of increasing the size of the clip region is
reset_clip().
array(float) clip_extents()
Computes a bounding box in user coordinates covering the area inside the current clip.
an array with coordinates for the left, top, right, and bottom, respectively, of the resulting extents
void clip_preserve()
Establishes a new clip region by intersecting the current clip
region with the current path as it would be filled by fill()
and according to the current fill rule (see set_fill_rule()).
Unlike clip(), clip_preserve() preserves the path within the
cairo context.
The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region.
Calling clip_preserve() can only make the clip region smaller,
never larger. But the current clip is part of the graphics
state, so a temporary restriction of the clip region can be
achieved by calling clip_preserve() within a
save()/restore() pair. The only other means of increasing
the size of the clip region is reset_clip().
void close_path()
Adds a line segment to the path from the current point to the beginning of the current sub-path, (the most recent point passed to move_to()), and closes this sub-path. After this call the current point will be at the joined endpoint of the sub-path.
The behavior of close_path() is distinct from simply calling line_to() with the equivalent coordinate in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of the sub-path. Instead, there is a line join connecting the final and initial segments of the sub-path.
If there is no current point before the call to close_path(), this function will have no effect.
array(Rectangle) copy_clip_rectangle_list()
Gets the current clip region as a list of rectangles in user coordinates.
the current clip region as an array of rectangles in user coordinates.
void copy_page()
Emits the current page for backends that support multiple pages,
but doesn't clear it, so, the contents of the current page will
be retained for the next page too. Use show_page() if you
want to get an empty page after the emission.
This is a convenience function that simply calls
Surface->copy_page() on the context's target.
Path copy_path()
Creates a copy of the current path and returns it to the user as
a Path.
the copy of the current path.
Path copy_path_flat()
Gets a flattened copy of the current path and returns it to the
user as a Path.
This function is like copy_path() except that any curves in
the path will be approximated with piecewise-linear
approximations, (accurate to within the current tolerance
value).
the copy of the current path.
Cairo.Context Cairo.Context(Surface target)
Creates a new context with all graphics state parameters set to default values and with target as a target surface.
targettarget surface for the context
void curve_to(float|int x1, float|int y1, float|int x2, float|int y2, float|int x3, float|int y3)
Adds a cubic Bézier spline to the path from the current point to position (x3, y3) in user-space coordinates, using (x1, y1) and (x2, y2) as the control points. After this call the current point will be (x3, y3).
If there is no current point before the call to curve_to() this function will behave as if preceded by a call to move_to(x1, y1).
x1the X coordinate of the first control point
y1the Y coordinate of the first control point
x2the X coordinate of the second control point
y2the Y coordinate of the second control point
x3the X coordinate of the end of the curve
y3the Y coordinate of the end of the curve
array(float) device_to_user(float|int x, float|int y)
Transform a coordinate from device space to user space by multiplying the given point by the inverse of the current transformation matrix (CTM).
xX value of coordinate
yY value of coordinate
The transformed point
| Array | |
| X position of the new point |
| Y position of the new point |
array(float) device_to_user_distance(float|int dx, float|int dy)
Transform a distance vector from device space to user space.
This function is similar to device_to_user() except that the
translation components of the inverse CTM will be ignored when
transforming (dx, dy).
dxX component of a distance vector (in/out parameter)
dyY component of a distance vector (in/out parameter)
The transformed distance vector
| Array | |
| X component of the new distance vector |
| Y component of the new distance vector |
void fill()
A drawing operator that fills the current path according to the current fill rule, (each sub-path is implicitly closed before being filled). After fill(), the current path will be cleared from the cairo context.
set_fill_rule() and fill_preserve().
array(float) fill_extents()
Computes a bounding box in user coordinates covering the area
that would be affected, (the "inked" area), by a fill()
operation given the current path and fill parameters. If the
current path is empty, returns an empty rectangle ({0, 0, 0,
0}). Surface dimensions and clipping are not taken into
account.
Contrast with path_extents(), which is similar, but returns
non-zero extents for some paths with no inked area, (such as a
simple line segment).
Note that fill_extents() must necessarily do more work to
compute the precise inked areas in light of the fill rule, so
path_extents() may be more desirable for sake of performance
if the non-inked path extents are desired.
an array with coordinates for the left, top, right, and bottom, respectively, of the resulting extents
fill(), set_fill_rule() and fill_preserve().
void fill_preserve()
A drawing operator that fills the current path according to the
current fill rule, (each sub-path is implicitly closed before
being filled). Unlike fill(), fill_preserve() preserves the
path within the cairo context.
set_fill_rule() and fill().
array(float) font_extents()
Gets the font extents for the currently selected font.
an array which stores the retrieved extents:
| Array | |
| ascent: the distance that the font extends above the baseline. Note that this is not always exactly equal to the maximum of the extents of all the glyphs in the font, but rather is picked to express the font designer's intent as to how the font should align with elements above it. |
| descent: the distance that the font extends below the baseline. This value is positive for typical fonts that include portions below the baseline. Note that this is not always exactly equal to the maximum of the extents of all the glyphs in the font, but rather is picked to express the font designer's intent as to how the font should align with elements below it. |
| height: the recommended vertical distance between baselines when setting consecutive lines of text with the font. This is greater than ascent + descent by a quantity known as the line spacing or external leading. When space is at a premium, most fonts can be set with only a distance of ascent + descent between lines. |
| max_x_advance: the maximum distance in the X direction that the origin is advanced for any glyph in the font. |
| max_y_advance: the maximum distance in the Y direction that the origin is advanced for any glyph in the font. This will be zero for normal fonts used for horizontal writing. (The scripts of East Asia are sometimes written vertically.) |
int get_antialias()
Gets the current shape antialiasing mode, as set by
set_antialias().
the current shape antialiasing mode.
array(float) get_current_point()
Gets the current point of the current path, which is conceptually the final point reached by the path so far.
The current point is returned in the user-space coordinate
system. If there is no defined current point or if the context
is in an error status, both returned coordinates will be 0.0.
It is possible to check this in advance with has_current_point().
an array with the current x and y coordinates
array(array(float)|float) get_dash()
Gets the current dash array.
an array with two elements, the first is the dash array, and the second is the current dash offset
int get_dash_count()
This function returns the length of the dash array (0 if dashing is not currently in effect).
the length of the dash array, or 0 if no dash array set.
set_dash() and get_dash().
int get_fill_rule()
Gets the current fill rule, as set by set_fill_rule().
the current fill rule.
FontFace get_font_face()
Gets the current font face for a Context.
the current font face
Matrix get_font_matrix()
Returns the current font matrix. See set_font_matrix().
the matrix
void get_font_options(FontOptions options)
Retrieves font rendering options set via
set_font_options(). Note that the returned options do not
include any options derived from the underlying surface; they
are literally the options passed to set_font_options().
optionsa FontOptions object into which to store the retrieved
options. All existing values are overwritten
Surface get_group_target()
Gets the current destination surface for the context. This is
either the original target surface or the target surface for the
current group as started by the most recent call to
push_group() or push_group_with_content().
the target surface.
bool get_hairline()
Returns whether or not hairline mode is set, as set by
set_hairline().
whether hairline mode is set.
int get_line_cap()
Gets the current line cap style, as set by set_line_cap().
the current line cap style.
int get_line_join()
Gets the current line join style, as set by set_line_join().
the current line join style.
float get_line_width()
This function returns the current line width value exactly as
set by set_line_width(). Note that the value is unchanged
even if the CTM has changed between the calls to
set_line_width() and get_line_width().
the current line width.
Matrix get_matrix()
Returns the current transformation matrix (CTM).
the matrix
float get_miter_limit()
Gets the current miter limit, as set by set_miter_limit().
the current miter limit.
int get_operator()
Gets the current compositing operator for a cairo context.
the current compositing operator.
ScaledFont get_scaled_font()
Gets the current scaled font for a Context.
the current scaled font.
Pattern get_source()
Gets the current source pattern.
the current source pattern.
Surface get_target()
Gets the target surface for the cairo context
the target surface.
float get_tolerance()
Gets the current tolerance value, as set by set_tolerance().
the current tolerance value.
TextExtents glyph_extents(array(Glyph|array(int|float)) glyphs)
Gets the extents for an array of glyphs. The extents describe a
user-space rectangle that encloses the "inked" portion of the
glyphs, (as they would be drawn by show_glyphs().
Additionally, the x_advance and y_advance values indicate the
amount by which the current point would be advanced by
show_glyphs().
Note that whitespace glyphs do not contribute to the size of the
rectangle (TextExtents->width and TextExtents->height).
glyphsan array of glyph IDs with X and Y offsets, with each glyph
being represented either as a Glyph object or as an array
having the following format:
| Array | |
| glyph index in the font. The exact interpretation of the glyph index depends on the font technology being used. |
| the offset in the X direction between the origin used for drawing the string and the origin of this glyph |
| the offset in the Y direction between the origin used for drawing the string and the origin of this glyph |
a TextExtents object which stores the results.
void glyph_path(array(Glyph|array(int|float)) glyphs)
Adds closed paths for the glyphs to the current path. The
generated path if filled, achieves an effect similar to that of
show_glyphs().
glyphsarray of glyphs to show, with each glyph being represented
either as a Glyph object or as an array of the following
format:
| Array | |
| glyph index in the font. The exact interpretation of the glyph index depends on the font technology being used. |
| the offset in the X direction between the origin used for drawing the string and the origin of this glyph |
| the offset in the Y direction between the origin used for drawing the string and the origin of this glyph |
bool has_current_point()
Returns whether a current point is defined on the current path.
get_current_point() for details on the current point.
whether a current point is defined.
void identity_matrix()
Resets the current transformation matrix (CTM) by setting it equal to the identity matrix. That is, the user-space and device-space axes will be aligned and one user-space unit will transform to one device-space unit.
bool in_clip(float|int x, float|int y)
Tests whether the given point is inside the area that would be
visible through the current clip, i.e. the area that would be
filled by a paint() operation.
clip(), and clip_preserve().
xX coordinate of the point to test
yY coordinate of the point to test
A non-zero value if the point is inside, or zero if outside.
bool in_fill(float|int x, float|int y)
Tests whether the given point is inside the area that would be
affected by a fill() operation given the current path and
filling parameters. Surface dimensions and clipping are not
taken into account.
xX coordinate of the point to test
yY coordinate of the point to test
A non-zero value if the point is inside, or zero if outside.
fill(), set_fill_rule() and fill_preserve().
bool in_stroke(float|int x, float|int y)
Tests whether the given point is inside the area that would be
affected by a stroke() operation given the current path and
stroking parameters. Surface dimensions and clipping are not
taken into account.
xX coordinate of the point to test
yY coordinate of the point to test
A non-zero value if the point is inside, or zero if outside.
stroke(), set_line_width(), set_line_join(),
set_line_cap(), set_dash(), and stroke_preserve().
void line_to(float|int x, float|int y)
Adds a line to the path from the current point to position (x, y) in user-space coordinates. After this call the current point will be (x, y).
If there is no current point before the call to line_to() this function will behave as move_to(x, y).
xthe X coordinate of the end of the new line
ythe Y coordinate of the end of the new line
void mask(Pattern pattern)
A drawing operator that paints the current source using the alpha channel of pattern as a mask. (Opaque areas of pattern are painted with the source, transparent areas are not painted.)
patterna Pattern
void mask_surface(Surface surface, float|int surface_x, float|int surface_y)
A drawing operator that paints the current source using the alpha channel of surface as a mask. (Opaque areas of surface are painted with the source, transparent areas are not painted.)
surfacea Surface
surface_xX coordinate at which to place the origin of surface
surface_yY coordinate at which to place the origin of surface
void move_to(float|int x, float|int y)
Begin a new sub-path. After this call the current point will be (x, y).
xthe X coordinate of the new position
ythe Y coordinate of the new position
void new_path()
Clears the current path. After this call there will be no path and no current point.
void new_sub_path()
Begin a new sub-path. Note that the existing path is not affected. After this call there will be no current point.
In many cases, this call is not needed since new sub-paths are
frequently started with move_to().
A call to new_sub_path() is particularly useful when beginning a new sub-path with one of the arc() calls. This makes things easier as it is no longer necessary to manually compute the arc's initial coordinates for a call to move_to().
void paint()
A drawing operator that paints the current source everywhere within the current clip region.
void paint_with_alpha(float alpha)
A drawing operator that paints the current source everywhere
within the current clip region using a mask of constant alpha
value alpha . The effect is similar to paint(), but the
drawing is faded out using the alpha value.
alphaalpha value, between 0 (transparent) and 1 (opaque)
array(float) path_extents()
Computes a bounding box in user-space coordinates covering the points on the current path. If the current path is empty, returns an empty rectangle ({0, 0, 0, 0}). Stroke parameters, fill rule, surface dimensions and clipping are not taken into account.
Contrast with fill_extents() and stroke_extents() which
return the extents of only the area that would be "inked" by the
corresponding drawing operations.
an array with coordinates for the left, top, right, and bottom, respectively, of the resulting extents
Pattern pop_group()
Terminates the redirection begun by a call to push_group() or
push_group_with_content() and returns a new pattern
containing the results of all drawing operations performed to
the group.
The pop_group() function calls restore(), (balancing a call
to save() by the push_group function), so that any changes
to the graphics state will not be visible outside the group.
a newly created (surface) pattern containing the results of all drawing operations performed to the group.
void pop_group_to_source()
Terminates the redirection begun by a call to push_group() or
push_group_with_content() and installs the resulting pattern
as the source pattern in the given cairo context.
The pop_group() function calls restore(), (balancing a call
to save() by the push_group function), so that any changes
to the graphics state will not be visible outside the group.
void push_group()
Temporarily redirects drawing to an intermediate surface known
as a group. The redirection lasts until the group is completed
by a call to pop_group() or pop_group_to_source(). These
calls provide the result of any drawing to the group as a
pattern, (either as an explicit object, or set as the source
pattern).
This group functionality can be convenient for performing intermediate compositing. One common use of a group is to render objects as opaque within the group, (so that they occlude each other), and then blend the result with translucence onto the destination.
Groups can be nested arbitrarily deep by making balanced calls to push_group()/pop_group(). Each call pushes/pops the new target group onto/from a stack.
The push_group() function calls save() so that any changes to
the graphics state will not be visible outside the group, (the
pop_group functions call restore()).
By default the intermediate group will have a content type of
CONTENT_COLOR_ALPHA. Other content types can be chosen for
the group by using push_group_with_content() instead.
void push_group_with_content(int content)
Temporarily redirects drawing to an intermediate surface known
as a group. The redirection lasts until the group is completed
by a call to pop_group() or pop_group_to_source(). These
calls provide the result of any drawing to the group as a
pattern, (either as an explicit object, or set as the source
pattern).
The group will have a content type of content. The ability to
control this content type is the only distinction between this
function and push_group() which you should see for a more
detailed description of group rendering.
contentthe type of group that will be created
void rectangle(float|int x, float|int y, float|int width, float|int height)
Adds a closed sub-path rectangle of the given size to the current path at position (x, y) in user-space coordinates.
xthe X coordinate of the top left corner of the rectangle
ythe Y coordinate to the top left corner of the rectangle
widththe width of the rectangle
heightthe height of the rectangle
void rel_curve_to(float|int dx1, float|int dy1, float|int dx2, float|int dy2, float|int dx3, float|int dy3)
Relative-coordinate version of curve_to(). All offsets are
relative to the current point. Adds a cubic Bézier spline to
the path from the current point to a point offset from the
current point by (dx3, dy3), using points offset by (dx1, dy1)
and (dx2, dy2) as the control points. After this call the
current point will be offset by (dx3, dy3).
Given a current point of (x, y), rel_curve_to(dx1, dy1, dx2, dy2, dx3, dy3) is logically equivalent to curve_to(x+dx1, y+dy1, x+dx2, y+dy2, x+dx3, y+dy3).
It is an error to call this function with no current point.
dx1the X offset to the first control point
dy1the Y offset to the first control point
dx2the X offset to the second control point
dy2the Y offset to the second control point
dx3the X offset to the end of the curve
dy3the Y offset to the end of the curve
void rel_line_to(float|int dx, float|int dy)
Relative-coordinate version of line_to(). Adds a line to the
path from the current point to a point that is offset from the
current point by (dx, dy) in user space. After this call the
current point will be offset by (dx, dy).
Given a current point of (x, y), rel_line_to(dx, dy) is logically equivalent to line_to(x + dx , y + dy).
It is an error to call this function with no current point.
dxthe X offset to the end of the new line
dythe Y offset to the end of the new line
void rel_move_to(float|int dx, float|int dy)
Begin a new sub-path. After this call the current point will offset by (x, y).
Given a current point of (x, y), rel_move_to(dx , dy) is logically equivalent to move_to(x + dx , y + dy).
It is an error to call this function with no current point.
dxthe X offset
dythe Y offset
void reset_clip()
Reset the current clip region to its original, unrestricted state. That is, set the clip region to an infinitely large shape containing the target surface. Equivalently, if infinity is too hard to grasp, one can imagine the clip region being reset to the exact bounds of the target surface.
Note that code meant to be reusable should not call reset_clip()
as it will cause results unexpected by higher-level code which
calls clip(). Consider using save() and restore()
around clip() as a more robust means of temporarily
restricting the clip region.
void restore()
Restores to the state saved by a preceding call to save() and
removes that state from the stack of saved states.
void rotate(float angle)
Modifies the current transformation matrix (CTM) by rotating the user-space axes by angle radians. The rotation of the axes takes places after any existing transformation of user space. The rotation direction for positive angles is from the positive X axis toward the positive Y axis.
angleangle (in radians) by which the user-space axes will be rotated
void save()
Makes a copy of the current state and saves it on an internal
stack of saved states. When restore() is called, the context
will be restored to the saved state. Multiple calls to save()
and restore() can be nested; each call to restore() restores the
state from the matching paired save().
void scale(float|int sx, float|int sy)
Modifies the current transformation matrix (CTM) by scaling the X and Y user-space axes by sx and sy respectively. The scaling of the axes takes place after any existing transformation of user space.
sxscale factor for the X dimension
syscale factor for the Y dimension
void select_font_face(string family, int slant, int weight)
The select_font_face() function call is part of what the cairo designers call the "toy" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for serious text-using applications.
Selects a family and style of font from a simplified description as a family name, slant and weight. Cairo provides no operation to list available family names on the system (this is a "toy", remember), but the standard CSS2 generic family names, ("serif", "sans-serif", "cursive", "fantasy", "monospace"), are likely to work as expected.
If family starts with the string "@cairo:", or if no native font backends are compiled in, cairo will use an internal font family. The internal font family recognizes many modifiers in the family string, most notably, it recognizes the string "monospace". That is, the family name "@cairo:monospace" will use the monospace version of the internal font family.
For "real" font selection, see the font-backend-specific
font_face_create functions for the font backend you are using.
The resulting font face could then be used with
scaled_font_create() and set_scaled_font().
If text is drawn without a call to select_font_face(), (nor
set_font_face() nor set_scaled_font()), the default family
is platform-specific, but is essentially "sans-serif". Default
slant is FONT_SLANT_NORMAL, and default weight is
FONT_WEIGHT_NORMAL.
This function is equivalent to a call to
toy_font_face_create() followed by set_font_face().
familya font family name
slantthe slant for the font
weightthe weight for the font
void set_antialias(int antialias)
Set the antialiasing mode of the rasterizer used for drawing
shapes. This value is a hint, and a particular backend may or
may not support a particular value. At the current time, no
backend supports ANTIALIAS_SUBPIXEL when drawing shapes.
Note that this option does not affect text rendering, instead
see FontOptions->set_antialias().
antialiasthe new antialiasing mode
void set_dash(array(float|int) dashes, float|int offset)
Sets the dash pattern to be used by stroke(). A dash pattern
is specified by dashes, an array of positive values. Each
value provides the length of alternate "on" and "off" portions
of the stroke. The offset specifies an offset into the pattern
at which the stroke begins.
Each "on" segment will have caps applied as if the segment were
a separate sub-path. In particular, it is valid to use an "on"
length of 0.0 with LINE_CAP_ROUND or LINE_CAP_SQUARE in
order to distributed dots or squares along a path.
The length values are in user-space units as evaluated at the time of stroking. This is not necessarily the same as the user space at the time of set_dash().
If dashes is empty dashing is disabled.
If dashes contains a single value a symmetric pattern is assumed with alternating on and off portions of the size specified by the value.
dashesan array specifying alternate lengths of on and off stroke portions
offsetan offset into the dash pattern at which the stroke should start
void set_fill_rule(int fill_rule)
Set the current fill rule within the cairo context. The fill
rule is used to determine which regions are inside or outside a
complex (potentially self-intersecting) path. The current fill
rule affects both fill() and clip().
The default fill rule is FILL_RULE_WINDING.
fill_rulea fill rule
void set_font_face(FontFace|zero font_face)
Replaces the current FontFace object in the Context with
font_face.
font_facea FontFace, or 0 to restore to the default font
void set_font_matrix(Matrix matrix)
Sets the current font matrix to matrix. The font matrix gives a
transformation from the design space of the font (in this space,
the em-square is 1 unit by 1 unit) to user space. Normally, a
simple scale is used (see set_font_size()), but a more
complex font matrix can be used to shear the font or stretch it
unequally along the two axes
matrixa Matrix describing a transform to be applied to the current
font.
void set_font_options(FontOptions options)
Sets a set of custom font rendering options for the Context.
Rendering options are derived by merging these options with the
options derived from underlying surface; if the value in options
has a default value (like ANTIALIAS_DEFAULT), then the value
from the surface is used.
optionsfont options to use
void set_font_size(float|int size)
Sets the current font matrix to a scale by a factor of size,
replacing any font matrix previously set with set_font_size() or
set_font_matrix(). This results in a font size of size user
space units. (More precisely, this matrix will result in the
font's em-square being a size by size square in user space.)
If text is drawn without a call to set_font_size(), (nor
set_font_matrix() nor set_scaled_font()), the default font
size is 10.0.
sizethe new font size, in user space units
void set_hairline(bool set_hairline)
Sets lines within the cairo context to be hairlines. Hairlines are logically zero-width lines that are drawn at the thinnest renderable width possible in the current context.
On surfaces with native hairline support, the native hairline functionality will be used. Surfaces that support hairlines include:
pdf/ps: Encoded as 0-width line. win32_printing: Rendered with PS_COSMETIC pen. svg: Encoded as 1px non-scaling-stroke. script: Encoded with set-hairline function.
Cairo will always render hairlines at 1 device unit wide, even
if an anisotropic scaling was applied to the stroke width. In
the wild, handling of this situation is not well-defined. Some
PDF, PS, and SVG renderers match Cairo's output, but some very
popular implementations (Acrobat, Chrome, rsvg) will scale the
hairline unevenly. As such, best practice is to reset any
anisotropic scaling before calling stroke().
set_hairlinewhether or not to set hairline mode
void set_line_cap(int line_cap)
Sets the current line cap style within the cairo context.
As with the other stroke parameters, the current line cap style
is examined by stroke(), and stroke_extents(), but does
not have any effect during path construction.
The default line cap style is LINE_CAP_BUTT.
line_capa line cap style
void set_line_join(int line_join)
Sets the current line join style within the cairo context.
As with the other stroke parameters, the current line join style
is examined by stroke(), and stroke_extents(), but does
not have any effect during path construction.
The default line join style is LINE_JOIN_MITER.
line_joina line join style
void set_line_width(float|int width)
Sets the current line width. The line width value specifies the diameter of a pen that is circular in user space.
As with the other stroke parameters, the current line width is
examined by stroke(), and stroke_extents(), but does not
have any effect during path construction.
The default line width value is 2.0.
widtha line width
void set_matrix(Matrix matrix)
Modifies the current transformation matrix (CTM) by setting it equal to matrix.
matrixa transformation matrix from user space to device space
void set_miter_limit(float|int limit)
Sets the current miter limit within the cairo context.
If the current line join style is set to LINE_JOIN_MITER (see
set_line_join()), the miter limit is used to determine
whether the lines should be joined with a bevel instead of a
miter. Cairo divides the length of the miter by the line width.
If the result is greater than the miter limit, the style is
converted to a bevel.
As with the other stroke parameters, the current line miter
limit is examined by stroke(), and stroke_extents(), but
does not have any effect during path construction.
The default miter limit value is 10.0, which will convert joins with interior angles less than 11 degrees to bevels instead of miters. For reference, a miter limit of 2.0 makes the miter cutoff at 60 degrees, and a miter limit of 1.414 makes the cutoff at 90 degrees.
A miter limit for a desired angle can be computed as: miter limit = 1/sin(angle/2)
limitmiter limit to set
void set_operator(int op)
Sets the compositing operator to be used for all drawing operations.
The default operator is OPERATOR_OVER.
opa compositing operator
void set_scaled_font(ScaledFont scaled_font)
Replaces the current font face, font matrix, and font options in
the Context with those of the ScaledFont. Except for some
translation, the current CTM of the Context should be the
same as that of the ScaledFont, which can be accessed using
ScaledFont->get_ctm().
scaled_fonta ScaledFont
void set_source(Pattern source)
Sets the source pattern to source. This pattern will then be
used for any subsequent drawing operation until a new source
pattern is set.
The pattern's transformation matrix will be locked to the user
space in effect at the time of set_source(). This means that
further modifications of the current transformation matrix will
not affect the source pattern. See Pattern->set_matrix().
The default source pattern is a solid pattern that is opaque black, (that is, it is equivalent to set_source_rgb(0.0, 0.0, 0.0)).
sourcea Pattern to be used as the source for subsequent drawing operations.
void set_source_rgb(float red, float green, float blue)
Sets the source pattern to an opaque color. This opaque color will then be used for any subsequent drawing operation until a new source pattern is set.
The color components are floating point numbers in the range 0 to 1. If the values passed in are outside that range, they will be clamped.
The default source pattern is opaque black, (that is, it is equivalent to set_source_rgb(0.0, 0.0, 0.0)).
redred component of color
greengreen component of color
blueblue component of color
void set_source_rgba(float red, float green, float blue, float alpha)
Sets the source pattern to a translucent color. This color will then be used for any subsequent drawing operation until a new source pattern is set.
The color and alpha components are floating point numbers in the range 0 to 1. If the values passed in are outside that range, they will be clamped.
Note that the color and alpha values are not premultiplied.
The default source pattern is opaque black, (that is, it is equivalent to set_source_rgba(0.0, 0.0, 0.0, 1.0)).
redred component of color
greengreen component of color
blueblue component of color
alphaalpha component of color
void set_source_surface(Surface surface, float|int x, float|int y)
This is a convenience function for creating a pattern from
surface and setting it as the source with set_source().
The x and y parameters give the user-space coordinate at which the surface origin should appear. (The surface origin is its upper-left corner before any transformation has been applied.) The x and y parameters are negated and then set as translation values in the pattern matrix.
Other than the initial translation pattern matrix, as described
above, all other pattern attributes, (such as its extend mode),
are set to the default values as in Pattern->create(). The
resulting pattern can be queried with get_source() so that
these attributes can be modified if desired, (eg. to create a
repeating pattern with Pattern->set_extend()).
surfacea surface to be used to set the source pattern
xUser-space X coordinate for surface origin
yUser-space Y coordinate for surface origin
void set_tolerance(float|int tolerance)
Sets the tolerance used when converting paths into trapezoids. Curved segments of the path will be subdivided until the maximum deviation between the original path and the polygonal approximation is less than tolerance. The default value is 0.1. A larger value will give better performance, a smaller value, better appearance. (Reducing the value from the default value of 0.1 is unlikely to improve appearance significantly.) The accuracy of paths within Cairo is limited by the precision of its internal arithmetic, and the prescribed tolerance is restricted to the smallest representable internal value.
tolerancethe tolerance, in device units (typically pixels)
void show_glyphs(array(Glyph|array(int|float)) glyphs)
A drawing operator that generates the shape from an array of glyphs, rendered according to the current font face, font size (font matrix), and font options.
glyphsarray of glyphs to show, with each glyph being represented
either as a Glypg object or as an array of the following
format:
| Array | |
| glyph index in the font. The exact interpretation of the glyph index depends on the font technology being used. |
| the offset in the X direction between the origin used for drawing the string and the origin of this glyph |
| the offset in the Y direction between the origin used for drawing the string and the origin of this glyph |
void show_page()
Emits and clears the current page for backends that support
multiple pages. Use copy_page() if you don't want to clear
the page.
This is a convenience function that simply calls
Surface->show_page() on the context's target.
void show_text(string|zero text)
A drawing operator that generates the shape from a string of characters, rendered according to the current font_face, font_size (font_matrix), and font_options.
This function first computes a set of glyphs for the string of text. The first glyph is placed so that its origin is at the current point. The origin of each subsequent glyph is offset from that of the previous glyph by the advance values of the previous glyph.
After this call the current point is moved to the origin of
where the next glyph would be placed in this same progression.
That is, the current point will be at the origin of the final
glyph offset by its advance values. This allows for easy
display of a single logical string with multiple calls to
show_text().
The show_text() function call is part of what the cairo
designers call the "toy" text API. It is convenient for short
demos and simple programs, but it is not expected to be adequate
for serious text-using applications. See show_glyphs() for
the "real" text display API in cairo.
texta string of text, or 0
void show_text_glyphs(string text, array(Glyph|array(int|float)) glyphs, array(TextCluster) clusters, int cluster_flags)
This operation has rendering effects similar to show_glyphs()
but, if the target surface supports it, uses the provided text
and cluster mapping to embed the text for the glyphs shown in
the output. If the target does not support the extended
attributes, this function acts like the basic show_glyphs()
as if it had been passed glyphs.
The mapping between text and glyphs is provided by an array of clusters. Each cluster covers a number of text bytes and glyphs, and neighboring clusters cover neighboring areas of text and glyphs. The clusters should collectively cover text and glyphs in entirety.
The first cluster always covers bytes from the beginning of
text. If cluster_flags do not have the flag
TEXT_CLUSTER_FLAG_BACKWARD set, the first cluster also
covers the beginning of glyphs, otherwise it covers the end of
the glyphs array and following clusters move backward.
See TextCluster for constraints on valid clusters.
texta string of text
glyphsarray of glyphs to show
clustersarray of cluster mapping information
cluster_flagscluster mapping flags
void stroke()
A drawing operator that strokes the current path according to the current line width, line join, line cap, and dash settings. After stroke(), the current path will be cleared from the context.
set_line_width(), set_line_join(), set_line_cap(),
set_dash(), and stroke_preserve().
array(float) stroke_extents()
Computes a bounding box in user coordinates covering the area
that would be affected, (the "inked" area), by a stroke()
operation given the current path and stroke parameters. If the
current path is empty, returns an empty rectangle ({0, 0, 0,
0}). Surface dimensions and clipping are not taken into
account.
Note that if the line width is set to exactly zero, then
stroke_extents() will return an empty rectangle. Contrast with
path_extents() which can be used to compute the non-empty
bounds as the line width approaches zero.
Note that stroke_extents() must necessarily do more work to
compute the precise inked areas in light of the stroke
parameters, so path_extents() may be more desirable for sake
of performance if non-inked path extents are desired.
an array with coordinates for the left, top, right, and bottom, respectively, of the resulting extents
stroke(), set_line_width(), set_line_join(),
set_line_cap(), set_dash(), and stroke_preserve().
void stroke_preserve()
A drawing operator that strokes the current path according to
the current line width, line join, line cap, and dash
settings. Unlike stroke(), stroke_preserve() preserves the
path within the cairo context.
set_line_width(), set_line_join(), set_line_cap(),
set_dash(), and stroke_preserve().
void tag_begin(string tag_name, string|void attributes)
Marks the beginning of the tag_name structure. Call
ddtag_end() with the same tag_name to mark the end of the
structure.
The attributes string is of the form "key1=value2 key2=value2 ...". Values may be boolean (true/false or 1/0), integer, float, string, or an array.
String values are enclosed in single quotes ('). Single quotes and backslashes inside the string should be escaped with a backslash.
Boolean values may be set to true by only specifying the key. eg the attribute string "key" is the equivalent to "key=true".
Arrays are enclosed in '[]'. eg "rect=[1.2 4.3 2.0 3.0]".
If no attributes are required, attributes can be an empty string or omitted.
tag_end()
tag_nametag name
attributestag attributes
void tag_end(string tag_name)
Marks the end of the tag_name structure.
tag_begin().
tag_nametag name
TextExtents text_extents(string|zero text)
Gets the extents for a string of text. The extents describe a
user-space rectangle that encloses the "inked" portion of the
text, (as it would be drawn by show_text()). Additionally,
the x_advance and y_advance values indicate the amount by which
the current point would be advanced by show_text().
Note that whitespace characters do not directly contribute to
the size of the rectangle (TextExtents->width and
TextExtents->height). They do contribute indirectly by
changing the position of non-whitespace characters. In
particular, trailing whitespace characters are likely to not
affect the size of the rectangle, though they will affect the
x_advance and y_advance values.
texta string of text, or 0
a TextExtents object which stores the results.
void text_path(string|zero text)
Adds closed paths for text to the current path. The generated
path if filled, achieves an effect similar to that of
show_text().
Text conversion and positioning is done similar to show_text().
Like show_text(), After this call the current point is moved to the origin of where the next glyph would be placed in this same progression. That is, the current point will be at the origin of the final glyph offset by its advance values. This allows for chaining multiple calls to to text_path() without having to set current point in between.
texta string of text, or 0
void transform(Matrix matrix)
Modifies the current transformation matrix (CTM) by applying matrix as an additional transformation. The new transformation of user space takes place after any existing transformation.
matrixa transformation to be applied to the user-space axes
void translate(float|int tx, float|int ty)
Modifies the current transformation matrix (CTM) by translating
the user-space origin by (tx, ty). This offset is interpreted as
a user-space coordinate according to the CTM in place before the
new call to translate(). In other words, the translation of
the user-space origin takes place after any existing
transformation.
txamount to translate in the X direction
tyamount to translate in the Y direction
array(float) user_to_device(float|int x, float|int y)
Transform a coordinate from user space to device space by multiplying the given point by the current transformation matrix (CTM).
xX value of coordinate
yY value of coordinate
The transformed point
| Array | |
| X position of the new point |
| Y position of the new point |
array(float) user_to_device_distance(float|int dx, float|int dy)
Transform a distance vector from user space to device space.
This function is similar to user_to_device() except that the
translation components of the CTM will be ignored when
transforming (dx, dy).
dxX component of a distance vector
dyY component of a distance vector
The transformed distance vector
| Array | |
| X component of the new distance vector |
| Y component of the new distance vector |
interface to underlying rendering system
bool res = Cairo.Device() == x
Returns 1 if x is the same Device,
and 0 (zero) otherwise.
void acquire()
Acquires the device for the current thread. This function will block until no other thread has acquired the device.
From now on your thread owns the device and no other thread will
be able to acquire it until a matching call to release(). It
is allowed to recursively acquire the device multiple times from
the same thread.
You must never acquire two different devices at the same time unless this is explicitly allowed. Otherwise the possibility of deadlocks exist. As various Cairo functions can acquire devices when called, these functions may also cause deadlocks when you call them with an acquired device. So you must not have a device acquired when calling them. These functions are marked in the documentation.
After a successful call to acquire(), a matching call to
release() is required.
void finish()
This function finishes the device and drops all references to
external resources. All surfaces, fonts and other objects
created for this device will be finished, too. Further
operations on the device will not affect the device but will
instead trigger a STATUS_DEVICE_FINISHED error.
When the reference count of a Device drops to zero, cairo
will call finish() if it hasn't been called already, before
freeing the resources associated with the device.
This function may acquire devices.
void flush()
Finish any pending operations for the device and also restore any temporary modifications cairo has made to the device's state. This function must be called before switching from using the device with Cairo to operating on it directly with native APIs. If the device doesn't support direct access, then this function does nothing.
This function may acquire devices.
float observer_elapsed()
Returns the total elapsed time of the observation.
the elapsed time, in nanoseconds.
float observer_fill_elapsed()
Returns the elapsed time of the fill operations.
the elapsed time, in nanoseconds.
float observer_glyphs_elapsed()
Returns the elapsed time of the glyph operations.
the elapsed time, in nanoseconds.
float observer_mask_elapsed()
Returns the elapsed time of the mask operations.
the elapsed time, in nanoseconds
float observer_paint_elapsed()
Returns the elapsed time of the paint operations.
the elapsed time, in nanoseconds.
void observer_print(Stdio.OutputStreamMixin stream)
Prints the device log to the given output stream
streamthe output stream
float observer_stroke_elapsed()
Returns the elapsed time of the stroke operations.
the elapsed time, in nanoseconds.
void release()
Releases a device previously acquired using acquire(). See
that function for details.
Error object used for Cairo errors.
inherit Error.Generic : Generic
constant int Cairo.Error.is_cairo_error
constant string Cairo.Error.error_type
Object recognition constants.
int Cairo.Error.status
The numeric status code (STATUS_xxx)
FontFace represents a particular font at a particular weight,
slant, and other characteristic but no size, transformation, or
size.
bool res = Cairo.FontFace() == x
Returns 1 if x is the same FontFace,
and 0 (zero) otherwise.
The font options specify how fonts should be rendered. Most of the time the font options implied by a surface are just right and do not need any changes, but for pixel-based targets tweaking font options may result in superior output on a particular display.
bool res = Cairo.FontOptions() == x
Returns 1 if all fields of the two font options
objects match and 0 (zero) otherwise. Note that this
function will return 0 if either object is in error.
Cairo.FontOptions Cairo.FontOptions(FontOptions|void original)
Allocates a new font options object with all options initialized
either to default values, or to values taken from original.
originalIf specified, a set of font options to copy
int get_antialias()
Gets the antialiasing mode for the font options object.
the antialiasing mode
int get_color_mode()
Gets the color mode for the font options object.
the color mode for the font options object
int(0..) get_color_palette()
Gets the current OpenType color font palette for the font options object.
the palette index
array(float) get_custom_palette_color(int(0..) index)
Gets the custom palette color for the color index for the font options object.
indexthe index of the color to get
An array with the components of the color
| Array | |
| red component of color |
| green component of color |
| blue component of color |
| alpha component of color |
int get_hint_metrics()
Gets the metrics hinting mode for the font options object.
the metrics hinting mode for the font options object
int get_hint_style()
Gets the hint style for font outlines for the font options object.
the hint style for the font options object
int get_subpixel_order()
Gets the subpixel order for the font options object.
the subpixel order for the font options object
string(7bit)|zero get_variations()
Gets the OpenType font variations for the font options object.
See set_variations() for details about the string format.
the font variations for the font options object.
void merge(FontOptions other)
Merges non-default options from other into options, replacing
existing values. This operation can be thought of as somewhat
similar to compositing other onto options with the operation of
OPERATOR_OVER.
otheranother FontOptions
void set_antialias(int antialias)
Sets the antialiasing mode for the font options object. This specifies the type of antialiasing to do when rendering text.
antialiasthe new antialiasing mode
void set_color_mode(int color_mode)
Sets the color mode for the font options object. This controls whether color fonts are to be rendered in color or as outlines.
color_modethe new color mode
void set_color_palette(int(0..) palette_index)
Sets the OpenType font color palette for the font options
object. OpenType color fonts with a CPAL table may contain
multiple palettes. The default color palette index is
COLOR_PALETTE_DEFAULT.
If palette_index is invalid, the default palette is used.
Individual colors within the palette may be overriden with
set_custom_palette_color().
palette_indexthe palette index in the CPAL table
void set_custom_palette_color(int(0..) index, float red, float green, float blue, float alpha)
Sets a custom palette color for the font options object. This
overrides the palette color at the specified color index. This
override is independent of the selected palette index and will
remain in place even if set_color_palette() is called to
change the palette index.
It is only possible to override color indexes already in the font palette.
indexthe index of the color to set
redred component of color
greengreen component of color
blueblue component of color
alphaalpha component of color
void set_hint_metrics(int hint_metrics)
Sets the metrics hinting mode for the font options object. This controls whether metrics are quantized to integer values in device units.
hint_metricsthe new metrics hinting mode
void set_hint_style(int hint_style)
Sets the hint style for font outlines for the font options object. This controls whether to fit font outlines to the pixel grid, and if so, whether to optimize for fidelity or contrast.
hint_stylethe new hint style
void set_subpixel_order(int subpixel_order)
Sets the subpixel order for the font options object. The
subpixel order specifies the order of color elements within each
pixel on the display device when rendering with an antialiasing
mode of ANTIALIAS_SUBPIXEL.
subpixel_orderthe new subpixel order
void set_variations(string(7bit)|zero variations)
Sets the OpenType font variations for the font options object. Font variations are specified as a string with a format that is similar to the CSS font-variation-settings. The string contains a comma-separated list of axis assignments, which each assignment consists of a 4-character axis name and a value, separated by whitespace and optional equals sign.
wght=200,wdth=140.5 wght 200 , wdth 140.5
variationsthe new font variations, or 0
Holds information about a single glyph when drawing or measuring text. A font is (in simple terms) a collection of shapes used to draw text. A glyph is one of these shapes. There can be multiple glyphs for a single character (alternates to be used in different contexts, for example), or a glyph can be a ligature of multiple characters. Cairo doesn't expose any way of converting input text into glyphs, so in order to use the Cairo interfaces that take arrays of glyphs, you must directly access the appropriate underlying font system.
Note that the offsets given by x and y are not cumulative.
When drawing or measuring text, each glyph is individually
positioned with respect to the overall origin
int(0..) Cairo.Glyph.index
glyph index in the font. The exact interpretation of the glyph index depends on the font technology being used.
float Cairo.Glyph.x
the offset in the X direction between the origin used for drawing or measuring the string and the origin of this glyph.
float Cairo.Glyph.y
the offset in the Y direction between the origin used for drawing or measuring the string and the origin of this glyph.
string sprintf(string format, ... Cairo.Glyph arg ... )
Cairo.Glyph Cairo.Glyph(int(0..) index, float|int|void x, float|int|void y)
indexglyph index in the font. The exact interpretation of the glyph index depends on the font technology being used.
xthe offset in the X direction between the origin used for drawing or measuring the string and the origin of this glyph.
ythe offset in the Y direction between the origin used for drawing or measuring the string and the origin of this glyph.
A gradient.
inherit Pattern : Pattern
void add_color_stop_rgb(float offset, float red, float green, float blue)
Adds an opaque color stop to a gradient pattern. The offset specifies the location along the gradient's control vector. For example, a linear gradient's control vector is from (x0,y0) to (x1,y1) while a radial gradient's control vector is from any point on the start circle to the corresponding point on the end circle.
The color is specified in the same way as in
Context->set_source_rgb().
If two (or more) stops are specified with identical offset values, they will be sorted according to the order in which the stops are added, (stops added earlier will compare less than stops added later). This can be useful for reliably making sharp color transitions instead of the typical blend.
offsetan offset in the range [0.0 .. 1.0]
redred component of color
greengreen component of color
blueblue component of color
void add_color_stop_rgba(float offset, float red, float green, float blue, float alpha)
Adds a translucent color stop to a gradient pattern. The offset specifies the location along the gradient's control vector. For example, a linear gradient's control vector is from (x0,y0) to (x1,y1) while a radial gradient's control vector is from any point on the start circle to the corresponding point on the end circle.
The color is specified in the same way as in
Context->set_source_rgba().
If two (or more) stops are specified with identical offset values, they will be sorted according to the order in which the stops are added, (stops added earlier will compare less than stops added later). This can be useful for reliably making sharp color transitions instead of the typical blend.
offsetan offset in the range [0.0 .. 1.0]
redred component of color
greengreen component of color
blueblue component of color
alphaalpha component of color
int get_color_stop_count()
Gets the number of color stops specified in the gradient pattern.
the number of color stops
array(float) get_color_stop_rgba(int index)
Gets the color and offset information at the given index for a
gradient pattern. Values of index range from 0 to n-1 where n
is the number returned by get_color_stop_count().
Note that the color and alpha values are not premultiplied.
indexindex of the stop to return data for
| Array | |
| the offset of the stop |
| red component of color |
| green component of color |
| blue component of color |
| alpha component of color |
Rendering to memory buffers
inherit Surface : Surface
Cairo.ImageSurface Cairo.ImageSurface(int format, int width, int height)
Creates an image surface of the specified format and dimensions. Initially the surface contents are set to 0. (Specifically, within each pixel, each color or alpha channel belonging to format will be 0. The contents of bits within a pixel, but not belonging to the given format are undefined.)
formatformat of pixels in the surface to create
widthwidth of the surface, in pixels
heightheight of the surface, in pixels
Cairo.ImageSurface Cairo.ImageSurface(Image.Image|Image.Layer|string|Stdio.InputStream image_or_png)
Creates a new image surface and initializes the contents to the
given Image.Image or Image.Layer or PNG file.
image_or_pngEither an Image.Image or Image.Layer to copy pixel data
from, or the filename of a PNG file to load, or a
Stdio.InputStream to read PNG data from.
int get_format()
Get the format of the surface.
the format of the surface
int get_height()
Get the height of the image surface in pixels.
the height of the surface in pixels.
int get_stride()
Get the stride of the image surface in bytes
the stride of the image surface in bytes (or 0 if surface is not an image surface). The stride is the distance in bytes from the beginning of one row of the image data to the beginning of the next row.
int get_width()
Get the width of the image surface in pixels.
the width of the surface in pixels.
void write_to_png(string|Stdio.OutputStreamMixin png_file)
Writes the contents of this ImageSurface as a PNG image.
png_filethe name of a file to write to, or a
Stdio.OutputStreamMixin to write the PNG data to
A linear gradient.
inherit Gradient : Gradient
Cairo.LinearGradient Cairo.LinearGradient(float|int x0, float|int y0, float|int x1, float|int y1)
Create a new LinearGradient along the line defined by (x0,
y0) and (x1, y1). Before using the gradient pattern, a number
of color stops should be defined using add_color_stop_rgb()
or add_color_stop_rgba().
The coordinates here are in pattern space. For a new pattern,
pattern space is identical to user space, but the relationship
between the spaces can be changed with set_matrix().
x0x coordinate of the start point
y0y coordinate of the start point
x1x coordinate of the end point
y1y coordinate of the end point
array(float) get_linear_points()
Gets the gradient endpoints for a linear gradient.
| Array | |
| the x coordinate of the first point |
| the y coordinate of the first point |
| the x coordinate of the second point |
| the y coordinate of the second point |
Holds an affine transformation, such as a scale, rotation, shear, or a combination of those.
float Cairo.Matrix.x0
X translation component of the affine transformation
float Cairo.Matrix.xx
xx component of the affine transformation
float Cairo.Matrix.xy
xy component of the affine transformation
float Cairo.Matrix.y0
Y translation component of the affine transformation
float Cairo.Matrix.yx
yx component of the affine transformation
float Cairo.Matrix.yy
yy component of the affine transformation
string sprintf(string format, ... Cairo.Matrix arg ... )
Matrix res = Cairo.Matrix() * other
Multiplies the affine transformations in this and other. The effect of the resulting transformation is to first apply the transformation in this to the coordinates and then apply the transformation in other to the coordinates.
othera Matrix
Cairo.Matrix Cairo.Matrix(float|int|void xx, float|int|void yx, float|int|void xy, float|int|void yy, float|int|void x0, float|int|void y0)
xxxx component of the affine transformation
yxyx component of the affine transformation
xyxy component of the affine transformation
yyyy component of the affine transformation
x0X translation component of the affine transformation
y0Y translation component of the affine transformation
void invert()
Changes matrix to be the inverse of its original value. Not all transformation matrices have inverses; if the matrix collapses points together (it is degenerate), then it has no inverse and this function will fail.
void rotate(float radians)
Applies rotation by radians to the transformation. The effect of the new transformation is to first rotate the coordinates by radians, then apply the original transformation to the coordinates.
radiansangle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the positive X axis toward the positive Y axis. With the default axis orientation of cairo, positive angles rotate in a clockwise direction.
void scale(float|int sx, float|int sy)
Applies scaling by sx, sy to the transformation. The effect of the new transformation is to first scale the coordinates by sx and sy, then apply the original transformation to the coordinates.
sxscale factor in the X direction
syscale factor in the Y direction
array(float) transform_distance(float|int dx, float|int dy)
Transforms the distance vector (dx, dy). This is similar to
transform_point() except that the translation components of
the transformation are ignored. The calculation of the returned
vector is as follows:
dx_new = xx * dx + xy * dy;
dy_new = yx * dx + yy * dy;
dxX component of a distance vector
dyY component of a distance vector
The transformed distance vector
| Array | |
| X component of the new distance vector |
| Y component of the new distance vector |
array(float) transform_point(float|int x, float|int y)
Transforms the point (x, y). The transformation is given by:
x_new = xx * x + xy * y + x0;
y_new = yx * x + yy * y + y0;
xX position
yY position
The transformed point
| Array | |
| X position of the new point |
| Y position of the new point |
void translate(float|int tx, float|int ty)
Applies a translation by tx, ty to the transformation. The effect of the new transformation is to first translate the coordinates by tx and ty, then apply the original transformation to the coordinates.
txamount to translate in the X direction
tyamount to translate in the Y direction
Mesh patterns are tensor-product patch meshes (type 7 shadings in PDF). Mesh patterns may also be used to create other types of shadings that are special cases of tensor-product patch meshes such as Coons patch meshes (type 6 shading in PDF) and Gouraud-shaded triangle meshes (type 4 and 5 shadings in PDF).
Mesh patterns consist of one or more tensor-product patches, which
should be defined before using the mesh pattern. Using a mesh
pattern with a partially defined patch as source or mask will put
the context in an error status with a status of
STATUS_INVALID_MESH_CONSTRUCTION.
A tensor-product patch is defined by 4 Bézier curves (side 0, 1, 2, 3) and by 4 additional control points (P0, P1, P2, P3) that provide further control over the patch and complete the definition of the tensor-product patch. The corner C0 is the first point of the patch.
Degenerate sides are permitted so straight lines may be used. A zero length line on one side may be used to create 3 sided patches.
C1 Side 1 C2
+---------------+
| |
| P1 P2 |
| |
Side 0 | | Side 2
| |
| |
| P0 P3 |
| |
+---------------+
C0 Side 3 C3
Each patch is constructed by first calling begin_patch(), then
move_to() to specify the first point in the patch (C0). Then
the sides are specified with calls to curve_to() and
line_to().
The four additional control points (P0, P1, P2, P3) in a patch can
be specified with set_control_point().
At each corner of the patch (C0, C1, C2, C3) a color may be
specified with set_corner_color_rgb() or
set_corner_color_rgba(). Any corner whose color is not
explicitly specified defaults to transparent black.
A Coons patch is a special case of the tensor-product patch where the control points are implicitly defined by the sides of the patch. The default value for any control point not specified is the implicit value for a Coons patch, i.e. if no control points are specified the patch is a Coons patch.
A triangle is a special case of the tensor-product patch where the control points are implicitly defined by the sides of the patch, all the sides are lines and one of them has length 0, i.e. if the patch is specified using just 3 lines, it is a triangle. If the corners connected by the 0-length side have the same color, the patch is a Gouraud-shaded triangle.
Calling end_patch() completes the current patch. If less than
4 sides have been defined, the first missing side is defined as a
line from the current point to the first point of the patch (C0)
and the other sides are degenerate lines from C0 to C0. The
corners between the added sides will all be coincident with C0 of
the patch and their color will be set to be the same as the color
of C0.
Additional patches may be added with additional calls to
begin_patch()/end_patch().
inherit Pattern : Pattern
void begin_patch()
Begin a patch in a mesh pattern.
After calling this function, the patch shape should be defined
with move_to(), line_to() and curve_to().
After defining the patch, end_patch() must be called before
using pattern as a source or mask.
If pattern already has a current patch, it will be put into an
error status with a status of
STATUS_INVALID_MESH_CONSTRUCTION.
Cairo.MeshPattern Cairo.MeshPattern()
Create a new mesh pattern.
void curve_to(float|int x1, float|int y1, float|int x2, float|int y2, float|int x3, float|int y3)
Adds a cubic Bézier spline to the current patch from the current point to position (x3, y3) in pattern-space coordinates, using (x1, y1) and (x2, y2) as the control points.
If the current patch has no current point before the call to
curve_to(), this function will behave as if preceded by a call
to move_to(x1, y1).
After this call the current point will be (x3, y3).
If pattern has no current patch or the current patch already has
4 sides, pattern will be put into an error status with a status
of STATUS_INVALID_MESH_CONSTRUCTION.
x1the X coordinate of the first control point
y1the Y coordinate of the first control point
x2the X coordinate of the second control point
y2the Y coordinate of the second control point
x3the X coordinate of the end of the curve
y3the Y coordinate of the end of the curve
void end_patch()
Indicates the end of the current patch in a mesh pattern.
If the current patch has less than 4 sides, it is closed with a
straight line from the current point to the first point of the
patch as if line_to() was used.
If pattern has no current patch or the current patch has no
current point, pattern will be put into an error status with a
status of STATUS_INVALID_MESH_CONSTRUCTION.
array(float) get_control_point(int(0..) patch_num, int(2bit) point_num)
Gets the control point point_num of patch patch_num for a mesh pattern.
patch_num can range from 0 to n-1 where n is the number returned
by get_patch_count().
Valid values for point_num are from 0 to 3 and identify the
control points as explained in MeshPattern.
patch_numthe patch number to return data for
point_numthe control point number to return data for
the coordinates of the control point
| Array | |
| the x coordinate of the control point |
| the y coordinate of the control point |
array(float) get_corner_color_rgba(int(0..) patch_num, int(2bit) corner_num)
Gets the color information in corner corner_num of patch patch_num for a mesh pattern.
patch_num can range from 0 to n-1 where n is the number returned
by get_patch_count().
Valid values for corner_num are from 0 to 3 and identify the
corners as explained in MeshPattern.
Note that the color and alpha values are not premultiplied.
patch_numthe patch number to return data for
corner_numthe corner number to return data for
the color information of the corner
| Array | |
| red component of color |
| green component of color |
| blue component of color |
| alpha component of color |
int(0..) get_patch_count()
Gets the number of patches specified in this mesh pattern.
The number only includes patches which have been finished by
calling end_patch(). For example it will be 0 during the
definition of the first patch.
the number patches
Path get_path(int(0..) patch_num)
Gets path defining the patch patch_num for a mesh pattern.
patch_num can range from 0 to n-1 where n is the number returned
by get_patch_count().
patch_numthe patch number to return data for
the path defining the patch
void line_to(float|int x, float|int y)
Adds a line to the current patch from the current point to position (x, y) in pattern-space coordinates.
If there is no current point before the call to line_to() this
function will behave as move_to(x, y).
After this call the current point will be (x, y).
If pattern has no current patch or the current patch already has
4 sides, pattern will be put into an error status with a status
of STATUS_INVALID_MESH_CONSTRUCTION.
xthe X coordinate of the end of the new line
ythe Y coordinate of the end of the new line
void move_to(float|int x, float|int y)
Define the first point of the current patch in a mesh pattern.
After this call the current point will be (x, y).
If pattern has no current patch or the current patch already has
at least one side, pattern will be put into an error status with a
status of STATUS_INVALID_MESH_CONSTRUCTION.
xthe X coordinate of the new position
ythe Y coordinate of the new position
void set_control_point(int(2bit) point_num, float|int x, float|int y)
Set an internal control point of the current patch.
Valid values for point_num are from 0 to 3 and identify the
control points as explained in MeshPattern.
If point_num is not valid, pattern will be put into an error
status with a status of STATUS_INVALID_INDEX. If pattern has
no current patch, pattern will be put into an error status with
a status of STATUS_INVALID_MESH_CONSTRUCTION.
point_numthe control point to set the position for
xthe X coordinate of the control point
ythe Y coordinate of the control point
void set_corner_color_rgb(int(2bit) corner_num, float red, float green, float blue)
Sets the color of a corner of the current patch in a mesh pattern.
The color is specified in the same way as in
Context->set_source_rgb().
Valid values for corner_num are from 0 to 3 and identify the
corners as explained in MeshPattern.
If corner_num is not valid, pattern will be put into an error
status with a status of STATUS_INVALID_INDEX. If pattern has
no current patch, pattern will be put into an error status with
a status of STATUS_INVALID_MESH_CONSTRUCTION.
corner_numthe corner to set the color for
redred component of color
greengreen component of color
blueblue component of color
void set_corner_color_rgba(int(2bit) corner_num, float red, float green, float blue, float alpha)
Sets the color of a corner of the current patch in a mesh pattern.
The color is specified in the same way as in
Context->set_source_rgba().
Valid values for corner_num are from 0 to 3 and identify the
corners as explained in MeshPattern.
If corner_num is not valid, pattern will be put into an error
status with a status of STATUS_INVALID_INDEX. If pattern has
no current patch, pattern will be put into an error status with
a status of STATUS_INVALID_MESH_CONSTRUCTION.
corner_numthe corner to set the color for
redred component of color
greengreen component of color
blueblue component of color
alphaalpha component of color
Rendering PDF documents
inherit Surface : Surface
int add_outline(int parent_id, string name, string link_attribs, int flags)
Add an item to the document outline hierarchy with the given
name that links to the location specified by link_attribs.
Link attributes have the same keys and values as the Link Tag,
excluding the "rect" attribute. The item will be a child of the
item with id parent_id. Use PDF_OUTLINE_ROOT as the
parent id of top level items.
parent_idthe id of the parent item or PDF_OUTLINE_ROOT if this is a
top level item.
namethe name of the outline
link_attribsthe link attributes specifying where this outline links to
flagsoutline item flags
Cairo.PDFSurface Cairo.PDFSurface(string|Stdio.OutputStreamMixin|zero pdf_file, float|int width_in_points, float|int height_in_points)
Creates a PDF surface of the specified size in points to be
written to pdf_file.
pdf_filea filename for the PDF output (must be writable), or a
Stdio.OutputStreamMixin to write the output to. 0
may be used to specify no output. This will generate a PDF
surface that may be queried and used as a source, without
generating a temporary file.
width_in_pointswidth of the surface, in points (1 point == 1/72.0 inch)
height_in_pointsheight of the surface, in points (1 point == 1/72.0 inch)
array(int) get_versions()
Used to retrieve the list of supported versions. See
restrict_to_version().
supported version list
void restrict_to_version(int version)
Restricts the generated PDF file to version.
This function should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this function immediately after creating the surface.
versionPDF version
void set_custom_metadata(string name, string|zero value)
Set custom document metadata. name may be any string except
for the following names reserved by PDF: "Title", "Author",
"Subject", "Keywords", "Creator", "Producer", "CreationDate",
"ModDate", "Trapped".
If value is 0 or an empty string, the name metadata
will not be set.
pdf_surface->set_custom_metadata("ISBN", "978-0123456789");
nameThe name of the custom metadata item to set.
valueThe value of the metadata.
void set_metadata(int metadata, string value)
Set document metadata. The PDF_METADATA_CREATE_DATE and
PDF_METADATA_MOD_DATE values must be in ISO-8601 format:
YYYY-MM-DDThh:mm:ss. An optional timezone of the form
"[+/-]hh:mm" or "Z" for UTC time can be appended. All other
metadata values can be any string.
pdf_surface->set_metadata(Cairo.PDF_METADATA_TITLE, "My Document"); pdf_surface->set_metadata(Cairo.PDF_METADATA_CREATE_DATE, "2015-12-31T23:59+02:00");
metadataThe metadata item to set.
valuemetadata value
void set_page_label(string label)
Set page label for the current page.
labelThe page label.
void set_size(float|int width_in_points, float|int height_in_points)
Changes the size of a PDF surface for the current (and subsequent) pages.
This function should only be called before any drawing
operations have been performed on the current page. The
simplest way to do this is to call this function immediately
after creating the surface or immediately after completing a
page with either Context->show_page() or
Context->copy_page().
width_in_pointsnew surface width, in points (1 point == 1/72.0 inch)
height_in_pointsnew surface height, in points (1 point == 1/72.0 inch)
void set_thumbnail_size(int width, int height)
Set the thumbnail image size for the current and all subsequent pages. Setting a width or height of 0 disables thumbnails for the current and subsequent pages.
widthThumbnail width.
heightThumbnail height
string version_to_string(int version)
Get the string representation of the given version id. This
function will return UNDEFINED if version isn't valid.
See get_versions() for a way to get the list of valid version
ids.
the string associated to given version.
Rendering PostScript documents
inherit Surface : Surface
Cairo.PSSurface Cairo.PSSurface(string|Stdio.OutputStreamMixin|zero ps_file, float|int width_in_points, float|int height_in_points)
Creates a PostScript surface of the specified size in points to
be written to ps_file.
ps_filea filename for the PS output (must be writable), or a
Stdio.OutputStreamMixin to write the output to. 0
may be used to specify no output. This will generate a PS
surface that may be queried and used as a source, without
generating a temporary file.
width_in_pointswidth of the surface, in points (1 point == 1/72.0 inch)
height_in_pointsheight of the surface, in points (1 point == 1/72.0 inch)
void dsc_begin_page_setup()
This function indicates that subsequent calls to
dsc_comment() should direct comments to the PageSetup section
of the PostScript output.
This function call is only needed for the first page of a
surface. It should be called after any call to
dsc_begin_setup() and before any drawing is performed to the
surface.
See dsc_comment() for more details.
void dsc_begin_setup()
This function indicates that subsequent calls to
dsc_comment() should direct comments to the Setup section of
the PostScript output.
This function should be called at most once per surface, and
must be called before any call to dsc_begin_page_setup() and
before any drawing is performed to the surface.
See dsc_comment() for more details.
void dsc_comment(string comment)
Emit a comment into the PostScript output for the given surface.
The comment is expected to conform to the PostScript Language Document Structuring Conventions (DSC). Please see that manual for details on the available comments and their meanings. In particular, the %%IncludeFeature comment allows a device-independent means of controlling printer device features. So the PostScript Printer Description Files Specification will also be a useful reference.
The comment string must begin with a percent character (%) and the total length of the string (including any initial percent characters) must not exceed 255 characters. Violating either of these conditions will place surface into an error state. But beyond these two conditions, this function will not enforce conformance of the comment with any particular specification.
The comment string must not contain any newline characters.
The DSC specifies different sections in which particular comments can appear. This function provides for comments to be emitted within three sections: the header, the Setup section, and the PageSetup section. Comments appearing in the first two sections apply to the entire document while comments in the BeginPageSetup section apply only to a single page.
For comments to appear in the header section, this function
should be called after the surface is created, but before a call
to dsc_begin_setup().
For comments to appear in the Setup section, this function
should be called after a call to dsc_begin_setup() but before
a call to dsc_begin_page_setup().
For comments to appear in the PageSetup section, this function
should be called after a call to dsc_begin_page_setup().
Note that it is only necessary to call dsc_begin_page_setup()
for the first page of any surface. After a call to
Context->show_page() or Context->copy_page() comments are
unambiguously directed to the PageSetup section of the current
page. But it doesn't hurt to call this function at the
beginning of every page as that consistency may make the calling
code simpler.
As a final note, cairo automatically generates several comments on its own. As such, applications must not manually generate any of the following comments:
Header section: %!PS-Adobe-3.0, %%Creator, %%CreationDate, %%Pages, %%BoundingBox, %%DocumentData, %%LanguageLevel, %%EndComments.
Setup section: %%BeginSetup, %%EndSetup
PageSetup section: %%BeginPageSetup, %%PageBoundingBox, %%EndPageSetup.
Other sections: %%BeginProlog, %%EndProlog, %%Page, %%Trailer, %%EOF
Here is an example sequence showing how this function might be used:
Cairo.Surface surface = Cairo.PSSurface(filename, width, height); ... surface->dsc_comment("%%Title: My excellent document"); surface->dsc_comment("%%Copyright: Copyright (C) 2006 Cairo Lover") ... surface->dsc_begin_setup(); surface->dsc_comment("%%IncludeFeature: *MediaColor White"); ... surface->dsc_begin_page_setup(); surface->dsc_comment("%%IncludeFeature: *PageSize A3"); surface->dsc_comment("%%IncludeFeature: *InputSlot LargeCapacity"); surface->dsc_comment("%%IncludeFeature: *MediaType Glossy"); surface->dsc_comment("%%IncludeFeature: *MediaColor Blue"); ... draw to first page here .. cr->show_page(); ... surface->dsc_comment("%%IncludeFeature: *PageSize A5"); ...
commenta comment string to be emitted into the PostScript output
bool get_eps()
Check whether the PostScript surface will output Encapsulated PostScript.
1 if the surface will output Encapsulated PostScript.
array(int) get_levels()
Used to retrieve the list of supported levels. See
restrict_to_level().
supported level list
string level_to_string(int level)
Get the string representation of the given level id. This
function will return UNDEFINED if level id isn't valid.
See get_levels() for a way to get the list of valid level
ids.
levela level id
the string associated to given level.
void restrict_to_level(int level)
Restricts the generated PostSript file to level.
This function should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this function immediately after creating the surface.
levelPostScript level
void set_eps(bool eps)
If eps is 1, the PostScript surface will output
Encapsulated PostScript.
This function should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this function immediately after creating the surface. An Encapsulated PostScript file should never contain more than one page.
eps1 to output EPS format PostScript
void set_size(float|int width_in_points, float|int height_in_points)
Changes the size of a PostScript surface for the current (and subsequent) pages.
This function should only be called before any drawing
operations have been performed on the current page. The
simplest way to do this is to call this function immediately
after creating the surface or immediately after completing a
page with either Context->show_page() or
Context->copy_page().
width_in_pointsnew surface width, in points (1 point == 1/72.0 inch)
height_in_pointsnew surface height, in points (1 point == 1/72.0 inch)
Paths are the most basic drawing tools and are primarily used to implicitly generate simple masks
Cairo.Path a;
foreach( a; index; value ) orPathIterator _get_iterator(void|int ind)
Create and initiate a new PathIterator that could be used to iterate over this path.
An iterator.
string sprintf(string format, ... Cairo.Path arg ... )
This is the iterator for the Path.
int _iterator_index()
Returns the current index, or UNDEFINED if the iterator
doesn't point to any item.
The index is the current position in the data set, counting
from 0 (zero).
bool _iterator_next()
Advance the iterator one step.
Returns 1 if it succeeded in advancing, and 0 (zero) if it has reached the end of the iterator.
_iterator_index(), _iterator_value()
mixed _iterator_value()
Returns the current value, or UNDEFINED if the iterator
doesn't point to any item.
Cairo.Path.PathIterator Cairo.Path.PathIterator(Path path)
Creates a new iterator for the Path path.
The paint with which cairo draws. The primary use of patterns is as the source for all cairo drawing operations, although they can also be used as masks, that is, as the brush too.
bool res = Cairo.Pattern() == x
Returns 1 if x is the same Pattern,
and 0 (zero) otherwise.
int get_dither()
Gets the current dithering mode, as set by set_dither().
the current dithering mode.
int get_extend()
Gets the current extend mode for a pattern.
the current extend strategy used for drawing the pattern.
int get_filter()
Gets the current filter for a pattern.
the current filter used for resizing the pattern.
Matrix get_matrix()
Stores the pattern's transformation matrix into a Matrix.
the matrix
void set_dither(int dither)
Set the dithering mode of the rasterizer used for drawing shapes. This value is a hint, and a particular backend may or may not support a particular value. At the current time, only pixman is supported.
ditherthe new dithering mode
void set_extend(int extend)
Sets the mode to be used for drawing outside the area of a pattern.
The default extend mode is EXTEND_NONE for surface patterns
and EXTEND_PAD for gradient patterns.
extendhow the area outside of the pattern will be drawn
void set_filter(int filter)
Sets the filter to be used for resizing when using this pattern.
Note that you might want to control filtering even when you do
not have an explicit Pattern object, (for example when using
Context->set_source_surface()). In these cases, it is
convenient to use Context->get_source() to get access to the
pattern that cairo creates implicitly. For example:
cr->set_source_surface(image, x, y);
cr->get_source()->set_filter(Cairo.FILTER_NEAREST);
filterthe filter to use for resizing the pattern
void set_matrix(Matrix matrix)
Sets the pattern's transformation matrix to matrix. This matrix is a transformation from user space to pattern space.
When a pattern is first created it always has the identity matrix for its transformation matrix, which means that pattern space is initially identical to user space.
Important: Please note that the direction of this transformation matrix is from user space to pattern space. This means that if you imagine the flow from a pattern to user space (and on to device space), then coordinates in that flow will be transformed by the inverse of the pattern matrix.
Also, please note the discussion of the user-space locking
semantics of Context->set_source().
matrixa matrix
A radial gradient.
inherit Gradient : Gradient
Cairo.RadialGradient Cairo.RadialGradient(float|int cx0, float|int cy0, float|int radius0, float|int cx1, float|int cy1, float|int radius1)
Creates a new RadialGradient between the two circles defined
by (cx0, cy0, radius0) and (cx1, cy1, radius1). Before using
the gradient pattern, a number of color stops should be defined
using add_color_stop_rgb() or add_color_stop_rgba().
The coordinates here are in pattern space. For a new pattern,
pattern space is identical to user space, but the relationship
between the spaces can be changed with set_matrix().
cx0x coordinate for the center of the start circle
cy0y coordinate for the center of the start circle
radius0radius of the start circle
cx1x coordinate for the center of the end circle
cy1y coordinate for the center of the end circle
radius1radius of the end circle
array(float) get_radial_circles()
Gets the gradient endpoint circles for a radial gradient, each specified as a center coordinate and a radius.
| Array | |
| the x coordinate of the center of the first circle |
| the y coordinate of the center of the first circle |
| the radius of the first circle |
| the x coordinate of the center of the second circle |
| the y coordinate of the center of the second circle |
| the radius of the second circle |
Records all drawing operations
inherit Surface : Surface
Cairo.RecordingSurface Cairo.RecordingSurface(int content, Rectangle|void extents)
Creates a recording-surface which can be used to record all
drawing operations at the highest level (that is, the level of
Context->paint, Context->mask, Context->stroke,
Context->fill and Context->show_text_glyphs). The
recording surface can then be "replayed" against any target
surface by using it as a source to drawing operations.
The recording phase of the recording surface is careful to snapshot all necessary objects (paths, patterns, etc.), in order to achieve accurate replay.
contentthe content of the recording surface
extentsthe extents to record in pixels, can be omitted to record unbounded operations.
Rectangle get_extents()
Get the extents of the RecordingSurface.
A Rectangle if the surface is bounded, otherwise
UNDEFINED
array(float) ink_extents()
Measures the extents of the operations stored within the
RecordingSurface. This is useful to compute the required
size of an ImageSurface (or equivalent) into which to replay
the full sequence of drawing operations.
An array with the following elements:
| Array | |
| the x-coordinate of the top-left of the ink bounding box |
| the y-coordinate of the top-left of the ink bounding box |
| the width of the ink bounding box |
| the height of the ink bounding box |
A data structure for holding a rectangle.
float Cairo.Rectangle.height
height of the rectangle
float Cairo.Rectangle.width
width of the rectangle
float Cairo.Rectangle.x
X coordinate of the left side of the rectangle
float Cairo.Rectangle.y
Y coordinate of the top side of the rectangle
string sprintf(string format, ... Cairo.Rectangle arg ... )
Cairo.Rectangle Cairo.Rectangle(float|int x, float|int y, float|int width, float|int height)
xX coordinate of the left side of the rectangle
yY coordinate of the top side of the rectangle
widthwidth of the rectangle
heightheight of the rectangle
A data structure for holding a rectangle with integer coordinates.
int Cairo.RectangleInt.height
height of the rectangle
int Cairo.RectangleInt.width
width of the rectangle
int Cairo.RectangleInt.x
X coordinate of the left side of the rectangle
int Cairo.RectangleInt.y
Y coordinate of the top side of the rectangle
string sprintf(string format, ... Cairo.RectangleInt arg ... )
Cairo.RectangleInt Cairo.RectangleInt(int x, int y, int width, int height)
xX coordinate of the left side of the rectangle
yY coordinate of the top side of the rectangle
widthwidth of the rectangle
heightheight of the rectangle
Rendering SVG documents
inherit Surface : Surface
Cairo.SVGSurface Cairo.SVGSurface(string|Stdio.OutputStreamMixin|zero svg_file, float|int width_in_points, float|int height_in_points)
Creates a SVG surface of the specified size in points to be
written to svg_file.
svg_filea filename for the SVG output (must be writable), or a
Stdio.OutputStreamMixin to write the output to. 0
may be used to specify no output. This will generate a SVG
surface that may be queried and used as a source, without
generating a temporary file.
width_in_pointswidth of the surface, in points (1 point == 1/72.0 inch)
height_in_pointsheight of the surface, in points (1 point == 1/72.0 inch)
int get_document_unit()
Get the unit of the SVG surface.
the SVG unit of the SVG surface.
array(int) get_versions()
Used to retrieve the list of supported versions. See
restrict_to_version().
supported version list
void restrict_to_version(int version)
Restricts the generated SVG file to version. See
get_versions() for a list of available version values that
can be used here.
This function should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this function immediately after creating the surface.
versionSVG version
void set_document_unit(int unit)
Use the specified unit for the width and height of the generated SVG file.
This function can be called at any time before generating the SVG file.
However to minimize the risk of ambiguities it's recommended to call it before any drawing operations have been performed on the given surface, to make it clearer what the unit used in the drawing operations is.
The simplest way to do this is to call this function immediately after creating the SVG surface.
If this function is never called, the default unit for SVG documents generated by cairo will be user unit.
unitSVG unit
string version_to_string(int version)
Get the string representation of the given version id. This
function will return UNDEFINED if version isn't
valid. See get_versions() for a way to get the list of valid
version ids.
versiona version id
the string associated to given version.
ScaledFont represents a realization of a font face at a
particular size and transformation and a certain set of font
options
bool res = Cairo.ScaledFont() == x
Returns 1 if x is the same ScaledFont,
and 0 (zero) otherwise.
Cairo.ScaledFont Cairo.ScaledFont(FontFace font_face, Matrix font_matrix, Matrix ctm, FontOptions options)
Creates a ScaledFont object from a font face and matrices
that describe the size of the font and the environment in which
it will be used.
font_facea FontFace
font_matrixfont space to user space transformation matrix for the font.
In the simplest case of a N point font, this matrix is just a
scale by N, but it can also be used to shear the font or
stretch it unequally along the two axes. See
Context->set_font_matrix().
ctmuser to device transformation matrix with which the font will be used.
optionsoptions to use when getting metrics for the font and rendering with it.
array(float) extents()
Gets the metrics for a ScaledFont. Values are given in the
current user-space coordinate system.
Because font metrics are in user-space coordinates, they are
mostly, but not entirely, independent of the current
transformation matrix. If you call Context->scale(2.0, 2.0),
text will be drawn twice as big, but the reported text extents
will not be doubled. They will change slightly due to hinting
(so you can't assume that metrics are independent of the
transformation matrix), but otherwise will remain unchanged.
an array which stores the retrieved extents:
| Array | |
| ascent: the distance that the font extends above the baseline. Note that this is not always exactly equal to the maximum of the extents of all the glyphs in the font, but rather is picked to express the font designer's intent as to how the font should align with elements above it. |
| descent: the distance that the font extends below the baseline. This value is positive for typical fonts that include portions below the baseline. Note that this is not always exactly equal to the maximum of the extents of all the glyphs in the font, but rather is picked to express the font designer's intent as to how the font should align with elements below it. |
| height: the recommended vertical distance between baselines when setting consecutive lines of text with the font. This is greater than ascent + descent by a quantity known as the line spacing or external leading. When space is at a premium, most fonts can be set with only a distance of ascent + descent between lines. |
| max_x_advance: the maximum distance in the X direction that the origin is advanced for any glyph in the font. |
| max_y_advance: the maximum distance in the Y direction that the origin is advanced for any glyph in the font. This will be zero for normal fonts used for horizontal writing. (The scripts of East Asia are sometimes written vertically.) |
Matrix get_ctm()
Stores the CTM with which this ScaledFont was created into a
Matrix. Note that the translation offsets (x0, y0) of the
CTM are ignored by ScaledFont->create(). So, the matrix this
function returns always has 0,0 as x0,y0.
the matrix
FontFace get_font_face()
Gets the font face that this scaled font uses. This might be
the font face passed to create(), but this does not hold true
for all possible cases.
The FontFace with which scaled_font was created.
Matrix get_font_matrix()
Stores the font matrix with which this ScaledFont was created
into a Matrix.
the matrix
void get_font_options(FontOptions options)
Stores the font options with which this ScaledFont was
created into options.
optionsreturn value for the font options
Matrix get_scale_matrix()
Stores the scale matrix of this ScaledFont into a Matrix.
The scale matrix is product of the font matrix and the ctm
associated with the scaled font, and hence is the matrix mapping
from font space to device space.
the matrix
TextExtents glyph_extents(array(Glyph|array(int|float)) glyphs)
Gets the extents for an array of glyphs. The extents describe a
user-space rectangle that encloses the "inked" portion of the
glyphs, (as they would be drawn by Context->show_glyphs() if
the cairo graphics state were set to the same font_face,
font_matrix, ctm, and font_options as this ScaledFont).
Additionally, the x_advance and y_advance values indicate the
amount by which the current point would be advanced by
Context->show_glyphs().
Note that whitespace glyphs do not contribute to the size of the
rectangle (TextExtents->width and TextExtents->height).
glyphsan array of glyph IDs with X and Y offsets, with each glyph
being represented either as a Glyph object or as an array
having the following format:
| Array | |
| glyph index in the font. The exact interpretation of the glyph index depends on the font technology being used. |
| the offset in the X direction between the origin used for drawing the string and the origin of this glyph |
| the offset in the Y direction between the origin used for drawing the string and the origin of this glyph |
a TextExtents object which stores the retrieved extents.
TextExtents text_extents(string text)
Gets the extents for a string of text. The extents describe a
user-space rectangle that encloses the "inked" portion of the
text drawn at the origin (0,0) (as it would be drawn by
Context->show_text() if the cairo graphics state were set to
the same font_face, font_matrix, ctm, and font_options as this
ScaledFont). Additionally, the x_advance and y_advance
values indicate the amount by which the current point would be
advanced by Context->show_text().
Note that whitespace characters do not directly contribute to
the size of the rectangle (TextExtents->width and
TextExtents->height). They do contribute indirectly by
changing the position of non-whitespace characters. In
particular, trailing whitespace characters are likely to not
affect the size of the rectangle, though they will affect the
x_advance and y_advance values.
texta string of text
a TextExtents object which stores the retrieved extents.
array(array(Glyph)|array(TextCluster)|int) text_to_glyphs(float|int x, float|int y, string text)
Converts text to an array of glyphs, optionally with cluster
mapping, that can be used to render later using ScaledFont.
For details of how clusters, and cluster_flags map UTF-8 text to
the output glyphs see Context->show_text_glyphs().
The output values can be readily passed to
Context->show_text_glyphs(), Context->show_glyphs(), or
related functions, assuming that the exact same ScaledFont is
used for the operation.
xX position to place first glyph
yY position to place first glyph
texta string of text
An array with three elements
| Array | |
| array of glyphs |
| array of cluster mapping information |
| cluster flags corresponding to the output clusters |
Rendering to replayable scripts
inherit Device : Device
Cairo.ScriptDevice Cairo.ScriptDevice(string|Stdio.OutputStreamMixin script_file)
Creates a output device for emitting the script, used when creating the individual surfaces.
script_filethe name (path) of the file, or a Stdio.OutputStreamMixin,
to write the script to
void from_recording_surface(RecordingSurface recording_surface)
Converts the record operations in recording_surface into a
script.
recording_surfacethe recording surface to replay
int get_mode()
Queries the script for its current output mode.
the current output mode of the script
void set_mode(int mode)
Change the output mode of the script
modethe new mode
void write_comment(string(8bit) comment)
Emit a string verbatim into the script.
commentthe string to emit
Rendering to replayable scripts
inherit Surface : Surface
Cairo.ScriptSurface Cairo.ScriptSurface(ScriptDevice script, int content, float|int width, float|int height)
Create a new surface that will emit its rendering through script
scriptthe script (output device)
contentthe content of the surface
widthwidth in pixels
heightheight in pixels
Cairo.ScriptSurface Cairo.ScriptSurface(ScriptDevice script, Surface target)
Create a pxoy surface that will render to target and record the operations to device.
scriptthe script (output device)
targeta target surface to wrap
A solid (uniform) color. It may be opaque or translucent.
inherit Pattern : Pattern
Cairo.SolidPattern Cairo.SolidPattern(float red, float green, float blue, float|void alpha)
Creates a new Pattern corresponding to an opaque or
translucent color. The color components are floating point
numbers in the range 0 to 1. If the values passed in are
outside that range, they will be clamped.
redred component of the color
greengreen component of the color
blueblue component of the color
alphaalpha component of the color. If omitted the pattern will be opaque.
array(float) get_rgba()
Gets the solid color for a solid color pattern.
Note that the color and alpha values are not premultiplied.
An array with the components of the color
| Array | |
| red component of color |
| green component of color |
| blue component of color |
| alpha component of color |
Base class for surfaces
bool res = Cairo.Surface() == x
Returns 1 if x is the same Surface,
and 0 (zero) otherwise.
void copy_page()
Emits the current page for backends that support multiple pages,
but doesn't clear it, so that the contents of the current page
will be retained for the next page. Use show_page() if you
want to get an empty page after the emission.
There is a convenience function for this in Context, namely
Context->copy_page().
Surface create_for_rectangle(float|int x, float|int y, float|int width, float|int height)
Create a new surface that is a rectangle within the target surface. All operations drawn to this surface are then clipped and translated onto the target surface. Nothing drawn via this sub-surface outside of its bounds is drawn onto the target surface, making this a useful method for passing constrained child surfaces to library routines that draw directly onto the parent surface, i.e. with no further backend allocations, double buffering or copies.
The semantics of subsurfaces have not been finalized yet unless the rectangle is in full device units, is contained within the extents of the target surface, and the target or subsurface's device transforms are not changed.
xthe x-origin of the sub-surface from the top-left of the target surface (in device-space units)
ythe y-origin of the sub-surface from the top-left of the target surface (in device-space units)
widthwidth of the sub-surface (in device-space units)
heightheight of the sub-surface (in device-space units)
a newly allocated surface.
Surface create_similar(int content, int width, int height)
Create a new surface that is as compatible as possible with this surface. For example the new surface will have the same device scale, fallback resolution and font options as this. Generally, the new surface will also use the same backend, unless that is not possible for some reason.
Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.)
Use create_similar_image() if you need an image surface which
can be painted quickly to the target surface.
contentthe content for the new surface
widthwidth of the new surface, (in device-space units)
heightheight of the new surface (in device-space units)
a newly allocated surface.
Surface create_similar_image(int format, int width, int height)
Create a new image surface that is as compatible as possible for
uploading to and the use in conjunction with this surface.
However, this surface can still be used like any normal image
surface. Unlike create_similar() the new image surface won't
inherit the device scale from this.
Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.)
Use create_similar() if you don't need an image surface.
formatthe format for the new surface
widthwidth of the new surface, (in pixels)
heightheight of the new surface (in pixels)
a newly allocated image surface.
void finish()
This function finishes the surface and drops all references to
external resources. For example, for the Xlib backend it means
that cairo will no longer access the drawable, which can be
freed. After calling finish() the only valid operations on a
surface are checking status, getting and setting user,
referencing and destroying, and flushing and finishing it.
Further drawing to the surface will not affect the surface but
will instead trigger a STATUS_SURFACE_FINISHED error.
When the reference count of the Surface decreases to zero,
cairo will call finish() if it hasn't been called already,
before freeing the resources associated with the surface.
void flush()
Do any pending drawing for the surface and also restore any temporary modifications cairo has made to the surface's state. This function must be called before switching from drawing on the surface with cairo to drawing on it directly with native APIs, or accessing its memory outside of Cairo. If the surface doesn't support direct access, then this function does nothing.
int get_content()
This function returns the content type of surface which indicates whether the surface contains color and/or alpha information.
The content type of surface .
Device get_device()
This function returns the device for a surface. See Device.
The device for this surface or UNDEFINED if the
surface does not have an associated device.
array(float) get_device_offset()
This function returns the previous device offset set by
set_device_offset().
The device offset
| Array | |
| the offset in the X direction, in device units |
| the offset in the Y direction, in device units |
array(float) get_device_scale()
This function returns the previous device scale set by
set_device_scale().
The device scale
| Array | |
| the scale in the X direction, in device units |
| the scale in the Y direction, in device units |
array(float) get_fallback_resolution()
This function returns the previous fallback resolution set by
set_fallback_resolution(), or default fallback resolution if
never set.
The fallback resolution
| Array | |
| horizontal pixels per inch |
| vertical pixels per inch |
void get_font_options(FontOptions options)
Retrieves the default font rendering options for the surface.
This allows display surfaces to report the correct subpixel
order for rendering on them, print surfaces to disable hinting
of metrics and so forth. The result can then be used with
ScaledFont->create().
optionsa FontOptions object into which to store the retrieved
options. All existing values are overwritten
string(8bit)|zero get_mime_data(string(7bit) mime_type)
Return mime data previously attached to surface using the
specified mime type. If no data has been attached with the
given mime type, UNDEFINED is returned.
mime_typethe mime type of the image data
the image data attached to the surface
bool has_show_text_glyphs()
Returns whether the surface supports sophisticated
Context->show_text_glyphs() operations. That is, whether it
actually uses the provided text and cluster data to a
Context->show_text_glyphs() call.
Even if this function returns 0, a
Context->show_text_glyphs() operation targeted at this
surface will still succeed. It just will act like a
Context->show_glyphs() operation. Users can use this
function to avoid computing UTF-8 text and cluster mapping if
the target surface does not use it.
1 if surface supports Context->show_text_glyphs(),
0 otherwise
Surface map_to_image(RectangleInt|void extents)
Returns an image surface that is the most efficient mechanism for modifying the backing store of the target surface. The region retrieved may be limited to the extents, or the whole surface if no extents are given.
The use of the original surface as a target or source whilst
it is mapped is undefined. The result of mapping the surface
multiple times is undefined. Destroying or calling
finish() on the resulting image surface results in
undefined behavior. Changing the device transform of the
image surface or of surface before the image surface is
unmapped results in undefined behavior.
extentslimit the extraction to an rectangular region
a newly allocated image surface. The caller must use
unmap_image() to destroy this image surface.
void mark_dirty()
Tells cairo that drawing has been done to surface using means
other than cairo, and that cairo should reread any cached areas.
Note that you must call flush() before doing such drawing.
void mark_dirty_rectangle(int x, int y, int width, int height)
Like mark_dirty(), but drawing has been done only to the
specified rectangle, so that cairo can retain cached contents
for other parts of the surface.
Any cached clip set on the surface will be reset by this function, to make sure that future cairo calls have the clip set that they expect.
xX coordinate of dirty rectangle
yY coordinate of dirty rectangle
widthwidth of dirty rectangle
heightheight of dirty rectangle
void set_device_offset(float|int x_offset, float|int y_offset)
Sets an offset that is added to the device coordinates
determined by the CTM when drawing to surface. One use case for
this function is when we want to create a Surface that
redirects drawing for a portion of an onscreen surface to an
offscreen surface in a way that is completely invisible to the
user of the cairo API. Setting a transformation via
Context->translate() isn't sufficient to do this, since
functions like Context->device_to_user() will expose the
hidden offset.
Note that the offset affects drawing to the surface as well as using the surface in a source pattern.
x_offsetthe offset in the X direction, in device units
y_offsetthe offset in the Y direction, in device units
void set_device_scale(float|int x_scale, float|int y_scale)
Sets a scale that is multiplied to the device coordinates
determined by the CTM when drawing to this surface. One common
use for this is to render to very high resolution display
devices at a scale factor, so that code that assumes 1 pixel
will be a certain size will still work. Setting a
transformation via Context->scale() isn't sufficient to do
this, since functions like Context->device_to_user() will
expose the hidden scale.
Note that the scale affects drawing to the surface as well as using the surface in a source pattern.
x_scalea scale factor in the X direction
y_scalea scale factor in the Y direction
void set_fallback_resolution(float|int x_pixels_per_inch, float|int y_pixels_per_inch)
Set the horizontal and vertical resolution for image fallbacks.
When certain operations aren't supported natively by a backend, cairo will fallback by rendering operations to an image and then overlaying that image onto the output. For backends that are natively vector-oriented, this function can be used to set the resolution used for these image fallbacks, (larger values will result in more detailed images, but also larger file sizes).
Some examples of natively vector-oriented backends are the ps, pdf, and svg backends.
For backends that are natively raster-oriented, image fallbacks are still possible, but they are always performed at the native device resolution. So this function has no effect on those backends.
The fallback resolution only takes effect at the time of
completing a page (with Context->show_page() or
Context->copy_page()) so there is currently no way to have
more than one fallback resolution in effect on a single page.
The default fallback resolution is 300 pixels per inch in both dimensions.
x_pixels_per_inchhorizontal setting for pixels per inch
y_pixels_per_inchvertical setting for pixels per inch
void set_mime_data(string(7bit) mime_type, string(8bit)|zero data)
Attach an image in the format mime_type to surface. To remove
the data from a surface, call this function with same mime type
and 0 for data.
The attached image (or filename) data can later be used by backends which support it (currently: PDF, PS, SVG and Win32 Printing surfaces) to emit this data instead of making a snapshot of the surface. This approach tends to be faster and requires less memory and disk space.
The recognized MIME types are the following: MIME_TYPE_JPEG,
MIME_TYPE_PNG, MIME_TYPE_JP2, MIME_TYPE_URI,
MIME_TYPE_UNIQUE_ID, MIME_TYPE_JBIG2,
MIME_TYPE_JBIG2_GLOBAL, MIME_TYPE_JBIG2_GLOBAL_ID,
MIME_TYPE_CCITT_FAX, MIME_TYPE_CCITT_FAX_PARAMS.
See corresponding backend surface docs for details about which MIME types it can handle. Caution: the associated MIME data will be discarded if you draw on the surface afterwards. Use this function with care.
Even if a backend supports a MIME type, that does not mean cairo will always be able to use the attached MIME data. For example, if the backend does not natively support the compositing operation used to apply the MIME data to the backend. In that case, the MIME data will be ignored. Therefore, to apply an image in all cases, it is best to create an image surface which contains the decoded image data and then attach the MIME data to that. This ensures the image will always be used while still allowing the MIME data to be used whenever possible.
mime_typethe MIME type of the image data
datathe image data to attach to the surface
void show_page()
Emits and clears the current page for backends that support
multiple pages. Use copy_page() if you don't want to clear
the page.
There is a convenience function for this in Context, namely
Context->show_page().
bool supports_mime_type(string(7bit) mime_type)
Return whether surface supports mime_type.
mime_typethe mime type
1 if surface supports mime_type, 0 otherwise
void unmap_image(Surface image)
Unmaps the image surface as returned from map_to_image().
The content of the image will be uploaded to the target surface. Afterwards, the image is destroyed.
Using an image surface which wasn't returned by
map_to_image() results in undefined behavior.
imagethe currently mapped image
A pattern based on a surface (an image).
inherit Pattern : Pattern
Cairo.SurfacePattern Cairo.SurfacePattern(Surface target)
Create a new Pattern for the given surface.
surfacethe surface
Surface get_surface()
Gets the surface of a SurfacePattern.
surface of pattern
Redirect input to multiple surfaces
inherit Surface : Surface
void add(array(Surface) target)
Adds a new target surface to the list of replicas of a tee surface.
targetthe surface to add
Cairo.TeeSurface Cairo.TeeSurface(Surface primary)
Creates a new "tee" surface.
The primary surface is used when querying surface options, like font options and extents.
Operations performed on the tee surface will be replayed on any surface added to it.
primarythe primary Surface
Surface index(int(0..) index)
Retrieves the replica surface at the given index.
The primary surface used to create the cairo_tee_surface_t is always set at the zero index.
indexthe index of the replica to retrieve
the surface at the given index
void remove(Surface target)
Removes the given surface from the list of replicas of a tee surface.
targetthe surface to remove
Holds information about a single text cluster. A text cluster is a minimal mapping of some glyphs corresponding to some UTF-8 text.
For a cluster to be valid, both num_bytes and num_glyphs
should be non-negative, and at least one should be non-zero. Note
that clusters with zero glyphs are not as well supported as normal
clusters. For example, PDF rendering applications typically
ignore those clusters when PDF text is being selected.
See Context->show_text_glyphs() for how clusters are used in
advanced text operations.
int Cairo.TextCluster.num_bytes
the number of bytes of UTF-8 text covered by cluster
int Cairo.TextCluster.num_glyphs
the number of glyphs covered by cluster
string sprintf(string format, ... Cairo.TextCluster arg ... )
Cairo.TextCluster Cairo.TextCluster(int num_bytes, int num_glyphs)
num_bytesthe number of bytes of UTF-8 text covered by cluster
num_glyphsthe number of glyphs covered by cluster
Stores the extents of a single glyph or a string of glyphs in
user-space coordinates. Because text extents are in user-space
coordinates, they are mostly, but not entirely, independent of the
current transformation matrix. If you call
Context->scale(2.0, 2.0), text will be drawn twice as big, but
the reported text extents will not be doubled. They will change
slightly due to hinting (so you can't assume that metrics are
independent of the transformation matrix), but otherwise will
remain unchanged.
float Cairo.TextExtents.height
height of the glyphs as drawn
float Cairo.TextExtents.width
width of the glyphs as drawn
float Cairo.TextExtents.x_advance
distance to advance in the X direction after drawing these glyphs
float Cairo.TextExtents.x_bearing
the horizontal distance from the origin to the leftmost part of the glyphs as drawn. Positive if the glyphs lie entirely to the right of the origin.
float Cairo.TextExtents.y_advance
distance to advance in the Y direction after drawing these glyphs. Will typically be zero except for vertical text layout as found in East-Asian languages.
float Cairo.TextExtents.y_bearing
the vertical distance from the origin to the topmost part of the glyphs as drawn. Positive only if the glyphs lie completely below the origin; will usually be negative.
Font faces used in implementation of the Context "toy" font
API.
inherit FontFace : FontFace
Cairo.ToyFontFace Cairo.ToyFontFace(string family, int slant, int weight)
Creates a font face from a triplet of family, slant, and weight.
If family is the zero-length string "", the platform-specific
default family is assumed. The default family then can be
queried using get_family().
The Context->select_font_face() function uses this to create
font faces. See that function for limitations and other details
of toy font faces.
familya font family name
slantthe slant for the font
weightthe weight for the font
string get_family()
Gets the family name of a toy font.
The family name.
int get_slant()
Gets the slant a toy font.
The slant value
int get_weight()
Gets the weight a toy font.
The weight value
X Window System rendering using the XCB library
inherit Surface : Surface
void set_size(int width, int height)
Informs cairo of the new size of the XCB drawable underlying the surface. For a surface created for a window (rather than a pixmap), this function must be called each time the size of the window changes. (For a subwindow, you are normally resizing the window yourself, but for a toplevel window, it is necessary to listen for ConfigureNotify events.)
A pixmap can never change size, so it is never necessary to call this function on a surface created for a pixmap.
If flush() wasn't called, some pending operations might be
discarded.
widththe new width of the surface
heightthe new height of the surface
X Window System rendering using XLib
inherit Surface : Surface
int get_depth()
Get the number of bits used to represent each pixel value.
the depth of the surface in bits.
int get_height()
Get the height of the X Drawable underlying the surface in pixels.
the height of the surface in pixels.
int get_width()
Get the width of the X Drawable underlying the surface in pixels.
the width of the surface in pixels.
The CommonLog module is used to parse the lines in a www server's logfile, which must be in "common log" format -- such as used by default for the access log by Roxen, Caudium, Apache et al.
int read(function(array(int|string), int:void) callback, Stdio.File|string logfile, void|int offset)
Reads the log file and calls the callback function for every parsed line. For lines that fails to be parsed the callback is not called not is any error thrown. The number of bytes read are returned.
callbackThe callbacks first argument is an array with the different parts of the log entry.
| Array | |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| One of "GET", "POST", "HEAD" etc. |
| |
| E.g. "HTTP/1.0" |
| One of 200, 404 etc. |
| |
The second callback argument is the current offset to the end of the current line.
logfileThe logfile to parse. Either an open Stdio.File object, or
a string with the path to the logfile.
offsetThe absolute position in the file where the parser should begin.
Note that the offset defaults to 0 (zero), NOT the current offset
of logfile.
Implements Digital Video Broadcasting interface
Only Linux version is supported.
Object for controlling an audio subsystem on full featured cards.
DVB.Audio DVB.Audio(int card_number)
DVB.Audio DVB.Audio()
Create a Audio object.
card_numberThe number of card equipment.
int mixer(int left, int right)
int mixer(int both)
Sets output level on DVB audio device.
mute()
int mute(int mute)
int mute()
Mute or unmute audio device.
mixer()
mapping status()
Returns mapping of current audio device status.
Represents an elementary data stream (PES).
int _destruct()
Purge a stream reader.
DVB.dvb()->stream(), read()
void close()
Closes an open stream.
read()
string|int read()
Read data from a stream. It reads up to read buffer size data.
Read buffer size is 4096 by default.
DVB.dvb()->stream(), close()
int set_buffer(int len)
Sets stream's internal buffer.
The size is 4096 by default.
read()
Main class.
mapping analyze_pat()
Return mapping of all PMT.
sid:prognum
array(mapping)|int analyze_pmt(int sid, int prognum)
Parse PMT table.
analyze_pat()
DVB.dvb DVB.dvb(int card_number)
Create a DVB object.
card_numberThe number of card equipment.
The number specifies which device will be opened. Ie. /dev/ost/demux0, /dev/ost/demux1 ... for DVB v0.9.4 or /dev/dvb/demux0, /dev/dvb/demux1 ... for versions 2.0+
mapping fe_info()
Return info of a frondend device.
The information heavily depends on driver. Many fields contain dumb values.
mapping|int fe_status()
Return status of a DVB object's frondend device.
The resulting mapping contains the following fields:
| If 1 the frontend is powered up and is ready to be used. |
| If 1 the frontend detects a signal above a normal noise level |
| If 1 the frontend successfully locked to a DVB signal |
| If 1 carrier dectected in signal |
| If 1 then lock at viterbi state |
| If 1 then TS sync byte detected |
| If 1 then tuner has a frequency lock |
mapping|int get_pids()
Returns mapping with info of currently tuned program's pids.
tune()
DVB.Stream stream(int pid, int|function(:void) rcb, int ptype)
DVB.Stream stream(int pid, int|function(:void) rcb)
DVB.Stream stream(int pid)
Create a new stream reader object for PID.
pidPID of stream.
rcbCallback function called whenever there is the data to read from stream. Only for nonblocking mode.
ptypeType of payload data to read. By default, audio data is fetched.
Setting async callback doesn't set the object to nonblocking state.
DVB.Stream()->read()
int tune(int(2bit) lnb, int freq, bool|string pol, int sr)
Tunes to apropriate transponder's parameters.
lnbDiSeQc number of LNB.
freqFrequency divided by 1000.
polPolarization. 0 or "v" for vertical type,
1 or "h" for horizontal one.
srThe service rate parameter.
inherit _Debug : _Debug
mapping Debug.globals
Can be custom filled from within your program in order to
have global references to explore live datastructures using
Inspect; comes preinitialised with the empty mapping, ready for use.
void add_to_perf_map(program p)
Updates the perf map file with new program p.
generate_perf_map()
Expects generate_perf_map() to have been called before.
int(0..) assembler_debug(int(0..) level)
Set the assembler debug level.
The old assembler debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
int(0..) compiler_trace(int(0..) level)
Set the compiler trace level.
The old compiler trace level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
mapping(string:int) count_objects()
Returns the number of objects of every kind in memory.
int(0..) debug(int(0..) level)
Set the run-time debug level.
The old debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
mixed describe(mixed x)
Prints out a description of the thing x to standard error.
The description contains various internal info associated with
x.
This function only exists if the Pike runtime has been compiled with RTL debug.
int describe_encoded_value(string data)
Describe the contents of an encode_value() string.
Returns the number of encoding errors that were detected (if any).
array(array(int|string|type)) describe_program(program p)
Debug function for showing the symbol table of a program.
Returns an array of arrays with the following information
for each symbol in p:
| Array | |
| Bitfield with the modifiers for the symbol. |
| Name of the symbol. |
| Value type for the symbol. |
| Type of symbol. |
| Offset into the code or data area for the symbol. |
| Offset in the inherit table to the inherit containing the symbol. |
| Depth in the inherit tree for the inherit containing the symbol. |
The API for this function is not fixed, and has changed since Pike 7.6. In particular it would make sense to return an array of objects instead, and more information about the symbols might be added.
void disassemble(function(:void) fun)
Disassemble a Pike function to Stdio.stderr.
This function is only available if the Pike runtime has been compiled with debug enabled.
void dmalloc_set_name()
Only available when compiled with dmalloc.
void dmalloc_set_name(string filename, int(1..) linenumber)
Only available when compiled with dmalloc.
void dump_backlog()
Dumps the 1024 latest executed opcodes, along with the source
code lines, to standard error. The backlog is only collected on
debug level 1 or higher, set with _debug or with the -d
argument on the command line.
This function only exists if the Pike runtime has been compiled with RTL debug.
void dump_dmalloc_locations(string|array|mapping|multiset|function(:void)|object|program|type o)
Only available when compiled with dmalloc.
void dump_program_tables(program p, int(0..)|void indent)
Dumps the internal tables for the program p on stderr.
pProgram to dump.
indentNumber of spaces to indent the output.
array(object) find_all_clones(program p, bool|void include_subclasses)
Return an array with all objects that are clones of p.
pProgram that the objects should be a clone of.
include_subclassesIf true, include also objects that are clones of programs
that have inherited p. Note that this adds significant
overhead.
This function is only intended to be used for debug purposes.
map_all_objects()
void gc_set_watch(array|multiset|mapping|object|function(:void)|program|string x)
Sets a watch on the given thing, so that the gc will print a message whenever it's encountered. Intended to be used together with breakpoints to debug the garbage collector.
This function only exists if the Pike runtime has been compiled with RTL debug.
mapping(string:int|float) gc_status()
Get statistics from the garbage collector.
A mapping with the following content will be returned:
| Number of arrays, mappings, multisets, objects and programs. |
| Number of memory allocations since the last gc run. |
| Threshold for "num_allocs" when another automatic gc run is scheduled. |
| Estimation of the current amount of garbage. |
| Decaying average over the number of allocated objects between gc runs. |
| Decaying average over the number of freed objects in each gc run. |
| Garbage ratio in the last gc run. |
| Decaying average over the interval between gc runs, measured in real time nanoseconds. |
| Decaying average over the length of the gc runs, measured in real time nanoseconds. |
| The garbage accumulation goal that the gc aimed for when
setting "alloc_threshold" in the last run. The value is
either "garbage_ratio_low", "garbage_ratio_high" or
"garbage_max_interval". The first two correspond to the gc
parameters with the same names in |
| Time when the garbage-collector last ran. |
| The total amount of CPU time that has been consumed in implicit GC runs, in nanoseconds. 0 on systems where Pike lacks support for CPU time measurement. |
| The total amount of real time that has been spent in implicit GC runs, in nanoseconds. |
gc(), Pike.gc_parameters(), Pike.implicit_gc_real_time
void generate_perf_map()
Generates a perf map file of all Pike code and writes it to
/tmp/perf-<pid>.map. This is useful only if pike has been
compiled with machine code support. It allows the linux perf tool to
determine the correct name of Pike functions that were compiled to
machine code by pike.
mapping(string:int) get_program_layout(program p)
Returns a mapping which describes the layout of compiled machine
code in the program p. The indices of the returned mapping
are function names, the values the starting address of the compiled
function. The total size of the program code is stored with index
0.
void hexdump(string(8bit) raw)
Write a hexadecimal dump of the contents of raw to Stdio.stderr.
void list_open_fds()
Only available when compiled with dmalloc.
mixed locate_references(string|array|mapping|multiset|function(:void)|object|program|type o)
This function is mostly intended for debugging. It will search through
all data structures in Pike looking for o and print the
locations on stderr. o can be anything but int or
float.
This function only exists if the Pike runtime has been compiled with RTL debug.
int(0..) map_all_objects(function(object:void) cb)
Call cb for all objects that currently exist. The callback will not be called with destructed objects as it's argument.
Objects might be missed if cb creates new objects or destroys
old ones.
This function is only intended to be used for debug purposes.
The total number of objects
next_object(), find_all_clones()
int(0..) map_all_programs(function(program:void) cb)
Call cb for all programs that currently exist.
Programs might be missed if cb creates new programs.
This function is only intended to be used for debug purposes.
The total number of programs
map_all_objects()
int(0..) map_all_strings(function(string:void) cb)
Call cb for all strings that currently exist.
strings might be missed if cb creates new strings or destroys
old ones.
This function is only intended to be used for debug purposes.
The total number of strings
next_object()
mapping(string:int) memory_usage()
Check memory usage.
This function is mostly intended for debugging. It delivers a mapping with information about how many arrays/mappings/strings etc. there are currently allocated and how much memory they use.
The entries in the mapping are typically paired, with one
named "num_" + SYMBOL + "s" containing a count,
and the other named SYMBOL + "_bytes" containing
a best effort approximation of the size in bytes.
Exactly what fields this function returns is version dependant.
_verify_internals()
mixed next(mixed x)
Find the next object/array/mapping/multiset/program or string.
All objects, arrays, mappings, multisets, programs and strings are stored in linked lists inside Pike. This function returns the next item on the corresponding list. It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.
next_object(), prev()
object next_object(object o)
object next_object()
Returns the next object from the list of all objects.
All objects are stored in a linked list.
If no arguments have been given next_object() will return the first
object from the list.
If o has been specified the object after o on the list will be
returned.
This function is not recomended to use.
destruct()
int(0..) optimizer_debug(int(0..) level)
Set the optimizer debug level.
The old optimizer debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
string pp_memory_usage()
Returns a pretty printed version of the
output from memory_usage.
string pp_object_usage()
Returns a pretty printed version of the output from
count_objects (with added estimated RAM usage)
mixed prev(mixed x)
Find the previous object/array/mapping/multiset or program.
All objects, arrays, mappings, multisets and programs are stored in linked lists inside Pike. This function returns the previous item on the corresponding list. It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.
Unlike next() this function does not work on strings.
next_object(), next()
int refs(string|array|mapping|multiset|function(:void)|object|program o)
Return the number of references o has.
It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.
Note that the number of references will always be at least one since the value is located on the stack when this function is executed.
next(), prev()
void remove_from_perf_map(program p)
Removed p from the perf map file.
void reset_dmalloc()
Only available when compiled with dmalloc.
int size_object(object o)
Return the aproximate size of the object, in bytes. This might not work very well for native objects
The function tries to estimate the memory usage of variables belonging to the object.
It will not, however, include the size of objects assigned to variables in the object.
If the object has a lfun::_size_object() it will be called
without arguments, and the return value will be added to the final
size. It is primarily intended to be used by C-objects that
allocate memory that is not normally visible to pike.
lfun::_size_object(), sizeof()
void verify_internals()
Perform sanity checks.
This function goes through most of the internal Pike structures and generates a fatal error if one of them is found to be out of order. It is only used for debugging.
This function does a more thorough check if the Pike runtime has been compiled with RTL debug.
constant Debug.FP_SNAN
constant Debug.FP_QNAN
constant Debug.FP_NINF
constant Debug.FP_PINF
constant Debug.FP_ZERO
constant Debug.FP_PZERO
constant Debug.FP_NZERO
constant Debug.TAG_DELAYED
constant Debug.TAG_AGAIN
constant Debug.TAG_ARRAY
constant Debug.TAG_MAPPING
constant Debug.TAG_MULTISET
constant Debug.TAG_OBJECT
constant Debug.TAG_FUNCTION
constant Debug.TAG_PROGRAM
constant Debug.TAG_STRING
constant Debug.TAG_FLOAT
constant Debug.TAG_INT
constant Debug.TAG_TYPE
constant Debug.TAG_NEG
constant Debug.TAG_SMALL
constant Debug.ID_ENTRY_TYPE_CONSTANT
constant Debug.ID_ENTRY_EFUN_CONSTANT
constant Debug.ID_ENTRY_RAW
constant Debug.ID_ENTRY_EOT
constant Debug.ID_ENTRY_VARIABLE
constant Debug.ID_ENTRY_FUNCTION
constant Debug.ID_ENTRY_CONSTANT
constant Debug.ID_ENTRY_INHERIT
constant Debug.ID_ENTRY_ALIAS
constant Debug.T_ATTRIBUTE
constant Debug.T_NSTRING
constant Debug.T_NAME
constant Debug.T_SCOPE
constant Debug.T_ASSIGN
constant Debug.T_UNKNOWN
constant Debug.T_MIXED
constant Debug.T_NOT
constant Debug.T_AND
constant Debug.T_OR
constant Debug.T_ARRAY
constant Debug.T_MAPPING
constant Debug.T_MULTISET
constant Debug.T_OBJECT
constant Debug.T_FUNCTION
constant Debug.T_PROGRAM
constant Debug.T_STRING
constant Debug.T_TYPE
constant Debug.T_VOID
constant Debug.T_MANY
constant Debug.T_INT
constant Debug.T_FLOAT
constant Debug.T_ZERO
Stdio.Buffer Debug.Decoder.input
protected local void __create__(Stdio.Buffer input)
Debug.Decoder Debug.Decoder(Stdio.Buffer input)
Allows for interactive debugging and live data structure inspection
in both single- and multi-threaded programs.
Creates an independent background thread that every pollinterval
will show a list of running threads.
Optionally, a triggersignal can be specified which allows the dump to
be triggered by a signal.
Example: In the program you'd like to inspect, insert the following one-liner:
Debug.Inspect("/tmp/test.pike");
Then start the program and keep it running. Next you create a /tmp/test.pike with the following content:
void create() {
werror("Only once per modification of test.pike\n");
}
int main() {
werror("This will run every iteration\n");
werror("By returning 1 here, we disable the stacktrace dumps\n");
return 0;
}
void _destruct() {
werror("_destruct() runs just as often as create()\n");
}
Whenever you edit /tmp/test.pike, it will automatically reload the file.
string|function(void:void) Debug.Inspect._callback
Either the callback function which is invoked on each iteration, or the name of a file which contains a class which is (re)compiled automatically and called on each iteration.
create
Thread.Thread Debug.Inspect._loopthread
The inspect-thread. It will not appear in the displayed thread-list.
int Debug.Inspect.pollinterval
The polling interval in seconds, defaults to 4.
int Debug.Inspect.triggersignal
If assigned to, it will allow the diagnostics inspection to be triggered by this signal.
Debug.Inspect Debug.Inspect(string|function(void:void)|void cb)
Starts up the background thread.
cbSpecifies either the callback function which is invoked on each iteration,
or the
name of a file which contains a class which is (re)compiled automatically
with an optional main() method, which will be called on each
iteration.
If the main() method returns 0, new stacktraces will be dumped
every iteration; if it returns 1, stacktrace dumping will be suppressed.
The compilation and the running of the callback is guarded by a catch(), so that failures (to compile) in that section will not interfere with the running program.
If the list of running threads did not change, displaying the list again will be suppressed.
triggersignal, pollinterval, _loopthread, _callback,
Debug.globals
void inspect()
The internal function which does all the work each pollinterval. Run it directly to force a thread-dump.
Allows for rapid collection of logdata, which is then fed to the real werror() at idle moments. This allows for logging to occur with minimal timing interference.
void werror(string format, mixed ... args)
Overloads the predef::werror() function
to allow floods of logentries while introducing minimal latency.
Logs are buffered, and periodically flushed from another thread.
If the arrival rate of logs is excessive, it simply skips
part of the logs to keep up.
When parts are skipped, records are skipped in whole and will never be split up.
werror_options()
void werror_options(int options, void|int pollinterval, void|int drainrate, void|int maxbufentries)
optionsDefaults to 0, reserved for future enhancements.
pollintervalPollinterval in seconds for the log-flush thread; defaults to 1.
Logs will only be flushed out, if during the last pollinterval
no new logs have been added.
drainrateMaximum number of lines per second that will be dumped to stderr.
Defaults to 10.
maxbufentriesMaximum number of buffered logrecords which have not been flushed to stderr
yet. If this number is exceeded, the oldest maxbufentries/2 entries
will be skipped; a notice to that effect is logged to stderr.
werror()
This is a probe subject which you can send in somewhere to get probed (not to be confused with a probe object, which does some active probing). All calls to LFUNs will be printed to stderr. It is possible to name the subject by passing a string as the first and only argument when creating the subject object.
> object s = Debug.Subject(); create() > random(s); _random() (1) Result: 0 > abs(s); `<(0) _sprintf(79, ([ ])) (2) Result: Debug.Subject > abs(class { inherit Debug.Subject; int `<(mixed ... args) { return 1; } }()); create() `-() _destruct() (3) Result: 0 > pow(s,2); `[]("pow") Attempt to call the NULL-value Unknown program: 0(2)
A class that when instatiated will turn on trace, and when it's destroyed will turn it off again.
Debug.Tracer Debug.Tracer(int level)
Sets the level of debug trace to level.
This wrapper can be placed around another object to get printouts about what is happening to it. Only a few LFUNs are currently supported.
> object x=Debug.Wrapper(Crypto.MD5()); Debug.Wrapper is proxying ___Nettle.MD5_State() > x->name(); ___Nettle.MD5_State()->name (1) Result: "md5" > !x; !___Nettle.MD5_State() (2) Result: 0
array indices( Debug.Wrapper arg )
int sizeof( Debug.Wrapper arg )
string sprintf(string format, ... Debug.Wrapper arg ... )
array values( Debug.Wrapper arg )
bool res = !Debug.Wrapper()
mixed res = Debug.Wrapper()->X
mixed res = Debug.Wrapper()[ x ]
Debug.Wrapper Debug.Wrapper(object x)
void display(int|void num, string|array(string)|void pattern, string|array(string)|void exclude)
Show profiling information in a more-or-less readable manner. This only works if pike has been compiled with profiling support.
The function will print to stderr using werror.
This is mainly here for use from the Debug.Watchdog class, if
you want to do your own formatting or output to some other channel
use get_prof_info instead.
array(array(string|float|int)) get_prof_info(string|array(string)|void include, string|array(string)|void exclude)
Collect profiling data.
This will return the CPU usage, by function, since the last time the function was called.
The returned array contains the following entries per entry:
| Array | |
| The name of the function. |
| The number of calls. |
| Total self CPU time in milliseconds. |
| Total self CPU time in milliseconds, including children. |
| Average self CPU time in microseconds. |
| Average self CPU time in microseconds, including children. |
| The self CPU time as percentage of total time. |
| The self CPU time, including children, as percentage of total time. |
| Function's definition source location. |
The CompilerEnvironment object that is used
for loading C-modules and by predef::compile().
predef::compile() is essentially an alias for the
CompilerEnvironment()->compile() in this object.
CompilerEnvironment, predef::compile()
inherit CompilerEnvironment : CompilerEnvironment
object mkerror(mixed error)
Returns an Error object for any argument it receives. If the argument already is an Error object or is empty, it does nothing.
Class for exception objects for errors of unspecified type.
array(backtrace_frame|array(mixed)) Error.Generic.error_backtrace
The backtrace as returned by backtrace where the error
occurred.
Code that catches and rethrows errors should ensure that this remains the same in the rethrown error.
string Error.Generic.error_message
The error message. It always ends with a newline ('\n')
character and it might be more than one line.
Code that catches and rethrows errors may extend this with more error information.
bool res = is_type(Error.Generic())
Claims that the error object is an array, for compatibility with old style error handling code.
string sprintf(string format, ... Error.Generic arg ... )
array|string res = Error.Generic()[ index ]
Index operator.
Simulates an array
| Array | |
| Error message as returned by |
| Backtrace as returned by |
The error message is always terminated with a newline.
backtrace()
array backtrace()
Return the backtrace where the error occurred. Normally simply
returns error_backtrace.
predef::backtrace()
(array)Error.Generic()
Cast operator.
The only supported type to cast to is "array", which
generates an old-style error ({.message(),
backtrace()})
Error.Generic Error.Generic(string message, void|array(backtrace_frame|array(mixed)) backtrace)
string describe()
Return a readable error report that includes the backtrace.
string message()
Return a readable message describing the error. Normally simply
returns error_message.
If you override this function then you should ensure that
error_message is included in the returned message, since there
might be code that catches your error objects, extends
error_message with more info, and rethrows the error.
protected function(:void) `()(void|string path)
FIXME: Document this function
program get_filesystem(string what)
FIXME: Document this function
int parse_mode(int old, int|string mode)
FIXME: Document this function
Baseclass that can be extended to create new filesystems. Is used by the Tar and System filesystem classes.
int apply()
FIXME: Document this function
Base cd(string|void directory)
Change directory within the filesystem. Returns a new filesystem object with the given directory as cwd.
void chmod(string filename, int|string mode)
Change mode of a file or directory.
void chown(string filename, int|object owner, int|object group)
Change ownership of the file or directory
Base chroot(void|string directory)
Change the root of the filesystem.
string cwd()
Returns the current working directory within the filesystem.
array find(void|function(Stat:int) mask, mixed ... extra)
FIXME: Document this function
array(string) get_dir(void|string directory, void|string|array glob)
Returns an array of all files and directories within a given directory.
directoryDirectory where the search should be made within the filesystem. CWD is assumed if none (or 0) is given.
globReturn only files and dirs matching the glob (if given).
[get_stats]
array(Stat) get_stats(void|string directory, void|string|array glob)
Returns stat-objects for the files and directories matching the given glob within the given directory.
[get_dir]
int mkdir(string directory, void|int|string mode)
Create a new directory
Stdio.File open(string filename, string mode)
Open a file within the filesystem
A Stdio.File object.
int rm(string filename)
Remove a file from the filesystem.
Stat stat(string file, int|void lstat)
Return a stat-object for a file or a directory within the filesystem.
Describes the stat of a file
bool Filesystem.Stat.isblk
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool Filesystem.Stat.ischr
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool Filesystem.Stat.isdir
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool Filesystem.Stat.isdoor
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool Filesystem.Stat.isfifo
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool Filesystem.Stat.islnk
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool Filesystem.Stat.isreg
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
bool Filesystem.Stat.issock
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
Read only
void attach_statarray(array(int) a)
Fills the stat-object with data from a Stdio.File.stat() call.
object|zero cd()
Change to the stated directory.
the directory if the stated object was a directory, 0 otherwise.
string nice_date()
Returns the date of the stated object as cleartext.
Stdio.File open(string mode)
Open the stated file within the filesystem
a [Stdio.File] object
[Stdio.File]
void set_type(string x)
Set a type for the stat-object.
This call doesnot change the filetype in the underlaying filesystem.
xType to set. Type is one of the following:
[isfifo], [ischr], [isdir], [isblk], [isreg], [islnk], [issock], [isdoor]
Implements an abstraction of the normal filesystem.
inherit Filesystem.Base : Base
Filesystem.System Filesystem.System(void|string directory, void|string root, void|int fast, void|Filesystem.Base parent)
Instanciate a new object representing the filesystem.
directoryThe directory (in the real filesystem) that should become the root of the filesystemobject.
rootInternal
fastInternal
parentInternal
Iterator object that traverses a directory tree and returns files as values and paths as indices. Example that uses the iterator to create a really simple sort of make:
object i=Filesystem.Traversion("."); foreach(i; string dir; string file) { if(!has_suffix(file, ".c")) continue; file = dir+file; string ofile = file; ofile[-1]='o'; object s=file_stat(ofile); if(s && i->stat()->mtime<s->mtime) continue; // compile file }
Filesystem.Traversion Filesystem.Traversion(string path, void|bool symlink, void|bool ignore_errors, void|function(array:array) sort_fun)
pathThe root path from which to traverse.
symlinkDon't traverse symlink directories.
ignore_errorsIgnore directories that can not be accessed.
sort_funSort function to be applied to directory entries before traversing. Can also be a filter function.
float progress(void|float share)
Returns the current progress of the traversion as a value between 0.0 and 1.0. Note that this value isn't based on the number of files, but the directory structure.
Stdio.Stat|zero stat()
Returns the stat for the current index-value-pair.
Basic filesystem monitor.
This module is intended to be used for incremental scanning of a filesystem.
Supports FSEvents on MacOS X and Inotify on Linux to provide low overhead monitoring; other systems use a less efficient polling approach.
Filesystem.Monitor.symlinks, System.FSEvents, System.Inotify
protected constantint Filesystem.Monitor.basic.default_file_interval_factor
The default factor to multiply default_max_dir_check_interval
with to get the maximum number of seconds between checks of files.
The value can be changed by calling create().
The value can be overridden for individual files or directories
by calling monitor().
Overload this constant to change the default.
protected constantint Filesystem.Monitor.basic.default_max_dir_check_interval
The default maximum number of seconds between checks of directories in seconds.
This value is multiplied with default_file_interval_factor to
get the corresponding default maximum number of seconds for files.
The value can be changed by calling create().
The value can be overridden for individual files or directories
by calling monitor().
Overload this constant to change the default.
protected constantint Filesystem.Monitor.basic.default_stable_time
The default minimum number of seconds without changes for a change
to be regarded as stable (see stable_data_change().
protected Pike.Backend Filesystem.Monitor.basic.backend
Backend to use.
If 0 (zero) - use the default backend.
protected mixed Filesystem.Monitor.basic.co_id
Call-out identifier for backend_check() if in
nonblocking mode.
set_nonblocking(), set_blocking()
protected Thread.Mutex Filesystem.Monitor.basic.monitor_mutex
Mutex controlling access to monitor_queue.
protected ADT.Heap(< Monitor >) Filesystem.Monitor.basic.monitor_queue
Heap containing active Monitors that need polling.
The heap is sorted on Monitor()->next_poll.
protected mapping(string:Monitor) Filesystem.Monitor.basic.monitors
Mapping from monitored path to corresponding Monitor.
The paths are normalized to canonic_path(path),
All filesystems are handled as if case-sensitive. This should not be a problem for case-insensitive filesystems as long as case is maintained.
protected void adjust_monitor(Monitor m)
Update the position in the monitor_queue for the monitor m
to account for an updated next_poll value.
void attr_changed(string path, Stdio.Stat st)
File attribute changed callback.
pathPath of the file or directory which has changed attributes.
stStatus information for path as obtained by file_stat(path, 1).
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check() and check_monitor().
If there is a data_changed() callback, it may supersede this
callback if the file content also has changed.
Overload this to do something useful.
protected void backend_check()
Backend check callback function.
This function is intended to be called from a backend,
and performs a check() followed by rescheduling
itself via a call to set_nonblocking().
check(), set_nonblocking()
protected string canonic_path(string path)
Canonicalize a path.
pathPath to canonicalize.
The default implementation returns combine_path(path, "."),
i.e. no trailing slashes.
int check(int|void max_wait, int|void max_cnt, mapping(string:int)|void ret_stats)
Check for changes.
max_waitMaximum time in seconds to wait for changes. -1
for infinite wait.
max_cntMaximum number of paths to check in this call. 0
(zero) for unlimited.
ret_statsOptional mapping that will be filled with statistics (see below).
A suitable subset of the monitored files will be checked for changes.
The function returns when either a change has been detected
or when max_wait has expired. The returned value indicates
the number of seconds until the next call of check().
If ret_stats has been provided, it will be filled with
the following entries:
| The total number of active monitors when the scan completed. |
| The number of monitors that were scanned for updates during the call. |
| The number of monitors that were updated during the call. |
| The number of seconds that the call slept. |
Any callbacks will be called from the same thread as the one
calling check().
check_all(), monitor()
void check_all(mapping(string:int)|void ret_stats)
Check all monitors for changes.
ret_statsOptional mapping that will be filled with statistics (see below).
All monitored paths will be checked for changes.
You typically don't want to call this function, but instead
check().
Any callbacks will be called from the same thread as the one
calling check().
check(), monitor()
protected bool check_monitor(Monitor m, MonitorFlags|void flags)
Check a single Monitor for changes.
mMonitor to check.
flags | Don't recurse. |
| Check all monitors for the entire subtree rooted in |
This function is called by check() for the Monitors
it considers need checking. If it detects any changes an
appropriate callback will be called.
Returns 1 if a change was detected and 0 (zero)
otherwise.
Any callbacks will be called from the same thread as the one
calling check_monitor().
The return value can not be trusted to return 1 for all
detected changes in recursive mode.
check(), data_changed(), attr_changed(), file_created(),
file_deleted(), stable_data_change()
void clear()
Clear the set of monitored files and directories.
Due to circular datastructures, it's recomended to call this function prior to discarding the object.
Filesystem.Monitor.basic Filesystem.Monitor.basic(int|void max_dir_check_interval, int|void file_interval_factor, int|void stable_time)
Create a new monitor.
max_dir_check_intervalOverride of default_max_dir_check_interval.
file_interval_factorOverride of default_file_interval_factor.
stable_timeOverride of default_stable_time.
void data_changed(string path)
File content changed callback.
pathPath of the file which has had content changed.
This function is called when a change has been detected for a monitored file.
Called by check() and check_monitor().
Overload this to do something useful.
void file_created(string path, Stdio.Stat st)
File creation callback.
pathPath of the new file or directory.
stStatus information for path as obtained by file_stat(path, 1).
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
Called by check() and check_monitor().
Overload this to do something useful.
This callback has similar semantics to file_exists(), but
is called at run time.
file_exists(), file_deleted(), stable_data_change()
void file_deleted(string path)
File deletion callback.
pathPath of the new file or directory that has been deleted.
This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.
Called by check() and check_monitor().
Overload this to do something useful.
file_created(), file_exists(), stable_data_change()
void file_exists(string path, Stdio.Stat st)
File existance callback.
pathPath of the file or directory.
stStatus information for path as obtained by file_stat(path, 1).
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_exists() will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
Called by check() and check_monitor() the first time a monitored
path is checked (and only if it exists).
Overload this to do something useful.
This callback has similar semantics to file_created(), but
is called at initialization time.
file_created(), file_deleted(), stable_data_change()
protected void inotify_event(int wd, int event, int cookie, string(8bit) path)
Event callback for Inotify.
bool is_monitored(string path)
Check whether a path is monitored or not.
pathPath to check.
Returns 1 if there is a monitor on path,
and 0 (zero) otherwise.
monitor(), release()
protected void low_eventstream_callback(string path, int flags, int event_id)
This function is called when the FSEvents EventStream detects a change in one of the monitored directories.
Monitor|void monitor(string path, MonitorFlags|void flags, int(0..)|void max_dir_check_interval, int(0..)|void file_interval_factor, int(0..)|void stable_time)
Register a path for monitoring.
pathPath to monitor.
flags | Don't recurse. |
| Monitor the entire subtree, and any directories or files that may appear later. |
| Monitor the entire subtree, and any directories
or files that may appear later. Remove the monitor
automatically when |
max_dir_check_intervalOverride of default_max_dir_check_interval for this path
or subtree.
file_interval_factorOverride of default_file_interval_factor for this path
or subtree.
stable_timeOverride of default_stable_time for this path
or subtree.
release()
protected DefaultMonitor monitor_factory(string path, MonitorFlags|void flags, int(0..)|void max_dir_check_interval, int(0..)|void file_interval_factor, int(0..)|void stable_time)
Create a new Monitor for a path.
This function is called by monitor() to create a new Monitor
object.
The default implementation just calls DefaultMonitor with the
same arguments.
monitor(), DefaultMonitor
void release(string path, MonitorFlags|void flags)
Release a path from monitoring.
pathPath to stop monitoring.
flags | Don't recurse. |
| Release the entire subtree. |
| Release the entire subtree, but only those paths that were added automatically by a recursive monitor. |
monitor()
protected void release_monitor(Monitor m)
Release a single Monitor from monitoring.
release()
protected void report(SeverityLevel level, string(7bit) fun, sprintf_format format, sprintf_args ... args)
Event tracing callback.
levelSeverity level of the event.
funName of the function that called report().
formatsprintf() formatting string describing the event.
argsOptional extra arguments for the format string.
This function is called in various places to provide granular tracing of the monitor state.
The default implementation calls werror() with
format and args if level is ERROR or higher,
or if FILESYSTEM_MONITOR_DEBUG has been defined.
protected void reschedule_backend_check(int|void suggested_t)
Reschedule beckend check.
suggested_tSuggested time in seconds until next call of check().
Register suitable callbacks with the backend to automatically
call check().
check() and thus all the callbacks will be called from the
backend thread.
void set_backend(Pike.Backend|void backend)
Change backend.
backendBackend to use. 0 (zero) for the default backend.
void set_blocking()
Turn off nonblocking mode.
set_nonblocking()
void set_file_interval_factor(int file_interval_factor)
Set the file_interval_factor.
void set_max_dir_check_interval(int max_dir_check_interval)
Set the max_dir_check_interval.
void set_nonblocking(int|void suggested_t)
Turn on nonblocking mode.
suggested_tSuggested time in seconds until next call of check().
Register suitable callbacks with the backend to automatically
call check().
check() and thus all the callbacks will be called from the
backend thread.
If nonblocking mode is already active, this function will be a noop.
set_blocking(), check().
void set_stable_time(int stable_time)
Set the stable_time.
void stable_data_change(string path, Stdio.Stat st)
Stable change callback.
pathPath of the file or directory that has stopped changing.
stStatus information for path as obtained by file_stat(path, 1).
This function is called when previous changes to path are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time seconds.
Called by check() and check_monitor().
Overload this to do something useful.
This callback being called does not mean that the contents
or inode has changed, just that they don't seem to change any
more. In particular it is called for paths found during
initialization after stable_time seconds have passed.
file_created(), file_exists(), file_deleted()
Flags for Monitors.
constant Filesystem.Monitor.basic.MF_RECURSE
constant Filesystem.Monitor.basic.MF_AUTO
constant Filesystem.Monitor.basic.MF_INITED
constant Filesystem.Monitor.basic.MF_HARD
This symbol evaluates to the Monitor class used by
the default implementation of monitor_factory().
It is currently one of the values Monitor, EventStreamMonitor
or InotifyMonitor.
monitor_factory()
inherit Monitor : Monitor
FSEvents EventStream-accelerated Monitor.
inherit Monitor : Monitor
Inotify-accelerated Monitor.
inherit Monitor : Monitor
Monitoring information for a single filesystem path.
monitor()
inherit ADT.Heap.Element(< Monitor >) : Element
string Filesystem.Monitor.basic.Monitor.path
MonitorFlags Filesystem.Monitor.basic.Monitor.flags
int Filesystem.Monitor.basic.Monitor.max_dir_check_interval
int Filesystem.Monitor.basic.Monitor.file_interval_factor
int Filesystem.Monitor.basic.Monitor.stable_time
protected local void __create__(string path, MonitorFlags flags, int max_dir_check_interval, int file_interval_factor, int stable_time)
protected void attr_changed(string path, Stdio.Stat st)
File attribute or content changed callback.
stStatus information for path as obtained by
file_stat(path, 1).
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check() and check_monitor().
The default implementation calls global::attr_changed() or
global::data_changed() depending on the state.
If there is a data_changed() callback, it may supersede this
callback if the file content also has changed.
void bump(MonitorFlags|void flags, int|void seconds)
Bump the monitor to an earlier scan time.
flags | Don't recurse. |
| Check all monitors for the entire subtree. |
secondsNumber of seconds from now to run next scan. Defaults to half of the remaining interval.
protected void call_callback(function(string, Stdio.Stat|void:void) cb, string path, Stdio.Stat|void st)
Call a notification callback.
cbCallback to call or UNDEFINED for no operation.
pathPath to notify on.
stStat for the path.
bool check(MonitorFlags|void flags)
Check for changes.
flags | Don't recurse. |
| Check all monitors for the entire subtree rooted in |
This function is called by check() for the Monitors
it considers need checking. If it detects any changes an
appropriate callback will be called.
Returns 1 if a change was detected and 0 (zero)
otherwise.
Any callbacks will be called from the same thread as the one
calling check_monitor().
The return value can not be trusted to return 1 for all
detected changes in recursive mode.
check(), data_changed(), attr_changed(), file_created(),
file_deleted(), stable_data_change()
void check_for_release(int mask, int flags)
Check if this monitor should be removed automatically.
protected void file_created(string path, Stdio.Stat st)
File creation callback.
stStatus information for path as obtained by
file_stat(path, 1).
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
Called by check() and check_monitor().
The default implementation registers the path, and
calls global::file_deleted().
This callback has similar semantics to file_exists(), but
is called at run time.
file_exists(), file_deleted(), stable_data_change()
protected void file_deleted(string path, Stdio.Stat|void old_st)
File deletion callback.
pathPath of the new file or directory that has been deleted.
old_stStat for the file prior to deletion (if known). Note that this argument is not passed along to top level function.
This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.
Called by check() and check_monitor().
The default implementation unregisters the path, and
calls global::file_deleted().
file_created(), file_exists(), stable_data_change()
protected void file_exists(string path, Stdio.Stat st)
File existance callback.
stStatus information for path as obtained by
file_stat(path, 1).
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_created() will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
Called by check() and check_monitor() the first time a monitored
path is checked (and only if it exists).
The default implementation registers the path, and
calls global::file_exists().
This callback has similar semantics to file_created(), but
is called at initialization time.
file_created(), file_deleted(), stable_data_change()
protected void monitor(string path, int flags, int max_dir_interval, int file_interval_factor, int stable_time)
Called to create a sub monitor.
this_program parent()
Returns the parent monitor, or UNDEFINED if no such monitor exists.
protected void register_path(int|void initial)
Register the Monitor with the monitoring system.
initialIndicates that the Monitor is newly created.
protected void report(SeverityLevel level, string(7bit) fun, sprintf_format format, sprintf_args ... args)
Event tracing callback.
levelSeverity level of the event.
funName of the function that called report().
formatsprintf() formatting string describing the event.
argsOptional extra arguments for the format string.
This function is called in various places to provide granular tracing of the monitor state.
The default implementation just calls global::report()
with the same arguments.
protected void stable_data_change(string path, Stdio.Stat st)
Stable change callback.
stStatus information for path as obtained by
file_stat(path, 1).
This function is called when previous changes to path are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time seconds.
Called by check() and check_monitor().
The default implementation calls global::stable_data_change().
This callback being called does not mean that the contents
or inode has changed, just that they don't seem to change any
more. In particular it is called for paths found during
initialization after stable_time seconds have passed.
file_created(), file_exists(), file_deleted()
protected bool status_change(Stdio.Stat old_st, Stdio.Stat st, int orig_flags, int flags)
Called when the status has changed for an existing file.
void submonitor_released(this_program submon)
To be called when a (direct) submonitor is released.
protected void unregister_path(int|void dying)
Unregister the Monitor from the monitoring system.
dyingIndicates that the Monitor is being destructed.
It is the destruction cause value offset by one.
protected void update(Stdio.Stat st)
Calculate and set a suitable time for the next poll of this monitor.
stNew stat for the monitor.
This function is called by check() to schedule the
next check.
Debugging filesystem monitor.
This module behaves as symlinks, but has default implementations
of all callbacks that call report(), as well as an implementation
of [report()] that logs everything to Stdio.stderr.
Filesystem.Monitor.basic, Filesystem.Monitor.symlinks
inherit "symlinks.pike" : "symlinks.pike"
mapping(string:Monitor) get_monitors()
Return the set of active monitors.
Filesystem monitor with support for symbolic links.
This module extends Filesystem.Monitor.basic with
support for symbolic links.
For operating systems where symbolic links aren't supported,
this module will behave exactly like Filesystem.Monitor.basic.
Filesystem.Monitor.basic
inherit Filesystem.Monitor.basic : basic
protected int Filesystem.Monitor.symlinks.available_ids
Bitmask of all unallocated symlink ids.
protected mapping(string:int) Filesystem.Monitor.symlinks.symlink_ids
Mapping from symlink name to symlink id.
protected mapping(string:string) Filesystem.Monitor.symlinks.symlink_targets
Mapping from symlink name to symlink target.
protected int allocate_symlink(string sym)
Allocates a symlink id for the link sym.
void attr_changed(string path, Stdio.Stat st)
File attribute changed callback.
pathPath of the file or directory which has changed attributes.
stStatus information for path as obtained by file_stat(path).
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check() and check_monitor().
If there is a data_changed() callback, it may supersede this
callback if the file content also has changed.
It differs from the Filesystem.Monitor.basic version in that
symbolic links have the st of their targets.
Overload this to do something useful.
void file_created(string path, Stdio.Stat st)
File creation callback.
pathPath of the new file or directory.
stStatus information for path as obtained by file_stat(path).
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
It differs from the Filesystem.Monitor.basic version in that
symbolic links have the st of their targets.
Called by check() and check_monitor().
Overload this to do something useful.
void file_exists(string path, Stdio.Stat st)
File existance callback.
pathPath of the file or directory.
stStatus information for path as obtained by file_stat(path).
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_created() will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
It differs from the Filesystem.Monitor.basic version in that
symbolic links have the st of their targets.
Called by check() and check_monitor() the first time a monitored
path is checked (and only if it exists).
Overload this to do something useful.
void stable_data_change(string path, Stdio.Stat st)
Stable change callback.
pathPath of the file or directory that has stopped changing.
stStatus information for path as obtained by file_stat(path).
This function is called when previous changes to path are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time seconds.
It differs from the Filesystem.Monitor.basic version in that
symbolic links have the st of their targets.
Called by check() and check_monitor().
Overload this to do something useful.
Monitoring information for a single filesystem path.
With support for expansion of symbolic links.
monitor()
inherit basic::DefaultMonitor : DefaultMonitor
Based on Filesystem.Monitor.basic.DefaultMonitor.
int Filesystem.Monitor.symlinks.DefaultMonitor.symlinks
Mask of symlink ids that can reach this monitor.
protected void attr_changed(string path, Stdio.Stat st)
File attribute or content changed callback.
stStatus information for path as obtained by
file_stat(path, 1).
This function is called when a change has been detected for an attribute for a monitored file or directory.
Called by check() and check_monitor().
If there is a data_changed() callback, it may supersede this
callback if the file content also has changed.
protected void call_callback(function(string, __unknown__ ... :void) cb, string path, Stdio.Stat|void st)
Call a notification callback and handle symlink expansion.
cbCallback to call or UNDEFINED for no operation.
extrasExtra arguments after the path argument to cb.
void check_for_release(int mask, int flags)
Check if this monitor should be removed automatically.
protected void check_symlink(string path, Stdio.Stat|zero st, int|void inhibit_notify)
Check whether a symlink has changed.
protected void file_created(string path, Stdio.Stat st)
File creation callback.
stStatus information for path as obtained by
file_stat(path, 1).
This function is called when either a monitored path has started existing, or when a new file or directory has been added to a monitored directory.
Called by check() and check_monitor().
protected void file_deleted(string path, Stdio.Stat old_st)
File deletion callback.
pathPath of the new file or directory that has been deleted.
This function is called when either a monitored path has stopped to exist, or when a file or directory has been deleted from a monitored directory.
Called by check() and check_monitor().
protected void file_exists(string path, Stdio.Stat st)
File existance callback.
stStatus information for path as obtained by
file_stat(path, 1).
This function is called during initialization for all monitored paths, and subpaths for monitored directories. It represents the initial state for the monitor.
For directories, file_created() will be called for the subpaths
before the call for the directory itself. This can be used to detect
when the initialization for a directory is finished.
Called by check() and check_monitor() the first time a monitored
path is checked (and only if it exists).
void low_call_callback(function(string, __unknown__ ... :void) cb, mapping(string:int) state, mapping(string:string) symlink_targets, string path, Stdio.Stat|void st, string|void symlink)
Call a notification callback and handle symlink expansion.
cbCallback to call or UNDEFINED for no operation.
stateState mapping to avoid multiple notification and infinite loops. Call with an empty mapping.
symlinksSymlinks that have not been expanded yet.
pathPath to notify on.
extrasExtra arguments to cb.
symlinkSymbolic link that must have been followed for the callback to be called.
protected void monitor(string path, int flags, int max_dir_interval, int file_interval_factor, int stable_time)
Called to create a sub monitor.
protected void stable_data_change(string path, Stdio.Stat st)
Stable change callback.
stStatus information for path as obtained by
file_stat(path, 1).
This function is called when previous changes to path are
considered "stable".
"Stable" in this case means that there have been no detected
changes for at lease stable_time seconds.
Called by check() and check_monitor().
protected bool status_change(Stdio.Stat old_st, Stdio.Stat st, int orig_flags, int flags)
Called when the status has changed for an existing file.
protected void zap_symlink(string path)
Called when the symlink path is no more.
Filesystem which can be used to mount a Tar file.
Two kinds of extended tar file records are supported:
| POSIX ustar (Version 0?). |
| GNU tar (POSIX draft) |
For a quick start, you probably want to use `()().
`()()
constant int Filesystem.Tar.EXTRACT_CHOWN
Set owning user and group from the tar records.
constant int Filesystem.Tar.EXTRACT_ERR_ON_UNKNOWN
Throw an error if an entry of an unsupported type is encountered. This is ignored otherwise.
constant int Filesystem.Tar.EXTRACT_SKIP_EXT_MODE
Don't set set-user-ID, set-group-ID, or sticky bits from the tar records.
constant int Filesystem.Tar.EXTRACT_SKIP_MODE
Don't set any permission bits from the tar records.
constant int Filesystem.Tar.EXTRACT_SKIP_MTIME
Don't set mtime from the tar records.
Low-level Tar Filesystem.
void extract(string src_dir, string dest_dir, void|string|function(string, Filesystem.Stat:int|string) filter, void|int flags)
Extracts files from the tar file in sequential order.
src_dirThe root directory in the tar file system to extract.
dest_dirThe root directory in the real file system that will receive
the contents of src_dir. It is assumed to exist and be
writable.
filterA filter for the entries under src_dir to extract. If it's
a string then it's taken as a glob pattern which is matched
against the path below src_dir. That path always begins
with a /. For directory entries it ends with a
/ too, otherwise not.
If it's a function then it's called for every entry under
src_dir, and those where it returns nonzero are extracted.
The function receives the path part below src_dir as the
first argument, which is the same as in the glob case above,
and the stat struct as the second. If the function returns a
string, it's taken as the path below dest_dir where this
entry should be extracted (any missing directories are created
automatically).
If filter is zero, then everything below src_dir is
extracted.
flagsBitfield of flags to control the extraction:
| Don't set any permission bits from the tar records. |
| Don't set set-user-ID, set-group-ID, or sticky bits from the tar records. |
| Don't set mtime from the tar records. |
| Set owning user and group from the tar records. |
| Throw an error if an entry of an unsupported type is encountered. This is ignored otherwise. |
Files and directories are supported on all platforms, and
symlinks are supported whereever symlink exists. Other record
types are currently not supported.
I/O errors are thrown.
inherit Filesystem.System : System
void chmod(string filename, int|string mode)
Not implemented yet.
void chown(string filename, int|object owner, int|object group)
Not implemented yet.
Filesystem.Tar._TarFS Filesystem.Tar._TarFS(_Tar _tar, string _wd, string _root, Filesystem.Base _parent)
int rm(string filename)
Not implemented yet.
inherit _TarFS : _TarFS
Filesystem.Tar.`() Filesystem.Tar.`()(string filename, void|Filesystem.Base parent, void|object file)
filenameThe tar file to mount.
parentThe parent filesystem. If none is given, the normal system filesystem is assumed. This allows mounting a TAR-file within a tarfile.
fileIf specified, this should be an open file descriptor. This object
could e.g. be a Stdio.File, Gz.File or Bz2.File object.
void Filesystem.Zipcreate(string filename, void|Filesystem.Base parent, void|object file)
Filesystem which can be used to mount a ZIP file.
filenameThe tar file to mount.
parentThe parent filesystem. If non is given, the normal system filesystem is assumed. This allows mounting a ZIP-file within a zipfile.
fileIf specified, this should be an open file descriptor. This object
could e.g. be a Stdio.File or similar object.
traditional Zip encryption is CRC32 based, and rather insecure. support here exists to ease transition and to work with legacy files.
string decrypt(string x)
decrypt a string
xencrypted string to decrypt
A class for reading and writing ZIP files.
Note that this class does not support the full ZIP format specification, but does support the most common features.
Storing, Deflating and Bzip2 (if the Bz2 module is available) are supported storage methods.
This class is able to extract data from traditional ZIP password encrypted archives.
Notably, advanced PKware encryption (beyond reading traditional password protected archives) and multi-part archives are not currently supported.
void add_dir(string path, int recurse, string|void archiveroot)
adds a directory to an archive
void add_file(string filename, string|Stdio.File|zero data, int|object|void stamp, int|void no_compress)
add a file to an archive.
Filesystem.Zip._Zip Filesystem.Zip._Zip(object|void fd, string|void filename, object|void parent)
int date_dos2unix(int time, int date)
Convert MS-DOS time/date pair to a linear UNIX date.
array date_unix2dos(int unix_date)
Convert linear UNIX date to a MS-DOS time/date pair.
an array containing ({time, date})
string generate()
generate the zip archive
int is_zip64()
is this archive using zip64 extensions?
void set_compression_value(int(0..9) v)
sets the compression value (0 to 9)
void set_password(string pw)
sets the password to be used for files encrypted using traditional PKZip encryption.
void set_zip64(int flag)
enable zip64 extensions (large files) for this archive
This setting may be used to force zip64 for files that do not otherwise require its use. If a file whose properties requires the use of zip65 is added to an archive, zip64 extensions will be enabled automatically.
void unzip(string todir)
inherit Filesystem.System : System
void set_password(string pw)
Fuse - Filesystem in USErspace
FUSE (Filesystem in USErspace) provides a simple interface for userspace programs to export a virtual filesystem to the Linux kernel. FUSE also aims to provide a secure method for non privileged users to create and mount their own filesystem implementations.
See http://sourceforge.net/projects/fuse/ for more information
This module maps the Fuse library more or less directly to pike.
In order to create a filesystem, create a subclass of the
Operations class, clone it and pass it to the run method.
You do not need to implemnent all functions, but at least getattr, readdir and read are needed to make a useable filesystem.
A tip: ERRNO constants are available in the System module, and if one is missing /usr/include/asm[-generic]/errno.h can be included in pike programs on Linux.
inherit "___Fuse" : "___Fuse"
constant Fuse.FUSE_MAJOR_VERSION
constant Fuse.FUSE_MINOR_VERSION
The version of FUSE
void run(Operations handler, array(string) args)
Start fuse. Args is as in argv in main(). This function will not return.
The first argument (argv[0], program name) is used as the filesystem name. The first non-flag argument after argv[0] is used as the mountpoint. Otherwise these arguments are supported:
-d enable debug output (implies -f)
-f foreground operation
-s disable multithreaded operation
-r mount read only (equivalent to '-o ro')
-o opt,[opt...] mount options
-h print help
Mount options:
rootmode=M permissions of the '/' directory in the filesystem (octal)
user_id=N user of '/' (numeric)
group_id=N group of '/' (numeric)
default_permissions enable permission checking
By default FUSE doesn't check file access permissions, the
filesystem is free to implement it's access policy or leave it to
the underlying file access mechanism (e.g. in case of network
filesystems). This option enables permission checking,
restricting access based on file mode. It is usually useful
together with the 'allow_other' mount option.
allow_other allow access to other users
This option overrides the security measure restricting file access
to the user mounting the filesystem. This option is by default
only allowed to root, but this restriction can be removed with a
(userspace) configuration option (in fuse.ini).
large_read issue large read requests (2.4 only)
max_read=N set maximum size of read requests (default 128K)
hard_remove immediate removal (don't hide files)
debug enable debug output
fsname=NAME set filesystem name in mtab (overrides argv[0])
This is the interface you have to implement to write a FUSE filesystem If something goes wrong in your callback, always return errno. Unless the function returns a specific value (Stat, string or similar), return 0 if all is well.
You do not have to implement all functions. Unimplemented functions have a default implementation that returns -ENOIMPL.
final constantint Fuse.Operations.DT_BLK
Block special directory entry
final constantint Fuse.Operations.DT_CHR
Character special directory entry
final constantint Fuse.Operations.DT_DIR
Directory directory entry
final constantint Fuse.Operations.DT_FIFO
FIFO directory entry
final constantint Fuse.Operations.DT_LNK
Symlink directory entry
final constantint Fuse.Operations.DT_REG
Normal file directory entry
final constantint Fuse.Operations.DT_SOCK
Socket directory entry
final constantint Fuse.Operations.DT_UNKNOWN
Unkown directory entry type
Fuse.Operations.final constantF_GETLK
Fuse.Operations.final constantF_SETLK
Fuse.Operations.final constantF_SETLKW
Fuse.Operations.final constantF_RDLCK
Fuse.Operations.final constantF_WRLCK
Fuse.Operations.final constantF_UNLCK
lock() mode operations.
final constantint Fuse.Operations.O_ACCMODE
Mask for read/write/rdwr
final constantint Fuse.Operations.O_APPEND
Open for append
final constantint Fuse.Operations.O_RDONLY
Open read only
final constantint Fuse.Operations.O_RDWR
Open read/write only
final constantint Fuse.Operations.O_WRONLY
Open write only
int access(string path, int mode)
Return if the user is allowed to access the path. If the
'default_permissions' mount option is given, this method is not
called.
int chmod(string path, int mode)
Change the permission of a file or directory
errno or 0
int chown(string path, int uid, int gid)
Change the owner of a file or directory
errno or 0
int creat(string path, int mode, int flag)
Create and open or just open the given path
int flush(string path, int flags)
Write unwritten data.
int fsync(string path, int datasync)
Flush data and user-data to disk. Not required.
If the datasync parameter is non-zero, then only the user data
should be flushed, not the meta data.
Stdio.Stat|int(1..) getattr(string path)
Stat a file.
This function is required.
A Stdio.Stat object or an errno.
string getxattr(string path, string name)
Get the extended attribute name on path
int link(string source, string destination)
Create a hard link from source to destination.
errno or 0
array(string)|int listxattr(string path)
Return a list of all available extended attributes on path
mapping(string:int)|int lock(string path, int mode, mapping(string:int) how)
Lock, unlock or test for the existence of record locks (POSIX
file locking). The owner of the lock is identified by how->owner
If you only need local file-locking on the computer the filesystem is mounted on you do not need to implement this interface. This is only needed for network filesystems that want locking to work over the network.
The operation mode depends on the mode argument.
F_SETLK
Acquire a lock (when how->type is F_RDLCK or F_WRLCK) or
release a lock (when how->type is F_UNLCK) on the bytes
specified by the how->whence, how->start, and how->len fields
of lock. If a conflicting lock is held by another process,
you should return EACCES or EAGAIN.
F_SETLKW
Identical to SETLK, but if a lock is held on the file, wait for it to be released before returning. You are allowed to return EINTR, to signal that the waiting has been interrupted and must be restarted.
F_GETLK
Identical to SETLK, but do not actually aquire the lock if it
can be aquired. If one or more incompatible locks would
prevent this lock being placed, then fcntl() returns details
about one of these locks in the type, whence, start, and len
fields of how and set pid to be the PID of the process
holding that lock. Then return the mapping.
int mkdir(string path, int mode)
Create a directory.
errno or 0
int mknod(string path, int mode, int rdev)
Create a node (file, device special, or named pipe). See man 2 mknod
errno or 0
int open(string path, int mode)
Open path. mode is as for the system call open.
(mode & O_ACCMODE) is one of O_RDONLY, O_WRONLY and O_RDWR.
The mode can also contain other flags, most notably O_APPEND.
You do not really have to implement this function. It's useful to start prefetch and to cache open files, and check that the user has permission to read/write the file.
errno or 0
string|int(1..) read(string path, int len, int offset)
Read data from a file. You have to return at most len
bytes, wunless an error occurs, or there is less than len bytes
of data still left to read.
errno or the data
int readdir(string path, function(string:void) callback)
Get directory contents.
Call the callback once per file in the directory with the filename as the argument.
This function is required.
errno or 0
string|int(1..) readlink(string path)
Read a symlink.
The symlink contents or errno
int release(string path)
The inverse of open.
The file might very well be openend multiple times. Keep reference counts.
int removexattr(string path, string name)
Remove the extended attribute name from path
int rename(string source, string destination)
Rename source to destination.
errno or 0
int rmdir(string path)
Remove a directory
errno or 0
int setxattr(string path, string name, string value, int flags)
Set the extended attrbiute name on path to value
mapping(string:int) statfs(string path)
Stat a filesystem.
Mapping as from filesystem_stat
required for 'df' support, without this function there is an error each time 'df' is run.
int symlink(string source, string destination)
Create a symlink from source to destination.
errno or 0
int truncate(string path, int new_length)
Shrink or enlarge a file
errno or 0
int unlink(string path)
Remove a file
errno or 0
int utime(string path, int atime, int mtime)
Set access and modification time. The arguments are the number of seconds since jan 1 1970 00:00.
This function is deprecated, utimens is the recommended method.
errno or 0
int utimens(string path, int atime, int mtime)
Set access and modification time, with nanosecond resolution. The arguments are the number of nanoseconds since jan 1 1970 00:00.
errno or 0
int write(string path, string data, int offset)
Write data to the file. Should write all data.
errno or amount written (bytes)
The base object classes used by GTK2 et al.
G.Object, GTK2, https://docs.gtk.org/gobject/
Abstract class - do not instantiate
inherit G.Object : Object
The base object. All GDK and GTK classes inherit from this. The Pango classes also inherit from this class.
Signals: notify
protected G.Object _destruct()
Destroy this object. This is the normal way to (eg) close a window - simply call destruct(obj) and it will be destroyed.
G.Object accel_groups_activate(int accel_key, int accel_mods)
Finds the first accelerator in an GTK.AccelGroup attached to this object that matches accel_key and accel_mods, and activates that accelerator.
object get_data(string name)
Gets a named field from the object.
string get_docs()
Get documentation on object
mixed get_property(string property)
Get a property.
int is_floating()
Checks whether this object has a floating reference.
int new_signal(string name, array types, string return_type)
Create a new signal.
G.Object notify(string property)
Emits a "notify" signal for the named property on the object.
object set_data(string name, mixed arg)
Each object carries around a table of associations from strings to pointers. This function lets you set an association.
If the object already had an association with that name, the old association will be destroyed.
G.Object set_property(string property, mixed value)
Set a property on a G.Object (and any derived types) to value.
G.Object signal_block(int signal_id)
Temporarily block a signal handler. No signals will be received while the handler is blocked. See signal_connect() for more info.
int signal_connect(string signal, function(:void) callback, mixed|void callback_arg, string|void detail, int|void connect_before)
Connect a signal to a pike function. The function will be called with the last argument to this function as its last argument (defaults to 0); the first argument is always the widget, and any other arguments are the ones supplied by GTK. If connect_before is nonzero, the callback will be called prior to the normal handling of the signal (and can return true to suppress that handling), otherwise it will be called after.
The return value of this function can be used to remove a signal with signal_disconnect(), and block and unblock the signal with signal_block() and signal_unblock().
G.Object signal_disconnect(int signal_id)
Remove a signal formerly added by signal_connect. The argument is the return value of signal_connect(). See signal_connect() for more info.
G.Object signal_emit(string signal_name, string|void detail)
Send the current named signal.
G.Object signal_stop(string signal_name)
Stop the emission of a signal.
G.Object signal_unblock(int signal_id)
Unblock a formerly blocked signal handler. See signal_block() and signal_connect() for more info.
Repository get_default_repository()
BaseInfo get_container()
string get_name()
string get_namespace()
mixed get()
array(ValueInfo) get_values()
mixed get_field(GBoxed box)
void set_field(GBoxed box, mixed value)
mixed invoke(mixed ... args)
GI.GBoxed GI.GBoxed(StructInfo info, mapping(string:mixed)|void props)
int connect(string signal_spec, function(:void) callback, mixed ... extra_args)
int connect_after(string signal_spec, function(:void) callback, mixed ... extra_args)
GI.GObject GI.GObject(ObjectInfo info, mapping(string:mixed)|void props)
array(FunctionInfo) get_methods()
array(InterfaceInfo) get_interfaces()
array(FunctionInfo) get_methods()
ObjectInfo get_parent()
array(string) enumerate_versions(strig namespace)
BaseInfo find_by_name(string namespace, string name)
array(BaseInfo) get_infos(string namespace)
void require(string namespace, string|void version, bool|void lazy)
array(FieldInfo) get_fields()
array(FunctionInfo) get_methods()
int get_value()
This class contains a geographical position, ie a point on the earths surface. The resulting position object implements comparision methods (__hash, `==, `< and `>) so that you can compare and sort positions as well as using them as index in mappings. Comparision is made primary on latidue and secondly on longitude. It does not currently take the ellipsoid into account.
It is possible to cast a position into an array, which will yield ({ float latitude, float longitude }), as well as into a string.
constant Geography.Position.ellipsoids
A mapping with reference ellipsoids, which can be fed to the UTM converter. The mapping maps the name of the ellipsoid to an array where the first element is a float describing the equatorial radius and the second element is a float describing the polar radius.
float Geography.Position.alt
Altitud of the position, in meters. Positive numbers is up. Zero is the shell of the current ellipsoid.
float Geography.Position.equatorial_radius
The equatorial radius is how many meters the earth radius is at the equator (east-west direction).
float Geography.Position.lat
Latitude (N--S) of the position, in degrees. Positive number is north, negative number is south.
float Geography.Position.long
Longitude (W--E) of the position, in degrees. Positive number is east, negative number is west.
float Geography.Position.polar_radius
The polar radius is how many meters the earth radius is at the poles (north-south direction).
array(float) ECEF()
Returns the current position as Earth Centered Earth Fixed Cartesian Coordinates.
({ X, Y, Z })
string GEOREF()
Gives the full GEOREF position for the current position, e.g. "LDJA0511".
array(float) RT38()
string UTM(int precision)
Returns the current UTM coordinates position. An example output is "32T 442063.562 5247479.500" where the parts are zone number + zone designator, easting and northing.
array(float) UTM_offset()
Returns the offset within the present UTM cell. The result will be returned in an array of floats, containing easting and northing.
string UTM_zone_designator()
Returns the UTM letter designator for the current latitude. Returns "Z" if latitude is outside the UTM limits of 84N to 80S.
int UTM_zone_number()
Returns the UTM zone number for the current longitude, with correction for the Svalbard deviations.
int hash_value( Geography.Position arg )
string sprintf(string format, ... Geography.Position arg ... )
int res = Geography.Position() < pos
int res = Geography.Position() == pos
int res = Geography.Position() > pos
float approx_height()
Returns a very crude approximation of where the ground level is at the current position, compared against the ellipsoid shell. WGS-84 is assumed, but the approximation is so bad that it doesn't matter which of the standard ellipsoids is used.
Geography.Position Geography.Position(int|float lat, int|float long, void|int|float alt)
Geography.Position Geography.Position(string lat, string long)
Geography.Position Geography.Position(string position)
Geography.Position Geography.Position()
Constructor for this class. If fed with strings, it will perform a dwim scan on the strings. If they fails to be understood, there will be an exception.
float eccentricity_squared()
Returns the first eccentricity squared for the selected earth approximation ellipsoid.
float euclidian_distance(this_program p)
Calculate the euclidian distance between two Geography.Position. Result is in meter. This uses the ECEF function.
float flattening()
Returns the flattening factor for the selected earth approximation ellipsoid.
string latitude(void|int n)
string longitude(void|int n)
Returns the nicely formatted latitude or longitude.
| "17°42.19'N" / "42°22.2'W" |
| "17.703°N" / "42.37°W" |
| "17°42.18'N" / "42°22.2'W" |
| "17°42'10.4"N" / "42°22'12"W" |
| "17.703" / "-42.37" |
bool set_ellipsoid(string name)
bool set_ellipsoid(float equatorial_radius, float polar_radius)
Sets the equatorial and polar radius to the provided values. A name can also be provided, in which case the radius will be looked up in the ellipsoid mapping. The function returns 1 upon success, 0 on failure.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The longitude and lattitude are not converted to the new ellipsoid.
void set_from_RT38(int|float|string x_n, int|float|string y_e)
Sets the longitude and lattitude from the given RT38 coordinates.
void set_from_UTM(int zone_number, string zone_designator, float UTME, float UTMN)
Sets the longitude and lattitude from the given UTM coordinates.
string standard_grid()
Returns the standard map grid system for the current position. Can either be "UPS" or "UTM".
Create a Position object from a RT38 coordinate
inherit .Position : Position
array(Country) Geography.Countries.countries
All known countries.
mixed `[](string what)
mixed `->(string what)
Convenience functions for getting a country the name-space way; it looks up whatever it is in the name- and domain-space and returns that country if possible:
> Geography.Countries.se;
Result: Country(Sweden)
> Geography.Countries.djibouti;
Result: Country(Djibouti)
> Geography.Countries.com;
Result: Country(United States)
> Geography.Countries.wallis_and_futuna_islands->iso2;
Result: "WF"
mapping(string:array(Country)) continents()
Gives back a mapping from continent name to an array of the countries on that continent.
The continents are:
"Europe"
"Africa"
"Asia"
"North America"
"South America"
"Oceania"
"Antarctica"
Some countries are considered to be on more than one continent.
Country from_domain(string domain)
Look up a country from a domain name. Returns zero if the domain doesn't map to a country. Note that there are some valid domains that don't:
International
US Military
Network
Non-Profit Organization
Old style Arpanet
Nato field
And that US has five domains, Great Britain and france two: <dl compact> <dt>EDU <dd>US Educational <dt>MIL <dd>US Military <dt>GOV <dd>US Government <dt>UM <dd>US Minor Outlying Islands <dt>US <dd>US <dt>GB <dd>Great Britain (UK) <dt>UK <dd>United Kingdom <dt>FR <dd>France <dt>FX <dd>France, Metropolitan <dt>There's also three domains that for convinience maps to US: <dt>NET <dd>Network <dt>ORG <dd>Organization <dt>COM <dd>Commercial </dl>
Country from_domain(string name)
Look up a country from its name or aka. The search is case-insensitive but regards whitespace and interpunctation.
Country
string Geography.Countries.Country.name
array(string) Geography.Countries.Country.aka
Country name and also-known-as, if any
string|zero Geography.Countries.Country.fips10
FIPS 10-character code; "Federal Information Processing Standards 10-4" etc, previously used by some goverments in the US.
This character code is slightly different from iso2,
and should only be used for compatibility with old code.
Replaced by iso2.
FIPS 10-4 was withdrawn by NIST 2008-09-02.
int Geography.Countries.Country.former
Flag that is set if this country doesn't exist anymore. (eg USSR.)
string|zero Geography.Countries.Country.iso2
ISO-3166-1 2-character code aka domain name.
May be zero in some obscure cases where the ISO-3166-1 grouping differs from the FIPS-10 grouping.
(string)Geography.Countries.Country()
It is possible to cast a country to a string,
which will be the same as performing
country->name;.
string continent()
Returns the continent of the country.
Some countries are geographically in more then one continent; any of the continents might be returned then, but probably the continent in which the capital is resident - Europe for Russia, for instance.
void parse_77(string line, object tree)
Parsing function for geoip databases in the format used my http://software77.net/.
void parse_maxmind(string line, object tree)
Parsing function for geoip databases in the format used my http://www.maxmind.com/.
Base class for GeoIP lookups. Use Geography.GeoIP.IPv4.
mixed from_ip(string ip)
Returns the geographical location of the given ip address ip.
When this object has been created using one of the standard parsing
functions the locations are instances of
Geography.Countries.Country.
Class for GeoIP lookups of ipv4 addresses.
Uses ADT.CritBit.IPv4Tree objects internally to map IPv4 addresses to
a geographical region.
inherit IP : IP
Geography.GeoIP.IPv4 Geography.GeoIP.IPv4(string file_name, function(string, ADT.CritBit.IPv4Tree:void) fun)
Geography.GeoIP.IPv4 Geography.GeoIP.IPv4(ADT.CritBit.IPv4Tree tree)
Objects of this class can either be created from a file
file_name with an optional parsing function fun.
When fun is omitted, it defaults to
Geography.GeoIP.parse_maxmind. fun will be called for each line in
file_name and the critbit tree to add the entry to.
Alternatively, an instance of ADT.CritBit.IPv4Tree can be passed.
tree is expected to map the first address of each range to
its geographical location.
Getopt is a group of functions which can be used to find command
line options.
Command line options come in two flavors: long and short. The short ones consists of a dash followed by a character (-t), the long ones consist of two dashes followed by a string of text (--test). The short options can also be combined, which means that you can write -tda instead of -t -d -a.
Options can also require arguments, in which case they cannot be combined. To write an option with an argument you write -t argument or -targument or --test=argument.
constant int Getopt.HAS_ARG
Used with find_all_options() to indicate that an option
requires an argument.
find_all_options()
constant int Getopt.MAY_HAVE_ARG
Used with find_all_options() to indicate that an option
takes an optional argument.
find_all_options()
constant int Getopt.NO_ARG
Used with find_all_options() to indicate that an option
does not take an argument.
find_all_options()
array(array) find_all_options(array(string|zero) argv, array(array(array(string)|string|int)) options, void|int(-1..1) posix_me_harder, void|int throw_errors)
This function does the job of several calls to find_option().
The main advantage of this is that it allows it to handle the
POSIX_ME_HARDER environment variable better. When either
the argument posix_me_harder or the environment variable
POSIX_ME_HARDER is true, no arguments will be parsed after
the first non-option on the command line.
argvThe should be the array of strings that was sent as the second
argument to your main() function.
optionsEach element in the array options should be an array on the
following form:
| Array | |
| Name is a tag used to identify the option in the output. |
| Type is one of |
| This is a string or an array of string of options that will be
looked for. Short and long options can be mixed, and short options
can be combined into one string. Note that you must include the
dashes so that |
| This is a string or an array of strings containing names of environment variables that can be used instead of the command line option. |
| This is the default value a |
Only the first three elements need to be included.
posix_me_harderDon't scan for arguments after the first non-option.
throw_errorsIf throw_errors has been specified find_all_options() will
throw errors on failure. If it has been left out, or is
0 (zero), it will instead print an error message on
Stdio.stderr and exit the program with result code 1 on
failure.
The good news is that the output from this function is a lot simpler.
find_all_options() returns an array where each element is an array on
this form:
| Array | |
| Option identifier name from the input. |
| Value given. If no value was specified, and no default has been specified, the value will be 1. |
find_all_options() modifies argv.
Index 0 (zero) of argv is not scanned for options,
since it is reserved for the program name.
Getopt.get_args(), Getopt.find_option()
void|string|bool find_option(array(string|zero) argv, array(string)|string shortform, array(string)|string|void longform, array(string)|string|void envvars, string|bool|void def, int|void throw_errors)
This is a generic function to parse command line options of the type -f, --foo or --foo=bar.
argvThe first argument should be the array of strings that was sent as
the second argument to your main() function.
shortformThe second is a string with the short form of your option. The short form must be only one character long. It can also be an array of strings, in which case any of the options in the array will be accepted.
longformThis is an alternative and maybe more readable way to give the
same option. If you give "foo" as longform your program
will accept --foo as argument. This argument can also be
an array of strings, in which case any of the options in the
array will be accepted.
envvarsThis argument specifies an environment variable that can be used to specify the same option, to make it easier to customize program usage. It can also be an array of strings, in which case any of the mentioned variables in the array may be used.
defThis argument has two functions: It specifies if the option takes an
argument or not, and it informs find_option() what to return if the
option is not present.
The value may be one of:
| The option does not require a value. |
| The option requires a value, and Note that a set option will always return a |
throw_errorsIf throw_errors has been specified find_option() will
throw errors on failure. If it has been left out, or is
0 (zero), it will instead print an error message on
Stdio.stderr and exit the program with result code 1 on
failure.
Returns the value the option has been set to if any.
If the option is present, but has not been set to anything
1 will be returned.
Otherwise if any of the environment variables specified in envvars has
been set, that value will be returned.
If all else fails, def will be returned.
If an option that requires an argument lacks an argument and
throw_errors is set an error will be thrown.
find_option() modifies argv. Parsed options will be removed
from argv. Elements of argv that have been removed entirely will
be replaced with zeroes.
This function reads options even if they are written after the first non-option on the line.
Index 0 (zero) of argv is not scanned for options,
since it is reserved for the program name.
Only the first ocurrance of an option will be parsed. To parse
multiple ocurrances, call find_option() multiple times.
Getopt.get_args()
array(string) get_args(array(string|zero) argv, void|int(-1..1) posix_me_harder, void|int throw_errors)
This function returns the remaining command line arguments after
you have run find_option() or find_all_options() to find
all the options in the argument list. If there are any options
left not handled by find_option() or find_all_options()
this function will fail.
If throw_errors has been specified get_args() will throw errors
on failure. If it has been left out, or is 0 (zero), it will
instead print an error message on Stdio.stderr and exit the
program with result code 1 on failure.
On success a new argv array without the parsed options is
returned.
Getopt.find_option(), Getopt.find_all_options()
This is a module for interacting with the Git distributed version control system.
constant int Git.MODE_DIR
A subdirectory.
constant int Git.MODE_EXE
A normal, but executable file.
constant int Git.MODE_FILE
A normal (non-executable) file.
constant int Git.MODE_GITLINK
A gitlink (aka submodule reference).
constant int Git.MODE_SYMLINK
A symbolic link.
constant string Git.NULL_SHA1
The NULL SHA1.
string Git.git_binary
The git binary to use.
Defaults to "git", but may be overridden
to select a different binary.
string git(string|zero git_dir, string command, string ... args)
Run a git command, and get the output.
git_dirDirectory containing the Git repository. May be UNDEFINED
to specify the Git repository for the current directory.
commandGit subcommand to execute.
argsArguemnts for command.
Returns the output on stdout from running the command on success, and throws an error on failure.
try_git(), low_git()
string hash_blob(string data)
Hash algorithm for blobs that is compatible with git.
Process.Process low_git(mapping(string:mixed) options, string|zero git_dir, string command, string ... args)
Start a git process.
optionsOptions for Process.Process().
git_dirDirectory containing the Git repository. May be UNDEFINED
to specify the Git repository for the current directory.
commandGit subcommand to execute.
argsArguemnts for command.
Returns the corresponding Process.Process object.
git(), try_git()
string|zero try_git(string git_dir, string command, string ... args)
Attempt to run a git command and get its output.
git_dirDirectory containing the Git repository. May be UNDEFINED
to specify the Git repository for the current directory.
commandGit subcommand to execute.
argsArguemnts for command.
Returns the output on stdout from running the command
on success, and 0 (zero) on failure.
This is a convenience function, and there is no way to get
the specific cause for failures other than rerunning the
command with e.g. git().
git(), low_git()
Framework for creating a command-stream suitable for git-fast-import.
void blob(string blob, string|void marker)
Upload data.
blobData to upload.
markerOptional export marker for referring to the data.
void cat_blob(string dataref)
Output a blob on the cat-blob-fd.
datarefReference to the blob to output.
void checkpoint()
Flush state to disk.
void command(sprintf_format cmd, sprintf_args ... args)
Send a raw command.
void commit(string ref, string|void commit_marker, string|void author_info, string committer_info, string message, string|void ... parents)
Create a new commit on a branch.
refReference to add the commit to.
Typically "refs/heads/" followed by a branchname,
or "refs/notes/commits".
commit_markerOptional export marker for referring to the new commit.
author_infoOptional author information. Defaults to committer_info.
committer_infoName, email and timestamp for the committer.
See format_author() for details.
messageCommit message.
parentsThe ordered set of parents for the commit.
Defaults to the current HEAD for ref, if it exists,
and to the empty set otherwise.
The set of files for the commit defaults to the set
for the first of the parents, and can be modified
with filemodify, filedelete, filecopy, filerename,
filedeleteall and notemodify.
Git.Export Git.Export()
Git.Export Git.Export(Stdio.File fd)
Git.Export Git.Export(string git_dir)
Create a new fast-import command-stream.
fdFile to write the command-stream to.
git_dirGit directory to modify. If the directory doesn't exist, it will be created empty. A git-fast-import session will be started for the directory to receive the command-stream.
If neither fd nor git_dir has been specified, the
command stream will be output to Stdio.stdout.
verbosityThe amount of verbosity on Stdio.stderr for various commands.
int done()
End the command-stream and wait for completion.
void export(string file_name, string|void git_name)
Convenience funtion for exporting a filesystem file or directory (recursively) to git.
file_nameName of the file on disc.
git_nameName of the file in git. Defaults to file_name.
void feature(string feature, string|void arg)
Require that the backend for the stream supports a certian feature.
featureFeature to require support for. Typically one of:
| Same as the corresponding command-line option. |
| |
| |
| |
| |
| |
| |
| Require the |
| |
| Require that the backend supports the |
| Require the stream to terminate with a |
void filecopy(string from, string to)
Copy a file or directory.
void filedelete(string path)
Delete a file.
void filedeleteall()
Delete all files.
Used to start a commit from a clean slate.
void filemodify(int mode, string path, string|void dataref)
Create or modify a file.
modeMode for the file. See the MODE_* constants.
pathPath to the file relative to the repository root.
datarefReference to the data for the file. One of:
| A mark reference set by a prior |
| Left out, |
void filerename(string from, string to)
Rename a file or directory.
void ls(string path, string|void dataref)
Output a file to the cat-blob-fd.
pathPath to the file to output.
datarefMarker, tag, commit or tree for the root. Defaults to the commit in progress.
void notemodify(string commit, string|void dataref)
Annotate a commit.
commitCommit to annotate.
datarefReference to the data for the annotation. One of:
| A mark reference set by a prior |
| Left out, |
Note that this command is typically only used when
a commit on a ref under "refs/notes/" is active.
void option(string option)
Set backend options.
void progress(string message)
Output a progress message.
messageMessage to output.
Note that each line of the message will be prefixed
with "progress ".
void reset(string ref, string|void committish)
Move a reference.
refReference to move.
committishCommit to reference.
This command can also be used to make light-weight tags.
tag
void tag(string name, string committish, string tagger_info, string message)
Create an annotated tag referring to a specific commit.
nameTag name. Note that it is automatically
prefixed with "refs/tags/".
committishCommit to tag.
tagger_infoName, email and timestamp for the tagger.
See format_author() for details.
messageMessage for the tag.
reset
GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. http://www.swox.com/gmp/
constant Gmp.version
The version of the current GMP library, e.g. "6.1.0".
Gmp.mpz fac(int x)
Returns the factorial of x (x!).
This program is used by the internal auto-bignum conversion. It can be used to explicitly type integers that are too big to be INT_TYPE. Best is however to not use this program unless you really know what you are doing.
Due to the auto-bignum conversion, all integers can be treated as
Gmp.mpz objects insofar as that they can be indexed with the
functions in the Gmp.mpz class. For instance, to calculate the
greatest common divisor between 51 and 85, you can
do 51->gcd(85). In other words, all the functions in
Gmp.mpz are also available here.
GMP floating point number.
The mantissa of each float has a user-selectable precision, limited only by available memory. Each variable has its own precision, and that can be increased or decreased at any time.
The exponent of each float is a fixed precision, one machine word on most systems. In the current implementation the exponent is a count of limbs, so for example on a 32-bit system this means a range of roughly 2^-68719476768 to 2^68719476736, or on a 64-bit system this will be greater.
Each variable keeps a size for the mantissa data actually in use. This means that if a float is exactly represented in only a few bits then only those bits will be used in a calculation, even if the selected precision is high.
All calculations are performed to the precision of the destination variable. Each function is defined to calculate with "infinite precision" followed by a truncation to the destination precision, but of course the work done is only what's needed to determine a result under that definition.
The precision selected for a variable is a minimum value, GMP may increase it a little to facilitate efficient calculation. Currently this means rounding up to a whole limb, and then sometimes having a further partial limb, depending on the high limb of the mantissa. But applications shouldn't be concerned by such details.
The mantissa in stored in binary, as might be imagined from the fact precisions are expressed in bits. One consequence of this is that decimal fractions like 0.1 cannot be represented exactly. The same is true of plain IEEE double floats. This makes both highly unsuitable for calculations involving money or other values that should be exact decimal fractions. (Suitably scaled integers, or perhaps rationals, are better choices.)
mpf functions and variables have no special notion of infinity or not-a-number, and applications must take care not to overflow the exponent or results will be unpredictable. This might change in a future release.
Note that the mpf functions are not intended as a smooth extension to IEEE P754 arithmetic. In particular results obtained on one computer often differ from the results on a computer with a different word size.
This class will use mpfr if available, in which case the precision will be exact and IEEE rules will be followed.
mpf Gmp.mpf.catalan
mpf Gmp.mpf.euler
mpf Gmp.mpf.ln2
mpf Gmp.mpf.pi
int hash_value( Gmp.mpf arg )
bool res = is_type(Gmp.mpf())
The Gmp.mpf object will claim to be a "float".
Perhaps it should also return true for "object"?
string sprintf(string format, ... Gmp.mpf arg ... )
bool res = !Gmp.mpf()
Gmp.mpf res = Gmp.mpf() * a
Gmp.mpf res = Gmp.mpf() + a
Gmp.mpf() += a
Gmp.mpf res = Gmp.mpf() - a
Gmp.mpf res = Gmp.mpf() / a
bool res = Gmp.mpf() < q
bool res = Gmp.mpf() == q
bool res = Gmp.mpf() > q
Gmp.mpf res = a * Gmp.mpf()
Gmp.mpf res = a + Gmp.mpf()
Gmp.mpf res = sv - Gmp.mpf()
Gmp.mpf res = sv / Gmp.mpf()
Gmp.mpf res = ~Gmp.mpf()
(string)Gmp.mpf()
(int)Gmp.mpf()
(float)Gmp.mpf()
mpf ceil()
Gmp.mpf Gmp.mpf(void|int|string|float|object x, void|int(0..) precision)
Gmp.mpf Gmp.mpf(string x, int(0..) precision, int(2..36) base)
mpf exp()
mpf exp10()
mpf exp2()
mpf floor()
mpf frac()
float get_float()
Returns the value of the object as a float.
int|object get_int()
int(0..) get_precision()
Returns the current precision, in bits.
string get_string()
mpf log()
mpf log10()
mpf log2()
mpf res = pow([Gmp.mpf]a, b) or mpf pow(int|float|Gmp.mpz|Gmp.mpf exp)
mpf rint()
mpf round()
Gmp.mpf set_precision(int(0..) prec)
Sets the precision of the current object to be at
least prec bits. The precision is limited to 128Kb.
The current object will be returned.
int sgn()
mpf sqr()
mpf res = sqrt([Gmp.mpf]a) or mpf sqrt()
mpf trunc()
Rational number stored in canonical form. The canonical from means that the denominator and the numerator have no common factors, and that the denominator is positive. Zero has the unique representation 0/1. All functions canonicalize their result.
int hash_value( Gmp.mpq arg )
bool res = is_type(Gmp.mpq())
string sprintf(string format, ... Gmp.mpq arg ... )
bool res = !Gmp.mpq()
Gmp.mpq res = Gmp.mpq() % a
a%b = a - floor(a/b)*b
Gmp.mpq res = Gmp.mpq() * a
Gmp.mpq res = Gmp.mpq() + a
Gmp.mpq() += a
Gmp.mpq res = Gmp.mpq() - a
Gmp.mpq res = Gmp.mpq() / a
bool res = Gmp.mpq() < q
bool res = Gmp.mpq() == q
bool res = Gmp.mpq() > q
Gmp.mpq res = a % Gmp.mpq()
Gmp.mpq res = a * Gmp.mpq()
Gmp.mpq res = a + Gmp.mpq()
Gmp.mpq res = sv - Gmp.mpq()
Gmp.mpq res = sv / Gmp.mpq()
Gmp.mpq res = ~Gmp.mpq()
Defined as -1-x.
(int)Gmp.mpq()
(string)Gmp.mpq()
(float)Gmp.mpq()
Casting to a string returns the number in the decimal fraction
format, where both decimal point and quotient is included only
if required. I.e. it is the same as calling get_string with 1
as argument.
Gmp.mpq Gmp.mpq(void|string|int|float|Gmp.mpz|Gmp.mpq x)
Gmp.mpq Gmp.mpq(int|Gmp.mpz numerator, int|Gmp.mpz denominator)
Gmp.mpq Gmp.mpq(string x, int base)
int den()
Returns the denominator. It is always positive.
float get_float()
int get_int()
string get_string(void|int decimal_fraction)
If decimal_fraction is zero or left out, the number is
returned as a string on the form "numerator/denominator",
where both parts are decimal integers. The numerator may be
negative, but the denominator is always positive.
If decimal_fraction is set, then the number is returned as a
(possibly negative) decimal fraction, i.e. a decimal number with
a decimal point somewhere inside. There is always at least one
digit before and after the decimal point.
If the number can be accurately described that way, i.e. without
an infinite number of decimals, then no denominator is included.
Otherwise the remaining denominator is added to the decimal
fraction after a "/". For example, 4711/100 is returned as
"47.11", 4711/200 as "23.555", and 4711/300 as
"47.11/3".
If decimal_fraction is 1 then the decimal fraction contains a
'.' only if there are decimals in it. If it is 2 or higher then
the decimal fraction always contains a '.' with at least one
digit before and after it.
In any case, there are no unnecessary padding zeroes at the beginning or end of any decimal number.
Gmp.mpq invert()
int num()
Returns the numerator.
int(-1..1) sgn()
Gmp.mpz implements very large integers. In fact, the only limitation on these integers is the available memory. The mpz object implements all the normal integer operations.
Note that the auto-bignum feature also makes these operations
available "in" normal integers. For instance, to calculate the
greatest common divisor between 51 and 85, you can
do 51->gcd(85).
int hash_value( Gmp.mpz arg )
Calculate a hash of the value.
Prior to Pike 7.8.359 this function returned the low 32-bits as an unsigned integer. This could in some common cases lead to very unbalanced mappings.
hash_value()
Gmp.mpz decode_value(string(8bit) data)
string(8bit) encode_value(Gmp.mpz data)
Gmp.mpz random( Gmp.mpz arg )
string sprintf(string format, ... Gmp.mpz arg ... )
bool res = !Gmp.mpz()
Gmp.mpz res = Gmp.mpz() % x
Gmp.mpz res = Gmp.mpz() & x
Gmp.mpz res = Gmp.mpz() * x
Gmp.mpz res = Gmp.mpz() + x
Gmp.mpz res = Gmp.mpz() - x
Gmp.mpz res = Gmp.mpz() / x
bool res = Gmp.mpz() < with
Gmp.mpz res = Gmp.mpz() << x
bool res = Gmp.mpz() == with
bool res = Gmp.mpz() > with
Gmp.mpz res = Gmp.mpz() >> x
Gmp.mpz res = Gmp.mpz() ^ x
Gmp.mpz res = x % Gmp.mpz()
Gmp.mpz res = x * Gmp.mpz()
Gmp.mpz|Gmp.mpq res = x ** Gmp.mpz()
Return x raised to the value of this object. The case when zero is
raised to zero yields one. When this object has a negative value and
x is not a float, a Gmp.mpq object will be returned.
pow
Gmp.mpz res = x + Gmp.mpz()
Gmp.mpz res = x - Gmp.mpz()
Gmp.mpz res = x / Gmp.mpz()
Gmp.mpz res = x << Gmp.mpz()
Gmp.mpz res = x >> Gmp.mpz()
Gmp.mpz res = Gmp.mpz() | x
Gmp.mpz res = ~Gmp.mpz()
Gmp.mpz bin(int k)
Return the binomial coefficient n over k, where
n is the value of this mpz object. Negative values of
n are supported using the identity
(-n)->bin(k) == (-1)->pow(k) * (n+k-1)->bin(k)
(See Knuth volume 1, section 1.2.6 part G.)
The k value can't be arbitrarily large. An error is thrown if
it's too large.
(string)Gmp.mpz()
(int)Gmp.mpz()
(float)Gmp.mpz()
Cast this mpz object to another type. Allowed types are string, int and float.
Gmp.mpz Gmp.mpz()
Gmp.mpz Gmp.mpz(string|int|float|object value)
Gmp.mpz Gmp.mpz(string value, int(2..62)|int(256)|int(-256) base)
Create and initialize a Gmp.mpz object.
valueInitial value. If no value is specified, the object will be initialized to zero.
baseBase the value is specified in. The default base is base 10. The
base can be either a value in the range [2..36]
(inclusive), in which case the numbers are taken from the ASCII
range 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
(case-insensitive), in the range [37..62] (inclusive), in
which case the ASCII range will be case sensitive, or either of
the values 256 or -256, in which case value
is taken to be the unsigned binary representation in network
byte order or reversed byte order respectively.
Values in base [2..62] can be prefixed with "+" or
"-". If no base is given, values prefixed with
"0b" or "0B" will be interpreted as binary.
Values prefixed with "0x" or "0X" will be
interpreted as hexadecimal. Values prefixed with "0"
will be interpreted as octal.
Leading zeroes in value are not significant when a base is
explicitly given. In particular leading NUL characters are not
preserved in the base 256 modes.
Before GMP 5.0 only bases 2-36 and 256 were supported.
string digits(void|int(2..62)|int(256)|int(-256) base)
Convert this mpz object to a string. If a base is given the
number will be represented in that base. Valid bases are 2-62 and
256 and -256. The default base is 10.
The bases 37 to 62 are not available when compiled with GMP earlier than version 5.
cast
string encode_json()
Gmp.mpz fac()
Return the factorial of this mpz object.
Since factorials grow very quickly, only small integers are supported. An error is thrown if the value in this mpz object is too large.
Gmp.mpz gcd(object|int|float|string ... args)
Return the greatest common divisor between this mpz object and all the arguments.
array(Gmp.mpz) gcdext(int|float|Gmp.mpz x)
Compute the greatest common divisor between this mpz object and
x. An array ({g,s,t}) is returned where g is
the greatest common divisor, and s and t are the
coefficients that satisfies
this * s + x * t = g
gcdext2, gcd
array(Gmp.mpz) gcdext2(int|float|Gmp.mpz x)
Compute the greatest common divisor between this mpz object and
x. An array ({g,s}) is returned where g is the
greatest common divisor, and s is a coefficient that
satisfies
this * s + x * t = gwhere t is some integer value.
gcdext, gcd
int hamdist(int x)
Calculates the hamming distance between this number and x.
Gmp.mpz invert(int|float|Gmp.mpz x)
Return the inverse of this mpz value modulo x. The returned
value satisfies 0 <= result < x.
An error is thrown if no inverse exists.
Gmp.mpz next_prime()
Returns the next higher prime for positive numbers and the next lower for negative.
The prime number testing is using Donald Knuth's probabilistic primality test. The chance for a false positive is pow(0.25,25).
int popcount()
For values >= 0, returns the population count (the number of set bits). For negative values (who have an infinite number of leading ones in a binary representation), -1 is returned.
Gmp.mpz res = pow([Gmp.mpz]a, b) or Gmp.mpz pow(int|float|Gmp.mpz x)
Return this mpz object raised to x. The case when zero is
raised to zero yields one.
powm
Gmp.mpz powm(int|string|float|Gmp.mpz exp, int|string|float|Gmp.mpz mod)
Return ( this->pow(.exp) ) % mod
pow
int(0..2) probably_prime_p(void|int count)
Return 2 if this mpz object is a prime, 1 if it probably is a prime, and 0 if it definitely is not a prime. Testing values below 1000000 will only return 2 or 0.
countThe prime number testing is using Donald Knuth's probabilistic primality test. The chance for a false positive is pow(0.25,count). Default value is 25 and resonable values are between 15 and 50.
int sgn()
Return the sign of the integer, i.e. 1 for positive
numbers and -1 for negative numbers.
int(0..) size(void|int base)
Return how long this mpz would be represented in the specified
base. The default base is 2.
int small_factor(void|int(1..) limit)
Gmp.mpz res = sqrt([Gmp.mpz]a) or Gmp.mpz sqrt()
Return the the truncated integer part of the square root of this mpz object.
array(Gmp.mpz) sqrtrem()
Toplevel GNOME applications would normally use one Gnome2.App widget as their toplevel window. You can create as many Gnome2.App widgets as you want, for example, some people use one GnomeApp per document their application loads.
Once you have created one instance of this widget, you would add your main application view information to this window by using set_contents() routine.
The GnomeApp has support for including a menubar, one or more toolbars and a statusbar for your application. It also takes care of intalling the accelerators for you when used in conjuction with the gnome-app-helper routines. The toolbars are inserted into Gnome2.Dock widgets.
The gnome-app-helper module provides various helper routines to simplify the configuration of your menus and toolbars, but you can create those yourself and use the set_menus(), add_toolbar(), set_toolbar(), add_dock_item() and add_docked(). Properties: string app-id
inherit GTK2.Window : Window
Gnome2.App add_docked(GTK2.Widget widget, string name, int behavior, int placement, int band_num, int band_position, int|void offset)
Create a new Gnome2.DockItem widget containing widget, and add it to app's dock with the specified layout information. Notice that, if automatic layout configuration is enabled, the layout is overridden by the saved configuration, if any.
widget : Widget to be added to app's dock
name : Name for the dock item that will contain toolbar
behavior : Behavior for the new dock item. One of GNOME_DOCK_ITEM_BEH_EXCLUSIVE, GNOME_DOCK_ITEM_BEH_LOCKED, GNOME_DOCK_ITEM_BEH_NEVER_FLOATING, GNOME_DOCK_ITEM_BEH_NEVER_HORIZONTAL, GNOME_DOCK_ITEM_BEH_NEVER_VERTICAL and GNOME_DOCK_ITEM_BEH_NORMAL
placement : Placement for the new dock item, one of Gnome2.DockTop, Gnome2.DockRight, Gnome2.DockBottom, Gnome2.DockLeft and Gnome2.DockFloating
band_num : Number of the band where the dock item should be placed
band_position : Position of the new dock item in band band_num
offset : Offset from the previous dock item in the band; if there is no previous item, offset from the beginning of the band.
Gnome2.App add_toolbar(GTK2.Toolbar toolbar, string name, int behavior, int placement, int band_num, int band_position, int|void offset)
Create a new Gnome2.DockItem widget containing toolbar, and add it to app's dock with the specified layout information. Notice that, if automatic layout configuration is enabled, the layout is overridden by the saved configuration, if any.
toolbar : Toolbar to be added to app's dock
name : Name for the dock item that will contain toolbar
behavior : Behavior for the new dock item. One or more of GNOME_DOCK_ITEM_BEH_EXCLUSIVE, GNOME_DOCK_ITEM_BEH_LOCKED, GNOME_DOCK_ITEM_BEH_NEVER_FLOATING, GNOME_DOCK_ITEM_BEH_NEVER_HORIZONTAL, GNOME_DOCK_ITEM_BEH_NEVER_VERTICAL and GNOME_DOCK_ITEM_BEH_NORMAL
placement : Placement for the new dock item, one of Gnome2.DockTop, Gnome2.DockRight, Gnome2.DockBottom, Gnome2.DockLeft and Gnome2.DockFloating
band_num : Number of the band where the dock item should be placed
band_position : Position of the new dock item in band band_num
offset : Offset from the previous dock item in the band; if there is no previous item, offset from the beginning of the band.
Gnome2.App Gnome2.App(void appname, void title)
Create a new (empty) application window. You must specify the application's name (used internally as an identifier). title can be left as 0, in which case the window's title will not be set.
Gnome2.App enable_layout_config(int enable)
Specify whether the the dock's layout configuration should be automatically saved via gnome-config whenever it changes, or not.
Gnome2.App set_contents(GTK2.Widget contents)
Sets the status bar of the application window.
Gnome2.App set_menus(GTK2.MenuBar menu_bar)
Sets the menu bar of the application window.
Gnome2.App set_statusbar(GTK2.Widget statusbar)
Sets the status bar of the application window.
Gnome2.App set_statusbar_custom(GTK2.Widget container, GTK2.Widget statusbar)
Sets the status bar of the application window, but use container as its container.
Gnome2.App set_toolbar(GTK2.Toolbar toolbar)
Sets the main toolbar of the application window.
A bar that GNOME applications put on the bottom of the windows to
display status, progress, hints for menu items or a minibuffer for
getting some sort of response. It has a stack for status messages
GTK2.Gnome2Appbar( 1, 1, GTK2.GNOME_PREFERENCES_USER )->set_progress_percentage( 0.4 );
![]()
Properties: int has-progress int has-status int interactivity
Signals: clear_prompt Emitted when the prompt is cleared. mixed user_data
user_response Emitted when the user hits enter after a prompt. mixed user_data
inherit GTK2.Hbox : Hbox
Gnome2.Appbar clear_prompt()
Remove any prompt.
Gnome2.Appbar clear_stack()
Remove all status messages from appbar, and display default status message (if present).
Gnome2.Appbar Gnome2.Appbar(void has_progress, void has_status, void interactivity)
Create a new GNOME application status bar. If has_progress is TRUE, a small progress bar widget will be created, and placed on the left side of the appbar. If has_status is TRUE, a status bar, possibly an editable one, is created.
interactivity determines whether the appbar is an interactive "minibuffer" or just a status bar. If it is set to Gnome2.PREFERENCES_NEVER, it is never interactive. If it is set to Gnome2.PREFERENCES_USER we respect user preferences from ui-properties. If it's Gnome2.PREFERENCES_ALWAYS we are interactive whether the user likes it or not. Basically, if your app supports both interactive and not (for example, if you use the gnome-app-util interfaces), you should use Gnome2.PREFERENCES_USER. Otherwise, use the setting you support. Please note that "interactive" mode is not functional now; GtkEntry is inadequate and so a custom widget will be written eventually.
GTK2.ProgressBar get_progress()
Returns GTK2.ProgressBar widget pointer, so that the progress bar may be manipulated further.
string get_response()
Get the response to the prompt, if any.
GTK2.Widget get_status()
Retrieves the statusbar widget.
Gnome2.Appbar pop()
Remove current status message, and display previous status message, if any. It is OK to call this with an empty stack.
Gnome2.Appbar push(string what)
Push a new status message onto the status bar stack, and display it.
Gnome2.Appbar refresh()
Reflect the current state of stack/default. Useful to force a set_status to disappear.
Gnome2.Appbar set_default(string default_status)
What to show when showing nothing else; defaults to "".
Gnome2.Appbar set_progress_percentage(float percentage)
Sets progress bar to the given percentage.
Gnome2.Appbar set_prompt(string prompt, int modal)
Put a prompt in the appbar and wait for a response. When the user responds or cancels, a "user-response" signal is emitted.
Gnome2.Appbar set_status(string status)
Sets the status label without changing widget state; next set or push will destroy this permanently.
Gnome2.Canvas is an engine for structured graphics that offers a rich imaging model, high performance rendering, and a powerful, high level API. It offers a choice of two rendering back-ends, one based on Xlib for extremely fast display, and another based on Libart, a sophisticated, antialiased, alpha-compositing engine. This widget can be used for flexible display of graphics and for creating interactive user interface elements.
A Gnome2.Canvas widget contains one or more Gnome2.CanvasItem objects. Items consist of graphing elements like lines, ellipses, polygons, images, text, and curves. These items are organized using Gnome2.CanvasGroup objects, which are themselves derived from Gnome2.CanvasItem. Since a group is an item it can be contained within other groups, forming a tree of canvas items. Certain operations, like translating and scaling, can be performed on all items in a group. See http://developer.gnome.org/doc/API/2.0/libgnomecanvas/GnomeCanvas.html for more information. Properties: int aa
Signals: draw_background
render_background
inherit GTK2.Layout : Layout
array c2w(int cx, int cy)
Converts canvas pixel coordinates to world coordinates.
Gnome2.Canvas Gnome2.Canvas(void anti_alias)
Create a new Gnome2.Canvas widget. Set anti_alias to true to create a canvas in antialias mode.
int get_center_scroll_region()
Returns whether the canvas is set to center the scrolling region in the window if the former is smaller than the canvas' allocation.
GDK2.Color get_color(string|void spec)
Allocates a color based on the specified X color specification. An omitted or empty string is considered transparent.
int get_color_pixel(int rgba)
Allocates a color from the RGBA value passed into this function. The alpha opacity value is discarded, since normal X colors do not support it.
int get_dither()
Returns the type of dithering used to render an antialiased canvas.
Gnome2.CanvasItem get_item_at(float x, float y)
Looks for the item that is under the specified position, which must be specified in world coordinates.
array get_scroll_offsets()
Queries the scrolling offsets of a canvas. The values are returned in canvas pixel units.
mapping get_scroll_region()
Queries the scrolling region of a canvas.
Gnome2.CanvasGroup root()
Queries the root group.
Gnome2.Canvas scroll_to(int cx, int cy)
Makes a canvas scroll to the specified offsets, given in canvas pixel units. The canvas will adjust the view so that it is not outside the scrolling region. This function is typically not used, as it is better to hook scrollbars to the canvas layout's scrolling adjustments.
Gnome2.Canvas set_center_scroll_region(int setting)
When the scrolling region of the canvas is smaller than the canvas window, e.g. the allocation of the canvas, it can be either centered on the window or simply made to be on the upper-left corner on the window.
Gnome2.Canvas set_dither(int dither)
Controls the dithered rendering for antialiased canvases. The value of dither should be GDK2.RgbDitherNone, GDK2.RgbDitherNormal, or GDK2.RgbDitherMax. The default canvas setting is GDK2.RgbDitherNormal.
Gnome2.Canvas set_pixels_per_unit(float n)
Sets the zooming factor of a canvas by specifying the number of pixels that correspond to one canvas unit.
The anchor point for zooming, i.e. the point that stays fixed and all others zoom inwards or outwards from it, depends on whether the canvas is set to center the scrolling region or not. You can contorl this using the set_center_scroll_region() function. If the canvas is set to center the scroll region, then the center of the canvas window is used as the anchor point for zooming. Otherwise, the upper-left corner of the canvas window is used as the anchor point.
Gnome2.Canvas set_scroll_region(float x1, float y1, float x2, float y2)
Sets the scrolling region of a canvas to the specified rectangle. The canvas will then be able to scroll only within this region. The view of the canvas is adjusted as appropriate to display as much of the new region as possible.
array w2c(float wx, float wy)
Converts world coordinates into canvas pixel coordinates.
array w2c_affine()
Gets the affine transform that converts from world coordinates to canvas pixel coordinates.
array w2c_d(float wx, float wy)
Converts world coordinates into canvas pixel coordinates. This version returns coordinates in floating point coordinates, for greater precision.
array window_to_world(float winx, float winy)
Converts window-relative coordinates into world coordinates. You can use this when you need to convert mouse coordinates into world coordinates, for example.
array world_to_window(float worldx, float worldy)
Converts world coordinates into window-relative coordinates.
inherit Gnome2.CanvasShape : CanvasShape
Properties: string path int wind
inherit Gnome2.CanvasGroup : CanvasGroup
inherit Gnome2.CanvasRE : CanvasRE
inherit Gnome2.CanvasItem : CanvasItem
This is the base class for all canvas items. Canvas items are the drawing elements of a Gnome2.Canvas. Example items include lines, ellipses, polygons, images, text, curves, and even arbitary GTK+ widgets.
Properties: Gnome2.CanvasItem parent
Signals: event
inherit GTK2.Object : Object
Properties: float arrow-shape-a float arrow-shape-b float arrow-shape-c int cap-style string fill-color GDK2.Color fill-color-gdk int fill-color-rgba GDK2.Drawable fill-stipple int first-arrowhead int join-style int last-arrowhead int line-style Gnome2.CanvasPoints points int smooth int spline-steps int width-pixels float width-units
inherit Gnome2.CanvasItem : CanvasItem
Properties: int anchor float height int height-in-pixels int height-set GDK2.Pixbuf pixbuf float width int width-in-pixels int width-set float x int x-in-pixels float y int y-in-pixels
inherit Gnome2.CanvasItem : CanvasItem
Properties: float x1 float x2 float y1 float y2
inherit Gnome2.CanvasShape : CanvasShape
inherit Gnome2.CanvasRE : CanvasRE
Properties: int anchor int cursor-blink int cursor-visible int direction int editable int grow-height float height int indent int justification int left-margin int pixels-above-lines int pixels-below-lines int pixels-inside-wrap int right-margin string text int visible float width int wrap-mode float x float y
Signals: tag_changed
inherit Gnome2.CanvasItem : CanvasItem
GTK2.TextBuffer get_buffer()
Get the text buffer.
Gnome2.CanvasRichText set_buffer(GTK2.TextBuffer buffer)
Set the text buffer.
Properties: int cap-style string dash string fill-color GDK2.Color fill-color-gdk int fill-color-rgba GDK2.Drawable fill-stipple int join-style float miterlimit string outline-color GDK2.Color outline-color-gdk int outline-color-rgba GDK2.Drawable outline-stipple int width-pixels float width-units int wind
inherit Gnome2.CanvasItem : CanvasItem
Properties: int anchor Pango.AttrList attributes int clip float clip-height float clip-width string family int family-set string fill-color GDK2.Color fill-color-gdk int fill-color-rgba GDK2.Drawable fill-stipple string font Pango.FontDescription font-dest int justification string markup int rise int rise-set float scale int scale-set int size float size-points int size-set Pango.Stretch stretch int stretch-set int strikethrough int strikethrough-set Pango.Style style int style-set string text float text-height float text-width Pango.Underline underline int underline-set Pango.Variant variant int variant-set int weight float x float x-offset float y float y-offset
inherit Gnome2.CanvasItem : CanvasItem
Properties: int anchor float height int size-pixels GTK2.Widget widget float width float x float y
inherit Gnome2.CanvasItem : CanvasItem
Signals: connect Called once the client has been connected to the signal manager. int arg1, mixed user_data
die Called when the session manager wants the client to shut down. mixed user_data
disconnect Called when the client is disconnected from the session manager. mixed user_data
save_complete Called when the session manager has finished checkpointing all of the clients. Clients are then free to change their state. mixed user_data
save_yourself Called when either a "SaveYourself" or a "SaveYourselfPhase2" call is made by the session manager. int arg1: the phase of the "SaveYourself" command ('1' or '2'). int arg2: the data which should be saved (local, global, or both). int arg3: true if the session manager is shutting down. int arg4: how the client is allowed to interact with the user while saving. int arg5: true if this is to be a "fast" shutdown. mixed user_data
shutdown_cancelled Called if the session manager had sent a "SaveYourself" to all clients in preparation for shutting down and the shutdown was then cancelled. A client can then continue running and change its state. mixed user_data
inherit GTK2.Object : Object
Gnome2.Client Gnome2.Client()
Gets the master session management client.
Gnome2.Client disconnect()
Disconnect the client from the session manager.
Gnome2.Client flush()
This will force the underlying connection to the session manager to be flushed. This is useful if you have some pending changes that you want to make sure get committed.
string get_config_prefix()
Get the config prefix. This config prefix provides a suitable place to store any details about the state of the client which can not be described using the app's command line arguments (as set in the restart command).
string get_desktop_id()
Get the client ID of the desktop's current instance, i.e. if you consider the desktop as a whole as a session managed app, this returns its session ID using a gnome extension to session management. May return empty for apps not running under a recent version of gnome-session; apps should handle that case.
int get_flags()
Determine the client's status with the session manager.
string get_global_config_prefix()
Get the config prefix that will be returned by get_config_prefix() for clients which have NOT been restarted or cloned (i.e. for clients started by the user without '--sm-' options). This config prefix may be used to write the user's preferred config for these "new"clients".
You could also use this prefix as a place to store and retrieve config details that you wish to apply to ALL instances of the app. However, this practice limits the users freedom to configure each instance in a different way so it should be used with caution.
string get_id()
Returns the session management ID.
string get_previous_id()
Get the session management ID from the previous session.
Gnome2.Client request_phase_2()
Request the session manager to emit the "save-yourself" signal for a second time after all the clients in the session have ceased interacting with the user and entered an idle state. This might be useful if your app managers other apps and requires that they are in an idle state before saving its final data.
Gnome2.Client request_save(int save_style, int shutdown, int interact_style, int fast, int global)
Request the session manager to save the session in some way. The arguments correspond with the arguments passed to the "save-yourself" signal handler.
The save_style (GNOME_SAVE_BOTH, GNOME_SAVE_GLOBAL and GNOME_SAVE_LOCAL) indicates whether the save should
affect data accessible to other users (GTK2.GNOME_SAVE_GLOBAL) or only the
state visible to the current user (GTK2.GNOME_SAVE_LOCAL), or both. Setting
shutdown to true will initiate a logout. The interact_style
(GNOME_INTERACT_ANY, GNOME_INTERACT_ERRORS and GNOME_INTERACT_NONE) specifies which kinds of interaction will be
available. Setting fast to true will limit the save to setting the session
manager properties plus any essential data. Setting the value of global to
true will request that all the other apps in the session do a save as well.
A global save is mandatory when doing a shutdown.
Gnome2.Client save_any_dialog(GTK2.Dialog dialog)
May be called during a "save-yourself" handler to request that a (modal) dialog is presented to the user. The session manager decides when the dialog is shown, but it will not be shown it unless the session manager is sending an interaction style of GTK2.GNOME_INTERACT_ANY. "Cancel" and "Log out" buttons will be added during a shutdown.
Gnome2.Client save_error_dialog(GTK2.Dialog dialog)
May be called during a "save-yourself" handler when an error has occurred during the save.
Gnome2.Client set_clone_command(array argv)
Set a command the session manager can use to create a new instance of the application. Not implemented yet.
Gnome2.Client set_current_directory(string dir)
Set the directory to be in when running shutdown, discard, restart, etc. commands.
Gnome2.Client set_discard_command(array argv)
Provides a command to run when a client is removed from the session. It might delete session-specific config files, for example. Executing the discard command on the local host should delete the information saved as part of the session save that was in progress when the discard command was set. For example: string prefix=client->get_config_prefix(); array argv=({ "rm","-r" }); argv+=({ Gnome2.Config->get_real_path(prefix) }); client->set_discard_command(argv); Not implemented yet.
Gnome2.Client set_environment(string name, string value)
Set an environment variable to be placed in the client's environment prior to running restart, shutdown, discard, etc. commands.
Gnome2.Client set_global_config_prefix(string prefix)
Set the value used for the global config prefix. The global config prefix defaults to a name based on the name of the executable. This function allows you to set it to a different value. It should be called BEFORE retrieving the config prefix for the first time. Later calls will be ignored.
Gnome2.Client set_priority(int priority)
The gnome-session manager restarts clients in order of their priorities in a similar way to the start up ordering in SysV. This function allows the app to suggest a position in this ordering. The value should be between 0 and 99. A default value of 50 is assigned to apps that do not provide a value. The user may assign a different priority.
Gnome2.Client set_resign_command(array argv)
Some clients can be "undone", removing their effects and deleting any saved state. For example, xmodmap could register a resign command to undo the keymap changes it saved.
Used by clients that use the GTK2.GNOME_RESTART_ANYWAY restart style to undo their effects (these clients usually perform initialization functions and leave effects behind after they die). The resign command combines the effects of a shutdown command and a discard command. It is executed when the user decides that the client should cease to be restarted. Not implemented yet.
Gnome2.Client set_restart_command(array argv)
When clients crash or the user logs out and back in, they are restarted. This command should perform the restart. Executing the restart command on the local host should reproduce the state of the client at the time of the session save as closely as possible. Saving config info under the get_config_prefix() is generally useful. Not implemented yet.
Gnome2.Client set_restart_style(int style)
Tells the session manager how the client should be restarted in future
sessions. One of GNOME_RESTART_ANYWAY, GNOME_RESTART_IF_RUNNING, GNOME_RESTART_IMMEDIATELY and GNOME_RESTART_NEVER
Gnome2.Client set_shutdown_command(array argv)
GTK2.GNOME_RESTART_ANYWAY clients can set this command to run when the user logs out but the client is no longer running.
Used by clients that use the GTK2.GNOME_RESTART_ANYWAY restart style to undo their effects (these clients usually perform initialization functions and leave effects behind after they die). The shutdown command simply undoes the effects of the client. It is executed during a normal logout. Not implemented yet.
The GnomeDateEdit widget provides a way to enter dates and times
with a helper calendar to let the user select the date.
GTK2.Gnome2DateEdit(time(),1,1);
![]()
GTK2.Gnome2DateEdit(time(),0,1);
![]()
Properties: int dateedit-flags int initial-time int lower-hour int time int upper-hour
Signals: date_changed
time_changed
inherit GTK2.Hbox : Hbox
Gnome2.DateEdit Gnome2.DateEdit(void the_time, void show_time, void use_24_format)
Creates a new GnomeDateEdit widget which can be used to provide an easy to use way for entering dates and times.
int get_flags()
Get the flags.
int64 get_initial_time()
Queries the initial time that was set using set_time() or during creation.
int64 get_time()
Return the time entered in the widget.
Gnome2.DateEdit set_flags(int flags)
Bitwise or of GNOME_DATE_EDIT_24_HR, GNOME_DATE_EDIT_SHOW_TIME and GNOME_DATE_EDIT_WEEK_STARTS_ON_MONDAY.
Gnome2.DateEdit set_popup_range(int low_hour, int up_hour)
Sets the range of times that will be provide by the time popup selectors.
Gnome2.DateEdit set_time(int64 the_time)
Changes the displayed date and time in the GnomeDateEdit widget to be the one represented by the_time.
The GNOME druid is a system for assisting the user with installing a service. It is roughly equivalent in functionality to the "Wizards" available in Windows.
There are two major parts of the druid, the Gnome2.Druid widget, and the set of W(Gnome2.DruidPage) widgets. The Gnome2.Druid widget is the main widget that interacts with the user. It has a Next, a Prev, and a Cancel button, and acts as a container for the pages. It is not a top-level window, so it needs to be put in a W(GTK2.Window) in almost all cases. The W(Gnome2.DruidPage) is a virtual widget, from which all of the actual content of the page inherits from. There are currently three of these available within gnome-libs.
GNOME druids are fairly simple to program with. You start by creating a GnomeDruid into which you put all of your pages. This widget will handle the presentation of the W(GnomeDruidPage) widgets.
You then create all appropriate W(GnomeDruidPage) widgets. There are three implementations of these, although there is no reason why more couldn't be written. They are the W(GnomeDruidPageStart), the W(GnomeDruidPageStandard), and the W(GnomeDruidPageFinish). The W(GnomeDruidPageStandard) acts as a W(Container), and is probably the most commonly used druid page. The other ones, as their names might suggest, are used at the endpoints of the druid. More information on the specific properties of these widgets can be found on their respective pages.
You will need to add the pages to the druid in order for them to appear. The druid itself keeps an internal list of all pages, and using the prepend_page(), append_page(), and insert_page() functions will place them into it.
Properties: int show-finish int show-help
Signals: cancel This signal is emitted when the "cancel" button has been pressed. Note that the current druid page has the option to trap the signal and use it, if need be, preventing this signal from being emitted.
help
inherit GTK2.Container : Container
Gnome2.Druid append_page(Gnome2.DruidPage page)
This will append a GnomeDruidPage into the internal list of pages that the druid has.
Gnome2.Druid Gnome2.Druid()
Create a new druid
Gnome2.Druid insert_page(Gnome2.DruidPage back_page, Gnome2.DruidPage page)
This will insert page after back_page into the list of internal pages that the druid has. If back_page is not present in the list or is 0, page will be prepended to the list.
Gnome2.Druid prepend_page(Gnome2.DruidPage page)
This will prepend a GnomeDruidPage into the internal list of pages that the druid has.
Gnome2.Druid set_buttons_sensitive(int back_sensitive, int next_sensitive, int cancel_sensitive, int help_sensitive)
Sets the sensitivity of the druid's control-buttons. If the variables are TRUE, then they will be clickable. This function is used primarily by the actual W(GnomeDruidPage) widgets.
Gnome2.Druid set_page(Gnome2.DruidPage page)
This will make page the currently showing page in the druid. page must already be in the druid.
Gnome2.Druid set_show_finish(int show_finish)
Sets the text on the last button on the druid. If show_finish is TRUE, then the text becomes "Finish". If show_finish is FALSE, then the text becomes "Cancel".
Gnome2.Druid set_show_help(int show_help)
Sets the "Help" button on the druid to be visible in the lower left corner of the widget, if show_help is true.
This widget is a virtual widget to define the interface to a druid page. It's descendants are placed in a W(Gnome2.Druid) widget.
Signals: back
cancel
finish
next
prepare
inherit GTK2.Bin : Bin
int back()
This will emit the "back" signal for that particular page.
int cancel()
This will emit the "cancel" signal for that particular page.
Gnome2.DruidPage Gnome2.DruidPage()
Creates a new Gnome2.DruidPage.
Gnome2.DruidPage finish()
This emits the "finish" signal for the page.
int next()
This will emit the "next" signal for that particular page. It is called by gnome-druid exclusviely. It is expected that non-linear Druid's will override this signal and return true if it handles changing pages.
Gnome2.DruidPage prepare()
This emits the "prepare" signal for the page. It is called by gnome-druid exclusively. This function is called immediately prior to a druid page being show so that it can "prepare" for display.
inherit Gnome2.DruidPage : DruidPage
Gnome2.DruidPageEdge Gnome2.DruidPageEdge(void position, void anti_alias)
Create a new Gnome2.DruidPageEdge, with optional anti-aliasing.
Gnome2.DruidPageEdge set_bg_color(GDK2.Color color)
This will set the background color.
Gnome2.DruidPageEdge set_logo(GDK2.Pixbuf logo)
Sets a GDK2.Pixbuf as the logo in the top right corner. If omitted, then no logo will be displayed.
Gnome2.DruidPageEdge set_logo_bg_color(GDK2.Color color)
Sets the color behind the druid page's logo.
Gnome2.DruidPageEdge set_text(sprintf_format text, sprintf_args ... fmt)
Sets the contents of the text portion.
Gnome2.DruidPageEdge set_text_color(GDK2.Color color)
Sets the color of the text in the body of the page.
Gnome2.DruidPageEdge set_textbox_color(GDK2.Color color)
Sets the color of the background in the main text area of the page.
Gnome2.DruidPageEdge set_title(string title)
Sets the contents of the page's title text.
Gnome2.DruidPageEdge set_title_color(GDK2.Color color)
Sets the color of the title text.
Gnome2.DruidPageEdge set_top_watermark(GDK2.Pixbuf watermark)
Sets a GDK2.Pixbuf as the watermark on top of the top strip on the druid. If watermark is omitted, it is reset to the normal color.
Gnome2.DruidPageEdge set_watermark(GDK2.Pixbuf watermark)
Sets a GDK2.Pixbuf as the watermark on the left strip on the druid. If watermark is omitted, it is reset to the normal color.
Properties: string background GDK2.Color background-gdk int background-set string contents-background GDK2.Color contents-background-gdk int contents-background-set GDK2.Pixbuf logo string logo-background GDK2.Color logo-background-gdk int logo-background-set string title string title-foreground GDK2.Color title-foreground-gdk int title-foreground-set GDK2.Pixbuf top-watermark
inherit Gnome2.DruidPage : DruidPage
Gnome2.DruidPageStandard append_item(string question, GTK2.Widget item, string additional_info)
Convenience function to add a GTK2.Widget to the vbox. This function creates a new contents section that has the question text followed by the item widget and then the additional_info text, all stacked vertically from top to bottom.
The item widget could be something like a set of radio checkbuttons requesting a choice from the user.
Gnome2.DruidPageStandard Gnome2.DruidPageStandard(void title, void logo, void top_watermark)
Construct a new Gnome2.DruidPageStandard.
Gnome2.DruidPageStandard set_background(GDK2.Color color)
Sets the background color of the top section.
Gnome2.DruidPageStandard set_contents_background(GDK2.Color color)
Sets the color of the main contents section's background.
Gnome2.DruidPageStandard set_logo(GDK2.Pixbuf logo)
Sets a GDK2.Pixbuf as the logo in the top right corner. If omitted, then no logo will be displayed.
Gnome2.DruidPageStandard set_logo_background(GDK2.Color color)
Sets the background color of the logo.
Gnome2.DruidPageStandard set_title(string title)
Sets the title.
Gnome2.DruidPageStandard set_title_foreground(GDK2.Color color)
Sets the title text to the specified color.
Gnome2.DruidPageStandard set_top_watermark(GDK2.Pixbuf watermark)
Sets a GDK2.Pixbuf as the watermark on top of the top strip on the druid. If watermark is omitted, it is reset to the normal color.
This widget is a GtkButton button that contains a URL. When clicked it invokes the configured browser for the URL you provided.
GTK2.Gnome2Href( "http://www.gnome.org", "GNOME Web Site" )
![]()
GTK2.Gnome2Href( "http://www.gnome.org" )
![]()
Properties: string text string url
Style properties: GDK.Color link-color
inherit GTK2.Button : Button
Gnome2.Href Gnome2.Href(void url, void label)
Created a GNOME href object, a label widget with a clickable action and an associated URL. If label is set to 0, url is used as the label.
string get_text()
Returns the contents of the label widget used to display the link text.
string get_url()
Return the url
Gnome2.Href set_text(sprintf_format text, sprintf_args ... fmt)
Sets the internal label widget text (used to display a URL's link text) to the given value.
Gnome2.Href set_url(string url)
Sets the internal URL
This widget provides the facilities to select an icon. An icon is displayed inside a button, when the button is pressed, an Icon selector (a dialog with a W(GnomeIconSelection) widget) pops up to let the user choose an icon. It also allows one to Drag and Drop the images to and from the preview button. Properties: string browse-dialog-title string filename string history-id GTK2.Dialog pick-dialog string pixmap-subdir
Signals: browse
changed
inherit GTK2.Vbox : Vbox
Gnome2.IconEntry Gnome2.IconEntry(void history_id, void title)
Creates a new icon entry widget
string get_filename()
Gets the file name of the image if it was possible to load it into the preview. That is, it will only return a filename if the image exists and it was possible to load it as an image.
GTK2.Widget pick_dialog()
If a pick dialog exists, returns it. This is if you need to do something with all dialogs. You would use the browse signal with connect_after to get the pick dialog when it is displayed.
Gnome2.IconEntry set_browse_dialog_title(string title)
Set the title of the browse dialog.
int set_filename(string filename)
Sets the icon of Gnome2.IconEntry to be the one pointed to by filename.
Gnome2.IconEntry set_history_id(string history_id)
Set the history_id of the entry in the browse dialog and reload the history.
Gnome2.IconEntry set_pixmap_subdir(string subdir)
Sets the subdirectory below gnome's default pixmap directory to use as the default path for the file entry.
An icon listing/chooser display.
inherit GTK2.Vbox : Vbox
Gnome2.IconSelection add_defaults()
Adds the default pixmap directory into the selection widget.
Gnome2.IconSelection add_directory(string dir)
Adds the icons from the directory dir to the selection widget.
Gnome2.IconSelection clear(int|void not_shown)
Clear the currently shown icons, the ones that weren't shown yet are not cleared unless the not_shown parameter is given, in which case even those are cleared.
Gnome2.IconSelection Gnome2.IconSelection()
Creates a new icon selection widget, it uses a W(GnomeIconList) for the listing of icons
GTK2.Widget get_box()
Gets the W(Vbox) widget.
string get_icon(int full_path)
Gets the currently selected icon name, if full_path is true, it returns the full path to the icon, if none is selected it returns 0.
Gnome2.IconSelection select_icon(string filename)
Selects the icon filename. This icon must have already been added and shown
Gnome2.IconSelection show_icons()
Shows the icons inside the widget that were added with add_defaults and add_directory. Before this function isf called the icons aren't actually added to the listing and can't be picked by the user.
Gnome2.IconSelection stop_loading()
Stop the loading of images when we are in the loop in show_icons.
protected inherit .create_pie : create_pie
Image.Image pie(mapping(string:mixed) diagram_data)
Image.Image bars(mapping(string:mixed) diagram_data)
Image.Image sumbars(mapping(string:mixed) diagram_data)
Image.Image line(mapping(string:mixed) diagram_data)
Image.Image norm(mapping(string:mixed) diagram_data)
Image.Image graph(mapping(string:mixed) diagram_data)
Generate a graph of the specified type. See check_mapping
for an explanation of diagram_data.
mapping(string:mixed) check_mapping(mapping(string:mixed) diagram_data, string type)
This function sets all unset elements in diagram_data to its
default value as well as performing some simple sanity checks.
This function is called from within pie, bars, sumbars,
line, norm and graph.
diagram_data | Default: "linear" Will be set to "2D" for pie below Only "linear" works for now. |
| Default: 0 If present a Pie-chart will be toned. |
| Default: 10 How much 3D-depth a graph will have in pixels Default is 10. |
| Default: ({({1.0}), ({2.0}), ({4.0})}) Will be set to something else with graph An array of arrays. Each array describing a data-set. The graph-function however should be fed with an array of arrays with X,Y-pairs. Example: ({({1.0, 2.0, 3.0}),({1.2, 2.2, 3.8})}) draws stuff in yellow with the values (1.0, 2.0, 3.0), and (1.2, 2.2, 3.8) in blue. |
| Default: 0 Should have four elements ({xquantity, yquantity, xunit, yunit}). The strings will be written on the axes. |
| Default: 0 An array(string) with the text that will be written under the X-axis. This should be the same size as sizeof(data). |
| Default: 0 An array(string) with the text that will be written to the left of the Y-axis. |
| Default: 10 The size of the text. Default is 10. |
| Default: 1.0 Width of the lines that draws data in Graph and line. Default is 1.0 |
| Default: same as fontsize The size of the text for labels. |
| Default: same as fontsize The size of the text for the legend. |
| Default: 0 The texts that will be written the legend. |
| Default: 0 An array(float) that describes where the ynames should be placed. The numbers are like the data-numbers. Default is equally distributed. |
| Default: 0 An array(float) that describes where the ynames should be placed. The numbers are like the data-numbers. Default is equally distributed. |
| Default: 100 X-size of the graph in pixels. |
| Default: 100 Y-size of the graph in pixels. |
| Default: 0 An image that the graph will be drawn on. |
| Default: 0 The color of the text in the legend. Default is? |
| Default: 0 I have no idea. |
| Default: 0 The bakground-color. If the the background is a image this color is used for antialias the texts. |
| Default: 0 Some sort of image... |
| Default: ({0,0,0}) The color of the axis. |
| Default: 0 An array of colors for the datasets. |
| Default: 0 An array of color that do something... |
| Default: ({0,0,0}) Color of the text. Default is black. |
| Default: 0 Color of the labeltexts. |
| Default: "hor" Can be "hor" or "vert". Orientation of the graph. |
| Default: 0 Width of lines (the axis and their like). |
| Default: 0 Width of the outline-lines. Default is 0. |
| Default: 0 If the vertical grid should be present. |
| Default: 0 If the horizontal grid should be present. |
| Default: 0 Width of the grid. Default is linewidth/4. |
| Default: 0 How much a the Pie in a Pie-shart should be rotated in degrees. |
| Default: 0 Makes the first Pie-slice be centered. |
| Default: 0 Draws the graph black and white. |
| Default: 0 Writes the numbers in eng format. |
| Default: 0 Writes the numbers in engformat except for 0.1 < x < 1.0 |
| Default: 0 Where the X-axis should start. This will be overrided by datavalues. |
| Default: 0 Where the Y-axis should start. This will be overridden by datavalues. |
| Default: 0 A string with the name of the graph that will be written at top of the graph. |
| Default: 0 The color of the name. |
| Default: Image.Font() The font that will be used. |
| Default: ({0,0,0} The color of the grid. Default is black. |
Graph sub-module for drawing bars.
inherit .create_graph : create_graph
Graph sub-module for drawing graphs.
create_graph draws a graph but there are also some other functions
used by create_pie and create_bars.
inherit .polyline : polyline
Graph sub-module for drawing pie-charts.
inherit .create_bars : create_bars
Graph sub-module providing draw functions.
High performance webserver optimized for somewhat static content.
HTTPAccept is a less capable WWW-server than the
Protocols.HTTP.Server server, but for some applications it can be
preferable. It is significantly more optimized, for most uses, and
can handle a very high number of requests per second on even
low end machines.
string HTTPAccept.LogEntry.from
string HTTPAccept.LogEntry.method
string HTTPAccept.LogEntry.protocol
string HTTPAccept.LogEntry.raw
int HTTPAccept.LogEntry.received_bytes
int HTTPAccept.LogEntry.reply
int HTTPAccept.LogEntry.sent_bytes
int HTTPAccept.LogEntry.time
string HTTPAccept.LogEntry.url
mapping(string:int) cache_status()
Returns information about the cache.
| The number of hits since start |
| The number of misses since start |
| The number of misses that were stale hits, and not used |
| The total current size |
| The number of entries in the cache |
| The maximum size of the cache |
| The number of bytes sent since the last call to cache_status |
| The number of bytes received since the last call to cache_status |
| The number of requests received since the last call to cache_status |
HTTPAccept.Loop HTTPAccept.Loop(Stdio.Port port, RequestProgram program, function(RequestProgram:void) request_handler, int cache_size, bool keep_log, int timeout)
Create a new HTTPAccept.
This will start a new thread that will listen for requests on the
port, parse them and pass on requests, instanced from the
program class (which has to inherit RequestProgram to the
request_handler callback function.
cache_size is the maximum size of the cache, in bytes.
keep_log indicates if a log of all requests should be kept.
timeout if non-zero indicates a maximum time the server will wait for requests.
array(LogEntry) log_as_array()
Return the current log as an array of LogEntry objects.
int log_as_commonlog_to_file(Stdio.Stream fd)
Write the current log to the specified file in a somewhat common commonlog format.
Will return the number of bytes written.
int log_size()
Returns the number of entries waiting to be logged.
bool logp()
Returns true if logging is enabled
string HTTPAccept.RequestProgram.client
The user agent
string HTTPAccept.RequestProgram.data
Any payload that arrived with the request
mapping(string:array(string)) HTTPAccept.RequestProgram.headers
All received headers
string HTTPAccept.RequestProgram.method
The method (GET, PUT etc)
Stdio.NonblockingStream HTTPAccept.RequestProgram.my_fd
The filedescriptor for this request.
string HTTPAccept.RequestProgram.not_query
The part of the URL before the first '?'.
multiset(string) HTTPAccept.RequestProgram.pragma
Tokenized pragma headers
string HTTPAccept.RequestProgram.prot
The protocol part of the request. As an example "HTTP/1.1"
string HTTPAccept.RequestProgram.query
The part of the URL after the first '?'
string HTTPAccept.RequestProgram.raw
The full request
string HTTPAccept.RequestProgram.raw_url
The raw URL received, the part after the method and before the protocol.
string HTTPAccept.RequestProgram.referer
The referer header
string HTTPAccept.RequestProgram.remoteaddr
The remote address
string HTTPAccept.RequestProgram.rest_query
The part of the URL after the first '?' that does not seem to be query variables.
string HTTPAccept.RequestProgram.since
The get-if-not-modified, if set.
int HTTPAccept.RequestProgram.time
The time_t when the request arrived to the server
mapping(string:string) HTTPAccept.RequestProgram.variables
Parsed query variables
void output(string data)
Send data directly to the remote side.
void reply(string data)
void reply(string headers, Stdio.File fd, int len)
void reply(int(0) ignore, Stdio.File fd, int len)
Send a reply to the remote side.
In the first case the data will be sent.
In the second case the headers will be sent, then len bytes from fd.
In the last case len bytes from fd will be sent.
void reply_with_cache(string data, int(1..) stay_time)
Send data as the reply, and keep it as a cache entry to
requests to this URL for stay_time seconds.
inherit "___Java" : "___Java"
object Java.pkg
Singleton 'package' object.
Usage: object cls = Java.pkg.java.lang.String;
or: object cls = Java.pkg["java/lang/String"];
cls is a jclass object; call it to create a jobject, which will have all the methods of the Java class.
Example: Java.pkg.FooClass()->getResult();
jobject JArray(array a)
jobject JBoolean(int i)
jobject JFloat(float f)
jobject JHashMap(mapping m)
jobject JInteger(int i)
jobject JString(string s)
Interface to one Java class. Can be called to construct a jobject.
Obtained normally via Java.pkg.`[] and not created directly.
An instantiated Java object. Has methods for all the Java object's methods. Can be cast to string.
NOTE: Use indices(x) to get a list of the available methods.
Constructed from a jclass object.
bool authenticate(string user, string password)
PLIS, Permuted Lisp. A Lisp language somewhat similar to scheme.
Environment default_environment()
Creates a new environment on which it runs init_functions, init_specials and the following boot code.
(begin
(defmacro (cddr x)
(list (quote cdr) (list (quote cdr) x)))
(defmacro (cadr x)
(list (quote car) (list (quote cdr) x)))
(defmacro (cdar x)
(list (quote cdr) (list (quote car) x)))
(defmacro (caar x)
(list (quote car) (list (quote car) x)))
(defmacro (when cond . body)
(list (quote if) cond
(cons (quote begin) body)))
(define (map fun list)
(if (null? list) (quote ())
(cons (fun (car list))
(map fun (cdr list)))))
(defmacro (let decl . body)
(cons (cons (quote lambda)
(cons (map car decl) body))
(map cadr decl))))
void init_functions(Environment environment)
Adds the functions +, *, -, =, <, >,
concat, read-string, eval,
apply, global-environment, var, cdr, null?,
setcar!, setcdr!, cons and list to the
environment.
void init_specials(Environment environment)
Adds the special functions quote, set!, setq,
while, define, defmacro, lambda, if, and, or,
begin and catch to the environment.
void main()
Instantiates a copy of the default environment and starts an interactive main loop that connects to standard I/O. The main loop is as follows:
(begin
(define (loop)
(let ((line (read-line
object Languages.PLIS.Binding.value
protected local void __create__(object value)
Languages.PLIS.Binding Languages.PLIS.Binding(object value)
inherit LObject : LObject
function(:void) Languages.PLIS.Builtin.apply
protected local void __create__(function(:void) apply)
Languages.PLIS.Builtin Languages.PLIS.Builtin(function(:void) apply)
inherit LObject : LObject
object Languages.PLIS.Lambda.formals
object Languages.PLIS.Lambda.list
protected local void __create__(object formals, object list)
Languages.PLIS.Lambda Languages.PLIS.Lambda(object formals, object list)
inherit SelfEvaluating : SelfEvaluating
int|float|object Languages.PLIS.Number.value
protected local void __create__(int|float|object value)
Languages.PLIS.Number Languages.PLIS.Number(int|float|object value)
string Languages.PLIS.Parser.buffer
protected local void __create__(string buffer)
Languages.PLIS.Parser Languages.PLIS.Parser(string buffer)
inherit LObject : LObject
string Languages.PLIS.SelfEvaluating.name
protected local void __create__(string name)
Languages.PLIS.SelfEvaluating Languages.PLIS.SelfEvaluating(string name)
inherit SelfEvaluating : SelfEvaluating
string Languages.PLIS.String.value
protected local void __create__(string value)
Languages.PLIS.String Languages.PLIS.String(string value)
Local gives a local module namespace used for locally
installed pike modules.
Modules are searched for in the directory pike_modules which can be located in the user's home directory or profile directory, or in any of the system directories /opt/share, /usr/local/share, /opt or /usr/local/.
The user's home directory is determined by examining the environment variable HOME, and if that fails the environment variable USERPROFILE.
If the environment variable PIKE_LOCAL_PATH is set, the paths specified there will be searched first.
If the user has installed the pike module Mine.pmod in the directory $HOME/pike_modules. it can be accessed as Local.Mine.
Local.add_path(), Local.remove_path()
inherit __joinnode : __joinnode
bool add_path(string path)
This function prepends path to the Local module
searchpath.
pathThe path to the directory to be added.
Returns 1 on success, otherwise 0.
void remove_path(string path)
This function removes path from the Local module
searchpath. If path is not in the search path, this is
a noop.
pathThe path to be removed.
The functions and classes in the top level of the Locale module implements a dynamic localization system, suitable for programs that need to change locale often. It is even possible for different threads to use different locales at the same time.
The highest level of the locale system is called projects. Usually one program consists of only one project, but for bigger applications, or highly modular applications it is possible for several projects to coexist.
Every project in turn contains several unique tokens, each one representing an entity that is different depending on the currently selected locale.
// The following line tells the locale extractor what to // look for. // <locale-token project="my_project">LOCALE</locale-token> // The localization macro. #define LOCALE(X,Y) Locale.translate("my_project", \ get_lang(), X, Y) string get_lang() { return random(2)?"eng":"swe"; } int(0..0) main() { write(LOCALE(0, "This is a line.")+"\n"); write(LOCALE(0, "This is another one.\n"); return 0; }
In order to update your code to actually use the locale strings you need to run the locale extractor.
This is available as pike -x extract_locale
Syntax: pike -x extract_locale [arguments] infile(s)
Arguments: --project=name default: first found in infile
--config=file default: [project].xml
--out=file default: [project]_eng.xml
--nocopy update infile instead of infile.new
--notime don't include dump time in xml files
--wipe remove unused ids from xml
--sync synchronize all locale projects
--encoding=enc default: ISO-8859-1
--verbose more informative text in xml
mapping(string:int) cache_status()
Retrieve some statistics about the
currently loaded LocaleObjects.
function(:void)|zero call(string project, string lang, string name, void|function(:void)|string fb)
Returns a localized function If function not found, tries fallback function fb, or fallback language fb instead
void clean_cache()
Remove old LocaleObjects from the cache.
flush_cache()
void flush_cache()
Remove all entries in the LocaleObject cache.
LocaleObject|zero get_object(string project, string lang)
Returns the corresponding LocaleObject if it exists
and 0 (zero) if it does not.
get_objects()
mapping(string:object)|zero get_objects(string lang)
Reads in and returns a mapping with all the registred projects' LocaleObjects in the language 'lang'
array(string) list_languages(string project)
Returns a list of all registered languages for a specific project.
void register_project(string name, string path, void|string path_base)
Make a connection between a project name and where its localization files can be found. The mapping from project name to locale file is stored in projects.
void set_default_project_path(string path)
In the event that a translation is requested in an unregistered project, this path will be used as the project path. %P will be replaced with the requested projects name.
string translate(string project, string lang, string|int id, string fallback)
Returns a translation for the given id, or the fallback string
This class simulates a multi-language "string". The actual language to use is determined as late as possible.
protected string Locale.DeferredLocale.project
protected function(:string) Locale.DeferredLocale.get_lang
protected string|int Locale.DeferredLocale.key
protected string Locale.DeferredLocale.fallback
protected local void __create__(string project, function(:string) get_lang, string|int key, string fallback)
Locale.DeferredLocale Locale.DeferredLocale(string project, function(:string) get_lang, string|int key, string fallback)
array get_identifier()
Return the data nessesary to recreate this "string".
array(string) Locale.LanguageListObject.languages
protected local void __create__(array(string) languages)
Locale.LanguageListObject Locale.LanguageListObject(array(string) languages)
Class for objects representing a Locale.
string sprintf(string format, ... Locale.LocaleObject arg ... )
mixed res = Locale.LocaleObject()()
Calls the function f with the arguments args if it
exists and is a function. Otherwise returns the value
(ie constant function) for f and UNDEFINED
if it does not exist.
Locale.LocaleObject Locale.LocaleObject(mapping(string|int:string) _bindings, mapping(string:function(:void))|void _functions, mapping(string|int:string)|void _origs)
int estimate_size()
Returns an estimate of the number of bytes that the object uses.
function(:void) is_function(string f)
Returns the function for the function name f if it exists
and is a function and 0 (zero) otherwise.
string translate(string|int key, string|void fallback)
Returns the translation for the key key
This is the old location for the predef::Charset module.
Replaced by predef::Charset.
inherit predef::Charset : Charset
This module enables access to localization functions from within Pike.
The message conversion functions in this module do not handle Unicode strings. They only provide thin wrappers to gettext(3) etc, which means strings are assumed to be encoded according to the LC_* and LANG variables. See the docs for gettext(3) for details.
constant Locale.Gettext.LC_ALL
Locale category for all of the locale.
Only supported as an argument to setlocale().
constant Locale.Gettext.LC_COLLATE
Locale category for the functions strcoll() and strxfrm() (used by pike, but not directly accessible).
constant Locale.Gettext.LC_CTYPE
Locale category for the character classification and conversion routines.
constant Locale.Gettext.LC_MESSAGES
Document this constant.
constant Locale.Gettext.LC_MONETARY
Locale category for localeconv().
constant Locale.Gettext.LC_NUMERIC
Locale category for the decimal character.
constant Locale.Gettext.LC_TIME
Locale category for strftime() (currently not accessible from Pike).
string bindtextdomain(string|void domainname, string|void dirname)
Binds the path predicate for a message domainname domainname to
the directory name specified by dirname.
If domainname is a non-empty string and has not been bound
previously, bindtextdomain() binds domainname with dirname.
If domainname is a non-empty string and has been bound previously,
bindtextdomain() replaces the old binding with dirname.
The dirname argument can be an absolute or relative pathname
being resolved when gettext(), dgettext() or dcgettext()
are called.
If domainname is zero or an empty string, bindtextdomain()
returns 0.
User defined domain names cannot begin with the string "SYS_".
Domain names beginning with this string are reserved for system use.
The return value from bindtextdomain() is a string containing
dirname or the directory binding associated with domainname if
dirname is unspecified. If no binding is found, the default locale
path is returned. If domainname is unspecified or is an empty string,
bindtextdomain() takes no action and returns a 0.
textdomain, gettext, setlocale, localeconv
string dcgettext(string domain, string msg, int category)
Return a translated version of msg within the context of the
specified domain and current locale for the specified
category. Calling dcgettext with category Locale.Gettext.LC_MESSAGES
gives the same result as dgettext.
If there is no translation available, msg is returned.
Replaced by gettext.
Obsoleted by gettext() in Pike 7.3.
bindtextdomain, textdomain, gettext, setlocale, localeconv
string dgettext(string domain, string msg)
Return a translated version of msg within the context
of the specified domain and current locale. If there is
no translation available, msg is returned.
Replaced by gettext.
Obsoleted by gettext() in Pike 7.3.
bindtextdomain, textdomain, gettext, setlocale, localeconv
string gettext(string msg)
string gettext(string msg, string domain)
string gettext(string msg, string domain, int category)
msgMessage to be translated.
domainDomain from within the message should be translated. Defaults to the current domain.
categoryCategory from which the translation should be taken.
Defaults to Locale.Gettext.LC_MESSAGES.
Return a translated version of msg within the context
of the specified domain and current locale. If there is no
translation available, msg is returned.
bindtextdomain, textdomain, setlocale, localeconv
mapping localeconv()
The localeconv() function returns a mapping with settings for
the current locale. This mapping contains all values
associated with the locale categories LC_NUMERIC and
LC_MONETARY.
| The decimal-point character used to format non-monetary quantities. | ||||||||||
| The character used to separate groups of digits to the left of the decimal-point character in formatted non-monetary quantities. | ||||||||||
| The international currency symbol applicable to the current locale, left-justified within a four-character space-padded field. The character sequences should match with those specified in ISO 4217 Codes for the Representation of Currency and Funds. | ||||||||||
| The local currency symbol applicable to the current locale. | ||||||||||
| The decimal point used to format monetary quantities. | ||||||||||
| The separator for groups of digits to the left of the decimal point in formatted monetary quantities. | ||||||||||
| The string used to indicate a non-negative-valued formatted monetary quantity. | ||||||||||
| The string used to indicate a negative-valued formatted monetary quantity. | ||||||||||
| The number of fractional digits (those to the right of the decimal point) to be displayed in an internationally formatted monetary quantity. | ||||||||||
| The number of fractional digits (those to the right of the decimal point) to be displayed in a formatted monetary quantity. | ||||||||||
| Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a non-negative formatted monetary quantity. | ||||||||||
| Set to 1 or 0 if the currency_symbol respectively is or is not separated by a space from the value for a non-negative formatted monetary quantity. | ||||||||||
| Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a negative formatted monetary quantity. | ||||||||||
| Set to 1 or 0 if the currency_symbol respectively is or is not separated by a space from the value for a negative formatted monetary quantity. | ||||||||||
| Set to a value indicating the positioning of the positive_sign for a non-negative formatted monetary quantity. The value of p_sign_posn is interpreted according to the following:
| ||||||||||
| Set to a value indicating the positioning of the negative_sign for a negative formatted monetary quantity. The value of n_sign_posn is interpreted according to the rules described under p_sign_posn. |
bindtextdomain, textdomain, gettext, dgettext, dcgettext, setlocale
int setlocale(int category, string locale)
The setlocale() function is used to set the program's
current locale. If locale is "C" or "POSIX", the current
locale is set to the portable locale.
If locale is "", the locale is set to the default locale which
is selected from the environment variable LANG.
The argument category determines which functions are
influenced by the new locale are LC_ALL, LC_COLLATE, LC_CTYPE,
LC_MONETARY, LC_NUMERIC and LC_TIME.
Returns 1 if the locale setting successed, 0 for failure
bindtextdomain, textdomain, gettext, dgettext, dcgettext, localeconv
string textdomain(void|string domain)
The textdomain() function sets or queries the name of the
current domain of the active LC_MESSAGES locale category. The
domain argument is a string that can contain only the
characters allowed in legal filenames. It must be non-empty.
The domain argument is the unique name of a domain on the
system. If there are multiple versions of the same domain on
one system, namespace collisions can be avoided by using
bindtextdomain(). If textdomain() is not called, a default
domain is selected. The setting of domain made by the last
valid call to textdomain() remains valid across subsequent
calls to setlocale(), and gettext().
The normal return value from textdomain() is a string containing the current setting of the domain. If domainname is void, textdomain() returns a string containing the current domain. If textdomain() was not previously called and domainname is void, the name of the default domain is returned.
bindtextdomain, gettext, setlocale, localeconv
Abstract language locale class, inherited by all the language locale classes.
constant Locale.Language.abstract.days
Array(string) with the days of the week, beginning with Sunday.
constant string Locale.Language.abstract.english_name
The name of the language in english.
optional constantint Locale.Language.abstract.iso_639_1
String with the language code in ISO-639-1 (two character code). Note that all languages does not have a ISO-639-1 code.
constant int Locale.Language.abstract.iso_639_2
String with the language code in ISO-639-2/T (three character code).
constant int Locale.Language.abstract.iso_639_2B
String with the language code in ISO-639-2/B (three character code). This
is usually the same as the ISO-639-2/T code (iso_639_2).
constant Locale.Language.abstract.languages
Mapping(string:string) that maps an ISO-639-2/T id code to the name of that language.
constant Locale.Language.abstract.months
Array(string) with the months of the year, beginning with January.
constant string Locale.Language.abstract.name
The name of the langauge. E.g. "svenska" for Swedish.
string date(int timestamp, string|void mode)
Returns the date for posix time timestamp as a textual string.
modeDetermines what kind of textual string should be produced.
| I.e. "06:36" |
| I.e. "January the 17th in the year of 2002" |
| I.e. "06:37, January the 17th, 2002" |
> Locale.Language.eng()->date(time()); Result: "today, 06:36"
string day(int(1..7) num)
Returns the name of weekday number num.
string month(int(1..12) num)
Returns the name of month number num.
string number(int i)
Returns the number i as a string.
string ordered(int i)
Returns the ordered number i as a string.
string short_day(int(1..7) num)
Returns an abbreviated weekday name from the weekday number
num.
string short_month(int(1..12) num)
Returns an abbreviated month name from the month number num.
Catalan language locale.
inherit "abstract" : "abstract"
Czech language locale by Jan Petrous 16.10.1997, based on Slovenian language module by Iztok Umek.
inherit "abstract" : "abstract"
German language locale by Tvns Böker.
inherit "abstract" : "abstract"
English language locale.
inherit "abstract" : "abstract"
Finnish language locale created by Janne Edelman, Turku Unix Users Group ry, Turku, Finland
inherit "abstract" : "abstract"
French language locale by Patrick Kremer.
inherit "abstract" : "abstract"
Croatian language locale by Klara Makovac 1997/07/02
inherit "abstract" : "abstract"
Hungarian language locale by Zsolt Varga.
inherit "abstract" : "abstract"
Italian language locale by Francesco Chemolli
inherit "abstract" : "abstract"
Japanese language locale.
inherit "abstract" : "abstract"
Maaori (New Zealand) language locale by Jason Rumney
inherit "abstract" : "abstract"
Dutch language locale by Stephen R. van den Berg
inherit "abstract" : "abstract"
Norwegian language locale
inherit "abstract" : "abstract"
Polish language locale by Piotr Klaban <makler@man.torun.pl>.
inherit "abstract" : "abstract"
Portuguese language locale
inherit "abstract" : "abstract"
Russian language locale
inherit "abstract" : "abstract"
Slovenian language locale by Iztok Umek 7. 8. 1997
inherit "abstract" : "abstract"
Spanish language locale
inherit "abstract" : "abstract"
Serbian language locale by Goran Opacic 1996/12/11
inherit "abstract" : "abstract"
Swedish language locale
inherit "abstract" : "abstract"
RFC 1521, the Multipurpose Internet Mail Extensions memo, defines a structure which is the base for all messages read and written by modern mail and news programs. It is also partly the base for the HTTP protocol. Just like RFC 0822, MIME declares that a message should consist of two entities, the headers and the body. In addition, the following properties are given to these two entities:
A MIME-Version header must be present to signal MIME compatibility
A Content-Type header should be present to describe the nature of the data in the message body. Seven major types are defined, and an extensive number of subtypes are available. The header can also contain attributes specific to the type and subtype.
A Content-Transfer-Encoding may be present to notify that the data of the body is encoded in some particular encoding.
Raw data to be interpreted according to the Content-Type header
Can be encoded using one of several Content-Transfer-Encodings to allow transport over non 8bit clean channels
The MIME module can extract and analyze these two entities from a stream
of bytes. It can also recreate such a stream from these entities.
To encapsulate the headers and body entities, the class MIME.Message is
used. An object of this class holds all the headers as a mapping from
string to string, and it is possible to obtain the body data in either
raw or encoded form as a string. Common attributes such as message type
and text char set are also extracted into separate variables for easy
access.
The Message class does not make any interpretation of the body
data, unless the content type is multipart. A multipart
message contains several individual messages separated by boundary
strings. The Message->create method of the Message class will
divide a multipart body on these boundaries, and then create
individual Message objects for each part. These objects will be
collected in the array Message->body_parts within the original
Message object. If any of the new Message objects have a body of
type multipart, the process is of course repeated recursively.
inherit ___MIME : ___MIME
constant MIME.TOKENIZE_KEEP_ESCAPES
Don't unquote backslash-sequences in quoted strings during tokenizing. This is used for bug-compatibility with Microsoft...
tokenize(), tokenize_labled()
string|StringRange decode(string|StringRange data, void|string encoding)
Extract raw data from an encoded string suitable for transport between systems.
The encoding can be any of
|
|
|
|
|
|
|
The encoding string is not case sensitive.
MIME.encode()
string decode_base32(string encoded_data)
This function decodes data encoded using the base32 transfer encoding.
MIME.encode_base32(), MIME.decode()
string decode_base32hex(string encoded_data)
Decode strings according to RFC 4648 base32hex encoding.
MIME.decode_base32
string decode_base64(string encoded_data)
This function decodes data encoded using the base64 transfer encoding.
MIME.encode_base64(), MIME.decode()
string decode_base64url(string encoded_data)
Decode strings according to RFC 4648 base64url encoding.
MIME.decode_base64
string(8bit) decode_crypt64(string(7bit) encoded_data)
This function decodes data encoded using the crypt64 encoding.
This is an ad hoc encoding similar to base64 that several password hashing algorithms use for entries in the password database.
This is NOT a MIME-compliant encoding, and MUST NOT be used as such.
MIME.encode_crypt64()
array(ADT.OrderedMapping(< string, string >)) decode_headerfield_params(string s)
Decodes the given string as a key-value parameter cascade according to e.g. RFC 7239 section 4.
This function will decode all conforming inputs, but it will also be forgiving when presented with non-conforming inputs.
encode_headerfield_params
string decode_qp(string encoded_data)
This function decodes data encoded using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding.
MIME.encode_qp(), MIME.decode()
string decode_uue(string encoded_data)
This function decodes data encoded using the x-uue transfer encoding. It can also be used to decode generic UUEncoded files.
MIME.encode_uue(), MIME.decode()
array(string) decode_word(string word)
Extracts the textual content and character set from an encoded word as specified by RFC 1522/RFC 2047. The result is an array where the first element is the raw text, and the second element the name of the character set. If the input string is not an encoded word, the result is still an array, but the char set element will be set to 0.
Note that this function can only be applied to individual encoded words.
MIME.encode_word()
array(array(string)) decode_words_text(string txt)
Separates a header value containing text into units and calls
MIME.decode_word() on them. The result is an array where each element
is a result from decode_word().
MIME.decode_words_tokenized
MIME.decode_words_text_remapped
string decode_words_text_remapped(string txt)
Like MIME.decode_words_text(), but the extracted strings are
also remapped from their specified character encoding into UNICODE,
and then pasted together. The result is thus a string in the original
text format, without RFC 1522 escapes, and with all characters in UNICODE
encoding.
MIME.decode_words_tokenized_remapped
array(array(string)|int) decode_words_tokenized(string phrase, int|void flags)
Tokenizes a header value just like MIME.tokenize(), but also
converts encoded words using MIME.decode_word(). The result is
an array where each element is either an int representing
a special character, or an array as returned by
decode_word() representing an atom or a quoted string.
MIME.decode_words_tokenized_labled
MIME.decode_words_tokenized_remapped
MIME.decode_words_text
array(array(string|int|array(array(string)))) decode_words_tokenized_labled(string phrase, int|void flags)
Tokenizes and labels a header value just like MIME.tokenize_labled(),
but also converts encoded words using MIME.decode_word(). The result
is an array where each element is an array of two or more elements, the
first being the label. The rest of the array depends on the label:
| One additional element, containing the character code for the special
character as an |
| Two additional elements, the first being the word, and the second being the character set of this word (or 0 if it did not originate from an encoded word). |
| One additional element, containing the domain literal as a string. |
| One additional element, containing an array as returned by
|
MIME.decode_words_tokenized_labled_remapped
array(array(string|int)) decode_words_tokenized_labled_remapped(string phrase, int|void flags)
Like MIME.decode_words_tokenized_labled(), but the extracted words are
also remapped from their specified character encoding into UNICODE.
The result is identical to that of MIME.tokenize_labled(), but
without RFC 1522 escapes, and with all characters in UNICODE encoding.
array(string|int) decode_words_tokenized_remapped(string phrase, int|void flags)
Like MIME.decode_words_tokenized(), but the extracted atoms are
also remapped from their specified character encoding into UNICODE.
The result is thus identical to that of MIME.tokenize(), but
without RFC 1522 escapes, and with all characters in UNICODE encoding.
MIME.decode_words_tokenized_labled_remapped
MIME.decode_words_text_remapped
string encode(string data, void|string encoding, void|string filename, void|int no_linebreaks)
Encode raw data into something suitable for transport to other systems.
The encoding can be any of
|
|
|
|
|
|
|
The encoding string is not case sensitive. For the x-uue encoding,
an optional filename string may be supplied.
If a nonzero value is passed as no_linebreaks, the result string
will not contain any linebreaks (base64 and quoted-printable
only).
MIME.decode()
string encode_base32(string data, void|int no_linebreaks, void|int no_pad)
Encode strings according to RFC 4648 base32 encoding.
If a nonzero value is passed as no_linebreaks, the result string
will not contain any linebreaks.
MIME.decode_base32(), MIME.encode()
string encode_base32hex(string data, void|int no_linebreaks, void|int no_pad)
Encode strings according to RFC 4648 base32hex encoding.
If a nonzero value is passed as no_linebreaks, the result string
will not contain any linebreaks.
MIME.encode_base32hex
string encode_base64(string data, void|int no_linebreaks, void|int no_pad)
This function encodes data using the base64 transfer encoding.
If a nonzero value is passed as no_linebreaks, the result string
will not contain any linebreaks.
MIME.decode_base64(), MIME.encode()
string encode_base64url(string data, void|int no_linebreaks, void|int no_pad)
Encode strings according to RFC 4648 base64url encoding. No padding is performed and no_linebreaks defaults to true.
MIME.encode_base64
string encode_crypt64(string(8bit) data)
This function encodes data using the crypt64 encoding.
This is an ad hoc encoding similar to base64 that several password hashing algorithms use for entries in the password database.
This is NOT a MIME-compliant encoding, and MUST NOT be used as such.
MIME.decode_crypt64()
string encode_headerfield_params(array(mapping(string:string)|ADT.OrderedMapping(< string, string >)) params)
Encodes the given key-value parameters as a string according to e.g. RFC 7239 section 4.
decode_headerfield_params
string encode_qp(string data, void|int no_linebreaks)
This function encodes data using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding.
If a nonzero value is passed as no_linebreaks, the result
string will not contain any linebreaks.
Please do not use this function. QP is evil, and there's no excuse for using it.
MIME.decode_qp(), MIME.encode()
string(7bit) encode_uue(string(8bit) encoded_data, void|string(7bit) filename)
This function encodes data using the x-uue transfer encoding.
The optional argument filename specifies an advisory filename to include
in the encoded data, for extraction purposes.
This function can also be used to produce generic UUEncoded files.
MIME.decode_uue(), MIME.encode()
string encode_word(string|array(string|zero) word, string|zero encoding)
Create an encoded word as specified in RFC 1522 from an array containing a raw text string and a char set name.
The text will be transfer encoded according to the encoding argument,
which can be either "base64" or "quoted-printable"
(or either "b" or "q" for short).
If either the second element of the array (the char set name), or the encoding argument is 0, the raw text is returned as is.
MIME.decode_word()
string encode_words_quoted(array(array(string)|int) phrase, string encoding)
The inverse of decode_words_tokenized(), this functions accepts
an array like the argument to quote(), but instead of simple strings
for atoms and quoted-strings, it will also accept pairs of strings to
be passed to encode_word().
encodingEither "base64" or "quoted-printable"
(or either "b" or "q" for short).
MIME.encode_words_quoted_remapped()
MIME.encode_words_quoted_labled()
string encode_words_quoted_labled(array(array(string|int|array(string|array(string)))) phrase, string encoding)
The inverse of decode_words_tokenized_labled(), this functions accepts
an array like the argument to quote_labled(), but "word" labled
elements can optionally contain an additional string element specifying
a character set, in which case an encoded-word will be used. Also, the
format for "comment" labled elements is entirely different; instead of
a single string, an array of strings or pairs like the first argument to
encode_words_text() is expected.
encodingEither "base64" or "quoted-printable"
(or either "b" or "q" for short).
MIME.encode_words_quoted()
MIME.encode_words_quoted_labled_remapped()
string encode_words_quoted_labled_remapped(array(array(string|int)) phrase, string encoding, string|function(string:string) charset, string|void replacement, function(string:string)|void repcb)
The inverse of decode_words_tokenized_labled_remapped(), this function
accepts an array equivalent to the argument of quote_labled(), but also
performs on demand word encoding in the same way as
encode_words_text_remapped().
string encode_words_quoted_remapped(array(string|int) phrase, string encoding, string|function(string:string) charset, string|void replacement, function(string:string)|void repcb)
The inverse of decode_words_tokenized_remapped(), this functions
accepts an array equivalent to the argument of quote(), but also
performs on demand word encoding in the same way as
encode_words_text_remapped().
MIME.encode_words_text_remapped()
MIME.encode_words_quoted_labled_remapped()
string encode_words_text(array(string|array(string)) phrase, string encoding)
The inverse of decode_words_text(), this function accepts
an array of strings or pairs of strings which will each be encoded
by encode_word(), after which they are all pasted together.
encodingEither "base64" or "quoted-printable"
(or either "b" or "q" for short).
MIME.encode_words_text_remapped
string encode_words_text_remapped(string text, string encoding, string|function(string:string) charset, string|void replacement, function(string:string)|void repcb)
This is the reverse of MIME.decode_words_text_remapped(). A
single UNICODE string is provided, which is separated into
fragments and transcoded to selected character sets by this
function as needed.
encodingEither "base64" or "quoted-printable"
(or either "b" or "q" for short).
charsetEither the name of a character set to use, or a function returning a character set to use given a text fragment as input.
replacementThe replacement argument to use when calling Charset.encoder
repcbThe repcb argument to use when calling Charset.encoder
MIME.encode_words_tokenized_remapped
string ext_to_media_type(string extension)
Returns the MIME media type for the provided filename extension.
Currently 469 file extensions are known to this method. Zero will
be returned on unknown file extensions.
string generate_boundary()
This function will create a string that can be used as a separator string
for multipart messages. If a boundary prefix has been set
using MIME.set_boundary_prefix(), the generated string will be prefixed
with the boundary prefix.
The generated string is guaranteed not to appear in base64, quoted-printable, or x-uue encoded data. It is also unlikely to appear in normal text. This function is used by the cast method of the Message class if no boundary string is specified.
MIME.set_boundary_prefix()
string(8bit) get_boundary_prefix()
Returns the boundary_prefix set via set_boundary_prefix().
MIME.set_boundary_prefix(), MIME.Message.setboundary()
string|zero guess_subtype(string type)
Provide a reasonable default for the subtype field.
Some pre-RFC 1521 mailers provide only a type and no subtype in the
Content-Type header field. This function can be used to obtain a
reasonable default subtype given the type of a message. (This is done
automatically by the MIME.Message class.)
Currently, the function uses the following guesses:
|
|
|
|
|
|
array(mapping(string:string)|string) parse_headers(string message)
array(mapping(string:array(string))|string) parse_headers(string message, int(1) use_multiple)
This is a low level function that will separate the headers from the body of an encoded message. It will also translate the headers into a mapping. It will however not try to analyze the meaning of any particular header. This means that the body is returned as is, with any transfer-encoding intact.
It is possible to call this function with just the header part of a message, in which case an empty body will be returned.
The result is returned in the form of an array containing two elements. The first element is a mapping containing the headers found. The second element is a string containing the body.
Headers that occur multiple times will have their contents NUL separated,
unless use_multiple has been specified, in which case the contents will
be arrays.
Some headers (eg Subject) may include RFC 1522/RFC 2047 encoded words. To
decode these, see decode_words_text and decode_words_tokenized and
their friends.
string quote(array(string|int) lexical_elements)
This function is the inverse of the MIME.tokenize function.
A header field value is constructed from a sequence of lexical elements.
Characters (ints) are taken to be special-characters, whereas
strings are encoded as atoms or quoted-strings, depending on whether
they contain any special characters.
There is no way to construct a domain-literal using this function. Neither can it be used to produce comments.
MIME.tokenize()
string quote_labled(array(array(string|int)) tokens)
This function performs the reverse operation of tokenize_labled().
MIME.quote(), MIME.tokenize_labled()
int|object reconstruct_partial(array(object) collection)
This function will attempt to reassemble a fragmented message from its parts.
The array collection should contain MIME.Message objects forming
a complete set of parts for a single fragmented message.
The order of the messages in the array is not important, but every part
must exist at least once.
Should the function succeed in reconstructing the original message, a
new MIME.Message object will be returned.
If the function fails to reconstruct an original message, an integer indicating the reason for the failure will be returned:
| Returned if empty |
| If more fragments are needed to reconstruct the entire message, the number of additional messages needed is returned. |
| If more fragments are needed, but the function can't determine exactly how many. |
Note that the returned message may in turn be a part of another, larger, fragmented message.
MIME.Message->is_partial()
void set_boundary_prefix(string(8bit) boundary_prefix)
Set a message boundary prefix. The MIME.generate_boundary() will use this
prefix when creating a boundary string.
An error is thrown if boundary_prefix doesn't adhere to RFC 1521.
MIME.generate_boundary(), MIME.get_boundary_prefix()
boundary_prefixThis must adhere to RFC 1521 and can not be longer than 56 characters.
array(string|int) tokenize(string header, int|void flags)
A structured header field, as specified by RFC 0822, is constructed from a sequence of lexical elements.
headerThe header value to parse.
flagsAn optional set of flags. Currently only one flag is defined:
| Keep backslash-escapes in quoted-strings. |
The lexical elements parsed are:
individual special characters
quoted-strings
domain-literals
comments
atoms
This function will analyze a string containing the header value, and produce an array containing the lexical elements.
Individual special characters will be returned as characters (i.e.
ints).
Quoted-strings, domain-literals and atoms will be decoded and returned as strings.
Comments are not returned in the array at all.
As domain-literals are returned as strings, there is no way to tell the domain-literal [127.0.0.1] from the quoted-string "[127.0.0.1]". Hopefully this won't cause any problems. Domain-literals are used seldom, if at all, anyway...
The set of special-characters is the one specified in RFC 1521
(i.e. "<", ">", "@", ",", ";", ":", "\", "/", "?", "="),
and not the set specified in RFC 0822.
MIME.quote(), tokenize_labled(),
decode_words_tokenized_remapped().
array(array(string|int)) tokenize_labled(string header, int|void flags)
Similar to tokenize(), but labels the contents, by making
arrays with two elements; the first a label, and the second
the value that tokenize() would have put there, except
for that comments are kept.
headerThe header value to parse.
flagsAn optional set of flags. Currently only one flag is defined:
| Keep backslash-escapes in quoted-strings. |
The following labels exist:
| Word encoded according to =?... |
| Special character. |
| Word. |
| Domain literal. |
| Comment. |
MIME.quote(), tokenize(),
decode_words_tokenized_labled_remapped()
This class is used to hold a decoded MIME message.
array(object) MIME.Message.body_parts
If the message is of type multipart, this is an array
containing one Message object for each part of the message.
If the message is not a multipart, this field is 0 (zero).
type, boundary
string MIME.Message.boundary
For multipart messages, this Content-Type parameter gives a delimiter string for separating the individual messages. As multiparts are handled internally by the module, you should not need to access this field.
setboundary()
string MIME.Message.charset
One of the possible parameters of the Content-Type header is the charset attribute. It determines the character encoding used in bodies of type text.
If there is no Content-Type header, the value of this field
is "us-ascii".
type
string MIME.Message.data
This variable contains the raw data of the message body entity.
The type and subtype attributes indicate how this data should
be interpreted.
In Pike 7.6 and earlier you had to use getdata() and
setdata() to access this value.
getdata(), setdata()
mapping(string:string) MIME.Message.disp_params
A mapping containing all the additional parameters to the Content-Disposition header.
setdisp_param(), get_filename()
string MIME.Message.disposition
The first part of the Content-Disposition header, hinting on how this part of a multipart message should be presented in an interactive application.
If there is no Content-Disposition header, this field
is 0.
mapping(string:string) MIME.Message.headers
This mapping contains all the headers of the message.
The key is the header name (in lower case) and the value is the header value.
Although the mapping contains all headers, some particular headers get special treatment by the module and should not be accessed through this mapping. These fields are currently:
|
|
|
|
The contents of these fields can be accessed and/or modified through a set of variables and methods available for this purpose.
type, subtype, charset, boundary, transfer_encoding,
params, disposition, disp_params, setencoding(),
setparam(), setdisp_param(), setcharset(), setboundary()
Some headers (eg Subject) may include RFC 1522/RFC 2047 encoded words. To
decode these, see decode_words_text and decode_words_tokenized and
their friends.
mapping(string:string) MIME.Message.params
A mapping containing all the additional parameters to the Content-Type header.
Some of these parameters have fields of their own, which should be accessed instead of this mapping wherever applicable.
charset, boundary, setparam()
string MIME.Message.subtype
The Content-Type header contains a type, a subtype, and optionally some parameters. This field contains the subtype attribute extracted from the header.
If there is no Content-Type header, the value of this field
is "plain".
type, params
string MIME.Message.transfer_encoding
The contents of the Content-Transfer-Encoding header.
If no Content-Transfer-Encoding header is given, this field
is 0 (zero).
Transfer encoding and decoding is done transparently by the module, so this field should be interesting only to applications wishing to do auto conversion of certain transfer encodings.
setencoding()
string MIME.Message.type
The Content-Type header contains a type, a subtype, and optionally some parameters. This field contains the type attribute extracted from the header.
If there is no Content-Type header, the value of this field
is "text".
subtype, params
(string)MIME.Message()
Casting the message object to a string will yield a byte stream suitable for transmitting the message over protocols such as ESMTP and NNTP.
The body will be encoded using the current transfer encoding, and
subparts of a multipart will be collected recursively. If the message
is a multipart and no boundary string has been set, one will be
generated using generate_boundary().
create()
MIME.Message MIME.Message()
MIME.Message MIME.Message(string message)
MIME.Message MIME.Message(string message, mapping(string:string|array(string)) headers, array(object)|void parts)
MIME.Message MIME.Message(string message, mapping(string:string|array(string)) headers, array(object)|void parts, bool guess)
There are several ways to call the constructor of the Message class:
With zero arguments, you will get a dummy message with neither headers nor body. Not very useful.
With one argument, the argument is taken to be a byte stream containing a message in encoded form. The constructor will analyze the string and extract headers and body.
With two or three arguments, the first argument is taken to be the raw body data, and the second argument a desired set of headers. The keys of this mapping are not case-sensitive. If the given headers indicate that the message should be of type multipart, an array of Message objects constituting the subparts should be given as a third argument.
With the guess argument set to 1 (headers and parts may be 0
if you don't want to give any), you get a more forgiving MIME Message
that will do its best to guess what broken input data really meant. It
won't always guess right, but for applications like mail archives and
similar where you can't get away with throwing an error at the user,
this comes in handy. Only use the guess mode only for situations
where you need to process broken MIME messages silently; the
abuse of overly lax tools is what poisons standards.
cast()
string get_filename()
This method tries to find a suitable filename should you want to save the body data to disk.
It will examine the filename attribute of the Content-Disposition header, and failing that the name attribute of the Content-Type header. If neither attribute is set, the method returns 0.
An interactive application should always query the user for the actual filename to use. This method may provide a reasonable default though.
string getdata()
This method returns the raw data of the message body entity.
The type and subtype attributes indicate how this data should
be interpreted.
setdata(), getencoded(), data
string getencoded()
This method returns the data of the message body entity, encoded using the current transfer encoding.
You should never have to call this function.
getdata()
array(string|int)|zero is_partial()
If this message is a part of a fragmented message (i.e. has a Content-Type of message/partial), an array with three elements is returned.
The first element is an identifier string. This string should be used to group this message with the other fragments of the message (which will have the same id string).
The second element is the sequence number of this fragment. The first part will have number 1, the next number 2 etc.
The third element of the array is either the total number of fragments that the original message has been split into, or 0 of this information is not available.
If this method is called in a message that is not a part of a fragmented message, it will return 0.
MIME.reconstruct_partial()
protected void parse_param(mapping(string:string) params, array(string|int) entry, string header, int|void guess, array(string|int)|void entry2)
Parse a Content-Type or Content-Disposition parameter.
paramsMapping to add parameters to.
entryArray of tokens containing a parameter declaration.
headerName of the header from which entry originated.
This is only used to report errors.
guessMake a best-effort attempt to parse broken entries.
entry2Same as entry, but tokenized with MIME.TOKENIZE_KEEP_ESCAPES.
create()
void setboundary(string boundary)
Sets the boundary parameter of the Content-Type header.
This is equivalent of calling setparam("boundary", .boundary)
setparam()
void setcharset(string charset)
Sets the charset parameter of the Content-Type header.
This is equivalent of calling setparam("charset", .charset)
setparam()
void setdata(string data)
Replaces the body entity of the data with a new piece of raw data.
The new data should comply to the format indicated by the
type and subtype attributes.
Do not use this method unless you know what you are doing.
getdata(), setencoded, data
void setdisp_param(string param, string value)
Set or modify the named parameter of the Content-Disposition header.
A common parameters is e.g. filename.
It is not allowed to modify the Content-Disposition header directly, please use this function instead.
setparam(), get_filename()
void setencoding(string encoding)
Select a new transfer encoding for this message.
The Content-Transfer-Encoding header will be modified accordingly,
and subsequent calls to getencoded will produce data encoded using
the new encoding.
See MIME.encode() for a list of valid encodings.
getencoded(), MIME.encode()
void setparam(string param, string value)
Set or modify the named parameter of the Content-Type header.
Common parameters include charset for text messages, and boundary for multipart messages.
It is not allowed to modify the Content-Type header directly, please use this function instead.
setcharset(), setboundary(), setdisp_param()
Class representing a substring of a larger string.
This class is used to reduce the number of string copies
during parsing of MIME.Messages.
void Finalize()
Cleans up the MPI stack. Will be called automatically upon
termination of the Pike program, but can be called explicitly
when it is required that some of the parallel processes continue
running and some terminate.
Init(), MPI_Finalize(3)
void Init()
Initializes MPI. MPI in Pike will auto-initialize once the
first MPI-operation is called. You can call this function to
initialize the parallel MPI at a specific time, since
initialization is a collective operation and will block the process
until all member processes of the parallel program are present.
int main() { MPI.Init(); write("I am process %d of %d.\n", MPI.world->rank, MPI.world->size); MPI.Finalize(); return 0; }
Finalize(), MPI_Init(3)
Op Op_create(function(object, object:void) ufun, int commute)
Creates a user-defined MPI operation.
ufunThe function that implements the MPI.Op to be created.
commuteSet to 1 if the operation commutes.
void my_add_fun(object invec, object outvec) { for (int i = 0; i < sizeof(outvec); i++) { outvec[i] += invec[i]; }
int main() { MPI.Op myadd; MPI.IntArray ia = MPI.IntArray(10), results;
MPI.Init();
myadd = MPI.Op_create(my_add_fun, 1);
for (int i = 0; i < sizeof(ia); i++) ia[i] = random(1000);
if (!MPI.world->rank) results = MPI.IntArray(sizeof(ia)); MPI.world->Reduce(ia, results, 0); if (!MPI.world->rank) for (int i; i < sizeof(results); i++) write("%02d: %d\n", i, results[i]);
MPI.Finalize(); return 0; }
User-defined MPI operations may not call any MPI operations themselves.
MPI.Comm->Reduce(), MPI_Op_create(3)
A communicator object holds a group of processes both relate messages between those processes as well as perform collective operations, in which all member processes of the communicator are involved.
void Recv(MPI.Pointer buf, int source, int|void tag, MPI.Status|void status)
void Recv(MPI.IntArray buf, int source, int|void tag, MPI.Status|void status)
void Recv(MPI.FloatArray buf, int source, int|void tag, MPI.Status|void status)
void Recv(MPI.SingleArray buf, int source, int|void tag, MPI.Status|void status)
void Recv(MPI.Sentinel buf, int source, int|void tag, MPI.Status|void status)
Receives a message from source with matching tag into
buf, storing the sender's rank and the tag used into the
optionally given MPI.Status.
The type of the buffer of the receiver site has to match the
type of the buffer of the sender. Exception: If a string
is sent, it has to be received into a MPI.Pointer.
int main() { MPI.IntArray ia = MPI.IntArray(5);
MPI.Init();
write("This is rank %d, %d processes total.\n", MPI.world->rank, MPI.world->size);
if (MPI.world->rank) { for (int i = 0; i < sizeof(ia); i++) { ia[i] = MPI.world->rank + i; }
MPI.world->Send(ia, 0); // send to rank 0 } else { for (int i = 0; i < MPI.world->size; i++) { MPI.world->Recv(ia, i); write("Rank %d sent %O to rank 0.\n", i, (array)ia); } }
MPI.Finalize(); return 0; }
MPI.Comm->Send(), MPI.Comm->Bcast(), MPI.ANY_SOURCE,
MPI.ANY_TAG, MPI_Send(3).
void Send(string buf, int dest, int|void tag)
void Send(MPI.IntArray buf, int dest, int|void tag)
void Send(MPI.FloatArray buf, int dest, int|void tag)
void Send(MPI.SingleArray buf, int dest, int|void tag)
void Send(MPI.Sentinel buf, int dest, int|void tag)
Sends the buffer buf to the process with rank dest,
marked with tag.
MPI.Comm()->Recv(), MPI.Comm()->Bcast(), MPI_Send(3).
This class implements an array of double precision floats.
Values will be converted to and from the Pike float type, which may introduce rounding errors if the types don't match in your installation.
int sizeof( MPI.FloatArray arg )
The number of entries in this MPI_FloatArray .
array(float) values( MPI.FloatArray arg )
A Pike array copy of this array.
array pike_array = values(typed_array);
float res = MPI.FloatArray()[ idx ]
Gives the idxths element of the MPI_FloatArray .
MPI.FloatArray()[ idx ] = val
Sets the idxths element of the MPI_FloatArray to
val.
void assign(MPI_FloatArray other)
Assigns the first sizeof(other) entries from other to the
respective entries in the current array.
If sizeof(other) > sizeof(this)
(int)MPI.FloatArray()
(float)MPI.FloatArray()
(string)MPI.FloatArray()
(array)MPI.FloatArray()
(mapping)MPI.FloatArray()
(multiset)MPI.FloatArray()
Supports casting (by copy) this MPI_FloatArray to a Pike array.
array pike_array = (array)typed_array;
void clear()
Sets all elements of the MPI_FloatArray to 0.
MPI.FloatArray MPI.FloatArray(int(0..) size)
This class implements an array of 32 bit integers.
int sizeof( MPI.IntArray arg )
The number of entries in this MPI_IntArray .
array(int) values( MPI.IntArray arg )
A Pike array copy of this array.
array pike_array = values(typed_array);
int res = MPI.IntArray()[ idx ]
Gives the idxths element of the MPI_IntArray .
MPI.IntArray()[ idx ] = val
Sets the idxths element of the MPI_IntArray to
val.
void assign(MPI_IntArray other)
Assigns the first sizeof(other) entries from other to the
respective entries in the current array.
If sizeof(other) > sizeof(this)
(int)MPI.IntArray()
(float)MPI.IntArray()
(string)MPI.IntArray()
(array)MPI.IntArray()
(mapping)MPI.IntArray()
(multiset)MPI.IntArray()
Supports casting (by copy) this MPI_IntArray to a Pike array.
array pike_array = (array)typed_array;
void clear()
Sets all elements of the MPI_IntArray to 0.
MPI.IntArray MPI.IntArray(int(0..) size)
Objects of this class represent MPI operations used in collective
operations like MPI.Comm()->reduce(). You can use operations
predefined by MPI or create your own.
Other than that, Ops are not that useful from Pike.
MPI constants, MPI.Op_create(), MPI.Comm->Reduce().
A pointer like class. Because MPI.Comm->Recv() et al do not return
"results" but take references/pointers to the target storage, you need to
pass a Pointer to MPI.Comm()->recv() in order to receive the string.
int main() { string s; MPI.Pointer p = MPI.Pointer();
MPI.Init();
if (MPI.world->rank()) MPI.world->Send(ctime(time(1)), 0); else for (int i = 1; i < MPI.world->size; i++) { MPI.world->Recv(p, i); write("Rank %03d says now is %s.\n", p()); }
MPI.Finalize(); return 0; }
mixed res = MPI.Pointer()()
mixed res = MPI.Pointer()()
If called with 0 arguments, returns the pointee. If called with
argument m, now points to m.
MPI.Pointer MPI.Pointer()
MPI.Pointer MPI.Pointer(mixed m)
If m is given, point to m, else point to
UNDEFINED.
A Sentinel is a kind of handle that can be given out by objects if
they want to allow MPI to send from/receive into the memory areas
pointed to by the Sentinel.
Other than that, Sentinels are not that useful from Pike.
Math.FMatrix()->get_sentinel(), Math.FMatrix
This class implements an array of single precision floats.
Values will be converted to and from the Pike float type, which may introduce rounding errors if the types don't match in your installation.
int sizeof( MPI.SingleArray arg )
The number of entries in this MPI_SingleArray .
array(float) values( MPI.SingleArray arg )
A Pike array copy of this array.
array pike_array = values(typed_array);
float res = MPI.SingleArray()[ idx ]
Gives the idxths element of the MPI_SingleArray .
MPI.SingleArray()[ idx ] = val
Sets the idxths element of the MPI_SingleArray to
val.
void assign(MPI_SingleArray other)
Assigns the first sizeof(other) entries from other to the
respective entries in the current array.
If sizeof(other) > sizeof(this)
(int)MPI.SingleArray()
(float)MPI.SingleArray()
(string)MPI.SingleArray()
(array)MPI.SingleArray()
(mapping)MPI.SingleArray()
(multiset)MPI.SingleArray()
Supports casting (by copy) this MPI_SingleArray to a Pike array.
array pike_array = (array)typed_array;
void clear()
Sets all elements of the MPI_SingleArray to 0.
MPI.SingleArray MPI.SingleArray(int(0..) size)
Objects of this class can be passed as the last argument to the receive
operation of MPI.Comm communicators. After the operation has finished,
they will contain information about the sender the message was received
from and the tag used for communication.
Therefore, Status objects are particularly helpful in combination with
MPI.ANY_SOURCE and MPI.ANY_TAG.
MPI.Comm()->Recv()
int MPI.Status.SOURCE
Contains the source that the message was received from.
int main() { if (MPI.world->rank) { sleep(random(MPI.world->size)/10.0); MPI.world->Send(gethostname(), MPI.world->rank), 0); } else { MPI.Status status; MPI.Pointer p;
for (int i = 0; i < MPI.world->size; i++) { MPI.world->Recv(p, MPI.ANY_SOURCE, 0, status); write("Rank %d has hostname %s.\n", status->SOURCE, p()); } }
return 0; }
MPI.Comm()->Recv()
int MPI.Status.TAG
Contains the tag that was used in the MPI.Comm()->Recv operation.
MPI.Comm()->Recv()
inherit "___Math" : "___Math"
constant Math.e
The constant e (2.7182818284590452354).
constant Math.inf
Floating point infinity.
constant Math.nan
Floating point not-a-number (e.g. inf/inf).
Float.isnan()
constant Math.pi
The constant pi (3.14159265358979323846).
int(0..) choose(int(0..) n, int(0..) k)
Calculate the binomial coefficient n choose k.
This is equal to n!/(k!*(n-k)!).
int|float convert_angle(int|float angle, string from, string to)
This function converts between degrees, radians and gons. The
from and to arguments may be any of the follwoing
strings: "deg", "rad", "gon" and "str" for degrees, radians, gon
and streck respectivly. The output is not guaranteed to be within
the first turn, e.g. converting 10 radians yields almost 573
degrees as output.
array(int(-1..)) factor(int x)
Factorize the integer x. The returned list of factors will
be sorted biggest to smallest factor.
In Pike versions prior to v8.0, only primes <= 8161 were
considered.
float log10(int|float x)
The 10-logarithm of x.
float log2(int|float x)
The 2-logarithm of x.
float logn(int|float n, int|float x)
The n-logarithm of x.
Represents an angle.
int|float Math.Angle.angle
The actual keeper of the angle value.
string Math.Angle.type
The type of the angle value. Is either "deg", "rad", "gon" or "str".
int hash_value( Math.Angle arg )
float|int|Angle res = Math.Angle() % _angle
Returns this result of this angle modulo the provided value. If differenced with an angle, a new angle object is returned.
float|int|Angle res = Math.Angle() * _angle
Returns the product between this angle and the provided value. If differenced with an angle, a new angle object is returned.
float|int|Angle res = Math.Angle() + _angle
Returns the sum of this angle and what it is added with. If added with an angle, a new angle object is returnes.
float|int|Angle res = Math.Angle() - _angle
Returns the difference between this angle and the provided value. If differenced with an angle, a new angle object is returned.
float|int|Angle res = Math.Angle() / _angle
Returns the fraction between this angle and the provided value. If differenced with an angle, a new angle object is returned.
int res = Math.Angle() < _angle
Compares the unnormalized angle of two Angle objects.
int res = Math.Angle() == _angle
Compares the unnormalized angle of two Angle objects.
int res = Math.Angle() > _angle
Compares the unnormalized angle of two Angle objects.
void about_face()
Turns the direction of the angle half a turn. Equal to
add(180,"deg").
Angle add(float|int angle)
Angle add(float|int angle, string type)
Angle add(Angle angle)
Adds the provided angle to the current angle. The result is normalized within 360 degrees.
(float)Math.Angle()
(int)Math.Angle()
(string)Math.Angle()
An angle can be casted to float, int and string.
Angle clone_me()
Returns a copy of the object.
float cos()
Returns the cosinus for the angle.
Math.Angle Math.Angle()
Math.Angle Math.Angle(int|float radians)
Math.Angle Math.Angle(int|float angle, string type)
If an angle object is created without arguments it will have the value 0 radians.
int|float degree()
Returns the number of degrees, including minutes and seconds as decimals.
string format_dms()
Returns degrees, minutes and seconds as a string, e.g. 47°6'36.00".
int|float get(string type)
Gets the value in the provided type.
int|float gon()
Returns the number of gons.
void left_face()
Turns the direction of the angle a quarter of a turn to the left.
Equal to add(90,"deg").
int minute()
Returns the number of minute.
void normalize()
Normalizes the angle to be within one turn.
float rad()
Returns the number of radians.
void right_face()
Turns the direction of the angle a quarter of a turn to the right.
Equal to subtract(90,"deg").
float second()
Returns the number of seconds.
Angle set(string type, int|float _angle)
Sets the angle value and type to the given value and type.
Angle set_degree(int|float degree)
Sets the angle to the provided degree. Alters the type to degrees. Returns the current object.
Angle set_dms(int degrees)
Angle set_dms(int degrees, int minutes)
Angle set_dms(int degrees, int minutes, float seconds)
Set degrees, minues and seconds. Returns the current angle object.
Angle set_gon(int|float gon)
Set the angle to the provided gons. Alters the type to gons. Returns the current angle object.
Angle set_rad(int|float rad)
Set the angle to the provided radians. Alters the type to radians. Returns the current angle object.
Angle set_streck(int|float str)
Set the angle to the provided strecks. Alters the type to streck. Returns the current angle object.
float sin()
Returns the sinus for the angle.
float|int streck()
Returns the number of strecks.
Angle subtract(float|int angle)
Angle subtract(float|int angle, string type)
Angle subtract(Angle angle)
Subtracts the provided angle from the current angle. The result is normalized within 360 degrees.
float tan()
Returns the tangen for the angle.
Matrix representation with single precision floating point values.
inherit Matrix : Matrix
Matrix representation with 32 bit integer values.
inherit Matrix : Matrix
Matrix representation with 64 bit integer values.
inherit Matrix : Matrix
Matrix representation with double precision floating point values.
Matrix res = Math.Matrix() * with
Matrix res = with * Math.Matrix()
Matrix mult(object with)
Matrix multiplication.
Matrix res = Math.Matrix() + with
Matrix res = with + Math.Matrix()
Matrix add(object with)
Add this matrix to another matrix. A new matrix is returned. The matrices must have the same size.
Matrix res = Math.Matrix() - x
Matrix res = Math.Matrix() - with
Matrix res = with - Math.Matrix()
Matrix sub(object with)
Subtracts this matrix from another. A new matrix is returned.
-m is equal to -1*m.
(array(array(float)))Math.Matrix()
(array(array(float)))Math.Matrix()
It is possible to cast the matrix to an array and get back a double array of floats with the matrix values.
vect
Matrix convolve(object with)
Convolve called matrix with the argument.
Math.Matrix Math.Matrix(array(array(int|float)) matrix_2d)
Math.Matrix Math.Matrix(array(int|float) matrix_1d)
Initializes the matrix as a 1D or 2D matrix, e.g.
Math.Matrix( ({({1,2}),({3,4})}) ).
Math.Matrix Math.Matrix(int n, int m)
Math.Matrix Math.Matrix(int n, int m, string type)
Math.Matrix Math.Matrix(int n, int m, float|int init)
Initializes the matrix as to be a n*m matrix with init in
every value. If no third argument is given, or the third argument
is "identity", the matrix will be initialized with all
zeroes except for the diagonal which will be 1.
Math.Matrix Math.Matrix(string type, int size)
When type is "identity" the matrix is initializes as a
square identity matrix.
Math.Matrix Math.Matrix(string type, int size, float rads, Matrix axis)
Math.Matrix Math.Matrix(string type, int size, float rads, float x, float y, float z)
When type is "rotate" the matrix is initialized as a
rotation matrix.
Matrix cross(object with)
Matrix cross-multiplication.
float dot_product(object with)
Matrix dot product.
Matrix max()
Matrix min()
Produces the maximum or minimum value of all the elements in the matrix.
float norm()
float norm2()
Matrix normv()
Norm of the matrix, and the square of the norm of the matrix. (The later method is because you may skip a square root sometimes.)
This equals |A| or sqrt( A02 + A12 + ... + An2 ).
It is only usable with 1xn or nx1 matrices.
m->normv() is equal to m*(1.0/m->norm()),
with the exception that the zero vector will still be
the zero vector (no error).
Matrix sum()
Produces the sum of all the elements in the matrix.
Matrix transpose()
Returns the transpose of the matrix as a new object.
array vect()
Return all the elements of the matrix as an array of numbers
int xsize()
Returns the width of the matrix.
int ysize()
Returns the height of the matrix.
Matrix representation with 16 bit integer values.
inherit Matrix : Matrix
Math.Transforms.FFT Math.Transforms.FFT(void|int n, void|bool exact)
Creates a new transform object. If n is specified, a plan is created for transformations of n-size arrays.
nSize of the transform to be preformed. Note that the transform object will be initialized for this size, but if an array of different size is sent to the object, it will be reinitialized. This can be used to gain preformace if all transforms will be of a given size.
exactIf exact is 1, a "better" plan for the transform will be created. This will take more time though. Use only if preformance is needed.
array(array(float)) rFFT(array(int|float) real_input)
Returns the FFT of the input array. The input must be real and the output is complex. The output consists of an array. It's first element is the amplitudes and the second element is the phases.
real_inputThe array of floats and/or ints to transform.
rIFFT(rFFT()) returns the input array scaled by n=sizeof(input array). This is due to the nature of the DFT algorithm.
rIFFT()
array(float) rIFFT(array(array(float)) input)
Returns the inverse FFT of the input array. The input must be complex and guaranteed to generate a real output.
The input is an array. It's first element is the amplitudes and the second element is the phases.
The output is an array of the real values for the iFFT.
real_inputThe array of floats and/or ints to transform.
rIFFT(rFFT()) returns the input array scaled by n=sizeof(input array). This is due to the nature of the DFT algorithm.
rFFT()
Various networking-related utility functions.
constant NetUtils.locality
Mapping from NetworkType to an integer between 0 and 10 that
describes how local that type of network is.
string|zero NetUtils.ANY
Returns either 0 or "::" depending on whether or not this computer has IPv6 support.
The intent is to use this when binding addresses, like port->bind(portno,callback,NetUtils.ANY) to get ipv6 support if present.
The reason for the existence of this function is that using "::" on a computer that does not actually have any ipv6 addresses (and thus no support for ipv6), at least on linux, causes the bind call to fail entirely.
Read only
mapping(string:array(string)) broadcast_addresses()
Returns a mapping from interface name to the broadcast addresses on that interface.
array(int)|zero cidr_to_netmask(string|zero cidr)
Converts a string with an IP address and mask (in CIDR notation) into a binary IP address and bitmask.
cidrThe CIDR-notation input string.
An array containing:
| Array | |
| The binary representation of the IP address. |
| The bitmask. |
Returns 0 if the string could not be parsed.
void clear_cache()
Clear any caches. This might be needed if the network setup on the system changes.
array(NetworkType) connectable_network_types()
Returns network types in priority order according to RFC 3484.
This function assumes a network category (ipv4 or ipv6) is available if the local host has a configured address (excluding localhost) of that network type.
This function will always list the v6 and non-v6 addresses separately.
NetworkType get_network_type(int|string ipstr, bool|void separate_6)
Determine the network type of a given ip address.
ipstrIP address in string or numerical form
separate_6Adds a 'v6' to the category for ipv6 addresses (ie, "global" and "globalv6")
Returns one of:
| The local computer. |
| The local network. |
| An unrouted local network (IPv6). |
| A private network, such as 10.0.0.0/8 or fc00::/7 that is not also a local network. |
| A multicast address. |
| An address in the teredo or 6to4 IPv6 tunneling systems, respectively. |
| |
| A globally routable address that does not match any other category. |
bool has_ipv4()
Returns true if the local host has a public IPv4 address
bool has_ipv6()
Returns true if the local host has a public IPv6 address
string host_to_cidr(int|string ip)
Return the CIDR notation for the single host defined by x.
ipThe host ip in either string or raw form
either ip/128 or ip/32 depending on the IPV6-ness of the host IP.
array(string)|zero ip_and_port_of(RemoteAddressObject|string|int(0) inc, bool|void local_address)
Similar to ip_of. Returns 2-element array containing IP address and port number. Second element will be 0 if no port number can be retrieved.
This function can return 0 if inc is a RemoteAddressObject
and query_address throws an error or does not return a string.
bool ip_in_block(int net, int mask, int|string ip)
Checks whether an IP address is in a block.
The net and mask parameters should be as returned from cidr_to_netmask.
Throws an error if the IP address could not be parsed.
netThe network component of the block.
maskThe bitmask of the block.
ipThe IP address to check, in either string or binary representation.
true if the IP is in the given block, false otherwise.
bool ip_less_global(int|string which, int|string towhat, bool|void prefer_v4)
Returns true if which is less globally accessible than
towhat.
string ip_of(RemoteAddressObject|string|int(0) inc, bool|void local_address, string|void def)
If the argument is an object with a query_address method,
return the IP# part of the string returned by calling that
function with local_address as the argument.
This means that for Stdio.File objects the remote address is
returned by default, but if local_address is true the local
address is returned.
If the argument is a string instead, the part of the string before the first space is returned.
If the argument is 0 the default def value is returned,
UNDEFINED unless specified.
If def is supplied, it is used both when query_address() fails
or something that is not a file descriptor object or a string is
passed as the argument to this function.
string|zero ip_to_string(int ip, bool|void v6_only)
Converts a binary representation of an IP address into the IPv4 or IPv6 string representation.
The reverse of string_to_ip.
ipThe binary representation of the address.
v6_onlyAlways return IPV6 addresses. IPV4 addresses will be formatted as ::FFFF:<ipv4>
The string representation of the address, or 0 if the IP was invalid.
bool is_ipv6(int|string ip)
Returns true if the IP ip is a IPV6 IP.
bool is_local_host(RemoteAddressObject|string|int host, bool|void only_localhost)
Returns true if host points to the local host.
hostThe host to check
only_localhostOnly check if it is ipv6 or ipv4 localhost, not if it is one of the public IP# of this host.
true if the given host is the local host, false otherwise
string is_local_network(RemoteAddressObject|int|string host)
Returns non-zero if host is on one of the local networks, and if so which interface it is on.
string local_host()
Returns either ::1 or 127.0.0.1 depending on the availability of IPV6.
mapping(string:array(string)) local_interfaces()
Return a mapping from interface to address/netmask (only returns non link-local addresses for ipv6)
multiset(string) local_ips(bool|void include_localhost)
Return an array with locally configured IP-numbers, excluding the
ones configured on the loopback inteface, unless
include_localhost is specified.
multiset(int) local_ips_raw(bool|void include_localhost)
Much like local_ips, but returns the IP:s parsed to the integer raw format.
IpRangeLookup local_networks()
Returns an IpRangeLookup that can be used to find the interface for an IP address.
int netmask_to_cidr(string mask)
Returns the CIDR of a given netmask. Only returns the correct value for netmasks with all-zeroes at the end (eg, 255.255.255.128 works, while 255.255.255.3 will give the wrong return value)
http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation
string|zero normalize_address(string a)
Normalize the IP specified in a. This normalizes IPv6
addresses and converts ::FFFF:<ipv4> and ::<ipv4> to "normal" IPV4
addresses.
Will return 0 if a is not a valid address.
string port_of(RemoteAddressObject|string|int(0) inc, bool|void local_address, string|void def)
Similar to ip_of but instead of IP returns port number.
If the argument is an object with a query_address method,
return the port# part of the string returned by calling that
function with local_address as the argument.
This means that for Stdio.File objects the remote address is
returned by default, but if local_address is true the local
address is returned.
If the argument is a string instead, the part of the string after the first space is returned.
If the argument is 0 the default def value is returned,
UNDEFINED unless specified.
If def is supplied, it is used both when query_address() fails
or something that is not a file descriptor object or a string is
passed as the argument to this function.
array(string) sort_addresses(array(string) addresses, array(NetworkType)|void exclude_types, bool|void separate_v6)
Given a list of addresses, sort them according to connectable priority order (RFC 3484).
If exclude_types is specified, addresses that match any of the
network types (({"local", "localhost"}) for the local network as an example)
in the given array will be exluded from the result.
If separate_v6 is true, exclude_types separates v6 from
v4. That is, you can disable "localhost" without also disabling
"localhostv6".
The addresses inside each group will be returned in random order.
IpRangeLookup special_networks()
Return an IpRangeLookup instance useful for finding out the
address category of a ip. Basically like get_network_type
without the "local" category.
int string_to_ip(string ips)
Converts a string representation of an IPv4 address into the binary representation.
ipsThe string representation of the address. For convenience this function accepts the notation returned from fd->query_adddress() ("ip port")
The binary representation of the address, or -1 if the string could not be parsed.
bool valid_domain_name(string hostname)
Perform a basic sanity check on hostname based on total and subdomain label length. Does not test for invalid chars.
hostnameDomain name string to test.
True if hostname looks like a valid domain name
constant NetUtils.Unsupported
constant NetUtils.NT
constant NetUtils.GenericIFConfig
constant NetUtils.LinuxIFConfig
constant NetUtils.LinuxIP
A list of all known network type/classes
constant NetUtils.LOCALHOST
constant NetUtils.LOCAL
constant NetUtils.MULTICAST
constant NetUtils.GLOBAL
constant NetUtils.PRIVATE
V4 and in non-v6-separate mode also used for V6
constant NetUtils.LOCALHOSTV6
constant NetUtils.LOCALV6
constant NetUtils.PRIVATEV6
constant NetUtils.MULTICASTV6
constant NetUtils.GLOBALV6
V6 only versions
constant NetUtils.LINKLOCAL
constant NetUtils.TEREDO
constant NetUtils.V6TO4
Tunneling reserved addresses
Class used for checking an IP against a list of IP ranges and looking up some associated information.
NetUtils.IpRangeLookup NetUtils.IpRangeLookup(mapping(mixed:array(string)) ranges)
Creates a new IpRangeLookup object and initialises the IP range
table. Errors will be thrown if ranges contains invalid
data.
rangesA mapping from information data to arrays of IP ranges.
Each range can be a single addresses ("192.168.1.1"), a range of addresses ("192.168.1.1-192.168.1.5") or be written in CIDR notation ("192.168.1.0/24").
mapping(string:array(Range)) get_ranges()
Return a copy of the internal range to info mapping.
mixed lookup(int|string ipstr)
Looks up an IP address and returns the associated information, if any.
ipstrThe IP address in string or binary form.
The information associated with the most-specific IP range matching ipstr.
Range lookup_range(int|string ipstr)
Looks up an IP address and returns the associated Range, if any.
ipstrThe IP address in string or binary form.
The matching net-range
Represents a single range in a IpRangeLoopup.
inherit NetMask : NetMask
mixed NetUtils.IpRangeLookup.Range.info
Persistent representation of a network + mask.
int NetUtils.NetMask.mask
The network mask
int NetUtils.NetMask.net
The network number
(int)NetUtils.NetMask()
(float)NetUtils.NetMask()
(string)NetUtils.NetMask()
(array)NetUtils.NetMask()
(mapping)NetUtils.NetMask()
(multiset)NetUtils.NetMask()
Convert to either a string (back to CIDR notation) or an array (net,mask)
NetUtils.NetMask NetUtils.NetMask(string cidr)
Construct a new NetMask object from the given CIDR.
cidrAn IP and mask in CIDR notation.
bool ip_in(int|string ip)
Match an IP number against the mask.
true if the ip is in the network, false otherwise.
ipThe IP address to check, in either string or binary representation.
Interface for objects that can be sent to ip_of and friends.
This matches at least Stdio.File and Stdio.Port, Stdio.UDP and some other classes.
constant Object.DESTRUCT_EXPLICIT
constant Object.DESTRUCT_NO_REFS
constant Object.DESTRUCT_GC
constant Object.DESTRUCT_CLEANUP
Flags passed to lfun::_destruct.
Object.DESTRUCT_EXPLICIT is 0 and
Object.DESTRUCT_CLEANUP is 1 for compatibility.
object secure(object str)
Marks the object as secure, which will clear the memory area before freeing the object.
String.secure()
constant PDF.a0_width
constant PDF.a0_height
constant PDF.a1_width
constant PDF.a1_height
constant PDF.a2_width
constant PDF.a2_height
constant PDF.a3_width
constant PDF.a3_height
constant PDF.a4_width
constant PDF.a4_height
constant PDF.a5_width
constant PDF.a5_height
constant PDF.a6_width
constant PDF.a6_height
constant PDF.b5_width
constant PDF.b5_height
constant PDF.letter_width
constant PDF.letter_height
constant PDF.legal_width
constant PDF.legal_height
constant PDF.ledger_width
constant PDF.ledger_height
constant PDF.p11x17_width
constant PDF.p11x17_height
Interface to the pdflib pdf generator. For more information see http://www.pdflib.com
int add_bookmark(string text, int parent, int open)
object add_launchlink(float llx, float lly, float urx, float ury, string filename)
object add_locallink(float llx, float lly, float urx, float ury, int page, string dest)
object add_pdflink(float llx, float lly, float urx, float ury, string filename, int page, string dest)
object add_weblink(float llx, float lly, float urx, float ury, string url)
object arc(float x, float y, float r, float start, float end)
object attach_file(float llx, float lly, float urx, float ury, string filename, string description, string author, string mimetype, string icon)
PDF begin_page()
PDF begin_page(float width, float height)
note: Defaults to a4, portrait
object circle(float x, float y, float r)
PDF close()
object close_image(int image)
object concat(float a, float b, float c, float d, float e, float f)
PDF continue_text(string s)
PDF.PDFgen PDF.PDFgen()
object curveto(float x1, float y1, float x2, float y2, float x3, float y3)
PDF end_page()
int findfont(string fontname)
int findfont(string fontname, void|string encoding, void|int embed)
string get_parameter(string key)
string get_parameter(string key, float modifier)
float get_value(string key)
float get_value(string key, float modifier)
object lineto(float x, float y)
object moveto(float x, float y)
int open_CCITT(string filename, int width, int height, int BitReverse, int K, int BlackIs1)
int open_file(string filename)
int open_image(string type, string source, string data, int width, int height, int components, int bpc, string params)
int open_image_file(string type, string filename)
int open_image_file(string type, string filename, void|string stringparam, void|int intparam)
object place_image(int image, float x, float y, float scale)
object rect(float x, float y, float width, float height)
object rotate(float phi)
object scale(float sx, float sy)
object set_border_color(float red, float green, float blue)
object set_border_dash(float b, float w)
object set_border_style(string style, float width)
float set_info(string key, string info)
float set_parameter(string key, string parameter)
object set_text_pos(float x, float y)
float set_value(string key, float value)
object setdash(float b, float w)
object setflat(float flatness)
PDF setfont(int n, float size)
object setgray(float gray)
object setgray_fill(float gray)
object setgray_stroke(float gray)
object setlinecap(int linecap)
object setlinejoin(int linejoin)
object setlinewidth(float width)
object setmiterlimit(float miter)
object setrgbcolor(float red, float green, float blue)
object setrgbcolor_fill(float red, float green, float blue)
object setrgbcolor_stroke(float red, float green, float blue)
PDF show(string s)
int show_boxed(string text, float x, float y, float width, float height, string mode)
int show_boxed(string text, float x, float y, float width, float height, string mode, string feature)
PDF showxy(string s, float x, float y)
object skew(float alpha, float beta)
float stringwidth(string text, int font, float size)
object translate(float tx, float ty)
A PangoAttrList.
Pango.AttrList copy()
Copy the list.
Pango.AttrList Pango.AttrList()
Create a new empty attribute list.
PangoContext.
inherit G.Object : Object
Pango Font Description.
int better_match(Pango.FontDescription new, Pango.FontDescription old)
Determines if the style attributes of new are a closer match than old, or if old is omitted, determines if new is a match at all. Approximate matching is done for weight and style; other attributes must match exactly.
Pango.FontDescription copy()
Copy a font description.
Pango.FontDescription Pango.FontDescription(void desc)
Create a new font description. If desc is present, creates a new font description from a string representation in the form "[FAMILY-LIST] [STYLE-OPTIONS] [SIZE]", where FAMILY-LIST is a comma separated list of families optionally terminated by a comma, STYLE-OPTIONS is a whitespace separated list of words where each word describes one of style, variant, weight, or stretch, and size is a decimal number (size in points). Any one of the options may be absent. If FAMILY-LIST is absent, then the family name will be blank. If STYLE-OPTIONS is missing, then all style options will be set to the default values. If SIZE is missing, the size in the resulting font description will be set to 0.
int equal(Pango.FontDescription desc)
Compares two font descriptions for equality.
string get_family()
Gets the family name.
int get_size()
Gets the size.
int get_stretch()
Get the stretch.
int get_style()
Gets the style.
int get_variant()
Gets the variant.
int get_weight()
Gets the weight.
Pango.FontDescription merge(Pango.FontDescription desc, int replace)
Merges the fields that are set int desc to the fields in this description. If replace is false, only fields in this description that are not already set are affected. If true, then fields that are already set will be replaced as well.
Pango.FontDescription set_family(string family)
Sets the family name. The family name represents a family of related fonts styles, and will resolve to a particular PangoFontFamily.
Pango.FontDescription set_size(int size)
Sets the size in fractional points. This is the size of the font in points, scaled by PANGO_SCALE. (That is, a size value of 10*PANGO_SCALE) is a 10 point font. The conversion factor between points and device units depends on system configuration and the output device. For screen display, a logical DPI of 96 is common, in which case a 10 point font corresponds to a 1o*(96.72) = 13.3 pixel font. Use set_absolute_size() if you need a particular size in device units.
Pango.FontDescription set_stretch(int stretch)
Sets the stretch. This specifies how narrow or wide the font should be.
One of PANGO_STRETCH_CONDENSED, PANGO_STRETCH_EXPANDED, PANGO_STRETCH_EXTRA_CONDENSED, PANGO_STRETCH_EXTRA_EXPANDED, PANGO_STRETCH_NORMAL, PANGO_STRETCH_SEMI_CONDENSED, PANGO_STRETCH_SEMI_EXPANDED, PANGO_STRETCH_ULTRA_CONDENSED and PANGO_STRETCH_ULTRA_EXPANDED.
Pango.FontDescription set_style(int style)
Sets the style. This describes whether the font is slanted and the manner
in which is is slanted. One of PANGO_STYLE_ITALIC, PANGO_STYLE_NORMAL and PANGO_STYLE_OBLIQUE. Most fonts will
either have an italic style or an oblique style, but not both, and font
matching in Pango will match italic specifications with oblique fonts and
vice-versa if an exact match is not found.
Pango.FontDescription set_variant(int variant)
Sets the variant. One of PANGO_VARIANT_NORMAL and PANGO_VARIANT_SMALL_CAPS.
Pango.FontDescription set_weight(int weight)
Sets the weight. The weight specifies how bold or light the font should
be. In addition to the values of PANGO_WEIGHT_BOLD, PANGO_WEIGHT_HEAVY, PANGO_WEIGHT_LIGHT, PANGO_WEIGHT_NORMAL, PANGO_WEIGHT_ULTRABOLD and PANGO_WEIGHT_ULTRALIGHT, other intermediate
numeric values are possible.
string to_filename()
Creates a filename representation. The filename is identical to the result from calling to_string(), but with underscores instead of characters that are untypical in filenames, and in lower case only.
string to_string()
Creates a string representation. The family list in the string description will only have a terminating comm if the last word of the list is a valid style option.
Pango Layout.
inherit G.Object : Object
Pango.Layout context_changed()
Forces recomputation of any state in the layout that might depend on the layout's context. This function should be called if you make changes to the context subsequent to creating the layout.
Pango.Layout copy(Pango.Layout src)
Does a copy of the src.
Pango.Layout Pango.Layout(void context)
Create a new layout with attributes initialized to default values for a particular Pango.Context
int get_alignment()
Gets the alignment.
int get_auto_dir()
Gets whether to calculate the bidirectional base direction for the layout according to the contents of the layout.
Pango.Context get_context()
Returns the Pango.Context.
array get_cursor_pos(int index)
Given an index within a layout, determines the positions of the strong and weak cursors if the insertion point is at that index. The position of each cursor is stored as a zero-width rectangle. The strong cursor is the location where characters of the directionality equal to the base direction of the layout are inserted. The weak cursor location is the location where characters of the directionality opposite to the base direction of the layout are inserted. Returns: array of mappings, each mapping is the same as index_to_pos().
int get_indent()
Gets the paragraph indent in pango units. A negative value indicates a hanging indent.
int get_justify()
Gets whether or not each complete line should be stretched to fill the entire width of the layout.
Pango.LayoutLine get_line(int line)
Retrieves a specific line.
int get_line_count()
Retrieves the count of lines.
int get_single_paragraph_mode()
Gets the value set by set_single_paragraph_mode().
mapping get_size()
Determines the logical width and height in Pango units.
int get_spacing()
Gets the amount of spacing between the lines.
Pango.TabArray get_tabs()
Gets the current W(TabArray) used by this layout. If no W(TabArray) has been set, then the default tabs are in use and 0 is returned. Default tabs are every 8 spaces.
string get_text()
Gets the text.
int get_width()
Gets the line wrap width.
int get_wrap()
Gets the wrap mode for the layout.
mapping index_to_pos(int index)
Converts from an index to the onscreen position corresponding to the grapheme at that index, which is represented as a rectangle. Note that x is always the leading edge of the grapheme and x+width the trailing edge of the grapheme. If the direction of the grapheme is right-to-left, then width will be negative.
Returns: ([ "x": x coordinate, "y": y coordinate, "width": width of the rectangle, "height": height of the rectangle ])
mapping move_cursor_visually(int strong, int old_index, int old_trailing, int dir)
Computes a new cursor position from an old position and a count of positions to move visually. If count is positive, then the new strong cursor position will be one position to the right of the old cursor position. If count is negative, then the new strong cursor position will be one position to the left of the old cursor position.
In the presence of bidirectional text, the correspondence between logical and visual order will depend on the direction of the current run, and there may be jumps when the cursor is moved off the end of a run.
Motion here is in cursor positions, not in characters, so a single call to move_cursor_visually() may move the cursor over multiple characters when multiple characters combine to form a single grapheme.
Pango.Layout set_alignment(int alignment)
Sets the alignment for the layout (how partial lines are positioned within
the horizontal space available.) One of PANGO_ALIGN_CENTER, PANGO_ALIGN_LEFT and PANGO_ALIGN_RIGHT.
Pango.Layout set_auto_dir(int auto_dir)
Sets whether to calculate the bidirectional base direction for the layout according to the contents of the layout; when this flag is on (the default), then paragraphs that begin with strong right-to-left characters (Arabic and Hebrew principally), will have right-left-layout, paragraphs with letters from other scripts will have left-to-right layout. Paragraphs with only neutral characters get their direction from the surrounding paragraphs.
When false, the choice between left-to-right and right-to-left layout is done by according to the base direction of the Pango.Context.
Pango.Layout set_font_description(Pango.FontDescription desc)
Sets the default font description for the layout. If no font description is set on the layout, the font descriptions from the layout's context is used.
Pango.Layout set_indent(int indent)
Sets the width in pango units to indent each paragraph. A negative value of indent will produce a hanging indent. That is, the first line will have the full width, and subsequent lines will be indented by the absolute value of indent.
Pango.Layout set_justify(int justify)
Sets whether or not each complete line should be stretched to fill the entire width of the layout. This stretching is typically done by adding whitespace, but for some scripts (such as Arabic), the justification is done by extending the characters.
Pango.Layout set_markup(string markup, int length)
Same as set_markup_with_accel(), but the markup text isn't scanned for accelerators.
Pango.Layout set_markup_with_accel(string markup, int length, int|void accel_marker)
Sets the layout text and attribute from marked-up text. Replaces the current text and attribute list.
If accel_marker is nonzero, the given character will mark the character following it as an accelerator. For example, the accel marker might be an ampersand or underscore. All characters marked as an acclerator will receive a GTK2.PANGO_UNDERLINE_LOW attribute, and the first character so marked will be returned. Two accel_marker characters following each other produce a single literal accel_marker character.
Pango.Layout set_single_paragraph_mode(int setting)
If setting is true, do not treat newlines and similar characters as paragraph separators; instead, keep all text in a single paragraph, and display a glyph for paragraph separator characters. Used when you want to allow editing of newlines on a single text line.
Pango.Layout set_spacing(int spacing)
Sets the amount of spacing between the lines.
Pango.Layout set_tabs(Pango.TabArray tabs)
Sets the tabs to use, overriding the default tabs (by default, tabs are every 8 spaces). If tabs is omitted, the default tabs are reinstated.
Pango.Layout set_text(sprintf_format text, sprintf_args ... fmt)
Sets the text of the layout.
Pango.Layout set_width(int width)
Sets the width to which the lines should be wrapped.
Pango.Layout set_wrap(int wrap)
Sets the wrap mode; the wrap mode only has an effect if a width is set on
the layout with set_width(). To turn off wrapping, set the width to -1.
One of PANGO_WRAP_CHAR, PANGO_WRAP_WORD and PANGO_WRAP_WORD_CHAR.
mapping xy_to_index(int x, int y)
Converts from x and y position within a layout to the byte index to the character at that logical position. If the y position is not inside the layout, the closest position is chosen (the position will be clamped inside the layout). If the X position is not within the layout, then the start or the end of the line is chosen as describe for x_to_index(). If either the x or y positions were not inside the layout, then returns 0.
Returns: ([ "index": byte index, "trailing": where in grapheme user clicked ]).
PangoLayoutIter.
int at_last_line()
Determines whether this iter is on the last line of the layout.
int get_baseline()
Gets the y position of the current line's baseline, in layout coordinates (origin at top left of the entire layout).
mapping get_char_extents()
Gets the extents of the current character, in layout coordinates (origin is the top left of the entire layout).
array get_cluster_extents()
Gets the extents of the current cluster, in layout coordinates.
int get_index()
Gets the current byte index. Note that iterating forward by char moves in visual order, not logical order, so indexes may not be sequential. Also, the index may be equal to the length of the text in the layout.
array get_layout_extents()
Obtains the extents of the layout.
Pango.LayoutLine get_line()
Gets the current line.
array get_line_extents()
Obtains the extents of the current line.
array get_line_yrange()
Divides the vertical space being iterated over between the lines in the layout, and returns the space belonging to the current line. A line's range includes the line's logical extents, plus half of the spacing above and below the line, if Pango.Layout->set_spacing() has been called to set layout spacing. The y positions are in layout coordinates.
array get_run_extents()
Gets the extents of the current run in layout coordinates.
int next_char()
Moves forward to the next character in visual order. If it was already at the end of the layout, returns false.
int next_cluster()
Moves forward to the next cluster in visual order. If it was already at the end of the layout, returns false.
int next_line()
Moves forward to the start of the next line. If it is already on the last line, returns false.
int next_run()
Moves forward to the next run in visual order. If it was already at the end of the layout, returns false.
PangoLayoutLine.
array get_extents()
Computes the logical and ink extents of a layout line.
array get_pixel_extents()
Computes the logical and ink extents of a layout line, in device units.
int index_to_x(int index, int trailing)
Converts an index within a line to an x position.
mapping x_to_index(int x_pos)
Converts from x offset to the byte index of the corresponding character within the text of the layout. If x_pos is outside the line, index and trailing will point to the very first or very last position in the line. This determination is based on the resolved direction of the paragraph; for example, if the resolved direction is right-to-left, then an X position to the right of the line (after it) results in 0 being stored in index and trailing. An X position to the left of the line results in index pointing to the (logical) last grapheme in the line and trailing set to the number of characters in that grapheme. The reverse is true for a left-to-right line.
A set of tab stops for laying out text that includes tab characters.
inherit G.Object : Object
Pango.TabArray copy()
Returns a copy.
Pango.TabArray Pango.TabArray(void initial_size, void position_in_pixels)
Creates an array of initial_size tab stops. Tab stops are specified in pixel units if positions_in_pixels is true, otherwise in Pango units. All stops are initially at position 0.
int get_positions_in_pixels()
Returns true if the tab positions are in pixels, false if they are in Pango units.
int get_size()
Gets the number of tab stops.
mapping get_tab(int tab_index)
Gets the alignment and position of a tab stop.
array get_tabs()
Gets alignments and locations of all tab stops.
Pango.TabArray resize(int new_size)
Resizes the array. You must subsequently initialize any tabs that were added as a result of growing the array.
Pango.TabArray set_tab(int tab_index, int alignment, int location)
Sets the alignment and location of a tab stop. Alignment must always be
PANGO_TAB_LEFT.
Pike.local constantINDEX_FROM_BEG
Pike.local constantINDEX_FROM_END
Pike.local constantOPEN_BOUND
Used with predef::`[..] and lfun::`[..] to specify how the
corresponding index maps to an upper or lower range bound:
The index is relative to the beginning of the string or array (or any other sequence implemented through an object). Sequences typically start at zero.
The index is relative to the end of the sequence. In strings and arrays, the last element is at zero, the one before that at one, etc.
The range is open in the corresponding direction. The index is irrelevant in this case.
Pike.local constantWEAK_INDICES
Pike.local constantWEAK_VALUES
Pike.local constantWEAK
Flags for use together with set_weak_flag and get_weak_flag.
See set_weak_flag for details.
Pike.local constant__HAVE_CPP_PREFIX_SUPPORT__
This constant exists and has the value 1 if cpp supports the prefix feature.
cpp()
int count_memory(int|mapping(string:int) options, mixed ... things)
In brief, if you call Pike.count_memory(0,x) you get back
the number of bytes x occupies in memory.
The detailed story is a bit longer:
This function calculates the number of bytes that all things
occupy. Or put another way, it calculates the number of bytes that
would be freed if all those things would lose their references at
the same time, i.e. not only the memory in the things themselves,
but also in all the things that are directly and indirectly
referenced from those things and not from anywhere else.
The memory counted is only that which is directly occupied by the things in question, including any overallocation for mappings, multisets and arrays. Other memory overhead that they give rise to is not counted. This means that if you would count the memory occupied by all the pike accessible things you would get a figure significantly lower than what the OS gives for the pike process.
Also, if you were to actually free the things, you should not expect the size of the pike process to drop the amount of bytes returned by this function. That since Pike often retains the memory to be reused later.
However, what you should expect is that if you actually free the things and then later allocates some more things for which this function returns the same size, there should be essentially no increase in the size of the pike process (some increase might occur due to internal fragmentation and memory pooling, but it should be small in general and over time).
The search for things only referenced from things can handle
limited cyclic structures. That is done by doing a "lookahead",
i.e. searching through referenced things that apparently have
other outside references. You can control how long this lookahead
should be through options (see below). If the lookahead is too
short to cover the cycles in a structure then a too low value is
returned. If the lookahead is made gradually longer then the
returned value will eventually become accurate and not increase
anymore. If the lookahead is too long then unnecessary time might
be spent searching through things that really have external
references.
Objects that are known to be part of cyclic structures are
encouraged to have an integer constant or variable
pike_cycle_depth that specifies the lookahead needed to
discover those cycles. When Pike.count_memory visits such
objects, it uses that as the lookahead when going through the
references emanating from them. Thus, assuming objects adhere to
this convention, you should rarely have to specify a lookahead
higher than zero to this function.
Note that pike_cycle_depth can also be set to zero to
effectively stop the lookahead from continuing through the object.
That can be useful to put in objects you know have global
references, to speed up the traversal.
optionsIf this is an integer, it specifies the maximum lookahead
distance. -1 counts only the memory of the given things,
without following any references. 0 extends the count to all
their referenced things as long as there are no cycles (except
if pike_cycle_depth is found in objects - see above). 1
makes it cover cycles of length 1 (e.g. a thing points to
itself), 2 handles cycles of length 2 (e.g. where two things
point at each other), and so on.
However, the lookahead is by default blocked by programs, i.e. it never follows references emanating from programs. That since programs seldom are part of dynamic data structures, and they also typically contain numerous references to global data which would add a lot of work to the lookahead search.
To control the search in more detail, options can be a
mapping instead:
| The maximum lookahead distance, as described above. Defaults to 0 if missing. |
| When any of these are given with a nonzero value, the corresponding type is blocked when lookahead references are followed. They are unblocked if the flag is given with a zero value. Only programs are blocked by default. These blocks are only active during the lookahead, so blocked things are still recursed and memory counted if they are given as arguments or only got internal references. |
| |
| |
| |
| |
| If positive then strings are always excluded (except any
given directly in |
| Do not heed |
| Return the number of things that memory was counted for,
instead of the byte count. (This is the same number
|
| If this is nonzero then its value is replaced with an array that contains the things that memory was counted for. |
| If set then the value is replaced with an array containing the things that were visited but turned out to have external references (within the limited lookahead). |
| If set then the value is replaced with an array containing
the things found during the lookahead that (appears to) have
direct external references. This list is a subset of the
|
| If this is nonzero then the mapping is extended with more elements containing statistics from the search; see below. |
When the collect_stats flag is set, the mapping is
extended with these elements:
| Number of things that were marked internal and hence memory counted. It includes the things given as arguments. |
| Number of things that were marked internal only after resolving cycles. |
| Number of things that were visited through the lookahead but were found to be external. |
| Number of times things were visited in total. This figure includes visits to various internal things that aren't visible from the pike level, so it might be larger than what is apparently motivated by the numbers above. |
| Number of times the same things were revisited. This can
occur in the lookahead when a thing is encountered through a
shorter path than the one it first got visited through. It
also occurs in resolved cycles. Like |
| Number of search rounds. This is usually 1 or 2. More rounds are necessary only when blocked types turn out to be (acyclic) internal, so that they need to be counted and recursed anyway. |
| The number of elements that were allocated to store the work queue which is used to keep track of the things to visit during the lookahead. This is usually bigger than the maximum number of things the queue actually held. |
| The memory occupied by the internal things. This is the same as the normal return value, but it's put here too for convenience. |
thingsOne or more things to count memory size for. Only things passed by reference are allowed, except for functions which are forbidden because a meaningful size calculation can't be done for them.
Integers are allowed because they are bignum objects when they become sufficiently large. However, passing an integer that is small enough to fit into the native integer type will return zero.
Returns the number of bytes occupied by the counted things. If
the return_count option is set then the number of things
are returned instead.
The result of Pike.count_memory(0,a,b) might be larger
than the sum of Pike.count_memory(0,a) and
Pike.count_memory(0,b) since a and b
together might reference things that aren't referenced from
anywhere else.
It's possible that a string that is referenced still isn't counted, because strings are always shared in Pike and the same string may be in use in some unrelated part of the program.
mapping(string:float) gc_parameters(void|mapping(string:mixed) params)
Set and get various parameters that control the operation of the garbage collector. The passed mapping contains the parameters to set. If a parameter is missing from the mapping, the current value will be filled in instead. The same mapping is returned. Thus an empty mapping, or no argument at all, causes a mapping with all current settings to be returned.
The following parameters are recognized:
| If this is 1 then the gc is enabled as usual. If it's 0 then all
automatically scheduled gc runs are disabled and the parameters
below have no effect, but explicit runs through the | ||||
| As long as the gc time is less than time_ratio below, aim to run the gc approximately every time the ratio between the garbage and the total amount of allocated things is this. | ||||
| When more than this fraction of the time is spent in the gc, aim for garbage_ratio_high instead of garbage_ratio_low. | ||||
| Upper limit for the garbage ratio - run the gc as often as it takes to keep it below this. | ||||
| This puts an upper limit on the gc interval, in addition to the factors above. It is specified as the minimum amount of time spent doing gc, as a factor of the total time. The reason for this limit is that the current amount of garbage can only be measured in a gc run, and if the gc starts to run very seldom due to very little garbage, it might get too slow to react to an increase in garbage generation. Set to 0.0 to turn this limit off. | ||||
| When predicting the next gc interval, use a decaying average with this slowness factor. It should be a value between 0.0 and 1.0 that specifies the weight to give to the old average value. The remaining weight up to 1.0 is given to the last reading. | ||||
| This function is called when the gc starts. | ||||
| This function is called when the mark and sweep pass of the gc is done. | ||||
| This function is called once for each object that is part of a cycle just before the gc will destruct it. The arguments are:
| ||||
| This function is called when the gc is done and about to exit. The argument is the same value as will be returned by gc(). |
gc, Debug.gc_status
type|zero get_first_arg_type(type fun_type)
Check if a function of the type fun_type may be called
with an argument, and return the type of that argument.
Returns the expected type of the first argument to the function.
Returns 0 (zero) if a function of the type fun_type
may not be called with any argument, or if it is not callable.
type|zero get_return_type(type fun_type)
type|zero get_return_type(type fun_type, mapping state)
Check what a function of the type fun_type will
return if called with no further arguments.
stateState mapping. This mapping may be used by attribute handlers to store state between different arguments. Note that attribute handlers may alter the contents of the mapping.
Returns the type of the returned value on success
Returns 0 (zero) on failure.
mapping(string:int|string) get_runtime_info()
Get information about the Pike runtime.
Returns a mapping with the following content:
| A string describing the bytecode method used by the Pike interpreter. |
| The number of bits in the ABI. Usually |
| The byte order used by the native cpu.
Usually |
| The number of bits in the native integer type.
Usually |
| The number of bits in the native time_t type.
This is typically the same value as |
| The number of bits in the native floating point type.
Usually |
| Integers larger than the native size are now always automatically converted into bignums. |
| The runtime has been compiled --with-rtldebug. |
| The runtime has been compiled --with-debug-malloc. |
| The number of nested valgrinds the runtime is running under. |
array(string) get_type_attributes(type t)
Get the attribute markers for a type.
Returns an array with the attributes for the type t.
get_return_type(), get_first_arg_type()
array(mixed) identify_cycle(mixed x)
Identify reference cycles in Pike datastructures.
This function is typically used to identify why certain
datastructures need the gc to run to be freed.
xValue that is believed to be involved in a reference cycle.
| Returns |
| Otherwise returns an array identifying a cycle with |
int implicit_gc_real_time(void|int nsec)
Returns the total amount of real time that has been spent in
implicit GC runs. The time is normally returned in microseconds,
but if the optional argument nsec is nonzero it's returned in
nanoseconds.
Debug.gc_status
type|zero low_check_call(type fun_type, type arg_type)
type|zero low_check_call(type fun_type, type arg_type, int flags)
type|zero low_check_call(type fun_type, type arg_type, int flags, mapping state)
type|zero low_check_call(type fun_type, type arg_type, int flags, mapping state, mixed val)
Check whether a function of type fun_type may be called
with a first argument of type arg_type.
flagsThe following flags are currently defined:
| Strict types. Fail if not all possible values in |
| Last argument. |
| Both strict types and last argument as above. |
stateState mapping. This mapping may be used by attribute handlers to store state between different arguments. Note that attribute handlers may alter the contents of the mapping.
valValue of the argument if known.
Returns a continuation type on success.
Returns 0 (zero) on failure.
bool signal_contextp()
Returns whether the current thread is running in a signal handler context.
A signal handler context implies that ordinary program flow for the current thread has been interrupted (note that other threads will continue to execute concurrently), and will resume when the handler returns. Note that code that is executing in a signal context may still be interrupted.
Some origins for entering a signal handler context are:
A caught signal triggering a signal handler to be called.
An object implementing lfun::_destruct() running out
of references or being destructed by the gc().
An uncaught runtime error (causing MasterObject()->handle_error()
to be called).
In a signal handler context some operations are not supported
eg locking of Thread.Mutex or waiting on Thread.Condition.
Intended use is to be able to throw errors early in APIs that are
not signal context safe, or to be able to detect this and upgrade
the call to a normal context (eg via call_out()).
lfun::_destruct(), call_out(), gc(),
MasterObject()->handle_error()
type|zero soft_cast(type to, type from)
Return the resulting type from a soft cast of from to to.
Returns UNDEFINED if the cast is invalid.
The return value for the invalid case may in the future
change to __unknown__.
int switch_lookup(array|mapping switch_table, mixed val)
Lookup a switch-case.
switch_tableLookup table as generated by the compiler.
valValue to lookup.
Returns the entry number (ie >= 0) if val was found
in switch_table, and the binary inverse of the next entry
number (ie < 0) if it was not found.
This class describes the API that the compiler expects for the annotation syntax.
Classes implementing this API typically need to be marked constant.
Annotations
optional void end_pass(int pass, program prog, CompilerEnvironment.PikeCompiler compiler)
Callback called by the compiler when it is finishing a compilation pass.
passCompilation pass.
progProgram being compiled.
compilerCompilerEnvironment.PikeCompiler state for the compiler.
bool res = is_type(Pike.BacktraceFrame())
This object claims to be an array for backward compatibility.
int(3..) sizeof( Pike.BacktraceFrame arg )
string sprintf(string format, ... Pike.BacktraceFrame arg ... )
mixed res = Pike.BacktraceFrame()[ index ]
The BacktraceFrame object can be indexed as an array.
Pike.BacktraceFrame()[ index ] = value
An empty class that can be inherited to get the PROGRAM_DESTRUCT_IMMEDIATE flag set.
InhibitDestruct
Used as a place holder in eg backtraces for objects that are unsuitable to have references to in backtraces.
Examples of such objects are instances of Thread.MutexKey,
and Nettle.Cipher.State.
backtrace()
This is a class that implements a way to temporarily
inhibit destruction by explicit calls of destruct().
This is mostly useful as a mix-in for modules implemented in C or similar.
All symbols in the class are either protected
or private in order to affect users minimally.
DestructImmediate
bool _destruct(int|void reason)
Returns 1 when inhibit_destruct() has been
called more times than permit_destruct().
inhibit_destruct(), permit_destruct(),
destruct(), lfun::_destruct()
void inhibit_destruct()
Inhibit explicit destruction of this object.
permit_destruct(), _destruct(),
destruct(), lfun::_destruct()
void permit_destruct()
Allow explicit destruction of this object again.
inhibit_destruct(), _destruct(),
destruct(), lfun::_destruct()
A BacktraceFrame which retains access to the running code.
This means that unless the corresponding thread running the code is halted (or similar), the values in the fields contained in this object may change at any time.
On the other hand it allows for inspection and altering of the local variables (if any) belonging to the frame. Typical use of this would be for debugging.
BacktraceFrame
bool res = is_type(Pike.LiveBacktraceFrame())
This object claims to be an array for backward compatibility.
int(3..) sizeof( Pike.LiveBacktraceFrame arg )
mixed res = Pike.LiveBacktraceFrame()[ index ]
The BacktraceFrame object can be indexed as an array.
This is a bare-bones codec that is used when loading a dumped master.
Codec
object decode_object(object obj, mixed data)
Calls obj->_decode(.data)
mixed functionof(mixed symbol)
Look up a function in all_constants().
mixed objectof(mixed symbol)
Look up an object in all_constants().
mixed programof(mixed symbol)
Look up a program in all_constants().
Backend implemented with poll(2) (SVr4, POSIX).
Backend
inherit __Backend : __Backend
float|int(0) res = Pike.PollBackend()()
Perform one pass through the backend.
Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.
sleep_timeWait at most sleep_time seconds. The default when
unspecified or the integer 0 is no time limit.
If the backend did call any callbacks or call outs then the
time spent in the backend is returned as a float. Otherwise
the integer 0 is returned.
Pike.DefaultBackend, main()
Backend implemented with /dev/poll (Solaris and OSF/1),
epoll(2) (Linux) or kqueue(2) (MacOS X, FreeBSD, OpenBSD, etc).
Backend
inherit __Backend : __Backend
float|int(0) res = Pike.PollDeviceBackend()()
Perform one pass through the backend.
Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.
sleep_timeWait at most sleep_time seconds. The default when
unspecified or the integer 0 is no time limit.
If the backend did call any callbacks or call outs then the
time spent in the backend is returned as a float. Otherwise
the integer 0 is returned.
Pike.DefaultBackend, main()
int enable_core_foundation(bool enable)
On systems with CoreFoundation (OSX, iOS, etc), use CoreFoundation to poll for events. This enables system level technologies that rely on CoreFoundation Runloops to function properly.
enableenable or disable this functionality
the previous value of this setting.
int enable_external_runloop(bool enable)
On systems with CoreFoundation (OSX, iOS, etc), delegate running of the Pike Backend to the main runloop of the process (such as a Cocoa application's NSRunLoop).
Enabling the external runloop allows Pike callouts and callback-based I/O to function normally while greatly reducing cpu utilization compared to running the external runloop manually.
enableenable or disable this functionality
the previous value of this setting.
int query_core_foundation_enabled()
On systems with CoreFoundation (OSX, iOS, etc), indicate whether CoreFoundation is being used by this backend to poll for events.
the current state of CoreFoundation polling: 1=enabled, 0=disabled
optional void set_signal_event_callback(int signum, function(:void) cb)
Request cb to be called from the backend when the signal
signum is received.
This function is a noop except for the kqueue case.
Caveat emptor: Unlikely to work.
signal()
Backend based on the classic select(2) system call from BSD.
inherit __Backend : __Backend
float|int(0) res = Pike.SelectBackend()()
Perform one pass through the backend.
Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.
sleep_timeWait at most sleep_time seconds. The default when
unspecified or the integer 0 is no time limit.
If the backend did call any callbacks or call outs then the
time spent in the backend is returned as a float. Otherwise
the integer 0 is returned.
Pike.DefaultBackend, main()
@@Pike.Annotations.Implements(Pike.__Backend)This is the most suitable backend implementation if you only want
to monitor a small number of Stdio.File objects.
inherit Pike.__Backend : __Backend
A Watchdog that ensures that the process is not hung for an extended period of time. The definition of 'hung' is: Has not used the default backend.
An important and useful side-effect of this class is that the process will start to respond to kill -QUIT by printing a lot of debug information to stderr, including memory usage, and if pike is compiled with profiling, the CPU used since the last time kill -QUIT was called.
void add_debug(function(void:void) f)
The function f will be called if the watchdog triggers, before
the normal watchdog output is written.
void add_probe(function(void:bool) f)
Add additional functions to be called each time the watchdog is checked. If any of the probes return false, the watchdog will trigger.
void alarm_alarm_alarm()
Explicitly trigger the watchdog, if enough CPU time has been used. This is not normally called manually.
Pike.Watchdog Pike.Watchdog(int t)
Create a new watchdog, with the intended delay.
Even though the actual watchdog functionality is currently not available on systems without sigalarm, such as Windows, the functionality can still be triggered by adding probe functions
add_probe() and set_delay()
void ping()
Tell the watchdog that all is well, and the CPU is not really blocked. Can be used during long calculations that block the normal backend, note that this basically bypasses the main functionality of the watchdog, that is, detecting blocked backend threads.
void print_debug()
Output thread stacktraces, memory and profiling (if available) debug information to stderr.
void really_trigger_watchdog_promise()
Really trigger the watchdog, killing the current process. This is not normally called manually.
void set_delay(int t)
Set the watchdog interval to t seconds.
The change will not take effect until the previous probe has been triggered.
Base class for the various backend implementations.
Implements callback registration functions and defines the main backend APIs.
function(Backend:void) Pike.__Backend.before_callback
function(Backend:void) Pike.__Backend.after_callback
If set, these are called just before and after the backend waits for an event.
If an error is thrown from these callbacks then it is reported
using master()->handle_error() - it doesn't interrupt
the operation of the backend.
int _do_call_outs()
Do all pending call_outs.
This function runs all pending call_outs that should have been run if Pike returned to the backend. It should not be used in normal operation.
As a side-effect, this function sets the value returned by
time(1) to the current time.
Zero if no call outs were called, nonzero otherwise.
call_out(), find_call_out(), remove_call_out()
void _m_clear()
Clear all active registrations with this backend (ie unlink all file event callbacks and pending call_outs).
Files are still registered with the backend (albeit the backend does no longer hold any references to them).
float|int(0) res = Pike.__Backend()()
Perform one pass through the backend.
Calls any outstanding call-outs and non-blocking I/O callbacks that are registred in this backend object.
sleep_timeWait at most sleep_time seconds. The default when
unspecified or the integer 0 is no time limit.
If the backend did call any callbacks or call outs then the
time spent in the backend is returned as a float. Otherwise
the integer 0 is returned.
If multiple threads concurrently call this function, then:
One of the threads will be the controlling thread.
All callbacks will be called from the controlling thread.
All threads will be woken up when the controlling thread is done. This may be prematurely if the controlling thread had a shorter timeout.
The backend may also be woken up prematurely if the set of events to monitor is changed.
Multiple concurrent calls was not supported prior to Pike 8.0.
Pike.DefaultBackend, main()
void add_file(Stdio.File|Stdio.FILE f)
Register a file to be handled by this backend.
fFile to register.
Registers f to be handled by this backend.
This simply does f->set_backend(backend) where
backend is this object.
Pike.DefaultBackend, main()
array call_out(function(:void) f, float|int delay, mixed ... args)
Make a delayed call to a function.
call_out() places a call to the function f with the argument
args in a queue to be called in about delay seconds.
If f returns -1, no other call out or callback will be
called by the backend in this round. I.e. `() will return right
away. For the main backend that means it will immediately start
another round and check files and call outs anew.
Returns a call_out identifier that identifies this call_out.
This value can be sent to eg find_call_out() or remove_call_out().
remove_call_out(), find_call_out(), call_out_info(),
CallOut
array(array) call_out_info()
Get info about all call_outs.
This function returns an array with one entry for each entry in the call out queue. The first in the queue will be at index 0. Each index contains an array that looks like this:
| Array | |
| Time remaining in seconds until the call_out is to be performed. |
| Used to be the object that scheduled the call_out. |
| Function to be called. |
| Arguments to the function. |
call_out(), find_call_out(), remove_call_out()
Pike.__Backend Pike.__Backend()
Thread.Thread executing_thread()
int executing_thread()
Return the thread currently executing in the backend. I.e. the
thread that has called `() and hasn't exited from that call.
Zero is returned if there's no thread in the backend.
If Pike is compiled without thread support then 1 is
returned if we're inside the backend, 0 otherwise.
int find_call_out(function(:void) f)
int find_call_out(array id)
Find a call out in the queue.
This function searches the call out queue. If given a function as argument, it looks for the first call out scheduled to that function.
The argument can also be a call out id as returned by call_out(), in
which case that call_out will be found (Unless it has already been
called).
find_call_out() returns the remaining time in seconds before that
call_out will be executed. If no call_out is found,
zero_type(find_call_out(f)) will return 1.
call_out(), remove_call_out(), call_out_info()
mapping(string:int) get_stats()
Get some statistics about the backend.
Returns a mapping with the follwoing content:
| The number of active call-outs. |
| The amount of memory used by the call-outs. |
int id()
Return an integer that uniquely identifies this backend. For
the default backend that integer is 0.
int remove_call_out(function(:void) f)
int remove_call_out(array id)
Remove a call out from the call out queue.
This function finds the first call to the function f in the call_out
queue and removes it. You can also give a call out id as argument (as
returned by call_out()).
The remaining time in seconds left to that call out will be returned.
If no call_out was found, zero_type(remove_call_out(f))
will return 1.
call_out_info(), call_out(), find_call_out()
Represents a single call_out in the call_out list.
call_out()
protected array Pike.__Backend.CallOut.args
The array containing the function and arguments.
Pike.__Backend.CallOut Pike.__Backend.CallOut(int|float seconds, mixed fun, mixed ... args)
Start a new call out.
This is the low-level implementation of call_out().
call_out() is essentially implemented as:
array call_out(mixed fun, int|float seconds, mixed ... args)
{
return CallOut(seconds, fun, @args)->args;
}
call_out()
This module contains the set of annotations that the compiler and runtime care about.
constant Pike.Annotations.AutoCodec
This Annotation causes the compiler to automatically
add an implementation of _encode() that returns
an array with suitable arguments to lfun::create.
This annotation is only useful for classes that use the implicit create()-syntax, or have a create() that doesn't need any arguments.
constant Pike.Annotations.Inherited
This Annotation informs the compiler that any Annotation
marked with it is to be inherited. The default is that annotations
on classes are not inherited.
constant Pike.Annotations.Override
This Annotation informs the compiler that any symbol
marked with it is expected to also have been inherited.
This is the class that implements the AutoCodec annotation.
inherit Annotation : Annotation
This annotation causes the compiler to validate that the annotated class implements the specified API.
inherit Pike.Annotation : Annotation
This is the class for the Inherited annotation.
inherit Pike.Annotation : Annotation
This is the class for the Override annotation.
inherit Pike.Annotation : Annotation
This is the Backend object that files and call_outs are
handled by by default.
This is also the Backend object that will be used if main()
returns -1.
Backend, Stdio.File()->set_nonblocking(), call_out()
This module provides lazy resolving of functions.
The expression
Pike.Lazy.Standards.JSON.decodewill evaluate toStandards.JSON.decode, but the resolution (and associated compilation) ofStandards.JSONwill be delayed until the first time that the expression is evaluated.
Note that this destroys type information and delays resolver errors.
Typical use is to break circular compilation dependencies between modules.
string Pike.Lazy.LazyValue.path
protected local void __create__(string path)
Pike.Lazy.LazyValue Pike.Lazy.LazyValue(string path)
Single socket output.
Regular file output and (multiple, adding) socket output with no mmap input.
Multiple socket output without regular file output illegal.
It is preferable to use the Shuffler API, it is significantly
more flexible.
Concatenation pipe.
int bytes_sent()
Return the number of bytes sent.
void finish()
Terminate and reinitialize the pipe.
void input(object obj)
Add an input file to this pipe.
void output(object obj, int|void start_pos)
Add an output file object.
void set_done_callback(void|function(mixed:mixed) done_cb, void|mixed id)
Set the callback function to be called when all the outputs have been sent.
void set_output_closed_callback(void|function(mixed, object:mixed) close_cb, void|mixed id)
Set the callback function to be called when one of the outputs has been closed from the other side.
void start()
Start sending the input(s) to the output(s).
string version()
Return the version of the module.
void write(string bytes)
Add an input string to this pipe.
void daemon(int nochdir, int noclose, void|mapping(string:string|Stdio.File) modifiers)
A function to run current program in the background.
nochdirIf 0 the process will continue to run in / or the directory dictadet by modifiers.
nocloseIf this is not 0 the process will keep current file descriptors open.
modifiersOptional extra arguments. The parameters passed in this mapping will override the arguments nochdir and noclose.
| Change current working directory to this directory. |
| If this is a string this will be interpreted as a filename pointing out a file to be used as stdandard input to the process. If this is a Stdio.File object the process will use this as standard input. |
| If this is a string this will be interpreted as a filename pointing out a file to be used as stdandard output to the process. If this is a Stdio.File object the process will use this as standard output. |
| If this is a string this will be interpreted as a filename pointing out a file to be used as stdandard error to the process. If this is a Stdio.File object the process will use this as standard error. |
System.daemon
This function only works on UNIX-like operating systems.
/* close all fd:s and cd to '/' */ Process.daemon(0, 0);
/* Do not change working directory. Write stdout to a file called access.log and stderr to error.log. */ Process.daemon(1, 0, ([ "stdout": "access.log", "stderr": "error.log" ]) );
int exec(string file, string ... foo)
bool get_forkd_default()
Get the default value for the "forkd" modifier
to Process.
The default default value is 0 (zero).
set_forkd_default(), Process()->create()
string popen(string command)
Executes command as a shell statement ("/bin/sh -c
" for Unix, "commandcmd /c " for Windows),
waits until it has finished and returns the result as a string.command
system, spawn
Replaced by Process.Process.
Stdio.FILE popen(string command, string mode)
Open a "process" for reading or writing. The command is executed
as a shell statement ("/bin/sh -c " for Unix,
"commandcmd /c " for Windows). The parameter commandmode
should be one of the following letters:
| Open for reading. Data written by the process to stdout is available for read. |
| Open for writing. Data written to the file is available to the process on stdin. |
system, spawn
Replaced by Process.Process.
mapping run(string|array(string) cmd, mapping|void modifiers)
Easy and lazy way of using Process.Process that runs a process
and returns a mapping with the output and exit code without
having to make sure you read nonblocking yourself.
argsEither a command line array, as the command_args
argument to create_process(), or a string that
will be splitted into a command line array by
calling split_quoted_string() in an operating
system dependant mode.
modifiersIt takes all the modifiers Process.Process accepts, with
the exception of stdout and stderr. Each must be either absent, or
a function accepting a string; if present, the functions will be called
whenever output is made on the corresponding stream, otherwise the data
will be collected and returned in the result mapping.
If modifiers->stdin is set to a string it will automatically be
converted to a pipe that is fed to stdin of the started process.
Process.Process create_process
| Everything the process wrote on stdout, unless a stdout function was provided. |
| Everything the process wrote on stderr, similarly. |
| The process' exitcode. |
As the entire output of stderr and stdout is stored in the returned mapping it could potentially grow until memory runs out. It is therefore advisable to set up rlimits if the output has a potential to be very large, or else provide functions to handle partial data.
Process.run( ({ "ls", "-l" }) ); Process.run( ({ "ls", "-l" }), ([ "cwd":"/etc" ]) ); Process.run( "ls -l" ); Process.run( "awk -F: '{print $2}'", ([ "stdin":"foo:2\nbar:17\n" ]) ); Process.run( ({ "echo Output will be immediately written to stdout" }), ([ "stdout": lambda(string s) { write(s); }, "stderr": lambda(string e) { werror(e); } ]) );
string search_path(string command)
Search for the path to an executable.
commandExecutable to search for.
Searches for command in the directories listed in the
environment variable $PATH.
Returns the path to command if found, and
0 (zero) on failure.
This function is NOT thread safe if the environment variable $PATH is being changed concurrently.
In Pike 7.8.752 and earlier the environment variable $PATH was only read once.
void set_forkd_default(bool mode)
Set the default value for the "forkd" modifier
to Process.
The default default value is 0 (zero).
get_forkd_default(), Process()->create()
string sh_quote(string s)
__deprecated__ Process spawn(string command, void|Stdio.Stream stdin, void|Stdio.Stream stdout, void|Stdio.Stream stderr)
Spawns a process that executes command as a command shell
statement ("/bin/sh -c " for Unix, "commandcmd /c
" for Windows).command
stdinstdoutstderrStream objects to use as standard input, standard output and standard error, respectively, for the created process. The corresponding streams for this process are used for those that are left out.
Returns a Process.Process object for the created process.
system, popen
Replaced by Process.Process.
Process spawn_pike(array(string) argv, void|mapping(string:mixed) options, array(string)|void launcher)
Spawn a new pike process similar to the current.
argvArguments for the new process.
optionsProcess creation options. See Process.Process for details. May also
specify "add_predefines", "add_program_path", or "add_include_path" in
order to include these components in command path (module path is
included by default.)
launcherOptional launcher prefix command used to spawn the pike binary.
When used this is typically something like
({ "/usr/bin/valgrind" }).
Defaults to the empty array.
Process.Process
array(string) split_quoted_string(string s, bool|void nt_mode)
Splits the given string into a list of arguments, according to
common (i.e. /bin/sh-based) command line quoting rules:
Sequences of whitespace, i.e. space, tab, \n or
\r, are treated as argument separators by default.
Single or double quotes (' or ") can be used
around an argument to avoid whitespace splitting inside it. If
such quoted strings are used next to each other then they get
concatenated to one argument; e.g. a"b"'c' becomes a
single argument abc.
Backslash (\) can be used in front of one of the space
or quote characters mentioned above to treat them literally.
E.g. x\ y is a single argument with a space in the
middle, and x\"y is a single argument with a double
quote in the middle.
A backslash can also be used to quote itself; i.e. \\
becomes \.
Backslashes in front of other characters are removed by default.
However, if the optional nt_mode flag is set then they are
retained as-is, to work better with Windows style paths.
Backslashes are treated literally inside quoted strings, with
the exception that \" is treated as a literal "
inside a "-quoted string. It's therefore possible to
include a literal " in a "-quoted string, as
opposed to '-quoted strings which cannot contain a
'.
__deprecated__ int system(string command, void|Stdio.Stream stdin, void|Stdio.Stream stdout, void|Stdio.Stream stderr)
Executes command as a shell statement ("/bin/sh -c
" for Unix, "commandcmd /c " for Windows),
waits until it has finished and returns its return value.command
stdinstdoutstderrStream objects to use as standard input, standard output and standard error, respectively, for the created process. The corresponding streams for this process are used for those that are left out.
Returns the exit code for the subprocess on normal completion. Returns the negation of the last signal code if it terminated due to a signal.
In Pike 8.0 and earlier this function returned the result
straight from Process.Process()->wait().
Replaced by Process.Process.
spawn, popen
Decoder for data received by Tools.Standalone.forkd.
ForkdEncoder
array(Stdio.Fd) Process.ForkdDecoder.fds
protected local void __create__(array(Stdio.Fd) fds)
Process.ForkdDecoder Process.ForkdDecoder(array(Stdio.Fd) fds)
Encoder for data to be sent to Tools.Standalone.forkd.
ForkdDecoder
Stdio.File Process.ForkdEncoder.remote_fd
protected local void __create__(Stdio.File remote_fd)
Process.ForkdEncoder Process.ForkdEncoder(Stdio.File remote_fd)
Slightly polished version of create_process.
In addition to the features supported by create_process,
it also supports:
Callbacks on timeout and process termination.
Using Tools.Standalone.forkd via RPC to
spawn the new process.
create_process, Tools.Standalone.forkd
inherit create_process : create_process
Based on create_process.
Process.Process Process.Process(string|array(string) command_args, mapping(string:mixed)|void modifiers)
command_argsEither a command line array, as the command_args
argument to create_process(), or a string that
will be splitted into a command line array by
calling split_quoted_string() in an operating
system dependant mode.
modifiersIn addition to the modifiers that create_process accepts,
this object also accepts
| This callback is called when there is data to be read from the process. |
| This callback is called if the process times out. |
| The time it takes for the process to time out. Default is 15 seconds. |
| Use |
The default value for the "forkd" modifier may be
set via set_forkd_default().
create_process, create_process()->create(),
split_quoted_string(), Tools.Standalone.forkd,
set_forkd_default(), get_forkd_default()
Process.Spawn Process.Spawn(string cmd, void|array(string) args, void|mapping(string:string) env, string|void cwd, void|array(Stdio.File|void) ownpipes, void|array(Stdio.File|void) fds_to_close)
int kill(int signal)
int wait()
Class that enables tracing of processes.
The new process will be started in stopped state.
Use cont() to let it start executing.
This class currently only exists on systems that implement ptrace().
inherit create_process : create_process
void cont(int|void signal)
Allow a traced process to continue.
signalDeliver this signal to the process.
This function may only be called for stopped processes.
wait()
void exit()
Cause the traced process to exit.
This function may only be called for stopped processes.
cont(), wait()
int wait()
Waits for the process to stop.
| The exit code of the process. |
| The process was killed by a signal. |
| The process has stopped. |
create_process::wait()
Interface to the current register contents of a stopped process.
TraceProcess
int res = Process.TraceProcess.Registers()[ regno ]
Get the contents of register regno.
This is the recommended and most portable way to start processes in Pike. The process object is a pike abstraction of the running system process, with methods for various process housekeeping.
Process
constant Process.create_process.limit_value
Each limit_value may be either of:
sets current limit, max is left as it is.
([ "hard":int, "soft":int ]) Both values are optional, hard <= soft.
({ hard, soft }), both can be set to the string "unlimited". A value of -1 means 'keep the old value'.
The string "unlimited" sets both the hard and soft limit to unlimited
string sprintf(string format, ... Process.create_process arg ... )
Process.create_process Process.create_process(array(string) command_args, void|mapping modifiers)
command_argsThe command name and its command-line arguments. You do not have to worry about quoting them; pike does this for you.
modifiersThis optional mapping can can contain zero or more of the following parameters:
| Function called when the created process changes state. Note that this function is called in a signal handler context, which means that it may be called by any thread at any time after the child process has changed state, and is thus not only called by the main thread when the main backend is idle. Indeed, you can specify a callback even if your program does not use a backend. | ||||||||||||||||
| Execute the command in another directory than the current directory of this process. Please note that if the command is given is a relative path, it will be relative to this directory rather than the current directory of this process. Note also that the path is relative to the Note that support for the | ||||||||||||||||
| Chroot to this directory before executing the command. Note that the current directory will be changed to Note that support for the | ||||||||||||||||
| These parameters allows you to change the standard input, output
and error streams of the newly created process. This is
particularly useful in combination with | ||||||||||||||||
| |||||||||||||||||
| |||||||||||||||||
| This mapping will become the environment variables for the
created process. Normally you will want to only add or change
variables which can be achived by getting the environment mapping
for this process with | ||||||||||||||||
| This parameter changes which user the new process will execute as. Note that the current process must be running as UID 0 to use this option. The uid can be given either as an integer as a string containing the login name of that user. The "gid" and "groups" for the new process will be set to the right values for that user unless overriden by options below. (See | ||||||||||||||||
| This parameter changes the primary group for the new process.
When the new process creates files, they will will be created
with this group. The group can either be given as an int or a
string containing the name of the group. (See | ||||||||||||||||
| Set this to | ||||||||||||||||
| This parameter allows you to the set the list of groups that the new process belongs to. It is recommended that if you use this parameter you supply at least one and no more than 16 groups. (Some system only support up to 8...) The groups can be given as gids or as strings with the group names. | ||||||||||||||||
| This parameter overrides a behaviour of the "uid" parameter. If this parameter is used, the gid and groups of the new process will be inherited from the current process rather than changed to the approperiate values for that uid. | ||||||||||||||||
| This sets the priority of the new process, see
| ||||||||||||||||
| This sets the nice level of the new process; the lower the number, the higher the priority of the process. Note that only UID 0 may use negative numbers. | ||||||||||||||||
| This prevents Pike from restoring all signal handlers to their default values for the new process. Useful to ignore certain signals in the new process. | ||||||||||||||||
| This parameter allows you to map files to filedescriptors 3 and
up. The file | ||||||||||||||||
| There are two values for each limit, the soft limit and the hard
limit. Processes that do not have UID 0 may not raise the hard
limit, and the soft limit may never be increased over the hard
limit. The indices of the mapping indicate what limit to impose,
and the values dictate what the limit should be. (See also
| ||||||||||||||||
| Bind the process to the console associated with this pty slave. NT only. |
Process.create_process(({ "/usr/bin/env" }), (["env" : getenv() + (["TERM":"vt100"]) ]));
//! Spawn a new process with the args @[args] and optionally a //! standard input if you provide such a @[Stdio.File] object. //! @returns //! Returns the new process and a pipe from which you can read //! its output. array(Process.Process|Stdio.File) spawn(Stdio.File|void stdin, string ... args) { Stdio.File stdout = Stdio.File(); mapping opts = ([ "stdout" : stdout->pipe() ]); if( stdin ) opts->stdin = stdin; return ({ Process.create_process( args, opts ), stdout }); }
All parameters that accept both string or int input can be noticeably slower using a string instead of an integer; if maximum performance is an issue, please use integers.
On NT the only supported modifiers are: "cwd",
"conpty", "stdin", "stdout", "stderr"
and "env". All other modifiers are silently ignored.
Support for "callback" was added in Pike 7.7.
Chroot changing directory to "/" was added in Pike 7.9.
bool kill(int signal)
Send a signal to the process.
| Success. |
| Failure. |
This function is only available on platforms that support signals.
predef::kill()
int(0..) last_signal()
Returns the last signal that was sent to the process.
int pid()
Returns the process identifier of the process.
int set_priority(string priority)
Sets the priority of the process. priority is one of the strings
int(-1..2) status()
Returns the status of the process:
| Unknown |
| Running |
| Stopped |
| Exited |
int wait()
Waits for the process to end.
| The exit code of the process. |
| The process was killed by a signal. |
| The process is stopped. |
TraceProcess()->wait()
Implements NIST SP800-90Ar1 pseudo random number generator CTR_DRBG using AES-128.
https://csrc.nist.gov/publications/detail/sp/800-90a/rev-1/final
inherit Nettle.AES128_CTR_DRBG : AES128_CTR_DRBG
inherit Builtin.RandomInterface : RandomInterface
Random.AES128_CTR_DRBG Random.AES128_CTR_DRBG(string(8bit) entropy, void|string(8bit) personalization)
Instantiate a random generator without derivation function, with the given initial entropy and personalization.
protected void entropy_underflow()
This method is called when a reseed is forced. By default new entropy is gethered from Random.System. Overload to change the default behaviour.
This class implements a detministic random generator by combining
a Fortuna random generator with the Random.Interface. The
generator is not reseeded after the initial seed.
In case of a process fork the random generators in both processes will continue to generate identical results.
inherit Nettle.Fortuna : Fortuna
inherit Builtin.RandomInterface : RandomInterface
Random.Deterministic Random.Deterministic(string(8bit)|int seed)
Initialize the random generator with seed. The internal state is 256 bits, but all seed sizes are allowed.
This class implements a fast and secure random generator. The generator is a Fortuna PRNG that is fed additional entropy from the system RNG (or hardware RNG, if available) for every generated megabyte of data.
If a hardware RNG is present it will be used instead of Fortuna for random strings shorter than 48 bytes.
In case of a process fork it is possible that the random generators will produce identical results for up to one megabyte of generated data.
inherit Nettle.Fortuna : Fortuna
inherit Builtin.RandomInterface : RandomInterface
This class implements a random generator based on the hardware generator available on some system. Currently only supports Intel RDRAND CPU extension.
In case of a process fork the generators in the two processes will generate independent random values.
inherit Builtin.RandomInterface : RandomInterface
This class implements the Pike predef::random API on top of a
byte stream random source. This source should be implemented in
the random_string method and will be called by random(int) for
random input. random(int) is in turned called by all the other
variants of random and applied to their use cases.
While it is possible to overload the random variants, care must be taken to not introduce any bias. The default implementation gathers enough bits to completely reach the limit value, and discards them if the result overshoots the limit.
inherit Builtin.RandomInterface : RandomInterface
int(0..) random(int(0..) max)
float random(float max)
mixed random(array|multiset x)
array random(mapping m)
mixed random(object o)
Implementation of predef::random.
string(8bit) random_string(int length)
Prototype for the random source stream function. Must return
exactly length bytes of random data.
This is the default implementation of the random
functions. This is the Random.Interface combined with a system
random source. On Windows this is the default crypto service while
on Unix systems it is /dev/urandom.
In case of a process fork the generators in the two processes will generate independent random values.
inherit Builtin.RandomSystem : RandomSystem
inherit "___Regexp" : "___Regexp"
protected SimpleRegexp `()(void|string regexp)
Convenience/compatibility method to get a SimpleRegexp object.
bool match(string regexp, string data)
Calls Regexp.PCRE.Plain.match in a temporary regexp object.
Faster to type but slower to run...
string replace(string regexp, string data, string|function(string:string) transform)
Calls Regexp.PCRE.Plain.replace in a temporary regexp object.
Faster to type but slower to run...
array split(string regexp, string data)
Calls Regexp.PCRE.Plain.split in a temporary regexp object.
Faster to type but slower to run...
array split2(string regexp, string data)
Calls Regexp.PCRE.Plain.split2 in a temporary regexp object.
Faster to type but slower to run...
This class implements the interface to a simple regexp engine with the following capabilities:
| . | Matches any character. |
| [abc] | Matches a, b or c. |
| [a-z] | Matches any character a to z inclusive. |
| [^ac] | Matches any character except a and c. |
| (x) | Matches x (x might be any regexp) If used with split, this also puts the string matching x into the result array. |
| x* | Matches zero or more occurances of 'x' (x may be any regexp). |
| x+ | Matches one or more occurances of 'x' (x may be any regexp). |
| x|y | Matches x or y. (x or y may be any regexp). |
| xy | Matches xy (x and y may be any regexp). |
| ^ | Matches beginning of string (but no characters). |
| $ | Matches end of string (but no characters). |
| \< | Matches the beginning of a word (but no characters). |
| \> | Matches the end of a word (but no characters). |
Note that \ can be used to quote these characters in which case they match themselves, nothing else. Also note that when quoting these something in Pike you need two \ because Pike also uses this character for quoting.
inherit _SimpleRegexp : _SimpleRegexp
string(8bit) encode_value(Regexp.SimpleRegexp data)
Regexp.SimpleRegexp decode_value(string(8bit) data)
Regexp objects can be encoded and decoded.
encode_value, decode_value
Regexp.SimpleRegexp Regexp.SimpleRegexp(string re)
When create is called, the current regexp bound to this object is
cleared. If a string is sent to create(), this string will be compiled
to an internal representation of the regexp and bound to this object
for laters calls to e.g. match or split. Calling create() without
an argument can be used to free up a little memory after the regexp has
been used.
int match(string str)
Returns 1 if str matches the regexp bound to the regexp object.
Zero otherwise.
array(string) match(array(string) strs)
Returns an array containing strings in strs that match the
regexp bound to the regexp object.
The current implementation doesn't support searching in strings containing the NUL character or any wide character.
split
string replace(string in, string|function(string:string) transform)
array(string) split(string s)
Works as match, but returns an array of the strings that
matched the subregexps. Subregexps are those contained in "( )" in
the regexp. Subregexps that were not matched will contain zero.
If the total regexp didn't match, zero is returned.
You can currently only have 39 subregexps.
The current implementation doesn't support searching in strings containing the NUL character or any wide character.
match
inherit "____Regexp_PCRE" : "____Regexp_PCRE"
constant Regexp.PCRE.buildconfig_LINK_SIZE
(from the pcreapi man-page) "The output is an integer that contains the number of bytes used for internal linkage in compiled regular expressions. The value is 2, 3, or 4. Larger values allow larger regular expressions to be compiled, at the expense of slower match- ing. The default value of 2 is sufficient for all but the most massive patterns, since it allows the compiled pattern to be up to 64K in size." This constant is calculated when the module is initiated by using pcre_config(3).
constant Regexp.PCRE.buildconfig_MATCH_LIMIT
(from the pcreapi man-page) "The output is an integer that gives the default limit for the number of internal matching function calls in a pcre_exec() execution. Further details are given with pcre_exec() below." This constant is calculated when the module is initiated by using pcre_config(3).
constant Regexp.PCRE.buildconfig_NEWLINE
(from the pcreapi man-page) "The output is an integer that is set to the value of the code that is used for the newline character. It is either linefeed (10) or carriage return (13), and should normally be the standard character for your operating system." This constant is calculated when the module is initiated by using pcre_config(3).
constant Regexp.PCRE.buildconfig_POSIX_MALLOC_THRESHOLD
(from the pcreapi man-page) "The output is an integer that contains the threshold above which the POSIX interface uses malloc() for output vectors. Further details are given in the pcreposix documentation." This constant is calculated when the module is initiated by using pcre_config(3).
constant Regexp.PCRE.buildconfig_UTF8
(from the pcreapi man-page) "The output is an integer that is set to one if UTF-8 support is available; otherwise it is set to zero." This constant is calculated when the module is initiated by using pcre_config(3).
StudiedWidestring `()(string pattern, void|int options, void|object table)
Convenience function to create a suitable PCRE Regexp object; will create a StudiedWidestring from the arguments.
That means the result will be able to handle widestrings, and will produce fast matchings by studying the pattern, but the widestring wrapping will on the other hand add overhead.
If you need a faster regexp and doesn't use widestring, create a Regexp.PCRE.Studied instead.
Widestring support will not be used if the linked libpcre lacks UTF8 support. This can be tested with checking that the Regexp.PCRE.Widestring class exist.
array(string) split_subject(string subject, array(int) previous_result)
Convenience function that splits a subject string on the result from _pcre->exec()
equal to map(previous_result/2, lambda(array v) { return subject[v[0]..v[1]-1]; })
The main regexp class. Will provide anything needed for matching regexps.
There are subclasses that adds wrappers for widestrings, and to optimize the regexp pattern.
inherit _pcre : _pcre
bool match(string subject, void|int startoffset)
returns true (1) if a match is found, false otherwise
example:
> Regexp.PCRE.Plain("is fun")->match("pike is fun");
Result: 1
> Regexp.PCRE.Plain("is fun")->match("pike isn't fun");
Result: 0
this_program matchall(string subject, function(array(string)|void, array(int)|void:mixed|void) callback)
Will give a callback for each match in a subject. Called arguments will be matching patterns and subpatterns in an array and as second argument the exec result array.
returns called object
example:
> Regexp.PCRE("b(a*)([^-\1234]*)(\1234*)m")
->matchall("abam-boom-fooabado\1234m",
lambda(mixed s) { werror("%O\n",s); return "gurka"; });
({ /* 4 elements */
"bam",
"a",
"",
""
})
({ /* 4 elements */
"boom",
"",
"oo",
""
})
({ /* 4 elements */
"bado\1234m",
"a",
"do",
"\1234"
})
Result: Regexp.PCRE.StudiedWidestring("b(a*)([^-Ê\234]*)(Ê\234*)m")
string replace(string subject, string|function(:void) with, mixed ... args)
replace all occurances of a pattern in a subject; callbacks and replacements will be from the first occurance, not from the last as in Regexp.Builtin.replace.
if with is a function, the first argument will be the total match string, and the subsequent arguments will contain any submatches
example:
> Regexp.PCRE("b[^-]*m")->replace("abam-boom-fooabadoom","gurka");
Result: "agurka-gurka-fooagurka"
> Regexp.PCRE("b[^-]*m")->replace("abam-boom-fooabadoom",
lambda(string s) { werror("%O\n",s); return "gurka"; });
"bam"
"boom"
"badoom"
Result: "agurka-gurka-fooagurka"
example:
> Regexp.PCRE("([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})")
->replace("foo@bar.org",
lambda(string whole, string user, string loc, string domain)
{ return user + " from " + loc + " dot " + domain; }
);
(4) Result: "foo from bar dot org"
string replace1(string subject, string|function(string:string) with)
replace one (first) occurance of a pattern in a subject
example:
> Regexp.PCRE("b[^-]*m")->replace1("abam-boom-fooabadoom","gurka");
Result: "agurka-boom-fooabadoom"
string replace_positional(string subject, string subst)
replaces matches in a string, with support for backreferences (matched groups)
subjectthe string to be tested against the regular expression
subststring to be inserted in place of each match. backreferences can be inserted into the string to be substituted using the syntax %[n]s where n is the nth matching string group, and 0 (zero) is the full match.
example:
> Regexp.PCRE.Plain("my name is ([a-zA-Z]+)")
->replace_positional("allow me to introduce myself: my name is john",
"%[0]s is my name");
(1) Result: "allow me to introduce myself: john is my name"
array(string)|int(0) split(string subject, void|int startoffset)
Matches a subject against the pattern, compatible with the old split method: returns an array of the subpatterns, or if there are no subpattern but still a match, ({0}). Returns 0 if there was no match.
example:
> Regexp.PCRE.Plain("i\(.*\) is \(.*\)u")->split("pike is fun");
(1) Result: ({
"ke",
"f"
})
> Regexp.PCRE.Plain("is fun")->split("pike is fun");
(4) Result: ({
0
})
array(string)|int(0) split2(string subject, void|int startoffset)
Matches a subject against the pattern, returns an array where the first element are the whole match, and the subsequent are the matching subpatterns. Returns 0 if there was no match.
example:
> Regexp.PCRE.Plain("i\(.*\) is \(.*\)u")->split2("pike is fun");
Result: ({
"ike is fu",
"ke",
"f"
})
Same as Plain, but will be studied to match faster; useful if you're doing many matches on the same pattern
inherit Plain : Plain
Same as Widestring, but will be studied to match faster; useful if you're doing many matches on the same pattern
inherit Widestring : Widestring
Wrapper class around Plain, that will allow widestring patterns and subjects.
Widestring support and this class will not be implemented if the linked libpcre lacks UTF8 support.
inherit Plain : Plain
array(int)|int exec(string subject, void|int startoffset)
The exec function is wrapped to give the correct indexes for the widestring.
string sprintf(string format, ... Regexp.PCRE._pcre arg ... )
Regexp.PCRE._pcre Regexp.PCRE._pcre(string pattern, void|int options, void|object table)
The option bits are:
| Force pattern anchoring |
| Do caseless matching |
| $ not to match newline at end |
| . matches anything including NL |
| Ignore whitespace and # comments |
| PCRE extra features (not much use currently) |
| ^ and $ match newlines within data |
| Disable numbered capturing parentheses (named ones available) |
| Invert greediness of quantifiers |
| Run in UTF-8 mode |
int|array exec(string subject, void|int startoffset)
Matches the regexp against subject, starting at
startoffset if it is given.
If the match is successful, the return value is an array that holds the offsets of all matches:
Elements 0 and 1 have the start and end offsets, respectively,
of the match for the whole regexp. The start offset is
inclusive while the end is exclusive, i.e. the matching string
is .subject[res[0]..res[1]-1]
Elements 2 and 3 have the offsets of the first capturing submatch (if any) in the same way, elements 4 and 5 are for the second capturing submatch, etc. If a submatch didn't match anything, the corresponding elements are set to -1. If a submatch has matched successfully several times, the offsets of the last match are returned.
The returned array is always of length 2*n + 1, where n is the total number of capturing submatches in the regexp.
If there is an error, an integer error code is returned:
| The subject string did not match the pattern. |
| Either code or subject was passed as NULL, or ovector was NULL and oversize was not zero. |
| An unrecognized bit was set in the options argument. |
| PCRE stores a 4-byte "magic number" at the start of the compiled code, to catch the case when it is passed a junk pointer. This is the error it gives when the magic number isn't present. |
| While running the pattern match, an unknown item was encountered in the compiled pattern. This error could be caused by a bug in PCRE or by overwriting of the compiled pattern. |
| If a pattern contains back references, but the ovector that is passed to pcre_exec() is not big enough to remember the referenced substrings, PCRE gets a block of memory at the start of matching to use for this purpose. If the call via pcre_malloc() fails, this error is given. The memory is freed at the end of matching. |
| This error is used by the pcre_copy_substring(), pcre_get_substring(), and pcre_get_substring_list() functions (see below). It is never returned by pcre_exec(). |
| The recursion and backtracking limit, as specified by the match_limit field in a pcre_extra structure (or defaulted) was reached. See the description above. |
| This error is never generated by pcre_exec() itself. It is provided for use by callout functions that want to yield a distinctive error code. See the pcrecallout documentation for details. |
int get_stringnumber(string stringname)
returns the number of a named subpattern
mapping info()
Returns additional information about a compiled pattern. Only available if PCRE was compiled with Fullinfo.
| Return the number of the highest back reference in the pattern. The fourth argument should point to an int variable. Zero is returned if there are no back references. | ||||||||
| Return the number of capturing subpatterns in the pattern. The fourth argument should point to an int variable. | ||||||||
| Return information about the first byte of any matched string, for a non-anchored pattern. (This option used to be called PCRE_INFO_FIRSTCHAR; the old name is still recognized for backwards compatibility.) If there is a fixed first byte, e.g. from a pattern such as (cat|cow|coyote), it is returned in the integer pointed to by where. Otherwise, if either (a) the pattern was compiled with the PCRE_MULTILINE
option, and every branch starts with (b) every branch of the pattern starts with | ||||||||
| Return the value of the rightmost literal byte that must
exist in any matched string, other than at its start, if
such a byte has been recorded. The fourth argument should
point to an int variable. If there is no such byte,
| ||||||||
| |||||||||
| |||||||||
| Return a copy of the options with which the pattern was compiled. The fourth argument should point to an unsigned long int variable. These option bits are those specified in the call to pcre_compile(), modified by any top-level option settings within the pattern itself. A pattern is automatically anchored by PCRE if all of its top-level alternatives begin with one of the following:
For such patterns, the PCRE_ANCHORED bit is set in the options returned. | ||||||||
| Return the size of the compiled pattern, that is, the value that was passed as the argument to pcre_malloc() when PCRE was getting memory in which to place the compiled data. The fourth argument should point to a size_t variable. | ||||||||
| Returns the size of the data block pointed to by the study_data field in a pcre_extra block. That is, it is the value that was passed to pcre_malloc() when PCRE was getting memory into which to place the data created by pcre_study(). The fourth argument should point to a size_t variable. |
object study()
(from the pcreapi man-page) "When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for match- ing."
constant Regexp.PCRE.ERROR.NOMATCH
constant Regexp.PCRE.ERROR.NULL
constant Regexp.PCRE.ERROR.BADOPTION
constant Regexp.PCRE.ERROR.BADMAGIC
constant Regexp.PCRE.ERROR.UNKNOWN_NODE
constant Regexp.PCRE.ERROR.NOMEMORY
constant Regexp.PCRE.ERROR.NOSUBSTRING
constant Regexp.PCRE.ERROR.MATCHLIMIT
constant Regexp.PCRE.ERROR.CALLOUT
Documented in exec.
contains all option constants
constant Regexp.PCRE.OPTION.ANCHORED
(from the pcreapi manpage) If this bit is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the first matching point in the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.
constant Regexp.PCRE.OPTION.CASELESS
(from the pcreapi manpage) If this bit is set, letters in the pattern match both upper and lower case letters. It is equivalent to Perl's /i option, and it can be changed within a pattern by a (?i) option setting.
constant Regexp.PCRE.OPTION.DOLLAR_ENDONLY
(from the pcreapi manpage) If this bit is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this option, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set. There is no equivalent to this option in Perl, and no way to set it within a pattern.
constant Regexp.PCRE.OPTION.DOTALL
(from the pcreapi manpage) If this bit is set, a dot metacharater in the pattern matches all characters, including newlines. Without it, newlines are excluded. This option is equivalent to Perl's /s option, and it can be changed within a pattern by a (?s) option setting. A negative class such as [^a] always matches a newline character, independent of the setting of this option.
constant Regexp.PCRE.OPTION.EXTENDED
(from the pcreapi manpage) If this bit is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class. Whitespace does not include the VT character (code 11). In addition, characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x option, and it can be changed within a pattern by a (?x) option setting.
This option makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.
constant Regexp.PCRE.OPTION.EXTRA
(from the pcreapi manpage) This option was invented in order to turn on additional functionality of PCRE that is incompatible with Perl, but it is currently of very little use. When set, any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this option. It can also be set by a (?X) option setting within a pattern.
constant Regexp.PCRE.OPTION.MULTILINE
(from the pcreapi manpage) By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless PCRE_DOL- LAR_ENDONLY is set). This is the same as Perl.
When PCRE_MULTILINE it is set, the "start of line" and "end of line" constructs match immediately following or immediately before any new- line in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m option, and it can be changed within a pattern by a (?m) option setting. If there are no "\n" charac- ters in a subject string, or no occurrences of ^ or $ in a pattern, setting PCRE_MULTILINE has no effect.
constant Regexp.PCRE.OPTION.NO_AUTO_CAPTURE
(from the pcreapi manpage) If this option is set, it disables the use of numbered capturing paren- theses in the pattern. Any opening parenthesis that is not followed by ? behaves as if it were followed by ?: but named parentheses can still be used for capturing (and they acquire numbers in the usual way). There is no equivalent of this option in Perl.
constant Regexp.PCRE.OPTION.UNGREEDY
(from the pcreapi manpage) This option inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) option setting within the pattern.
constant Regexp.PCRE.OPTION.UTF8
(from the pcreapi manpage) This option causes PCRE to regard both the pattern and the subject as strings of UTF-8 characters instead of single-byte character strings. However, it is available only if PCRE has been built to include UTF-8 support. If not, the use of this option provokes an error. Details of how this option changes the behaviour of PCRE are given in the section on UTF-8 support in the main pcre page.
Remote RPC system.
Wrapper for a remote function.
mixed res = Remote.Call()()
Call the wrapped function.
argsArguments to pass to the wrapped function.
This function can operate in two modes depending
on whether asynchronous mode has been activated
or not. If it has it is equivalent to a call of
async() and if not of sync() with the same
arguments.
async(), sync(), is_async(), set_async()
void async(mixed ... args)
Call the wrapped remote function asynchronously.
argsArguments to send to the remote function.
sync(), `()()
Remote.Call Remote.Call(string|zero objectid, string name, object connection, object context, int async)
int exists()
Check whether the wrapped function actually exists at the other end.
int is_async()
Whether asynchronous mode is active or not.
set_async()
void set_async(int a)
Change to/from asynchronous mode.
is_async()
mixed sync(mixed ... args)
Call the wrapped remote function synchronously.
argsArguments to send to the remote function.
Returns (the possibly wrapped) result from the remote function.
async(), `()()
Remote RPC Client.
Remote.Connection Remote.Client.con
Connection to the Remote.Server.
void close()
Close the connection.
int closed()
Check if the connection is closed.
Remote.Client Remote.Client(string host, int port, void|int nice, void|int timeout, void|int max_call_threads)
Connect to a Remote.Server.
hostportHostname and port for the Remote.Server.
niceIf set, inhibits throwing of errors from call_sync().
timeoutConnection timeout in seconds.
max_call_threadsMaximum number of concurrent threads.
object get(string name)
Get a named object from the remote server.
void provide(string name, mixed thing)
Provide a named thing to the Remote.Server.
nameName to provide thing under.
thingThing to provide.
void set_close_callback(function(:void) f)
Set the callback to call when the connection is closed.
void add_close_callback(function(:void) f, mixed ... args)
Add a function that is called when the connection is closed.
void call_async(array data)
Make a call but don't wait for the result
mixed call_sync(array data)
Make a call and wait for the result
void close()
Closes the connection nicely, after waiting in outstanding calls in both directions.
int connect(string host, int port, void|int timeout)
This function is called by clients to connect to a server.
Remote.Connection Remote.Connection(void|int nice, void|int max_call_threads)
niceIf set, no errors will be thrown.
string|zero error_message()
Returns an error message for the last error, in case connect
returns zero. Returns zero if the last connect call was
successful.
object get_named_object(string name)
Get a named object provided by the server.
void remove_close_callback(array f)
Remove a function that is called when the connection is closed.
void start_server(object c, object cx)
This function is called by servers when they have got a connection from a client. The first argument is the connection file object, and the second argument is the context to be used.
Remote context tracker.
This class keeps track of what local things correspond to what remote things, and the reverse.
void add(object o, string id)
Remote.Context Remote.Context(string b, object|void cn)
mixed decode(array a)
function(:void)|object decode_call(array data)
int decode_existp(array data)
string describe(array data)
array encode(mixed val)
array encode_call(object|string o, string|function(:void) f, array args, int type)
object function_for(string id)
string id_for(mixed thing)
object|zero object_for(string id)
void set_server_context(object ctx, object cn)
Wrapper for a remote object.
mixed res = Remote.Obj()->X
mixed res = Remote.Obj()[ f ]
Remote.Obj Remote.Obj(string id, object connection, object context)
int exists()
mixed get_function(string f)
Remote RPC server.
array(Connection) Remote.Server.connections
Open connections.
Stdio.Port Remote.Server.port
Port for the Remote.Server.
Minicontext Remote.Server.sctx
Server context.
void close()
Shut down the Remote.Server for new connections.
void close_all()
Shut down the Remote.Server and terminate all current clients.
int closed()
Check if the Remote.Server is closed.
Remote.Server Remote.Server(string host, int port, void|int max_call_threads)
Create a Remote.Server.
hostportHostname and port for the Remote.Server.
max_call_threadsMaximum number of concurrent threads.
void provide(string name, mixed thing)
Provide a named thing to the Remote.Client(s).
nameName to provide thing under.
thingThing to provide.
The server Context class.
This module enables access to the SANE (Scanner Access Now Easy) library from pike
constant SANE.FrameGray
constant SANE.FrameRGB
constant SANE.FrameRed
constant SANE.FrameGreen
constant SANE.FrameBlue
array(mapping) list_scanners()
Returns an array with all available scanners.
Pike v0.7 release 120 running Hilfe v2.0 (Incremental Pike Frontend) > SANE.list_scanners(); Result: ({ ([ "model":"Astra 1220S ", "name":"umax:/dev/scg1f", "type":"flatbed scanner", "vendor":"UMAX " ]), ([ "model":"Astra 1220S ", "name":"net:lain.idonex.se:umax:/dev/scg1f", "type":"flatbed scanner", "vendor":"UMAX " ]) })
void cancel_scan()
SANE.Scanner SANE.Scanner(string name)
mixed get_option(string name)
mapping(string:int) get_parameters()
|
|
|
|
|
|
array(mapping) list_options()
This method returns an array where every element is a mapping, layed out as follows.
| |||||||||||||||||
| |||||||||||||||||
| |||||||||||||||||
|
| ||||||||||||||||
|
| ||||||||||||||||
| |||||||||||||||||
|
| ||||||||||||||||
| Constraints can be of three different types; range, word list or string list. Constraint contains 0 if there are no constraints.
|
void nonblocking_row_scan(function(Image.Image, int, Scanner, int:void) callback)
void row_scan(function(Image.Image, int, Scanner:void) callback)
void set_option(string name, mixed new_value)
void set_option(string name)
If no value is specified, the option is set to it's default value
Image.Image simple_scan()
SDL or Simple DirectMedia Layer is a cross-platform multimedia library designed to provide fast access to the graphics framebuffer, audio device, input and other devices. This module implements a wrapper for SDL and other relevant libraries like SDL_mixer. The interface is similar to the C one, but using generally accepted Pike syntax.
This means that classes are used when appropriate and that method
names use all lowercase letters with words separated by _. For
example SDL_SetVideoMode is named SDL.set_video_mode. Also note
that unless otherwise noted, errors result in an error being
thrown rather than returning -1 or 0, as commonly
done in SDL methods.
int blit_surface(SDL.Surface src, SDL.Surface dst, SDL.Rect|void srcrect, SDL.Rect|void dstrect)
Peforms a fast blit from the source surface to the destination surface.
The final blit rectangle is stored in dstrect. This may differ from srcrect if there was clipping.
This function should not be called on a locked surface.
srcThe surface to be copied.
dstThe destination surface. This will usually be your main screen,
initialized with a call to SDL.set_video_mode().
srcrectThe rectangular section of src to copy. If the whole surface is to be copied, you can set this to 0.
dstrectWhere the source surface should be copied to on the destination surface.
Only the x and y fields of the SDL.Rect object are used.
To copy src to the top-left corner of dst, i.e. at coordinates
<0,0>, you can set this to 0.
If successful, 0, otherwise -1.
SDL.Surface()->blit()
string|void cd_name(int drive)
Returns a human-readable and system-dependent name for the given drive.
driveThe CD drive index.
A human-readable and system-dependent name for the given drive,
or 0 if no name is available.
SDL.cd_num_drives()
int cd_num_drives()
The number of CD-ROM drives on the system.
SDL.cd_name()
int enable_unicode(int enable)
Enables/Disables UNICODE keyboard translation.
If you wish to translate a keysym to its printable
representation, you need to enable UNICODE translation using this
function and then look in the unicode member of the
SDL.Keysym class. This value will be zero for keysyms that do
not have a printable representation. UNICODE translation is
disabled by default as the conversion can cause a slight
overhead.
enableA value of 1 enables Unicode translation, 0 disables
it and -1 leaves it unchanged (useful for querying the current
translation mode).
The previous translation mode (1 enabled, 0 disabled).
If enable is -1, the return value is the current translation
mode.
SDL.Keysym
int flip(SDL.Surface|void screen)
On hardware that supports double-buffering, this function
sets up a flip and returns. The hardware will wait for
vertical retrace, and then swap video buffers before the
next video surface blit or lock will return. On hardware
that doesn't support double-buffering, this is equivalent
to calling SDL.update_rect(screen, 0, 0, 0, 0)
The SDL.DOUBLEBUF flag must have been passed to
SDL.set_video_mode() when setting the video mode for this
function to perform hardware flipping.
screenThe screen object to flip. If missing, the default screen is used.
This function returns 1 if successful, or 0 if there was an error.
SDL.update_rect()
array(string) get_caption()
A 2-element array holding the window title and icon name.
SDL.set_caption()
string|zero get_error()
Get the last internal SDL error.
The error string, or zero if there was no error.
string get_key_state()
Gets a snapshot of the current keyboard state.
The current state is returned as a string.
The string is indexed by the SDL.K_* symbols.
A value of 1 means the key is pressed and
a value of 0 means it's not.
Call SDL.pump_events() to update the state array.
SDL.get_mod_state(), SDL.pump_events()
// Test if the 'Escape' key is pressed. SDL.pump_events(); string ks = SDL.get_key_state(); if ( ks[SDL.K_ESCAPE] ) { // handle key press...
int get_mod_state()
Returns the current state of the modifier keys (CTRL, ALT, etc.).
The return value can be an OR'd combination of the following: SDL.KMOD_NONE, SDL.KMOD_LSHIFT, SDL.KMOD_RSHIFT, SDL.KMOD_LCTRL, SDL.KMOD_RCTRL, SDL.KMOD_LALT, SDL.KMOD_RALT, SDL.KMOD_LMETA, SDL.KMOD_RMETA, SDL.KMOD_NUM, SDL.KMOD_CAPS, and SDL.KMOD_MODE.
For convenience, the following are also defined: SDL.KMOD_CTRL, SDL.KMOD_SHIFT, SDL.KMOD_ALT and SDL.KMOD_META
SDL.get_key_state(), SDL.pump_events()
object get_video_info()
Returns an SDL.VideoInfo object, which holds information about the video
hardware, or 0 if the video device has not yet been initialized (with a
call to SDL.init()).
object get_video_surface()
Returns the current display surface.
If SDL is doing format conversion on the display surface, this method returns the publicly visible surface, not the real video surface.
The current display surface, or 0 if there is no display surface.
SDL.set_video_mode()
int gl_get_attribute(int attribute)
Returns the value of the given SDL/OpenGL attribute. You might want
to call this after SDL.set_video_mode() to check that attributes
have been set as you expected.
attributeThe SDL/OpenGL attribute to query.
The value of the given attribute.
// Has double-buffering been set? int db = SDL.gl_get_attribute( SDL.GL_DOUBLEBUFFER ); if ( db ) { // yes...
void gl_set_attribute(int attribute, int value)
Sets an SDL/OpenGL attribute to the given value.
This won't take effect until after a call to SDL.set_video_mode().
attributeThe attribute to set. This will be one of SDL.GL_RED_SIZE,
SDL.GL_GREEN_SIZE, SDL.GL_BLUE_SIZE,
SDL.GL_DEPTH_SIZE or SDL.GL_DOUBLEBUFFER.
valueThe value to set for this attribute.
SDL.gl_get_attribute()
void gl_swap_buffers()
Swaps the OpenGL buffers on a double-buffered screen.
SDL.gl_set_attribute(), SDL.gl_get_attribute(),
SDL.set_video_mode()
int grab_input(int mode)
Sets or queries the current 'grab' mode.
Grabbing input means asking that all mouse activity be confined to this application window and that nearly all keyboard events are passed directly to the application, bypassing the window manager.
modeOne of the following constants:
SDL.GRAB_ON
SDL.GRAB_OFF
SDL.GRAB_QUERY
The current grab mode, either SDL.GRAB_ON or SDL.GRAB_OFF.
int iconify_window()
Attempts to iconify (i.e. minimize) the application window.
If the call is successful, the application will receive an
SDL.APPACTIVE loss event.
Non-zero if successful, otherwise 0.
void init(int flags)
Initializes SDL. This should be called before all other SDL functions.
flagsThe flags parameter specifies what part(s) of SDL to initialize. It can be one of many of the following ORed together.
Initializes the timer subsystem.
Initializes the audio subsystem.
Initializes the video subsystem.
Initializes the cdrom subsystem.
Initializes the joystick subsystem.
Initialize all of the above.
Prevents SDL from catching fatal signals.
Run event polling in a separate thread. Not always supported.
SDL.quit(), SDL.init_sub_system(), SDL.quit_sub_system()
void init_sub_system(int flags)
After SDL has been initialized with SDL.init() you may initialize
uninitialized subsystems with this method.
flagsThe same as what is used in SDL.init().
SDL.init(), SDL.quit(), SDL.quit_sub_system()
int joystick_event_state(int state)
Enables, disables or queries the state of joystick event processing.
stateOne of the following constants:
SDL.ENABLE
Enables joystick event processing.
SDL.IGNORE
Disables joystick event processing.
SDL.QUERY
Queries the current state and returns it.
The current state of joystick event processing. If state was
SDL.ENABLE or SDL.IGNORE, then processing will now be enabled
or disabled, respectively.
string joystick_name(int device_index)
Returns the implementation-dependent name of the nth joystick device available to the system.
device_indexThe nth joystick device.
The implementation-dependent name of the given joystick device.
SDL.Joystick->name()
int joystick_opened(int device_index)
Determines whether the given joystick device has already been opened.
device_indexThe nth joystick device.
1 if this device has already been opened, otherwise 0.
void joystick_update()
Updates the state of all open joysticks attached to the system.
int num_joysticks()
The number of joysticks available to the system.
SDL.Joystick
void open_audio(int frequency, int format, int channels, int bufsize)
Initializes the audio API.
Throws an exception if audio can't be initialized.
frequencyOutput sampling frequency, measured in samples per second (Hz).
A value of 44100 provides CD-quality playback.
A less CPU-intensive value for games is 22050.
formatOutput sample format. One of the following constants:
Unsigned 8-bit samples.
Signed 8-bit samples.
Unsigned 16-bit samples in little-endian byte order.
Signed 16-bit samples in little-endian byte order.
Unsigned 16-bit samples in big-endian byte order.
Signed 16-bit samples in big-endian byte order.
Same as SDL.AUDIO_U16LSB.
Same as SDL.AUDIO_S16LSB.
Unsigned 16-bit samples in system byte order.
Signed 16-bit samples in system byte order. If in doubt, try this one first.
channelsNumber of sound channels in output: 1 for mono,
2 for stereo.
bufsizeHow many bytes to use per output sample.
1024 is a typical value for games. If just playing
music you might set this to 4096 or higher.
void pump_events()
Pumps the event loop, gathering events from the input devices.
Normally you won't need to call this method, as it's called implicitly
by SDL.Event->poll().
get_key_state(), get_mod_state()
void quit()
Shuts down all SDL subsystems and frees the resources allocated to them. This should always be called before you exit.
You can use the atexit() method to ensure that this method is always
called when Pike exits normally.
SDL.init(), SDL.init_sub_system(), SDL.quit_sub_system()
void quit_sub_system(int flags)
After an SDL subsystem has been initialized with SDL.init() or
SDL.init_sub_system(), it may be shut down with this method.
flagsA bitwise OR'd combination of the subsystems
you wish to shut down (see SDL.init() for a list of subsystem flags).
SDL.init(), SDL.init_sub_system(), SDL.quit()
void set_caption(string title, string icon)
Sets the window's title and icon name. Icon name refers to the text that appears next to the application's icon in its minimized window.
titleThe window's title.
iconThe minimized window's icon name.
SDL.get_caption()
int set_gamma(float red, float green, float blue)
Document this function
object set_video_mode(int width, int height, int bpp, int flags)
Sets up a video mode with the specified width, height and bits per pixel.
widthThe desired width. Setting this to <= 0 results in an SDL error.
heightThe desired height. Setting this to <= 0 results in an SDL error.
bppThe bits per pixel. This should be either 0, 8, 16, 24 or 32. If you set this to 0, the bits-per-pixel value of the current display will be used.
flagsAn OR'd combination of the desired SDL.Surface flags.
The framebuffer surface. An error is thrown if the video mode can't be set.
SDL.Surface, SDL.video_mode_ok()
int show_cursor(int show)
Sets the state of the mouse cursor on the SDL screen (visible or hidden), or queries its current state.
By default, the cursor is visible.
showOne of these constants:
Show the cursor.
Hide the cursor.
Determine the current state of the cursor.
The current state of the mouse cursor, either SDL.ENABLE or
SDL.DISABLE.
int toggle_fullscreen(void|SDL.Surface screen)
Toggles the application between windowed and fullscreen mode, if supported. X11 is the only target currently supported.
screenThe framebuffer surface, as returned by SDL.set_video_mode().
Returns 1 on success or 0 on failure.
void update_rect(int x, int y, int w, int h, SDL.Surface|void screen)
Makes sure the given area is updated on the given screen. The rectangle must be confined within the screen boundaries (no clipping is done).
If 'x', 'y', 'w' and 'h' are all 0, SDL.update_rect() will update
the entire screen.
This function should not be called while screen is locked.
xyTop left corner of the rectangle to update.
whWidth and height of the rectangle to update.
screenThe screen object to flip. If missing, the default screen is used.
SDL.flip()
string video_driver_name()
Obtains the name of the video driver. This is a simple one-word identifier such as 'x11' or 'windib'.
The name of the video driver, or 0 if video has not yet been initialized
(with a call to SDL.init()).
int video_mode_ok(int width, int height, int bpp, int flags)
Checks to see if a particular video mode is supported.
Returns 0 if the requested mode isn't supported under any bit depth, or the
bits-per-pixel of the closest available mode with the given width, height
and SDL.Surface flags.
SDL.Surface, SDL.set_video_mode(), SDL.get_video_info()
void warp_mouse(int xpos, int ypos)
Sets the position of the mouse cursor to the given coordinates. This generates an SDL.MOUSEMOTION event.
xposRequested position of the mouse cursor along the x-axis.
yposRequested position of the mouse cursor along the y-axis.
int was_init(int flags)
This method allows you to see which SDL subsytems have been initialized.
flagsA bitwise OR'd combination of the subsystems
you wish to check (see SDL.init() for a list of subsystem flags).
A bitwised OR'd combination of the initialized subsystems
SDL.init(), SDL.init_sub_system()
int SDL.CD.current_frame
Document this variable
int SDL.CD.current_track
Document this variable
int SDL.CD.id
Document this variable
int SDL.CD.numtracks
Document this variable
SDL.CD SDL.CD(int drive)
Document this function
int eject()
Document this function
int pause()
Document this function
int play(int start, int length)
Document this function
int play_tracks(int start_track, int start_frame, int ntracks, int nframes)
Document this function
int resume()
Document this function
int status()
Document this function
int stop()
Document this function
CDTrack track(int track)
Document this function
int SDL.CDTrack.id
int SDL.CDTrack.length
int SDL.CDTrack.offset
int SDL.CDTrack.type
Document this variable
int SDL.Event.axis
int SDL.Event.ball
int SDL.Event.button
int SDL.Event.code
int SDL.Event.gain
int SDL.Event.h
int SDL.Event.hat
Keysym SDL.Event.keysym
int SDL.Event.state
int SDL.Event.type
int SDL.Event.value
int SDL.Event.w
int SDL.Event.which
int SDL.Event.x
int SDL.Event.xrel
int SDL.Event.y
int SDL.Event.yrel
int get()
Removes the next event (if any) from the queue and stores it in this
SDL.Event object.
1 if there was an event to 'get', otherwise 0.
int poll()
Polls for currently pending events.
1 if there are currently pending events, otherwise 0.
int wait()
Waits indefinitely for the next available event, which is then removed
from the queue and stored in this SDL.Event object.
Returns 1 on success, or 0 if there was an error while waiting for the next event.
Represents a joystick, gamepad or other similar input device attached to the system.
You must call SDL.init() with the SDL.INIT_JOYSTICK flag to
enable joystick support.
All index numbers count from 0.
All SDL.Joystick methods throw an exception if they are called on
an uninitialized object.
SDL.Joystick SDL.Joystick(int device_index)
Opens the given joystick device for use.
device_indexThe nth joystick device available to the system.
SDL.num_joysticks()
float get_axis(int axis)
Returns the current position of the given axis.
The returned value is a float between -1.0 and 1.0.
axisThe axis index.
The current position of the given axis.
num_axes()
array(int) get_ball(int ball)
Returns the axis change of the given trackball.
This is its relative motion along both axes since the last call to
get_ball(). It is returned as a 2-element array holding the values
of dx and dy (- the motion deltas).
The axis change of the given trackball.
num_balls()
int get_button(int button)
Returns the current state of the given button.
This is 1 if the button is pressed, otherwise 0.
buttonThe button index.
The current state of the given button.
num_buttons()
int get_hat(int hat)
Returns the current state of the given hat.
This is represented as an OR'd combination of one or more of the following constants:
SDL.HAT_CENTERED
SDL.HAT_UP
SDL.HAT_RIGHT
SDL.HAT_DOWN
SDL.HAT_LEFT
SDL.HAT_RIGHTUP
SDL.HAT_RIGHTDOWN
SDL.HAT_LEFTUP
SDL.HAT_LEFTDOWN
hatThe hat index.
The current state of the given hat.
num_hats()
int index()
The index of this joystick.
string name()
The implementation-dependent name of this joystick.
SDL.joystick_name()
int num_axes()
The number of axes available for this joystick.
int num_balls()
The number of trackballs available for this joystick.
int num_buttons()
The number of buttons available for this joystick.
int num_hats()
The number of hats available for this joystick.
The Keysym class is used to report key presses and releases. It's
available from the SDL.Event class for keyboard events.
int SDL.Keysym.mod
Current key modifiers
mod stores the current state of the keyboard modifiers as
explained in SDL.get_mod_state().
int SDL.Keysym.scancode
Hardware specific scancode
The scancode field should generally be left alone - it is the
hardware dependent scancode returned by the keyboard.
int SDL.Keysym.sym
SDL virtual keysym
The sym field is extremely useful.
It is the SDL-defined value of the key.
This field is very useful when you are checking for certain key presses.
int SDL.Keysym.unicode
Translated character
The unicode field is only used
when UNICODE translation has beed enabled with SDL.enable_unicode().
If unicode is non-zero then this the UNICODE character corresponding
to the keypress.
UNICODE translation does have a slight overhead so don't enable it unless its needed.
Use an SDL.Music object to load in a music file or sample and
then play it back using an internal player.
You must call SDL.init() with the SDL.INIT_AUDIO flag for
audio support to be available. You must also first set up some
audio parameters with a call to SDL.open_audio().
SDL.open_audio()
SDL.Music SDL.Music(string fname)
Loads in the given music file and initializes the object ready for playback.
Supported formats are OGG, MP3, MOD, MID and WAV.
An exception is thrown if the file fails to load.
fnameThe name of the music file to be loaded.
object fade_in(int ms, int|void loops)
Fades the music in over the given number of milliseconds. Playback is repeated loops number of times.
The fade-in will only happen on the first play, not on subsequent loops.
Likewise, calling this method on an object that is already playing has
the same effect as rewind(): playback will start over at the
beginning but without fading in.
msMusic fades in over this number of milliseconds.
loopsHow many times the music should be repeated (looped).
Passing a value of 0 here means the music
plays once over - i.e. no repeats. A value of -1
loops the music indefinitely. This is the default if you
don't specify a value.
The SDL.Music object.
fade_out(), fading()
object fade_out(int ms)
Fades the music out over the given number of milliseconds.
After ms milliseconds have passed, the music will be stopped;
i.e. playing() will return 0.
msThe number of milliseconds it will take to fade out the music, starting from now.
The SDL.Music object.
int fading()
Determines the current state of fading for this SDL.Music object.
One of the following constants:
SDL.MIX_NO_FADING
SDL.MIX_FADING_IN
SDL.MIX_FADING_OUT
fade_in(), fade_out()
object halt()
Stops music playback immediately, including any fader effects.
The SDL.Music object.
object pause()
Pauses the music playback.
It is safe to call this method when the music is already paused.
The SDL.Music object.
resume(), paused()
int paused()
Determines if the music is already paused.
1 if the music is paused, otherwise 0.
object play(int|void loops)
Starts playback. Repeats loops number of times.
loopsThe number of times the music should be looped (i.e. repeated).
If loops is -1 or omitted, the music will repeat
indefinitely.
The SDL.Music object.
int playing()
Determines if the music is already playing.
This method will return 1 even if the music has been paused.
1 if the music is playing, otherwise 0.
object resume()
Resume music playback after a call to pause().
It is safe to call this method when the music isn't paused.
The SDL.Music object.
pause(), paused()
object rewind()
Rewinds the music to the start and resumes playback.
If the music was paused at the time of this call, you will still
need to call resume() to restart playback.
This function works only for MOD, OGG, MP3 and Native MIDI streams.
The SDL.Music object.
float set_volume(float vol)
Sets the volume for music playback.
volThe volume to set. This is a float value from 0.0
(silent) to 1.0 (full volume). Values
above and below these limits will be clamped.
The previous volume setting.
float volume()
The current volume setting. This is a float value from
0.0 (silent) to 1.0 (full volume).
This describes the format of the pixel data stored at the pixels field
of a SDL.Surface. Every surface stores a PixelFormat in the format
field.
int SDL.PixelFormat.rloss
int SDL.PixelFormat.gloss
int SDL.PixelFormat.bloss
int SDL.PixelFormat.aloss
Precision loss of each color component.
int SDL.PixelFormat.alpha
Overall surface alpha value.
int SDL.PixelFormat.rmask
int SDL.PixelFormat.gmask
int SDL.PixelFormat.bmask
int SDL.PixelFormat.amask
Binary mask used to retrieve individual color values.
int SDL.PixelFormat.rshift
int SDL.PixelFormat.gshift
int SDL.PixelFormat.bshift
int SDL.PixelFormat.ashift
Binary left shift of each color component in the pixel value.
int SDL.PixelFormat.bits_per_pixel
The number of bits used to represent each pixel in a surface. Usually 8, 16, 24 or 32.
int SDL.PixelFormat.bytes_per_pixel
The number of bytes used to represent each pixel in a surface. Usually one to four.
int SDL.PixelFormat.colorkey
Pixel value of transparent pixels.
Image.Color.Color get_rgb(int pixel)
Get RGB component values from a pixel stored in this pixel format.
pixelA pixel retrieved from a surface with this pixel format or a color
previously mapped with map_rgb() or map_rgba().
A Image.Color.Color object with the RGB components of the pixel.
map_rgb(), map_rgba(), get_rgba()
mapping(string:Image.Color.Color|int) get_rgba(int pixel)
Get RGB component values from a pixel stored in this pixel format.
pixelA pixel retrieved from a surface with this pixel format or a color
previously mapped with map_rgb() or map_rgba().
A mapping containing the RGBA components of the pixel:
| The RGB color value of the pixel. |
| The alpha value of the pixel in the range 0-255. |
map_rgb(), map_rgba(), get_rgb()
array(int) losses()
Convenience method returning the RGBA precision loss as an array.
int map_rgb(int r, int g, int b)
int map_rgb(Image.Color.Color color)
Maps the RGB color value to the specified pixel format and returns the pixel value as an integer.
If the format has a palette (8-bit) the index of the closest matching color in the palette will be returned.
If the pixel format has an alpha component it will be returned as all 1 bits (fully opaque).
rgbThe red, green and blue components specified as an integer between 0 and 255.
colorThe color as represented by an Image.Color.Color object.
A pixel value best approximating the given RGB color value for a given pixel format.
map_rgba(), get_rgb(), get_rgba()
int map_rgba(int r, int g, int b, int a)
int map_rgba(Image.Color.Color color, int a)
Maps the RGBA color value to the specified pixel format and returns the pixel value as an integer.
If the format has a palette (8-bit) the index of the closest matching color in the palette will be returned.
If the pixel format has an alpha component it will be returned as all 1 bits (fully opaque).
rgbaThe red, green and blue components specified as an integer between 0 and 255.
colorThe color as represented by an Image.Color.Color object.
A pixel value best approximating the given RGB color value for a given pixel format.
map_rgb(), get_rgb(), get_rgba()
array(int) masks()
Convenience method returning the RGBA masks as an array.
array(int) shifts()
Convenience method returning the RGBA shifts as an array.
Used in SDL to define a rectangular area. It is sometimes also used to specify only points or sizes (i.e only one of the position and dimension is used).
int(16bit) SDL.Rect.w
int(16bit) SDL.Rect.h
The width and height of the rectangle. Internally these are 16 bit unsigned integers. A runtime error will be generated when integer values are used that are too big.
int(-32768..32767) SDL.Rect.x
int(-32768..32767) SDL.Rect.y
Position of the upper-left corner of the rectangle. Internally these are 16 bit signed integers. A runtime error will be generated when integer values are used that are too big.
(array)SDL.Rect()
(mapping)SDL.Rect()
It is possible to cast a Rect object to an array or to a mapping. The array will have the values in the order x, y, w, h and the mapping will have the values associated with the corresponding names.
SDL.Rect SDL.Rect()
SDL.Rect SDL.Rect(int(-32768..32767) x, int(-32768..32767) y)
SDL.Rect SDL.Rect(int(-32768..32767) x, int(-32768..32767) y, int(16bit) w, int(16bit) h)
Create a new Rect.
xyOptional initial values for Rect()->x and Rect()->y.
whOptional initial values for Rect()->w and Rect()->h.
Surface's represent areas of "graphical" memory, memory that can
be drawn to. The video framebuffer is returned as a
SDL.Surface by SDL.set_video_mode() and
SDL.get_video_surface().
SDL.Rect SDL.Surface.clip_rect
This is the clipping rectangle as set by set_clip_rect().
int SDL.Surface.flags
The following are supported in the flags field.
Surface is stored in system memory
Surface is stored in video memory
Surface uses asynchronous blits if possible.
Allows any pixel-format (Display surface).
Surface has exclusive palette.
Surface is double buffered (Display surface).
Surface is full screen (Display Sur face).
Surface has an OpenGL context (Display Surface).
Surface supports OpenGL blitting (Display Surface).
Surface is resizable (Display Surface).
Surface blit uses hardware acceleration.
Surface use colorkey blitting.
Colorkey blitting is accelerated with RLE.
Surface blit uses alpha blending.
Surface uses preallocated memory.
SDL.PixelFormat SDL.Surface.format
The pixel format of this surface.
int SDL.Surface.w
int SDL.Surface.h
The width and height of the surface in pixels.
object blit(SDL.Surface dst, SDL.Rect|void srcrect, SDL.Rect|void dstrect)
Perform a blit from this surface to the dst surface.
dstDestination Surface for the blit.
srcrectOptional source Rect. If UNDEFINED the entire source Surface
will be copied.
dstrectOptional destination Rect. Only the position fields
x and y values are used. If UNDEFINED the
blit will be performed to position 0, 0.
object convert_surface(SDL.PixelFormat fmt, int flags)
Document this function
SDL.Surface display_format()
This function takes a surface and copies it to a new surface
of the pixel format and colors of the video framebuffer,
suitable for fast blitting onto the display surface. It calls
convert_surface().
If you want to take advantage of hardware colorkey or alpha blit acceleration, you should set the colorkey and / or alpha value before calling this function.
If you want an alpha channel, see display_format_alpha().
The new surface. An error is thrown if the conversion fails.
SDL.Surface display_format_alpha()
This function takes a surface and copies it to a new surface
of the pixel format and colors of the video framebuffer,
suitable for fast blitting onto the display surface. It calls
convert_surface().
If you want to take advantage of hardware colorkey or alpha blit acceleration, you should set the colorkey and / or alpha value before calling this function.
This function can be used to convert a colourkey to an alpha channel, if the SDL.SRCCOLORKEY flag is set on the surface. The generated surface will then be transparent (alpha=0) where the pixels match the colourkey, and opaque (alpha=255) elsewhere.
The new surface. An error is thrown if the conversion fails.
object fill(int color)
Fill the entire surface with a solid color.
fill_rect()
object fill_rect(int color, SDL.Rect dstrect)
Fill a rectangle with a solid color.
fill()
int get_pixel(int x, int y)
Get the value of the specified pixel. The surface needs to be locked before this method can be used.
xyPixel coordinate to get.
The value of the specified pixel.
set_pixel(), unlock(), lock()
SDL.Surface init(int flags, int width, int height, int depth, int Rmask, int Gmask, int Bmask, int Amask)
This (re)initializes this surface using the specified parameters.
Any previously allocated data will be freed.
depthRmaskGmaskBmaskAmaskIf depth is 8 bits an empty palette is allocated for the surface,
otherwise a 'packed-pixel' SDL.PixelFormat is created using
the [RGBA]mask's provided.
widthheightwidth and height specify the desired size of the image.
flagsflags specifies the type of surface that should be created.
It is an OR'd combination of the following possible values:
SDL will create the surface in system memory. This improves the performance of pixel level access, however you may not be able to take advantage of some types of hardware blitting.
SDL will attempt to create the surface in video memory. This will allow SDL to take advantage of Video->Video blits (which are often accelerated).
This flag turns on colourkeying for blits from this
surface. If SDL.HWSURFACE is also specified and colourkeyed
blits are hardware-accelerated, then SDL will attempt to
place the surface in video memory. Use set_color_key() to
set or clear this flag after surface creation.
This flag turns on alpha-blending for blits from this
surface. If SDL.HWSURFACE is also specified and alpha
blending blits are hardware-accelerated, then the surface
will be placed in video memory if possible. Use
set_alpha() to set or clear this flag after surface
creation.
If an alpha-channel is specified (that is, if Amask is
nonzero), then the SDL.SRCALPHA flag is automatically set. You
may remove this flag by calling set_alpha() after surface
creation.
A reference to itself.
If this method fails, the surface will become uninitialized.
set_image()
int lock()
This methods locks the surface to allow direct access to the pixels
using the get_pixel() and set_pixel() methods.
Note that although all surfaces in SDL don't require locking, you still need to call this method to enable the set/get pixel methods. You should unlock the surface when you're doing modifying it.
Calling this method multiple times means that you need to call unlock an equal number of times for the surface to become unlocked.
1 for success or 0 if the surface couldn't be locked.
unlock(), set_pixel(), get_pixel()
object set_alpha(int flag, int alpha)
Document this function
object set_clip_rect(SDL.Rect rect)
Document this function
object set_color_key(int flag, int key)
Set or clear the color key (aka transparent pixel) for a the surface. Also control whether RLE-accelleration is enabled or not.
flagDocument this function
SDL.Surface set_image(Image.Image image, int|void flags)
SDL.Surface set_image(Image.Image image, Image.Image alpha, int|void flags)
This (re)initializes this surface from the Image.Image in
image.
Any previously allocated data will be freed.
If initialization is successful, this surface will use RGBA8888
format. For good blitting performance, it should be converted to
the display format using display_format().
imageThe source image.
alphaOptional alpha channel. In Pike, the alpha channel can have different alpha values for red, green and blue. Since SDL doesn't support this, only the alpha value of the red color is used in the conversion. When this calling convention is used, the surface alpha value of image is ignored.
flagsWhen present this specifies the type of surface that should be created. It is an OR'd combination of the following possible values:
SDL will create the surface in system memory. This improves the performance of pixel level access, however you may not be able to take advantage of some types of hardware blitting.
SDL will attempt to create the surface in video memory. This will allow SDL to take advantage of Video->Video blits (which are often accelerated).
This flag turns on colourkeying for blits from this
surface. If SDL.HWSURFACE is also specified and colourkeyed
blits are hardware-accelerated, then SDL will attempt to
place the surface in video memory. Use set_color_key() to
set or clear this flag after surface creation.
This flag turns on alpha-blending for blits from this
surface. If SDL.HWSURFACE is also specified and alpha
blending blits are hardware-accelerated, then the surface
will be placed in video memory if possible. Note that if
this surface has an alpha value specified, this flag is
enabled automatically. Use set_alpha() to modify this
flag at a later point.
If this method fails, the surface will become uninitialized.
A reference to itself.
init()
int set_pixel(int x, int y, int pixel)
Set the value of the specified pixel. The surface needs to be locked before this method can be used.
xyPixel coordinate to modify.
pixelPixel value to set to the specified pixel.
A reference to the surface itself.
get_pixel(), unlock(), lock()
void unlock()
Surfaces that were previously locked using lock() must be
unlocked with unlock().
Surfaces should be unlocked as soon as possible.
lock()
This (read-only) class is returned by SDL.get_video_info(). It
contains information on either the 'best' available mode (if
called before SDL.set_video_mode()) or the current video mode.
int SDL.VideoInfo.blit_fill
Are color fills accelerated?
int SDL.VideoInfo.blit_hw
Are hardware to hardware blits accelerated?
int SDL.VideoInfo.blit_hw_a
Are hardware to hardware alpha blits accelerated?
int SDL.VideoInfo.blit_hw_cc
Are hardware to hardware colorkey blits accelerated?
int SDL.VideoInfo.blit_sw
Are software to hardware blits accelerated?
int SDL.VideoInfo.blit_sw_a
Are software to hardware alpha blits accelerated?
int SDL.VideoInfo.blit_sw_cc
Are software to hardware colorkey blits accelerated?
SDL.PixelFormat SDL.VideoInfo.format
Pixel format of the video device.
int SDL.VideoInfo.hw_available
Is it possible to create hardware surfaces?
int SDL.VideoInfo.video_mem
Total amount of video memory in KB.
int SDL.VideoInfo.wm_available
Is there a window manager available
ResultSet do_query_and(array(string) words, array(int) field_coefficients, array(int) proximity_coefficients, int cutoff, function(string, int, int:string) blobfeeder)
wordsArrays of word ids. Note that the order is significant for the ranking.
field_coefficientsAn array of ranking coefficients for the different fields. In the range of [0x0000-0xffff]. The array (always) has 65 elements:
| Array | |
| body |
| Special field 0..63. |
proximity_coefficientsAn array of ranking coefficients for the different proximity categories. Always has 8 elements, in the range of [0x0000-0xffff].
| Array | |
| spread: 0 (Perfect hit) |
| spread: 1-5 |
| spread: 6-10 |
| spread: 11-20 |
| spread: 21-40 |
| spread: 41-80 |
| spread: 81-160 |
| spread: 161- |
blobfeederThis function returns a Pike string containing the word hits for a
certain word. Call repeatedly until it returns 0.
ResultSet do_query_or(array(string) words, array(int) field_coefficients, array(int) proximity_coefficients, int cutoff, function(string, int, int:string) blobfeeder)
wordsArrays of word ids. Note that the order is significant for the ranking.
field_coefficientsAn array of ranking coefficients for the different fields. In the range of [0x0000-0xffff]. The array (always) has 65 elements:
| Array | |
| body |
| Special field 0..63. |
proximity_coefficientsAn array of ranking coefficients for the different proximity categories. Always has 8 elements, in the range of [0x0000-0xffff].
| Array | |
| spread: 0 (Perfect hit) |
| spread: 1-5 |
| spread: 6-10 |
| spread: 11-20 |
| spread: 21-40 |
| spread: 41-80 |
| spread: 81-160 |
| spread: 161- |
blobfeederThis function returns a Pike string containing the word hits for a
certain word. Call repeatedly until it returns 0.
ResultSet do_query_phrase(array(string) words, array(int) field_coefficients, function(string, int, int:string) blobfeeder)
wordsArrays of word ids. Note that the order is significant for the ranking.
field_coefficientsAn array of ranking coefficients for the different fields. In the range of [0x0000-0xffff]. The array (always) has 65 elements:
| Array | |
| body |
| Special field 0..63. |
blobfeederThis function returns a Pike string containing the word hits for a
certain word. Call repeatedly until it returns 0.
Search.Filer.Base get_filter(string mime_type)
Returns the appropriate filter object for the given mime
type. This will be one of the objects in Search.Filter.
array(string) get_filter_fields()
Returns an array of field types supported by the available set of media plugins.
mapping(string:Search.Filter.Base) get_filter_mime_types()
Returns a mapping from mime-type to filter objects. The filter
objects are from Search.Filter.
void add(int docid, int field, int offset)
Search.Blob Search.Blob(void|string initial)
string data()
int memsize()
void merge(string data)
void remove(int doc_id)
void remove_list(array(int) docs)
void add_words(int docid, array(string) words, int field_id)
Add all the words in the 'words' array to the blobs
int memsize()
Returns the in-memory size of the blobs
array read()
returns ({ string word_id, string blob }) or ({0,0}) As a side-effect,
this function frees the blob and the word_id, so you can only read
the blobs struct once. Also, once you have called read,
add_words will no longer work as expected.
array(array(string)) read_all_sorted()
Returns ({({ string word1_id, string blob1 }),...}), sorted by word_id in octet order.
This function also frees the blobs and the word_ids, so you can only read
the blobs struct once. Also, once you have called read or
read_all_sorted, add_words will no longer work as expected.
void add(int, array, int, int)
int memsize()
Returns the in-memory size of the linkfarm
array read()
returns ({ int word_id, Blob b }) or 0
Search.MergeFile Search.MergeFile(Stdio.File _fd)
void merge_mergefiles(Search.MergeFile a, Search.MergeFile b)
void write_blobs(_WhiteFish.Blobs blobs)
int Search.RankingProfile.cutoff
array(int) Search.RankingProfile.field_ranking
array(int) Search.RankingProfile.proximity_ranking
this_program copy()
Returns a copy of this object.
Search.RankingProfile Search.RankingProfile(void|int cutoff, void|array(int) proximity_ranking)
Search.RankingProfile Search.RankingProfile(int cutoff, array(int) proximity_ranking, Search.Database.Base db, array(int)|mapping(string:int) field_ranking)
cutoffDefaults to 8
proximity_rankingDefaults to ({ 8, 7, 6, 5, 4, 3, 2, 1, })
field_rankingDefaults to ({ 17, 0, 147 }) + allocate(62).
dbOnly needed if field_ranking is provided as a mapping.
A resultset is basically an array of hits from the search.
Note: inheriting this class is _not_ supported (for performance reasons)
int sizeof( Search.ResultSet arg )
int size()
Return the size of this resultset, in entries.
ResultSet intersect(ResultSet a)
ResultSet res = Search.ResultSet() & a
Return a new resultset with all entries that are present in _both_ sets. Only the document_id is checked, the resulting ranking is the sum of the rankings if the two sets.
ResultSet res = Search.ResultSet() | a
ResultSet res = Search.ResultSet() + a
ResultSet or(ResultSet a)
Add the given resultsets together, to generate a resultset with both sets included. The rankings will be added if a document exists in both resultsets.
ResultSet sub(ResultSet a)
ResultSet res = Search.ResultSet() - a
Return a new resultset with all entries in a removed from the current ResultSet.
Only the document_id is checked, the ranking is irrelevalt.
ResultSet add_ranking(ResultSet a)
Return a new resultset. All entries are the same as in this set,
but if an entry exists in a, the ranking from a is added to
the ranking of the entry
(array)Search.ResultSet()
Only works when type == "array". Returns the resultset
data as a array.
ResultSet dup()
Return a new resultset with the same contents as this one.
int memsize()
Return the size of this resultset, in bytes.
int overhead()
Return the size of the memory overhead, in bytes.
You can minimize the overhead by calling dup(), which will create a new resultset with the exact size needed.
array(array(int)) slice(int first, int nelems)
Return nelems entries from the result-set, starting with first. If 'first' is outside the resultset, or nelems is 0, 0 is returned.
void sort()
Sort this ResultSet according to ranking.
void sort()
Sort this ResultSet according to ranking.
void sort_docid()
Sort this ResultSet according to document id.
ResultSet test(int nelems, int start, int incr)
Fills the resulttest with nelems entries, the document IDs are
strictly raising, starting with start, ending with
start+nelems*incr.
Used for debug and testing.
Base class for Search database storage abstraction implementations.
int allocate_field_id(string field)
Allocate a field id.
fieldThe (possibly wide string) field name wanted.
An allocated numeric id, or -1 if the allocation failed.
Search.Database.Base Search.Database.Base(string db_url)
Initialize the database object.
pathThe URL that identifies the underlying database storage
string get_blob(string word, int num, void|mapping(string:mapping(int:string)) blobcache)
Retrieves a blob from the database.
wordThe wanted word. Possibly in wide-string format. (Not UTF-8 encoded.)
numblobcacheThe blob requested, or 0 if there's no more blobs.
int get_database_size()
Returns the size, in bytes, of the search database.
int get_document_id(string uri, void|string language, void|int do_not_create)
Retrieve and possibly creates the document id corresponding to the given URI and language code.
uriThe URI to be retrieved or created.
languageA two letter ISO-639-1 language code, or 0 if the document is language neutral.
do_not_createIf non-zero, do not create the document.
The non-zero numeric identifier if the document identified by uri
and language_code exists, or 0 otherwise.
int get_field_id(string field, void|int do_not_create)
Retrieve and possibly creates the numeric id of a field
fieldThe (possibly wide string) field name wanted.
do_not_createIf non-zero, do not allocate a field id for this field
An allocated numeric id, or -1 if it did not exist, or allocation failed.
mapping(string|int:int) get_language_stats()
Retrieve statistics about the number of documents in different languages.
A mapping with the the language code in the index part, and the corresponding number of documents as values.
int get_lastmodified(Standards.URI|string|array(Standards.URI|string) uri, void|string language)
Get last modification time for uri, language.
Returns modification time in seconds since
1970-01-01T00:00:00 UTC) if known,
and 0 (zero) otherwise.
mapping(string:string) get_metadata(int|Standards.URI|string uri, void|string language, void|array(string) wanted_fields)
Retrieve a metadata collection for a document.
uriThe URI of the resource being indexed.
languageA two letter ISO-639-1 language code, or 0 if the document is language neutral.
wanted_fieldsAn array containing the wanted metadata field names, or 0.
The metadata fields in wanted_fields or all existing fields
if wanted_fields is 0.
array(array) get_most_common_words(void|int count)
Returns a list of the count most common words in the database.
count defaults to 10.
int get_num_deleted_documents()
Returns the number of deleted documents in the database.
int get_num_words()
Returns the number of distinct words in the database.
mapping get_uri_and_language(int|array(int) doc_id)
Retrieve the URI and language code associated with doc_id.
| The URI of the document. |
| The ISO-639-1 language code of the document, or 0 if not set. |
int get_uri_id(string uri, void|int do_not_create)
Retrieve and possibly creates the URI id corresponding to the given URI.
uriThe URI to be retrieved or created.
do_not_createIf non-zero, do not create the URI.
The non-zero numeric identifier if uri exists, or 0 otherwise.
void insert_words(Standards.URI|string uri, void|string language, string field, array(string) words)
Index words into the database. The data may be buffered until the
next sync call.
uriThe URI of the resource being indexed.
languageA two letter ISO-639-1 language code, or 0 if the document is language neutral.
fieldThe field name for the words being indexed.
wordsThe words being indexed. Possibly in wide-string format. (Not UTF8 encoded.)
mapping(string:int) list_fields()
Lists all fields in the search database.
A mapping with the fields in the index part, and the corresponding numeric field id as values.
void list_url_by_prefix(string url_prefix, function(string:void) cb)
Calls cb for all uri:s that match uri_prefix.
void remove_document(string|Standards.URI uri, void|string language)
Remove a document from the database.
uriThe URI of the resource being indexed.
languageA two letter ISO-639-1 language code. If zero, delete all
existing language forks with the URI of uri.
void remove_document_prefix(string|Standards.URI uri)
Removes all documents that matches the provided uri prefix.
uriThe URI prefix of the documents to delete.
void remove_field(string field)
Remove a field from the database. Also removes all stored metadata with this field, but not all indexed words using this field id.
fieldThe (possibly wide string) field name to be removed.
void remove_metadata(Standards.URI|string uri, void|string language)
Remove all metadata for a document
uriThe URI of the resource whose metadata should be removed.
languageA two letter ISO-639-1 language code, or 0 if the document is language neutral.
void remove_uri(string|Standards.URI uri)
Remove URI from the database.
uriThe URI of the resource being removed.
void remove_uri_prefix(string|Standards.URI uri)
Remove URI prefix from the database.
uriThe URI prefix of the resource being removed.
void safe_remove_field(string field)
Remove a field from the database if it isn't used by the filters. Also removes all stored metadata with this field, but not all indexed words using this field id.
fieldThe (possibly wide string) field name to be removed.
void set_lastmodified(Standards.URI|string uri, void|string language, int when)
Set last modification time for uri, language to
mtime (seconds since 1970-01-01T00:00:00 UTC).
void set_metadata(Standards.URI|string uri, void|string language, mapping(string:string) metadata)
Set a metadata collection for a document.
uriThe URI of the resource being indexed.
languageA two letter ISO-639-1 language code, or 0 if the document is language neutral.
metadataA collection of metadata strings to be set for a document. The strings may be wide. The "body" metadata may be cut off at 64K.
void set_sync_callback(function(:void) f)
Sets a function to be called when sync has been completed.
void sync()
Writes the data stored in temporary buffers to permanent storage.
Calls the function set by set_sync_callback] when done.
constant array(string) Search.Filter.Base.contenttypes
The MIME content types this object can filter.
optional constantarray(string) Search.Filter.Base.fields
The different fields this object can extract from the media. The list can contain any of the following values.
|
|
|
|
|
|
|
|
|
.Output filter(Standards.URI uri, string|Stdio.File data, string content_type, mixed ... more)
This object is returned from Search.Filter plugins.
int Search.Filter.Output.document_size
The size of the document.
mapping(string:string) Search.Filter.Output.fields
Data extracted from input, grouped by type. Standard fields are
"body", "title", "description",
"keywords" and "mtime".
Note that all field values (even "mtime") are strings.
array(Standards.URI|string) Search.Filter.Output.links
All links collected from the document.
mapping(string:string) Search.Filter.Output.uri_anchors
Maps un-normalized URLs to raw text, e.g.
([ "http://pike.lysator.liu.se": "Pike language" ]) .
void fix_relative_links(Standards.URI base_uri)
Modifies relative links in links to be relative to base_uri.
multiset(string) getDefaultFields()
ParseNode|zero optimize(ParseNode node, string|void parentOp)
void remove_stop_words(ParseNode node, array(string) stop_words)
Search.Grammar.AbstractParser Search.Grammar.AbstractParser(void|mapping(string:mixed) options)
options | Either of the strings: "and", "or". If not supplied, default to "or". |
| The words that should be recognized as fields. If not supplied, it should default to Search.Grammar.getDefaultFields() |
And node.
inherit ParseNode : ParseNode
Date node.
inherit ParseNode : ParseNode
protected inherit .AbstractParser : AbstractParser
protected inherit .Lexer : Lexer
mapping(string:mixed) Search.Grammar.DefaultParser.options
Search.Grammar.DefaultParser Search.Grammar.DefaultParser(mapping(string:mixed)|void opt)
ParseNode parse(string q)
Or node.
inherit ParseNode : ParseNode
Abstract parse tree node.
Text node.
inherit ParseNode : ParseNode
string|array(array(Token|string)) tokenize(string query)
Tokenizes a query into tokens for later use by a parser.
queryThe query to tokenize.
An array containing the tokens: ({ ({ TOKEN_WORD, "foo" }), ... }) Or, in case of an error, a string with the error message.
constant Search.Grammar.Lexer.TOKEN_AND
constant Search.Grammar.Lexer.TOKEN_OR
constant Search.Grammar.Lexer.TOKEN_PLUS
constant Search.Grammar.Lexer.TOKEN_MINUS
constant Search.Grammar.Lexer.TOKEN_COLON
constant Search.Grammar.Lexer.TOKEN_END
constant Search.Grammar.Lexer.TOKEN_EQUAL
constant Search.Grammar.Lexer.TOKEN_LESSEQUAL
constant Search.Grammar.Lexer.TOKEN_GREATEREQUAL
constant Search.Grammar.Lexer.TOKEN_NOTEQUAL
constant Search.Grammar.Lexer.TOKEN_LESS
constant Search.Grammar.Lexer.TOKEN_GREATER
constant Search.Grammar.Lexer.TOKEN_LPAREN
constant Search.Grammar.Lexer.TOKEN_RPAREN
constant Search.Grammar.Lexer.TOKEN_TEXT
constant Search.Grammar.Lexer.TOKEN_UNKNOWN
string extension_to_type(string extension)
string filename_to_type(string filename)
Search.Filter.Output|zero filter_and_index(Search.Database.Base db, string|Standards.URI uri, void|string language, string|Stdio.File data, string content_type, void|mapping headers, void|string default_charset)
void index_document(Search.Database.Base db, string|Standards.URI uri, void|string language, mapping fields)
void remove_document(Search.Database.Base db, string|Standards.URI uri, void|string language)
array(Search.ResultSet|array(string)) execute(Search.Database.Base db, Search.Grammar.AbstractParser parser, string query, Search.RankingProfile ranking, void|array(string) stop_words, search_order|void order)
queryThe query string entered by user.
dbThe search database.
defaultRankingUsed when searching in the field "any:".
An array with three elements:
| Array | |
| The ResultSet containing the hits. |
| All wanted words in the query. (I.e. not the words that were preceded by minus.) |
| All wanted globs in the query. (I.e. not the globs that were preceded by minus.) |
constant Search.Query.RELEVANCE
constant Search.Query.DATE_ASC
constant Search.Query.DATE_DESC
constant Search.Query.NONE
constant Search.Query.PUBL_DATE_ASC
constant Search.Query.PUBL_DATE_DESC
Virtual base class for the Search crawler state.
inherit Web.Crawler.Queue : Queue
void add_uri(Standards.URI uri, int recurse, string template, void|int force)
Add an URI to be crawled.
void clear()
Clear and empty the entire queue.
void clear_cache()
Clear any RAM caches.
void clear_md5(int ... stages)
Clear the content MD5 for all URIs at the specified stages.
void clear_stage(int ... stages)
Reset all URIs at the specified stage to stage 0 (zero).
int|Standards.URI get()
mapping get_extra(Standards.URI uri)
Returns a mapping with the current state for the URI.
|
|
|
|
Currently this function always returns a
mapping(string:string), but this
may change to the above in the future.
array(Standards.URI) get_uris(void|int stage)
Returns all URIs if no stage is specified,
otherwise returns the URIs at the specified stage.
State 0 (zero) is a special case,
and returns all URIs. This may change in
the future.
int num_with_stage(int ... stage)
Returns the number of URIs at the specified stage(s).
void put(string|array(string)|Standards.URI|array(Standards.URI) uri)
Add one or multiple URIs to the queue.
All the URIs will be added with recursion enabled and an empty template.
void remove_stage(int stage)
Remove all URIs at the specified stage.
void remove_uri(string|Standards.URI uri)
Remove an URI from the queue.
void remove_uri_prefix(string|Standards.URI uri)
Remove all URIs with the specified prefix from the queue.
void set_md5(Standards.URI uri, string md5)
Set the content MD5 for an URI.
void set_recurse(Standards.URI uri, int recurse)
Set the recurse mode for an URI.
void set_stage(Standards.URI uri, int stage)
Set the stage for a single URI.
The queue stage levels.
constant Search.Queue.Base.STAGE_WAITING
constant Search.Queue.Base.STAGE_FETCHING
constant Search.Queue.Base.STAGE_FETCHED
constant Search.Queue.Base.STAGE_FILTERED
constant Search.Queue.Base.STAGE_INDEXED
constant Search.Queue.Base.STAGE_COMPLETED
constant Search.Queue.Base.STAGE_ERROR
Search crawler state stored in a Mysql database.
inherit .Base : Base
Search.Queue.MySQL Search.Queue.MySQL(Web.Crawler.Stats _stats, Web.Crawler.Policy _policy, string _url, string _table, void|Web.Crawler.RuleSet _allow, void|Web.Crawler.RuleSet _deny)
_urlSql.Sql URL for the database to store the queue.
_tableSql.Sql table name to store the queue in.
If the table doesn't exist it will be created.
array(string) get_schemes()
Returns an array with all URI schemes currently used in the queue.
int get_stage(Standards.URI uri)
Returns the current stage for the specified URI.
set_stage()
void reset_stage(string|void uri_prefix)
Reset the stage to 0 (zero) for all URIs with the specified
uri_prefix. If no uri_prefix is specified reset the stage for
all URIs.
void flush_profile(int p)
Flushes the profile p from all ProfileCache objects
obtained with get_profile_cache.
ProfileCache get_profile_cache(string db_name)
Returns a ProfileCache for the profiles stored
in the database db_name.
mapping get_profile_storage(string db_name)
Returns a profile storage mapping, which will be shared
between all callers with the same db_name given.
Scheduler get_scheduler(string db_name)
Returns a scheduler for the given profile database.
string normalize(string in)
Normalize the input string. Performs unicode NFKD normalization and then lowercases the whole string
array(string) tokenize(string in)
Tokenize the input string (Note: You should first call normalize on it)
array(string) tokenize_and_normalize(string what)
This can be optimized quite significantly when compared to tokenize( normalize( x ) ) in the future, currently it's not all that much faster, but still faster.
int add_program_name(int code, string name)
Search.Utils.Logger Search.Utils.Logger(Sql.Sql db_object, int profile, int stderr_logging)
Search.Utils.Logger Search.Utils.Logger(string db_url, int profile, int stderr_logging)
array(array(string|int)) get_log(int profile, array(string) types, int from, int to)
void log_error(int code, void|string extra, void|int log_profile)
void log_event(int code, string type, void|string extra, void|int log_profile)
void log_notice(int code, void|string extra, void|int log_profile)
void log_warning(int code, void|string extra, void|int log_profile)
string Search.Utils.ProfileCache.db_name
protected local void __create__(string db_name)
Search.Utils.ProfileCache Search.Utils.ProfileCache(string db_name)
void flush_cache()
Empty the whole cache.
void flush_profile(int p)
Flushes profile entry p from the profile cache.
int get_db_profile_number(string name)
Returns the profile number for the given database profile.
ProfileEntry get_profile_entry(string db_name, void|string query_name)
Returns a ProfileEntry object with the states needed for
commiting searches in the database profile db_name with
the rules from query profile query_name.
int get_query_profile_number(string name)
Returns the profile number for the given query profile.
mapping get_value_mapping(int profile)
Returns the value mapping for the given profile.
array(string) list_db_profiles()
Returns a list of available database profiles.
array(string) list_query_profiles()
Returns a list of available query profiles.
int(-1..1) up_to_datep(int profile_id)
Checks if the profile profile_id has been changed, and clears
related caches if so.
| The profile is deleted. |
| The profile is not up to date. |
| The profile is up to date. |
A result entry from the ProfileCache.
bool check_timeout()
Checks if it is time to check if the profile values are to old.
Search.Utils.ProfileEntry Search.Utils.ProfileEntry(int database_profile_id, int query_profile_id, ProfileCache cache)
cacheThe parent cache object.
Search.Database.MySQL get_database()
Returns a cached search database for the current database profile.
mixed get_database_value(string index)
Returns the database profile value index.
mixed get_query_value(string index)
Returns the query profile value index.
Search.RankingProfile get_ranking()
Returns a cached ranking profile for the current database and query profile.
array(string) get_stop_words()
Returns a cached array of stop words for the current query profile.
void new_entry(int latency, array(int) profiles)
Call this method to indicate that a new entry has been added
to the queue. The scheduler will delay indexing with at most
latency minutes.
Serialization interface.
This module contains APIs to simplify serialization and deserialization of objects.
serialize(), deserialize()
void deserialize(object o, function(function(mixed:void), string, type:void) deserializer)
Call lfun::_deserialize() in o.
serialize(), lfun::_deserialize(),
Serializable()->_deserialize()
void serialize(object o, function(mixed, string, type:void) serializer)
Call lfun::_serialize() in o.
deserialize(), lfun::_serialize(),
Serializable()->_serialize()
Simple base for an object that can be serialized by encode_value. Also supports decoding.
Uses Serializable as it's base.
Simply inherit this class in the classes you want to have encoded and decoded.
Note that it's not automatically recursive, objects assigned to variables in this object have to be Encodeable on their own for encode to work.
When decoding only variables that existed at the time the object was encoded are assigned, that is, if the class now has more variables they new variables will be set to 0.
inherit Serializable : Serializable
Serializer.Encodeable decode_value(string(8bit) data)
Callback for decoding the object. Sets variables in the object from the values in the mapping.
Called automatically by decode_value, not normally called
manually.
string(8bit) encode_value(Serializer.Encodeable data)
Callback for encoding the object. Returns a mapping from variable name to value.
Called automatically by encode_value, not normally called
manually.
The base class for serializable objects.
Inherit this class in classes that need to be serializable.
Serializer.serialize(), Serializer.deserialize()
protected void _deserialize(object o, function(function(mixed:void), string, type:void) deserializer)
Dispatch function for deserialization.
oObject to serialize. Always a context of the current object.
deserializerFunction to typically be called once for every variable in the inheriting class.
This function calls _deserialize_variable() once
for every variable in the inheriting class, which
in turn will call deserializer with the arguments:
The setter for the variable.
The name of the variable.
The declared type of the variable.
The symbols will be listed in the order they were defined in the class.
This function is typically called via Serializer.deserialize().
Serializer.deserialize(), _deserialize_variable(),
_serialize(), Builtin.Setter
protected void _deserialize_variable(function(function(mixed:void), string, type:void) deserializer, function(mixed:void) setter, string symbol, type symbol_type)
Default deserialization function for variables.
deserializerFunction to be called in turn.
setterFunction that sets the value of the variable.
symbolVariable name.
symbol_typeType of the variable.
This function is typically called from _deserialize(), and does
something like:
if (object_typep(symbol_type)) {
program p = program_from_type(symbol_type);
if (p && !needs_parent(p) && is_deserializable(p)) {
object value = p();
setter(value);
Serializer.deserialize(value, deserializer);
return;
}
}
deserializer(setter, symbol, symbol_type);
The above takes care of the most common cases, but
Does not support anonymous object types.
Does not support objects needing a parent.
Does not support non-serializable objects.
Selects one of the object types in case of a complex
symbol_type. The selected type is NOT deterministic
in case there are multiple choices that satisfy the above.
Is likely to throw errors if p() requires arguments.
These issues can all be solved by overloading this function.
_deserialize(), _serialize_variable(), Builtin.Setter
protected void _serialize(object o, function(mixed, string, type:void) serializer)
Dispatch function for serialization.
oObject to serialize. Always a context of the current object.
serializerFunction to typically be called once for every variable in the inheriting class.
This function calls _serialize_variable() once
for every variable in the inheriting class, which
in turn will call serializer with the arguments:
The value of the variable.
The name of the variable.
The declared type of the variable.
The symbols will be listed in the order they were defined in the class.
This function is typically called via Serializer.serialize().
Serializer.serialize(), _serialize_variable(),
_deserialize()
protected void _serialize_variable(function(mixed, string, type:void) serializer, mixed value, string symbol, type symbol_type)
Default serialization function for variables.
serializerFunction to be called in turn.
valueValue of the variable.
symbolVariable name.
symbol_typeType of the variable.
This function is typically called from _serialize(), and just does
serializer(value, symbol, symbol_type);It is provided for overloading for eg filtering or validation purposes.
_serialize(), _deserialize_variable()
Module implementing sending to and from nonblocking streams and other sources.
Most useful when implementing sending of data from strings, files and other sources to a network connection. The module also supports generic bandwidth throttling.
Multiple Shuffler object can be created, each optionally with
their own backend.
This makes it easier to use more than one CPU for pure data transmission, just have multiple backends each in their own thread, with their own shuffle object.
constant Shuffler.INITIAL
constant Shuffler.RUNNING
constant Shuffler.PAUSED
constant Shuffler.DONE
constant Shuffler.WRITE_ERROR
constant Shuffler.READ_ERROR
constant Shuffler.USER_ABORT
The state of an individual Shuffle object.
This class contains the state for one ongoing data
shuffling operation. To create a Shuffle instance, use the
Shuffler()->shuffle method.
Shuffler Shuffler.Shuffle.shuffler
The Shuffler that owns this Shuffle object
Throttler Shuffler.Shuffle.throttler
The Throttler that is associated with this Shuffle object,
if any.
void add_source(mixed source, int|void start, int|void length)
void add_source(mixed source, function(Shuffle, int:array(string)|zero) wrap_cb)
void add_source(array source)
void add_source(array source, function(Shuffle, int:array(string)|zero) wrap_cb)
Add a new source to the list of data sources. The data from the sources will be sent in order.
If start and length are not specified, the whole source will be
sent, if start but not length is specified, the whole source,
excluding the first start bytes will be sent.
Currently supported sources
An ordinary 8-bit wide byte.
An ordinary 8-bit wide pike string.
An initialized instance of the System.Memory class.
A Stdio.Buffer object which will be called once with read_buffer() to acquire the data.
Stdio.File instance pointing to a normal file.
Stdio.File instance pointing to a stream of some kind (network socket, named pipe, stdin etc). Blocking or nonblocking.
An object implementing the callback based reading (set_read_callback and set_close_callback).
An array of any of the supported sources. Note that neither
start nor length can be specified then.
Shuffler.Shuffle Shuffler.Shuffle(object fd, object shuffler, mixed throttler, mixed backend, void|int start, void|int length)
This object is normally not created directly, instead use
Shuffler()->shuffle
void pause()
Temporarily pause all data transmission
int sent_data()
Returns the amount of data that has been sent so far.
void set_done_callback(function(Shuffle, int:void) cb)
Sets the done callback. This function will be called when all sources have been processed, or if an error occurs.
void set_request_arg(mixed arg)
Sets the extra argument sent to Throttler()->request() and
Throttler()->give_back.
void set_throttler(Throttler t)
Calling this function overrides the Shuffler global throttler.
void start(void|int autopause, void|int freerun)
Start sending data from the sources.
autopauseIf true, automatically pause the shuffler when all sources
have been consumed. Everytime this happens, the done_callback
will ben called.
freerunIf true, do not attempt to coalesce output by using bulkmode.
int state()
Returns the current state of the shuffler.
This is one of the following:
INITIAL,
RUNNING,
PAUSED,
DONE,
WRITE_ERROR,
READ_ERROR and
USER_ABORT
void stop()
Stop all data transmission, and then call the done callback
A data shuffler. An instance of this class handles a list of
Shuffle objects. Each Shuffle object can send data from one
or more sources to a destination in the background.
void pause()
Pause all Shuffle objects associated with this Shuffler
void set_backend(Pike.Backend b)
Set the backend that will be used by all Shuffle objects created
from this shuffler.
void set_throttler(Throttler t)
Set the throttler that will be used in all Shuffle objects
created from this shuffler, unless overridden in the
Shuffle objects.
Shuffle shuffle(Stdio.NonblockingStream destination, int|void start, int|void length)
Create a new Shuffle object.
The destination has to support nonblocking I/O
through set_nonblocking_keep_callbacks and set_write_callback
member functions.
For destinations that connect directly to a kernel-filedescriptor please note that the filedescriptor will be dup()ed for the duration of the shuffle. This means that if the original destination object is kept, we temporarily use two filedescriptors for it.
void start()
Unpause all Shuffle objects associated with this Shuffler
This is an interface that all Throttlers must implement.
It's not an actual class in this module.
void give_back(Shuffle shuffle, int amount)
This function will be called by the Shuffle object to report
that some data assigned to it by this throttler was unused, and
can be given to another Shuffle object instead.
void request(Shuffle shuffle, int amount, function(int:void) callback)
This function is called when the Shuffle wants to send some
data to a client.
When data can be sent, the callback function should be called
with the amount of data that can be sent as the argument.
This class implements URI parsing and resolving of relative references to absolute form, as defined in RFC 2396 and RFC 3986.
string|zero Standards.URI.authority
Authority component of URI (formerly called net_loc, from RFC 2396 known as authority)
this_program|zero Standards.URI.base_uri
The base URI object, if present
string|zero Standards.URI.fragment
The fragment part of URI. May be 0 if not present.
string|zero Standards.URI.host
string|zero Standards.URI.user
string|zero Standards.URI.password
Certain classes of URI (e.g. URL) may have these defined
string Standards.URI.path
Path component of URI. May be empty, but not undefined.
int Standards.URI.port
If no port number is present in URI, but the scheme used has a default port number, this number is put here.
string|zero Standards.URI.query
Query component of URI. May be 0 if not present.
string|zero Standards.URI.scheme
Scheme component of URI
Standards.URI()->X = value
Standards.URI()[ property ] = value
Assign a new value to a property of URI
propertyWhen any of the following properties are used, properties that depend on them are recalculated: user, password, host, port, authority, base_uri.
valueThe value to assign to property
int res = Standards.URI() == something
Compare this URI to something, in a canonical way.
somethingCompare the URI to this
void add_query_variable(string name, string value)
Adds the provided query variable to the already existing ones. Will overwrite an existing variable with the same name.
void add_query_variables(mapping(string:string) vars)
Appends the provided set of query variables with the already existing ones. Will overwrite all existing variables with the same names.
(string)Standards.URI()
(mapping)Standards.URI()
When cast to string, return the URI (in a canonicalized form). When cast to mapping, return a mapping with scheme, authority, user, password, host, port, path, query, fragment, raw_uri, base_uri as documented above.
Standards.URI Standards.URI(URI uri)
Standards.URI Standards.URI(URI uri, URI base_uri)
Standards.URI Standards.URI(URI uri, string base_uri)
Standards.URI Standards.URI(string uri)
Standards.URI Standards.URI(string uri, URI base_uri)
Standards.URI Standards.URI(string uri, string base_uri)
base_uriWhen supplied, will root the URI a the given location. This is needed to correctly verify relative URIs, but may be left out otherwise. If left out, and uri is a relative URI, an error is thrown.
uriWhen uri is another URI object, the created URI will inherit all properties of the supplied uri except, of course, for its base_uri.
An exception is thrown if the uri is a relative URI or only a
fragment, and missing a base_uri.
string get_http_path_query()
Return the path and query part of the URI, coded according to RFC 1738.
string|zero get_http_query()
Return the query part, coded according to RFC 1738, or zero.
string get_path_query()
Returns path and query part of the URI if present.
mapping(string:string) get_query_variables()
Returns the query variables as a mapping(string:string).
void reparse_uri()
void reparse_uri(URI base_uri)
void reparse_uri(string base_uri)
Reparse the URI with respect to a new base URI. If no base_uri was supplied, the old base_uri is thrown away. The resolving is performed according to the guidelines outlined by RFC 2396, Uniform Resource Identifiers (URI): Generic Syntax.
base_uriSet the new base URI to this.
An exception is thrown if the uri is a relative URI or only a
fragment, and missing a base_uri.
void set_query_variables(mapping(string:string) vars)
Sets the query variables from the provided mapping.
string decode_der_oid(string der_oid)
Convenience function to convert a DER/BER encoded oid (object identifier) to the human readable dotted-decimal form.
encode_der_oid
string encode_der_oid(string dotted_decimal)
Convenience function to convert an oid (object identifier) on
dotted-decimal form (e.g. "1.3.6.1.4.1.1466.115.121.1.38")
to its DER (and hence also BER) encoded form.
decode_der_oid
Decodes a DER object.
.Types.Object der_decode(Stdio.Buffer data, mapping(int:program) types, void|bool secure)
dataAn instance of Stdio.Buffer containing the DER encoded data.
typesA mapping from combined tag numbers to classes from or derived
from Standards.ASN1.Types. Combined tag numbers may be
generated using Standards.ASN1.Types.make_combined_tag.
secureWill fail if the encoded ASN.1 isn't in its canonical encoding.
An object from Standards.ASN1.Types or, either
Standards.ASN1.Decode.Primitive or
Standards.ASN1.Decode.constructed, if the type is unknown.
Throws an exception if the data could not be decoded.
Handling of implicit and explicit ASN.1 tagging, as well as other context dependence, is next to non_existant.
.Types.Object|zero secure_der_decode(string(8bit) data, mapping(int:program)|void types)
Works just like simple_der_decode, except it will return
0 on errors, including if there is leading or trailing
data in the provided ASN.1 data.
simple_der_decode
.Types.Object simple_der_decode(string(8bit) data, mapping(int:program)|void types)
decode a DER encoded object using universal data types
dataa DER encoded object
typesAn optional set of application-specific types. Should map
combined tag numbers to classes from or derived from
Standards.ASN1.Types. Combined tag numbers may be generated
using Standards.ASN1.Types.make_combined_tag. This set is
used to extend universal_types.
an object from Standards.ASN1.Types or
either Standards.ASN1.Decode.Primitive or
Standards.ASN1.Decode.Constructed if the type is unknown.
Constructed type
inherit .Types.Compound : Compound
int Standards.ASN1.Decode.Constructed.cls
int Standards.ASN1.Decode.Constructed.tag
string(8bit) Standards.ASN1.Decode.Constructed.raw
array(.Types.Object) Standards.ASN1.Decode.Constructed.elements
protected local void __create__(int cls, int tag, string(8bit) raw, array(.Types.Object) elements)
Standards.ASN1.Decode.Constructed Standards.ASN1.Decode.Constructed(int cls, int tag, string(8bit) raw, array(.Types.Object) elements)
string(8bit) get_der_content()
Get raw encoded contents of object
Primitive unconstructed ASN1 data type.
inherit Types.Object : Object
int Standards.ASN1.Decode.Primitive.cls
int Standards.ASN1.Decode.Primitive.tag
string(8bit) Standards.ASN1.Decode.Primitive.raw
protected local void __create__(int cls, int tag, string(8bit) raw)
Standards.ASN1.Decode.Primitive Standards.ASN1.Decode.Primitive(int cls, int tag, string(8bit) raw)
string(8bit) get_der_content()
Get raw encoded contents of object
Encodes various asn.1 objects according to the Distinguished Encoding Rules (DER)
MetaExplicit Standards.ASN1.Types.TaggedType0
MetaExplicit Standards.ASN1.Types.TaggedType1
MetaExplicit Standards.ASN1.Types.TaggedType2
MetaExplicit Standards.ASN1.Types.TaggedType3
Some common explicit tags for convenience.
These are typically used to indicate which of several optional fields are present.
ECPrivateKey ::= SEQUENCE { version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), privateKey OCTET STRING, parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, publicKey [1] BIT STRING OPTIONAL }The presence of the fields parameters and publicKey above are indicated with
TaggedType0andTaggedType1respectively.
bool asn1_IA5_valid(string s)
bool asn1_bmp_valid(string s)
bool asn1_broken_teletex_valid(string s)
bool asn1_printable_valid(string s)
Checks if a Pike string can be encoded as a PrintableString.
int(0) asn1_universal_valid(string s)
int(1) asn1_utf8_valid(string s)
Checks if a Pike string can be encoded with UTF8. That is always the case...
int(2bit) extract_cls(int(0..) i)
Extract ASN1 type class from a combined tag.
make_combined_tag
int(0..) extract_tag(int(0..) i)
Extract ASN1 type tag from a combined tag.
make_combined_tag
int(0..) make_combined_tag(int(2bit) cls, int(0..) tag)
Combines tag and class to a single integer, for internal uses.
clsASN1 type class.
tagASN1 type tag.
The combined tag.
extract_tag, extract_cls
@Pike.Annotations.Implements(Object)BMP String object
Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 2 octets per character.
FIXME: The encoding is very likely UCS-2, but that's not yet verified.
inherit OctetString : OctetString
@Pike.Annotations.Implements(Object)Bit string object
inherit Object : Object
string(8bit) Standards.ASN1.Types.BitString.value
value of object
this_program set_from_ascii(string(8bit) s)
Set the bitstring value as a string with "1" and
"0".
this_program set_length(int len)
Sets the length of the bit string to len number of bits. Will
only work correctly on strings longer than len bits.
@Pike.Annotations.Implements(Object)boolean object
inherit Object : Object
int Standards.ASN1.Types.Boolean.value
value of object
@Pike.Annotations.Implements(Object)(broken) TeletexString object
Encodes and decodes latin1, but labels it TeletexString, as is common in many broken programs (e.g. Netscape 4.0X).
inherit String : String
@Pike.Annotations.Implements(Object)Compound object primitive
inherit Object : Object
constant int Standards.ASN1.Types.Compound.constructed
array(Object) Standards.ASN1.Types.Compound.elements
Contents of compound object.
@Pike.Annotations.Implements(Object)Enumerated object
inherit Integer : Integer
@Pike.Annotations.Implements(UTC)inherit UTC : UTC
int get_posix()
variant this_program set_posix(Calendar.ISO_UTC.Second second)
@Pike.Annotations.Implements(Object)IA5 String object
Character set: ASCII. Fixed width encoding with 1 octet per character.
inherit String : String
@Pike.Annotations.Implements(Object)Object identifier object
inherit Object : Object
array(int) Standards.ASN1.Types.Identifier.id
value of object
this_program append(int ... args)
Returns a new Identifier object with args appended to the
ID path.
@Pike.Annotations.Implements(Object)Integer object All integers are represented as bignums, for simplicity
inherit Object : Object
Gmp.mpz Standards.ASN1.Types.Integer.value
value of object
Meta-instances handle a particular explicit tag and set of types. Once cloned this object works as a factory for Compound objects with the cls and tag that the meta object was initialized with.
MetaExplicit m = MetaExplicit(1,2); Compound c = m(Integer(3));
Standards.ASN1.Types.MetaExplicit Standards.ASN1.Types.MetaExplicit(int(2bit) cls, int(0..) tag, mapping(int:program)|void types)
@Pike.Annotations.Implements(Object)inherit Compound : Compound
@Pike.Annotations.Implements(Object)Null object
inherit Object : Object
Generic, abstract base class for ASN1 data types.
constant int Standards.ASN1.Types.Object.constructed
Flag indicating whether this type is
a constructed (aka Compound) type or not.
constant string Standards.ASN1.Types.Object.type_name
ASN1 type name.
int(2bit) Standards.ASN1.Types.Object.cls
ASN1 type class.
int(0..) Standards.ASN1.Types.Object.tag
ASN1 type tag.
int(2bit) get_cls()
Get the class of this object.
The class of this object.
int(0..) get_combined_tag()
Get the combined tag (tag + class) for this object.
the combined tag header
string(8bit) get_der()
Get the DER encoded version of this object.
DER encoded representation of this object.
int(0..) get_tag()
Get the tag for this object.
The tag for this object.
@Pike.Annotations.Implements(Object)Octet string object
inherit String : String
@Pike.Annotations.Implements(Object)PrintableString object
inherit String : String
@Pike.Annotations.Implements(Object)inherit Object : Object
@Pike.Annotations.Implements(Object)Sequence object
inherit Compound : Compound
@Pike.Annotations.Implements(Object)Set object
inherit Compound : Compound
@Pike.Annotations.Implements(Object)string object primitive
inherit Object : Object
string Standards.ASN1.Types.String.value
value of object
@Pike.Annotations.Implements(Object)UTCTime
inherit String : String
int get_posix()
variant this_program set_posix(Calendar.ISO_UTC.Second second)
@Pike.Annotations.Implements(Object)UTF8 string object
Character set: ISO/IEC 10646-1 (compatible with Unicode).
Variable width encoding, see RFC 2279.
inherit String : String
@Pike.Annotations.Implements(Object)Universal String object
Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 4 octets per character.
The encoding is very likely UCS-4, but that's not yet verified.
inherit OctetString : OctetString
@Pike.Annotations.Implements(Object)inherit String : String
Tools for handling the BSON structured data format. See http://www.bsonspec.org/.
inherit Standards._BSON : _BSON
object Standards.BSON.MaxKey
object Standards.BSON.MinKey
mixed decode(string bson)
Decode a BSON formatted document string into a native Pike data structure.
array decode_array(string bsonarray)
Decode a BSON formatted string containing multiple data structures
string encode(array|mapping m, int|void query_mode)
Encode a data structure as a BSON document.
query_modeif set to true, encoding will allow "$" and "." in key names, which would normally be disallowed.
Standards.BSON.Binary Standards.BSON.Binary(string data, int|void subtype)
Standards.BSON.Javascript Standards.BSON.Javascript(string _data, void|mapping _scope)
Standards.BSON.ObjectId Standards.BSON.ObjectId(string|void _id)
Standards.BSON.Regex Standards.BSON.Regex(string regex, void|string options)
Standards.BSON.Symbol Standards.BSON.Symbol(string _data)
Standards.BSON.Timestamp Standards.BSON.Timestamp()
This module implements EXIF (Exchangeable image file format for Digital Still Cameras) 2.2 parsing.
mapping(string:mixed) get_properties(Stdio.BlockFile file, void|mapping tags)
Parses and returns all EXIF properties.
fileA JFIF file positioned at the start.
tagsAn optional list of tags to process. If given, all unknown tags will be ignored.
A mapping with all found EXIF properties.
This module implements the FIPS10-4 standard for short-form codes of "Countries, Dependencies, Areas of Special Sovereignty, and Their Principal Administrative Divisions."
This is a list of two-letter country codes used by the US government until 2008-10-02, when GENC, based on ISO 3166 replaced it as the prefered standard. The subdivisions are named using the main region name followed by two digits.
This list is similar to, but not entirely compatible with, ISO-3166 alpha-2.
array(string) division_code_to_line(string code)
Convert a division code to the information about the division. As an example division_code_to_line("sw16") would return
({ "SW","SW16","Ostergotlands Lan","province/lan"})
| Array |
|
|
|
|
string division_code_to_name(string code)
Similar to division_code_to_line(), but only returns the name
array(string) division_guess_to_codes(string code)
Return an array of possible division codes given a division name.
| Array | ||||||
|
| |||||
array(array(string)) division_guess_to_lines(string name)
Return an array of possible divisions given a division name.
| Array | ||||||
|
| |||||
array(string) division_name_to_line(string name)
string division_name_to_code(string code)
Lookup a division by name.
These aren't really all that useful, since there might very well be multiple divisions with the same name.
division_guess_to_lines() and division_guess_to_codes() are
more useful.
string region_code_to_name(string code)
Convert a region (country etc) code to the name of the region. As an example, region_code_to_name("se") would return "SEYCHELLES".
string region_name_to_code(string code)
The reverse of region_code_to_name(),
region_name_to_code("Sweden") would return "SW".
array(string) region_to_division_codes(string region)
Given a region (country etc) return all divisions codes in that region
array(array(string)) region_to_divisions(string region)
Given a region (country etc) return all divisions in that region
| Array | ||||||
|
| |||||
ID3 decoder/encoder. Supports versions 1.0, 1.1, 2.2-2.4. For more info see http://www.id3.org
Note that this implementation is far from complete and that interface changes might be necessary during the implementation of the full standard.
string decode_string(string in, int type)
Decodes the string in from the type, according to
ID3v2.4.0-structure section 4, into a wide string.
encode_string
array(string|int) encode_string(string in)
Encodes the string in to an int-string pair, where the
integer is the encoding mode, according to ID3v2.4.0-structure,
and the string is the encoded string. This function tries to
minimize the size of the encoded string by selecting the most
apropriate encoding method.
decode_string, encode_strings
array(string|int) encode_strings(array(string) in)
Encodes several strings in the same way as encode_string, but
encodes all the strings with the same method, selected as in
encode_string. The first element in the resulting array is the
selected method, while the following elements are the encoded strings.
decode_string, encode_string
array(int) int_to_synchsafe(int in, void|int no_bytes)
Encodes a integer to a synchsafe integer according to ID3v2.4.0-structure section 6.2.
synchsafe_to_int
string resynchronise(string in)
Reverses the effects of unsyncronisation done according to ID3v2.4.0-structure section 6.1.
unsynchronise
int synchsafe_to_int(array(int) bytes)
Decodes a synchsafe integer, generated according to ID3v2.4.0-structure section 6.2.
int_to_synchsafe
string unsynchronise(string in)
Unsynchronises the string according to ID3v2.4.0-structure section 6.1.
resynchronise
A wrapper around a Stdio.File object that provides a read
limit capability.
Stdio.File Standards.ID3.Buffer.buffer
protected local void __create__(Stdio.File buffer)
int bytes_left()
The number of bytes left before reaching the limit set by
set_limit.
Standards.ID3.Buffer Standards.ID3.Buffer(Stdio.File buffer)
string peek()
Preview the next byte. Technically it is read from the encapsulated buffer and put locally to avoid seeking.
string read(int bytes)
Read bytes bytes from the buffer. Throw an exception
if bytes is bigger than the number of bytes left in the
buffer before reaching the limit set by set_limit.
void set_limit(int bytes)
Set an artificial EOF bytes bytes further into the
buffer.
Standards.ID3.ExtendedHeader Standards.ID3.ExtendedHeader(void|Buffer buffer)
void decode(Buffer buffer)
string encode()
Manages the common frame information.
Standards.ID3.Frame Standards.ID3.Frame(string|Buffer in, TagHeader thd)
Abstract class for frame data.
bool changed()
Is the content altered?
Standards.ID3.FrameData Standards.ID3.FrameData(void|string data)
This is a ID3 tag super object, which encapsulates all versions ID3 tags. This is useful if you are only interested in the metadata of a file, and care not about how it is stored or have no interest in changing the data.
Version 1 tag is searched only if version 2 isn't found.
Tagv2, Tagv1
constant Standards.ID3.Tag.version
The version of the encapsulated tag in the form "%d.%d.%d".
array indices( Standards.ID3.Tag arg )
Indices will return the indices of the tag object.
array values( Standards.ID3.Tag arg )
Values will return the values of the tag object.
mixed res = Standards.ID3.Tag()[ index ]
mixed res = Standards.ID3.Tag()->X
The index operators are overloaded to index the encapsulated Tagv1 or Tagv2 object.
Standards.ID3.Tag Standards.ID3.Tag(Stdio.File fd)
The file object fd is searched for version 2 tags, and if
not found, version 1 tags.
If no tag was found in the file an error is thrown.
mapping(string:string) friendly_values()
Returns tag values in a mapping. Only tag values that exists in ID3v1.1 is used. Nonexisting or undefined values will not appear in the mapping.
| Takes its value from TPE1 or TP1 frames. |
| Takes its value from TALB or TAL frames. |
| Takes its value from TIT2 or TT2 frames. |
| Takes its value from TCON or TCM frames. |
| Takes its value from TYER or TYE frames. |
| Takes its value from TRCK or TRK frames.
The string may be either in the |
Represents an ID3v2 header.
Standards.ID3.TagHeader Standards.ID3.TagHeader(void|Buffer buffer)
void decode(Buffer buffer)
Decode a tag header from buffer and store its data in
this object.
string encode()
Encode the data in this tag and return as a string.
bool set_flag_unsynchronisation(array(Frame) frames)
Should the unsynchronisation flag be set or not?
ID3 version 1.0 or 1.1 tag. This is really a clumsy way of reading ID3v1 tags, but it has the same interface as the v2 reader.
ID3 version 2 (2.2, 2.3, 2.4) Tags
Standards.ID3.Tagv2 Standards.ID3.Tagv2(void|Buffer|Stdio.File buffer, void|bool _best_effort)
This module implements various algorithms specified by the Internationalizing Domain Names in Applications (IDNA) memo by the Internet Engineering Task Force (IETF), see RFC 3490.
object Standards.IDNA.Punycode
Punycode transcoder, see RFC 3492. Punycode is used by
to_ascii as an "ASCII Compatible Encoding" when needed.
string nameprep(string s, bool|void allow_unassigned)
Prepare a Unicode string for ACE transcoding. Used by
to_ascii. Nameprep is a profile of Stringprep, which is
described in RFC 3454.
sThe string to prep.
allow_unassignedSet this flag the the string to transform is a "query string", and not a "stored string". See RFC 3454.
string(7bit) to_ascii(string s, bool|void allow_unassigned, bool|void use_std3_ascii_rules)
The to_ascii operation takes a sequence of Unicode code points that make up one label and transforms it into a sequence of code points in the ASCII range (0..7F). If to_ascci succeeds, the original sequence and the resulting sequence are equivalent labels.
sThe sequence of Unicode code points to transform.
allow_unassignedSet this flag if the the string to transform is a "query string", and not a "stored string". See RFC 3454.
use_std3_ascii_rulesSet this flag to enforce the restrictions on ASCII characters in host names imposed by STD3.
string to_unicode(string s)
The to_unicode operation takes a sequence of Unicode code points that make up one label and returns a sequence of Unicode code points. If the input sequence is a label in ACE form, then the result is an equivalent internationalized label that is not in ACE form, otherwise the original sequence is returned unaltered.
sThe sequence of Unicode code points to transform.
string(7bit) zone_to_ascii(string s, bool|void allow_unassigned, bool|void use_std3_ascii_rules)
Takes a sequence of labels separated by '.' and applies
to_ascii on each.
string zone_to_unicode(string s)
Takes a sequence of labels separated by '.' and applies
to_unicode on each.
IPTC Information Interchange Model data (aka "IPTC header") extraction.
mapping(string(7bit):array(string)) get_information(Stdio.InputStream fd)
Get IPTC information from an open file.
Supported embedding formats are:
PhotoShop Document (aka PSD).
Postscript and Embedded Postscript.
Joint Picture Experts Group (aka JPEG).
Returns a mapping containing any found IPTC IIM data.
string|zero convert_b_to_t(string code)
Converts an ISO 639-2/B code to an ISO 639-2/T code.
string|zero convert_t_to_b(string code)
Converts an ISO 639-2/T code to an ISO 639-2/B code.
string get_language(string code)
Look up the language name given an ISO 639-2 code in lower case. It will first be looked up in the ISO 639-2/T table and then in ISO 639-2/B if the first lookup failed. Returns zero typed zero on failure.
string get_language_b(string code)
Look up the language name given an ISO 639-2/B code in lower case. Returns zero typed zero on failure.
string get_language_t(string code)
Look up the language name given an ISO 639-2/T code in lower case. Returns zero typed zero on failure.
mapping(string:string) list_639_1()
Return a mapping from ISO 639-1 code to ISO 639-2/T code.
mapping(string:string) list_languages()
Return a mapping from ISO 639-2/T + ISO 639-2/B codes to language names.
mapping(string:string) list_languages_b()
Return a mapping from ISO 639-2/B codes to language names.
mapping(string:string) list_languages_t()
Return a mapping from ISO 639-2/T codes to language names.
string map_639_1(string code)
Look up the ISO 639-2/T code given an ISO 639-1 code in lower case.
string map_to_639_1(string code)
Look up the ISO 639-1 code given an ISO 639-2/T code in lower case.
Tools for handling the JSON structured data format. See http://www.json.org/ and RFC 4627.
constant Standards.JSON.ASCII_ONLY
constant Standards.JSON.HUMAN_READABLE
constant Standards.JSON.PIKE_CANONICAL
constant Standards.JSON.CANONICAL
Bit field flags for use with encode:
Use \uxxxx escapes for all non-ascii characters and DEL
(U+007f). The default is to escape only the characters that must
be escaped. The flag value is 1.
Characters above U+FFFF are encoded using escaped surrogate pairs, as per RFC 4627.
Pretty print with indentation to make the result easier on human eyes. The default is to use no extra whitespace at all. The flag value is 2.
Make the output canonical, so that the same value always
generates the same char-by-char equal string. In practice this
means that mapping elements are sorted on their indices. Note
that the other flags take precedence, so e.g. the canonical form
with HUMAN_READABLE is not the same as the canonical form
without it. The flag value is 4.
This canonical form is stable for the encode function,
providing floats aren't used (their formatting is currently
affected by float size and libc formatting code). In the future
there may be a standardized canonical form which quite likely
will be different from this one. In that case a separate flag
has to be added so this one doesn't change - hence the name
PIKE_CANONICAL. See also CANONICAL below.
Make the output canonical as per RFC 8785, so that the same value always generates the same char-by-char equal string. The flag value is 8.
Note that RFC 8785-compliant output will only be generated
if this is the only flag that has been set and no indentation
has been requested, and Pike.get_runtime_info()->float_size
== 64. In other cases a best effort attempt to comply with
RFC 8785 will be performed, but deviations may occur.
constant Standards.JSON.NO_OBJECTS
Bit field flags for use with decode:
Do not decode "true", "false" and "null"
into Val.true, Val.false and Val.null, but instead
1, 0 and UNDEFINED.
Val.True Standards.JSON.true
Val.False Standards.JSON.false
Val.Null Standards.JSON.null
Compat aliases for the corresponding Val objects. These are
used to represent the three JSON literals true,
false and null.
Replaced by Val.true, Val.false and Val.null.
array|mapping|string|float|int|object decode(string s, void|int flags)
Decodes a JSON string.
flagsThe flag NO_OBJECTS can be used to output 1, 0
and UNDEFINED instead of Val.true, Val.false and
Val.null.
Throws an exception in case the data contained in s is not valid
JSON.
array|mapping|string|float|int|object decode_utf8(string s)
Decodes an utf8 encoded JSON string.
Should give the same result as Standards.JSON.decode(utf8_to_string(s)).
Throws an exception in case the data contained in s is not valid
JSON.
string encode(int|float|string|array|mapping|object val, void|int flags, void|function(:void)|object|program|string callback)
Encodes a value to a JSON string.
valThe value to encode. It can contain integers, floats (except the
special numbers NaN and infinity), strings, arrays, mappings
with string indices, and the special object values null,
true and false defined in this module (or really any
object that implements an encode_json callback or
is handled by the supplied callback argument).
flagsFlag bit field to control formatting. See ASCII_ONLY,
HUMAN_READABLE and PIKE_CANONICAL for further details.
callbackA function that will be called for types that can not be encoded otherwise. It will be called with the value to be encoded as the first argument, and optionally with flags and indent arguments. If a string is supplied, it will be used to replace the value verbatim. The callback must return a string or throw an error.
8-bit and wider characters in input strings are neither escaped
nor utf-8 encoded by default. string_to_utf8 can be used safely
on the returned string to get a valid transport encoded JSON
string. See escape_string for further details on string
escaping.
escape_string
string escape_string(string str, void|int flags)
Escapes string data for use in a JSON string.
8-bit and wider characters in input strings are neither escaped
nor utf-8 encoded by default. string_to_utf8 can be used safely
on the returned string to get a valid transport encoded JSON
string.
The characters U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) are exceptions - they are encoded with \u escapes for compatibility. The reason is that those characters are not allowed in Javascript strings, so JSON parsers built in Javascript may have trouble with them otherwise.
valThe string to escape.
flagsFlag bit field to control formatting. ASCII_ONLY is the only
flag that has any effect for this function.
The difference between using this function and encode on a
string is that encode returns quotations marks around the
result.
encode
int validate(string s)
Checks if a string is valid JSON.
In case the string contains valid JSON -1 is returned. It is then guaranteed to be parsed
without errors by decode().
In case the string is not valid JSON, the error position is returned.
int validate_utf8(string s)
Checks if a string is valid utf8 encoded JSON.
In case the string contains valid JSON -1 is returned. It is then guaranteed to be parsed
without errors by decode().
In case the string is not valid JSON, the integer position inside the string
where the error occurs is returned.
Error thrown when JSON decode fails.
inherit Error.Generic : Generic
int Standards.JSON.DecodeError.err_pos
The failing position in err_str.
string Standards.JSON.DecodeError.err_str
The string that failed to be decoded.
An instance of this class can be used to validate a JSON object against a JSON schema.
string schema_s = "{\n" + " \"name\": \"SomeExample\",\n" + " \"type\": \"object\",\n" + " \"properties\": {\n" + " \"name\": { \"type\": \"string\" },\n" + " \"id\": {\n" + " \"type\": \"integer\",\n" + " \"minimum\": 0\n" + " }\n" + " }\n" + "}"; string example_s = "{\n" + " \"name\": \"An Example\",\n" + " \"id\": 17\n" + "}"; mixed schema =
Standards.JSON.decode(schema_s); mixed example =Standards.JSON.decode(example_s); if (string error =Standards.JSON.Validator(schema).validate(example)) werror("Error: JSON string %O did not validate: %s\n", example_s, error); else write("JSON ok\n");
This class validates only a subset of the JSON schema specification.
Currently dependencies and references are not handled and regular
expressions (for pattern properties) are limited to those that can be
handled by Regexp.SimpleRegexp.
For more information of JSON schema look at http://json-schema.org/documentation.html "The home of JSON Schema".
Standards.JSON.Validator Standards.JSON.Validator(mixed _schema)
Create a JSON validator for some JSON schema.
_schemaThe JSON schema to use in validate(). This must be a valid JSON
object.
Throws an error if the schema is invalid.
private bool has_schema_array(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is an array.
Throws an error if the value of the property is no array.
1 if the schema has the specified property.
private bool has_schema_array_mapping(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is an array(mapping).
Throws an error if the value of the property is no array(mapping).
1 if the schema has the specified property.
private bool has_schema_array_string(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is an array(string).
Throws an error if the value of the property is no array(string).
1 if the schema has the specified property.
private bool has_schema_boolean(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value
of the property is a boolean (with values Standards.JSON.true
or Standards.JSON.false).
Throws an error if the value of the property is no boolean.
1 if the schema has the specified property.
private bool has_schema_integer(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is an integer.
Throws an error if the value of the property is no integer.
1 if the schema has the specified property.
private bool has_schema_mapping(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is a mapping.
Throws an error if the value of the property is no mapping.
1 if the schema has the specified property.
private bool has_schema_mapping_mapping(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is a mapping(string:mapping).
Throws an error if the value of the property is no mapping(string:mapping).
1 if the schema has the specified property.
private bool has_schema_number(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is a number (integer or float).
Throws an error if the value of the property is no number.
1 if the schema has the specified property.
private bool has_schema_string(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is a string.
Throws an error if the value of the property is no string.
1 if the schema has the specified property.
private bool is_JSON_boolean(mixed value)
1 if the specified value is either Standards.JSON.true or
Standards.JSON.false.
string|zero validate(mixed json)
This function validates a JSON object against the JSON schema that was specified in the Validator's constructor. If the JSON object is not valid, a string with an error-message is returned. If the JSON object is valid, 0 is returned.
jsonThe JSON object to validate.
0, if the json object is valid, and an error-message if it is not valid.
private string|zero validate_array(string key, mixed value, mapping(string:mixed) schema)
Verify that the specified value is an array according to the specified schema. The following properties of schema are verified:
If schema has the property "minItems", then the array must have at least the specified number of items.
If schema has the property "maxItems", then the array must not have more than the specified number of items.
If schema has the property "items", which is an array of schema objects, then each element in the value array must be valid according the corresponding schema in the "items" array.
private string|zero validate_integer(string key, mixed value, mapping(string:mixed) schema)
Verify that the specified value is an integer according to the specified
schema. This is the similar to validate_number(), but the
value must be an int and not a float.
The following properties of schema are verified:
If the schema has the property "minimum", then the value must be greater than or equal to the specified minimum.
If the schema has the properties "minimum" and
"exclusiveMinimum" is Standards.JSON.true, then the
value must be greater than the specified minimum.
If the schema has the property "maximum", then the value must be lower than or equal to the specified maximum.
If the schema has the properties "maximum" and
"exclusiveMaximum" is Standards.JSON.true, then the
value must be lower than the specified minimum.
If schema has the property "multipleOf", then the value must be an integer multiple of the specified multpleOf.
private string|zero validate_item_type(string key, mixed value, mapping schema)
Verify that the specified value has the correct type that is defined by schema->type. schema->type can be any of
"boolean",
"integer",
"number",
"string",
"array",
"object",
"null",
or an array of these.
private string|zero validate_number(string key, mixed value, mapping(string:mixed) schema)
Verify that the specified value is a number (integer or float) according to the specified schema. The following properties of schema are verified:
If the schema has the property "minimum", then the value must be greater than or equal to the specified minimum.
If the schema has the properties "minimum" and
"exclusiveMinimum" is Standards.JSON.true, then the
value must be greater than the specified minimum.
If the schema has the property "maximum", then the value must be lower than or equal to the specified maximum.
If the schema has the properties "maximum" and
"exclusiveMaximum" is Standards.JSON.true, then the
value must be lower than the specified minimum.
If schema has the property "multipleOf", then the value must be an integer multiple of the specified multpleOf.
private string|zero validate_object(string key, mixed value, mapping(string:mixed) schema)
Verify that the specified value is an object according to the specified schema. The following properties of schema are verified:
If schema has the property "minProperties", then the object must have at least the specified number of properties.
If schema has the property "maxProperties", then the object must not have more than the specified number of items.
If schema has the property "required", which is an array of strings, then the object must have all properties that are listed in the specified array.
If schema has the property "properties", which is a mapping of property-name to a schema, then each property of the object that has a corresponding schema in "properties" must be valid according to that schema.
If schema has the property "properties", which is a mapping of property-name-pattern to a schema, then each property of the object must be valid according to all schema objects for which the pattern matches the property-name.
If schema has the property "additionalProperties", it can be either a boolean value, or a schema.
If it is a boolean with value Standards.JSON.false, then all
properties of the object must be validated either by a schema from
"properties" or "patternProperties".
If it is a boolean with value Standards.JSON.true, then the
object is allowed to have additional properties without validation.
If it is a schema, then any propery of the object that is not validated by a schema from "properties" or "patternProperties" must be validated by the specified schema.
TODO: We use Regexp.SimpleRegexp to handle
schema->patternProperties, but that covers only some part of the
possible regular expressions.
private string|zero validate_properties(string key, mixed value, mapping schema)
Verify that the specified value matches the specified schema. The following properties of schema are verified:
If the schema has a property "type", then the value
must match the specified type (see validate_item_type()).
If the schema has a property "allOf", which is
an array of schema objects, then the value must match
each schema specified in that array (via another call to
validate_properties()).
If the schema has a property "anyOf", which is
an array of schema objects, then the value must match
at least one schema specified in that array (via another
call to validate_properties()).
If the schema has a property "oneOf", which is
an array of schema objects, then the value must match
exactly one schema specified in that array (via another call
to validate_properties()).
If the schema has a property "not", then the value
must not match the schema specified by that property (via another
call to validate_properties()).
If the schema has a property "enum", then the value must be equal to any of the values specified in the enum array.
If the schema is empty (i.e., it has none of the above specified properties, then the value is valid).
private string|zero validate_string(string key, mixed value, mapping(string:mixed) schema)
Verify that the specified value is a string according to the specified schema. The following properties of schema are verified:
If schema has the property "minLength", then the value must not be shorter than the specified length.
If schema has the property "maxLength", then the value must not be longer than the specified length.
If schema has the property "pattern", then the value must match the specified pattern.
TODO: We use Regexp.SimpleRegexp to handle schema->pattern,
but that covers only some part of the possible regular expressions.
Tools for handling the JSON5 structured data format. See http://www.json5.org/ and RFC 4627.
constant Standards.JSON5.ASCII_ONLY
constant Standards.JSON5.HUMAN_READABLE
constant Standards.JSON5.PIKE_CANONICAL
constant Standards.JSON5.UNQUOTED_IDENTIFIERS
constant Standards.JSON5.SINGLE_QUOTED_STRINGS
Bit field flags for use with encode:
Use \uxxxx escapes for all non-ascii characters and DEL
(U+007f). The default is to escape only the characters that must
be escaped. The flag value is 1.
Characters above U+FFFF are encoded using escaped surrogate pairs, as per RFC 4627.
Pretty print with indentation to make the result easier on human eyes. The default is to use no extra whitespace at all. The flag value is 2.
Make the output canonical, so that the same value always
generates the same char-by-char equal string. In practice this
means that mapping elements are sorted on their indices. Note
that the other flags take precedence, so e.g. the canonical form
with HUMAN_READABLE is not the same as the canonical form
without it. The flag value is 4.
This canonical form is stable for the encode function,
providing floats aren't used (their formatting is currently
affected by float size and libc formatting code). In the future
there may be a standardized canonical form which quite likely
will be different from this one. In that case a separate flag
has to be added so this one doesn't change - hence the name
PIKE_CANONICAL.
When producing mapping keys, permit keys which are identifiers to be expressed without surrounding quotation marks.
Use single quotation marks rather than double quotation marks when encoding string values.
Val.True Standards.JSON5.true
Val.False Standards.JSON5.false
Val.Null Standards.JSON5.null
Compat aliases for the corresponding Val objects. These are
used to represent the three JSON5 literals true,
false and null.
Replaced by Val.true, Val.false and Val.null.
array|mapping|string|float|int|object decode(string s)
Decodes a JSON5 string.
Throws an exception in case the data contained in s is not valid
JSON5.
array|mapping|string|float|int|object decode_utf8(string s)
Decodes an utf8 encoded JSON5 string.
Should give the same result as Standards.JSON5.decode(utf8_to_string(s)).
Throws an exception in case the data contained in s is not valid
JSON5.
string encode(int|float|string|array|mapping|object val, void|int flags, void|function(:void)|object|program|string callback)
Encodes a value to a JSON5 string.
valThe value to encode. It can contain integers, floats (except the
special numbers NaN and infinity), strings, arrays, mappings
with string indices, and the special object values null,
true and false defined in this module (or really any
object that implements an encode_json5 callback or
is handled by the supplied callback argument).
flagsFlag bit field to control formatting. See ASCII_ONLY,
HUMAN_READABLE and PIKE_CANONICAL for further details.
callbackA function that will be called for types that can not be encoded otherwise. It will be called with the value to be encoded as the first argument, and optionally with flags and indent arguments. If a string is supplied, it will be used to replace the value verbatim. The callback must return a string or throw an error.
8-bit and wider characters in input strings are neither escaped
nor utf-8 encoded by default. string_to_utf8 can be used safely
on the returned string to get a valid transport encoded JSON5
string. See escape_string for further details on string
escaping.
escape_string
string escape_string(string str, void|int flags)
Escapes string data for use in a JSON5 string.
8-bit and wider characters in input strings are neither escaped
nor utf-8 encoded by default. string_to_utf8 can be used safely
on the returned string to get a valid transport encoded JSON5
string.
The characters U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR) are exceptions - they are encoded with \u escapes for compatibility. The reason is that those characters are not allowed in Javascript strings, so JSON5 parsers built in Javascript may have trouble with them otherwise.
valThe string to escape.
flagsFlag bit field to control formatting. ASCII_ONLY is the only
flag that has any effect for this function.
The difference between using this function and encode on a
string is that encode returns quotations marks around the
result.
encode
int validate(string s)
Checks if a string is valid JSON5.
In case the string contains valid JSON5 -1 is returned. It is then guaranteed to be parsed
without errors by decode().
In case the string is not valid JSON5, the error position is returned.
int validate_utf8(string s)
Checks if a string is valid utf8 encoded JSON5.
In case the string contains valid JSON5 -1 is returned. It is then guaranteed to be parsed
without errors by decode().
In case the string is not valid JSON5, the integer position inside the string
where the error occurs is returned.
Error thrown when JSON5 decode fails.
inherit Error.Generic : Generic
int Standards.JSON5.DecodeError.err_pos
The failing position in err_str.
string Standards.JSON5.DecodeError.err_str
The string that failed to be decoded.
An instance of this class can be used to validate a JSON5 object against a JSON5 schema.
string schema_s = "{\n" + " \"name\": \"SomeExample\",\n" + " \"type\": \"object\",\n" + " \"properties\": {\n" + " \"name\": { \"type\": \"string\" },\n" + " \"id\": {\n" + " \"type\": \"integer\",\n" + " \"minimum\": 0\n" + " }\n" + " }\n" + "}"; string example_s = "{\n" + " \"name\": \"An Example\",\n" + " \"id\": 17\n" + "}"; mixed schema =
Standards.JSON5.decode(schema_s); mixed example =Standards.JSON5.decode(example_s); if (string error =Standards.JSON5.Validator(schema).validate(example)) werror("Error: JSON5 string %O did not validate: %s\n", example_s, error); else write("JSON5 ok\n");
This class validates only a subset of the JSON5 schema specification.
Currently dependencies and references are not handled and regular
expressions (for pattern properties) are limited to those that can be
handled by Regexp.SimpleRegexp.
For more information of JSON5 schema look at http://json5-schema.org/documentation.html "The home of JSON5 Schema".
Standards.JSON5.Validator Standards.JSON5.Validator(mixed _schema)
Create a JSON5 validator for some JSON5 schema.
_schemaThe JSON5 schema to use in validate(). This must be a valid JSON5
object.
Throws an error if the schema is invalid.
private bool has_schema_array(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is an array.
Throws an error if the value of the property is no array.
1 if the schema has the specified property.
private bool has_schema_array_mapping(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is an array(mapping).
Throws an error if the value of the property is no array(mapping).
1 if the schema has the specified property.
private bool has_schema_array_string(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is an array(string).
Throws an error if the value of the property is no array(string).
1 if the schema has the specified property.
private bool has_schema_boolean(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value
of the property is a boolean (with values Standards.JSON5.true
or Standards.JSON5.false).
Throws an error if the value of the property is no boolean.
1 if the schema has the specified property.
private bool has_schema_integer(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is an integer.
Throws an error if the value of the property is no integer.
1 if the schema has the specified property.
private bool has_schema_mapping(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is a mapping.
Throws an error if the value of the property is no mapping.
1 if the schema has the specified property.
private bool has_schema_mapping_mapping(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is a mapping(string:mapping).
Throws an error if the value of the property is no mapping(string:mapping).
1 if the schema has the specified property.
private bool has_schema_number(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is a number (integer or float).
Throws an error if the value of the property is no number.
1 if the schema has the specified property.
private bool has_schema_string(mapping(string:mixed) schema, string property)
Test if the schema has the specified property and the value of the property is a string.
Throws an error if the value of the property is no string.
1 if the schema has the specified property.
private bool is_JSON5_boolean(mixed value)
1 if the specified value is either Standards.JSON5.true or
Standards.JSON5.false.
string|zero validate(mixed json5)
This function validates a JSON5 object against the JSON5 schema that was specified in the Validator's constructor. If the JSON5 object is not valid, a string with an error-message is returned. If the JSON5 object is valid, 0 is returned.
json5The JSON5 object to validate.
0, if the json5 object is valid, and an error-message if it is not valid.
private string|zero validate_array(string key, mixed value, mapping(string:mixed) schema)
Verify that the specified value is an array according to the specified schema. The following properties of schema are verified:
If schema has the property "minItems", then the array must have at least the specified number of items.
If schema has the property "maxItems", then the array must not have more than the specified number of items.
If schema has the property "items", which is an array of schema objects, then each element in the value array must be valid according the corresponding schema in the "items" array.
private string|zero validate_integer(string key, mixed value, mapping(string:mixed) schema)
Verify that the specified value is an integer according to the specified
schema. This is the similar to validate_number(), but the
value must be an int and not a float.
The following properties of schema are verified:
If the schema has the property "minimum", then the value must be greater than or equal to the specified minimum.
If the schema has the properties "minimum" and
"exclusiveMinimum" is Standards.JSON5.true, then the
value must be greater than the specified minimum.
If the schema has the property "maximum", then the value must be lower than or equal to the specified maximum.
If the schema has the properties "maximum" and
"exclusiveMaximum" is Standards.JSON5.true, then the
value must be lower than the specified minimum.
If schema has the property "multipleOf", then the value must be an integer multiple of the specified multpleOf.
private string|zero validate_item_type(string key, mixed value, mapping schema)
Verify that the specified value has the correct type that is defined by schema->type. schema->type can be any of
"boolean",
"integer",
"number",
"string",
"array",
"object",
"null",
or an array of these.
private string|zero validate_number(string key, mixed value, mapping(string:mixed) schema)
Verify that the specified value is a number (integer or float) according to the specified schema. The following properties of schema are verified:
If the schema has the property "minimum", then the value must be greater than or equal to the specified minimum.
If the schema has the properties "minimum" and
"exclusiveMinimum" is Standards.JSON5.true, then the
value must be greater than the specified minimum.
If the schema has the property "maximum", then the value must be lower than or equal to the specified maximum.
If the schema has the properties "maximum" and
"exclusiveMaximum" is Standards.JSON5.true, then the
value must be lower than the specified minimum.
If schema has the property "multipleOf", then the value must be an integer multiple of the specified multpleOf.
private string|zero validate_object(string key, mixed value, mapping(string:mixed) schema)
Verify that the specified value is an object according to the specified schema. The following properties of schema are verified:
If schema has the property "minProperties", then the object must have at least the specified number of properties.
If schema has the property "maxProperties", then the object must not have more than the specified number of items.
If schema has the property "required", which is an array of strings, then the object must have all properties that are listed in the specified array.
If schema has the property "properties", which is a mapping of property-name to a schema, then each property of the object that has a corresponding schema in "properties" must be valid according to that schema.
If schema has the property "properties", which is a mapping of property-name-pattern to a schema, then each property of the object must be valid according to all schema objects for which the pattern matches the property-name.
If schema has the property "additionalProperties", it can be either a boolean value, or a schema.
If it is a boolean with value Standards.JSON5.false, then all
properties of the object must be validated either by a schema from
"properties" or "patternProperties".
If it is a boolean with value Standards.JSON5.true, then the
object is allowed to have additional properties without validation.
If it is a schema, then any propery of the object that is not validated by a schema from "properties" or "patternProperties" must be validated by the specified schema.
TODO: We use Regexp.SimpleRegexp to handle
schema->patternProperties, but that covers only some part of the
possible regular expressions.
private string|zero validate_properties(string key, mixed value, mapping schema)
Verify that the specified value matches the specified schema. The following properties of schema are verified:
If the schema has a property "type", then the value
must match the specified type (see validate_item_type()).
If the schema has a property "allOf", which is an array of
schema objects, then the value must match each schema specified
in that array (via another call to validate_properties()).
If the schema has a property "anyOf", which is an array of
schema objects, then the value must match at least one schema
specified in that array (via another call to
validate_properties()).
If the schema has a property "oneOf", which is an array of
schema objects, then the value must match exactly one schema
specified in that array (via another call to
validate_properties()).
If the schema has a property "not", then the value
must not match the schema specified by that property (via another
call to validate_properties()).
If the schema has a property "enum", then the value must be equal to any of the values specified in the enum array.
If the schema is empty (i.e., it has none of the above specified properties, then the value is valid).
private string|zero validate_string(string key, mixed value, mapping(string:mixed) schema)
Verify that the specified value is a string according to the specified schema. The following properties of schema are verified:
If schema has the property "minLength", then the value must not be shorter than the specified length.
If schema has the property "maxLength", then the value must not be longer than the specified length.
If schema has the property "pattern", then the value must match the specified pattern.
TODO: We use Regexp.SimpleRegexp to handle schema->pattern,
but that covers only some part of the possible regular expressions.
Tools for handling the MsgPack data format. MsgPack is a binary
serialization format with applications similar to JSON. However,
MsgPack is more versatile and is able to serialize arbitrary
objects using an extension format. The following table shows how
some special Pike data types are encoded in the MsgPack
format. All basic types, namely int, string,
float, array and mapping are mapped onto
their natural MsgPack counterparts. Note that the encoder does not
use all integer and floating point lengths and in particular
integers are never encoded as unsigned.
Stdio.Buffer
Val.null
Val.true
Val.false
All other types can be encoded and decoded using extension handlers.
typedef function(int(-127..128), Stdio.Buffer:mixed) Standards.MsgPack.decode_handler
Function prototype for decode extension handlers. The first
argument is the extension type identifier. The second argument is
a Stdio.Buffer containing the payload.
decode, decode_from
typedef function(Stdio.Buffer, mixed:void) Standards.MsgPack.encode_handler
Function prototype for encode extension handlers. The first
argument is the Stdio.Buffer, the second the value to
encode. Use add_extension_header to generate the correct
extension header.
decode, decode_from
void add_extension_header(Stdio.Buffer b, int(-128..127) type, int(0..) len)
Adds an extension header to b for given type and payload length.
mixed decode(string(8bit) data, void|decode_handler|object handler)
Decode one MsgPack encoded value from data.
mixed decode_from(Stdio.Buffer buffer, void|decode_handler|object handler)
Decode one MsgPack encoded value from the buffer.
void default_handler(Stdio.Buffer b, function(:void)|object|program v)
Default encoding handler. Encodes Val.null, Val.true and
Val.false.
string(8bit) encode(mixed v, void|encode_handler|object handler)
Encode v into a string.
void encode_to(Stdio.Buffer buf, mixed v, void|encode_handler|object handler)
Encode v into buf. If handler is not specified,
it defaults to default_handler.
Error thrown when MsgPack decoding fails.
inherit Error.Generic : Generic
Stdio.Buffer Standards.MsgPack.DecodeError.buffer
The data which failed to be decoded.
int Standards.MsgPack.DecodeError.err_pos
The failing position in buffer.
Support for parsing PEM-style messages, defined in RFC 1421. Encapsulation defined in RFC 0934.
string build(string tag, string data, void|mapping(string:string) headers, void|string checksum)
Creates a PEM message, wrapped to 64 character lines.
tagThe encapsulation boundary string.
dataThe data to be encapsulated.
headersOptional mapping containing encapsulated headers as name value pairs.
checksumOptional checksum string, added as per RFC 4880.
string(8bit) decrypt_body(string(8bit) dek_info, string(8bit) body, string(8bit) password)
Decrypt a PEM body.
dek_info"dek-info" header from the Message.
bodyEncypted PEM body.
passwordDecryption password.
Returns the decrypted body text.
string(8bit)|zero decrypt_fragment(Message m, string(8bit) pwd)
Decrypt a PEM Message.
bodyFragment with encypted PEM body.
passwordDecryption password.
Returns the decrypted body text.
string(8bit) derive_key(string(8bit) password, string(8bit) salt, int bytes)
Key derivation function used in PEM.
Derived from OpenSSL. Is there any proper specification?
It seems to be related to PBKDF1 from RFC 2898.
string(8bit)|zero simple_decode(string(8bit) pem)
Convenience function that decodes a PEM message containing only
one part, and returns it as a string. Returns 0 for indata
containing no or multiple parts.
Represents a PEM-style message.
string(8bit)|zero Standards.PEM.Message.body
The decode message body.
mapping(string(8bit):string(8bit))|zero Standards.PEM.Message.headers
Encapsulated headers. If headers occur multiple times, they will be concatenated separated by delimiting NUL characters.
string|zero Standards.PEM.Message.post
Post-encapsulation boundary string.
Usually the same value as pre.
string|zero Standards.PEM.Message.pre
Pre-encapsulation boundary string.
Typically a string like "CERTIFICATE" or "PRIVATE KEY".
string(8bit)|zero Standards.PEM.Message.trailer
Message trailer, like RFC 4880 checksum.
The Messages class acts as an envelope for a PEM message file or stream.
array(string(8bit)|Message) Standards.PEM.Messages.fragments
The fragments array contains the different message fragments, as Message objects for decoded messages and strings for non-messages or incomplete messages.
mapping(string(8bit):array(Message)) Standards.PEM.Messages.parts
This is a mapping from encapsulation boundary string to Message
objects. All message objects and surrounding text will be
listed, in order, in fragments.
Standards.PEM.Messages Standards.PEM.Messages(string(8bit) data)
A Messages object is created with the file or stream data.
string get_certificate()
Convenience wrapper for get_certificates that returns the
first available certificate, or 0.
array(string) get_certificates()
Returns an array of all the bodies of "CERTIFICATE" and
"X509 CERTIFICATE" fragments.
string|zero get_encrypted_private_key(string(8bit) pwd)
Returns the first key, decoded by the pwd password.
array(string) get_fragment_bodies(multiset labels)
Returns an array of the string bodies of all fragments with any
of the given labels in the boundy preamble.
array(Message) get_fragments(multiset labels)
Returns an array of all fragments with any of the given
labels in the boundy preamble.
string get_private_key()
Convenience wrapper for get_private_key that returns the
first available key, or 0.
array(string) get_private_keys()
Returns an array of all the bodies of "RSA PRIVATE KEY",
"DSA PRIVATE KEY", "EC PRIVATE KEY" and
"ANY PRIVATE KEY" fragments.
Public-Key Cryptography Standards (PKCS).
This is the Pike API for dealing with a set of standards initially published by RSA Security Inc, and later by IETF and others in various RFCs.
Standards.ASN1, Crypto,
RFC 2314, RFC 2459, RFC 2986, RFC 3279, RFC 3280,
RFC 4055, RFC 4985, RFC 5208, RFC 5280, RFC 5480,
RFC 5639, RFC 5915, RFC 5958, RFC 7292, RFC 7468
Crypto.Sign.State parse_private_key(Sequence seq)
Parse a PKCS#8 PrivateKeyInfo (cf RFC 5208 section 5).
parse_public_key(), RSA.parse_private_key(), DSA.parse_private_key()
Crypto.Sign.State parse_public_key(Sequence seq)
Parse a PKCS#10 SubjectPublicKeyInfo (cf RFC 5280 section 4.1 and RFC 7468 section 13).
parse_private_key(), RSA.parse_public_key(), DSA.parse_public_key()
Sequence build_csr(Crypto.Sign sign, Sequence name, mapping(string:array(Object)) attributes, Crypto.Hash|void hash)
Build a Certificate Signing Request.
signSignature algorithm for the certificate. Both private and public keys must be set.
nameThe distinguished name for the certificate.
attributesAttributes from PKCS #9 to add to the certificate.
hashHash algoritm to use for the CSR signature.
Defaults to Crypto.SHA256.
Prior to Pike 8.0 this function only supported signing
with Crypto.RSA and the default (and only) hash was
Crypto.MD5.
Sequence sign_cri(CRI cri, Crypto.Sign sign, Crypto.Hash hash)
Sign a CRI to generate a Certificate Signing Request.
criCertificationRequestInfo to sign.
signSignature to use. Must have a private key set that matches
the public key in the keyinfo in cri.
hashHash algorithm to use for the signature.
CertificationRequestInfo
This is the data that is signed by sign_cri().
inherit Sequence : Sequence
void Standards.PKCS.CSR.CRI.attributes
Subject attributes.
void Standards.PKCS.CSR.CRI.keyinfo
Public key information.
void Standards.PKCS.CSR.CRI.subject
Certificate subject.
void Standards.PKCS.CSR.CRI.version
inherit .Certificate.Attributes : Attributes
Handle PKCS-6 and PKCS-10 certificates and certificate requests.
variant Sequence build_distinguished_name(array args)
Creates an ASN.1 Sequence with the distinguished name of the
list of pairs given in args. Supported identifiers are
argsEither a mapping that lists from id string to string or ASN.1 object, or an array with mappings, each containing one pair. No type validation is performed.
array(mapping(string(7bit):string)) decode_distinguished_name(Sequence dn)
Perform the reverse operation of build_distinguished_name().
build_distinguished_name()
string get_dn_string(Sequence dnsequence)
Converts an RDN (relative distinguished name) Seqeunce object to a human readable string in X500 format.
A string containing the certificate issuer Distinguished Name (DN) in human readable X500 format.
We don't currently handle attributes with multiple values, not all attribute types are understood.
DSA operations as defined in RFC 2459.
Sequence algorithm_identifier(Crypto.DSA|void dsa)
Returns the AlgorithmIdentifier as defined in RFC 5280 section 4.1.1.2. Optionally the DSA parameters are included, if a DSA object is given as argument.
Sequence build_private_key(Crypto.DSA dsa)
Creates a PrivateKeyInfo ASN.1 sequence for the given rsa
object. See RFC 5208 section 5.
Sequence build_public_key(Crypto.DSA dsa)
Creates a SubjectPublicKeyInfo ASN.1 sequence for the given dsa
object. See RFC 5280 section 4.1.2.7.
Crypto.DSA parse_private_key(Sequence seq)
variant Crypto.DSA parse_private_key(string key)
Crypto.DSA|zero parse_public_key(string key, Gmp.mpz p, Gmp.mpz q, Gmp.mpz g)
Decodes a DER-encoded DSAPublicKey structure.
keyDSAPublicKey provided in ASN.1 DER-encoded format
pPublic parameter p, usually transmitted in the algoritm identifier.
qPublic parameter q, usually transmitted in the algoritm identifier.
gPublic parameter g, usually transmitted in the algoritm identifier.
Crypto.DSA object
string private_key(Crypto.DSA dsa)
string public_key(Crypto.DSA dsa)
Generates the DSAPublicKey value, as specified in RFC 2459.
Sequence|zero signature_algorithm_id(Crypto.Hash hash)
Returns the PKCS-1 algorithm identifier for DSA and the provided
hash algorithm. One of SHA1, SHA224 or SHA256.
ECDSA operations.
protected mapping(string:Crypto.ECC.Curve) Standards.PKCS.ECDSA.curve_lookup
Lookup from ASN.1 DER encoded ECC named curve identifier to
the corresponding Crypto.ECC.Curve.
Crypto.ECC.Curve|zero parse_ec_parameters(string ec_parameters)
Get the ECC curve corresponding to an ASN.1 DER encoded named curve identifier.
Returns UNDEFINED if the curve is unsupported.
Crypto.ECC.SECP_521R1.ECDSA|zero parse_private_key(Sequence a, Crypto.ECC.Curve|void c)
Get an initialized ECDSA object from an ECC curve and an ASN.1 ec private key sequence.
As specified in RFC 5915 section 3.
variant Crypto.ECC.SECP_521R1.ECDSA|zero parse_private_key(string(8bit) ec_private_key, Crypto.ECC.Curve|void c)
Get an initialized ECDSA object from an ECC curve and an ASN.1 DER encoded ec private key.
As specified in RFC 5915 section 3.
Crypto.ECC.SECP_521R1.ECDSA parse_public_key(string(8bit) key, Crypto.ECC.Curve c)
Get an initialized ECDSA object from an ECC curve and an ec public key.
string(8bit) private_key(Crypto.ECC.SECP_521R1.ECDSA ecdsa)
Create a DER-coded ECPrivateKey structure
ecdsaCrypto.ECC.Curve()->ECDSA object.
ASN.1 coded ECPrivateKey structure as specified in RFC 5915 section 3.
string(8bit) public_key(Crypto.ECC.SECP_521R1.ECDSA ecdsa)
Create a DER-coded ECPublicKey structure
ecdsaCrypto.ECC.Curve()->ECDSA object.
ASN.1 coded ECPublicKey structure as specified in RFC 5480 section 2.
PKCS #12: Personal Information Exchange Syntax v1.1, RFC 7292.
RSA operations and types as described in PKCS-1.
Sequence algorithm_identifier()
Returns the AlgorithmIdentifier as defined in RFC 5280 section 4.1.1.2.
Sequence build_private_key(Crypto.RSA rsa)
Creates a PrivateKeyInfo ASN.1 sequence for the given rsa
object. See RFC 5208 section 5.
Sequence build_public_key(Crypto.RSA rsa)
Creates a SubjectPublicKeyInfo ASN.1 sequence for the given rsa
object. See RFC 5280 section 4.1.2.7.
Sequence oaep_algorithm_id(Crypto.Hash hash, string(8bit)|void label)
Returns the PKCS-1 algorithm identifier for RSAES-OAEP and the provided hash algorithm and label.
Crypto.RSA.State parse_private_key(Sequence seq)
Decode a RSAPrivateKey structure
keyRSAPrivateKey provided in ASN.1 format
Crypto.RSA object
variant Crypto.RSA.State parse_private_key(string key)
Decode a DER-coded RSAPrivateKey structure
keyRSAPrivateKey provided in ASN.1 DER-encoded format
Crypto.RSA object
Crypto.RSA.State parse_public_key(string key)
Decode a DER-coded RSAPublicKey structure
keyRSAPublicKey provided in ASN.1 DER-encoded format
Crypto.RSA object
string private_key(Crypto.RSA rsa)
Create a DER-coded RSAPrivateKey structure
rsaCrypto.RSA object
ASN1 coded RSAPrivateKey structure
Sequence pss_signature_algorithm_id(Crypto.Hash hash, int(0..)|void saltlen)
Returns the PKCS-1 algorithm identifier for RSASSA-PSS and the provided hash algorithm and saltlen.
string public_key(Crypto.RSA rsa)
Create a DER-coded RSAPublicKey structure
rsaCrypto.RSA object
ASN1 coded RSAPublicKey structure
Sequence|zero signature_algorithm_id(Crypto.Hash hash)
Returns the PKCS-1 algorithm identifier for RSA and the provided
hash algorithm. One of MD2, MD5, SHA1, SHA256,
SHA384 or SHA512.
string build_digestinfo(string msg, Crypto.Hash hash)
Construct a PKCS-1 digestinfo.
msgmessage to digest
hashcrypto hash object such as Crypto.SHA1 or Crypto.MD5
Crypto.RSA()->sign
Signed sign(Sequence tbs, Crypto.Sign sign, Crypto.Hash hash)
Generic PKCS signing.
tbsStandards.ASN1 structure to be signed.
signSignature to use. Must have a private key set.
hashHash algorithm to use for the signature. Must be valid for the signature algorithm.
Returns a Standards.ASN1.Types.Sequence with
the signature.
This is an ASN.1 structure from PKCS #10 v1.7 and others, which represents a signed block of data.
sign(), Standards.X509.sign_tbs().
inherit Sequence : Sequence
Sequence Standards.PKCS.Signature.Signed.algorithm
Getting
Signing algorithm that was used to sign with.
Setting
Signing algorithm that was used to sign with.
BitString Standards.PKCS.Signature.Signed.signature
Getting
The signature.
Setting
The signature.
Object Standards.PKCS.Signature.Signed.tbs
Getting
ASN.1 structure that has been signed.
Setting
ASN.1 structure that has been signed.
this_program sign(Crypto.Sign sign, Crypto.Hash hash)
Sign tbs with the provided sign and hash.
Sets algorithm and signature.
Returns the Signed object.
constant Standards.TLD.cc
A mapping between country TLDs and the name of the country.
multiset Standards.TLD.generic
A multiset containing the generic TLDs, such as "com" and "info".
Support for Universal Unique Identifiers (UUID) and Globally Unique Identifiers (GUID).
A Universally Unique IDentifier (UUID) URN Namespace.
Generation and registration of Universally Unique Identifiers (UUIDs) and their use as ASN.1 object identifier components.
constant string Standards.UUID.NameSpace_DNS
Name space UUID for DNS.
constant string Standards.UUID.NameSpace_OID
Name space UUID for OID.
constant string Standards.UUID.NameSpace_URL
Name space UUID for URL.
constant string Standards.UUID.NameSpace_X500
Name space UUID for X500.
constant string Standards.UUID.Nil_UUID
The Nil UUID.
string format_uuid(string uuid)
Returns the string representation of the binary UUID uuid.
array(int) get_clock_state()
Returns the internal clock state. Can be used for persistent storage when an application is terminated.
set_clock_state
UUID make_dns(string name)
Creates a DNS UUID with the given DNS name.
UUID make_dns(string name)
Creates a DNS UUID with the given DNS name.
UUID make_null()
Creates a null UUID object.
UUID make_oid(string name)
Creates an OID UUID with the given OID.
UUID make_oid(string name)
Creates an OID UUID with the given OID.
UUID make_url(string name)
Creates a URL UUID with the given URL.
UUID make_url(string name)
Creates a URL UUID with the given URL.
UUID make_version1(int node)
Creates a new version 1 UUID.
nodeEither the 48 bit IEEE 802 (aka MAC) address of the system or -1.
UUID make_version3(string name, string|UUID namespace)
Creates a version 3 UUID with a name string and a binary
representation of a name space UUID.
UUID make_version4()
Creates a version 4 (random) UUID.
UUID make_version5(string name, string|UUID namespace)
Creates a version 5 UUID with a name string and a binary
representation of a name space UUID.
UUID make_x500(string name)
Creates an X500 UUID with the gived X500 address.
UUID make_x500(string name)
Creates an X500 UUID with the gived X500 address.
string parse_uuid(string uuid)
Returns the binary representation of the UUID uuid.
void set_clock_state(int last_time, int seq)
Sets the internal clock state.
get_clock_state
Represents an UUID
int Standards.UUID.UUID.clk_seq
The clock sequence. Should be 13 to 15 bits depending on UUID version.
int Standards.UUID.UUID.node
The UUID node. Should be 48 bit.
int Standards.UUID.UUID.timestamp
60 bit value representing the time stamp.
int Standards.UUID.UUID.var
The variant of the UUID.
int Standards.UUID.UUID.version
The version of the UUID.
Standards.UUID.UUID Standards.UUID.UUID(void|string in)
Optionally created with a string or binary representation of a UUID.
string encode()
Encodes a binary representation of the UUID.
int posix_time()
Returns the posix time of the UUID.
string str()
Creates a string representation of the UUID.
string str_variant()
Returns a string representation of the variant, e.g.
"IETF draft variant".
string str_version()
Returns a string representation of the version, e.g.
"Name-based (MD5)".
int time_hi_and_version()
Returns the time_hi_and_version field.
int time_low()
Returns the time_low field.
int time_mid()
Returns the time_mid field.
string urn()
Creates a URN representation of the UUID.
void validate()
Validates the current UUID.
Functions to generate and validate RFC 2459 style X.509 v3 certificates.
TBSCertificate|zero decode_certificate(string|.PKCS.Signature.Signed cert)
Decodes a certificate and verifies that it is structually sound.
Returns a TBSCertificate object if ok, otherwise 0.
mapping(Identifier:Crypto.Hash) get_algorithms()
Returns the mapping of signature algorithm to hash algorithm
supported by Verifier and thus verify_ca_certificate(),
verify_certificate(), and verify_certificate_chain().
array get_letsencrypt_cert(string host)
Read and decode certificate chain for the given host from the
letsencrypt directory (/etc/letsencrypt/live/{host}/). Note that
the process has to have read privileges for the directory.
The resulting array can be used directly as input to the
SSL.Context()->add_cert() method.
| Array | |
| A signing object using the private key. |
| An array of DER encoded certificates representing the certificate chain. |
mapping(string:array(Verifier)) load_authorities(string|array(string)|void root_cert_dirs, bool|void cache)
Convenience function for loading known root certificates.
root_cert_dirsDirectory/directories containing the PEM-encoded root certificates
to load. Defaults to a rather long list of directories, including
"/etc/ssl/certs", "/etc/pki/tls/certs" and
"/System/Library/OpenSSL/certs", which seem to be the most
common locations.
cacheA flag to control if the answer should be given from an internal cache or always scan the directories. If a cache is used, it will refresh when any certificate expires (which typically is measured in years) or when asked for in unchached mode.
Returns a mapping from DER-encoded issuer to Verifiers
compatible with eg verify_certificate()
If a certificate directory contains a file named
"ca-certificates.crt", "ca-bundle.crt" or
"ca-bundle.trust.crt", it is assumed to
contain a concatenation of all the certificates
in the directory.
verify_certificate(), verify_certificate_chain()
Sequence make_extension(Identifier id, Object ext, void|int critical)
Creates a certificate extension with the id as identifier and
ext as the extension payload. If the critical flag is set
the extension will be marked as critical.
string make_selfsigned_certificate(Crypto.Sign.State c, int ttl, mapping|array name, mapping(Identifier:Sequence)|void extensions, Crypto.Hash|void h, int|void serial)
Creates a selfsigned certificate, i.e. where issuer and subject
are the same entity. This entity is derived from the list of pairs
in name, which is encoded into an distinguished_name by
Standards.PKCS.Certificate.build_distinguished_name.
cThe public key cipher used for the certificate, Crypto.RSA,
Crypto.DSA or Crypto.ECC.Curve.ECDSA. The object should be
initialized with both public and private keys.
ttlThe validity of the certificate, in seconds, starting from creation date.
nameList of properties to create distinguished name from.
extensionsMapping with extensions as ASN.1 structures, as produced by
make_extension. The extensions subjectKeyIdentifier, keyUsage
(flagged critical) and basicConstraints (flagged critical) will
automatically be added if not present.
hThe hash function to use for the certificate. Must be one of the
standardized PKCS hashes to be used with the given Crypto. By
default Crypto.SHA256 is selected for both RSA and DSA.
serialSerial number of the certificate. Defaults to generating a UUID version1 value with random node. Some browsers will refuse different certificates from the same signer with the same serial number.
sign_key(), sign_tbs()
TBSCertificate make_tbs(Sequence issuer, Sequence algorithm, Sequence subject, Sequence keyinfo, Integer serial, Sequence validity, array|int(0)|void extensions)
Creates the ASN.1 TBSCertificate sequence (see RFC 2459 section
4.1) to be signed (TBS) by the CA. version is explicitly set to
v3, and extensions is optionally added to the sequence.
issuerUniqueID and subjectUniqueID are not supported.
variant TBSCertificate make_tbs(Sequence issuer, Sequence algorithm, Sequence subject, Sequence keyinfo, Integer serial, int ttl, array|int(0)|void extensions)
Creates the ASN.1 TBSCertificate sequence (see RFC 2459 section
4.1) to be signed (TBS) by the CA. version is explicitly set to
v3, validity is calculated based on time and ttl, and
extensions is optionally added to the sequence. issuerUniqueID
and subjectUniqueID are not supported.
Prior to Pike 8.0 this function returned a plain Sequence object.
Crypto.Sign.State parse_private_key(Sequence seq)
DWIM-parse the ASN.1-sequence for a private key.
variant Crypto.Sign.State parse_private_key(string(8bit) private_key)
DWIM-parse the DER-sequence for a private key.
string sign_key(Sequence issuer, Crypto.Sign.State c, Crypto.Sign.State ca, Crypto.Hash h, Sequence subject, int serial, int ttl, array|mapping|void extensions)
Low-level function for creating a signed certificate.
issuerDistinguished name for the issuer.
See Standards.PKCS.Certificate.build_distinguished_name.
cRSA, DSA or ECDSA parameters for the subject. Only the public
key needs to be set. See Crypto.RSA, Crypto.DSA and
Crypto.ECC.Curve.ECDSA.
caRSA, DSA or ECDSA parameters for the issuer. Only the private
key needs to be set. See Crypto.RSA, Crypto.DSA and
Crypto.ECC.Curve.ECDSA.
hThe hash function to use for the certificate. Must be one of the standardized PKCS hashes to be used with the given Crypto.
subjectDistinguished name for the subject.
See Standards.PKCS.Certificate.build_distinguished_name.
public_keyDER-encoded RSAPublicKey structure.
See Standards.PKCS.RSA.public_key().
serialSerial number for this key and subject.
ttlValidity time in seconds for this signature to be valid.
extensionsSet of extensions.
Returns a DER-encoded certificate.
make_selfsigned_certificate(), make_tbs(), sign_tbs()
Sequence sign_tbs(TBSCertificate tbs, Crypto.Sign.State sign, Crypto.Hash hash)
Sign the provided TBSCertificate.
tbsA TBSCertificate as returned by decode_certificate()
or make_tbs().
signRSA, DSA or ECDSA parameters for the issuer.
See Crypto.RSA, Crypto.DSA and Crypto.ECC.Curve.ECDSA.
Must be initialized with the private key.
hashThe hash function to use for the certificate. Must be one of the standardized PKCS hashes to be used with the given Crypto.
decode_certificate(), make_tbs()
TBSCertificate|zero verify_ca_certificate(string|TBSCertificate tbs)
Verifies that all extensions mandated for certificate signing certificates are present and valid.
TBSCertificate|zero verify_certificate(string s, mapping(string:Verifier|array(Verifier)) authorities, mapping(Standards.ASN1.Types.Identifier:Crypto.Hash)|void options)
Decodes a certificate, checks the signature. Returns the TBSCertificate structure, or 0 if decoding or verification fails. The valid time range for the certificate is not checked.
authoritiesA mapping from (DER-encoded) names to a verifiers.
options | A mapping of verifier algorithm identifier to hash algorithm implementation. |
This function allows self-signed certificates, and it doesn't check that names or extensions make sense.
mapping verify_certificate_chain(array(string|.PKCS.Signature.Signed) cert_chain, mapping(string:Verifier|array(Verifier)) authorities, int|void require_trust, mapping(string:mixed)|bool|void options)
Decodes a certificate chain, ordered from leaf to root, and checks the signatures. Verifies that the chain can be decoded correctly, is unbroken, and that all certificates are in effect (time-wise.) and allowed to sign its child certificate.
No verifications are done on the leaf certificate to determine what it can and can not be used for.
Returns a mapping with the following contents, depending on the verification of the certificate chain:
| Error describing type of verification failures, if
verification failed. May be one of the following, OR:ed
together: |
| Index number of the certificate that caused the verification failure. |
| Non-zero if the certificate is self-signed. |
| Non-zero if the certificate is verified. |
| The authority RDN that verified the chain. |
| The common name RDN of the leaf certificate. |
| An array with the decoded certificates, ordered from root to leaf. |
cert_chainAn array of certificates, with the relative-root last. Each
certificate should be a DER-encoded certificate, or decoded as a
Standards.PKCS.Signature.Signed object.
authoritiesA mapping from (DER-encoded) names to verifiers.
require_trustRequire that the certificate be traced to an authority, even if it is self signed.
strictBy default this function only requires that the certificates are in order, it ignores extra certificates we didn't need to verify the leaf certificate.
If you specify strict, this will change, each certificate has
to be signed by the next in the chain.
Some https-servers send extraneous intermediate certificates that aren't used to validate the leaf certificate. So strict mode will be incompatible with such srevers.
options | A mapping of verifier algorithm identifier to hash algorithm implementation. |
| See |
get_algorithms()
See Standards.PKCS.Certificate.get_dn_string for converting the
RDN to an X500 style string.
constant Standards.X509.CERT_BAD_SIGNATURE
constant Standards.X509.CERT_CHAIN_BROKEN
constant Standards.X509.CERT_EXCEEDED_PATH_LENGTH
The certificate chain is longer than allowed by a certificate in the chain.
constant Standards.X509.CERT_INVALID
constant Standards.X509.CERT_ROOT_UNTRUSTED
constant Standards.X509.CERT_TOO_NEW
constant Standards.X509.CERT_TOO_OLD
constant Standards.X509.CERT_UNAUTHORIZED_CA
A CA certificate is not allowed by basic constraints to sign another certificate.
constant Standards.X509.CERT_UNAUTHORIZED_SIGNING
The certificate is not allowed by its key usage to sign data.
constant Standards.X509.KU_digitalSignature
constant Standards.X509.KU_nonRepudiation
constant Standards.X509.KU_keyEncipherment
constant Standards.X509.KU_dataEncipherment
constant Standards.X509.KU_keyAgreement
constant Standards.X509.KU_keyCertSign
constant Standards.X509.KU_cRLSign
constant Standards.X509.KU_encipherOnly
constant Standards.X509.KU_decipherOnly
constant Standards.X509.KU_last_keyUsage
Unique identifier for the certificate issuer.
X.509v2 (deprecated).
inherit BitString : BitString
Unique identifier for the certificate subject.
X.509v2 (deprecated).
inherit BitString : BitString
Represents a TBSCertificate.
Was not compatible with Standards.ASN1.Types.Sequence
prior to Pike 8.0.
inherit Sequence : Sequence
void Standards.X509.TBSCertificate.algorithm
Algorithm Identifier.
multiset Standards.X509.TBSCertificate.critical
optional
Read only
void Standards.X509.TBSCertificate.der
bool Standards.X509.TBSCertificate.ext_authorityKeyIdentifier
Set if the certificate contains a valid authorityKeyIdentifier extension. RFC 3280 section 4.2.1.1.
Gmp.mpz Standards.X509.TBSCertificate.ext_authorityKeyIdentifier_authorityCertSerialNumber
Set to the CertificateSerialNumber, if set in the extension.
string Standards.X509.TBSCertificate.ext_authorityKeyIdentifier_keyIdentifier
Set to the KeyIdentifier, if set in the extension.
bool Standards.X509.TBSCertificate.ext_basicConstraints
Set if the certificate contains a valid basicConstraints extension. RFC 3280 section 4.2.1.10.
bool Standards.X509.TBSCertificate.ext_basicConstraints_cA
If set, the certificate may be used as a CA certificate, i.e. sign other certificates.
int Standards.X509.TBSCertificate.ext_basicConstraints_pathLenConstraint
The maximum number of certificates that may follow this
certificate in a certificate chain. 0 in case no limit
is imposed. Note that this variable is off by one compared to
the RFC 3280 definition, which only counts intermediate
certificates (i.e. 0 intermediates means this variable would be
1, as in one following certificate).
array(Identifier) Standards.X509.TBSCertificate.ext_extKeyUsage
Set to the list of extended key usages from anyExtendedKeyUsage,
if the certificate contains the extKeyUsage extensions. These
Identifier objects are typically found in
.PKCS.Identifiers.reverse_kp_ids. RFC 3280 section 4.2.1.13.
keyUsage Standards.X509.TBSCertificate.ext_keyUsage
Set to the value of the KeyUsage if the certificate contains the keyUsage extension. RFC 3280 section 4.2.1.3.
string Standards.X509.TBSCertificate.ext_subjectKeyIdentifier
Set to the value of the SubjectKeyIdentifier if the certificate contains the subjectKeyIdentifier extension. RFC 3280 section 4.2.1.2.
mapping(Identifier:Object) Standards.X509.TBSCertificate.extensions
optional
Read only
Crypto.Hash Standards.X509.TBSCertificate.hash
Algorithm hash if known and supported.
Otherwise UNDEFINED.
Read only
protected multiset Standards.X509.TBSCertificate.internal_critical
optional
protected mapping(Identifier:Object) Standards.X509.TBSCertificate.internal_extensions
optional
void Standards.X509.TBSCertificate.issuer
Certificate issuer.
void Standards.X509.TBSCertificate.issuer_id
optional
void Standards.X509.TBSCertificate.keyinfo
void Standards.X509.TBSCertificate.not_after
void Standards.X509.TBSCertificate.not_before
void Standards.X509.TBSCertificate.public_key
void Standards.X509.TBSCertificate.raw_extensions
The raw ASN.1 objects from which extensions and critical
have been generated.
optional
void Standards.X509.TBSCertificate.serial
void Standards.X509.TBSCertificate.subject
void Standards.X509.TBSCertificate.subject_id
optional
void Standards.X509.TBSCertificate.validity
void Standards.X509.TBSCertificate.version
string dn_str(Sequence dn)
Try to extract a readable name from dn. This is one of
commonName, organizationName or organizationUnitName. The first
that is found is returned. Suitable for subjects and issuer
sequences.
this_program init(array|Object asn1)
Populates the object from a certificate decoded into an ASN.1
Object. Returns the object on success, otherwise 0. You
probably want to call decode_certificate or even
verify_certificate.
string issuer_str()
Return the issuer of the certificate as a human readable string. Mainly useful for debug.
protected void low_set(int index, Sequence|Integer val)
indexIndex in a v1 certificate.
valNew value for index.
string subject_str()
Attempt to create a presentable string from the subject DER.
bool verify(Sequence algorithm, string(8bit) msg, string(8bit) signature, mapping(Identifier:Crypto.Hash)|void verifier_algorithms)
Verifies the signature of the certificate msg using the
indicated hash algorithm, choosing from verifier_algorithms.
get_algorithms()
Helper module for generating Windows Installer XML structures.
Parser.XML.Tree.SimpleNode
WixNode get_module_xml(Directory dir, string id, string version, string|void manufacturer, string|void description, string|void guid, string|void comments, string|void installer_version)
Modifies dir if it contains files at the root level.
mapping decode(Stdio.Buffer document)
mapping decode(string(8bit) document)
inherit __builtin.Sql.Connection : Connection
This module embodies common operating system calls, making them available to the Pike programmer.
inherit _system : _system
constant string System.CPU_TIME_IMPLEMENTATION
This string constant identifies the internal interface used to get the CPU time. It is an implementation detail - see rusage.c for possible values and their meanings.
gethrvtime, gauge
constant string System.CPU_TIME_IS_THREAD_LOCAL
This string constant tells whether or not the CPU time, returned
by e.g. gethrvtime, is thread local or not. The value is "yes"
if it is and "no" if it isn't. The value is also "no" if there is
no thread support.
gethrvtime, gauge
constant int System.CPU_TIME_RESOLUTION
The resolution of the CPU time, returned by e.g. gethrvtime, in
nanoseconds. It is -1 if the resolution isn't known.
gethrvtime, gauge
constant int System.HKEY_CLASSES_ROOT
constant int System.HKEY_LOCAL_MACHINE
constant int System.HKEY_CURRENT_USER
constant int System.HKEY_USERS
Root handles in the Windows registry.
These constants are only available on Win32 systems.
RegGetValue(), RegGetValues(), RegGetKeyNames()
constant System.ITIMER_PROF
Identifier for a timer that decrements both when the process is executing and when the system is executing on behalf of the process.
setitimer, getitimer
constant System.ITIMER_REAL
Identifier for a timer that decrements in real time.
setitimer, getitimer
constant System.ITIMER_VIRTUAL
Identifier for a timer that decrements only when the process is executing.
setitimer, getitimer
constant string System.REAL_TIME_IMPLEMENTATION
This string constant identifies the internal interface used to get the high resolution real time. It is an implementation detail - see rusage.c for possible values and their meanings.
gethrtime
constant string System.REAL_TIME_IS_MONOTONIC
This string constant tells whether or not the high resolution real
time returned by gethrtime, is monotonic or not. The value is
"yes" if it is and "no" if it isn't.
Monotonic time is not affected by clock adjustments that might happen to keep the calendaric clock in synch. It's therefore more suited to measure time intervals in programs.
gethrtime
constant int System.REAL_TIME_RESOLUTION
The resolution of the real time returned by gethrtime, in
nanoseconds. It is -1 if the resolution isn't known.
gethrtime
int AllocConsole()
Allocates a new console for the calling process.
Only available on certain Windows systems.
0 on success, non-zero otherwise.
int AttachConsole(int pid)
Attaches calling process to a specific console.
pidOnly available on certain Windows systems.
0 on success, non-zero otherwise.
int FreeConsole()
Detaches the calling process from its console.
Before calling this function, Stdio.stderr, Stdio.stdout and
Stdio.stdin must be closed.
Only available on certain Windows systems.
0 on success, non-zero otherwise.
string GetComputerName()
Retrieves the NetBIOS name of the local computer.
This function is Windows specific, and is not available on all systems.
int GetFileAttributes(string(8bit) filename)
Get the file attributes for the specified file.
This function is only available on Win32 systems.
SetFileAttributes()
mapping(string:mixed) GetNamedSecurityInfo(string name, int|void type, int|void flags)
This function is only available on some Win32 systems.
SetNamedSecurityInfo()
string GetUserName()
Retrieves the name of the user associated with the current thread.
This function is Windows specific, and is not available on all systems.
UserToken LogonUser(string username, string|zero domain, string|zero password, int|void logon_type, int|void logon_provider)
Logon a user.
usernameUser name of the user to login.
domainDomain to login on, or zero if local logon.
passwordPassword to login with (if required).
logon_typeOne of the following values:
| |
| |
| |
| This is the default. |
logon_providerOne of the following values:
| This is the default. |
Returns a login UserToken object on success, and zero on failure.
This function is only available on some Win32 systems.
array(mixed) LookupAccountName(string|int(0) sys, string account)
Returns 0 (zero) if the account was not found,
and an array containing the following on success:
| Array | |
|
|
| Domain name. |
| Account type. |
This function is only available on some Win32 systems.
string NetGetAnyDCName(string|int(0) server, string domain)
Get name of a domain controller from a server.
serverServer the domain exists on.
domainDomain to get a domain controller for.
Returns the name of a domain controller on success. Throws errors on failure.
This function is only available on some Win32 systems.
NetUserGetInfo(), NetUserEnum(),
NetGroupEnum(), NetLocalGroupEnum(),
NetUserGetGroups(), NetUserGetLocalGroups(),
NetGroupGetUsers(), NetLocalGroupGetMembers(),
NetGetDCName()
string NetGetDCName(string|int(0) server, string domain)
Get name of the domain controller from a server.
serverServer the domain exists on.
domainDomain to get the domain controller for.
Returns the name of the domain controller on success. Throws errors on failure.
This function is only available on some Win32 systems.
NetUserGetInfo(), NetUserEnum(),
NetGroupEnum(), NetLocalGroupEnum(),
NetUserGetGroups(), NetUserGetLocalGroups(),
NetGroupGetUsers(), NetLocalGroupGetMembers(),
NetGetAnyDCName()
array(string|array(string|int)) NetGroupEnum(string|int(0)|void server, int|void level)
Get information about network groups.
serverServer the groups exist on.
levelInformation level. One of:
|
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo(), NetUserEnum(),
NetLocalGroupEnum(), NetUserGetGroups(),
NetUserGetLocalGroups(), NetGroupGetUsers(),
NetLocalGroupGetMembers(), NetGetDCName(),
NetGetAnyDCName()
array(string|array(int|string)) NetGroupGetUsers(string|int(0) server, string group, int|void level)
Get information about group membership for a network group.
serverServer the groups exist on.
groupGroup to retrieve members for.
levelInformation level. One of:
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo(), NetUserEnum(),
NetGroupEnum(), NetLocalGroupEnum(),
NetUserGetGroups(), NetUserGetLocalGroups(),
NetLocalGroupGetMembers(), NetGetDCName(),
NetGetAnyDCName()
array(array(string|int)) NetLocalGroupEnum(string|int(0)|void server, int|void level)
Get information about local network groups.
serverServer the groups exist on.
levelInformation level. One of:
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo(), NetUserEnum(),
NetGroupEnum(), NetUserGetGroups(),
NetUserGetLocalGroups(), NetGroupGetUsers(),
NetLocalGroupGetMembers(), NetGetDCName(),
NetGetAnyDCName()
array(string|array(int|string)) NetLocalGroupGetMembers(string|int(0) server, string group, int|void level)
Get information about group membership for a network group.
serverServer the groups exist on.
groupGroup to retrieve members for.
levelInformation level. One of:
|
|
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo(), NetUserEnum(),
NetGroupEnum(), NetLocalGroupEnum(),
NetUserGetGroups(), NetUserGetLocalGroups(),
NetGroupGetUsers(), NetGetDCName(),
NetGetAnyDCName()
array(int|string) NetSessionEnum(string|int(0) server, string|int(0) client, string|int(0) user, int level)
Get session information.
levelOne of
|
|
|
|
|
This function is only available on some Win32 systems.
array(string|array(string|int)) NetUserEnum(string|int(0)|void server, int|void level, int|void filter)
Get information about network users.
serverServer the users exist on.
levelInformation level. One of:
|
|
|
|
|
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo(), NetGroupEnum()
NetLocalGroupEnum(), NetUserGetGroups(),
NetUserGetLocalGroups(), NetGroupGetUsers(),
NetLocalGroupGetMembers(), NetGetDCName(),
NetGetAnyDCName()
array(array(string|int)) NetUserGetGroups(string|int(0) server, string user, int|void level)
Get information about group membership for a network user.
serverServer the groups exist on.
userUser to retrieve groups for.
levelInformation level. One of:
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo(), NetUserEnum(),
NetGroupEnum(), NetLocalGroupEnum(),
NetUserGetLocalGroups(), NetGroupGetUsers(),
NetLocalGroupGetMembers(), NetGetDCName(),
NetGetAnyDCName()
string|array(string|int) NetUserGetInfo(string username, string|int(0) server, int|void level)
Get information about a network user.
usernameUser name of the user to get information about.
serverServer the user exists on.
levelInformation level. One of:
|
|
|
|
|
|
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserEnum(), NetGroupEnum()
NetLocalGroupEnum(), NetUserGetGroups(),
NetUserGetLocalGroups(), NetGroupGetUsers(),
NetLocalGroupGetMembers(), NetGetDCName(),
NetGetAnyDCName()
array(string) NetUserGetLocalGroups(string|int(0) server, string user, int|void level, int|void flags)
Get information about group membership for a local network user.
serverServer the groups exist on.
userUser to retrieve groups for.
levelInformation level. One of:
|
flagsZero, of one of the following:
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo(), NetUserEnum(),
NetGroupEnum(), NetLocalGroupEnum(),
NetUserGetGroups(), NetGroupGetUsers(),
NetLocalGroupGetMembers(), NetGetDCName(),
NetGetAnyDCName()
array(mixed) NetWkstaUserEnum(string|int(0) server, int level)
levelOne of
|
|
This function is only available on some Win32 systems.
int SetFileAttributes(string(8bit) filename)
Set the file attributes for the specified file.
This function is only available on Win32 systems.
GetFileAttributes()
int SetNamedSecurityInfo(string name, mapping(string:mixed) options)
This function is only available on some Win32 systems.
GetNamedSecurityInfo()
void chmod(string path, int mode)
Sets the protection mode of the specified path.
Throws errors on failure.
Stdio.File->open(), errno()
void chown(string path, int uid, int gid, void|int symlink)
Sets the owner and group of the specified path.
If symlink is set and path refers to a symlink, then the
owner and group for the symlink are set. Symlinks are dereferenced
otherwise.
Throws errors on failure.
This function is not available on all platforms. On some
platforms the symlink flag isn't supported. In that case, the
function does nothing if path is a symlink.
int chroot(string newroot)
int chroot(Stdio.File newroot)
Changes the root directory for this process to the indicated directory.
A nonzero value is returned if the call is successful. If
there's an error then zero is returned and errno is set
appropriately.
Since this function modifies the directory structure as seen from Pike, you have to modify the environment variables PIKE_MODULE_PATH and PIKE_INCLUDE_PATH to compensate for the new root-directory.
This function only exists on systems that have the chroot(2) system call.
The second variant only works on systems that also have the fchroot(2) system call.
On success the current working directory will be changed to
the new "/". This behavior was added in Pike 7.9.
This function could be interrupted by signals prior to Pike 7.9.
void cleargroups()
Clear the supplemental group access list.
Throws errors on failure.
This function is not available on all platforms.
setgroups(), initgroups(), getgroups()
void clonefile(string from, string to)
Copy a file from with copy-on-write semantics to the destination named
to.
This function is currently only available on macOS and Linux, and then
only when from and to reference a common file system with
copy-on-write support (e.g. an APFS volume).
hardlink(), symlink()
void closelog()
Document this function.
int daemon(int nochdir, int noclose)
Low level system daemon() function, see also Process.daemon()
void drop_privs(string user, void|string group, void|int exception)
Drops the process privileges to the provided user and
optionally group. If no group is provided the default group for
the user is used.
exceptionIf true, an error exception will be thrown if
bool dumpable(bool|void val)
Get and/or set whether this process should be able to dump core.
valOptional argument to set the core dumping state.
| Disable core dumping for this process. |
| Enable core dumping for this process. |
Returns 1 if this process currently is capable of dumping core,
and 0 (zero) if not.
This function is currently only available on some versions of Linux.
int endgrent()
Closes the /etc/groups file after using the getgrent function.
get_all_groups()
getgrent()
setgrent()
int endpwent()
Closes the passwd source opened by getpwent function using the
systemfunction endpwent(3).
Always 0 (zero)
get_all_users()
getpwent()
setpwent()
string|zero get_home()
Get the full path for the current user's home directory
the full path to the current user's home directory, or zero if the appropriate environment variables have not been set.
This method uses the standard environment variables for various systems to determine the home directory.
array(string) get_netinfo_property(string domain, string path, string property)
Queries a NetInfo server for property values at the given path.
domainNetInfo domain. Use "." for the local domain.
pathNetInfo path for the property.
propertyName of the property to return.
An array holding all property values. If the path or property
cannot be not found 0 is returned instead. If the NetInfo domain
is not found or cannot be queried an exception is thrown.
system.get_netinfo_property(".", "/locations/resolver", "domain"); ({ "idonex.se" })
Only available on operating systems which have NetInfo libraries installed.
string|zero get_user()
Get the username of the user that started the process.
the username of the user "associated" with the current process, or zero if a method to find this information does not exist on the current system.
On NT systems, this returns the user the current thread is running as, while on Unix-like systems this function returns the user that started the process (rather than the effective user)..
int getegid()
Get the effective group ID.
setuid, getuid, setgid, getgid,
seteuid, geteuid, setegid
int geteuid()
Get the effective user ID.
setuid, getuid, setgid, getgid,
seteuid, getegid, setegid
int getgid()
Get the real group ID.
setuid, getuid, setgid,
seteuid, geteuid, getegid, setegid
array(int|string|array(string)) getgrent()
Get a group entry from /etc/groups file.
getgrent interates thru the groups source and returns
one entry per call using the systemfunction getgrent(3).
Always call endgrent when done using getgrent!
An array with the information about the group
| Array | |
| Group name |
| Group password (encrypted) |
| ID of the group |
| Array with UIDs of group members |
get_all_groups()
getgrnam()
getgrgid()
array(int) getgroups()
Get the current supplemental group access list for this process.
Throws errors on failure.
This function is not available on all platforms.
setgroups(), cleargroups(), initgroups(),
getgid(), getgid(), getegid(), setegid()
array(string|array(string)) gethostbyaddr(string addr)
Returns an array with information about the specified IP address.
The returned array contains the same information as that returned
by gethostbyname().
This function only exists on systems that have the gethostbyaddr(2) or similar system call.
gethostbyname()
array(string|array(string)) gethostbyname(string hostname)
Returns an array with information about the specified host.
The returned array contains the following:
| Array | |
| Name of the host. |
| Array of IP numbers for the host. |
| Array of alternative names for the host. |
This function only exists on systems that have the gethostbyname(2) or similar system call.
gethostbyaddr()
string gethostname()
Returns a string with the name of the host.
This function only exists on systems that have the gethostname(2) or uname(2) system calls.
array(float) getitimer(int timer)
Shows the state of the selected timer.
| Array | |
| The interval of the timer. |
| The value of the timer. |
timerOne of ITIMER_REAL, ITIMER_VIRTUAL and ITIMER_PROF.
array(float) getloadavg()
Get system load averages.
| Array | |
| Load average over the last minute. |
| Load average over the last 5 minutes. |
| Load average over the last 15 minutes. |
int getpgrp(int|void pid)
Get the process group id for the process pid.
With no argguments or with 'pid' equal to zero,
returns the process group ID of this process.
Not all platforms support getting the process group for other processes.
Not supported on all platforms.
getpid, getppid
int getpid()
Returns the process ID of this process.
getppid, getpgrp
int getppid()
Returns the process ID of the parent process.
getpid, getpgrp
array(int|string) getpwent()
When first called, the getpwent function opens the passwd source
and returns the first record using the systemfunction getpwent(3).
For each following call, it returns the next record until EOF.
Call endpwent when done using getpwent.
An array with the information about the user
| Array | |
| Users username (loginname) |
| User password (encrypted) |
| Users ID |
| Users primary group ID |
| Users real name an possibly some other info |
| Users home directory |
| Users shell |
0 if EOF.
get_all_users()
getpwnam()
getpwent()
setpwent()
endpwent()
array(int) getrlimit(string resource)
Returns the current process limitation for the selected resource.
resource | The CPU time limit in seconds. |
| The maximum size of files the process may create. |
| The maximum size of the process's data segment. |
| The maximum size of process stack, in bytes. |
| |
| Specifies the limit of pages the process's resident set. |
| The maximum number of processes that can be created for the real user ID of the calling process. |
| The maximum number of file descriptors the process can open, +1. |
| The maximum number of bytes of virtual memory that may be locked into RAM. |
| |
|
| Array | |
| The soft limit for the resource.
|
| The hard limit for the resource.
|
This function nor all the resources are available on all systems.
getrlimits, setrlimit
mapping(string:array(int)) getrlimits()
Returns all process limits in a mapping.
getrlimit, setrlimit
mapping(string:int) getrusage()
Return resource usage about the current process. An error is thrown if it isn't supported or if the system fails to return any information.
Returns a mapping describing the current resource usage:
| Time in milliseconds spent in user code. |
| Time in milliseconds spent in system calls. |
| Maximum used resident size in kilobytes. [1] |
| Quote from GNU libc: An integral value expressed in kilobytes times ticks of execution, which indicates the amount of memory used by text that was shared with other processes. [1] |
| Quote from GNU libc: An integral value expressed the same way, which is the amount of unshared memory used for data. [1] |
| Quote from GNU libc: An integral value expressed the same way, which is the amount of unshared memory used for stack space. [1] |
| Minor page faults, i.e. TLB misses which required no disk I/O. |
| Major page faults, i.e. paging with disk I/O required. |
| Number of times the process has been swapped out entirely. |
| Number of block input operations. |
| Number of block output operations. |
| Number of IPC messsages sent. |
| Number of IPC messsages received. |
| Number of signals received. |
| Number of voluntary context switches (usually to wait for some service). |
| Number of preemptions, i.e. context switches due to expired time slices, or when processes with higher priority were scheduled. |
| Number of system calls. [2] |
| Number of characters read and written. [2] |
| Elapsed real time (ms). [2] |
| Elapsed system trap (system call) time (ms). [2] |
| Text page fault sleep time (ms). [2] |
| Data page fault sleep time (ms). [2] |
| Kernel page fault sleep time (ms). [2] |
| User lock wait sleep time (ms). [2] |
| Other sleep time (ms). [2] |
| Wait CPU (latency) time (ms). [2] |
| Time spent in stopped (suspended) state. [2] |
| Heap size. [3] |
| Stack size. [3] |
[1] Not if /proc rusage is used.
[2] Only from (Solaris?) /proc rusage.
[3] Only from /proc PRS usage.
On some systems, only utime will be filled in.
gethrvtime()
int getsid(int|void pid)
Get the process session ID for the given process. If pid is not specified, the session ID for the current process will be returned.
This function is not available on all platforms.
Throws an error if the system call fails.
getpid, getpgrp, setsid
array(int) gettimeofday()
Calls gettimeofday(); the result is an array of seconds, microseconds, and possible tz_minuteswes, tz_dstttime as given by the gettimeofday(2) system call (read the man page).
time(), gethrtime()
int getuid()
Get the real user ID.
setuid, setgid, getgid, seteuid,
geteuid, setegid, getegid
void hardlink(string from, string to)
Create a hardlink named to from the file from.
This function is not available on all platforms.
symlink(), clonefile(), mv(), rm()
string(8bit) hw_random(int(0..) length)
Read a specified number of bytes from the hardware random generator, if available. This function will not exist if hardware random is not available. Currently only supports Intel RDRAND CPU instruction.
void initgroups(string name, int base_gid)
Initializes the supplemental group access list according to the system
group database. base_gid is also added to the group access
list.
Throws errors on failure.
This function is not available on all platforms.
setuid(), getuid(), setgid(), getgid(), seteuid(),
geteuid(), setegid(), getegid(), getgroups(), setgroups()
bool innetgr(string netgroup, string|void machine, string|void user, string|void domain)
Searches for matching entries in the netgroup database (usually
/etc/netgroup). If any of the machine, user or domain
arguments are zero or missing, those fields will match any
value in the selected netgroup.
This function isn't available on all platforms.
float nanosleep(int|float seconds)
Call the system nanosleep() function.
This is not to be confused with the global function predef::sleep()
that does more elaborate things and can sleep with better precision
(although dependant on a normal functioning system clock).
Returns the remaining time to sleep (as the system function does).
predef::sleep() sleep() usleep()
May not be present; only exists if the function exists in the current system.
utf8_string normalize_path(utf8_string path)
Normalize an existing MacOS X file system path.
The following transformations are currently done:
Relative paths are expanded to absolute paths.
Initial components "/private" and "/var/automount"
(or both) are removed if the result indicates the same
directory node.
Trailing slashes ('/') are removed.
Current- and parent-directory path components ("."
and "..") are followed, similar to combine_path.
Case-information in directory and file names is restored.
File fork information is stripped (ie all stuff after the first non-directory in the path is stripped).
A normalized absolute path without trailing slashes.
May throw errors on failure, e.g. if the file or directory doesn't
exist or if the path is not valid UTF-8.
combine_path()
utf8_string normalize_path(string(8bit) path)
Normalize an existing Windows file system path.
The following transformations are currently done:
If the path is not valid UTF-8, it will be converted
into UTF-8.
Forward slashes ('/') are converted to backward
slashes ('\').
Trailing slashes are removed, except a single slash after a
drive letter (e.g. "C:\" is returned instead of
"C:").
Extraneous empty extensions are removed.
Short filenames are expanded to their corresponding long variants.
Relative paths are expanded to absolute paths.
Current- and parent-directory path components ("."
and "..") are followed, similar to combine_path.
Case-information in directory and file names is restored.
Drive letters are returned in uppercase.
The host and share parts of UNC paths are returned in lowercase.
A normalized absolute path without trailing slashes.
Throws errors on failure, e.g. if the file or directory doesn't exist.
File fork information is currently not supported (invalid data).
In Pike 7.6 and earlier, this function didn't preserve a single slash after drive letters, and it didn't convert the host and share parts of an UNC path to lowercase.
combine_path(), combine_path_nt()
void openlog(string ident, int options, int facility)
Initializes the connection to syslogd.
ident.The ident argument specifies an identifier to tag all logentries
with.
optionsA bitfield specifying the behaviour of the message logging. Valid options are:
| Log the process ID with each message. |
| Write messages to the console if they can't be sent to syslogd. |
| Open the connection to syslogd now and not later. |
| Do not wait for subprocesses talking to syslogd. |
facilitySpecifies what subsystem you want to log as. Valid facilities are:
| Authorization subsystem |
| |
| Crontab subsystem |
| System daemons |
| Kernel subsystem (NOT USABLE) |
| For local use |
| |
| |
| |
| |
| |
| |
| |
| Line printer spooling system |
| Mail subsystem |
| Network news subsystem |
| |
| |
| UUCP subsystem |
Only available on systems with syslog(3).
LOG_NOWAIT should probably always be specified.
syslog, closelog
int rdtsc()
Executes the rdtsc (clock pulse counter) instruction and returns the result.
string readlink(string path)
Returns what the symbolic link path points to.
This function is not available on all platforms.
symlink()
string(8bit) resolvepath(string(8bit) path)
Resolve all symbolic links of a pathname.
This function resolves all symbolic links, extra ``/'' characters and
references to /./ and /../ in pathname, and returns the resulting
absolute path, or 0 (zero) if an error occurs.
This function is not available on all platforms.
readlink(), symlink()
int setegid(int egid)
Set the effective group ID to egid. If egid is
-1 the uid for "nobody" will be used.
Returns the current errno.
Throws an error if there is no "nobody" user when
egid is -1.
This function isn't available on all platforms.
int seteuid(int euid)
Set the effective user ID to euid. If euid is
-1 the uid for "nobody" will be used.
Returns the current errno.
Throws an error if there is no
"nobody" user when euid is -1.
This function isn't available on all platforms.
int setgid(int gid)
Sets the real group ID, effective group ID and saved group ID to gid.
If gid is -1 the uid for "nobody" will be used.
Throws an error if no "nobody" user when gid is -1.
Returns the current errno.
This function is not available on all platforms.
getuid(), setuid(), getgid(), seteuid(), geteuid(),
setegid(), getegid()
int setgrent()
Rewinds the getgrent pointer to the first entry
get_all_groups()
getgrent()
endgrent()
void setgroups(array(int) gids)
Set the supplemental group access list for this process.
Throws errors on failure.
This function is not available on all platforms.
initgroups(), cleargroups(), getgroups(),
getgid(), getgid(), getegid(), setegid()
float setitimer(int timer, int|float value)
Sets the timer to the supplied value. Returns the
current timer interval.
timerOne of ITIMER_REAL, ITIMER_VIRTUAL and ITIMER_PROF.
int setpgrp()
Make this process a process group leader.
Not supported on all platforms.
void setproctitle(string title, mixed ... extra)
Sets the processes title.
int setpwent()
Resets the getpwent function to the first entry in the passwd source
using the systemfunction setpwent(3).
Always 0 (zero)
get_all_users()
getpwent()
endpwent()
int setresgid(int rgid, int egid, int sgid)
Sets the real, effective and saved group ID to rgid,
egid and sgid respectively.
Returns zero on success and errno on failure.
int setresuid(int ruid, int euid, int suid)
Sets the real, effective and saved set-user-ID to ruid,
euid and suid respectively.
Returns zero on success and errno on failure.
bool setrlimit(string resource, int soft, int hard)
Sets the soft and the hard process limit on a resource.
getrlimit, getrlimits
int setsid()
Set a new process session ID for the current process, and return it.
This function isn't available on all platforms.
Throws an error if the system call fails.
getpid, setpgrp, getsid
int setuid(int uid)
Sets the real user ID, effective user ID and saved user ID to uid.
Returns the current errno.
This function isn't available on all platforms.
getuid(), setgid(), getgid(), seteuid(), geteuid(),
setegid(), getegid()
int sleep(int seconds)
Call the system sleep() function.
This is not to be confused with the global function predef::sleep()
that does more elaborate things and can sleep with better precision
(although dependant on a normal functioning system clock).
The system's sleep function often utilizes the alarm(2) call and might not be perfectly thread safe in combination with simultaneous sleep()'s or alarm()'s. It might also be interrupted by other signals.
If you don't need it to be independant of the system clock, use
predef::sleep() instead.
May not be present; only exists if the function exists in the current system.
predef::sleep() usleep() nanosleep()
void symlink(string from, string to)
Create a symbolic link named to that points to from.
This function is not available on all platforms.
hardlink(), readlink(), clonefile(), mv(), rm()
void sync()
Flush operating system disk buffers to permanent storage.
On some operating systems this may require administrative privileges.
void syslog(int priority, string msg)
Writes the message msg to the log with the priorities in
priority.
priorityPriority is a bit vector with the wanted priorities or:ed together.
| LOG_EMERG, system is unusable. |
| LOG_ALERT, action must be taken immediately. |
| LOG_CRIT, critical conditions. |
| LOG_ERR, error conditions. |
| LOG_WARNING, warnind conditions. |
| LOG_NOTICE, normal, but significant, condition. |
| LOG_INFO, informational message. |
| LOG_DEBUG, debug-level message. |
int umask(void|int mask)
Set the current umask to mask.
If mask is not specified the current umask will not be changed.
Returns the old umask setting.
mapping(string:string) uname()
Get operating system information.
The resulting mapping contains the following fields:
| Operating system name. |
| Hostname. |
| Operating system release. |
| Operating system version. |
| Hardware architecture. |
| Basic instruction set architecture. |
| List of upported instruction set architectures. Usually space-separated. |
| Specific model of hardware. |
| Manufacturer of the hardware. |
| Serial number of the hardware. |
| Secure RPC domain. |
This function only exists on systems that have the uname(2) or sysinfo(2) system calls.
Only the first five elements are always available.
void usleep(int usec)
Call the system usleep() function.
This is not to be confused with the global function predef::sleep()
that does more elaborate things and can sleep with better precision
(although dependant on a normal functioning system clock).
The system's usleep function often utilizes the alarm(2) call and might not be perfectly thread safe in combination with simultaneous sleep()'s or alarm()'s. It might also be interrupted by other signals.
If you don't need it to be independant of the system clock, use
predef::sleep() instead.
May not be present; only exists if the function exists in the current system.
predef::sleep() sleep() nanosleep()
void utime(string path, int atime, int mtime, void|int symlink)
Set the last access time and last modification time for the path
path to atime and mtime repectively. They are specified
as unix timestamps with 1 second resolution.
If symlink is set and path refers to a symlink, then the
timestamps for the symlink are set. Symlinks are dereferenced
otherwise.
Throws errors on failure.
This function is not available on all platforms. On some
platforms the symlink flag isn't supported. In that case, the
function does nothing if path is a symlink.
System.set_file_atime, System.set_file_mtime
A popular demand is a class representing a raw piece of memory or a mmap'ed file. This is usually not the most effective way of solving a problem, but it might help in rare situations.
Using mmap can lead to segmentation faults in some cases. Beware, and read about mmap before you try anything. Don't blame Pike if you shoot your foot off.
int sizeof( System.Memory arg )
returns the size of the memory (bytes). note: throws if not allocated
string(8bit) res = System.Memory()[start..end]
The range operator on the object gives a string containing the bytes in the range.
int(8bit) res = System.Memory()[ pos ]
Indexing the object returns the value of the byte at that position.
System.Memory()[ pos ] = char
Set the value of the byte at the specified position.
void allocate(int bytes)
void allocate(int bytes, int(8bit) fill)
(string)System.Memory()
(array)System.Memory()
Cast to string or array.
Throws if not allocated.
System.Memory System.Memory()
System.Memory System.Memory(string|Stdio.File filename_to_mmap)
System.Memory System.Memory(int shmkey, int shmsize, int shmflg)
System.Memory System.Memory(int bytes_to_allocate)
Will call mmap() or allocate()
depending on argument, either mmap'ing a file
(in shared mode, writeable if possible) or allocating
a chunk of memory.
void free()
Free the allocated or <tt>mmap</tt>ed memory.
int mmap(string|Stdio.File file)
int mmap(string|Stdio.File file, int offset, int size)
int mmap_private(string|Stdio.File file)
int mmap_private(string|Stdio.File file, int offset, int size)
mmap a file. This will always try to mmap the file in PROT_READ|PROT_WRITE, readable and writable, but if it fails it will try once more in PROT_READ only.
string(8bit) pread(int(0..) pos, int(0..) len)
string(16bit) pread16(int(0..) pos, int(0..) len)
string pread32(int(0..) pos, int(0..) len)
string(16bit) pread16i(int(0..) pos, int(0..) len)
string pread32i(int(0..) pos, int(0..) len)
string(16bit) pread16n(int(0..) pos, int(0..) len)
string pread32n(int(0..) pos, int(0..) len)
Read a string from the memory. The 16 and 32 variants reads widestrings, 16 or 32 bits (2 or 4 bytes) wide, the i variants in intel byteorder, the normal in network byteorder, and the n variants in native byteorder.
len is the number of characters, wide or not. pos
is the byte position (!).
int pwrite(int(0..) pos, string data)
int pwrite16(int(0..) pos, string data)
int pwrite32(int(0..) pos, string data)
int pwrite16i(int(0..) pos, string data)
int pwrite32i(int(0..) pos, string data)
Write a string to the memory (and to the file, if it's mmap()ed). The 16 and 32 variants writes widestrings, 16 or 32 bits (2 or 4 bytes) wide, the 'i' variants in intel byteorder, the other in network byteorder.
returns the number of bytes (not characters) written
bool valid()
returns 1 if the memory is valid, 0 if not allocated
bool writeable()
returns 1 if the memory is writeable, 0 if not
Security Identifier.
Objects of this class are returned by LookupAccountName().
LookupAccountName()
bool res = System.SID() == x
array(string|int) account(string|void sys)
Returns an array with the following content:
| Array | |
| Account name. |
| Domain name. |
| Account type. |
Returns an array with three zeroes on failure.
This function is only available on some Win32 systems.
System.SecurityContext System.SecurityContext(string pkgName)
array(string|int) gen_context(string)
array(string|int) get_last_context()
int get_last_error()
string get_username()
int is_done()
string type()
A wrapper for the system struct tm time keeping structure. This can be used as a (very) lightweight alternative to Calendar.
int System.TM.gmtoff
The offset from GMT for the time in this tm-struct
int(0..60) System.TM.sec
int(0..59) System.TM.min
int(0..59) System.TM.hour
int(1..31) System.TM.mday
int(0..11) System.TM.mon
int System.TM.year
The various fields in the structure. Note that setting these might cause other fields to be recalculated, as an example, adding 1000 to the hour field would advance the 'mday', 'mon' and possibly 'year' fields.
When read the fields are always normalized.
Unlike the system struct tm the 'year' field is not year-1900, instead it is the actual year.
int System.TM.isdst
True if daylight-saving is in effect. If this field is -1 (the default) it (and the timezone info) will be updated automatically using the timezone rules.
int System.TM.wday
The day of the week, sunday is 0, saturday is 6. This is calculated from the other fields and can not be changed directly.
int System.TM.yday
The day of the year, from 0 (the first day) to 365 This is calculated from the other fields and can not be changed directly.
string|zero System.TM.zone
The timezone of this structure
string asctime()
Return a string representing the time. Mostly useful for debug purposes.
In versions of Pike prior to Pike 8.0.1866 the exact format
was very locale (see Gettext.setlocale) and OS dependent.
(int)System.TM()
(string)System.TM()
Casted to an integer unix_time will be returned.
Casting to a string will call asctime.
System.TM System.TM()
Construct a new TM, all fields will be set to 0.
System.TM System.TM(int|Gmp.mpz t)
Create a new TM initialized from a unix time_t.
The timezone will always be UTC when using this function.
System.TM System.TM(int year, int(0..11) mon, int(1..31) mday, int(0..24) hour, int(0..59) min, int(0..59) sec, string|void timezone)
Construct a new time using the given values. Slightly faster than setting them individually.
bool gmtime(int time)
Initialize the struct tm to the UTC time for the specified unix time_t.
bool gmtime(Gmp.mpz time)
Initialize the struct tm to the UTC time for the specified unix time_t.
bool localtime(int time)
Initialize the struct tm to the local time for the specified unix time_t.
string(1..255) strftime(string(1..255) format)
Format the timestamp into a string.
See predef::strftime() for details.
strptime(), predef::strftime(), predef::strptime(),
Gettext.setlocale()
bool strptime(string(1..255) format, string(1..255) data)
The order of format and data are reversed
compared to predef::strptime().
strftime(), predef::strftime(), predef::strptime()
int unix_time()
Return the unix time corresponding to this time_t. If no time can be parsed from the structure -1 is returned.
The current time as a structure containing a sec and a usec member.
int System.Time.sec
int System.Time.usec
The number of seconds and microseconds since the epoch and the
last whole second, respectively. (See also predef::time())
Please note that these variables will continually update when they are requested, there is no need to create new Time() objects.
int System.Time.usec_full
The number of microseconds since the epoch. Please note that pike needs to have been compiled with bignum support for this variable to contain sensible values.
System.Time System.Time(int fast)
If fast is true, do not request a new time from the system,
instead use the global current time variable.
This will only work in callbacks, but can save significant amounts of CPU.
System.Timer System.Timer(int|void fast)
Create a new timer object. The timer keeps track of relative time with sub-second precision.
If fast is specified, the timer will not do system calls to get
the current time but instead use the one maintained by pike. This
will result in faster but more or less inexact timekeeping.
The pike maintained time is only updated when a Pike.Backend
object stops waiting and starts executing code.
float get()
Return the time in seconds since the last time get was called. The first time this method is called the time since the object was created is returned instead.
float peek()
Return the time in seconds since the last time get was called.
inherit System._FSEvents : _FSEvents
The System.FSEvents module provides an interface to FSEvents.
FSEvents is an API in Mac OS X which allows an application to register
for notifications of changes to a given directory tree without forcing
the application to continously poll the directory tree.
This module is designed for use in asynchronous, or backend mode. That is, rather than polling for changes, a function you specify will be called when events of interest occur.
This module requires the presence and use of a CFRunLoop based Backend object, otherwise this module will not receive events from the OS. CFRunLoop based backends are avilable on Mac OS X 10.5 and higher.
Pike.PollDeviceBackend.enable_core_foundation
constant System.FSEvents.kFSEventStreamCreateFlagFileEvents
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamCreateFlagIgnoreSelf
Available in MacOS X 10.6 and newer.
constant System.FSEvents.kFSEventStreamCreateFlagNoDefer
constant System.FSEvents.kFSEventStreamCreateFlagNone
constant System.FSEvents.kFSEventStreamCreateFlagWatchRoot
constant System.FSEvents.kFSEventStreamEventFlagChangeOwner
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventFlagEventIdsWrapped
constant System.FSEvents.kFSEventStreamEventFlagFinderInfoMod
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventFlagHistoryDone
constant System.FSEvents.kFSEventStreamEventFlagInodeMetaMod
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventFlagIsDir
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventFlagIsFile
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventFlagIsSymlink
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventFlagItemCreated
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventFlagItemModified
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventFlagItemRemoved
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventFlagKernelDropped
constant System.FSEvents.kFSEventStreamEventFlagMount
constant System.FSEvents.kFSEventStreamEventFlagMustScanSubDirs
constant System.FSEvents.kFSEventStreamEventFlagNone
constant System.FSEvents.kFSEventStreamEventFlagRenamed
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventFlagRootChanged
constant System.FSEvents.kFSEventStreamEventFlagUnmount
constant System.FSEvents.kFSEventStreamEventFlagUserDropped
constant System.FSEvents.kFSEventStreamEventFlagXattrMod
Available in MacOS X 10.7 and newer.
constant System.FSEvents.kFSEventStreamEventIdSinceNow
string describe_event_flag(int mask)
describe the event flags associated with an event.
a string describing the flags set.
A variation of EventStream that provides a blocking interface.
A quirk of the underlying IO subsystem in CoreFoundation is that
there is exactly one runloop per thread. Because FSEvents uses
CoreFoundation, this means that there's no meaningful way to
specify which backend should process these events. Therefore,
always make sure that the thread you create the EventStream
object is the same one you read events from, otherwise
read_event will run not run the EventLoop that this
EventStream is registered with, resulting in events never being
delivered.
inherit .EventStream : EventStream
System.FSEvents.BlockingEventStream System.FSEvents.BlockingEventStream(array(string) paths, float latency, int|void since_when, int|void flags)
mixed read_event(void|float timeout)
wait for an event to be received, and return it.
timeoutan optional limit to the amount of time we're willing to wait
void add_path(string path)
Add a path to the monitor list.
paththis can only be called when the monitor is stopped.
System.FSEvents.EventStream System.FSEvents.EventStream(array(string) paths, float latency, int|void since_when, int|void flags)
Creates a new Public.System.FSEvents.EventStream object
pathsAn array with each element containing a path to a directory, signifying the root of a filesystem hierarchy to be watched for modifications.
Additional paths may be added later using add_path(), though only if the stream is stopped.
latencyThe number of seconds the service should wait after hearing about an event from the kernel before passing it along to the client via its callback. Specifying a larger value may result in more effective temporal coalescing, resulting in fewer callbacks and greater overall efficiency.
since_whenThe service will supply events that have happened after the given event ID. To ask for events "since now" pass the constant kFSEventStreamEventIdSinceNow. Do not pass zero for this value unless you want to receive events for the requested directories "since the beginning of time".
flagsFlags that modify the behavior of the stream being created. See Apple's FSEvents documentation for details of the various flags available.
void flush_async()
Requests that the FS Events service to flush out any events that have occurred but have not yet been delivered, due to the latency parameter that was supplied when the stream was created.
This flushing occurs asynchronously -- events most likely will not have been delivered by the time this call returns.
Only call this function after the stream has been started, via start().
void flush_sync()
Requests that the FS Events service to flush out any events that have occurred but have not yet been delivered, due to the latency parameter that was supplied when the stream was created.
Flushing synchronously when using this method; clients will have received all the callbacks by the time this call returns to them.
Only call this function after the stream has been started, via start().
int is_started()
Has start() been called?
void set_callback(function(:void) callback)
Sets the function that will be called when a file notification event is received.
The method signature for the callback is:
void event_callback(string path, int flags, int event_id)
void start()
Requests that new events be delivered to this EventStream.
If a value was supplied for the since_when parameter then "historical" events will be sent via your callback first, then a HistoryDone event, then "contemporary" events will be sent on an ongoing basis.
void stop()
Stops watching for new events.
This module implements an API to linux inotify. It is available on all kernels from version 2.6.13 onwards. Inotify offers fast and scalable file notifications.
constant System.Inotify.IN_ACCESS
constant System.Inotify.IN_ATTRIB
constant System.Inotify.IN_CLOSE
constant System.Inotify.IN_CLOSE_WRITE
constant System.Inotify.IN_CLOSE_NOWRITE
constant System.Inotify.IN_CREATE
constant System.Inotify.IN_DELETE
constant System.Inotify.IN_DELETE_SELF
constant System.Inotify.IN_MODIFY
constant System.Inotify.IN_MOVE_SELF
constant System.Inotify.IN_MOVED_FROM
constant System.Inotify.IN_MOVED_TO
constant System.Inotify.IN_OPEN
constant System.Inotify.IN_MOVE
constant System.Inotify.IN_CLOSE
constant System.Inotify.IN_DONT_FOLLOW
constant System.Inotify.IN_MASK_ADD
constant System.Inotify.IN_ONESHOT
constant System.Inotify.IN_ONLYDIR
constant System.Inotify.IN_IGNORED
constant System.Inotify.IN_ISDIR
constant System.Inotify.IN_Q_OVERFLOW
constant System.Inotify.IN_UNMOUNT
Please have a look at the inotify(7) manpage for information about these constants.
Some constants may not be available when the module has been compiled on a machine with linux kernel before 2.6.15. See the manpage for more details.
constant System.Inotify.IN_ALL_EVENTS
This is a derived constant that is not part of the standard inotify API. It is the union of all other constants.
string describe_mask(int mask)
Turn an event mask into a human readable representation. This is used for debugging purpose.
array(string|int) parse_event(string data)
Parses one inotify_event struct from data.
Returns an array consisting of
| Array | |
| The watch descriptor returned by |
| An integer that describes the event that occured. See the inotify manpage for a list of possible events and their numerical identifiers. |
| An integer cookie that can be used to group together different events that were triggered by moving a file from one location to another. |
| The name of the file. This will only be present if the
event happened to a file in a directory that was
watched, e.g. with |
| The length of the data that has been parsed. If the |
More convenient interface to inotify(7). Automatically reads events from the inotify file descriptor and parses them.
Objects of this class will be destructed when they go out of external
references. As such they behave differently from other classes which use
callbacks, e.g. Stdio.File.
The number of inotify instances is limited by ulimits.
inherit _Instance : _Instance
int add_watch(string filename, int mask, function(int, int, string, mixed ... :void) callback, mixed ... extra)
Add a watch for a certain file and a set of events specified by
mask. The function callback will be called when
such an event occurs. The arguments to the callback will be the
events mask, the cookie, the filename and extra.
Returns a watch descriptor which can be used to remove the watch.
When adding a second watch for the same file the old one
will be removed unless System.Inotify.IN_MASK_ADD is
contained in mask.
The mask of an event may be a subset of the mask given when adding the watch.
In case the watch is added for a regular file, the filename will be passed to the callback. In case the watch is added for a directory, the name of the file to which the event happened inside the directory will be concatenated.
Simple wrapper class that gives direct access to the inotify(7)
interface. On create an inotify instance is initiated by calling
inotify_init(2). Every object of this class has its own inotify
file descriptor. Use this class only if you want direct access to
the file descriptor to read from it manually. For a more user
friendly interface use System.Inotify.Instance.
System.Inotify.Instance
private function(int, int, int, string:void) System.Inotify._Instance.event_callback
Callback function that is called when an event is triggered.
set_event_callback(), query_event_callback()
int add_watch(string path, int mask)
Add a watch for a certain file or directory and specific events.
Adding more than one watch for a path will overwrite the
previous watch unless System.Inotify.IN_MASK_ADD is contained
in the mask.
pathPath of the file or directory.
maskInteger mask specifying the event type. This can be a
combination of different event types using bitwise OR.
See the inotify manpage for possible values and their
description. The values defined by the inotify header
file are exported by System.Inotify as constants
using the same names (e.g. System.Inotify.IN_CREATE).
Returns a watch descriptor on success, and -1
on filesystem-related failures, in which case errno()
will indicate the cause. These typically indicate time of
check, time of use race conditions. For other failures
errors are thrown.
Subdirectories are not watched. If you want to watch subdirectories as well, you need to add watches for them individually.
At creation of a watch for a directory, simulated
IN_CREATE-events with cookie 0x7fffffff will
be added for the initial contents of the directory.
This is to reduce the risk of losing state changes
due to races. Note that is is not known whether these
paths are in flux or not. Note also that there may
be multiple notifications for content that is created
at the moment the watch is created.
In old versions of Pike errors were thrown for all failures.
rm_watch(), parse_event()
function(int, int, int, string:void) get_event_callback()
Get the current event_callback.
set_event_callback(), event_callback, poll()
void poll()
Check for any pending events.
Any pending events will be read and parsed, and event_callback will
be called once for each event. The arguments to the event_callback
will be:
| Array | |
| The watch descriptor that was triggered. |
| The event that was triggerend (one of IN_*). |
| An integer cookie used to identify grouped events. |
| The name of the path segment (if any). |
This function is called by the backend when there are events pending.
set_event_callback()
int query_fd()
Returns the file descriptor associated with this inotify instance.
int rm_watch(int wd)
Remove a watch.
wdThe watch descriptor that was returned by add_watch().
void set_backend(Pike.Backend backend)
Set the backend used for callbacks.
set_event_callback(), set_nonblocking(), poll()
void set_blocking()
Disable backend callback mode.
The configured backend will stop calling poll(), so
poll() will need to be called by hand.
set_blocking(), poll()
void set_event_callback(function(int, int, int, string:void) cb)
Set the event_callback.
get_event_callback(), event_callback, poll()
void set_nonblocking()
Enable backend callback mode.
The configured backend will call poll() automatically
as soon as there are events pending.
set_blocking(), poll()
An interface to Windows filesystem change information.
constant System.Wnotify.FILE_NOTIFY_CHANGE_ATTRIBUTES
constant System.Wnotify.FILE_NOTIFY_CHANGE_DIR_NAME
constant System.Wnotify.FILE_NOTIFY_CHANGE_FILE_NAME
constant System.Wnotify.FILE_NOTIFY_CHANGE_LAST_WRITE
constant System.Wnotify.FILE_NOTIFY_CHANGE_SECURITY
constant System.Wnotify.FILE_NOTIFY_CHANGE_SIZE
void add_handle(NotificationHandle handle)
NotificationHandle|int poll(void|float timeout)
System.Wnotify.NotificationHandle System.Wnotify.NotificationHandle(string path, int watch_subtree, int filter)
int get_error()
Display a image on the screen. Requires GTK.
inherit GTK.Window : Window
typedef Standards.URI|string|Image.Image|Image.Layer|array(Image.Layer) Tools.PV.PVImage
The image types accepted. If the image is a string, it is assumed to be a filename of a image that can be loaded with Image.load. This includes URLs.
Image.Image get_as_image(PVImage i)
Return the current image as a Image object, with the alpha combining done.
void save(string filename, string|void format)
Write the image to a file. If no format is specified, PNG is used. The alpha combination is done on the image before it's saved.
void scale(float factor)
Scale the image before display with the specified factor.
void set_alpha_colors(Image.Color.Color c1, Image.Color.Color|void c2)
Set the colors used for the alpha combination. c2 is only used
for the Squares alpha mode.
set_alpha_mode()
void set_alpha_mode(AlphaMode m)
Set the alpha combining mode. m is one of Squares, Solid,
None and AlphaOnly.
void set_image(PVImage i)
Change the image.
The alpha combination modes.
Use set_alpha_mode() to change the mode.
constant Tools.PV.AlphaOnly
Only show the alpha channel (if any).
constant Tools.PV.None
Ignore alpha.
constant Tools.PV.Solid
Solid color.
constant Tools.PV.Squares
Checkerboard pattern (default).
Flags affecting autodoc extractor behaviour.
ProcessXML.extractXML(), MirarDocParser,
Tools.Standalone.extract_autodoc()
constant Tools.AutoDoc.FLAG_COMPAT
Attempt to be compatible with old Pike.
constant Tools.AutoDoc.FLAG_DEBUG
Full verbosity.
constant Tools.AutoDoc.FLAG_KEEP_GOING
Attempt to keep going after errors.
constant Tools.AutoDoc.FLAG_NORMAL
Normal verbosity.
constant Tools.AutoDoc.FLAG_NO_DYNAMIC
Reduce the amount of dynamic information in the generated files (line numbers, extractor version, extraction time, etc).
constant Tools.AutoDoc.FLAG_QUIET
Keep quiet about non-fatal errors.
constant Tools.AutoDoc.FLAG_VERBOSE
Extra verbosity.
constant Tools.AutoDoc.FLAG_VERB_MASK
Verbosity mask.
Base class for errors generated by the autodoc extraction system.
string Tools.AutoDoc.AutoDocError.message
Error message.
string Tools.AutoDoc.AutoDocError.part
Which part of the autodoc system.
SourcePosition Tools.AutoDoc.AutoDocError.position
protected local void __create__(SourcePosition position, string part, string message)
Tools.AutoDoc.AutoDocError Tools.AutoDoc.AutoDocError(SourcePosition position, string part, string message)
inherit Regexp.SimpleRegexp : is_example
protected inherit Regexp.SimpleRegexp : lastident
protected inherit Regexp.SimpleRegexp : megamagic
string magic(string s, int quote)
Convert a block of tab-indented text to a set of paragraphs.
A very special purpose Pike parser that can parse some selected elements of the Pike language...
protected inherit .PikeObjects : PikeObjects
constant string Tools.AutoDoc.PikeParser.EOF
The end of file marker.
constant int Tools.AutoDoc.PikeParser.WITH_NL
Newline indicator flag value.
SourcePosition Tools.AutoDoc.PikeParser.currentPosition
The current position in the source.
Tools.AutoDoc.PikeParser Tools.AutoDoc.PikeParser(string|void s, string|SourcePosition|void _filename, int|void line, .Flags|void flags)
string eat(multiset(string)|string token)
Consume one token, error if not (one of) the expected in token.
string eatIdentifier(void|int allowScopePrefix)
Expect an identifier.
Also ::ident, scope::ident.
This function also converts old-style getters and setters into new-style.
string eatLiteral()
Expect a literal constant.
parseLiteral()
int getReadDocComments()
Returns the number of documentation comments
that have been returned by readToken().
Type|zero literalType(string literal)
Returns the type of a literal. Currently only recognizes the top level type. Currently does not thoroughly check that the literal is syntactically valid.
string lookAhead(int offset, int|void with_newlines)
Peek offset tokens ahead, skipping newlines,
unless with_newlines is set.
peekToken()
Annotation|zero parseAnnotation()
Parse a single annotation from the token stream.
array(Annotation) parseAnnotations()
Parse a set of annotations from the token stream.
array parseArgList(int|void allowLiterals)
Parse the list of arguments in a function declaration.
allowLiteralsIf allowLiterals != 0 then you can write a literal or Pike idents as an argument, like:
void convert("jpeg", Image image, float quality)
For a literal arg, the argname[] string contains the literal and the corresponding argtypes element is 0
Expects that the arglist is followed by a ")".
ArrayType parseArray()
Parse an array type.
PikeObject|array(PikeObject)|Annotation parseDecl(mapping|void args)
Parse the next Pike declaration from the token stream.
parseDecl() reads ONLY THE HEAD, NOT the ";"
or "{" .. "}" !!!
FunctionType parseFunction()
Parse a function type.
string|void parseIdents()
Parse a '.'-separated identitifer string.
Also parses stuff preceded by "scope::" or "::"
IntType parseInt()
Parse an integer type.
string|zero parseLiteral()
Parse the next literal constant (if any) from the token stream.
MappingType parseMapping()
Parse a mapping type.
array(string) parseModifiers()
Parse a set of modifiers from the token stream.
MultisetType parseMultiset()
Parse a multiset type.
Type parseOrType()
Parse a union type.
StringType parseString()
Parse a string type.
string peekToken(int|void with_newlines)
Peek at the next token in the stream without advancing.
with_newlinesIf set will return "\n" tokens, these will
otherwise silently be skipped.
Returns the next token.
readToken(), lookAhead()
string readToken(int|void with_newlines)
Read the next token from the stream and advance.
with_newlinesIf set will return "\n" tokens, these will
otherwise silently be skipped.
Returns the next token.
peekToken()
void setTokens(array(string) t, array(int) p)
void skip(multiset(string)|string tokens)
Skip the next token if it is a member of the tokens set.
The newline token ("\n") is not skipped implicitly
by this function.
readToken(), peekToken(), eat(), skipUntil()
array(string) skipBlock()
Skip passed a matched pair of parenthesis, brackets or braces.
void skipNewlines()
Skip past any newlines.
array(string) skipUntil(multiset(string)|string tokens)
Skip tokens until one of tokens is the next to read.
The newline token ("\n") is not skipped implicitly
by this function.
skip()
array(array(string)|array(int)) tokenize(string s, int line)
Tokenize a string of Pike code.
Class used to keep track of where in the source a piece of documentation originated.
string Tools.AutoDoc.SourcePosition.filename
int Tools.AutoDoc.SourcePosition.firstline
int Tools.AutoDoc.SourcePosition.lastline
Range of lines.
SourcePosition copy()
Returns a copy of the current object.
Tools.AutoDoc.SourcePosition Tools.AutoDoc.SourcePosition(string filename, int firstline, int|void lastline)
string xml(Flags|void flags)
Returns a string with an XML-fragment describing the source position.
inherit .PikeObjects : PikeObjects
constant Tools.AutoDoc.DocParser.EOF
End of file marker.
mapping(string:DocTokenType) Tools.AutoDoc.DocParser.keywordtype
The DocTokenTypes for the documentation @-keywords.
array(array(Token)) splitDocBlock(string block, SourcePosition position)
Split a block of documentation text into segments of Tokens
split on METAKEYWORDs.
Each of the arrays in the returned array can be fed to
Parse::create()
Enum of documentation token types.
constant Tools.AutoDoc.DocParser.BRACEKEYWORD
eg @i{@}
constant Tools.AutoDoc.DocParser.CONTAINERKEYWORD
eg @mapping
constant Tools.AutoDoc.DocParser.DELIMITERKEYWORD
eg @param
constant Tools.AutoDoc.DocParser.ENDKEYWORD
eg @endmapping
constant Tools.AutoDoc.DocParser.ENDTOKEN
End of documentation marker.
constant Tools.AutoDoc.DocParser.ERRORKEYWORD
eg @invalid
constant Tools.AutoDoc.DocParser.METAKEYWORD
eg @decl
constant Tools.AutoDoc.DocParser.SINGLEKEYWORD
None existant.
constant Tools.AutoDoc.DocParser.TEXTTOKEN
Documentation text.
Internal class for parsing documentation markup.
mapping(string:function(string, string:string)|function(string, string:mapping(string:string))) Tools.AutoDoc.DocParser.DocParserClass.argHandlers
Contains functions that handle keywords with non-standard arg list syntax. The function for each keyword can return a mapping or a string:
| If a |
| If a string is returned, it is an XML fragment that gets inserted inside the tag. |
SourcePosition Tools.AutoDoc.DocParser.DocParserClass.currentPosition
string getDoc(string context)
Returns the documentation corresponding to the context
as an XML string.
getMetaData() must be called before this function.
MetaData getMetaData()
Returns the MetaData for the documentation string.
Metadata about a Documentation object.
string Tools.AutoDoc.DocParser.MetaData.belongs
string Tools.AutoDoc.DocParser.MetaData.appears
Relocation information.
array(PikeObject) Tools.AutoDoc.DocParser.MetaData.decls
Set of declarations.
array(PikeObject) Tools.AutoDoc.DocParser.MetaData.inherits
Set of inherits.
string Tools.AutoDoc.DocParser.MetaData.name
If type is one of "class", "module",
"endmodule", or "endclass".
string Tools.AutoDoc.DocParser.MetaData.type
Type of documented entity.
Documentation markup parser.
This is a class, because you need to examine the meta lines before you can determine which context to parse the actual doc lines in.
inherit DocParserClass : DocParserClass
Tools.AutoDoc.DocParser.Parse Tools.AutoDoc.DocParser.Parse(string|array(Token) s, SourcePosition|void sp, .Flags|void flags)
Parse a documentation string s.
string|zero doc(string context)
Returns the documentation corresponding to the context
as an XML string.
metadata() must be called before this function.
MetaData metadata()
Returns the MetaData for the documentation string.
int Tools.AutoDoc.DocParser.Token.type
string|zero Tools.AutoDoc.DocParser.Token.keyword
string|zero Tools.AutoDoc.DocParser.Token.arg
string|zero Tools.AutoDoc.DocParser.Token.text
SourcePosition|zero Tools.AutoDoc.DocParser.Token.position
protected local void __create__(int type, string|zero keyword, string|zero arg, string|zero text, SourcePosition|zero position)
Tools.AutoDoc.DocParser.Token Tools.AutoDoc.DocParser.Token(int type, string|zero keyword, string|zero arg, string|zero text, SourcePosition|zero position)
protected inherit .DocParser : DocParser
void extractClass(AutoDoc root, Module parent, string s, void|string filename, void|string className, void|.Flags flags)
Extract documentation for a Pike class (aka program).
extractNamespace(), extractModule()
void extractModule(AutoDoc root, Module parent, string s, void|string filename, void|string moduleName, void|.Flags flags)
Extract documentation for a Pike module.
extractNamespace(), extractClass()
void extractNamespace(AutoDoc root, string s, void|string filename, void|string namespaceName, void|.Flags flags)
Extract documentation for a Pike namespace.
extractModule(), extractClass()
This module contains classes to represent Pike objects such as classes, modules, methods, variables ... The classes can produce XML representations of themselves.
protected inherit "module.pmod" : "module.pmod"
protected inherit Parser.XML.Tree : Tree
protected Documentation Tools.AutoDoc.PikeObjects.EmptyDoc
The empty Documentation.
Class representing an annotation.
The class for representing array types.
Type
inherit Type : Type
Type Tools.AutoDoc.PikeObjects.ArrayType.length
The length of the array.
Type Tools.AutoDoc.PikeObjects.ArrayType.valuetype
The Type of the array elements.
Tools.AutoDoc.PikeObjects.ArrayType Tools.AutoDoc.PikeObjects.ArrayType()
The class for representing attributed types.
Type
inherit Type : Type
string Tools.AutoDoc.PikeObjects.AttributeType.attribute
The name of the attribute.
int Tools.AutoDoc.PikeObjects.AttributeType.prefix
Flag indicating:
| The attribute is on the type. |
| The attribute is a prefix and acts as a modifier. This is only used for functions. |
Type Tools.AutoDoc.PikeObjects.AttributeType.subtype
The type that is attributed.
Tools.AutoDoc.PikeObjects.AttributeType Tools.AutoDoc.PikeObjects.AttributeType()
The top-level container. This container should only contain namespaces, and they in turn contain modules etc.
inherit _Class_or_Module : _Class_or_Module
constant string Tools.AutoDoc.PikeObjects.AutoDoc.objtype
Represents a class.
inherit _Class_or_Module : _Class_or_Module
constant string Tools.AutoDoc.PikeObjects.Class.objtype
Represents a named constant.
inherit PikeObject : PikeObject
constant string Tools.AutoDoc.PikeObjects.Constant.objtype
Type Tools.AutoDoc.PikeObjects.Constant.type
The type of the constant, if known.
Type Tools.AutoDoc.PikeObjects.Constant.typedefType
Typedef Type if it is a typedef.
Representation of an inherit.
inherit PikeObject : PikeObject
constant string Tools.AutoDoc.PikeObjects.CppDirective.objtype
A class associating a piece of Documentation
with a set of PikeObjects.
string Tools.AutoDoc.PikeObjects.DocGroup.appears
string Tools.AutoDoc.PikeObjects.DocGroup.belongs
Relocation information.
Documentation Tools.AutoDoc.PikeObjects.DocGroup.documentation
The Documentation for the objects.
array(PikeObject) Tools.AutoDoc.PikeObjects.DocGroup.objects
The set of PikeObjects that are documented.
Tools.AutoDoc.PikeObjects.DocGroup Tools.AutoDoc.PikeObjects.DocGroup(array(PikeObject) objs, Documentation|void doc)
string xml(.Flags|void flags)
Returns a string with an XML representation of the documentation.
The base class for documentation strings.
DocGroup
string|void Tools.AutoDoc.PikeObjects.Documentation.text
string|void Tools.AutoDoc.PikeObjects.Documentation.xml
SourcePosition|void Tools.AutoDoc.PikeObjects.Documentation.position
protected local void __create__(string|void text, string|void xml, SourcePosition|void position)
Tools.AutoDoc.PikeObjects.Documentation Tools.AutoDoc.PikeObjects.Documentation(string|void text, string|void xml, SourcePosition|void position)
The enum container.
inherit PikeObject : PikeObject
constant string Tools.AutoDoc.PikeObjects.Enum.objtype
array(DocGroup) Tools.AutoDoc.PikeObjects.Enum.children
The set of children.
Documentation Tools.AutoDoc.PikeObjects.Enum.documentation
Mimic the class { ... } behaviour.
void addChild(DocGroup c)
Adds c to the set of children.
void addGroup(DocGroup c)
Adds c to the set of children.
int containsDoc()
Returns 1 if there is any documentation
at all for this entity.
The values inside enum Foo { ... }
These are currently handled identically to normal constants.
inherit Constant : Constant
The class for representing the float type.
Type
inherit Type : Type
Tools.AutoDoc.PikeObjects.FloatType Tools.AutoDoc.PikeObjects.FloatType()
The class for representing function types.
Type
inherit Type : Type
array(Type) Tools.AutoDoc.PikeObjects.FunctionType.argtypes
An array with types for the arguments to the function.
Type Tools.AutoDoc.PikeObjects.FunctionType.returntype
The type for the return value of the function.
Tools.AutoDoc.PikeObjects.FunctionType Tools.AutoDoc.PikeObjects.FunctionType()
Represents a generic.
inherit Typedef : Typedef
constant string Tools.AutoDoc.PikeObjects.Generic.objtype
Type Tools.AutoDoc.PikeObjects.Generic.default_type
Default Type.
int Tools.AutoDoc.PikeObjects.Generic.generic_argument_number
Representation of an import.
inherit Inherit : Inherit
constant string Tools.AutoDoc.PikeObjects.Import.objtype
Representation of an inherit.
inherit PikeObject : PikeObject
constant string Tools.AutoDoc.PikeObjects.Inherit.objtype
array(Type) Tools.AutoDoc.PikeObjects.Inherit.bindings
Bindings (if any).
string Tools.AutoDoc.PikeObjects.Inherit.classname
Name of the class that is inherited.
The class for representing integer types.
Type
inherit Type : Type
string Tools.AutoDoc.PikeObjects.IntType.min
string Tools.AutoDoc.PikeObjects.IntType.max
The minimum and maximum range limits for the integer type.
Tools.AutoDoc.PikeObjects.IntType Tools.AutoDoc.PikeObjects.IntType()
The class for representing mapping types.
Type
inherit Type : Type
Type Tools.AutoDoc.PikeObjects.MappingType.indextype
Type Tools.AutoDoc.PikeObjects.MappingType.valuetype
The types for the indices and values of the mapping.
Tools.AutoDoc.PikeObjects.MappingType Tools.AutoDoc.PikeObjects.MappingType()
Represents a function.
inherit PikeObject : PikeObject
constant string Tools.AutoDoc.PikeObjects.Method.objtype
array(string) Tools.AutoDoc.PikeObjects.Method.argnames
The names of the arguments.
array(Type) Tools.AutoDoc.PikeObjects.Method.argtypes
The types for the arguments.
Type Tools.AutoDoc.PikeObjects.Method.returntype
The return type for the function.
The class for representing the mixed type.
Type
inherit Type : Type
Tools.AutoDoc.PikeObjects.MixedType Tools.AutoDoc.PikeObjects.MixedType()
A modifier range, e.g.:
final protected {
...
<<declarations>>
...
}
inherit _Class_or_Module : _Class_or_Module
constant string Tools.AutoDoc.PikeObjects.Modifier.objtype
Represents a module.
inherit _Class_or_Module : _Class_or_Module
constant string Tools.AutoDoc.PikeObjects.Module.objtype
The class for representing multiset types.
Type
inherit Type : Type
Type Tools.AutoDoc.PikeObjects.MultisetType.indextype
The type for the indices of the multiset.
Tools.AutoDoc.PikeObjects.MultisetType Tools.AutoDoc.PikeObjects.MultisetType()
Represents a name space, eg: predef:: or lfun::.
inherit _Class_or_Module : _Class_or_Module
constant string Tools.AutoDoc.PikeObjects.NameSpace.objtype
The class for representing object types.
Type
inherit Type : Type
string Tools.AutoDoc.PikeObjects.ObjectType.classname
The name of the class for the object.
Tools.AutoDoc.PikeObjects.ObjectType Tools.AutoDoc.PikeObjects.ObjectType()
The class for representing union types.
Type
inherit Type : Type
array(Type) Tools.AutoDoc.PikeObjects.OrType.types
An array with the types that are member of the union.
Tools.AutoDoc.PikeObjects.OrType Tools.AutoDoc.PikeObjects.OrType()
Base class for representing a documentable Pike lexical entity.
This class is inherited by classes for representing classes, functions, variables, etc.
Inherit, Import, Class, Module, NameSpace, AutoDoc,
Modifier, Method, Constant, Typedef, EnumConstant,
Enum, Variable
constant string Tools.AutoDoc.PikeObjects.PikeObject.objtype
The object type identifier.
string Tools.AutoDoc.PikeObjects.PikeObject.appears
string Tools.AutoDoc.PikeObjects.PikeObject.belongs
Relocation information.
array(string) Tools.AutoDoc.PikeObjects.PikeObject.modifiers
The set of modifiers affecting this entity.
string Tools.AutoDoc.PikeObjects.PikeObject.name
The name of the entity.
SourcePosition Tools.AutoDoc.PikeObjects.PikeObject.position
The source position where the entity was found.
Documentation Tools.AutoDoc.PikeObjects.PikeObject.squeezedInDoc
string print()
Returns a string with a Pike syntax representation of the entity.
string xml(.Flags|void flags)
Returns a string with an XML representation of the entity.
The class for representing program (aka class) types.
Type
inherit Type : Type
string Tools.AutoDoc.PikeObjects.ProgramType.classname
The name of the class (if any).
Tools.AutoDoc.PikeObjects.ProgramType Tools.AutoDoc.PikeObjects.ProgramType()
The class for representing string types.
Type
inherit Type : Type
string Tools.AutoDoc.PikeObjects.StringType.max
The maximum value for characters in the string.
string Tools.AutoDoc.PikeObjects.StringType.min
The minimum value for characters in the string.
Tools.AutoDoc.PikeObjects.StringType Tools.AutoDoc.PikeObjects.StringType()
The base class for representing types.
string Tools.AutoDoc.PikeObjects.Type.name
protected local void __create__(string name)
Tools.AutoDoc.PikeObjects.Type Tools.AutoDoc.PikeObjects.Type(string name)
string print()
Returns a string with a Pike-syntax representation of the type.
string xml(.Flags|void flags)
Returns a string with an XML representation of the type.
The class for representing type types.
Type
inherit Type : Type
Type Tools.AutoDoc.PikeObjects.TypeType.subtype
The subtype of the type.
Tools.AutoDoc.PikeObjects.TypeType Tools.AutoDoc.PikeObjects.TypeType()
Represents a typedef.
inherit PikeObject : PikeObject
constant string Tools.AutoDoc.PikeObjects.Typedef.objtype
Type Tools.AutoDoc.PikeObjects.Typedef.type
Typedef Type.
The class for representing the unknown type.
Type
inherit Type : Type
Tools.AutoDoc.PikeObjects.UnknownType Tools.AutoDoc.PikeObjects.UnknownType()
The class for representing varargs types.
Type
inherit Type : Type
Type Tools.AutoDoc.PikeObjects.VarargsType.type
The type that is varargs.
Tools.AutoDoc.PikeObjects.VarargsType Tools.AutoDoc.PikeObjects.VarargsType(Type t)
@Pike.Annotations.Implements(PikeObject)Represents a variable.
inherit PikeObject : PikeObject
constant string Tools.AutoDoc.PikeObjects.Variable.objtype
Type Tools.AutoDoc.PikeObjects.Variable.type
Type of the variable.
The class for representing the void type.
Type
inherit Type : Type
Tools.AutoDoc.PikeObjects.VoidType Tools.AutoDoc.PikeObjects.VoidType()
The class for representing the zero type.
Type
inherit Type : Type
Tools.AutoDoc.PikeObjects.ZeroType Tools.AutoDoc.PikeObjects.ZeroType()
Base class for representing classes, modules and namespaces.
Class, Module, NameSpace, AutoDoc, Modifier
inherit PikeObject : PikeObject
array(_Class_or_Module) Tools.AutoDoc.PikeObjects._Class_or_Module.children
Entities that are children to this entity.
array(DocGroup) Tools.AutoDoc.PikeObjects._Class_or_Module.docGroups
Documented entities that are children to this entity.
Documentation Tools.AutoDoc.PikeObjects._Class_or_Module.documentation
The documentation appears as a child of the <class> or <module>
array(array(string|PikeObject)) Tools.AutoDoc.PikeObjects._Class_or_Module.generics
Array of symbol followed by type and default type triples.
array(Inherit|Import) Tools.AutoDoc.PikeObjects._Class_or_Module.inherits
Inherits and Imports that affect the symbol lookup
for the entity.
void addChild(_Class_or_Module c)
Adds c to the set of children.
void addGroup(DocGroup d)
Adds d to the set of docGroups.
void addInherit(PikeObject p)
Adds p to the set of inherits.
int containsDoc()
Returns 1 if there is any documentation
at all for this entity.
PikeObject|zero findChild(string name)
Returns the first child with the name name if any.
DocGroup|zero findObject(string name)
Returns the first DocGroup that documents an entity
with the name name if any.
protected inherit "module.pmod" : "module.pmod"
protected inherit Parser.XML.Tree : Tree
string extractXML(string filename, int|void pikeMode, string|void type, string|void name, array(string)|void parentModules, void|.Flags flags)
This function extracts documentation from a file. The parameters
type, name, and parentModules are used only when
pikeMode != 0 and no C-style doc comments are present.
filenameThe file to extract from.
pikeModeNon-zero if it is a Pike file. If the file contains style doc comments, C-mode is used despite pikeMode != 0.
type"class", "module" or "namespace".
nameThe name of the class/module/namespace.
parentModulesThe ancestors of the class/module/namespace.
flagsFlags adjusting the extractor behaviour.
Defaults to FLAG_NORMAL.
// To extract doc for Foo.Bar.Ippa: string xml = extractXML("lib/modules/Foo.pmod/Bar.pmod/Ippa.pike", 1, "class", "Ippa", ({ "Foo", "Bar" }));
void handleAppears(SimpleNode root, .Flags|void flags)
Take care of all the @appears and @belongs directives everywhere, and rearranges the nodes in the tree accordingly
rootThe root (<autodoc>) node of the documentation tree.
void mergeTrees(SimpleNode dest, SimpleNode source)
Puts all children of source into the tree dest, in their
correct place module-hierarchically.
Used to merge the results of extractions of different Pike and C files.
Some minor effort is expended to normalize the result to some sort of canonical order.
sourcedestThe nodes source and dest are <class>, <module>,
<namespace> or <autodoc> nodes that are identical in
the sense that they represent the same module, class or namespace.
Typically they both represent <autodoc> nodes.
Both source and dest are modified destructively.
After calling this method, any <class> or <module> nodes
that have been marked with @appears or @belongs, are still in the
wrong place in the tree, so handleAppears() (or postProcess())
must be called on the whole documentation tree to relocate them once
the tree has been fully merged.
string moveImages(string docXMLFile, string imageSourceDir, string imageDestDir, int|void quiet)
Copy all images to canonical files in a flat directory.
docXMLFileThe contents of the XML file. The XML file is the result of extraction
from a single C or Pike file, for example the result of calling
extractXML.
imageSourceDirThe directory that is the base of the relative paths to images. This should be the directory of the source file that was the input to extract the XML file.
imageDestDirThe directory where the images should be copied.
quietQuiet operation.
The XML file contents (with decorated <image>-tags)
void postProcess(SimpleNode root, string|void logfile, .Flags|void flags)
Perform the last steps on a completed documentation tree.
rootRoot <autodoc> node of the completed documentation tree.
Calls handleAppears(), cleanUndocumented() and resolveRefs()
in turn.
handleAppears(), cleanUndocumented(), resolveRefs()
string Tools.AutoDoc.ProcessXML.DummyNScope.name
protected local void __create__(string name)
Tools.AutoDoc.ProcessXML.DummyNScope Tools.AutoDoc.ProcessXML.DummyNScope(string name)
A symbol lookup scope.
void addImplicitInherits(string|void fallback_namespace)
This function improves the symbol resolution by adding implicit inherits for modules in compatibility namespaces.
SimpleNode Tools.AutoDoc.ProcessXML.ReOrganizeTask.n
SimpleNode Tools.AutoDoc.ProcessXML.ReOrganizeTask.parent
protected local void __create__(SimpleNode n, SimpleNode parent)
Tools.AutoDoc.ProcessXML.ReOrganizeTask Tools.AutoDoc.ProcessXML.ReOrganizeTask(SimpleNode n, SimpleNode parent)
string|void Tools.AutoDoc.ProcessXML.Scope.type
string|void Tools.AutoDoc.ProcessXML.Scope.name
protected local void __create__(string|void type, string|void name)
Tools.AutoDoc.ProcessXML.Scope Tools.AutoDoc.ProcessXML.Scope(string|void type, string|void name)
string format_hr_time(int i)
Helper function that formats a time span in nanoseconds to something more human readable (ns, ms or s).
Abstract class for Hilfe commands.
string doc(string what, string with)
A more elaborate documentation of the command. This should be less than 68 characters per line.
void exec(Evaluator e, string line, array(string) words, array(string) tokens)
The actual command callback. Messages to the user should be
written out by using the safe_write method in the Evaluator
object.
string help(string|zero what)
Returns a one line description of the command. This help should be shorter than 54 characters.
Variable reset command. Put ___Hilfe->commands->reset = Tools.Hilfe.CommandReset(); in your .hilferc to have this command defined when you open Hilfe.
inherit Command : Command
inherit Command : Command
string Tools.Hilfe.CommandSet.Intwriter.type
function(:void) Tools.Hilfe.CommandSet.Intwriter.fallback
protected local void __create__(string type, function(:void) fallback)
Tools.Hilfe.CommandSet.Intwriter Tools.Hilfe.CommandSet.Intwriter(string type, function(:void) fallback)
string Tools.Hilfe.CommandSet.Reswriter.format
protected local void __create__(string format)
Tools.Hilfe.CommandSet.Reswriter Tools.Hilfe.CommandSet.Reswriter(string format)
This class implements the actual Hilfe interpreter. It is accessible as ___Hilfe from Hilfe expressions.
int Tools.Hilfe.Evaluator.assembler_debug_level
The current assembler debug level. Only available if Pike is compiled with RTL debug.
mapping(string:Command) Tools.Hilfe.Evaluator.commands
This mapping contains the available Hilfe commands, including the built in ones (dump, exit, help, new, quit), so it is possible to replace or remove them. The name of a command should be 10 characters or less.
int Tools.Hilfe.Evaluator.compiler_trace_level
The current compiler trace level. Only available if Pike is compiled with RTL debug.
mapping(string:mixed) Tools.Hilfe.Evaluator.constants
The locally defined constants (name:value).
int Tools.Hilfe.Evaluator.debug_level
The current debug level. Only available if Pike is compiled with RTL debug.
mapping(string:function(:void)) Tools.Hilfe.Evaluator.functions
The locally defined functions (name:value).
HilfeHistory Tools.Hilfe.Evaluator.history
The current result history.
array(string) Tools.Hilfe.Evaluator.imports
The current imports.
array(string) Tools.Hilfe.Evaluator.inherits
The current inherits.
int(0..) Tools.Hilfe.Evaluator.last_compile_time
The last compile time;
string Tools.Hilfe.Evaluator.last_compiled_expr
The last created wrapper in which an expression was evaluated.
bool Tools.Hilfe.Evaluator.last_else
Should an else expression be carried out?
int(0..) Tools.Hilfe.Evaluator.last_eval_time
The last evaluation time;
mapping(string:program) Tools.Hilfe.Evaluator.programs
The locally defined programs (name:value).
function(:void) Tools.Hilfe.Evaluator.reswrite
The function used to write results. Gets as arguments in order: The safe_write function (function(string, mixed ...:int), the result as a string (string), the history entry number (int), the result (mixed), the compilation time (int) and the evaluation time (int). If the evaluated expression didn't return anything (e.g. a for loop) then 0 will be given as the result string.
ParserState Tools.Hilfe.Evaluator.state
Keeps the state, e.g. multiline input in process etc.
bool Tools.Hilfe.Evaluator.strict_types
Strict types?
int Tools.Hilfe.Evaluator.trace_level
The current trace level.
mapping(string:string) Tools.Hilfe.Evaluator.types
The types of the locally defined variables (name:type).
mapping(string:mixed) Tools.Hilfe.Evaluator.variables
The locally defined variables (name:value).
bool Tools.Hilfe.Evaluator.warnings
Show warnings?
array|object|function(string:int(0..)) Tools.Hilfe.Evaluator.write
The function to use when writing to the user.
void add_buffer(string s)
Add buffer tokenizes the input string and determines if the
new line is a Hilfe command. If not, it updates the current
state with the new tokens and sends any and all complete
expressions to evaluation in parse_expression.
void add_input_hook(function(:void)|object new)
Adds a function to the input hook, making all user data be fed into the function.
remove_input_hook
void add_input_line(string s)
Input a line of text into Hilfe. It checks if s is
".", in which case it calls state->flush(). Otherwise
just calls add_buffer.
void add_writer(object|function(string:int(0..)) new)
Adds another output function.
void evaluate(string a, bool show_result)
Compiles the Pike code a and evaluates it by
calling ___HilfeWrapper in the generated object.
If show_result is set the result will be displayed
and the result buffer updated with its value.
object|zero hilfe_compile(string f, void|string new_var)
Creates a wrapper and compiles the pike code f in it.
If a new variable is compiled to be tested, its name
should be given in new_var so that magically defined
entities can be undefined and a warning printed.
string|zero parse_expression(Expression expr)
Parses a Pike expression. Returns 0 if everything went well, or a string with an error message otherwise.
void print_version()
Displays the current version of Hilfe.
void remove_input_hook(function(:void)|object old)
Removes a function from the input hook.
add_input_hook
void remove_writer(object|function(:void) old)
Removes an output function.
void reset_evaluator()
Clears the current state, history and removes all locally defined variables, constants, functions and programs. Removes all imports and inherits. It does not reset the command mapping nor reevaluate the .hilferc file.
int safe_write(array(string)|string in, mixed ... args)
An output method that shouldn't crash.
void std_reswrite(function(:void) w, string sres, int num, mixed res)
The standard reswrite function.
int Tools.Hilfe.Evaluator.HilfeCompileHandler.stack_level
protected local void __create__(int stack_level)
Represents a Pike expression
int sizeof( Tools.Hilfe.Expression arg )
The number of non-whitespace tokens in the expression.
string|zero res = Tools.Hilfe.Expression()[ f ]
Returns a token or a token range without whitespaces.
Tools.Hilfe.Expression()[ f ] = v
Replaces a token with a new token.
(int)Tools.Hilfe.Expression()
(float)Tools.Hilfe.Expression()
(string)Tools.Hilfe.Expression()
(array)Tools.Hilfe.Expression()
(mapping)Tools.Hilfe.Expression()
(multiset)Tools.Hilfe.Expression()
An Expression object can be cast to an array or a string. In both forms all tokens, including white spaces will be returned.
string|zero check_modifiers()
See if there are any forbidden modifiers used in the expression, e.g. "private int x;" is not valid inside Hilfe.
Returns an error message as a string if the expression
contains a forbidden modifier, otherwise 0.
string code()
Returns the expression verbatim.
Tools.Hilfe.Expression Tools.Hilfe.Expression(array(string) t)
tAn array of Pike tokens.
int depth(int f)
Return the parenthesis depth at the given position.
int(-1..) endoftype(int(-1..) position)
Returns at which position the type declaration that begins at
position position ends. A return value of -1 means that the
token or tokens from position can not be a type declaration.
int(-1..) find_matching(string token, int(0..)|void pos)
Returns the position of the matching parenthesis of the given kind, starting from the given position. The position should be the position after the opening parenthesis, or later. Assuming balanced code. Returns -1 on failure.
bool in_sscanf(int f)
Returns 1 if the current position is within a sscanf expression.
bool is_block(int pos)
Is there a block starting at pos?
inherit Evaluator : Evaluator
Stdio.File Tools.Hilfe.GenericAsyncHilfe.infile
Stdio.File Tools.Hilfe.GenericAsyncHilfe.outfile
protected local void __create__(Stdio.File infile, Stdio.File outfile)
inherit Evaluator : Evaluator
Tools.Hilfe.GenericHilfe Tools.Hilfe.GenericHilfe(Stdio.FILE in, Stdio.File out)
In every Hilfe object (Evaluator) there is a HilfeHistory
object that manages the result history. That history object is
accessible both from __ and ___Hilfe->history in Hilfe expressions.
inherit ADT.History(< mixed >) : History
In every Hilfe object (Evaluator) there is a ParserState object
that manages the current state of the parser. Essentially tokens are
entered in one end and complete expressions are output in the other.
The parser object is accessible as ___Hilfe->state from Hilfe expressions.
Evaluator Tools.Hilfe.ParserState.evaluator
protected local void __create__(Evaluator evaluator)
Tools.Hilfe.ParserState Tools.Hilfe.ParserState(Evaluator evaluator)
int datap()
Returns true if there is any waiting expression that can be fetched
with read.
void feed(array(string) tokens)
Feed more tokens into the state.
bool finishedp()
Are we in the middle of an expression. Used e.g. for changing the Hilfe prompt when entering multiline expressions.
void flush()
Clear the current state.
array(string)|zero push_string(string line)
Sends the input line to Parser.Pike for tokenization,
but keeps a state between each call to handle multiline
/**/ comments and multiline #"" strings.
array(Expression) read()
Read out completed expressions. Returns an array where every element is an expression represented as an array of tokens.
void show_error(function(array(string)|string, mixed ... :int) w)
Prints out any error that might have occurred while
push_string was executed. The error will be
printed with the print function w.
string status()
Returns the current parser state. Used by "dump state".
This is a wrapper containing a user interface to the Hilfe Evaluator
so that it can actually be used. This wrapper uses the Stdio.Readline
module to interface with the user. All input history is handled by
that module, and as a consequence loading and saving .hilfe_history is
handled in this class. Also .hilferc is handled by this class.
inherit Evaluator : Evaluator
Stdio.Readline Tools.Hilfe.StdinHilfe.readline
The readline object,
Tools.Hilfe.StdinHilfe Tools.Hilfe.StdinHilfe(void|array(string) init)
Any hilfe statements given in the init array will be executed once .hilferc has been executed.
void save_history()
Saves the user input history, if possible, when called.
Evaluator Tools.Hilfe.SubSysLogger.Logger.e
Stdio.File Tools.Hilfe.SubSysLogger.Logger.logfile
protected local void __create__(Evaluator e, Stdio.File logfile)
Common routines which are useful for various install scripts based on Pike.
array(string) features()
Return an array of enabled features.
Used by the master when given the option --features.
Tools.Standalone.features
string make_absolute_path(string path, string|void cwd)
A class keeping some methods and state to conveniently render ASCII progress bars to stdout.
Tools.Install.ProgressBar Tools.Install.ProgressBar(string name, int cur, int max, float|void phase_base, float|void phase_size)
nameThe name (printed in the first 13 columns of the row)
curHow much progress has been made so far
maxThe amount of progress signifying 100% done. Must be greater than zero.
void set_current(int _cur)
Change the amount of progress without updating on stdout.
void set_name(string _name)
Change the name of the progress bar without updating on stdout.
void set_phase(float _phase_base, float _phase_size)
int update(int increment)
Write the current look of the progressbar to stdout.
incrementthe number of increments closer to completion since last call
the length (in characters) of the line with the progressbar
inherit Stdio.Readline : Readline
string absolute_path(string path)
string edit(mixed ... args)
string edit_directory(mixed ... args)
string edit_filename(mixed ... args)
void set_cwd(string _cwd)
void trap_signal(int n)
Contains functions and information to store and present copyright information about Pike and it's components.
void add(string what, array(string) holders)
Adds a copyright message for the copyright holders for the
component what.
An error is thrown if the copyrighted component what is
already in the list of copyrights.
mapping(string:array(string)) get_all()
Returns a mapping containing all the stored copyrights. The mapping maps component name to an array of copyright holders.
string get_latest_pike()
Return the latest copyright holder of Pike.
string get_text()
Returns the copyrights as a string, suitable for saving as a file.
string get_text()
Returns all the licenses as a string, suitable for saving as a file.
GNU General Public License 2
string get_name()
Returns the name of the license.
string get_text()
Returns the text of the license.
string get_xml()
Returns an XML <pre>-fragment with the text of the license.
GNU Lesser General Public License 2.1
inherit .GPL : GPL
Mozilla Public License 1.1
string get_name()
Returns the name of the license.
string get_text()
Returns the text of the license.
string get_xml()
Returns an XML <pre>-fragment with the text of the license.
This is a small stub entrypoint to Parser.Markdown - it is exactly
equivalent to calling Parser.Markdown.parse().
This module contains usage strings for the master()->_main().
constant Tools.MasterHelp.environment_help
The set of environment variables that the default master looks at.
constant Tools.MasterHelp.kladdkaka_help
Useful recipe for when all else fails.
constant Tools.MasterHelp.opt_summary
Summary of the options for the Pike interpreter binary, and the default master.
constant Tools.MasterHelp.options_help
Complete set of options for the Pike interpreter binary, and the default master.
string do_help(string|int what)
Select a suitable help message.
int add_new_version(string module_name, string version, string changes, string license)
int delete_dependency(string module_name, string version, string dependency, string min_version, string max_version)
array get_dependencies(string module_name, string version)
void set_auth(string _username, string _password)
set the username and password for accessing the remote repository.
void set_default_directory()
sets the default directory for working and storing configurations ($HOME/.monger)
void set_default_repository()
sets the default repository location (modules.gotpike.org)
int set_dependency(string module_name, string version, string dependency, string min_version, string max_version, bool required)
void set_directory(string _directory)
sets the monger directory to use for working and storing configurations.
int set_module_source(string module_name, string version, string filename)
void set_repository(string _repository)
specify an alternate repository location.
this should be a URL specifying the XMLRPC endpoint for the repository.
int set_version_active(string module_name, string version, int active)
int update_version(string module_name, string version, string|void changes, string|void license)
int user_change_email(string|void _username, string _newemail)
int user_change_password(string|void _username, string _newpassword)
string Tools.Monger.MongerDeveloper.xmlrpc_handler._caller.n
protected local void __create__(string n)
Tools.Monger.MongerDeveloper.xmlrpc_handler._caller Tools.Monger.MongerDeveloper.xmlrpc_handler._caller(string n)
string format_big_number(int i)
Format an integer with SI-suffixes.
mapping(string:int|float|string) run(Test test, int maximum_seconds, __deprecated__(float)|void overhead)
Run a single benchmark test.
testBenchmark to run.
maximum_secondsNumber of seconds to run the test before terminating it.
overheadIgnored, obsolete.
Returns a mapping with the following fields on success:
| Actual number of seconds that the test ran. |
| Number of times that the test ran. |
| Number of sub tests that were run. |
| Description of the test result. |
| Number of sub tests per second. |
On benchmark failure a mapping with the single entry
"readable" set to "FAIL" is returned.
run_sub(), tests()
void run_sub(Test test, int maximum_seconds, __deprecated__(float)|void overhead)
Run a single benchmark test in the current process and return the result as JSON on stdout.
testBenchmark to run.
maximum_secondsNumber of seconds to run the test before terminating it.
overheadIgnored, obsolete.
Writes a JSON-encoded mapping with the following fields on success:
| Actual number of seconds that the test ran. |
| Number of times that the test ran. |
| Number of sub tests that were run. |
| Description of the test result. |
| Number of sub tests per second. |
On benchmark failure a JSON-encoded mapping with the single entry
"readable" set to "FAIL" is written to stdout.
This is the funcction that is called in a sub-process by run().
run(), tests()
mapping(string:Test) tests()
Return a mapping with all known and enabled benchmark tests.
Returns a mapping indexed on the display names of the benchmark tests.
constant string Tools.Shoot.Test.name
The name of the test.
int perform(mixed|void context)
perform() is the function called in the tests, when it returns the test is complete.
The function returns the number of whatever the test did.
optional mixed prepare()
If this function exists, it computes the context to pass to the perform() function. The time consumed by this function will not count towards the test.
AutoDoc XML to HTML converter.
tree_split
mapping Tools.Standalone.autodoc_to_html.lay
Layout template headers and trailers.
string image_prefix()
Path to where in the destination filesystem the images are.
string parse_text(Node n, void|String.Buffer ret, array(string)|void section_path)
Typically called with a <group/> node or a sub-node that is a container.
inherit .autodoc_to_html : autodoc_to_html
Node|zero lookup(string reference)
Perform a lexical lookup rooted in the current node.
Node|zero low_lookup(string sym)
Lookup a single symbol in the current node.
Fork Daemon
This is a light-weight daemon that can be used via Process.Process
to spawn new processes (by specifying the "forkd" modifier).
The typical use is when the main program is large and/or when it has lots of open file descriptors. This can cause considerable overhead in process creation.
Process.RemoteProcess, Process.create_process
This is the main control Stdio.Fd and is
always on fd number 3.
To spawn a new process, a new Stdio.PROP_SEND_FD
capable Stdio.Fd is sent over this fd, and a
single byte of data is sent as payload.
The sent fd will become a ForkFd inside a ForkStream.
inherit Stdio.File : File
This class maps 1 to 1 to Process.RemoteProcess, and implements the daemon side of the RPC protocol.
It contains an array (fds) with the file descriptors
that have been received so far from the remote.
inherit Stdio.File : File
array(Stdio.Fd) Tools.Standalone.forkd.ForkStream.fds
The remote file descriptors received so far in order.
Tool for converting the Pike git repository to a corresponding git repository containing the extracted autodoc.xml and documentation.
It supports incremental operation, so that it can be used to keep track with the source.
Typical use: pike -x git_export_autodoc -v --git-dir=Autodoc.git
mapping(string:string) Tools.Standalone.git_export_autodoc.autodoc_hash
Mapping from doc commit sha1 or export reference to sha1 for the autodoc.xml blob.
mapping(string:string) Tools.Standalone.git_export_autodoc.doc_refs
Mapping from doc reference to doc commit sha1 or export reference.
mapping(string:array(string)) Tools.Standalone.git_export_autodoc.doc_to_parents
Mapping from doc commit sha1 or export reference to array of same for its direct parents.
mapping(string:array(string)) Tools.Standalone.git_export_autodoc.doc_to_src
Mapping from doc commit sha1 or export reference to the corresponding list of source commit sha1s.
mapping(string:string) Tools.Standalone.git_export_autodoc.refdoc_hash
Mapping from source commit to refdoc sha1.
mapping(string:multiset(string)) Tools.Standalone.git_export_autodoc.rev_refs
Lookup from source commit sha1 to the corresponding references (if any).
mapping(string:string) Tools.Standalone.git_export_autodoc.src_refs
Mapping from source reference to source commit sha1.
mapping(string:string) Tools.Standalone.git_export_autodoc.src_to_doc
Mapping from source commit sha1 to doc commit sha1 or export reference.
string get_version()
Attempt to get the version for the Pike source tree.
Convert Pike code to HTML with syntax highlighting
pike -x pike_to_html /path/to/file.pike > file.html
string convert(string code)
Turn code into HTML.
The following css classes will be used:
Delimiters: delim
Reserved words: lang
Data types: type
Constants: const
Modifiers: mods
Root namespaces: ns
Strings: string
Comments: comment
Macros: macro
codea prototype installer for prepackaged modules
note: portions of this code are highly inefficient (wrt tar filehandling). we assume that this will be used infrequently enough that this is not going to be a problem.
a package file is a tar file that contains the following structure:
ROOTDIR/ METADATA.TXT a file containing metadata about the package format: KEY=value, where values include: PLATFORM, in the form of os/processor (either can be "any") MODULE, the name of the module, in Module.Submodule format. VERSION, the version of this module. MODULE/ any files that need to be installed in the module directory MODREF/ ??? documentation suitable for inclusion in the modref INCLUDE/ ??? any pike language include files to be installed SCRIPTS/ standalone (no bundled dependencies) scripts used to perform custom actions they receive the installer object (this) and the System.Filesystem object of the package archive as arguments to the constructor. The method "run()" should perform the actual action. The run() method should return true or false to indicate success or failure. preinstall.pike postinstall.pike
Convert .cmod-files to .c files.
array Tools.Standalone.precompile.ArgCheckFunction.tokens
protected local void __create__(array tokens)
Tools.Standalone.precompile.ArgCheckFunction Tools.Standalone.precompile.ArgCheckFunction(array tokens)
Boilerplate to quickly whip up rsif-like hacks for creating file processing to churn away at stdin, or files and/or directories provided on the command line, recursively or not, creating backup files or not, listing the paths of all files action was taken for, and returning an exit status of how many files that would have been taken action on which could not be written back.
The all-round quickest way of making one of these tools is nicking
the top portion of
lib/modules/Tools.pmod/Standalone.pmod/process_files.pike or
copying rsif.pike from the same directory. (The latter is 20
lines long, including docs, or about four lines of code.) Inherit
process_files, and define your own version, description,
usage, process, and, if you want arguments, want_args.
inherit Toole.Standalone.process_files : process_files
string Tools.Standalone.process_files.default_flag_docs
Flag docs to append to your usage description. Explains default options.
string Tools.Standalone.process_files.description
One-liner that gets shown for this tool when running pike -x without additional options. (Assuming your tool resides in Standalone.pmod.) Does not include the name of the tool itself; just provide a nice, terse description, ending with a period for conformity.
bool Tools.Standalone.process_files.overwrite
0 to make backups, 1 to overwrite (default)
bool Tools.Standalone.process_files.recursive
1 to recurse into directories, 0 not to (default)
string Tools.Standalone.process_files.usage
Long description of the purpose and usage of your tool, for --help and the case where not enough options are given on the command line. Its invocation mode (for instance "pike -x yourtool", when invoked that way) is prepended, and a list of available flags appended to this description.
int(0..) Tools.Standalone.process_files.verbosity
0 in quiet mode, 1 by default, above = more output
string Tools.Standalone.process_files.version
Your hack's version number. If you version control your file with cvs, we suggest you set the contents of this variable to something that that will automatically expand to a number for every new revision, for instance
string version = sprintf("%d.%d.%d",(int)__REAL_VERSION__,__REAL_MINOR__,__REAL_BUILD__);
int Tools.Standalone.process_files.want_args
The number of (mandatory) command-line options your hack needs and which
your process callback wants (beside the input file). By default 0.
int(0..) main(int argc, array(string) argv)
Base implementation of main program, handling basic flags and returning an exit status matching the number of failures during operation.
No easy way of adding your own command-line flags implemented yet. This would be a rather natural next feature to add, once somebody needs some.
string process(string input, string ... args)
Gets called with the contents of a file (or stdin). Return your output, or
0 if you didn't do anything. args are the first want_args
command-line options provided, before the list of files to process.
bool process_file(string path, string ... args)
Takes the path to a file and the first want_args command-line options
provided, before the list of files to process. You might want to override
this method if your tool needs to see file paths.
process_path
int(0..) process_path(string path, string ... args)
Takes the path to a file or directory and the first want_args first
command-line options provided, before the list of files to process. You
might want to override this method if your tool needs to see all paths.
process_file
void log_msg(string msg, mixed ... args)
Logs a testsuite message to stderr. The message is shown regardless of the verbosity level. If the previous message was logged without a trailing newline then a newline is inserted first.
The message should normally have a trailing newline - no extra
newline is added to it. Use log_status to log a message
intended to be overwritten.
void log_msg_cont(string msg, mixed ... args)
Similar to log_msg, but doesn't insert a newline first if the
previous message didn't end with one. Does however insert a
newline if the previous message was logged "in place" by
log_status.
void log_status(string msg, mixed ... args)
Logs a testsuite status message to stdout. This is suitable for nonimportant progress messages.
If the verbosity is 0 then nothing is logged, but the message is
saved and will be logged if the next call is to log_msg.
If the verbosity is 1, the message is "in place" on the current
line without a trailing line feed, so that the next
log_status message will replace this one.
If the verbosity is 2 or greater, the message is logged with a trailing line feed.
The message should be short and not contain newlines, to work when the verbosity is 1, but if it ends with a newline then it's logged normally. It can be an empty string to just clear the last "in place" logged message - it won't be logged otherwise.
log_twiddler
void log_twiddler()
Logs a rotating bar for showing progress. Only output at the end
of an "in place" message written by log_status on verbosity
level 1.
void report_result(int succeeded, int failed, void|int skipped)
Use this to report the number of successful, failed, and skipped
tests in a script started using run_script. Can be called
multiple times - the counts are accumulated.
array(int) run_script(string|array(string) pike_script)
Runs an external pike script from a testsuite. Use
Tools.Testsuite.report_result in the script to report how many
tests succeeded, failed, and were skipped. Those numbers are
returned in the array from this function.
@Pike.Annotations.Implements(Plugin)A source code plugin for running code in different Pike compat
modes. Instantiated with the pike compat version to run in,
e.g. "7.8".
inherit Plugin : Plugin
string Tools.Testsuite.CompatPlugin.pike_compat
protected local void __create__(string pike_compat)
Tools.Testsuite.CompatPlugin Tools.Testsuite.CompatPlugin(string pike_compat)
string preprocess(string source)
Modifies the source code to add "#pike" and the version at the top of the code, followed by "#pragma no_deprecation_warnings".
string process_name(string name)
Modifies the name by adding the version and "compat" after the test name, e.g. "testsuite:1: Test 1 (7.8 compat)".
Represents a "testsuite" file, after m4 processing.
inherit Testsuite : Testsuite
Represents a test case from a "testsuite" file, after m4 processing.
inherit Test : Test
Tools.Testsuite.M4Testsuite.M4Test Tools.Testsuite.M4Testsuite.M4Test(string data)
dataThe data from a testsuite file, after start/stop markers have been stripped and the file splitted on "...." tokens. From this the conditions, file, line, number, type and source will be parsed.
Interface for source code plugins, added to a Test by calling
add_plugin.
bool active(Test t)
Returns 1 if the plugin is active (i.e. should be called by the test), otherwise 0. Defaults to 1.
string preprocess(string source)
Called by the test to modify the source code. By default just returns the unmodified source.
string process_name(string name)
Allows for modifications of the name of the test. By default just returns the name unmodified.
Rerpesents a test in a testsuite.
array(string) Tools.Testsuite.Test.conditions
The list of conditions that has to be met for this test to not be skipped. Each condition should be an expression.
string Tools.Testsuite.Test.file
The file the testsuite (source) resides in.
bool|object Tools.Testsuite.Test.inhibit_errors
This value will be sent to MasterObject.set_inhibit_errors
before compilation by compile().
int(1..) Tools.Testsuite.Test.line
The line number offset to this test in the file.
int(1..) Tools.Testsuite.Test.number
The test number in this file.
string Tools.Testsuite.Test.source
The source code that is to be compiled and evaluated.
string Tools.Testsuite.Test.type
The type of the test. Any of
| Compiles the source and make verifies there are no warnings or errors. | ||||||||
| Compiles the source and expects to get a compilation error. | ||||||||
| Compiles the source and expects to get a compilation warning. | ||||||||
| Evaluates the method a of the source source and expects an evaluation error. | ||||||||
| Verifies that the response from method a of the source is false. | ||||||||
| Verifies that the response from method a of the source is true. | ||||||||
| Evaluate the method a and take the resulting string and push it to the set of ignored warnings. The same warning can be pushed multiple times, but must be popped multiple times. | ||||||||
| Evaluate the method a and take the resulting string and pop the warning from the set of ignored warnings. When popped the same number of times as it has been pushed, the warning is no longer ignored. | ||||||||
| Evaluate the method a and take the resulting string and push it to the set of expected compilation errors. The same error can be pushed multiple times, but must also be popped the same number of times. | ||||||||
| Evaluate the method a and take the resulting string and pop the expected compilation error from the set of expected compilation errors. When popped a testsuite failure is logged if the compilation error was not triggered since it was pushed. | ||||||||
| Compiles and evaluates method a of the source, but ignores the result. | ||||||||
| Compiles and evaluates method a od source, and expects an array(int) of two or three elements back.
| ||||||||
| Compares the result of the method a and b with | ||||||||
| Compares the result of the method a and b with | ||||||||
void add_plugin(Plugin p)
Add a Plugin object to the test, allowing the source code to
be modified.
program compile(string src)
Compile the source code src in the context of the file this
test belongs. Note that no changes in error mode is done and
compilation errors are not caught.
variant program compile()
Set the error mode according to inhibi_errors, applies any
source code plugins by calling prepare_source and finally
compiles the result. Any resulting compilation errors will be
stored in compilation_error. The error mode will be set to
0 after compiltion is done.
Tools.Testsuite.Test Tools.Testsuite.Test(string file, int line, int number, string type, string source, void|array(string) cond)
string name()
The name of this test, in the form of filename:line:" Test "number. The result is then processed by any code plugins.
string prepare_source()
Applies all the plugins on the source code contained in this test and returns the result.
protected local void __create__()
Tools.Testsuite.Test.AdjustLine Tools.Testsuite.Test.AdjustLine()
edit commands supported:
<firstline>,<lastline><edit command>
^^ numeral (17) ^^
or relative (+17, -17)
or a search regexp (/regexp/)
or multiple (17/regexp//regexp/+2)
| Command | Action |
| D | Delete first line in space |
| G | Insert hold space |
| H | Append current space to hold space |
| P | Print current data |
| a<string> | Insert |
| c<string> | Change current space |
| d | Delete current space |
| h | Copy current space to hold space |
| i<string> | Print string |
| l | Print current space |
| p | Print first line in data |
| q | Quit evaluating |
| s/regexp/with/x | Replace |
| y/chars/chars/ | Replace chars |
where line is numeral, first 'line'==0
protected string|array `()(string|array(string) commands, string|array(string) data, void|int suppress)
constant Unicode.version
Contains the version of the current Unicode database as a string,
e.g. "5.0.0".
int is_rtlchar(int c)
Returns 1 if the character is a RTL character or
indicator, otherwise 0.
int is_rtlstring(string s)
Returns 1 if the string contains RTL characters or
RTL indicators, otherwise 0.
bool is_whitespace(int c)
Returns 1 if the character is a white space character,
otherwise 0.
int is_wordchar(int c)
Returns whether a unicode character c is a word, part of a word or not.
| The character is an ideograph (a CJK single-word character) |
| The character is a letter, number or non-spacing mark, as defined by its unicode (general category) specification |
| Any other character (such as symbols, punctuation and separators) |
string normalize(string data, string method)
Normalize the given unicode string according to the specified method.
The methods are:
NFC, NFD, NFKC and NFKD.
The methods are described in detail in the UAX #15 document, which can currently be found at http://www.unicode.org/unicode/reports/tr15/tr15-21.html
A short description:
C and D specifies whether to decompose (D) complex characters to their parts, or compose (C) single characters to complex ones.
K specifies whether or not do a canonical or compatibility conversion. When K is present, compatibility transformations are performed as well as the canonical transformations.
In the following text, 'X' denotes the single character 'X', even if there is more than one character inside the quotation marks. The reson is that it's somewhat hard to describe unicode in iso-8859-1.
The Unicode Standard defines two equivalences between characters: canonical equivalence and compatibility equivalence. Canonical equivalence is a basic equivalency between characters or sequences of characters.
'Å' and 'A' '° (combining ring above)' are canonically equivalent.
For round-trip compatibility with existing standards, Unicode has encoded many entities that are really variants of existing nominal characters. The visual representations of these character are typically a subset of the possible visual representations of the nominal character. These are given compatibility decompositions in the standard. Because the characters are visually distinguished, replacing a character by a compatibility equivalent may lose formatting information unless supplemented by markup or styling.
Examples of compatibility equivalences:
Font variants (thin, italic, extra wide characters etc)
Circled and squared characters
super/subscript ('²' -> '2')
Fractions ('½' -> '1/2')
Other composed characters ('fi' -> 'f' 'i', 'kg' -> 'k' 'g')
array(string) split_words(string input)
Splits the input string into an array of words, on the boundaries between
the different kinds of word characters as defined by is_wordchar. The
result is an array of words, with the non-word characters between them
thrown away.
array(string) split_words_and_normalize(string input)
A less wasteful equivalent of
.split_words(normalize(input, "NFKD"))
Pike glue for the open-vcdiff differential compression library. http://code.google.com/p/open-vcdiff/
Encoding and decoding relies on a common string that the differences are computed against - this string is called the dictionary.
Basic usage:
string dict = "abcdef";
VCDiff.Encoder encoder = VCDiff.Encoder (dict);
string encoded = encoder->encode ("abcdefghijklmnopqrstuvwxyz");
VCDiff.Decoder decoder = VCDiff.Decoder (dict);
string decoded = decoder->decode (encoded);
This module contains special values used by various modules, e.g.
a null value used both by Sql and Standards.JSON.
In many ways these values should be considered constant, but it is possible for a program to replace them with extended versions, provided they don't break the behavior of the base classes defined here. Since there is no good mechanism to handle such extending in several steps, pike libraries should preferably ensure that the base classes defined here provide required functionality directly.
Since resolving using the dot operator in e.g. Val.null is
done at compile time, replacement of these values often must take
place very early (typically in a loader before the bulk of the
pike code is compiled) to be effective in such cases. For this
reason, pike libraries should use dynamic resolution through e.g.
-> or master()->resolv() instead.
Boolean Val.true
Boolean Val.false
Objects that represent the boolean values true and false. In a boolean context these evaluate to true and false, respectively.
They produce 1 and 0, respectively, when cast to
integer, and "1" and "0" when cast to string. They
do however not compare as equal to the integers 1 and 0, or any
other values. Val.true only compares (and hashes) as equal with
other instances of True (although there should be as few as
possible). Similarly, Val.false is only considered equal to
other False instances.
Protocols.JSON uses these objects to represent the JSON
literals true and false.
The correct way to programmatically recognize these values is something like
if (objectp(something) && ([object]something)->is_val_true) ...
and
if (objectp(something) && ([object]something)->is_val_false) ...
respectively. See Val.null for rationale.
Pike natively uses integers (zero and non-zero) as booleans. These objects don't change that, and unless there's a particular reason to use these objects it's better to stick to e.g. 0 and 1 for boolean values - that is both more efficient and more in line with existing coding practice. These objects are intended for cases where integers and booleans occur in the same place and it is necessary to distinguish them.
int Val.local_timezone
The local timezone without daylight-saving correction.
This value is determined once at process start, and cached for the lifetime of the process.
Null Val.null
Object that represents a null value.
In general, null is a value that represents the lack of a real value in the domain of some type. For instance, in a type system with a null value, a variable of string type typically can hold any string and also null to signify no string at all (which is different from the empty string). Pike natively uses the integer 0 (zero) for this, but since 0 also is a real integer it is sometimes necessary to have a different value for null, and then this object is preferably used.
This object is false in a boolean context. It does not cast to
anything, and it is not equal to anything else but other instances
of Null (which should be avoided).
This object is used by the Sql module to represent SQL NULL,
and it is used by Protocols.JSON to represent the JSON literal
null.
Do not confuse the null value with UNDEFINED. Although
UNDEFINED often is used to represent the lack of a real value,
and it can be told apart from an ordinary zero integer with some
effort, it is transient in nature (for instance, it automatically
becomes an ordinary zero when inserted in a mapping). That makes
it unsuitable for use as a reliable null value.
The correct way to programmatically recognize Val.null is
something like
if (objectp(something) && ([object]something)->is_val_null) ...
That way it's possible for other code to replace it with an
extended class, or create their own variants which needs to behave
like Val.null.
The Oracle glue currently uses static null objects which won't be affected if this object is replaced.
string iso_time(mapping(string:int) tm)
tmStandard tm mapping, optionally extended with nsec for
nanoseconds.
ISO formatted time.
mktime()
final string iso_timezone(int timezone)
timezoneTimezone in seconds west from UTC (must include daylight-saving time adjustment).
ISO formatted timezone east from UTC.
localtime()
Common base class for Val.True and Val.False, mainly to
facilitate typing. Do not create any instances of this.
constant int Val.Boolean.is_val_boolean
Nonzero recognition constant that can be used to recognize both
Val.true and Val.false.
Lightweight date type. Stores internally in days since epoch.
Supports arithmetic with Interval, Timestamp, Time
and TimeTZ objects.
Cast it to int or float to obtain unix_time.
Interval, Timestamp, Time, TimeTZ, Range
int Val.Date.days
Since 1970-01-01 (epoch).
Val.Date Val.Date(int year, int month, int day)
Val.Date Val.Date(this_program copy)
Val.Date Val.Date(Timestamp copy)
Val.Date Val.Date(mapping(string:int) tm)
Val.Date Val.Date(int unix_time)
Val.Date Val.Date(float unix_time)
Val.Date Val.Date()
Type for the Val.false object. Do not create more instances of
this - use Val.false instead.
inherit Boolean : Boolean
constant int Val.False.is_val_false
Nonzero recognition constant.
Lightweight IPv4 and IPv6 address type that stores the netmask and allows simple arithmetic and comparison operators.
int Val.Inet.address
IP address converted to an integer. IPv4 addresses will be 32-bit or less.
int Val.Inet.masklen
Defines the netmask. For both IPv4 and IPv6 addresses,
masklen will be 128 in case of full addresses.
bool res = Val.Inet() << that
Is contained by.
bool res = Val.Inet() >> that
Contains.
Val.Inet Val.Inet(int ip, void|int masklen)
Val.Inet Val.Inet()
ipAn IPv4 or IPv6 ip address.
masklenDefines the netmask, always in the range between 0
and 128; i.e. for IPv4 addresses you should
add 12 * 8 to the actual IPv4-masklen.
Val.Inet Val.Inet(string ip)
ipA string defining an IPv4 or IPv6 address
with an optional masklen attached.
If the address is in IPv6 notation, the range
of the masklen is expected to be
between 0 and 128.
If the address is in IPv4 notation, the range
of the masklen is expected to be
between 0 and 32.
Lightweight time and date interval type.
It stores the interval in integers of nanoseconds, days and months.
Supports arithmetic with Time, TimeTZ, Timestamp
and Date objects.
Cast it to int or float to obtain seconds.
Depending on daylight-saving time, a day may not equal 24 hours.
The number of days in a month depends on the the time of the year.
Timestamp, Date, Time
inherit Time : Time
int Val.Interval.days
Number of days; may not be equal to 24 hours per day, depending on daylight-saving time.
int Val.Interval.months
Number of months; the number of days per month varies accordingly.
(int)Val.Interval()
(float)Val.Interval()
(string)Val.Interval()
(array)Val.Interval()
(mapping)Val.Interval()
(multiset)Val.Interval()
Casting intervals with days or months to int
or float is not possible since the units are not constant.
Casting an interval to string will return a value which
is SQL-compliant.
mapping(string:int) tm()
A tm-like mapping which describes the interval. The mapping will
include an extra nsec component, and optionally
isnegative = 1 if the interval is a negative time interval.
mktime(), gmtime()
Type for the Val.null object. Do not create more instances of
this - use Val.null instead.
inherit Builtin.Null : Null
A wrapper for a passing around raw pointers between modules. Should not be used directly from pike code.
inherit Builtin.Pointer : Pointer
Generic lightweight range type. Supports any values for lower
and upper boundaries that implement lfun::`<() and lfun::`-(),
and preferrably also cast to int and string.
Can only contain a single contiguous range.
The empty range must be stored as (Math.inf, -Math.inf)
if assigned directly to from and till.
value_type Val.Range.from
The lower inclusive boundary.
value_type Val.Range.till
The upper exclusive boundary.
bool res = !Val.Range()
True if range is empty.
isempty()
bool res = Val.Range() & that
Overlap: have points in common.
this_program res = Val.Range() * that
Intersection
this_program res = Val.Range() + that
Union
this_program res = Val.Range() - that
Difference
bool res = Val.Range() << that
Strictly left of
bool res = Val.Range() >> that
Strictly right of
bool res = Val.Range() | that
Is adjacent to
This does NOT seem like a good operator for this operation.
bool contains(this_program|value_type other)
True if this range fully contains another range or element.
Val.Range Val.Range(value_type from, value_type till)
Val.Range Val.Range(this_program copy)
Val.Range Val.Range()
fromLower inclusive boundary for the range. Specify no lower-boundary
by filling in -Math.inf.
tillUpper exclusive boundary for the range. Specify no upper-boundary
by filling in Math.inf.
Math.inf
mixed interval()
Calculates the value of the interval: till - from.
Returns 0 if the range is empty.
local bool isempty()
True if range is empty.
`!()
this_program merge(this_program ... other)
otherExtends the current range to the smallest range which encompasses itself and all other given ranges.
This seems like the operation that `|() ought to do.
final string sql()
A string representing the range using SQL-compliant syntax.
Lightweight time type. Stores absolute times in a day
with nanosecond resolution. Normalised value range is between
00:00:00.000000000 and 23:59:59.999999999.
Values outside this range are accepted, and have arithmetically
sound results. Supports arithmetic with Interval and Date objects.
Cast it to int or float to obtain seconds since
00:00.
Interval, Date, TimeTZ, Range
inherit Timebase : Timebase
Val.Time Val.Time(int hour, int min, void|int sec, void|int nsec)
Val.Time Val.Time(int sec)
hourHours since epoch.
minMinutes since epoch.
secSeconds since epoch.
nsecNanoseconds since epoch.
Val.Time Val.Time(mapping(string:int) tm)
tmStandard tm mapping, optionally extended with nsec for
nanoseconds.
Passed values will not be normalised.
Days/months/years are ignored.
mapping(string:int) tm()
A tm-like mapping which describes the time. The mapping will
include an extra nsec component.
mktime(), gmtime()
Lightweight time type with timezone. Equivalent to Time, but
stores a timezone offset as well.
Cast it to int or float to obtain seconds since
00:00.
Time, Date, Interval, Range
inherit Time : Time
int Val.TimeTZ.timezone
Timezone offset in seconds west from UTC (includes daylight-saving time adjustment).
ISO time format displays the timezone in seconds east from UTC.
localtime()
Val.TimeTZ Val.TimeTZ(mapping(string:int) tm)
tmStandard tm mapping, optionally extended with nsec for
nanoseconds. Any specified timezone is used as is.
Passed values will not be normalised.
Days/months/years are ignored.
Val.TimeTZ Val.TimeTZ(int year, int month, int day, int hour, int min, void|int sec, void|int nsec)
Stores just the time of the day components, but including the correct timezone offset with any daylight-saving correction active on the date specified.
yearAbsolute year (e.g. 1900 == 1900, 2000 = 2000, 2017 == 2017).
monthMonth of the year (January == 1 ... December == 12).
dayDay of the month (typically between 1 and 31).
hourHour of the day (typically between 0 and 23).
minMinutes (typically between 0 and 59).
secSeconds (typically between 0 and 59).
nsecNanoseconds (typically between 0 and 999999999).
Specified values are expected in the localised time (i.e. relative to the current timezone locale, including daylight-saving correction).
If any of these values are offered in a denormalised range, they will be normalised relative to the startdate offered.
Timestamp, Date, Interval, Time
Base class for time related objects. Supports arithmetic with
Interval objects.
Should not be used by itself.
Timestamp, Time, Interval
int Val.Timebase.nsecs
Nanoseconds since epoch (for absolute time classes,
epoch equals 1970/01/01 00:00:00 UTC).
int|float Val.Timebase.usecs
Getting
Microseconds since epoch; reflects the equivalent value as the basic
member nsecs.
Setting
Microseconds since epoch; reflects the equivalent value as the basic
member nsecs.
(int)Val.Timebase()
(float)Val.Timebase()
(string)Val.Timebase()
(array)Val.Timebase()
(mapping)Val.Timebase()
(multiset)Val.Timebase()
Can be casted to string, float and int. Casting it to float and int return unix-time values.
mktime(), gmtime()
Val.Timebase Val.Timebase(void|mapping(string:int) tm)
Val.Timebase Val.Timebase(this_program copy)
Val.Timebase Val.Timebase(int|float sec, void|int nsec)
secSeconds since epoch.
nsecNanoseconds since epoch.
Lightweight time and date type. The values point at absolute points
in time. The values are stored internally with nanosecond resolution
since epoch (1970/01/01 00:00:00 UTC). Supports arithmetic
with Interval objects.
Cast it to int or float to obtain unix_time.
Interval, Date, Range, localtime(), mktime()
inherit Timebase : Timebase
(int)Val.Timestamp()
(float)Val.Timestamp()
(string)Val.Timestamp()
(array)Val.Timestamp()
(mapping)Val.Timestamp()
(multiset)Val.Timestamp()
When cast to string it returns an ISO formatted timestamp that includes daylight-saving and timezone corrections.
Val.Timestamp Val.Timestamp(int year, int month, int day, void|int hour, void|int min, void|int sec, void|int nsec)
Val.Timestamp Val.Timestamp(int unix_time, void|int nsec)
yearAbsolute year (e.g. 1900 == 1900, 2000 = 2000, 2017 == 2017).
monthMonth of the year (January == 1 ... December == 12).
dayDay of the month (typically between 1 and 31).
hourHour of the day (typically between 0 and 23).
minMinutes (typically between 0 and 59).
secSeconds (typically between 0 and 59).
nsecNanoseconds (typically between 0 and 999999999).
Specified values are expected in the localised time (i.e. relative to the current timezone locale, including daylight-saving correction).
If any of these values are offered in a denormalised range,
they will be normalised relative to the startdate offered.
I.e. it allows primitive year/month/day/hour/minute/second/nanosecond
arithmetic. For more advanced arithmetic you must use Interval
objects.
localtime(), mktime()
mapping(string:int) tm()
The same as localtime(), but augmented
by an extra member called nsec.
localtime()
Type for the Val.true object. Do not create more instances of
this - use Val.true instead.
inherit Boolean : Boolean
constant int Val.True.is_val_true
Nonzero recognition constant.
Modules implementing various web standards.
Crypto.Sign.State|Crypto.MAC.State decode_jwk(mapping(string(7bit):string(7bit)) jwk)
Decode a JSON Web Key (JWK).
Returns an initialized Crypto.Sign.State or Crypto.MAC.State
on success and UNDEFINED on failure.
variant Crypto.Sign.State|Crypto.MAC.State decode_jwk(string(8bit) jwk)
Decode a JSON Web Key (JWK).
Returns an initialized Crypto.Sign.State or Crypto.MAC.State
on success and UNDEFINED on failure.
array(Crypto.Sign.State|Crypto.MAC.State) decode_jwk_set(mapping(string(8bit):array(mapping(string(7bit):string(7bit)))) jwk_set)
Decode a JSON Web Key (JWK) Set.
RFC 7517 section 5, decode_jwk()
variant array(Crypto.Sign.State|Crypto.MAC.State) decode_jwk_set(string(7bit) jwk_set)
Decode a JSON Web Key (JWK) Set.
RFC 7517 section 5, decode_jwk()
array|zero decode_jws(array(Crypto.Sign.State|Crypto.MAC.State)|Crypto.Sign.State|Crypto.MAC.State sign, string(7bit) jws)
Decode a JSON Web Signature (JWS).
signThe asymetric public or MAC key(s) to validate the jws against.
jwsA JWS as eg returned by encode_jws().
Returns 0 (zero) on validation failure.
Returns an array with two elements on success:
| Array | |
| The JOSE header. |
| The JWS payload. |
See RFC 7515 section 3.
encode_jws(), decode_jwt(), Crypto.Sign.State()->jose_decode(),
RFC 7515
mapping(string:string|int)|zero decode_jwt(array(Crypto.Sign.State|Crypto.MAC.State)|Crypto.Sign.State|Crypto.MAC.State sign, string(7bit) jwt)
Decode a JSON Web Token (JWT).
signThe asymetric public or MAC key(s) to validate the jwt against.
jwtA JWT as eg returned by encode_jwt().
Returns 0 (zero) on validation failure (this
includes validation of expiry times).
Returns a mapping of the claims for the token on success. See RFC 7519 section 4.
The time check of the "nbf" value has a hard coded
60 second grace time (as allowed by RFC 7519 section 4.1.5).
encode_jwt(), decode_jws(), RFC 7519 section 4
string(7bit) encode_jwk(mapping(string(7bit):string(7bit)) jwk)
Encode a JSON Web Key (JWK).
variant string(7bit) encode_jwk(Crypto.Sign.State|Crypto.MAC.State sign, bool|void private_key)
Encode a JSON Web Key (JWK).
signThe initialized Crypto.Sign.State or Crypto.MAC.State
for which a JWK is to be generated.
private_keyIf true the private fields of sign will also be encoded into
the result.
Returns the corresponding JWK.
string(7bit) encode_jws(Crypto.Sign.State|Crypto.MAC.State sign, mixed tbs, string(7bit)|void media_type)
Encode a JSON Web Signature (JWS).
signThe asymetric private or MAC key to use for signing the result.
tbsThe value to sign.
media_typeThe media type of tbs, cf RFC 7515 section 4.1.9.
Returns 0 (zero) on encoding failure (usually
that sign doesn't support JWS.
Returns a corresponding JWS on success.
decode_jwt(), RFC 7515
string(7bit) encode_jwt(Crypto.Sign.State|Crypto.MAC.State sign, mapping(string:string|int) claims)
Encode a JSON Web Token (JWT). Automatically adds the optional "issued at" timestamp and JWD ID (using UUID v4).
signThe asymetric private or MAC key to use for signing the result.
claimsThe set of claims for the token. See RFC 7519 section 4.
Returns 0 (zero) on encoding failure (usually
that sign doesn't support JWS.
Returns a corresponding JWT on success.
The claim "iat" (RFC 7519 section 4.1.6 is added unconditionally,
and the claim "jti" (RFC 7519 section 4.1.7) is added
if not already present.
decode_jwt(), RFC 7519 section 4
Represents an RDF tuple set from an OWL perspective.
inherit .RDFS : RDFS
Represents an RDF domain which can contain any number of complete statements.
constant string Web.RDF.rdf_ns
The RDF XML namespace.
RDFResource Web.RDF.rdf_Seq
Seq resource.
RDFResource Web.RDF.rdf_Statement
Statement resource.
RDFResource Web.RDF.rdf_first
first resource.
RDFResource Web.RDF.rdf_nil
nil resource.
RDFResource Web.RDF.rdf_object
object resource.
RDFResource Web.RDF.rdf_predicate
predicate resource.
RDFResource Web.RDF.rdf_rest
rest resource.
RDFResource Web.RDF.rdf_subject
subject resource.
RDFResource Web.RDF.rdf_type
type resource.
int sizeof( Web.RDF arg )
Returns the number of statements in the RDF domain.
Web.RDF res = Web.RDF() | x
Modifies the current object to create a union of the current object
and the object x.
this_program add_statement(Resource|string|multiset(string) subj, Resource|string|multiset(string) pred, Resource|string|multiset(string) obj)
Adds a statement to the RDF set. If any argument is a string, it
will be converted into a LiteralResource. If any argument is a
multiset with one string in it, it will be converted into a
URIResource.
Throws an exception if any argument couldn't be converted into a Resouce object.
string decode_n_triple_string(string in)
Decodes a string that has been encoded for N-triples serialization.
Doesn't correctly decode backslashes that has been encoded with with \u- or \U-notation.
bool dereify(Resource r)
Turns the reified statement r into a normal statement, if possible.
1 for success, 0 for failure.
int(0..) dereify_all()
Dereifies as many statements as possible. Returns the number of dereified statements.
string encode_n_triple_string(string in)
Encodes a string for use as tring in N-triples serialization.
array(array(Resource)) find_statements(Resource|int(0) subj, Resource|int(0) pred, Resource|int(0) obj)
Returns an array with the statements that matches the given
subject subj, predicate pred and object obj. Any
and all of the resources may be zero to disregard from matching
that part of the statement, i.e. find_statements(0,0,0) returns
all statements in the domain.
An array with arrays of three elements.
| Array | |
| The subject of the statement |
| The predicate of the statement |
| The object of the statement |
string get_3_tuples()
Returns a 3-tuple serialization of all the statements in the RDF set.
string get_n_triples()
Returns an N-triples serialization of all the statements in the RDF set.
array(Resource) get_properties()
Returns all properties in the domain, e.g. all resources that has been used as predicates.
Resource|zero get_reify(Resource subj, Resource pred, Resource obj)
Returns a resource that is the subject of the reified statement {subj, pred, obj}, if such a resource exists in the RDF domain.
URIResource|zero get_resource(string uri)
Returns an RDF resource with the given URI as identifier, or zero.
mapping(Resource:mapping(Resource:array(Resource))) get_subject_map()
Returns a mapping with all the domains subject resources as indices and a mapping with that subjects predicates and objects as value.
string get_xml(void|int no_optimize)
Serialize the RDF domain as an XML string.
no_optimizeIf set, the XML serializer will refrain from doing most (size) optimizations of the output.
bool has_statement(Resource subj, Resource pred, Resource obj)
Returns 1 if the RDF domain contains the relation {subj, pred, obj}, otherwise 0.
bool is_object(Resource r)
Returns 1 if resource r is used as an object, otherwise
0.
bool is_predicate(Resource r)
Returns 1 if resource r is used as a predicate,
otherwise 0.
bool is_subject(Resource r)
Returns 1 if resource r is used as a subject, otherwise
0.
URIResource make_resource(string uri)
Returns an RDF resource with the given URI as identifier, or if no such resrouce exists, creates it and returns it.
int parse_n_triples(string in)
Parses an N-triples string and adds the found statements to the RDF set. Returns the number of added relations.
The parser will throw errors on invalid N-triple input.
Web.RDF parse_xml(string|Parser.XML.NSTree.NSNode in, void|string base)
Adds the statements represented by the string or tree in to the
RDF domain. If in is a tree the in-node should be the RDF
node of the XML serialization. RDF documents take its default
namespace from the URI of the document, so if the RDF document relies
such ingenious mechanisms, pass the document URI in the base
variable.
Resource reify(Resource subj, Resource pred, Resource obj)
Returns the result of get_reify, if any. Otherwise calls
reify_low followed by remove_statement of the provided
statement {subj, pred, obj}.
The subject of the reified statement.
Resource reify_low(Resource subj, Resource pred, Resource obj)
Reifies the statement { pred, subj, obj } and returns the resource that denotes the reified statement. There will not be any check to see if the unreified statement is already in the domain, making it possible to define the relation twice. The original statement will not be removed.
The subject of the reified statement.
bool remove_statement(Resource subj, Resource pred, Resource obj)
Removes the relation from the RDF set. Returns 1 if the relation did exist in the RDF set.
Resource identified by literal.
inherit Resource : Resource
string Web.RDF.LiteralResource.datatype
Used to contain rdf:datatype value.
Web.RDF.LiteralResource Web.RDF.LiteralResource(string literal)
The resource will be identified by literal.
string get_literal()
Returns the literal string.
string get_xml()
Returns the literal as an XML string.
Resource used for RDF-technical reasons like reification.
inherit URIResource : URIResource
Web.RDF.RDFResource Web.RDF.RDFResource(string rdf_id)
The resource will be identified by the identifier rdf_id
string get_qname(void|string ns)
Returns the qualifying name.
Instances of this class represents resources as defined in RDF: All things being described by RDF expressions are called resources. A resource may be an entire Web page; such as the HTML document "http://www.w3.org/Overview.html" for example. A resource may be a part of a Web page; e.g. a specific HTML or XML element within the document source. A resource may also be a whole collection of pages; e.g. an entire Web site. A resource may also be an object that is not directly accessible via the Web; e.g. a printed book. This general resource is anonymous and has no URI or literal id.
Resources instantiated from this class should not be used in other RDF domain objects.
URIResource, LiteralResource
string get_3_tuple_name()
Returns the nodes' 3-tuple serialized ID.
string get_n_triple_name()
Returns the nodes' N-triple serialized ID.
Resource identified by URI.
inherit Resource : Resource
Web.RDF.URIResource Web.RDF.URIResource(string uri)
Creates an URI resource with the uri as identifier.
Throws an error if another resource with the same URI already exists in the RDF domain.
string get_namespace()
Returns the namespace this resource URI references to.
string|zero get_qname(void|string ns)
Returns the qualifying name, or zero.
string get_uri()
Returns the URI the resource references to.
RDF Schema.
inherit .RDF : RDF
constant string Web.RDFS.rdfs_ns
The RDF Schema XML-namespace.
RDFSResource Web.RDFS.rdfs_Class
RDFSResource Web.RDFS.rdfs_subClassOf
RDFSResource Web.RDFS.rdfs_Literal
RDFSResource Web.RDFS.rdfs_subPropertyOf
RDFSResource Web.RDFS.rdfs_domain
RDFSResource Web.RDFS.rdfs_range
void add_Class(Resource c)
void add_subClassOf(Resource a, Resource b)
void add_subPropertyOf(Resource a, Resource b)
inherit URIResource : URIResource
The Web.Api has modules and classes for communicating with various
(RESTful) web api's such as Web.Api.Facebook,
Web.Api.Instagram, Web.Api.Twitter etc.
string api_key = "......"; string api_secret = "......."; string redirect_uri = "http://localhost/insta/"; Web.Api.Instagram api; string cookie_file = "my-cookie.txt"; int main(int argc, array(string) argv) { api = Web.Api.Instagram(api_key, api_secret, redirect_uri); // If a stored authentication cookie exists, populate the auth object. if (Stdio.exist(cookie_file)) { api->auth->set_from_cookie(Stdio.read_file(cookie_file)); } if (!api->auth->is_authenticated()) { // A cookie existed but the authentication has expired if (api->auth->is_renewable()) { write("Trying to refresh token..."); if (string data = api->auth->refresh_token()) Stdio.write_file(cookie_file, data); write("done ok!\n"); } else { werror("failed!\n"); } } // No previous authentication exists. Create a new one... else { // Get the uri to the authentication endpoint string uri = api->auth->get_auth_uri(); write("Opening \"%s\" in browser.\nCopy the contents of the address " "bar and paste here: ", Standards.URI(uri)); sleep(2); // For Mac Process.create_process(({ "open", uri })); string resp = Stdio.Readline()->read(); mapping p = Web.Auth.query_to_mapping(Standards.URI(resp)->query); string code; // If the auth object is OAuth and not OAuth2 this step is required. // Instagram is OAuth2, but Twitter is OAuth1 if (p->oauth_token) { auth->set_authentication(p->oauth_token); code = p->oauth_verifier; } else { code = p->code; } // Now, get an access token if (string data = auth->request_access_token(code)) { Stdio.write_file(cookie, data); } else { werror("Failed getting an access token. Aborting!\n"); return 1; } } } if (api->auth->is_authenticated()) { // No UID (arg1) means get the authenticated users stuff // No additional params (arg2) // Run async (arg3) mapping m = api->users->recent(0, 0, lambda(mixed m) { werror("Insta: %O\n", m); exit(0); }); return -1; } else { werror("No authentication was aquired!\n"); return 1; } }
constant string Web.Api.USER_AGENT
Default user agent in HTTP calls
Base class for implementing a (RESTful) WebApi like Facebook's Graph API, Instagram's API, Twitter's API and so on.
Note: This class is useless in it self, and is intended to be inherited by classes implementing a given Web.Api.
Look at the code in Web.Api.Github, Web.Api.Instagram,
Web.Api.Linkedin etc to see some examples of implementations.
typedef function(mixed, Protocols.HTTP.Query, mixed ... :void) Web.Api.Api.Callback
Typedef for the async callback method signature.
typedef function(mixed, Protocols.HTTP.Query|Protocols.HTTP.Promise.Result, mixed ... :void) Web.Api.Api.Callback
Typedef for the async callback method signature.
typedef mapping|Web.Auth.Params Web.Api.Api.ParamsArg
Typedef for a parameter argument
protected constantstring Web.Api.Api.ACCESS_TOKEN_PARAM_NAME
In some API's (LinkedIn f ex) this is named something else so it needs to be overridden i cases where it has a different name than the standard one.
Obsolete.
This is only used if AUTHORIZATION_METHOD has been set to "".
constant string Web.Api.Api.API_URI
The default URI to the remote API
protected constantstring Web.Api.Api.AUTHORIZATION_METHOD
Authorization header prefix.
This is typically "Bearer" as per RFC 6750, but
some apis use the older "token".
constant Web.Api.Api.AuthClass
Authentication class to use
protected constantint Web.Api.Api.DECODE_UTF8
If 1 Standards.JSON.decode_utf8() will be used when JSON data
is decoded.
protected Web.Auth.OAuth2.Client Web.Api.Api._auth
Authorization object.
Web.Auth.OAuth2
protected mapping(int:array(Protocols.HTTP.Query|Callback)) Web.Api.Api._query_objects
The HTTP query objects when running async.
Web.Auth.OAuth2.Client Web.Api.Api.auth
Getter for the authentication object. Most likely this will be a class
derived from Web.Auth.OAuth2.Client.
Web.Auth.OAuth2.Client or Web.Auth.OWeb.Auth.Client
Read only
int(0..) Web.Api.Api.http_request_timeout
Request timeout in seconds. Only affects async queries.
bool Web.Api.Api.utf8_decode
If 1 Standards.JSON.decode_utf8() will be used when JSON data
is decoded.
mixed call(string api_method, void|ParamsArg params, void|string http_method, void|string data, void|Callback cb, mixed ... rest)
Calls a remote API method.
An exception is thrown if the response status code is other than
200, 301 or 302.
api_methodThe remote API method to call! This should be a Fully Qualified Domain Name
paramsAdditional params to send in the request
http_methodHTTP method to use. GET is default
dataInline data to send in a POST request for instance.
cbCallback function to get into in async mode
If JSON is available the JSON response from servie will be decoded
and returned. If not, the raw response (e.g a JSON string) will be
returned. The exception to this is if the status code in the response is a
30x (a redirect), then the response headers mapping will be
returned.
void close_connections()
Forcefully close all HTTP connections. This only has effect in async mode.
Web.Api.Api Web.Api.Api(void|string client_id, void|string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Creates a new Api instance
client_idThe application ID
client_secretThe application secret
redirect_uriWhere the authorization page should redirect back to. This must be fully qualified domain name.
scopeExtended permissions to use for this authentication.
protected mapping default_params()
Return default params
mixed delete(string api_method, void|ParamsArg params, void|Callback cb, mixed ... rest)
Invokes a call with a DELETE method
api_methodThe remote API method to call
paramscbCallback function to get into in async mode
mixed get(string api_method, void|ParamsArg params, void|Callback cb, mixed ... rest)
Invokes a call with a GET method
api_methodThe remote API method to call
paramscbCallback function to get into in async mode
protected string get_encoding(mapping h)
Returns the encoding from a response
hThe headers mapping from a HTTP respose
protected string get_uri(string method)
Convenience method for getting the URI to a specific API method
methodprotected array(string) make_multipart_message(mapping p, string body)
Creates the body of an Upload request
pThe API request parameters
bodyData of the document to upload
An array with two indices:
The value for the main Content-Type header
The request body
mapping(string:string|mapping) parse_canonical_url(string url)
This can be used to parse a link resource returned from a REST api. Many API returns stuff like:
{
...
"pagination" : {
"next" : "/api/v1/method/path?some=variables&page=2&per_page=20"
}
}
If pagination->next is passed to this method it will return a path of /method/path, given that the base URI of the web api is something along the line of https://some.url/api/v1, and a mapping containing the query variables (which can be passed as a parameter to any of the get, post, delete, put methods.
url |
|
mixed patch(string api_method, void|ParamsArg params, void|Callback cb, mixed ... rest)
Invokes a call with a PATCH method
api_methodThe remote API method to call
paramscbCallback function to get into in async mode
mixed post(string api_method, void|ParamsArg params, void|string data, void|Callback cb, mixed ... rest)
Invokes a call with a POST method
api_methodThe remote API method to call
paramsdataEventual inline data to send
cbCallback function to get into in async mode
mixed put(string api_method, void|ParamsArg params, void|Callback cb, mixed ... rest)
Invokes a call with a PUT method
api_methodThe remote API method to call
paramscbCallback function to get into in async mode
protected string unescape_forward_slashes(string s)
Unescapes escaped forward slashes in a JSON string
Internal class meant to be inherited by implementing Api's classes that corresponds to a given API endpoint.
protected constantint Web.Api.Api.Method.METHOD_PATH
API method location within the API
https://api.instagram.com/v1/media/search
............................^^^^^^^
protected mixed _delete(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
protected mixed _get(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
protected mixed _patch(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
protected mixed _post(string s, void|ParamsArg p, void|string data, void|Callback cb)
Internal convenience method
protected mixed _put(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
Web.Api.Api.Method Web.Api.Api.Method()
Hidden constructor. This class can not be instantiated directly
protected this_program `()(string client_id, string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Instantiates the default Facebook API.
See Web.Api.Api() for further information.
client_idYour application key/id
client_secretYour application secret
redirect_uriThe redirect URI after an authentication
scopeThe application scopes to grant access to
inherit Web.Api.Api : parent
constant string Web.Api.Facebook.Graph.API_URI
The base uri to the Graph API
Any Web.Api.Facebook.Graph.any
Getter for the Any object which is a generic object for making request
to the Facebook Graph API
Any
Read only
mapping delete(string path, void|ParamsArg params, void|Callback cb)
Make a generic DELETE request to the Facebook Graph API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
mapping get(string path, void|ParamsArg params, void|Callback cb)
Make a generic GET request to the Facebook Graph API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
mapping post(string path, void|ParamsArg params, void|string data, void|Callback cb)
Make a generic POST request to the Facebook Graph API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramsdatacbCallback for async requests
mapping put(string path, void|ParamsArg params, void|Callback cb)
Make a generic PUT request to the Facebook Graph API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
A generic wrapper around Method
inherit Method : Method
inherit Web.Api.Api.Method : Method
mixed delete(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
mixed get(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
mixed post(string s, void|ParamsArg p, void|string data, void|Callback cb)
Internal convenience method
mixed put(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
protected this_program `()(string client_id, string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Instantiates the default Github API.
See Web.Api.Api() for further information.
client_idYour application key/id
client_secretYour application secret
redirect_uriThe redirect URI after an authentication
scopeThe application scopes to grant access to
inherit Web.Api.Api : parent
constant string Web.Api.Github.Github.API_URI
The base uri to the Github API
Any Web.Api.Github.Github.any
Getter for the Any object which is a generic object for making request
to the Github API
Any
Read only
mapping delete(string path, void|ParamsArg params, void|Callback cb)
Make a generic DELETE request to the Github API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
mapping get(string path, void|ParamsArg params, void|Callback cb)
Make a generic GET request to the Github API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
mapping post(string path, void|ParamsArg params, void|string data, void|Callback cb)
Make a generic POST request to the Github API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramsdatacbCallback for async requests
mapping put(string path, void|ParamsArg params, void|Callback cb)
Make a generic PUT request to the Github API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
A generic wrapper around Method
inherit Method : Method
inherit Web.Api.Api.Method : Method
mixed delete(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
mixed get(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
mixed post(string s, void|ParamsArg p, void|string data, void|Callback cb)
Internal convenience method
mixed put(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
Base discover(string api, string version, void|string client_id, void|string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Get a Google API object
This example shows how you can use the Google API to find out all the compute zones that exist at Google Compute Engine.
#define SECRET_FILE "googleserviceaccount.json" #define PROJECT "somegoogleproject" #define TOKENTIME 3600 string jwt_secret = Stdio.File(SECRET_FILE, "r").read(); Web.Api.Google.Base api = Web.Api.Google.discover("compute", "v1"); void authenticated() { if (!api->auth->is_authenticated() || api->auth->expires->unix_time() - time(1) < TOKENTIME / 2) api->auth->get_token_from_jwt(jwt_secret); }; authenticated(); mixed allzones = api->resrc->zones->list( ([ "project":PROJECT ]) );
Internal class meant to be inherited by other Google API's
inherit Web.Api.Api : parent
inherit Web.Api.Api.Method : Method
protected mixed _delete(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
protected mixed _get(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
protected mixed _post(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
inherit Api : parent
resource Web.Api.Google.Base.resrc
Read only
array(string) Web.Api.Google.Base.valid_scopes
Read only
Web.Api.Google.Base Web.Api.Google.Base(mapping discovered, mixed ... rest)
void set_scope(string scope)
inherit Api : parent
protected constantstring Web.Api.Google.Discovery.API_URI
API base URI.
protected Apis Web.Api.Google.Discovery._apis
Internal singleton objects. Retrieve an apis via apis.
Apis Web.Api.Google.Discovery.apis
Getter for the Apis API
Read only
Interface to the Google Discovery Service API
inherit Method : Method
mixed getRest(mapping params, void|Callback cb)
Retrieve the description of a particular version of an API
paramscbmixed list(void|mapping params, void|Callback cb)
Retrieve the list of APIs supported at this endpoint
paramscbprotected this_program `()(string client_id, string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Instantiates the default Analytics API.
See Web.Api.Api() for further information.
client_idYour application key/id
client_secretYour application secret
redirect_uriThe redirect URI after an authentication
scopeThe application scopes to grant access to
inherit Web.Api.Google.Api : parent
protected constantstring Web.Api.Google.Analytics.V3.API_URI
API base URI.
protected Core Web.Api.Google.Analytics.V3._core
protected RealTime Web.Api.Google.Analytics.V3._realtime
protected Management Web.Api.Google.Analytics.V3._management
Internal singleton objects. Retrieve an instance via core,
realtime and management.
Core Web.Api.Google.Analytics.V3.core
Getter for the Core API
Read only
Management Web.Api.Google.Analytics.V3.management
Getter for the Management API
Read only
RealTime Web.Api.Google.Analytics.V3.realtime
Getter for the RealTime API
Read only
Interface to the Google Analytics core API
inherit Method : Method
mixed get(mapping params, void|Callback cb)
Get data from the core api
paramscbInterface to the Google Analytics managment API
inherit Method : Method
mixed account_summaries(void|ParamsArg params, void|Callback cb)
Get account summaries
paramscbInterface to the Google Analytics realtime API
inherit Method : Method
mixed get(mapping params, void|Callback cb)
Get data from the realtime api
paramscbprotected this_program `()(string client_id, string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Instantiates the default Google+ API.
See Web.Api.Api() for further information.
client_idYour application key/id
client_secretYour application secret
redirect_uriThe redirect URI after an authentication
scopeThe application scopes to grant access to
inherit Web.Api.Google.Api : Api
protected constantstring Web.Api.Google.Plus.V1.API_URI
API base URI.
private People Web.Api.Google.Plus.V1._people
private Activities Web.Api.Google.Plus.V1._activities
Internal singleton objects. Get an instance via people and
activities.
Activities Web.Api.Google.Plus.V1.activities
Getter for the Activities object which has methods for all
activities related Google+ API methods.
Read only
People Web.Api.Google.Plus.V1.people
Getter for the People object which has methods for all people
related Google+ API methods.
Read only
Class implementing the Google+ Activities API. https://developers.google.com/+/api/latest/activities
Retreive an instance of this class through the
activities property
inherit Method : Method
Class implementing the Google+ People API. https://developers.google.com/+/api/latest/people
Retreive an instance of this class through the
Social.Google.Plus()->people property
inherit Method : Method
mapping get(void|string user_id, void|Callback cb)
Get info ablut a person.
user_idIf empty the currently authenticated user will be fetched.
cbCallback for async request
mapping list(void|string user_id, void|string collection, void|ParamsArg params, void|Callback cb)
List all of the people in the specified collection.
user_idIf empty the currently authenticated user will be used.
collectionIf empty "public" activities will be listed. Acceptable values are:
The list of people who this user has added to one or more circles, limited to the circles visible to the requesting application.
params | Max number of items ti list |
| The order to return people in. Acceptable values are:
|
| The continuation token, which is used to page through large result
sets. To get the next page of results, set this parameter to the value
of |
cbCallback for async request
Instagram API implementation. https://instagram.com/developer/
protected this_program `()(string client_id, string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Instantiates the default Instagram API.
See Web.Api.Api() for further information.
client_idYour application key/id
client_secretYour application secret
redirect_uriThe redirect URI after an authentication
scopeThe application scopes to grant access to
Class for communicating with version 1 of the Instagram API.
inherit Web.Api.Api : parent
protected constantstring Web.Api.Instagram.V1.API_URI
The URI to the Instagram API
private Any Web.Api.Instagram.V1._any
Singleton Any object. Will be instantiated first time requested.
private Comments Web.Api.Instagram.V1._comments
Singleton Comments object. Will be instantiated first time requested.
private Likes Web.Api.Instagram.V1._likes
Singleton Likes object. Will be instantiated first time requested.
private Locations Web.Api.Instagram.V1._locations
Singleton Locations object. Will be instantiated first time requested.
private Media Web.Api.Instagram.V1._media
Singleton Media object. Will be instantiated first time requested.
private Tags Web.Api.Instagram.V1._tags
Singleton Tags object. Will be instantiated first time requested.
private Users Web.Api.Instagram.V1._users
Singleton User object. Will be instantiated first time requested.
Any Web.Api.Instagram.V1.any
Getter for the Any object which can be used to query any method in
the Instagram web api. The METHOD_PATH is set to / in
this object.
Read only
Comments Web.Api.Instagram.V1.comments
Getter for the Comments object which has methods for all
comments related Instagram API methods.
Read only
Likes Web.Api.Instagram.V1.likes
Getter for the Likes object which has methods for all likes
related Instagram API methods.
Read only
Locations Web.Api.Instagram.V1.locations
Getter for the Locations object which has methods for all
locations related Instagram API methods.
Read only
Media Web.Api.Instagram.V1.media
Getter for the Media object which has methods for all media
related Instagram API methods.
Read only
Tags Web.Api.Instagram.V1.tags
Getter for the Tags object which has methods for all tags
related Instagram API methods.
Read only
Users Web.Api.Instagram.V1.users
Getter for the Users object which has methods for all users
related Instagram API methods.
Read only
mapping delete(string path, void|ParamsArg params, void|Callback cb)
Make a generic DELETE request to the Instagram API.
pathWhat to request. Like me, users/self,
[some_id]/something.
paramscbCallback for async requests
mapping get(string path, void|ParamsArg params, void|Callback cb)
Make a generic GET request to the Instagram API.
pathWhat to request. Like me, users/self,
[some_id]/something.
paramscbCallback for async requests
mapping post(string path, void|ParamsArg params, string|zero data, void|Callback cb)
Make a generic POST request to the Instagram API.
pathWhat to request. Like me, users/self,
[some_id]/something.
paramsdataIgnored.
cbCallback for async requests
mapping put(string path, void|ParamsArg params, void|Callback cb)
Make a generic PUT request to the Instagram API.
pathWhat to request. Like me, users/self,
[some_id]/something.
paramscbCallback for async requests
A generic wrapper around Method. This will query the root of the
API, and can be used to query methods not implemented in this module.
inherit Method : Method
mixed delete(string s, void|ParamsArg p, void|Callback cb)
DELETE data
sThe path to the Instagram API to query
pParameters to the query
cbAsync callback
mixed get(string s, void|ParamsArg p, void|Callback cb)
GET data
sThe path to the Instagram API to query
pParameters to the query
cbAsync callback
mixed post(string s, void|ParamsArg p, string|zero data, void|Callback cb)
POST data
sThe path to the Instagram API to query
pParameters to the query
cbAsync callback
mixed put(string s, void|ParamsArg p, void|Callback cb)
PUT data
sThe path to the Instagram API to query
pParameters to the query
cbAsync callback
Class implementing the Instagram Comments API. http://instagram.com/developer/endpoints/comments/
Retreive an instance of this class via the comments property.
inherit Method : Method
mapping add(string media_id, string comment, void|Callback cb)
Get a full list of comments on a media.
This method is not allowed by default. You have to contact Instagram in order to activate this method. http://bit.ly/instacomments
Required scope: comments
media_idThe media to retreive comments for
cbCallback for async mode
mapping list(string media_id, void|Callback cb)
Get a full list of comments on a media.
Required scope: comments
media_idThe media to retreive comments for
cbCallback for async mode
mapping remove(string media_id, string comment_id, void|Callback cb)
Remove a comment either on the authenticated user's media or authored by the authenticated user.
Required scope: comments
media_idThe media the comment is for
comment_idThe comment to remove
cbCallback for async mode
Class implementing the Instagram Likes API. http://instagram.com/developer/endpoints/likes/
Retreive an instance of this class via the likes property.
inherit Method : Method
mapping add(string media_id, void|Callback cb)
Set a like on this media by the currently authenticated user.
Required scope: likes
media_idcbmapping list(string media_id, void|Callback cb)
Get a list of users who have liked this media.
http://instagram.com/developer/endpoints/likes/#get_media_likes
Required scope: likes
media_idcbmapping remove(string media_id, void|Callback cb)
Remove a like on this media by the currently authenticated user.
http://instagram.com/developer/endpoints/likes/#delete_likes
Required scope: likes
media_idcbClass implementing the Instagram Likes API. http://instagram.com/developer/endpoints/likes/
Retreive an instance of this class via the locations property.
inherit Method : Method
mapping location(string location_id, void|Callback cb)
Get information about a location.
http://instagram.com/developer/endpoints/locations/#get_locations
location_idcbmapping recent_media(string location_id, void|ParamsArg params, void|Callback cb)
Get a list of recent media objects from a given location. May return a mix of both image and video types.
http://instagram.com/developer/endpoints/locations/#get_locations_media_recent
location_idparams | Return media after this UNIX timestamp |
| Return media before this min_id. |
| Return media after this max_id. |
| Return media before this UNIX timestamp |
cbmapping search(ParamsArg params, void|Callback cb)
Search for a location by geographic coordinate.
http://instagram.com/developer/endpoints/locations/#get_locations_search
params | Latitude of the center search coordinate. If used, lng is required. |
| Default is 1000m (distance=1000), max distance is 5000. |
| Longitude of the center search coordinate. If used, lat is required. |
| Returns a location mapped off of a foursquare v2 api location id. If used, you are not required to use lat and lng. |
| Returns a location mapped off of a foursquare v1 api location id. If used, you are not required to use lat and lng. Note that this method is deprecated; you should use the new foursquare IDs with V2 of their API. |
cbClass implementing the Instagram Media API. http://instagram.com/developer/endpoints/media/
Retreive an instance of this class via the media property
inherit Method : Method
mapping item(string media_id, void|Callback cb)
Get information about a media object. The returned type key will allow you to differentiate between image and video media. Note: if you authenticate with an OAuth Token, you will receive the user_has_liked key which quickly tells you whether the current user has liked this media item.
media_idcbCallback function when in async mode
mapping popular(void|Callback cb)
Get a list of what media is most popular at the moment. Can return a mix of image and video types.
cbCallback function when in async mode
mapping search(void|ParamsArg params, void|Callback cb)
Search for media in a given area. The default time span is set to 5 days. The time span must not exceed 7 days. Defaults time stamps cover the last 5 days. Can return mix of image and video types.
paramsCan have:
| Latitude of the center search coordinate. If used, lng is required. |
| A unix timestamp. All media returned will be taken later than this timestamp. |
| Longitude of the center search coordinate. If used, lat is required. |
| A unix timestamp. All media returned will be taken earlier than this timestamp. |
| Default is 1km (distance=1000), max distance is 5km. |
cbCallback function when in async mode
Internal convenience class.
inherit Web.Api.Api.Method : Method
protected mixed _delete(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
protected mixed _get(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
protected mixed _post(string s, void|ParamsArg p, string|zero data, void|Callback cb)
Internal convenience method
protected mixed _put(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
Class implementing the Instagram Tags API. http://instagram.com/developer/endpoints/tags/
Retreive an instance of this class via the tags property.
inherit Method : Method
mapping recent(string tag_name, void|ParamsArg params, void|Callback cb)
Get a list of recently tagged media. Note that this media is ordered by when the media was tagged with this tag, rather than the order it was posted. Use the max_tag_id and min_tag_id parameters in the pagination response to paginate through these objects. Can return a mix of image and video types.
http://instagram.com/developer/endpoints/tags/#get_tags_media_recent
tag_nameparamsCan be:
| Return media before this min_id. |
| Return media after this max_id. |
cbCallback function when in async mode
mapping search(string tag_name, Callback cb)
Search for tags by name. Results are ordered first as an exact match, then by popularity. Short tags will be treated as exact matches.
http://instagram.com/developer/endpoints/tags/#get_tags_search
tag_namecbCallback function when in async mode
mapping tag(string tag_name, void|Callback cb)
Get information about a tag object.
tag_namecbCallback function when in async mode
Class implementing the Instagram Users API. http://instagram.com/developer/endpoints/users/
Retreive an instance of this class via the users property
inherit Method : Method
mapping feed(void|ParamsArg params, void|Callback cb)
Get the currently authenticated users feed. http://instagram.com/developer/endpoints/users/#get_users
paramsValida parameters are:
| Number of items to return. Default is 20. |
| Return media later than this min_id |
| Return media earlier than this max_id |
cbCallback function when in async mode
mapping followed_by(string|void user_id, void|Callback cb)
Get the list of users this user is followed by.
Required scope: relationships
http://instagram.com/developer/endpoints/relationships/#get_users_followed_by
user_idcbCallback function when in async mode
mapping follows(void|string user_id, void|Callback cb)
Get the list of users this user follows.
Required scope: relationships
http://instagram.com/developer/endpoints/relationships/#get_users_follows
user_idcbCallback function when in async mode
mapping liked(void|ParamsArg params, void|Callback cb)
See the authenticated user's list of media they've liked. May return a mix of both image and video types. Note: This list is ordered by the order in which the user liked the media. Private media is returned as long as the authenticated user has permission to view that media. Liked media lists are only available for the currently authenticated user.
http://instagram.com/developer/endpoints/users/#get_users_feed_liked
paramsValida parameters are:
| Number of items to return. Default is 20. |
| Return media liked before this id. |
cbCallback function when in async mode
mapping recent(void|string uid, void|ParamsArg params, void|Callback cb)
Get the most recent media published by a user. May return a mix of both image and video types. http://instagram.com/developer/endpoints/users/get_users_media_recent
uidAn Instagram user ID
paramsValida parameters are:
| Number of items to return. Default is 20. |
| Return media later than this min_id |
| Return media earlier than this max_id |
| Return media before this UNIX timestamp. |
| Return media after this UNIX timestamp. |
cbCallback function when in async mode
mapping relationship(string user_id, void|Callback cb)
Get information about a relationship to another user.
Required scope: relationships
http://instagram.com/developer/endpoints/relationships/#get_relationship
user_idcbCallback function when in async mode
mapping relationship_change(string user_id, string action, void|Callback cb)
Modify the relationship between the current user and the target user.
Required scope: relationships
user_idThe user to change the relationship to
actionHow to change the relationship. Can be:
cbCallback function if in async mode
mapping requested_by(void|Callback cb)
List the users who have requested this user's permission to follow.
Required scope: relationships
http://instagram.com/developer/endpoints/relationships/#get_incoming_requests
cbCallback function when in async mode
mapping search(string query, void|int count, void|Callback cb)
Search for a user by name.
http://instagram.com/developer/endpoints/users/#get_users_search
queryA query string.
countMax number of users to return
cbCallback function when in async mode
mapping user(void|string uid, void|Callback cb)
Get basic information about a user.
uidAn Instagram user ID. If not given the currently authenticated user will be fetched
cbCallback function when in async mode
protected this_program `()(string client_id, string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Instantiates the default Github API.
See Web.Api.Api() for further information about the arguments
client_idYour application key/id
client_secretYour application secret
redirect_uriThe redirect URI after an authentication
scopeThe application scopes to grant access to
inherit Web.Api.Api : parent
constant string Web.Api.Linkedin.V1.API_URI
The base uri to the API
Any Web.Api.Linkedin.V1.any
Getter for the Any object which is a generic object for making request
to the Linkedin API
Any
Read only
protected mapping default_params()
Default parameters that goes with every call
mapping delete(string path, void|ParamsArg params, void|Callback cb)
Make a generic DELETE request to the Linkedin API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
mapping get(string path, void|ParamsArg params, void|Callback cb)
Make a generic GET request to the Linkedin API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
mapping post(string path, void|ParamsArg params, void|string data, void|Callback cb)
Make a generic POST request to the Linkedin API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramsdatacbCallback for async requests
mapping put(string path, void|ParamsArg params, void|Callback cb)
Make a generic PUT request to the Linkedin API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
A generic wrapper around Method
inherit Method : Method
inherit Web.Api.Api.Method : Method
mixed delete(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
mixed get(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
mixed post(string s, void|ParamsArg p, void|string data, void|Callback cb)
Internal convenience method
mixed put(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
protected this_program `()(string client_id, string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Instantiates the default Twitter API. See https://dev.twitter.com/rest/public for further information.
client_idYour application key/id
client_secretYour application secret
redirect_uriThe redirect URI after an authentication
scopeThe application scopes to grant access to
Web.Api.Api
inherit Web.Api.Api : parent
Any Web.Api.Twitter.V1_1.any
Getter for the Any object which is a generic object for making request
to the Twitter API
Any
Read only
protected mapping default_params()
Default parameters that goes with every call
mapping delete(string path, void|ParamsArg params, void|Callback cb)
Make a generic DELETE request to the Twitter API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
mapping get(string path, void|ParamsArg params, void|Callback cb)
Make a generic GET request to the Twitter API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
mapping post(string path, void|ParamsArg params, void|string data, void|Callback cb)
Make a generic POST request to the Twitter API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramsdatacbCallback for async requests
mapping put(string path, void|ParamsArg params, void|Callback cb)
Make a generic PUT request to the Twitter API.
pathWhat to request. Like me, me/pictures,
[some_id]/something.
paramscbCallback for async requests
A generic wrapper around Method
inherit Method : Method
inherit Web.Api.Api.Method : Method
mixed delete(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
mixed get(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
mixed post(string s, void|ParamsArg p, void|string data, void|Callback cb)
Internal convenience method
mixed put(string s, void|ParamsArg p, void|Callback cb)
Internal convenience method
Various authentication modules and classes.
constant GOOGLE_KEY = "some-key-911bnn5s.apps.googleusercontent.com";
constant GOOGLE_SECRET = "5arQDOugDrtIOVklkIet2q2i";
Web.Auth.Google.Authorization auth;
int main(int argc, array(string) argv)
{
auth = Web.Auth.Google.Authorization(GOOGLE_KEY, GOOGLE_SECRET,
"http://localhost");
// The generated access token will be saved on disk.
string progname = replace(sprintf("%O", object_program(auth)), ".", "_");
string cookie = progname + ".cookie";
// If the cookie exists, set the authentication from the saved values
if (Stdio.exist(cookie)) {
auth->set_from_cookie(Stdio.read_file(cookie));
}
// Not authenticated, can mean no previous authentication is done, or that
// the authentication has expired. Some services have persistent access tokens
// some don't
if (!auth->is_authenticated()) {
// Try to renew the access token of it's renewable
if (auth->is_renewable()) {
write("Trying to refresh token...\n");
string data = auth->refresh_access_token();
Stdio.write_file(cookie, data);
}
else {
// No argument, start the authentication process
if (argc == 1) {
// Get the uri to the authentication page
string uri = auth->get_auth_uri();
write("Opening \"%s\" in browser.\nCopy the contents of the address "
"bar into here: ", Standards.URI(uri));
sleep(1);
string open_app;
// Mac
if (Process.run(({ "which", "open" }))->exitcode == 0) {
open_app = "open";
}
// Linux
else if (Process.run(({ "which", "xdg-open" }))->exitcode == 0) {
open_app = "xdg-open";
}
// ???
else {
open_app = "open";
}
Process.create_process(({ open_app, uri }));
// Wait for the user to paste the string from the address bar
string resp = Stdio.Readline()->read();
mapping p = Web.Auth.query_to_mapping(Standards.URI(resp)->query);
string code;
// This is if the service is OAuth1
if (p->oauth_token) {
auth->set_authentication(p->oauth_token);
code = p->oauth_verifier;
}
// OAuth2
else {
code = p->code;
}
// Get the access token and save the response to disk for later use.
string data = auth->request_access_token(code);
Stdio.write_file(cookie, data);
}
// If the user gives the access code from command line.
else {
string data = auth->request_access_token(argv[1]);
Stdio.write_file(cookie, data);
}
}
}
if (!auth->is_authenticated()) {
werror("Authentication failed");
}
else {
write("Congratulations you are now authenticated\n");
}
}
mapping query_to_mapping(string query)
Turns a query string into a mapping
queryThis class is used to OAuth2 authenticate agains Facebook
inherit .OAuth2.Client : Client
constant Web.Auth.Facebook.SCOPE_EMAIL
constant Web.Auth.Facebook.SCOPE_PUBLISH_ACTIONS
constant Web.Auth.Facebook.SCOPE_ABOUT_ME
constant Web.Auth.Facebook.SCOPE_ACTIONS_BOOKS
constant Web.Auth.Facebook.SCOPE_ACTIONS_MUSIC
constant Web.Auth.Facebook.SCOPE_ACTIONS_NEWS
constant Web.Auth.Facebook.SCOPE_ACTIONS_VIDEO
constant Web.Auth.Facebook.SCOPE_ACTIVITIES
constant Web.Auth.Facebook.SCOPE_BIRTHDAY
constant Web.Auth.Facebook.SCOPE_EDUCATION_HISTORY
constant Web.Auth.Facebook.SCOPE_EVENTS
constant Web.Auth.Facebook.SCOPE_FRIENDS
constant Web.Auth.Facebook.SCOPE_GAMES_ACTIVITY
constant Web.Auth.Facebook.SCOPE_GROUPS
constant Web.Auth.Facebook.SCOPE_HOMETOWN
constant Web.Auth.Facebook.SCOPE_INTERESTS
constant Web.Auth.Facebook.SCOPE_LIKES
constant Web.Auth.Facebook.SCOPE_LOCATION
constant Web.Auth.Facebook.SCOPE_NOTES
constant Web.Auth.Facebook.SCOPE_PHOTOS
constant Web.Auth.Facebook.SCOPE_QUESTIONS
constant Web.Auth.Facebook.SCOPE_RELATIONSHIP_DETAILS
constant Web.Auth.Facebook.SCOPE_RELATIONSHIPS
constant Web.Auth.Facebook.SCOPE_RELIGION_POLITICS
constant Web.Auth.Facebook.SCOPE_STATUS
constant Web.Auth.Facebook.SCOPE_SUBSCRIPTIONS
constant Web.Auth.Facebook.SCOPE_VIDEOS
constant Web.Auth.Facebook.SCOPE_WEBSITE
constant Web.Auth.Facebook.SCOPE_WORK_HISTORY
constant Web.Auth.Facebook.SCOPE_ADS_MANAGEMENT
constant Web.Auth.Facebook.SCOPE_ADS_READ
constant Web.Auth.Facebook.SCOPE_CREATE_EVENT
constant Web.Auth.Facebook.SCOPE_CREATE_NOTE
constant Web.Auth.Facebook.SCOPE_EXPORT_STREAM
constant Web.Auth.Facebook.SCOPE_FRIENDS_ONLINE_PRESENCE
constant Web.Auth.Facebook.SCOPE_MANAGE_FRIENDLISTS
constant Web.Auth.Facebook.SCOPE_MANAGE_NOTIFICATIONS
constant Web.Auth.Facebook.SCOPE_MANAGE_PAGES
constant Web.Auth.Facebook.SCOPE_PHOTO_UPLOAD
constant Web.Auth.Facebook.SCOPE_PUBLISH_STREAM
constant Web.Auth.Facebook.SCOPE_READ_FRIENDLISTS
constant Web.Auth.Facebook.SCOPE_READ_INSIGHTS
constant Web.Auth.Facebook.SCOPE_READ_MAILBOX
constant Web.Auth.Facebook.SCOPE_READ_PAGE_MAILBOXES
constant Web.Auth.Facebook.SCOPE_READ_REQUESTS
constant Web.Auth.Facebook.SCOPE_READ_STREAM
constant Web.Auth.Facebook.SCOPE_RSVP_EVENT
constant Web.Auth.Facebook.SCOPE_SHARE_ITEM
constant Web.Auth.Facebook.SCOPE_SMS
constant Web.Auth.Facebook.SCOPE_STATUS_UPDATE
constant Web.Auth.Facebook.SCOPE_USER_ONLINE_PRESENCE
constant Web.Auth.Facebook.SCOPE_VIDEO_UPLOAD
constant Web.Auth.Facebook.SCOPE_XMPP_LOGIN
constant Web.Auth.Facebook.SCOPE_FRIENDS_ABOUT_ME
constant Web.Auth.Facebook.SCOPE_FRIENDS_ACTIONS_BOOKS
constant Web.Auth.Facebook.SCOPE_FRIENDS_ACTIONS_MUSIC
constant Web.Auth.Facebook.SCOPE_FRIENDS_ACTIONS_NEWS
constant Web.Auth.Facebook.SCOPE_FRIENDS_ACTIONS_VIDEO
constant Web.Auth.Facebook.SCOPE_FRIENDS_ACTIVITIES
constant Web.Auth.Facebook.SCOPE_FRIENDS_BIRTHDAY
constant Web.Auth.Facebook.SCOPE_FRIENDS_EDUCATION_HISTORY
constant Web.Auth.Facebook.SCOPE_FRIENDS_EVENTS
constant Web.Auth.Facebook.SCOPE_FRIENDS_GAMES_ACTIVITY
constant Web.Auth.Facebook.SCOPE_FRIENDS_GROUPS
constant Web.Auth.Facebook.SCOPE_FRIENDS_HOMETOWN
constant Web.Auth.Facebook.SCOPE_FRIENDS_INTERESTS
constant Web.Auth.Facebook.SCOPE_FRIENDS_LIKES
constant Web.Auth.Facebook.SCOPE_FRIENDS_LOCATION
constant Web.Auth.Facebook.SCOPE_FRIENDS_NOTES
constant Web.Auth.Facebook.SCOPE_FRIENDS_PHOTOS
constant Web.Auth.Facebook.SCOPE_FRIENDS_QUESTIONS
constant Web.Auth.Facebook.SCOPE_FRIENDS_RELATIONSHIP_DETAILS
constant Web.Auth.Facebook.SCOPE_FRIENDS_RELATIONSHIPS
constant Web.Auth.Facebook.SCOPE_FRIENDS_RELIGION_POLITICS
constant Web.Auth.Facebook.SCOPE_FRIENDS_STATUS
constant Web.Auth.Facebook.SCOPE_FRIENDS_SUBSCRIPTIONS
constant Web.Auth.Facebook.SCOPE_FRIENDS_VIDEOS
constant Web.Auth.Facebook.SCOPE_FRIENDS_WEBSITE
constant Web.Auth.Facebook.SCOPE_FRIENDS_WORK_HISTORY
This class is used to OAuth2 authenticate against Github
inherit .OAuth2.Client : Client
constant Web.Auth.Github.SCOPE_REPO
constant Web.Auth.Github.SCOPE_GIST
constant Web.Auth.Github.SCOPE_USER
constant Web.Auth.Github.SCOPE_USER_EMAIL
constant Web.Auth.Github.SCOPE_USER_FOLLOW
constant Web.Auth.Github.SCOPE_PUBLIC_REPO
constant Web.Auth.Github.SCOPE_REPO_DEPLOYMENT
constant Web.Auth.Github.SCOPE_REPO_STATUS
constant Web.Auth.Github.SCOPE_DELETE_REPO
constant Web.Auth.Github.SCOPE_NOTIFICATIONS
constant Web.Auth.Github.SCOPE_READ_REPO_HOOK
constant Web.Auth.Github.SCOPE_WRITE_REPO_HOOK
constant Web.Auth.Github.SCOPE_ADMIN_REPO_HOOK
constant Web.Auth.Github.SCOPE_READ_ORG
constant Web.Auth.Github.SCOPE_WRITE_ORG
constant Web.Auth.Github.SCOPE_ADMIN_ORG
constant Web.Auth.Github.SCOPE_READ_PUBLIC_KEY
constant Web.Auth.Github.SCOPE_WRITE_PUBLIC_KEY
constant Web.Auth.Github.SCOPE_ADMIN_PUBLIC_KEY
This class is used to OAuth2 authenticate agains Instagram
inherit .OAuth2.Client : Client
constant string Web.Auth.Instagram.OAUTH_AUTH_URI
Instagram authorization URI
constant string Web.Auth.Instagram.OAUTH_TOKEN_URI
Instagram request access token URI
protected string Web.Auth.Instagram._scope
Default scope
protected multiset(string) Web.Auth.Instagram.valid_scopes
Valid Instagram scopes
This class is used to OAuth2 authenticate against LinkedIn
inherit .OAuth2.Client : Client
Web.Auth.Linkedin.protected constantDEFAULT_SCOPE
Default scope to use if none is set explicitly
protected constantint Web.Auth.Linkedin.STATE
Adds the state parameter to the request which will have the value of a random string
constant Web.Auth.Linkedin.SCOPE_R_BASIC
constant Web.Auth.Linkedin.SCOPE_R_NETWORK
constant Web.Auth.Linkedin.SCOPE_RW_GROUPS
constant Web.Auth.Linkedin.SCOPE_R_FULLPROFILE
constant Web.Auth.Linkedin.SCOPE_R_CONTACTINFO
constant Web.Auth.Linkedin.SCOPE_W_MESSAGES
constant Web.Auth.Linkedin.SCOPE_R_EMAILADDRESS
constant Web.Auth.Linkedin.SCOPE_RW_NUS
Representation of a parameter.
Many Social web services use a RESTful communication and have similiar API's. This class is suitable for many RESTful web services and if this class doesn't suite a particular service, just inherit this class and rewrite the behaviour where needed.
Params
protected string Web.Auth.Param.name
The name of the parameter
protected string Web.Auth.Param.value
The value of the parameter
string sprintf(string format, ... Web.Auth.Param arg ... )
String format method
tbool res = Web.Auth.Param() < other
Checks if this object is less than other
otherbool res = Web.Auth.Param() == other
Comparer method. Checks if other equals this object
otherbool res = Web.Auth.Param() > other
Checks if this object is greater than other
otherWeb.Auth.Param Web.Auth.Param(string name, mixed value)
Creates a new instance of Param
namevaluestring get_name()
Getter for the parameter name
string get_value()
Getter for the parameter value
private void low_set_value(string v)
Makes sure v to set as value is in UTF-8 encoding
vstring name_value()
Returns the name and value as querystring key/value pair
string name_value_encoded()
Same as name_value() except this URL encodes the value.
void set_name(string name)
Setter for the parameter name
namevoid set_value(mixed value)
Setter for the parameter value
valueParameter collection class
Param
protected array(Param) Web.Auth.Params.params
The parameters.
array(string) indices( Web.Auth.Params arg )
Parameter keys
string sprintf(string format, ... Web.Auth.Params arg ... )
String format method
tarray(string) values( Web.Auth.Params arg )
Parameter values
this_program res = Web.Auth.Params() + p
Add p to the array of Parameters
pA new Params object
this_program res = Web.Auth.Params() - p
Remove p from the Parameters array of the current object.
pParam|zero res = Web.Auth.Params()[ key ]
Index lookup
keyThe name of a Paramerter to find.
this_program add_mapping(mapping value)
Add a mapping of key/value pairs to the current instance
valueThe object being called
(int)Web.Auth.Params()
(float)Web.Auth.Params()
(string)Web.Auth.Params()
(array)Web.Auth.Params()
(mapping)Web.Auth.Params()
(multiset)Web.Auth.Params()
Casting method
howthis_program clone()
Clone the current instance
Web.Auth.Params Web.Auth.Params(Param ... args)
Creates a new instance of Params
argsarray(Param) get_params()
Returns the array of Parameters
string sign(string secret)
Sign the parameters
secretThe API secret
mapping(string:mixed) to_mapping()
Turns the parameters into a mapping
string to_query()
Turns the parameters into a query string
Tumblr authentication class
inherit .OAuth.Authentication : Authentication
constant string Web.Auth.Tumblr.ACCESS_TOKEN_URL
The endpoint to send request for an access token
constant string Web.Auth.Tumblr.REQUEST_TOKEN_URL
The endpoint to send request for a request token
constant string Web.Auth.Tumblr.USER_AUTH_URL
The enpoint to redirect to when authenticating an application
Twitter authentication class
inherit Web.Auth.OAuth.Authentication : Authentication
constant string Web.Auth.Twitter.ACCESS_TOKEN_URL
The endpoint to send request for an access token
constant string Web.Auth.Twitter.REQUEST_TOKEN_URL
The endpoint to send request for a request token
constant string Web.Auth.Twitter.USER_AUTH_URL
The enpoint to redirect to when authenticating an application
Google authentication classes.
Google Analytics authorization class
inherit Authorization : Authorization
constant string Web.Auth.Google.Analytics.SCOPE_RO
constant string Web.Auth.Google.Analytics.SCOPE_RW
constant string Web.Auth.Google.Analytics.SCOPE_EDIT
constant string Web.Auth.Google.Analytics.SCOPE_MANAGE_USERS
constant string Web.Auth.Google.Analytics.SCOPE_MANAGE_USERS_RO
Authentication scopes
protected string Web.Auth.Google.Analytics._scope
Default scope
multiset(string) Web.Auth.Google.Analytics.valid_scopes
All valid scopes
Default Google authorization class
inherit Web.Auth.OAuth2.Client : Client
constant string Web.Auth.Google.Authorization.OAUTH_AUTH_URI
constant string Web.Auth.Google.Authorization.SCOPE_EMAIL
constant string Web.Auth.Google.Authorization.SCOPE_OPENID
constant string Web.Auth.Google.Authorization.SCOPE_PROFILE
multiset(string) Web.Auth.Google.Authorization.valid_scopes
All valid scopes
Google+ authorization class
inherit Authorization : Authorization
constant string Web.Auth.Google.Plus.SCOPE_ME
constant string Web.Auth.Google.Plus.SCOPE_LOGIN
Authentication scopes
protected string Web.Auth.Google.Plus._scope
Default scope
protected multiset(string) Web.Auth.Google.Plus.valid_scopes
All valid scopes
OAuth module
Example
import Web.Auth.OAuth;
string endpoint = "http://twitter.com/users/show.xml";
Consumer consumer = Consumer(my_consumer_key, my_consumer_secret);
Token token = Token(my_access_token_key, my_access_token_secret);
Params params = Params(Param("user_id", 12345));
Request request = request(consumer, token, params);
request->sign_request(Signature.HMAC_SHA1, consumer, token);
Protocols.HTTP.Query query = request->submit();
if (query->status != 200)
error("Bad response status: %d\n", query->status);
werror("Data is: %s\n", query->data());
constant string Web.Auth.OAuth.CALLBACK_KEY
Query string variable name for a callback URL.
constant string Web.Auth.OAuth.CONSUMER_KEY_KEY
Query string variable name for the consumer key.
constant string Web.Auth.OAuth.NONCE_KEY
Query string variable name for the nonce.
constant string Web.Auth.OAuth.SIGNATURE_KEY
Query string variable name for the signature.
constant string Web.Auth.OAuth.SIGNATURE_METHOD_KEY
Query string variable name for the signature method.
constant string Web.Auth.OAuth.TIMESTAMP_KEY
Query string variable name for the timestamp.
constant string Web.Auth.OAuth.TOKEN_KEY
Query string variable name for the token key.
constant string Web.Auth.OAuth.TOKEN_SECRET_KEY
Query string variable name for the token secret.
constant string Web.Auth.OAuth.VERSION
Verion
constant string Web.Auth.OAuth.VERSION_KEY
Query string variable name for the version.
Params get_default_params(Consumer consumer, Token token)
Returns the default params for authentication/signing.
string nonce()
Generates a nonce.
string normalize_uri(string|Standards.URI uri)
Normalizes uri
uriA string or Standards.URI.
Params query_to_params(string|Standards.URI|mapping q)
Converts a query string, or a mapping, into a Params object.
Request request(string|Standards.URI uri, Consumer consumer, Token token, void|Params params, void|string http_method)
Helper method to create a Request object.
An error if consumer is null.
http_methodDefaults to GET.
The purpose of this class is to streamline OAuth1 with OAuth2. This class will not do much on it's own, since its purpose is to be inherited by some other class implementing a specific authorization service.
inherit .Client : oauth
inherit Web.Auth.OAuth2.Client : oauth2
constant string Web.Auth.OAuth.Authentication.ACCESS_TOKEN_URL
The endpoint to send request for an access token.
constant string Web.Auth.OAuth.Authentication.REQUEST_TOKEN_URL
The endpoint to send request for a request token.
constant string Web.Auth.OAuth.Authentication.USER_AUTH_URL
The enpoint to redirect to when authorize an application.
string call(string|Standards.URI url, void|mapping|.Params args, void|string method)
Does the low level HTTP call to a service.
An error if HTTP status != 200
urlThe full address to the service e.g: http://twitter.com/direct_messages.xml
argsArguments to send with the request
mehodThe HTTP method to use
Web.Auth.OAuth.Authentication Web.Auth.OAuth.Authentication(string client_id, string client_secret, void|string redir, void|string|array(string)|multiset(string) scope)
Creates an OAuth object.
client_idThe application ID.
client_secretThe application secret.
redirect_uriWhere the authorization page should redirect back to. This must be a
fully qualified domain name. This can be set/overridden in
get_request_token().
scopeExtended permissions to use for this authentication. This can be
set/overridden in get_auth_uri().
.Token get_access_token(void|string oauth_verifier)
Fetches an access token.
string get_auth_uri(void|mapping args)
.Token get_request_token(void|string|Standards.URI callback_uri, void|bool force_login)
Fetches a request token.
callback_uriOverrides the callback uri in the application settings.
force_loginIf 1 forces the user to provide its credentials at the Twitter login page.
bool is_authenticated()
Returns true if authenticated.
protected string low_get_access_token(void|string oauth_verifier)
Fetches an access token.
protected string normalize_method(string method)
Normalizes and verifies the HTTP method to be used in a HTTP call.
mapping parse_error_xml(string xml)
Parses an error xml tree.
A mapping:
|
|
string request_access_token(string code)
Same as get_access_token except this returns a string to comply
with the OAuth2 authentication process.
void set_authentication(string key, void|string secret)
Set authentication.
this_program set_from_cookie(string encoded_value)
Populate this object with the result from
request_access_token().
The object being called.
OAuth client class.
This class is of no use by it self. It's intended to be inherited by classes that uses OAuth authorization.
protected string Web.Auth.OAuth.Client.access_token_url
The endpoint to send request for an access token.
protected Consumer Web.Auth.OAuth.Client.consumer
The consumer object.
protected string Web.Auth.OAuth.Client.request_token_url
The endpoint to send request for a request token.
protected Token Web.Auth.OAuth.Client.token
The token object.
protected string Web.Auth.OAuth.Client.user_auth_url
The enpoint to redirect to when authorize an application.
Web.Auth.OAuth.Client Web.Auth.OAuth.Client(Consumer consumer, Token token)
Create a new Client.
This class must be inherited
string get_access_token_url()
Returns the url for requesting an access token.
Consumer get_consumer()
Returns the consumer.
string get_request_token_url()
Returns the url for requesting a request token.
Token get_token()
Returns the token.
string get_user_auth_url()
Returns the url for authorizing an application.
void set_token(Token token)
void set_token(string token_key, string token_secret)
Set the Token.
keyEither a Token object or a token key.
secretThe token secret if key is a token key.
An OAuth user
string|Standards.URI Web.Auth.OAuth.Consumer.callback
Callback url that the remote verifying page will return to.
string Web.Auth.OAuth.Consumer.key
Consumer key
string Web.Auth.OAuth.Consumer.secret
Consumer secret
Web.Auth.OAuth.Consumer Web.Auth.OAuth.Consumer(string key, string secret, void|string|Standards.URI callback)
Creates a new Consumer object.
callbackNOTE: Has no effect in this implementation.
Represents a query string parameter, i.e. key=value.
protected string Web.Auth.OAuth.Param.name
Param name
protected string Web.Auth.OAuth.Param.value
Param value
bool res = Web.Auth.OAuth.Param() == other
Comparer method. Checks if other equals this object.
bool res = Web.Auth.OAuth.Param() > other
Checks if this object is greater than other.
object|zero res = Web.Auth.OAuth.Param()[ key ]
Index lookup.
Web.Auth.OAuth.Param Web.Auth.OAuth.Param(string name, mixed value)
Creates a new Param.
string get_encoded_value()
Returns the value encoded.
string get_name()
Getter for the name attribute.
string get_signature()
Returns the name and value for usage in a signature string.
string get_value()
Getter for the value attribute.
void set_name(string value)
Setter for the value attribute.
void set_value(mixed _value)
Setter for the value attribute.
Collection of Param
private array(Param) Web.Auth.OAuth.Params.params
Storage for Params of this object.
int(0..) sizeof( Web.Auth.OAuth.Params arg )
Returns the size of the params array.
mixed values( Web.Auth.OAuth.Params arg )
Returns the params.
this_program res = Web.Auth.OAuth.Params() + p
Append p to the internal array.
The object being called.
this_program res = Web.Auth.OAuth.Params() - p
Removes p from the internal array.
The object being called.
mixed res = Web.Auth.OAuth.Params()[ key ]
Index lookup
If no Param is found returns 0.
If multiple Params with name key is found a new Params object
with the found params will be retured.
If only one Param is found that param will be returned.
this_program add_mapping(mapping args)
Append mapping args as Param objects.
The object being called.
(mapping)Web.Auth.OAuth.Params()
Supports casting to mapping, which will map parameter names to their values.
Web.Auth.OAuth.Params Web.Auth.OAuth.Params(Param ... params)
Create a new Params
paramsArbitrary number of Param objects.
string get_auth_header()
Returns the params for usage in an authentication header.
mapping get_encoded_variables()
Returns the parameters as a mapping with encoded values.
get_variables()
string get_query_string()
Returns the parameters as a query string.
string get_signature()
Returns the parameters for usage in a signature base string.
mapping get_variables()
Returns the parameters as a mapping.
Class for building a signed request and querying the remote service.
protected string Web.Auth.OAuth.Request.base_string
The signature basestring.
protected string Web.Auth.OAuth.Request.method
String representation of the HTTP method.
protected Params Web.Auth.OAuth.Request.params
The parameters to send.
protected Standards.URI Web.Auth.OAuth.Request.uri
The remote endpoint.
this_program add_param(Param|string name, void|string value)
Add a param.
The object being called.
void add_params(Params params)
Add a Params object.
(string)Web.Auth.OAuth.Request()
It is possible to case the Request object to a string, which will be the request URL.
Web.Auth.OAuth.Request Web.Auth.OAuth.Request(string|Standards.URI uri, string http_method, void|Params params)
Creates a new Request.
request()
uriThe uri to request.
http_methodThe HTTP method to use. Either "GET" or "POST".
Param|zero get_param(string name)
Get param with name name.
Params get_params()
Returns the Params collection.
string get_signature_base()
Generates a signature base.
void sign_request(int signature_type, Consumer consumer, Token token)
Signs the request.
signature_typeOne of the types in Signature.
Protocols.HTTP.Query submit(void|mapping extra_headers)
Send the request to the remote endpoint.
Token class.
string|zero Web.Auth.OAuth.Token.key
string|zero Web.Auth.OAuth.Token.secret
protected local void __create__(string|zero key, string|zero secret)
(string)Web.Auth.OAuth.Token()
Only supports casting to string wich will return a query string of the object.
Web.Auth.OAuth.Token Web.Auth.OAuth.Token(string|zero key, string|zero secret)
Module for creating OAuth signatures
constant int Web.Auth.OAuth.Signature.HMAC_SHA1
Signature type for hmac sha1 signing.
protected constantint Web.Auth.OAuth.Signature.NONE
Signature type for the Base class.
constant int Web.Auth.OAuth.Signature.PLAINTEXT
Signature type for plaintext signing.
constant int Web.Auth.OAuth.Signature.RSA_SHA1
Signature type for rsa sha1 signing.
constant Web.Auth.OAuth.Signature.SIGTYPE
Signature types to signature key mapping.
Base get_object(int type)
Returns a signature class for signing with type.
An error if type is unknown
typeEither PLAINTEXT, HMAC_SHA1 or RSA_SHA1.
Base signature class.
protected string Web.Auth.OAuth.Signature.Base.method
String representation of signature type.
protected int Web.Auth.OAuth.Signature.Base.type
Signature type.
string build_signature(Request request, Consumer consumer, Token token)
Builds the signature string.
string get_method()
Returns the method.
int get_type()
Returns the type.
HMAC_SHA1 signature.
inherit Base : Base
string build_signature(Request request, Consumer consumer, Token token)
Builds the signature string.
Plaintext signature.
inherit Base : Base
string build_signature(Request request, Consumer consumer, Token token)
Builds the signature string.
RSA_SHA1 signature. Currently not implemented.
inherit Base : Base
string build_signature(Request request, Consumer consumer, Token token)
Builds the signature string.
OAuth2 client
A base OAuth2 class can be instantiated either via `()
(Web.Auth.OAuth2(params...)) or via Web.Auth.OAuth2.Base().
protected Base `()(string client_id, string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Instantiate a generic OAuth2 Base class.
client_idThe application ID.
client_secretThe application secret.
redirect_uriWhere the authorization page should redirect back to. This must be a
fully qualified domain name. This can be set/overridden in
Base()->get_auth_uri() and/or Base()->set_redirect_uri().
scopeExtended permissions to use for this authentication. This can be
set/overridden in Base()->get_auth_uri().
Generic OAuth2 client class.
protected constantint Web.Auth.OAuth2.Base.STATE
Some OAuth2 verifiers need the STATE parameter. If this is not 0 a random string will be generated and the state parameter will be added to the request.
protected constantstring Web.Auth.OAuth2.Base.USER_AGENT
User agent string.
protected constantstring Web.Auth.OAuth2.Base.VERSION
Version of this implementation.
protected string Web.Auth.OAuth2.Base._access_type
Access type of the request.
protected string Web.Auth.OAuth2.Base._client_id
The application ID.
protected string Web.Auth.OAuth2.Base._client_secret
The application secret.
protected string Web.Auth.OAuth2.Base._grant_type
GRANT_TYPE_AUTHORIZATION_CODE for apps running on a web server
GRANT_TYPE_IMPLICIT for browser-based or mobile apps
GRANT_TYPE_PASSWORD for logging in with a username and password
GRANT_TYPE_CLIENT_CREDENTIALS for application access
protected string Web.Auth.OAuth2.Base._redirect_uri
Where the authorization page should redirect to.
protected string Web.Auth.OAuth2.Base._response_type
RESPONSE_TYPE_CODE for apps running on a webserver
RESPONSE_TYPE_TOKEN for apps browser-based or mobile apps
protected string|array(string)|multiset(string) Web.Auth.OAuth2.Base._scope
The scope of the authorization. Limits the access.
string Web.Auth.OAuth2.Base.access_token
Getting
Getter for access_token.
Setting
Getter for access_token.
Calendar.Second Web.Auth.OAuth2.Base.created
Getter for when the authentication was created.
Read only
Calendar.Second Web.Auth.OAuth2.Base.expires
Getter for when the authentication expires.
Read only
int(1..) Web.Auth.OAuth2.Base.http_request_timeout
Request timeout in seconds. Only affects async queries.
string Web.Auth.OAuth2.Base.refresh_token
Getter for refresh_token.
Read only
protected mapping Web.Auth.OAuth2.Base.request_headers
Default request headers.
string Web.Auth.OAuth2.Base.token_type
Getter for token_type.
Read only
mapping Web.Auth.OAuth2.Base.user
Getter for the user mapping which may or may not be set.
Read only
protected multiset(string) Web.Auth.OAuth2.Base.valid_scopes
A mapping of valid scopes for the API.
(int)Web.Auth.OAuth2.Base()
(float)Web.Auth.OAuth2.Base()
(string)Web.Auth.OAuth2.Base()
(array)Web.Auth.OAuth2.Base()
(mapping)Web.Auth.OAuth2.Base()
(multiset)Web.Auth.OAuth2.Base()
If casted to string the access_token will be returned. If casted to int the expires timestamp will be returned.
Web.Auth.OAuth2.Base Web.Auth.OAuth2.Base(string client_id, string client_secret, void|string redirect_uri, void|string|array(string)|multiset(string) scope)
Creates an OAuth2 object.
client_idThe application ID.
client_secretThe application secret.
redirect_uriWhere the authorization page should redirect back to. This must be a
fully qualified domain name. This can be set/overridden in
get_auth_uri() and/or set_redirect_uri().
scopeExtended permissions to use for this authentication. This can be
set/overridden in get_auth_uri().
protected bool decode_access_token_response(string r)
Decode the response from an authentication call. If the response
was ok the internal mapping gettable will be populated with
the members/variables in r.
rThe response from do_query()
protected string|zero do_query(string|zero oauth_token_uri, Web.Auth.Params p, void|function(bool, string:void) async_cb)
Send a request to oauth_token_uri with params p
async_cbIf given an async request will be made and this function will
be called when the request is finished. The first argument
passed to the callback will be true or false
depending on if the request was successfull or not. The second
argument will be a string. If the request failed it will be an
error message. If it succeeded it will be the result as a
string encoded with predef::encode_value().
string get_access_type()
Getter for the access type, if any.
string get_auth_uri(string|zero auth_uri, void|mapping args)
Returns an authorization URI.
auth_uriThe URI to the remote authorization page
argsAdditional argument.
string get_client_id()
Returns the application ID.
string get_client_secret()
Returns the application secret.
protected Web.Auth.Params get_default_params(void|string grant_type)
Returns a set of default parameters.
string get_grant_type()
Returns the grant_type of the object.
string get_redirect_uri()
Returns the redirect uri.
mixed get_scope()
Returns the scope/scopes set, if any.
string|zero get_token_from_jwt(string jwt, void|string token_endpoint, string|void sub, void|function(bool, string:void) async_cb)
Get an access_token from a JWT. http://jwt.io/
jwtJSON string.
token_endpointURI to the request access_token endpoint.
subEmail/id of the requesting user.
async_callbackIf given the request will be made asynchronously. The
signature is callback(bool, string). If successful the
second argument will be the result encoded with
predef::encode_value(), which can be stored and later used
to populate an instance via set_from_cookie().
Web.encode_jwt()
protected string get_valid_scopes(string|array(string)|multiset(string) s)
Returns a space separated list of all valid scopes in s.
s can be a comma or space separated string or an array or
multiset of strings. Each element in s will be matched
against the valid scopes set in the module inheriting this
class.
bool has_scope(string scope)
Check if scope exists in this object.
bool is_authenticated()
Do we have a valid authentication.
bool is_expired()
Checks if this authorization has expired.
bool is_renewable()
Checks if the authorization is renewable. This is true if the
Web.Auth.OAuth2.Base() object has been populated from
Web.Auth.OAuth2.Base()->set_from_cookie(), i.e the user has been
authorized but the session has expired.
multiset list_valid_scopes()
Returns the valid scopes.
string|zero refresh_access_token(string|zero oauth_token_uri, void|function(bool, string:void) async_cb)
Refreshes the access token, if a refresh token exists in the object.
oauth_token_uriEndpoint of the authentication service.
async_cbIf given an async request will be made and this function will
be called when the request is finished. The first argument
passed to the callback will be true or false
depending on if the request was successfull or not. The second
argument will be a string. If the request failed it will be an
error message. If it succeeded it will be the result as a
string encoded with predef::encode_value().
string|zero request_access_token(string|zero oauth_token_uri, string code, void|function(bool, string:void) async_cb)
Requests an access token.
An error if the access token request fails.
oauth_token_uriAn URI received from get_auth_uri().
codeThe code returned from the authorization page via get_auth_uri().
async_cbIf given an async request will be made and this function will
be called when the request is finished. The first argument
passed to the callback will be true or false
depending on if the request was successfull or not. The second
argument will be a string. If the request failed it will be an
error message. If it succeeded it will be the result as a
string encoded with predef::encode_value().
If OK a Pike encoded mapping (i.e it's a string) is
returned which can be used to populate an Web.Auth.OAuth2
object at a later time.
The mapping looks like
|
|
|
|
|
Depending on the authorization service it might also contain more members.
void set_access_type(string access_type)
Set access_type explicilty.
access_typeLike: offline
this_program set_from_cookie(string encoded_value)
Populate this object with the result from request_access_token().
An error if the decoding of encoded_value fails.
encoded_valueThe value from a previous call to request_access_token() or
refresh_access_token().
The object being called.
void set_grant_type(GrantType type)
Set the grant type to use.
void set_redirect_uri(string uri)
Setter for the redirect uri.
void set_scope(string scope)
Set scopes.
private mixed try_get_error(string data)
Try to get an error message from data. Only successful if
data is a JSON string and contains the key error.
Grant types.
constant Web.Auth.OAuth2.Base.GRANT_TYPE_AUTHORIZATION_CODE
constant Web.Auth.OAuth2.Base.GRANT_TYPE_CLIENT_CREDENTIALS
constant Web.Auth.OAuth2.Base.GRANT_TYPE_IMPLICIT
constant Web.Auth.OAuth2.Base.GRANT_TYPE_JWT
constant Web.Auth.OAuth2.Base.GRANT_TYPE_PASSWORD
constant Web.Auth.OAuth2.Base.GRANT_TYPE_REFRESH_TOKEN
Response types.
constant Web.Auth.OAuth2.Base.RESPONSE_TYPE_CODE
constant Web.Auth.OAuth2.Base.RESPONSE_TYPE_TOKEN
This class is intended to be extended by classes implementing different OAuth2 services.
inherit Base : Base
protected constantint Web.Auth.OAuth2.Client.DEFAULT_SCOPE
Scope to set if none is set.
constant int Web.Auth.OAuth2.Client.OAUTH_AUTH_URI
Authorization URI.
constant int Web.Auth.OAuth2.Client.OAUTH_TOKEN_URI
Request access token URI.
string get_auth_uri(void|mapping args)
Returns an authorization URI.
argsAdditional argument.
string get_token_from_jwt(string jwt, void|string sub, void|function(bool, string:void) async_cb)
Make a JWT (JSON Web Token) authentication.
string refresh_access_token(void|function(bool, string:void) async_cb)
Refreshes the access token, if a refresh token exists in the object.
async_cbIf given an async request will be made and this function will
be called when the request is finished. The first argument
passed to the callback will be true or false
depending on if the request was successfull or not. The second
argument will be a string. If the request failed it will be an
error message. If it succeeded it will be the result as a
string encoded with predef::encode_value().
string request_access_token(string code, void|function(bool, string:void) async_cb)
Requests an access token.
An error if the access token request fails.
codeThe code returned from the authorization page via get_auth_uri().
async_cbIf given an async request will be made and this function will
be called when the request is finished. The first argument
passed to the callback will be true or false
depending on if the request was successfull or not. The second
argument will be a string. If the request failed it will be an
error message. If it succeeded it will be the result as a
string encoded with predef::encode_value().
If OK a Pike encoded mapping (i.e it's a string) is
returned which can be used to populate an Base object at a
later time.
The mapping looks like
|
|
|
|
|
Depending on the authorization service it might also contain more members.
Retrieves information about a CGI request from the environment and creates an object with the request information easily formatted.
array(string) Web.CGI.Request.client
multiset(string) Web.CGI.Request.config
If used with Roxen or Caudium webservers, this field will be populated with "config" information.
mapping(string:string) Web.CGI.Request.cookies
string Web.CGI.Request.data
string Web.CGI.Request.method
mapping(string:int|string|array(string)) Web.CGI.Request.misc
multiset(string) Web.CGI.Request.pragma
multiset(string) Web.CGI.Request.prestate
If used with Roxen or Caudium webservers, this field will be populated with "prestate" information.
string Web.CGI.Request.prot
string Web.CGI.Request.query
string Web.CGI.Request.rest_query
array(string) Web.CGI.Request.referer
string Web.CGI.Request.remoteaddr
string Web.CGI.Request.remotehost
multiset(string) Web.CGI.Request.supports
If used with Roxen or Caudium webservers, this field will be populated with "supports" information.
mapping(string:array(string)) Web.CGI.Request.variables
Web.CGI.Request Web.CGI.Request()
creates the request object. To use, create a Request object while running in a CGI environment. Environment variables will be parsed and inserted in the appropriate fields of the resulting object.
This module implements a generic web crawler.
Features:
Fully asynchronous operation (Several hundred simultaneous requests)
Supports the /robots.txt exclusion standard
Extensible
URI Queues
Allow/Deny rules
Configurable
Number of concurrent fetchers
Bits per second (bandwidth throttling)
Number of concurrent fetchers per host
Delay between fetches from the same host
Supports HTTP and HTTPS
inherit Queue : Queue
Stats Web.Crawler.ComplexQueue.stats
Policy Web.Crawler.ComplexQueue.policy
protected local void __create__(Stats stats, Policy policy)
Web.Crawler.ComplexQueue Web.Crawler.ComplexQueue(Stats stats, Policy policy)
Web.Crawler.Crawler Web.Crawler.Crawler(Queue _queue, function(:void) _page_cb, function(:void) _error_cb, function(:void) _done_cb, function(:void) _prepare_cb, string|array(string)|Standards.URI|array(Standards.URI) start_uri, mixed ... _args)
_page_cbfunction called when a page is retreived. Arguments are: Standards.URI uri, mixed data, mapping headers, mixed ... args. should return an array containing additional links found within data that will be analyzed for insertion into the crawler queue (assuming they are allowed by the allow/deny rulesets.
_error_cbfunction called when an error is received from a server. Arguments are: Standards.URI real_uri, int status_code, mapping headers, mixed ... args. Returns void.
_done_cbfunction called when crawl is complete. Accepts mixed ... args and returns void.
_prepare_cbargument called before a uri is retrieved. may be used to alter the request. Argument is Standards.URI uri. Returns array with element 0 of Standards.URI uri, element 1 is a header mapping for the outgoing request.
start_urilocation to start the crawl from.
_argsoptional arguments sent as the last argument to the callback functions.
A rule that uses glob expressions
patterna glob pattern that the rule will match against.
GlobRule("http://pike.lysator.liu.se/*.xml");
inherit Rule : Rule
string Web.Crawler.GlobRule.pattern
protected local void __create__(string pattern)
Web.Crawler.GlobRule Web.Crawler.GlobRule(string pattern)
Memory queue
inherit Queue : Queue
Web.Crawler.MemoryQueue Web.Crawler.MemoryQueue(Stats _stats, Policy _policy, RuleSet _allow, RuleSet _deny)
int|Standards.URI get()
Get the next URI to index. Returns -1 if there are no URIs to index at the time of the function call, with respect to bandwidth throttling, outstanding requests and other limits. Returns 0 if there are no more URIs to index.
void put(string|array(string)|Standards.URI|array(Standards.URI) uri)
Put one or several URIs in the queue. Any URIs that were already present in the queue are silently disregarded.
inherit Queue : Queue
Web.Crawler.MySQLQueue Web.Crawler.MySQLQueue(Stats _stats, Policy _policy, string _host, string _table, void|RuleSet _allow, void|RuleSet _deny)
The crawler policy object.
int Web.Crawler.Policy.bandwidth_throttling_floating_window_width
Bandwidth throttling floating window width. Defaults to 30.
int Web.Crawler.Policy.max_bits_per_second_per_host
Maximum number of bits per second, per host. Defaults to off (0).
int Web.Crawler.Policy.max_bits_per_second_total
Maximum number of bits per second. Defaults to off (0).
int Web.Crawler.Policy.max_concurrent_fetchers
Maximum number of fetchers. Defaults to 100.
int Web.Crawler.Policy.max_concurrent_fetchers_per_host
Maximum concurrent fetchers per host. Defaults to 1.
int Web.Crawler.Policy.min_delay_per_host
Minimum delay per host. Defaults to 0.
A crawler queue. Does not need to be reentrant safe. The Crawler always runs in just one thread.
int|Standards.URI get()
Get the next URI to index. Returns -1 if there are no URIs to index at the time of the function call, with respect to bandwidth throttling and other limits. Returns 0 if there are no more URIs to index.
void put(string|array(string)|Standards.URI|array(Standards.URI) uri)
Put one or several URIs in the queue. Any URIs that were already present in the queue are silently disregarded.
A rule that uses Regexp expressions
inherit Rule : Rule
Web.Crawler.RegexpRule Web.Crawler.RegexpRule(string re)
rea string describing the Regexp expression
Abstract rule class.
int check(string|Standards.URI uri)
A set of rules
void add_rule(Rule rule)
add a rule to the ruleset
void remove_rule(Rule rule)
remove a rule from the ruleset
Statistics.
int Web.Crawler.Stats.window_width
int Web.Crawler.Stats.granularity
protected local void __create__(int window_width, int granularity)
void bytes_read_callback(Standards.URI uri, int num_bytes_read)
This callback is called when data has arrived for a presently crawled URI, but no more often than once a second.
void close_callback(Standards.URI uri)
This callback is called whenever the crawling of a URI is finished or fails.
Web.Crawler.Stats Web.Crawler.Stats(int window_width, int granularity)
This is an implementation of the Engine.IO server-side communication's driver. It basically is a real-time bidirectional packet-oriented communication's protocol for communicating between a webbrowser and a server.
The driver mainly is a wrapper around Protocols.WebSocket with
the addition of two fallback mechanisms that work around limitations
imposed by firewalls and/or older browsers that prevent native
Protocols.WebSocket connections from functioning.
This module supports the following features:
It supports both UTF-8 and binary packets.
If both sides support Protocols.WebSocket, then
packet sizes are essentially unlimited.
The fallback methods have a limit on packet sizes from browser
to server, determined by the maximum POST request size the involved
network components allow.
In most cases, Engine.IO is not used directly in applications. Instead one uses Socket.IO instead.
Sample small implementation of an EngineIO server farm:
class mysocket { inherit Web.EngineIO.Socket; void echo(string|Stdio.Buffer msg) { write(0, msg); } } void wsrequest(array(string) protocols, object req) { httprequest(req); } void httprequest(object req) { switch (req.not_query) { case "/engine.io/": mysocket client = Web.EngineIO.farm(mysocket, req); if (client) { client.open(client.echo); client.write(0, "Hello world!"); } break; } } int main(int argc, array(string) argv) { Protocols.WebSocket.Port(httprequest, wsrequest, 80); return -1; }
farm, Web.SocketIO, Protocols.WebSocket,
http://github.com/socketio/engine.io-protocol,
http://socket.io/
constant int Web.EngineIO.protocol
Engine.IO protocol version.
final mapping Web.EngineIO.options
Global options for all EngineIO instances.
Socket.create(), Gz.compress()
final Socket|zero farm(program createtype, Protocols.WebSocket.Request req, void|mapping(string:mixed) options)
optionsOptional options to override the defaults.
This parameter is passed down as is to the underlying
Socket.
Socket.create()
constant Web.EngineIO.BASE64
constant Web.EngineIO.OPEN
constant Web.EngineIO.CLOSE
constant Web.EngineIO.PING
constant Web.EngineIO.PONG
constant Web.EngineIO.MESSAGE
constant Web.EngineIO.UPGRADE
constant Web.EngineIO.NOOP
constant Web.EngineIO.ACK
constant Web.EngineIO.SENDQEMPTY
constant Web.EngineIO.SHUTDOWN
Runs a single Engine.IO session.
final Protocols.WebSocket.Request Web.EngineIO.Socket.request
Contains the last request seen on this connection. Can be used to obtain cookies etc.
final string Web.EngineIO.Socket.sid
The unique session identifier (in the Engine.IO docs referred to as simply: id).
final void close()
Close the socket signalling the other side.
Web.EngineIO.Socket Web.EngineIO.Socket(Protocols.WebSocket.Request req, void|mapping options)
optionsOptional options to override the defaults.
| If, the connection is idle for longer than this, the connection
is terminated, unit in |
| The browser-client will send a small ping message every
|
| When |
| The gzip compressionlevel used to compress packets. |
| Packets smaller than this will not be compressed. |
final void onrequest(Protocols.WebSocket.Request req)
Handle request, and returns a new Socket object if it's a new connection.
final void open(void|function(string|Stdio.Buffer:void) _read_cb, void|function(:void) _close_cb, void|function(:void) _lowmark_cb)
Set callbacks and open socket.
final void write(mapping(string:mixed) options, string|Stdio.Buffer ... msgs)
Send text string or binary Stdio.Buffer messages.
constant Web.EngineIO.Socket.RUNNING
constant Web.EngineIO.Socket.PAUSED
constant Web.EngineIO.Socket.SCLOSING
constant Web.EngineIO.Socket.RCLOSING
void close()
Close the transport properly, notify the far end.
void shutdown()
Shutdown the transport silently.
Represents a RSS (RDF Site Summary) file.
Index parse_xml(string|Parser.XML.Tree.Node n, void|string base)
Returns an Index object, populated with the rss information
given in the rss file n.
Represents an RSS channel.
inherit Thing : Thing
string Web.RSS.Channel.title
string Web.RSS.Channel.link
string Web.RSS.Channel.description
string|Standards.URI Web.RSS.Channel.image
string|Standards.URI Web.RSS.Channel.textinput
array(Item) Web.RSS.Channel.items
void add_item(Item i)
Adds the Item i to the Channel.
void remove_item(Item i)
Removes the Item i from the Channel.
Represents an RSS image resource.
inherit Thing : Thing
string Web.RSS.Image.title
string Web.RSS.Image.url
string Web.RSS.Image.link
Represents the top level of an RSS index.
array(Channel) Web.RSS.Index.channels
The RSS channels.
array(Image) Web.RSS.Index.images
The RSS images.
array(Item) Web.RSS.Index.items
The RSS items.
.RDF Web.RSS.Index.rdf
The underlying RDF representation of the RSS index.
array(Textinput) Web.RSS.Index.textinputs
The RSS textinputs.
Web.RSS.Index Web.RSS.Index(.RDF|void _rdf)
Represents an RSS item resource.
inherit Thing : Thing
string Web.RSS.Item.title
string Web.RSS.Item.link
string Web.RSS.Item.description
Represents an RSS textinput resource.
inherit Thing : Thing
string Web.RSS.Textinput.title
string Web.RSS.Textinput.description
string Web.RSS.Textinput.name
string Web.RSS.Textinput.link
The base class for the RSS resources.
Web.RSS.Thing Web.RSS.Thing(string about, mapping attributes)
Web.RSS.Thing Web.RSS.Thing(.RDF.Resource me)
Creates an RSS resource.
.RDF.Resource get_id()
Returns the RDF.Resource that identifies this RSS resource.
This is a limited SOAP wsdl parser using Promises.
Web.SOAP.Promise("https://foo.bar/Logon.svc?wsdl") .on_success(lambda(Web.SOAP.Client soap) { Web.SOAP.Arguments args, sh; args = soap->get_arguments("Logon"); sh = args->LogonRequestMsg; sh->Username = "foo"; sh->Password = "bar"; sh->WebServiceType = "Publisher"; soap->call(args) .on_success(lambda(mapping resp) { string token = resp->CredentialToken; }); });
final Concurrent.Future Promise(string wsdlurl, void|mapping headers)
A Concurrent.Future that eventually delivers a Client.
Client()
final Concurrent.Future call(Arguments args)
Calls the SOAP method you most recently addressed using
get_arguments().
A Concurrent.Future that eventually delivers a result mapping.
get_arguments()
Web.SOAP.Client Web.SOAP.Client(Protocols.HTTP.Promise.Result resp)
Usually not called directly.
Promise()
final Arguments get_arguments(string method)
Primes the Client to perform the call() later. Use the
returned structure to pass parameters. Only assigned parameters
will be passed to the call.
A structure describing all arguments for the specified method.
call()
final Arguments get_methods()
A structure describing all available methods on the current wsdl.
Sass is a scripting language that is interpreted into Cascading Style Sheets (CSS). This module is a glue for libsass.
protected typedefstring(8bit) Web.Sass.s8
Shorthand for string(8bit)
constant int Web.Sass.HTTP_IMPORT_NONE
constant int Web.Sass.HTTP_IMPORT_GREEDY
constant int Web.Sass.HTTP_IMPORT_ANY
Description:
| Default value of |
| Allow imports over HTTP only if the returned content type is text/scss. |
| Anything goes. |
constant string Web.Sass.LIBSASS_VERSION
The libsass version, as a string, this module was compiled agains.
constant int Web.Sass.SASS2SCSS_KEEP_COMMENT
constant int Web.Sass.SASS2SCSS_STRIP_COMMENT
constant int Web.Sass.SASS2SCSS_CONVERT_COMMENT
Constants that can be given as option to sass2scss().
constant int Web.Sass.STYLE_NESTED
constant int Web.Sass.STYLE_EXPANDED
constant int Web.Sass.STYLE_COMPACT
constant int Web.Sass.STYLE_COMPRESSED
Styling of output. Use as argument to Compiler.set_output_style()
| The default setting. The output will look like:
|
| Fully expanded output:
|
| Somewhat minified output:
|
| Minified output |
string libsass_language_version()
Returns the language version of Sass this module was compiled against
string libsass_version()
Returns the libsass version this module was compiled against
string(8bit) sass2scss(string(8bit) data)
string(8bit) sass2scss(string(8bit) data, int options)
Convert Sass syntax (i.e. indented syntax) to SCSS syntax.
dataSass syntax text to convert to SCSS syntax.
optionsThis is a bitwise union of compression level (STYLE_NESTED,
STYLE_EXPANDED, STYLE_COMPACT and $[STYLE_COMPRESSED]) and the
SASS2SCSS_* constants SASS2SCSS_KEEP_COMMENT,
SASS2SCSS_STRIP_COMMENT and SASS2SCSS_CONVERT_COMMENT.
It defaults to STYLE_NESTED|SASS2SCSS_KEEP_COMMENT.
data converted to SCSS syntax.
string sass2scss_version()
Returns the sass2scss version this module was compiled against
Low-level Sass/SCSS compiler.
You probably want to use Compiler instead of this class.
Compiler
string(8bit) Web.Sass.Api.include_path
The base path of @imports. Note! This needs to be set when
compile_string() is used.
bool Web.Sass.Api.omit_source_map_url
Set whether writing the sourceMappingUrl=# or not.
int(2bit) Web.Sass.Api.output_style
Determines the level of compression on the generated output.
STYLE_NESTED, STYLE_EXPANDED, STYLE_COMPACT and
STYLE_COMPRESSED.
int Web.Sass.Api.precision
Set the precision of fractional numbers. Default is 5.
bool Web.Sass.Api.sass_syntax
Set whether the code is Sass syntax, i.e. indented syntax or not. Only
necessary when using compile_string()
bool Web.Sass.Api.source_comments
Emit comments in the generated CSS indicating the corresponding source line. Default is false.
bool Web.Sass.Api.source_map_embed
Set whether embedding sourceMappingUrl=# as data uri or not.
string(8bit) Web.Sass.Api.source_map_file
Set the path of the source map file.
string(8bit) Web.Sass.Api.source_map_root
Set the root path of the source files, relative to where the source.map file is written.
string(8bit) compile_string(string(8bit) source)
Compiles the string source and returns the generated CSS.
sourceThe string to compile
A mapping with the generated CSS and source mapping file if such is set to be generated
| The generated CSS |
| The generated source mapping data |
If the source contain @import directives you have to
explicitly set the include path via include_path.
Sass/SCSS compiler.
Web.Sass.Compiler compiler = Web.Sass.Compiler(); // Allow for HTTP imports, disallowed by default. compiler->http_import = Web.Sass.HTTP_IMPORT_ANY; // Minify the output and create a source map file. compiler->set_options(([ "output_style" : Web.Sass.STYLE_COMPRESSED, "source_map_file" : "path/to/write/source.map" ])); if (mixed e = catch(compiler->compile_file("input.scss", "output.css"))) { werror("Failed compiling input.scss to output.css\n"); }
inherit Api : Api
bool Web.Sass.Compiler.check_file_access
Should file access be tested right away when paths are set or should that be left to Sass to handle? The default value is true.
int(0..2) Web.Sass.Compiler.http_import
If a Sass file is importing an external URI this flag determines if
thats allowed at all, or if the content type of the imported file has
to be in http_import_allow_ct, or if anything goes.
Default is HTTP_IMPORT_NONE.
HTTP_IMPORT_NONE, HTTP_IMPORT_GREEDY and
HTTP_IMPORT_ANY.
multiset(s8) Web.Sass.Compiler.http_import_allow_ct
List of allowed content types if http_import is set to
HTTP_IMPORT_GREEDY. The default is to allow text/scss and
text/sass.
mapping(s8:s8) compile_file(s8 input_file)
Compile the file input_file and return the result
input_fileThe SCSS file to compile
A mapping with the generated CSS and source mapping file if such is set to be generated
| The generated CSS |
| The generated source mapping data |
variant void compile_file(s8 input_file, s8 output_file)
Compile the file input_file and write the result to output_file.
If a source mapping file is set to be generated either via
set_options() or source_map_file it will be written as per
the value set in the option.
input_fileThe SCSS file to compile
output_fileThe name of the CSS file to save the result in.
protected string|array(string(8bit)) handle_sass_import(string(8bit) path, void|string(8bit) absolute_path, void|string(8bit) relative_path)
Resolve imports in sass/scss files.
In general this method doesn't need to overloaded. In principle it's only necessary if the Sass files reside in a non-standard filesystem.
If overloaded abs_path and rel_path is the absolute and relaive
paths of the file containing the import statement path.
If the Sass/SCSS files are located in a normal filesystem this method
can return the contents of path as a string and libsass will
resolve the paths to the imports by itself.
However, if the files are not located in a normal filesystem this
function should return an array of two indices, where the first index
should be the contents of path and the second the calculated absolute
path of path.
pathThis is the value of `path` in @import 'path'.
absolute_pathThis is the absolute path of the file containing the @import statement.
relative_pathThe relative path of absolute_path in relation to the prevoius
absolute_path
| If undefined is returned the import resolution is given back to libsass. |
| The contents of |
| if an array is returned it should contain two indices, where the first
if the contents of |
void set_options(mapping(s8:s8|int) opts)
Set options to the SASS compiler.
opts | Any of the |
| Path to root of incude files. See also |
| File to write source map file to.
See also |
| Turn on/off comments in the output containing info about the source
file - line numbers and such. Default of false. See also
|
| Turn on/off if a source map should be embedded in the output or not.
Default is false. See also |
| Set the root path of the source files, relative to where the
source.map file is written.
See also |
| Omit the #sourceMappingURL or not.
See also |
| Turn on/off Sass syntax, i.e. indented syntax. Only necessary when
using |
| Floating point precision. See also |
This is an implementation of the Socket.IO server-side communication's driver. It basically is a real-time bidirectional object-oriented communication's protocol for communicating between a webbrowser and a server.
This module supports the following features:
Passing any arbitrarily deep nested data object which can be represented in basic JavaScript datatypes.
In addition to the normal JavaScript datatypes, it also supports passing (nested) binary blobs in an efficient manner.
Every message/event sent, allows for a callback acknowledge to be specified.
Acknowledge callbacks which will be called when the other side actively decides to acknowledge it (not automatically upon message reception).
Acknowledgement messages can carry an arbitrary amount of data.
The driver uses Web.EngineIO as the underlying protocol.
Sample minimal implementation of a SocketIO server farm:
Web.SocketIO.Universe myuniverse; class myclient { inherit Web.SocketIO.Client; } void echo(myclient id, function sendack, string namespace, string event, mixed ... data) { id->emit(event, @data); if (sendack) sendack("Ack","me","harder"); } void wsrequest(array(string) protocols, object req) { httprequest(req); } void httprequest(object req) { switch (req.not_query) { case "/socket.io/": myclient client = myuniverse.farm(myclient, req); if (client) client->emit("Hello world!"); break; } } int main(int argc, array(string) argv) { myuniverse = Web.SocketIO.Universe(); // Create universe myuniverse.register("", echo); // Register root namespace Protocols.WebSocket.Port(httprequest, wsrequest, 80); return -1; }
farm, Web.EngineIO, Protocols.WebSocket,
http://github.com/socketio/socket.io-protocol,
http://socket.io/
final mapping(string:mixed) Web.SocketIO.options
Global options for all SocketIO instances.
SocketIO.Universe.farm()
final void sendackcb(function(mixed ... :void) fn, mixed arg)
Convenience function to aid assist in sending the acknowledgment callback.
constant Web.SocketIO.CONNECT
constant Web.SocketIO.DISCONNECT
constant Web.SocketIO.EVENT
constant Web.SocketIO.ACK
constant Web.SocketIO.ERROR
constant Web.SocketIO.BINARY_EVENT
constant Web.SocketIO.BINARY_ACK
constant Web.SocketIO.CONTAINER
Runs a single Socket.IO session.
function(void:void) Web.SocketIO.Client.onclose
Protocols.WebSocket.Request Web.SocketIO.Client.request
Contains the last request seen on this connection. Can be used to obtain cookies etc.
Read only
string Web.SocketIO.Client.sid
This session's unique session id.
Read only
void close()
Close the socket signalling the other side.
final variant void emit(function(Client, mixed ... :void) ack_cb, string event, mixed ... data)
final variant void emit(string event, mixed ... data)
final variant void emit(function(Client, mixed ... :void) ack_cb, mapping(string:mixed) options, string event, mixed ... data)
final variant void emit(mapping(string:mixed) options, string event, mixed ... data)
Send text or binary events to the client.
final void write(array data, void|function(Client, mixed ... :void) ack_cb, void|mapping(string:mixed) options)
Send text or binary messages to the client. When in doubt use the emit() interface instead. write() allows messages to be sent which do not have a string event-name up front.
constant Web.SocketIO.Client.RUNNING
constant Web.SocketIO.Client.SDISCONNECT
constant Web.SocketIO.Client.RDISCONNECT
final multiset(object) Web.SocketIO.Universe.clients
All SocketIO sessions in this universe.
mixed connect(Client client, void|string newnamespace)
Connects and disconnects clients.
0 upon success, the error itself otherwise.
Client farm(object createtype, Protocols.WebSocket.Request req, void|mapping options)
optionsOptional options to override the defaults.
This parameter is passed down as-is to the underlying EngineIO.Socket.
EngineIO.farm()
protected string|function(:void) lookupcb(string namespace, array data)
mixed read(string namespace, mixed id, function(mixed ... :void) sendackcb, mixed ... data)
variant void register(string namespace, string event, void|function(Client, function(mixed ... :void), string, string, mixed ... :void) fn)
variant void register(string namespace, void|function(Client, function(mixed ... :void), string, mixed ... :void) fn)
Register worker callback on namespace and event.
There can be only one worker per tuple.
Workers can be unregistered by omitting fn.
Having a default worker per namespace in addition zero or more
event specific ones, is supported.
protected .EngineIO.Socket seed(Protocols.WebSocket.Request req, void|mapping options)
Seed farm with EngineIO connection.
This module is an interface to the Yellow Pages functions. Yp is also known as NIS (Network Information System) and is most commonly used to distribute passwords and similar information within a network.
inherit "___Yp" : "___Yp"
string default_domain()
Returns the default yp-domain.
mapping(string:string) all(string map)
Returns the whole map as a mapping.
map is the YP-map to search in. This must be the full map name,
you have to use passwd.byname instead of just passwd.
Yp.Domain Yp.Domain(string|void domain)
void bind(string domain)
If domain is not specified , the default domain will be used.
(As returned by Yp.default_domain()).
If there is no YP server available for the domain, this function call will block until there is one. If no server appears in about ten minutes or so, an error will be returned. This timeout is not configurable.
Yp.default_domain()
void map(string map, function(string, string:void) fun)
For each entry in map, call the function specified by fun.
fun will get two arguments, the first being the key, and the
second the value.
map is the YP-map to search in. This must be the full map name.
eg passwd.byname instead of just passwd.
string match(string map, string key)
Search for the key key in the Yp-map map.
If there is no key in the map, 0 (zero) will be returned,
otherwise the string matching the key will be returned.
key must match exactly, no pattern matching of any kind is done.
int order(string map)
Returns the 'order' number for the map map.
This is usually the number of seconds since Jan 1 1970 (see time()).
When the map is changed, this number will change as well.
map is the YP-map to search in. This must be the full map name.
eg passwd.byname instead of just passwd.
string server(string map)
Returns the hostname of the server serving the map map. map
is the YP-map to search in. This must be the full map name.
eg passwd.byname instead of just passwd.
Network Information Service aka YP map.
array(string) indices( Yp.Map arg )
Return the keys of the map.
int sizeof( Yp.Map arg )
Return the number of entries in this map.
array(string) values( Yp.Map arg )
Return the values of the map.
string match(string key)
string res = Yp.Map()[ key ]
Search for the key key. If there is no key in the map, 0 (zero)
will be returned, otherwise the string matching the key will
be returned.
key must match exactly, no pattern matching of any kind is done.
mapping(string:string) all()
Returns the whole map as a mapping.
(mapping)Yp.Map()
Convert the map to a mapping
Yp.Map Yp.Map(string map, string|void domain)
Create a new YP-map object.
map is the YP-map to bind to. This may be a nickname, such as
passwd instead of just passwd.byname.
If domain is not specified, the default domain will be used.
If there is no YP server available for the domain, this function call will block until there is one. If no server appears in about ten minutes or so, an error will be returned. The timeout is not configurable.
void map(function(string, string:void) fun)
Call a function for each entry in the map.
For each entry in the map, call the function fun.
The function will be called like
void fun(string key, string value).
int order()
Return the order number for this map.
string server()
Return the server that provides this map.
Low-level tables and code for the Charset module.
This is probably not the module you want; try the Charset module.
Charset
object rfc1345(string charset, bool|void encoder, string|void rep, function(string:string)|void repcb)
Low-level charset codec factory.
charsetCanonical name of character set to look up.
encoderFlag indicating that an encoder and not a decoder is wanted.
repString to use for characters not representable in the charset.
Only used for encoders.
repcbFunction to call for characters not representable in the charset.
Only used for encoders.
This is the main entrypoint into the low-level _Charset module.
Returns a suitable encoder or decoder on success and 0
(zero) on failure.
Charset.encoder(), Charset.decoder()
constant _Ffmpeg.CODEC_ID_NONE
constant _Ffmpeg.CODEC_ID_AC3
constant _Ffmpeg.CODEC_ID_ADPCM_IMA_QT
constant _Ffmpeg.CODEC_ID_ADPCM_IMA_WAV
constant _Ffmpeg.CODEC_ID_ADPCM_MS
constant _Ffmpeg.CODEC_ID_H263
constant _Ffmpeg.CODEC_ID_H263I
constant _Ffmpeg.CODEC_ID_H263P
constant _Ffmpeg.CODEC_ID_MJPEG
constant _Ffmpeg.CODEC_ID_MPEG1VIDEO
constant _Ffmpeg.CODEC_ID_MPEG4
constant _Ffmpeg.CODEC_ID_MP2
constant _Ffmpeg.CODEC_ID_MP3LAME
constant _Ffmpeg.CODEC_ID_MSMPEG4V1
constant _Ffmpeg.CODEC_ID_MSMPEG4V2
constant _Ffmpeg.CODEC_ID_MSMPEG4V3
constant _Ffmpeg.CODEC_ID_PCM_ALAW
constant _Ffmpeg.CODEC_ID_PCM_MULAW
constant _Ffmpeg.CODEC_ID_PCM_S16BE
constant _Ffmpeg.CODEC_ID_PCM_S16LE
constant _Ffmpeg.CODEC_ID_PCM_S8
constant _Ffmpeg.CODEC_ID_PCM_U16BE
constant _Ffmpeg.CODEC_ID_PCM_U16LE
constant _Ffmpeg.CODEC_ID_PCM_U8
constant _Ffmpeg.CODEC_ID_RAWVIDEO
constant _Ffmpeg.CODEC_ID_RV10
constant _Ffmpeg.CODEC_ID_SVQ1
constant _Ffmpeg.CODEC_ID_VORBIS
constant _Ffmpeg.CODEC_ID_WMV1
constant _Ffmpeg.CODEC_ID_WMV2
Various audio and video codecs.
The list of supported codecs depends on Ffmpeg library.
constant _Ffmpeg.CODEC_TYPE_AUDIO
constant _Ffmpeg.CODEC_TYPE_VIDEO
Type of codec.
Implements support of all codecs from a nice project Ffmpeg. You can find more info about it at http://ffmpeg.sf.net/.
_Ffmpeg.ffmpeg _Ffmpeg.ffmpeg(int codec_name, int encoder)
Create decoder or encoder object.
codec_nameInternal number of codec, eg. CODEC_ID_MP2.
encoderIf true, encoder object will be created, decoder object otherwise.
mapping|int decode(string data)
Returns a mapping with the new decoded frame and lenght of
data which was used for decoding.
int decode(string data, function(:void) shuffler)
Decode all data buffer and pass result to shuffler.
Returns 1 on success, 0 otherwise.
Shuffler variant isn't implemented, yet.
Usable only in decoder.
create()
mapping|int encode(string data)
Returns mapping with new encoded frame and length of
data which was used for encoding.
int encode(string data, function(:void) shuffler)
Returns 1 on success, 0 otherwise.
Usable only in encoder
create()
mapping|int get_codec_info()
Returns mapping with info of used codec.
list_codecs()
mapping|int get_codec_status()
Returns a mapping with the actual codec parameters.
set_codec_param()
array(mapping) list_codecs()
Gets all supported codecs.
Array of mapping with codec features.
int set_codec_param(string name, mixed value)
Sets one codec parameter
nameThe name of parameter. One of "sample_rate",
"bit_rate", "channels".
Returns 1 on success, 0 otherwise (parameter not known).
get_codec_params()
A buffer to use as input or buffering when doing I/O. It is
similar to String.Buffer, but can only contain 8bit data and is
designed for protocol parsing. It is optimized for reading from
the beginning and adding to the end, and will try to minimise the
amount of data copying that is done.
The class maintains two separate offsets, one for reading and one for writing. The functions that add data all do so at the write offset (the end of the buffer), and reading is done from the read offset (the start of the buffer).
The class can also be used to directly read from and write to filedescriptors if so desired. This eliminates at least one memory copy.
The "avoid copy" part means that a Buffer will never shrink
unless you call the trim function.
void __set_on_write(function(:void) write_callback)
This tells the buffer to trigger the write callback for the specified file descriptor when data is added to the buffer.
This is used internally by Stdio.File and SSL.File to
handle nonblocking buffered mode, and is not necessarily
intended to be used directly by anything but implementations
of File or Stream like programs. Do not use this yourself
on buffers with Files or Streams in buffer modes.
string(8bit) encode_value(_Stdio.Buffer data)
_Stdio.Buffer decode_value(string(8bit) data)
Encode and decode Stdio.Buffer objects. Only the buffer data is kept, no other state is saved.
int(-1..) search(_Stdio.Buffer from, int(8bit) character, int|void start, int(0..)|void end)
Search forward from the indicated start position for the specified
character.
characterCharacter to search for.
startStart position relative to the current read position of the buffer.
Negative start values are supported and indicate positions
prior to the current read position.
endDon't search past this position of the buffer.
Returns the first found position of character relative to the
current read position of the buffer on success, and UNDEFINED
on not found. The read position is not advanced.
read_cstring(), search(), lfun::_search()
int(-1..) search(_Stdio.Buffer from, string(8bit) substring, int|void start, int|void end)
Search forward from the indicated start position for the specified
substring.
substringSubstring to search for.
startStart position relative to the current read position of the buffer.
Negative start values are supported and indicate positions
prior to the current read position.
endDon't search past this position of the buffer.
Returns the first found position of substring relative to the
current read position of the buffer on success, and UNDEFINED
on not found. The read position is not advanced.
read_cstring(), search(), lfun::_search()
int sizeof( _Stdio.Buffer arg )
Returns the buffer size, in bytes. This is how much you can read from the buffer until it runs out of data.
string(8bit) res = _Stdio.Buffer()[start..end]
Range operator.
Returns a string of the characters at offset low through high.
Returns the empty string if no data is available in the range.
int(-1..255) res = _Stdio.Buffer()[ off ]
Return the character at the specified offset.
Returns the character at offset off on success,
and -1 otherwise.
Indexing with negative offsets was not supported in Pike 8.0 and earlier.
_Stdio.Buffer()[ off ] = char
Set the character at the specified offset to char.
Indexing with negative offsets was not supported in Pike 8.0 and earlier.
Buffer add(AddArgument ... data)
private typedef System.Memory|Stdio.Buffer|String.Buffer BufferObject;
private typedef BufferObject|string(8bit)|int(8bit)|array(AddArgument) AddArgument;Add the items in data to the end of the buffer.
The supported argument types are:
| An eight bit string. |
| A single byte |
| A chunk of memory. The whole memory area is added. |
| A chunk of memory. The whole memory area is added. |
| A chunk of memory. The whole memory area is added. |
| Add all elements in the array individually. Each element may be any one of the types listed here. |
sprintf, add_int8, add_int16, add_int32, add_int
and
add_hstring
Buffer add_hint(int i, int(0..) size_width)
First add the size of the integer when encoded to base 256 as a
size_width integer, then add the integer to the buffer, both
in network byte order.
size_width must be less than Int.NATIVE_MAX.
Buffer add_hstring(string(8bit) data, int(0..) size_size)
Buffer add_hstring(Stdio.Buffer data, int(0..) size_size)
Buffer add_hstring(System.Memory data, int(0..) size_size)
Buffer add_hstring(String.Buffer data, int(0..) size_size)
Buffer add_hstring(int(8bit) data, int(0..) size_size)
Buffer add_hstring(array data, int(0..) size_size)
Buffer add_hstring(int|string(8bit)|Stdio.Buffer|System.Memory|array data, int(0..) size_size, int(0..) offset)
Adds length of data followed by data to the buffer.
This is identical to sprintf("%"+size_size+"H",(string)Stdio.Buffer(data)) but significantly faster.
size_size is the number of bytes used to represent the length of the data.
It must be less than Int.NATIVE_MAX.
offset is added to the length of the data prior to writing out
the length. Typical usage involves adding size_size to account
for the room used by the size.
The supported data argument types are
| An eight bit character. |
| An eight bit string. |
| A chunk of memory. The whole memory area is added. |
| A chunk of memory. The whole memory area is added. |
| A chunk of memory. The whole memory area is added. |
| Add all elements in the array individually. Each element may be any one of the types listed here. |
Buffer add_int(int i, int(0..) width)
Adds a generic integer to the buffer as an (width*8)bit network byteorder number.
width must be less than Int.NATIVE_MAX.
Buffer add_int16(int(16bit))
Add a 16-bit network byte order value to the buffer
Buffer add_int16(Gmp.mpz)
Add a 16-bit network byte order value to the buffer
Buffer add_int32(int i)
Adds a 32 bit network byte order value to the buffer
Buffer add_int32(Gmp.mpz i)
Adds a 32 bit network byte order value to the buffer
Buffer add_int8(int(8bit))
Adds a single byte to the buffer.
Buffer add_int8(Gmp.mpz)
Adds a single byte to the buffer.
Buffer add_ints(array(int) integers, int(8bit) len)
Add the integers in the specified array, len bytes per int.
Equivalent to calling add_int for each integer, but faster,
and if an error occurs the buffer will contain no new
data. Either all or none of the integers will be added.
Errors can occur if one of the elements in integers is not
actually an integer, if sizeof(integers)*len is bigger than can
be represented in a size_t, or if the buffer cannot grow due to
an out of memory condition.
Buffer add_padding(int(0..) nbytes, int(8bit)|void byte)
Add nbytes bytes of padding, if byte is not specified the
area will be filled with 0's, otherwise the specified byte will
be repeated.
void allocate(int(0..) n)
Make sure that at least n bytes of space are available in this buffer.
(string(8bit))_Stdio.Buffer()
Convert the buffer to a string.
This only works for buffers whose length is less than 0x7fffffff.
void clear()
Clear the buffer.
int(0..)|int(-1) consume(int(0..) n)
Discard the first n bytes from the buffer
Returns -1 on error and the amount of space still left otherwise.
_Stdio.Buffer _Stdio.Buffer(int|void len)
_Stdio.Buffer _Stdio.Buffer(string(8bit) contents)
_Stdio.Buffer _Stdio.Buffer(System.Memory|String.Buffer contents)
If passed an integer or no argument, create a buffer of that size, or if no argument is given, 226 bytes.
If contents are specified a new buffer with the contents of
the given string/System.Memory or String.Buffer will be created.
In the String.Buffer case the data has to be copied unless
there is only one reference to the String.Buffer object, since
modifications of the String.Buffer would cause the Buffer to
point into invalid memory.
In all other cases this will not copy the string data, instead data will be read from the source until it needs to be modified, so the buffer creation is fast regardless of the length of the string.
However, as an example, if the buffer is created with a 100Gb
System.Memory mmap:ed file as the contents and you later on
try to modify the buffer using one of the add functions (or
sprintf and similar) the old contents will be copied.
You can use read_only() to avoid accidents.
int(-1..) input_from(Stdio.Stream f, int|void nbytes)
Read data from f into this buffer. If nbytes is not
specified, read until there is no more data to read (currently).
Returns the amount of data that was read, or -1 on
read error.
Please note that this funcition will read all data from the filedescriptor unless it's set to be non-blocking.
object lock()
Makes this buffer read only until the returned object is released.
This currently simply returns a 0-length subbuffer.
__deprecated__ string(8bit)|int|float|array match(string(8bit) format)
Reads data from the beginning of the buffer to match the specifed format, then return the match.
The non-matching data will be left in the buffer.
This function is very similar to sscanf, but the
result is the sum of the matches. Most useful to match
a single value.
Returns the sum of the matching %-expressions,
"" if a prefix (but no %-expression) matches
and UNDEFINED on mismatch. Note that the addition
may throw errors.
Prior to Pike 9.0 0 was returned on mismatch
and format was returned on a prefix match.
// Get the next whitespace separated word from the buffer. buffer->match("%*[ \t\r\n]%[^ \t\r\n]"); // Get the next integer as a string. buffer->match("%0s%d");
Replaced by sscanf.
sscanf(), predef::sscanf(), array_sscanf()
int(-1..) output_to(Stdio.Stream|function(string(8bit):int) fun, int(0..)|void nbytes)
Write data from the buffer to the indicated file.
funWrite function. Either one of:
| A file object in which the function |
| A function which will be called with a |
nbytesIf nbytes is not specified the whole buffer will be written
if possible. Otherwise at most nbytes will be written.
Will return the number of bytes that have been written successfully.
If no bytes have been written successfully and fun() failed
with an error, -1 will be returned.
This function is similar to
int(-1..) output_to(Stdio.Stream|function(string(8bit):int) fun,
int(0..)|void nbytes)
{
if (objectp(fun)) fun = ([object]fun)->write;
int (0..) total;
while (sizeof(this)) {
int(0..) bytes = undefinedp(nbytes)?sizeof(this):nbytes;
if (bytes > 0x8000) bytes = 0x8000;
string(8bit) chunk = read(bytes);
int(-1..) written = ([function]fun)(chunk);
if (written <= 0) {
return total || written;
}
total += written;
if (written < sizeof(chunk)) {
unread(sizeof(chunk) - written);
}
if (!undefinedp(nbytes)) {
nbytes -= written;
if (!nbytes) {
break;
}
}
}
return total;
}
This function is going to get deprecated. In case you want to use
it against an Stdio.File like object, please consider using
the f->write(buf) API. If you want to use it against a custom
write function, please consider supporting the f->write(buf)
API in it.
protected bool range_error(int howmuch)
This function is called when an attempt is made to read out of bounds.
The default implementation simply returns 0 (zero).
Override this function to change the behavior.
howmuchThe argument howmuch indicates how much data is needed:
| Need |
| The amount of data needed is not certain.
This most often happens when |
| Tried to The only supported way is to extract the data from the buffer,
add the requested amount of "go backbuffer", add the data
back, and forward - |
true if the operation should be retried, false otherwise.
Do not return true unless you have added data to the buffer, doing so could result in an infinite loop (since no data is added, the range_error will be called again immediately).
string(8bit) read()
Read all data from the buffer.
If there is not enough data available this returns 0.
This is basically equivalent to (string)buffer, but it also removes the data from the buffer.
try_read()
string(8bit) read(int(0..) n)
Read n bytes of data from the buffer.
If there is not enough data available this returns 0.
try_read()
Buffer read_buffer(int(0..) n)
Buffer read_buffer(int(0..) n, bool copy)
Same as read, but returns the result as an Buffer.
No data is copied unless copy is specified and true, the new buffer
points into the old one.
As long as the subbuffer exists the main buffer is locked in memory.
Usually this is OK, since it often represents something that should be parsed before the next whatever is extracted from the buffer, but do take care.
string(8bit) read_cstring(void|int(8bit) sentinel, void|int(8bit) escape)
Reads a \0 terminated C-string and returns the string excluding the terminating \0.
If there is not enough data available return UNDEFINED.
Note that pike string can not be longer than 0x7fffffff bytes (~2Gb).
sentinelA different character can be used as end sentinel of the string.
escapeAn optional character used as a prefix to quote the following
character. UNDEFINED and the same value as sentinel mean
that there is no escape character.
Escape characters (if any) are left untouched in the returned string.
_search()
Buffer read_hbuffer(int n)
Buffer read_hbuffer(int n, bool copy)
Same as read_hstring, but returns the result as an Buffer.
No data is copied unless copy is specified and true, the new
buffer points into the old one.
As long as the subbuffer exists no data can be added to the main buffer.
Usually this is OK, since it often represents something that should be parsed before the next whatever is extracted from the buffer, but do take care.
If you need to unlink the new buffer after it has been
created, call trim in it.
int read_hint(int(0..) n)
Read a network byte order unsigned number of size n*8 bits, then read another network byte order number of the size indicated by the first size.
Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.
string(8bit) read_hstring(int(0..) n, void|int offset)
Identical in functionality to read(read_number(n)) but
faster.
Read a network byte order number of size n*8 bits, then return the indicated number of bytes as a string.
offset is substracted from the specified length prior to reading the
string. Typical usage involves substracting n to account
for the room used by the size.
If there is not enough data available return 0.
Note that pike string can not be longer than 0x7fffffff bytes (~2Gb).
int read_int(int(0..) n)
Read a network byte order unsigned number of size n*8 bits, then return it.
Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.
read_le_int
int(16bit) read_int16()
int(24bit) read_int24()
int(32bit) read_int32()
int(8bit) read_int8()
array(int) read_ints(int n, int(8bit) width)
Read a list of n network byte order unsigned numbers each of
size width*8 bits, then return it.
Will return 0 if there is not enough buffer space available unless error mode is set to throw errors.
mixed read_json(int|void require_whitespace_separator)
Read a single JSON expression from the buffer and return it.
If require_whitespace_separator is true there must be a whitespace
after each json value (as an example, newline or space).
The JSON is assumed to be utf-8 encoded.
UNDEFINED if no data is available to read. The read value otherwise.
Unless whitespaces are required this function only really work correctly with objects, arrays and strings.
There is really no way to see where one value starts and the other ends for most other cases
int read_le_int(int(0..) n)
Read a little endian byte order unsigned number of size n*8 bits, then return it.
Will return -1 if there is not enough buffer space available unless error mode is set to throw errors.
read_int
void read_only()
This makes the existing data in the buffer permanently read only.
You can use lock() to do this temporarily.
int read_sint(int size)
Read a network byte order two:s complement signed number of size n*8 bits, then return it.
Will return UNDEFINED if there is not enough buffer space available unless error mode is set to throw errors.
RewindKey rewind_on_error()
RewindKey rewind_key()
These functions are very similar. The rewind_on_error variant
will create an object that, when it goes out of scope without
having been destructed explicitly, will cause the buffer to
rewind to the location it had when this function is called.
This will happen if you throw an error or otherwise let the object fall out of scope.
Use destruct(RewindKey) or RewindKey.release to stop the
buffer from being rewound.
The second version (rewind_key) requires you to explicitly
call RewindKey.rewind to do the rewind.
Take some care with these objects, if you create multiple ones at once the results might be somewhat confusing if you do not release them in the reverse order they were created in (then again, you almost certainly really only need one)
You can call RewindKey.update in the generated object to
change where it will be rewound to.
The typical use-case of this functionality is when parsing a packet protocol with variable length packets where the length is not immediately known. It saves you from keeping track of how much to rewind if you had not actually gotten the whole packet yet.
void parse_packet( Stdio.Buffer b ) { Stdio.Buffer.RewindKey rewind = b->rewind_on_error(); b->set_error_mode(1); switch( b->read_int8() ) // packet type { case DATA: int channel = b->read_int8(); Stdio.Buffer data = b->read_hbuffer( 4 ); // we have read the whole packet, so no longer rewind on error. rewind->release(); return handle_data_packet( channel, data ); } }
Just calling rewind_on_error without assigning the return
value to something will not do anything. You need to keep the
object around while the rewind-to position is still valid.
Keeping the object around forbids the buffer from moving data inside itself, this means that it can only grow. So do not keep the rewind key when it is not needed.
Buffer set_error_mode(int m)
Buffer set_error_mode(program m)
Set the error mode of this buffer to m.
If true operations that would normally return 0 (like trying to
read too much) will instead throw an error. If m is a program
a clone of it will be thrown on error.
This is useful when parsing received data, you do not have to verify that each and every read operation suceeds.
However, the non-error mode is more useful when checking to see if a packet/segment/whatever has arrived.
The thrown error object will have the constant buffer_error set to a non-false value.
void read_callback(int i, string(8bit) new_data) { inbuffer->add( new_data ); while( Buffer packet = inbuffer->read_hbuffer(2) ) { packet->set_error_mode(Buffer.THROW_ERROR); if( mixed e = catch( handle_packet( packet ) ) ) if( e->buffer_error ) protocol_error(); // illegal data in packet else throw(e); // the other code did something bad } } void handle_packet( Buffer pack ) { switch( pack->read_int8() ) { ... case HEADER_FRAME: int num_headers = pack->read_int32(); for( int i = 0; i<num_headers; i++ ) headers[pack->read_hstring(2)] = pack->read_hstring(2); ... } }
void set_max_waste(float factor)
Configure how much free space should be allowed, at most, as a factor of the current buffer size.
The default is 0.5, leaving at most half the buffer as waste.
Buffer sprintf(strict_sprintf_format format, sprintf_args ... args)
Appends the output from sprintf at the end of the buffer.
This is somewhat faster than add(sprintf(...)) since no intermediate string is created.
array sscanf(string(8bit) format)
Reads data from the beginning of the buffer to match the specifed format, then return an array with the matches.
The non-matching data will be left in the buffer.
See array_sscanf for more information.
match(), predef::sscanf(), array_sscanf()
void trim()
Frees unused memory.
Note that calling this function excessively will slow things down, since the data often has to be copied.
This function could possibly throw an out-of-memory error if the realloc fails to find a new (smaller) memory area.
int(0..)|int(-1) truncate(int(0..) n)
Truncates the buffer to a length of n bytes.
Returns -1 on error and the number of bytes removed otherwise.
string(8bit) try_read(int(0..) len)
Attempt to read some data from the buffer.
lenRead at most len bytes from the buffer.
If the buffer contains less than len bytes
of data, the entire buffer contents are returned.
Otherwise the first len bytes are returned.
read()
int(0..)|int(-1) unread(int(0..) n)
Rewind the buffer n bytes.
This function returns how many more bytes of buffer is available to rewind, or -1 on error.
Unless you add new data to the buffer using any of the add functions you can always rewind.
You can call unread(0) to see how much.
The return value of Buffer.rewind_on_error() and
Buffer.rewind_key()
This object will cause the buffer to unwind to the position it was
at when the object was created either when it is released (when it
falls out of scope, explicit destruct does not count) or when
rewind is called, depending on which function was used to
create it.
void release()
Do not rewind if the object is released.
This is equivalent to calling destruct() on the object
void rewind()
Rewinds the buffer explicitly.
Destructs this RewindKey
void update()
Update the location the buffer will be rewound to to the current position of the buffer.
bool tcdrain()
Wait for transmission buffers to empty.
Returns 1 on success and 0 (zero) on failure.
tcflush()
bool tcflush(string(7bit)|void flush_direction)
Flush queued terminal control messages.
flush_direction | Flush received but not read. |
| Flush written but not transmitted. |
| Flush both of the above. Default. |
Returns 1 on success and 0 (zero) on failure.
tcdrain()
mapping(string(7bit):int) tcgetattr()
int tcsetattr(mapping(string(7bit):int) attr)
int tcsetattr(mapping(string(7bit):int) attr, string(7bit) when)
Gets/sets term attributes. The returned value/the attr parameter
is a mapping on the form
| In baud rate. |
| Out baud rate. |
| Character size in bits. |
| Terminal rows. |
| Terminal columns. |
| The value of a named flag. The flag name is the string describing the termios flags (IGNBRK, BRKINT, IGNPAR, PARMRK, INPCK, ISTRIP, INLCR, IGNCR, ICRNL, IUCLC, IXON, IXANY, IXOFF, IMAXBEL, OPOST, OLCUC, ONLCR, OCRNL, ONOCR, ONLRET, OFILL, OFDEL, OXTABS, ONOEOT, CSTOPB, CREAD, PARENB, PARODD, HUPCL, CLOCAL, CRTSCTS, ISIG, ICANON, XCASE, ECHO, ECHOE, ECHOK, ECHONL, ECHOCTL, ECHOPRT, ECHOKE, FLUSHO, NOFLSH, TOSTOP, PENDIN). See the manpage for termios or other documentation for more information. All flags are not available on all platforms. |
| Sets the value of a control character (VINTR, VQUIT, VERASE, VKILL, VEOF, VTIME, VMIN, VSWTC, VSTART, VSTOP, VSUSP, VEOL, VREPRINT, VDISCARD, VWERASE, VLNEXT, VEOL2). All control characters are not available on all platforms. |
Negative values are not allowed as indata, but might appear in the
result from tcgetattr when the actual value is unknown. tcsetattr
returns 0 if failed.
The argument when to tcsetattr describes when the
changes are to take effect:
| The change occurs immediately (default). |
| The change occurs after all output has been written. |
| The change occurs after all output has been written, and empties input buffers. |
// setting the terminal in raw mode: Stdio.stdin->tcsetattr((["ECHO":0,"ICANON":0,"VMIN":0,"VTIME":0]));
Unknown flags are ignored by tcsetattr(). tcsetattr always
changes the attribute, so only include attributes that actually
should be altered in the attribute mapping.
Terminal rows and columns setting by tcsetattr() is not
currently supported.
tcsetsize()
bool tcsendbreak(int|void duration)
Send a break signal.
durationDuration to send the signal for. 0 (zero) causes
a break signal to be sent for between 0.25 and 0.5 seconds.
Other values are operating system dependent:
The number of joined break signals as above.
The time in milliseconds.
The value is ignored.
The behavior is changed to be similar to tcdrain().
Returns 1 on success and 0 (zero) on failure.
bool tcsetsize(int rows, int cols)
Set the number of rows and columns for a terminal.
Returns 1 on success and 0 (zero) on failure.
tcgetattr(), tcsetattr()
constant _Stdio.UDP.MSG_OOB
Flag to specify to read() to read out of band packets.
constant _Stdio.UDP.MSG_PEEK
Flag to specify to read() to cause it to not remove the packet
from the input buffer.
UDP _Stdio.UDP._fd
Read only
int add_membership(string group, void|string address)
Join a multicast group.
groupgroup contains the address of the multicast group the
application wants to join. It must be a valid multicast address.
addressaddress is the address of the local interface with which
the system should join to the multicast group. If not provided
the system will select an appropriate interface.
See also the Unix man page for setsocketopt IPPROTO_IP IP_ADD_MEMBERSHIP and IPPROTO_IPV6 IPV6_JOIN_GROUP.
The address parameter is currently not supported for IPv6.
This function did not support IPv6 in Pike 7.8 and earlier.
drop_membership()
UDP bind(int|string port, string|void address, string|bool no_reuseaddr)
Binds a port for receiving or transmitting UDP.
portEither a port number or the name of a service as listed in /etc/services.
addressLocal address to bind to.
no_reuseaddrIf set to 1, Pike will not set the SO_REUSEADDR option
on the UDP port.
SO_REUSEADDR is never applied when binding a random port
(bind(0)).
In general, SO_REUSEADDR is not desirable on UDP ports.
Unless used for receiving multicast, be sure to never bind a
non-random port without setting no_reuseaddr to 1.
Throws error when unable to bind port.
bool close()
Closes an open UDP port.
This method was introduced in Pike 7.5.
bool connect(string address, int|string port)
Establish an UDP connection.
This function connects an UDP socket previously created with
Stdio.UDP() to a remote socket. The address is the IP name or
number for the remote machine.
Returns 1 on success, 0 (zero) otherwise.
If the socket is in nonblocking mode, you have to wait for a write or close callback before you know if the connection failed or not.
bind(), query_address()
int drop_membership(string group, void|string address)
Leave a multicast group.
groupgroup contains the address of the multicast group the
application wants to join. It must be a valid multicast address.
addressaddress is the address of the local interface with which
the system should join to the multicast group. If not provided
the system will select an appropriate interface.
See also the Unix man page for setsocketopt IPPROTO_IP IP_DROP_MEMBERSHIP and IPPROTO_IPV6 IPV6_LEAVE_GROUP.
The address parameter is currently not supported for IPv6.
This function did not support IPv6 in Pike 7.8 and earlier.
add_membership()
Stdio.UDP dup()
Duplicate the udp socket.
fd_factory()
bool enable_broadcast()
Set the broadcast flag. If enabled then sockets receive packets sent to a broadcast address and they are allowed to send packets to a broadcast address.
Returns 1 on success, 0 (zero) otherwise.
This is normally only avalable to root users.
bool enable_multicast(string reply_address)
Set the local device for a multicast socket.
reply_addressLocal address that should appear in the multicast packets.
See also the Unix man page for setsocketopt IPPROTO_IP IP_MULTICAST_IF and IPPROTO_IPV6 IPV6_MULTICAST_IF.
This function did not support IPv6 in Pike 7.8.
int errno()
Returns the error code for the last command on this object. Error code is normally cleared when a command is successful.
UDP fd_factory()
Factory creating Stdio.UDP objects.
This function is called by dup()
and other functions creating new UDP objects.
The default implementation calls object_program(this_object())()
to create the new object, and returns the UDP inherit in it.
Note that this function must return the UDP inherit in the object.
dup(), Stdio.File()->fd_factory()
array(int) get_type()
Returns socket type and protocol family.
string query_address()
Returns the local address of a socket on the form "x.x.x.x port". If this file is not a socket, not connected or some other error occurs, zero is returned.
Pike.Backend query_backend()
Return the backend used for the read callback.
set_backend
int query_fd()
Gets the file descriptor for this UDP port.
int query_mtu()
Get the Max Transfer Unit for the object (if any).
| Returns |
| Returns a positive value with the mtu on success. |
The returned value is adjusted to take account for the IP and UDP headers, so that it should be usable without further adjustment unless further IP options are in use.
mapping(string:int|string) read()
mapping(string:int|string) read(int flag)
Read from the UDP socket.
Flag flag is a bitfield, 1 for out of band data and 2 for peek
mapping(string:int|string) in the form ([ "data" : string received data "ip" : string received from this ip "port" : int ...and this port ])
set_read_callback(), MSG_OOB, MSG_PEEK
int send(string to, int|string port, string message)
int send(string to, int|string port, string message, int flags)
Send data to a UDP socket.
toThe recipient address. For connect()ed objects specifying a
recipient of either UNDEFINED or "" causes the default
recipient to be used.
portThe recipient port number. For connect()ed objects specifying
port number 0 casues the default recipient port to be used.
flagA flag bitfield with 1 for out of band data and
2 for don't route flag.
| The number of bytes that were actually written. | ||||
| Failed to send the
|
Throws errors on invalid arguments and uninitialized object.
Versions of Pike prior to 8.1.5 threw errors also on EMSGSIZE
("Too big message") and EWOULDBLOCK
("Message would block."). These versions of Pike also
did not update the object errno on this function failing.
Versions of Pike prior to 8.1.13 did not support the default
recipient for connect()ed objects.
connect(), errno(), query_mtu()
void set_backend(Pike.Backend backend)
Set the backend used for the read callback.
The backend keeps a reference to this object as long as there can be calls to the read callback, but this object does not keep a reference to the backend.
query_backend
object set_blocking()
Sets this object to be blocking.
void set_buffer(int bufsize, string mode)
void set_buffer(int bufsize)
Set internal socket buffer.
This function sets the internal buffer size of a socket or stream.
The second argument allows you to set the read or write buffer by
specifying "r" or "w".
It is not guaranteed that this function actually does anything, but it certainly helps to increase data transfer speed when it does.
open_socket(), accept()
UDP set_fd(int fd)
Use the file descriptor fd for UDP.
bind
int set_multicast_ttl(int ttl)
Set the time-to-live value of outgoing multicast packets for this socket.
ttlThe number of router hops sent multicast packets should survive.
It is very important for multicast packets to set the smallest TTL possible. The default before calling this function is 1 which means that multicast packets don't leak from the local network unless the user program explicitly requests it.
See also the Unix man page for setsocketopt IPPROTO_IP IP_MULTICAST_TTL and IPPROTO_IPV6 IPV6_MULTICAST_HOPS.
This function did not support IPv6 in Pike 7.8 and earlier.
add_membership()
object set_nonblocking(function(:void)|void rcb, function(:void)|void wcb)
Sets this object to be nonblocking and the read and write callbacks.
UDP set_type(int sock_type)
UDP set_type(int sock_type, int family)
Sets socket type and protocol family.
bool wait(int|float timeout)
Check for data and wait max. timeout seconds.
Returns 1 if data are ready, 0 (zero) otherwise.
Stdio.File accept()
Get the first connection request waiting for this port and return it as a connected socket.
If no connection request is waiting and the port is in nonblocking mode (i.e. an accept callback is installed) then zero is returned. Otherwise this function waits until a connection has arrived.
In Pike 7.8 and later the returned object is created via fd_factory().
In Pike 7.7 and later the resulting file object will be assigned to the same backend as the port object.
int bind(int|string port, void|function(:void) accept_callback, void|string ip, void|string reuse_port)
Opens a socket and binds it to port number on the local machine.
If the second argument is present, the socket is set to
nonblocking and the callback funcition is called whenever
something connects to it. The callback will receive the id for
this port as argument and should typically call accept to
establish a connection.
If the optional argument ip is given, bind will try to bind
to an interface with that host name or IP number. Omitting this
will bind to all available IPv4 addresses; specifying "::" will
bind to all IPv4 and IPv6 addresses.
If the OS supports TCP_FASTOPEN it is enabled automatically.
If the OS supports SO_REUSEPORT it is enabled if the fourth argument is true.
1 is returned on success, zero on failure. errno provides
further details about the error in the latter case.
accept, set_id
int bind_unix(string path, void|function(:void) accept_callback)
Opens a Unix domain socket at the given path in the file system.
If the second argument is present, the socket is set to
nonblocking and the callback funcition is called whenever
something connects to it. The callback will receive the id for
this port as argument and should typically call accept to
establish a connection.
1 is returned on success, zero on failure. errno provides
further details about the error in the latter case.
This function is only available on systems that support Unix domain sockets.
path had a quite restrictive length limit (~100 characters)
prior to Pike 7.8.334.
accept, set_id
void close()
Closes the socket.
_Stdio._port _Stdio._port(int|string port, void|function(:void) accept_callback, void|string ip)
_Stdio._port _Stdio._port("stdin", void|function(:void) accept_callback)
When called with an int or any string except "stdin" as
first argument, this function does the same as bind() would do
with the same arguments.
When called with "stdin" as argument, a socket is created
out of the file descriptor 0. This is only useful if that actually
IS a socket to begin with, and is equivalent to creating a port and
initializing it with listen_fd(0).
bind, listen_fd
int errno()
If the last call done on this port failed, this function will return an integer describing what went wrong. Refer to your unix manual for further information.
protected Stdio.Fd fd_factory()
Factory creating empty Stdio.Fd objects.
The default implementation creates an empty Stdio.Fd object.
int listen_fd(int fd, void|function(:void) accept_callback)
This function does the same as bind, except that instead of
creating a new socket and bind it to a port, it expects the file
descriptor fd to be an already open port.
This function is only for the advanced user, and is generally used when sockets are passed to Pike at exec time.
bind, accept
string query_address()
Get the address and port of the local socket end-point.
This function returns the address and port of a socket end-point
on the form "x.x.x.x port" (IPv4) or
"x:x:x:x:x:x:x:x port" (IPv6).
If there is some error querying or formatting the address,
0 (zero) is returned and errno() will return the
error code.
An error is thrown if the socket isn't bound.
Pike.Backend query_backend()
Return the backend used for the accept callback.
set_backend
int query_fd()
Returns the file descriptor number associated with this object.
mixed query_id()
This function returns the id for this port. The id is normally the first argument to accept_callback.
set_id
void set_accept_callback(function(:void)|void accept_callback)
Change or remove the accept callback.
accept_callbackNew accept callback.
bind(), listen(), set_id()
void set_backend(Pike.Backend backend)
Set the backend used for the accept callback.
The backend keeps a reference to this object as long as the port is accepting connections, but this object does not keep a reference to the backend.
query_backend
mixed set_id(mixed id)
This function sets the id used for accept_callback by this port.
The default id is this_object().
In Pike 8.0 and earlier the default value was 0 (zero)
(even though it was documented as above).
query_id, set_accept_callback()
Module containing various IP-protocol options.
Module containing constants for specifying socket options.
constant _Stdio.SOCK.DGRAM
constant _Stdio.SOCK.PACKET
constant _Stdio.SOCK.RAW
constant _Stdio.SOCK.RDM
constant _Stdio.SOCK.SEQPACKET
constant _Stdio.SOCK.STREAM