Kiwi is a library designed to make developing graphical applications as easy as possible. It offers both a framework and a set of enhanced widgets, and is based on Python and GTK+. Kiwi borrows concepts from MVC, Java Swing and Microsoft MFC, but implements a set of unique classes that take advantage of the flexibility and simplicity of Python to make real-world application creation much easier.
Kiwi includes a Framework and a set of enhanced widgets
- Authors: - Christian Reis <kiko@async.com.br> - Johan Dahlin <jdahlin@async.com.br>
- Website: U{http://www.async.com.br/projects/kiwi/}
- Organization: Async Open Source
The accessor module offers two important front-end functions: kgetattr and ksetattr. These functions allow retrieving attribute values from objects much in the same way as getattr/setattr allow, but with two important differences:
- They follow a dot hierarchy to retrieve or modify any value reachable from the object.
- They cache the method used to access a certain attribute and reuse it the next time the value is retrieved.
Bases: exceptions.Exception
This can be raised in kgetattr accessors to indicate that the default value should be used
Clears the kgetattr cache. It must be called repeatedly to avoid memory leaks in Python 2.0 and earlier.
Enables the use of the kgetattr cache when using Python versions that do not support weakrefs (1.5.x and earlier). Be warned, using the cache in these versions causes leaked references to accessor methods and models!
Obtains from model a callable through which attr_name can be retrieved. This callable is an accessor named get_foo, where foo is the value of attr_name, or getattr(model, foo) if the accessor does not exist. If the callable exists, it is returned; if getattr() is to be used a tuple in the format (model, attr_name) is returned.
Obtains from model a callable through which attr_name can be set. This callable is an accessor named set_foo, where foo is the value of attr_name, or setattr(model, foo, value) if the accessor does not exist. If the callable exists, it is returned; if setattr() is to be used a tuple in the format (model, attr_name) is returned.
Returns the value associated with the attribute in model named by attr_name. If default is provided and model does not have an attribute called attr_name, the default value is returned. If flat=1 is specified, no dot path parsing will be done.
Set the value associated with the attribute in model named by attr_name. If flat=1 is specified, no dot path parsing will be done.
Argument checking decorator and support
Bases: object
Decorator to check type and value of arguments.
Usage:
>>> @argcheck(types...)
... def function(args..)
or
>>> class Class:
... @argcheck(types..)
... def method(self, args)
You can customize the checks by subclassing your type from CustomType, there are two builtin types: number which is a float/int combined check and a percent which verifis that the value is a percentage
Bases: kiwi.argcheck.CustomType
Custom type that verifies that the type is a number (eg float or int)
Bases: exceptions.Exception
Called when a utility already exists.
Get the utility for the named interface. If the utility is not available (has not been set) a {NotImplementedError} is raised unless default is set.
Parameters: |
|
---|---|
Returns: | the utility |
A generic controller that can be attached to any View
BaseController defines one public variable:
- view: corresponds to a the associated View instance, which holds the UI implementation itself (widgets, layout, etc.)
The keypress handler, which dispatches keypresses to the functions mapped to in self.keyactions
Sets the keyactions mapping. See the constructor documentation for a description of it.
Currency and datatype converter
Data type converters with locale and currency support.
Provides routines for converting data to and from strings. Simple example:
>>> from kiwi.datatypes import converter
>>> converter.from_string(int, '1,234')
'1234'
>>> converter.from_string(float, '1,234')
'1234.0'
>>> converter.to_string(currency, currency('10.5'))
'$10.50'
Formats a price according to the current locales monetary settings
Parameters: |
|
---|
Function and method decorators used in kiwi
Bases: object
I am a decorator which prints a deprecation warning each time you call the decorated (and deprecated) function
Bases: object
A decorator to be used on kiwi.ui.views.SlaveView methods. It takes a list of arguments which is the name of the widget and the signal name separated by a dot.
For instance:
>>> class MyView(SlaveView):
... @signal_block('money.changed')
... def update_money(self):
... self.money.set_value(10)
... def on_money__changed(self):
... pass
When calling update_money() the value of the spinbutton called money will be updated, but on_money__changed will not be called.
Bases: ConfigParser.ConfigParser
A DesktopParser for GNOME/KDE .desktop files. The API is similar to GKeyFile from glib.
Example:
>>> parser = DesktopParser()
>>> parser.read('/usr/share/applications/gnome-terminal.desktop')
>>> parser.get_locale('Desktop Entry', 'Comment', 'pt')
Get a boolean list.
Parameters: |
|
---|
Get a list of integers as string.
Parameters: |
|
---|
Get locale.
Parameters: |
|
---|
Get a list as string.
Parameters: |
|
---|
Get list locale as an string.
Parameters: |
|
---|
Set an list wiht boolena values.
Parameters: |
|
---|
Set a list with integer values.
Parameters: |
|
---|
Sets the character which is used to separate values in lists. Typically ‘;’ or ‘,’ are used as separators. The default list separator is ‘;’.
Parameters: | separator – the separator |
---|
Set locale.
Parameters: |
|
---|
Distutils extensions and utilities
Bases: distutils.command.install_lib.install_lib
alias of KiwiInstallLib
Compiles po files to mo files. Note. this function depends on gettext utilities being installed
Parameters: |
|
---|---|
Returns: | a list of po files |
Gets the relative path of the site-packages directory
This is mainly useful for setup.py usage:
>>> setup(...
data_files=[(get_site_packages_dir('foo'),
files..)])
where files is a list of files to be installed in a directory called foo created in your site-packages directory
Parameters: | dirs – directory names to be appended |
---|
Lists all files in directories and optionally uses basic shell matching, example:
>>> listfiles('data', 'glade', '*.glade')
['data/glade/Foo.glade', 'data/glade/Bar.glade', ...]
Parameters: | dirs – directory parts |
---|
Bases: kiwi.python.enum
Bases: kiwi.python.enum
Bases: kiwi.python.enum
Bases: kiwi.python.enum
Bases: kiwi.python.enum
Bases: kiwi.python.enum
An enum used to indicate where a search filter should be added to a SearchContainer:
- TOP: top left corner
- BOTTOM: bottom
Environment helpers: path mangling and resource management
Bases: kiwi.environ.Library
Application extends a Library. It’s meant to be used by applications
Libraries are usually instantiated in __init__.py in the topmost package in your library, an example usage is kiwi itself which does:
>>> from kiwi.environ import Application
>>> app = Application('gnomovision')
>>> if app.uninstalled:
>>> app.add_global_resource('glade', 'glade')
>>> app.add_global_resource('pixmap', 'pixmaps')
If you want to do translations, you also need to do the following:
>>> app.enable_translation()
Enables translation for a application See Library.enable_translation.
Bases: kiwi.environ.Environment
A Library is a local environment object, it’s a subclass of the Environment class. It’s used by libraries and applications (through the Application class)
It provides a way to manage local resources, which should only be seen in the current context.
Libraries are usually instantiated in __init__.py in the topmost package in your library, an example usage is kiwi itself which does:
>>> from kiwi.environ import Library
>>> lib = Library('kiwi')
>>> if lib.uninstalled:
>>> lib.add_global_resource('glade', 'glade')
>>> lib.add_global_resource('pixmap', 'pixmaps')
which is combined with the following class in setup.py:
>>> from kiwi.dist import InstallLib
>>> class InstallLib(TemplateInstallLib):
>>> name = 'kiwi'
>>> global_resources = dict(glade='$datadir/glade',
>>> pixmap='$datadir/pixmaps')
>>>
>>> setup(...,
>>> data_files=[('share/kiwi/glade',
>>> listfiles('glade', '*.glade')),
>>> ('share/kiwi/pixmaps',
>>> listfiles('pixmaps', '*.png')),
>>> cmdclass=dict(install_lib=InstallLib))
It may seems like a bit of work, but this is everything that’s needed for kiwi to figure out how to load resources when installed and when running in an uninstalled mode, eg directly from the source tree. To locate a pixmap called kiwi.png the following is enough:
>>> from kiwi.environ import environ
>>> environ.find_resource('pixmap', 'kiwi.png')
'/usr/share/kiwi/pixmaps/kiwi.png' # installed mode
Which will lookup the resource kiwi.png in the domain pixmap, which points to $datadir/pixmaps (eg $prefix/share/kiwi/pixmaps) when running in installed mode and from $builddir/pixmaps otherwise.
Convenience method to add a global resource. This is the same as calling kiwi.environ.environ.add_resource
Enables translation for a library
Parameters: |
|
---|
Interface specifications and utilities
Extension to the logging module
This module defines a couple of extensions to the logging module included in the python standard distribution.
It creates an additional logging handler that print log records on the standard output. This handler is only showing records which has a level set to logging.WARNING or higher by default. The messages printed by this handler can be modified by using the environment variable called KIWI_LOG.
The syntax for the string which KIWI_LOG points to is the following:
domain ':' level [, domain ':', level]
domain can contain wildcards such as * and ? level is an integer 1-5 which defines the minimal level:
- B{5}: DEBUG
- B{4}: INFO
- B{3}: WARNING
- B{2}: ERROR
- B{1}: CRITICAL
Examples:
KIWI_LOG="stoq*:5"
will print all the messages in a domain starting with stoq with DEBUG or higher:
KIWI_LOG="kiwi*:4,stoq.*:5"
will print all the messages with INFO or higher in all domains starting with kiwi, and all the messages in the stoq.* domains which are DEBUG or higher
Inspiration for the syntax is taken from the U{debugging facilities<http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gstreamer/html/gstreamer-GstInfo.html#id2857358>} of the U{GStreamer<http://www.gstreamer.net>} multimedia framework.
Bases: logging.Filter
It’s like a reversed filter, the default behavior is to not show the message, you need to add custom filters for all the records you wish to see
Set the filename used for logging.
Parameters: |
|
---|
Holds the models part of the Kiwi Framework
The Model is a mixin to be used by domain classes when attached to Proxies. It also provides autonotification of changes to the attached proxies. Note that if using setters, a specific call to notify_proxies() may be necessary; see the doc for __setattr__.
Temporarily block a proxy from receiving any notification. See unblock_proxy()
disable automatic notification to proxies based on __setattr__. All changes to the model must be followed by a call to notify_proxies() to allow the proxies to notice the change.
Sets up the variables so the Model’s getattr hook and proxy notification work properly.
Bases: kiwi.model.Model
PickledModel is a model that is able to save itself into a pickle using save(). This has all the limitations of a pickle: its instance variables must be picklable, or pickle.dump() will raise exceptions. You can prefix variables with an underscore to make them non-persistent (and you can restore them accordingly by overriding __setstate__, but don’t forget to call PickledModel.__setstate__)
Saves the instance to a pickle filename. If no filename argument is provided, will try to use the internal _filename attribute that is set using set_filename() :param filename: optional filename to pass in
Loads an instance from a pickle file; if it fails for some reason, create a new instance.
- filename: the file from which the pickle should be loaded. If file is not provided, the name of the class suffixed by ”.pickle” is used (i.e. “FooClass.pickle” for the class FooClass).
If the pickle file is damaged, it will be saved with the extension ”.err”; if a file with that name also exists, it will use ”.err.1” and so on. This is to avoid the damaged file being clobbered by an instance calling save() unsuspectingly.
Generic python addons
Bases: object
I am an object which will call a classmethod called __class_init__ when I am created. Subclasses of me will also have __class_init__ called.
Note that __class_init__ is called when the class is created, eg when the file is imported at the first time. It’s called after the class is created, but before it is put in the namespace of the module where it is defined.
Pseudo-thread (coroutines) framework
This module adds infrastructure for managing tasklets. In this context, a X{tasklet} is defined as a routine that explicitly gives back control to the main program a certain points in the code, while waiting for certain events. Other terms that may be used to describe tasklets include I{coroutines}, or I{cooperative threads}.
The main advantages of tasklets are:
- Eliminates the danger of unexpected race conditions or deadlocks that happen with preemptive (regular) threads;
- Reduces the number of callbacks in your code, that sometimes are so many that you end up with I{spaghetti code}.
The fundamental block used to create tasklets is Python’s generators. Generators are objects that are defined as functions, and when called produce iterators that return values defined by the body of the function, specifically C{yield} statements.
The neat thing about generators are not the iterators themselves but the fact that a function’s state is completely frozen and restored between one call to the iterator’s C{next()} and the following one. This allows the function to return control to a program’s main loop while waiting for an event, such as IO on a socket, thus allowing other code to run in the mean time. When the specified event occurs, the function regains control and continues executing as if nothing had happened.
At the outset, a tasklet is simply a python U{generator function<http://www.python.org/peps/pep-0255.html>}, i.e. a function or method containing one or more C{yield} statements. Tasklets add a couple more requirements to regular generator functions:
- The values contained in C{yield} statements cannot be arbitrary (see below);
- After each C{yield} that indicates events, the function kiwi.tasklet.get_event must be called to retrieve the event that just occurred.
Inside tasklet functions, C{yield} statements are used to suspend execution of the tasklet while waiting for certain events. Valid C{yield} values are:
A single Message object, with a correctly set I{dest} parameter. With this form, a message is sent to the indicated tasklet. When C{yield} returns, no event is generated, so the tasklet should B{not} call get_event.
One, or a sequence of:
- WaitCondition, meaning to wait for that specific condition
- Tasklet, with the same meaning as L{WaitForTasklet}C{(tasklet)}
- generator, with the same meaning as :class:`WaitForTasklet`C{(Tasklet(gen))}
In this case, the tasklet is suspended until either one of the indicated events occurs. The tasklet must call get_event in this case.
- To start a tasklet, the Tasklet constructor must be used::
from kiwi import tasklet
- def my_task(x):
- [...]
tasklet.Tasklet(my_task(x=0))
- Alternatively, kiwi.tasklet.run can be used to the same effect::
- from kiwi import tasklet tasklet.run(my_task(x=0))
- Yet another approach is to use the @tasklet.task decorator::
from kiwi import tasklet
@tasklet.task def my_task(x):
[...] raise StopIteration(“return value”)yield my_task(x=0) retval = tasklet.get_event().retval
- This example demonstrates basic tasklet structure and timeout events::
import gobject from kiwi import tasklet
mainloop = gobject.MainLoop()
- def simple_counter(numbers):
timeout = tasklet.WaitForTimeout(1000) for x in xrange(numbers):
print x yield timeout tasklet.get_event()mainloop.quit()
tasklet.run(simple_counter(10)) mainloop.run()
This example extends the previous one and demonstrates message passing:
import gobject from kiwi import tasklet mainloop = gobject.MainLoop() @tasklet.task def printer(): msgwait = tasklet.WaitForMessages(accept=("quit", "print")) while True: yield msgwait msg = tasklet.get_event() if msg.name == "quit": return assert msg.name == 'print' print ">>> ", msg.value @tasklet.task def simple_counter(numbers, task): timeout = tasklet.WaitForTimeout(1000) for x in xrange(numbers): yield tasklet.Message('print', dest=task, value=x) yield timeout tasklet.get_event() yield tasklet.Message('quit', dest=task) mainloop.quit() task = printer() simple_counter(10, task) mainloop.run()
Bases: object
A message that can be received by or sent to a tasklet.
Bases: object
An object that launches and manages a tasklet.
Variables: |
|
---|
Add a callable to be invoked when the tasklet finishes. Return a connection handle that can be used in remove_join_callback()
where tasklet is the tasklet that finished, and retval its return value (or None).
When a join callback is invoked, it is automatically removed, so calling remove_join_callback afterwards produces a KeyError exception.
Dictionary mapping message names to actions (‘accept’ or ‘discard’ or ‘defer’). Should normally not be accessed directly by the programmer.
Dictionary mapping message names to actions (‘accept’ or ‘discard’ or ‘defer’). Should normally not be accessed directly by the programmer.
Remove a join callback previously added with add_join_callback
Method that executes the task.
Should be overridden in a subclass if no generator is passed into the constructor.
@note: do NOT call this method directly; it is meant to be called by the tasklet framework.
Bases: object
Base class for all wait-able condition objects.
WaitConditions are used in a yield statement inside tasklets body for specifying what event(s) it should wait for in order to receive control once more.
Prepare the wait condition to receive events.
When a wait condition receives the event it is waiting for, it should call the method L{wait_condition_fired<Tasklet.wait_condition_fired>} of the tasklet with the wait condition as argument. The method returns True or False; if it returns True, it means the WaitCondition object must “rearm” itself (continue to monitor events), otherwise it should disarm.
Parameters: | tasklet – the tasklet instance the wait condition is to be associated with. |
---|
Bases: kiwi.tasklet.WaitCondition
An object that waits until it is called.
import gobject from kiwi import tasklet
mainloop = gobject.MainLoop()
tasklet.run(my_task()) mainloop.run()
Variables: | return_value – value to return when called |
---|
Bases: kiwi.tasklet.WaitCondition
An object that waits for IO conditions on sockets or file descriptors.
Bases: kiwi.tasklet.WaitCondition
An object that waits for the main loop to become idle
Bases: kiwi.tasklet.WaitCondition
An object that waits for messages to arrive
Bases: kiwi.tasklet.WaitCondition
An object that waits for a process to end
Bases: kiwi.tasklet.WaitCondition
An object that waits for a signal emission
Bases: kiwi.tasklet.WaitCondition
An object that waits for a tasklet to complete
Bases: kiwi.tasklet.WaitCondition
An object that waits for a specified ammount of time (a timeout)
Return the last event that caused the current tasklet to regain control.
@note: this function should be called exactly once after each yield that includes a wait condition.
GObject utilities and addons
Add a GObject signal to the current object. It current supports the following types:
- str, int, float, long, object, enum
Parameters: |
|
---|
@note: retval: return value in signal callback
Return a list of all properties for GType gtype, excluding properties in parent classes