view cagou/core/cagou_widget.py @ 353:19422bbd9c8e

core (widgets handler): refactoring: - CagouWidget now has class properties (to be overridden when needed) which indicate how if the widget handle must add a wrapping ScreenManager (global_screen_manager) or show all instances of the class in a Carousel (collection_carousel). If none of those options is used, a ScrollView will be wrapping the widget, to be sure that the widget will be resized correctly when necessary (without it, the widget could still be drawn in the backround when the size is too small and overflow on the WidgetWrapper, this would be the case with WidgetSelector) - some helper methods/properties have been added to CagouWidget. Check docstrings for details - better handling of (in)visible widget in WidgetsHandler - thanks to the new wrapping ScrollView, WidgetSelect will show scroll bars if the available space is too small. - bugs fixes
author Goffi <goffi@goffi.org>
date Fri, 17 Jan 2020 18:44:35 +0100
parents 772c170b47a9
children 4d3a0c4f2430
line wrap: on
line source

#!/usr/bin/python
# -*- coding: utf-8 -*-

# Cagou: desktop/mobile frontend for Salut à Toi XMPP client
# Copyright (C) 2016-2019 Jérôme Poisson (goffi@goffi.org)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program 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 Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


from sat.core import log as logging
from sat.core import exceptions
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.dropdown import DropDown
from kivy.uix.screenmanager import Screen
from kivy import properties
from cagou import G
from .common import ActionIcon


log = logging.getLogger(__name__)


class HeaderWidgetChoice(ButtonBehavior, BoxLayout):

    def __init__(self, cagou_widget, plugin_info):
        self.plugin_info = plugin_info
        super(HeaderWidgetChoice, self).__init__()
        self.bind(on_release=lambda btn: cagou_widget.switchWidget(plugin_info))


class HeaderWidgetCurrent(ButtonBehavior, ActionIcon):
    pass


class HeaderWidgetSelector(DropDown):

    def __init__(self, cagou_widget):
        super(HeaderWidgetSelector, self).__init__()
        plg_info_cls = cagou_widget.plugin_info_class or cagou_widget.__class__
        for plugin_info in G.host.getPluggedWidgets(except_cls=plg_info_cls):
            choice = HeaderWidgetChoice(cagou_widget, plugin_info)
            self.add_widget(choice)

    def add_widget(self, *args):
        widget = args[0]
        widget.bind(minimum_width=self.set_width)
        return super(HeaderWidgetSelector, self).add_widget(*args)

    def set_width(self, choice, minimum_width):
        self.width = max([c.minimum_width for c in self.container.children])


class CagouWidget(BoxLayout):
    main_container = properties.ObjectProperty(None)
    header_input = properties.ObjectProperty(None)
    header_box = properties.ObjectProperty(None)
    # set to True if you want to be able to switch between visible widgets of this
    # class using a carousel
    collection_carousel = False
    # set to True if you a global ScreenManager global to all widgets of this class.
    # The screen manager is created in WHWrapper
    global_screen_manager = False
    # override this if a specific class (i.e. not self.__class__) must be used for
    # plugin info. Useful when a CagouWidget is used with global_screen_manager.
    plugin_info_class = None

    def __init__(self, **kwargs):
        plg_info_cls = self.plugin_info_class or self.__class__
        for p in G.host.getPluggedWidgets():
            if p['main'] == plg_info_cls:
                self.plugin_info = p
                break
        super().__init__(**kwargs)
        self.selector = HeaderWidgetSelector(self)

    @property
    def screen_manager(self):
        if ((not self.global_screen_manager
             and not (self.plugin_info_class is not None
                      and self.plugin_info_class.global_screen_manager))):
            raise exceptions.InternalError(
                "screen_manager property can't be used if global_screen_manager is not "
                "set")
        screen = self.getAncestor(Screen)
        if screen is None:
            raise exceptions.NotFound("Can't find parent Screen")
        if screen.manager is None:
            raise exceptions.NotFound("Can't find parent ScreenManager")
        return screen.manager

    @property
    def whwrapper(self):
        """Retrieve parent widget handler"""
        return G.host.getParentWHWrapper(self)

    def screenManagerInit(self, screen_manager):
        """Override this method to do init when ScreenManager is instantiated

        This is only called once even if collection_carousel is used.
        """
        if not self.global_screen_manager:
            raise exceptions.InternalError("screenManagerInit should not be called")

    def getAncestor(self, cls):
        """Helper method to use host.getAncestorWidget with self"""
        return G.host.getAncestorWidget(self, cls)

    def switchWidget(self, plugin_info):
        self.selector.dismiss()
        factory = plugin_info["factory"]
        new_widget = factory(plugin_info, None, iter(G.host.profiles))
        G.host.switchWidget(self, new_widget)

    def onHeaderInput(self):
        log.info("header input text entered")

    def onHeaderInputComplete(self, wid, text):
        return

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            G.host.selected_widget = self
        return super(CagouWidget, self).on_touch_down(touch)

    def headerInputAddExtra(self, widget):
        """add a widget on the right of header input"""
        self.header_box.add_widget(widget)

    def onVisible(self):
        pass
        # log.debug(u"{self} is visible".format(self=self))

    def onNotVisible(self):
        pass
        # log.debug(u"{self} is not visible anymore".format(self=self))