tuikit/core/application.py
author Radek Brich <radek.brich@devl.cz>
Tue, 18 Mar 2014 22:39:21 +0100
changeset 88 90d00354dc70
parent 86 0978fb755d31
child 89 94f5baef19ac
permissions -rw-r--r--
Add WindowManager, basic event handling.

from tuikit.core.window import WindowManager, Window

import logging


class Application:

    """Tuikit application helper.

    Joins all required pieces to build complete application
    using TUI widgets and event loop.

    """

    def __init__(self, driver='curses'):
        # logger
        self.log = logging.getLogger('tuikit')
        # Driver
        self.driver = None
        # Window Manager and root Window
        self.window_manager = WindowManager()
        self.root_window = Window()
        # flags
        self._started = False
        self._quit = False
        # find and initialize driver
        self.use_driver(driver)
        self.window_manager.add(self.root_window)

    def use_driver(self, driver_name):
        """Select driver to be used for rendering and input.

        `driver_name` should be one of: 'base', 'curses', 'sdl'

        """
        if self._started:
            raise Exception('Cannot change driver after starting the application.')
        module = __import__('tuikit.driver.' + driver_name, fromlist=['driver_class'])
        self.driver = module.driver_class()

    def start(self):
        """Start application. Runs main loop."""
        self.log.info('=== start ===')
        with self.driver:
            self.main_loop()

    def stop(self):
        """Terminate application."""
        self._quit = True

    def main_loop(self):
        """The main loop."""
        self._started = True
        self.window_manager.handle_event('resize', *self.driver.size)
#        timer = self._timer

        while not self._quit:
            self.window_manager.draw(self.driver)
            self.driver.flush()

            #timeout = timer.nearest_timeout()
            events = self.driver.getevents()#timeout)
            #timer.process_timeouts()

            for event in events:
                self.window_manager.handle_event(event[0], *event[1:])
        self._started = False
        self.log.info('=== quit ===')