Version

Quick search

Kivy Catalog

pic21

The Kivy Catalog viewer showcases widgets available in Kivy and allows interactive editing of kivy language code to get immediate feedback. You should see a two panel screen with a menu spinner button (starting with ‘Welcome’) and other controls across the top.The left pane contains kivy (.kv) code, and the right side is that code rendered. You can edit the left pane, though changes will be lost when you use the menu spinner button. The catalog will show you dozens of .kv examples controlling different widgets and layouts.

The catalog’s interface is set in the file kivycatalog.kv, while the interfaces for each menu option are set in containers_kvs directory. To add a new .kv file to the Kivy Catalog, add a .kv file into the container_kvs directory and reference that file in the ScreenManager section of kivycatalog.kv.

Known bugs include some issue with the drop

File demo/kivycatalog/main.py

'''
Kivy Catalog
============

The Kivy Catalog viewer showcases widgets available in Kivy
and allows interactive editing of kivy language code to get immediate
feedback. You should see a two panel screen with a menu spinner button
(starting with 'Welcome') and other controls across the top.The left pane
contains kivy (.kv) code, and the right side is that code rendered. You can
edit the left pane, though changes will be lost when you use the menu
spinner button. The catalog will show you dozens of .kv examples controlling
different widgets and layouts.

The catalog's interface is set in the file kivycatalog.kv, while the
interfaces for each menu option are set in containers_kvs directory. To
add a new .kv file to the Kivy Catalog, add a .kv file into the container_kvs
directory and reference that file in the ScreenManager section of
kivycatalog.kv.

Known bugs include some issue with the drop
'''
import kivy
kivy.require('1.4.2')
import os
import sys
from kivy.app import App
from kivy.factory import Factory
from kivy.lang import Builder, Parser, ParserException
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.codeinput import CodeInput
from kivy.animation import Animation
from kivy.clock import Clock

CATALOG_ROOT = os.path.dirname(__file__)

# Config.set('graphics', 'width', '1024')
# Config.set('graphics', 'height', '768')

'''List of classes that need to be instantiated in the factory from .kv files.
'''
CONTAINER_KVS = os.path.join(CATALOG_ROOT, 'container_kvs')
CONTAINER_CLASSES = [c[:-3] for c in os.listdir(CONTAINER_KVS)
    if c.endswith('.kv')]


class Container(BoxLayout):
    '''A container is essentially a class that loads its root from a known
    .kv file.

    The name of the .kv file is taken from the Container's class.
    We can't just use kv rules because the class may be edited
    in the interface and reloaded by the user.
    See :meth: change_kv where this happens.
    '''

    def __init__(self, **kwargs):
        super(Container, self).__init__(**kwargs)
        self.previous_text = open(self.kv_file).read()
        parser = Parser(content=self.previous_text)
        widget = Factory.get(parser.root.name)()
        Builder._apply_rule(widget, parser.root, parser.root)
        self.add_widget(widget)

    @property
    def kv_file(self):
        '''Get the name of the kv file, a lowercase version of the class
        name.
        '''
        return os.path.join(CONTAINER_KVS, self.__class__.__name__ + '.kv')


for class_name in CONTAINER_CLASSES:
    globals()[class_name] = type(class_name, (Container,), {})


class KivyRenderTextInput(CodeInput):
    def keyboard_on_key_down(self, window, keycode, text, modifiers):
        is_osx = sys.platform == 'darwin'
        # Keycodes on OSX:
        ctrl, cmd = 64, 1024
        key, key_str = keycode

        if text and key not in (list(self.interesting_keys.keys()) + [27]):
            # This allows *either* ctrl *or* cmd, but not both.
            if modifiers == ['ctrl'] or (is_osx and modifiers == ['meta']):
                if key == ord('s'):
                    self.catalog.change_kv(True)
                    return

        return super(KivyRenderTextInput, self).keyboard_on_key_down(
            window, keycode, text, modifiers)


class Catalog(BoxLayout):
    '''Catalog of widgets. This is the root widget of the app. It contains
    a tabbed pain of widgets that can be displayed and a textbox where .kv
    language files for widgets being demoed can be edited.

    The entire interface for the Catalog is defined in kivycatalog.kv,
    although individual containers are defined in the container_kvs
    directory.

    To add a container to the catalog,
    first create the .kv file in container_kvs
    The name of the file (sans .kv) will be the name of the widget available
    inside the kivycatalog.kv
    Finally modify kivycatalog.kv to add an AccordionItem
    to hold the new widget.
    Follow the examples in kivycatalog.kv to ensure the item
    has an appropriate id and the class has been referenced.

    You do not need to edit any python code, just .kv language files!
    '''
    language_box = ObjectProperty()
    screen_manager = ObjectProperty()
    _change_kv_ev = None

    def __init__(self, **kwargs):
        self._previously_parsed_text = ''
        super(Catalog, self).__init__(**kwargs)
        self.show_kv(None, 'Welcome')
        self.carousel = None

    def show_kv(self, instance, value):
        '''Called when an a item is selected, we need to show the .kv language
        file associated with the newly revealed container.'''

        self.screen_manager.current = value

        child = self.screen_manager.current_screen.children[0]
        with open(child.kv_file, 'rb') as file:
            self.language_box.text = file.read().decode('utf8')
        if self._change_kv_ev is not None:
            self._change_kv_ev.cancel()
        self.change_kv()
        # reset undo/redo history
        self.language_box.reset_undo()

    def schedule_reload(self):
        if self.auto_reload:
            txt = self.language_box.text
            child = self.screen_manager.current_screen.children[0]
            if txt == child.previous_text:
                return
            child.previous_text = txt
            if self._change_kv_ev is not None:
                self._change_kv_ev.cancel()
            if self._change_kv_ev is None:
                self._change_kv_ev = Clock.create_trigger(self.change_kv, 2)
            self._change_kv_ev()

    def change_kv(self, *largs):
        '''Called when the update button is clicked. Needs to update the
        interface for the currently active kv widget, if there is one based
        on the kv file the user entered. If there is an error in their kv
        syntax, show a nice popup.'''

        txt = self.language_box.text
        kv_container = self.screen_manager.current_screen.children[0]
        try:
            parser = Parser(content=txt)
            kv_container.clear_widgets()
            widget = Factory.get(parser.root.name)()
            Builder._apply_rule(widget, parser.root, parser.root)
            kv_container.add_widget(widget)
        except (SyntaxError, ParserException) as e:
            self.show_error(e)
        except Exception as e:
            self.show_error(e)

    def show_error(self, e):
        self.info_label.text = str(e).encode('utf-8')
        self.anim = Animation(top=190.0, opacity=1, d=2, t='in_back') +\
            Animation(top=190.0, d=3) +\
            Animation(top=0, opacity=0, d=2)
        self.anim.start(self.info_label)


class KivyCatalogApp(App):
    '''The kivy App that runs the main root. All we do is build a catalog
    widget into the root.'''

    def build(self):
        return Catalog()

    def on_pause(self):
        return True


if __name__ == "__main__":
    KivyCatalogApp().run()

File demo/kivycatalog/kivycatalog.kv

  1#:kivy 1.4
  2#:import KivyLexer kivy.extras.highlight.KivyLexer
  3
  4<Container>:
  5    canvas.before:
  6        Color:
  7            rgb: 0, 0, 0
  8        Rectangle:
  9            pos: self.pos
 10            size: self.size
 11
 12<Catalog>:
 13    language_box: language_box
 14    screen_manager: screen_manager
 15    auto_reload: chkbx.active
 16    info_label: info_lbl
 17    orientation: 'vertical'
 18    BoxLayout:
 19        padding: '2sp'
 20        canvas:
 21            Color:
 22                rgba: 1, 1, 1, .6
 23            Rectangle:
 24                size: self.size
 25                pos: self.pos
 26        size_hint: 1, None
 27        height: '45sp'
 28        Spinner:
 29            size_hint: None, 1
 30            width: '108sp'
 31            text: 'Welcome'
 32            values: [screen.name for screen in screen_manager.screens]
 33            on_text: root.show_kv(*args)
 34        Widget:
 35        BoxLayout:
 36            size_hint: None, 1
 37            width: '150sp'
 38            Label:
 39                text: "Auto Reload"
 40            CheckBox:
 41                id: chkbx
 42                active: True
 43                size_hint_x: 1
 44        Button:
 45            size_hint: None, 1
 46            width: '108sp'
 47            text: 'Render Now'
 48            on_release: root.change_kv(*args)
 49    BoxLayout:
 50        id: reactive_layout
 51        orientation: 'vertical' if self.width < self.height else 'horizontal'
 52
 53        Splitter:
 54            id: editor_pane
 55            max_size: (reactive_layout.height if self.vertical else reactive_layout.width) - self.strip_size
 56            min_size: sp(30) + self.strip_size
 57            vertical: 1 if reactive_layout.width < reactive_layout.height else 0
 58            sizable_from: 'bottom' if self.vertical else 'right'
 59            size_hint: (1, None) if self.vertical else (None, 1)
 60            size: 400, 400
 61            on_vertical:
 62                mid_size = self.max_size/2
 63                if args[1]: self.height = mid_size
 64                if not args[1]: self.width = mid_size
 65            ScrollView:
 66                id: kr_scroll
 67                KivyRenderTextInput:
 68                    catalog: root
 69                    id: language_box
 70                    auto_indent: True
 71                    lexer: KivyLexer()
 72                    size_hint: 1, None
 73                    height: max(kr_scroll.height, self.minimum_height)
 74                    valign: "top"
 75                    text: "This box will display the kivy language for whatever has been selected"
 76                    on_text: root.schedule_reload()
 77                    on_cursor: root.schedule_reload()
 78        ScreenManager:
 79            id: screen_manager
 80            Screen:
 81                name: "Welcome"
 82                PlaygroundContainer:
 83            Screen:
 84                name: "Float Layout"
 85                FloatLayoutContainer
 86            Screen:
 87                name: "Box Layout"
 88                BoxLayoutContainer:
 89            Screen:
 90                name: "Anchor Layout"
 91                AnchorLayoutContainer:
 92            Screen:
 93                name: "Grid Layout"
 94                GridLayoutContainer:
 95            Screen:
 96                name: "Stack Layout"
 97                StackLayoutContainer:
 98            Screen:
 99                name: "Buttons"
100                ButtonContainer:
101            Screen:
102                name: "Labels"
103                LabelContainer:
104            Screen:
105                name: "Booleans"
106                CheckBoxContainer:
107            Screen:
108                name: "Progress Bar"
109                ProgressBarContainer:
110            Screen:
111                name: "Media"
112                MediaContainer:
113            Screen:
114                name: "Text"
115                TextContainer:
116            Screen:
117                name: "Popups"
118                PopupContainer:
119            Screen:
120                name: "Selectors"
121                SelectorsContainer:
122            Screen:
123                name: "File Choosers"
124                FileChooserContainer:
125            Screen:
126                name: "Scatter"
127                ScatterContainer:
128            Screen:
129                name: "ReST"
130                RestContainer:
131    FloatLayout:
132        size_hint: 1, None
133        height: 0
134        TextInput:
135            id:info_lbl
136            readonly: True
137            font_size: '14sp'
138            background_color: (0, 0, 0, 1)
139            foreground_color: (1, 1, 1, 1)
140            opacity:0
141            size_hint: 1, None
142            text_size: self.size
143            height: '150pt'
144            top: 0