Source

Fat x Fast / FatxFast / gui / container.py

Full commit
# This file is part of FatxFast.
#
#    FatxFast is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    FatxFast is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with FatxFast.  If not, see <http://www.gnu.org/licenses/>.

# Versioning based on: 
# http://en.wikipedia.org/wiki/Versioning#Designating_development_stage
__author__ = "dryatu (c) 2013"
__version__ = "1.2.4"

class Container(object):

    def __init__(self, **kwargs):
        super(Container, self).__init__(**kwargs)
        self.widgets = {}
        
    def add_widget(self, name, widget):
        self.widgets[name] = widget
        
    def _delete_container_eval(self, widget, name):
        if widget.name == name:
            return widget.kill()

    def delete_widget(self, name):
        self._call_child_widgets(lambda x: self._delete_container_eval(x, name))

    def _forward_input_to_widgets(self, function, *args):
        for widget in self.widgets.values():
            getattr(widget, function)(*args)

    def _widget_name_eval(self, widget, name):
        if widget.name == name:
            return widget

    def get_widget(self, name):
        # TODO: Add unique id find to get_widget. East widget access
        return self._call_child_widgets(
            lambda x: self._widget_name_eval(x, name))

    def _call_child_widgets(self, function): 
        for widget in self.widgets.values():
            return_value = function(widget)  
            if not return_value and isinstance(widget, Container):
                return_value = widget._call_child_widgets(function)
            if return_value:
                return return_value

    def draw(self, surface):
        for widget in self.widgets:
            self.widgets[widget].draw(surface)

    def key_pressed(self, key, utf, mod):
        self._forward_input_to_widgets("key_pressed", key, utf, mod) 

    def key_released(self, key):
        self._forward_input_to_widgets("key_released", key)

    def mouse_pressed(self, button, pos): 
        self._forward_input_to_widgets("mouse_pressed", button, pos)

    def mouse_released(self, button):
        self._forward_input_to_widgets("mouse_released", button)

    def mouse_moved(self, pos, rel):
        self._forward_input_to_widgets("mouse_moved", pos, rel)
    
    def update(self, dt):
        for widget in self.widgets:
            self.widgets[widget].update(dt)