Example #1
0
File: lang.py Project: wilsaj/kivy
    def template(self, *args, **ctx):
        '''Create a specialized template using a specific context.
        .. versionadded:: 1.0.5

        With template, you can construct custom widget from a kv lang definition
        by giving them a context. Check :ref:`Template usage <template_usage>`.
        '''
        # Prevent naming clash with whatever the user might be putting into the
        # ctx as key.
        name = args[0]
        if not name in self.templates:
            raise Exception('Unknown <%s> template name' % name)
        baseclasses, defs, fn = self.templates[name]
        name, baseclasses
        key = '%s|%s' % (name, baseclasses)
        cls = Cache.get('kv.lang', key)
        if cls is None:
            rootwidgets = []
            for basecls in baseclasses.split('+'):
                rootwidgets.append(Factory.get(basecls))
            cls = ClassType(name, tuple(rootwidgets), {})
            Cache.append('kv.lang', key, cls)
        widget = cls()
        self._push_widgets()
        self._push_ids()
        self.idmap = copy(global_idmap)
        self.idmap['root'] = widget
        self.idmap['ctx'] = QueryDict(ctx)
        self.build_item(widget, defs, is_rule=True)
        self._pop_ids()
        self._pop_widgets()
        return widget
Example #2
0
 def load_sounds(self):
     self.symbol_to_sound = QueryDict()
     sound_ids = list('0123456789') + list(SOUND_ID_TO_SYMBOL)
     for sound_id in sound_ids:
         filename = SOUND_FILENAME_PATTERN.format(sound_id)
         symbol = SOUND_ID_TO_SYMBOL.get(sound_id, sound_id)
         self.symbol_to_sound[symbol] = SoundLoader.load(filename)
Example #3
0
 def add_album_to_playlist_callback(self, album_id):
     album = Globals.API.get_album_info(album_id)
     album_tracks = album['tracks']
     if album_tracks:
         album_tracks = self.formatter.format_tracks_list(album_tracks)
         for track in album_tracks:
             self.playlist.add_track(QueryDict(track))
         self.fix_scrolling_workaround()
Example #4
0
 def save(self, filename):
     doc = QueryDict()
     doc.document = self.infos
     doc.document.time_modification = time()
     doc.objects = self._objects
     doc.slides = self._slides
     with open(filename, 'w') as fd:
         fd.write(json.dumps(doc))
Example #5
0
 def test_QueryDict(self):
     qd = QueryDict()
     self.assertTrue(isinstance(qd, dict))
     # __setattr__
     qd.toto = 1
     self.assertEqual(qd.get('toto'), 1)
     # __getattr__
     toto = qd.toto
     self.assertEqual(toto, 1)
    def _create_entry_widget(self, ctx):
        widget = super()._create_entry_widget(ctx)
        kctx = QueryDict(ctx)
        if os.path.isdir(kctx["path"]):
            widget.image.icon = self.icon_folder
        else:
            if self.get_icon_file:
                widget.image.icon = self.get_icon_file(kctx["path"])

        return widget
 def test_QueryDict(self):
     qd = QueryDict()
     self.assertTrue(isinstance(qd, dict))
     # __setattr__
     qd.toto = 1
     self.assertEqual(qd.get('toto'), 1)
     # __getattr__
     toto = qd.toto
     self.assertEqual(toto, 1)
     with self.assertRaises(AttributeError):
         foo = qd.not_an_attribute
    def _create_entry_widget(self, ctx):
        # instantiate the widget
        widget = super(FileChooserThumbView, self)._create_entry_widget(ctx)

        kctx = QueryDict(ctx)
        # default icon
        widget.image.source = FOLDER_ICON if kctx.isdir else FILE_ICON
        # schedule generation for later execution
        self.thumbnail_generator.append(widget.image, kctx, self._get_image)
        self.thumbnail_generator.run()
        return widget
Example #9
0
 def __init__(self, **kwargs):
     self.infos = QueryDict()
     self.infos.version = 1
     self.infos.time_creation = time()
     self.infos.time_modification = time()
     self.infos.root_size = kwargs.get('size', (100, 100))
     self.infos.root_pos = kwargs.get('pos', (0, 0))
     self.infos.root_scale = kwargs.get('scale', 0.)
     self.infos.root_rotation = kwargs.get('rotation', 0.)
     self._objects = []
     self._slides = []
Example #10
0
 def on_touch_down(self, touch):
     if not self.collide_point(*touch.pos):
         return
     for child in self.children:
         if touch.x >= child.x and touch.x <= (child.x + child.width) and touch.y >= child.y and touch.y <= (child.y + child.height):
             child.on_touch_down( touch)
             return
     touch.grab(self)
     self.focus()
     uid = self._get_uid()
     touch.ud[uid] = QueryDict(mode='unknown')
     self._touches.append(touch)
     if self.scroll_timeout == 0:
         touch.ud[uid].mode = 'controlled'
         self._mouse_move(touch)
         self._bk.mouseButton(0, 1)
     else:
         Clock.schedule_once(self._change_touch_mode, self.scroll_timeout / 1000.)
     return True
Example #11
0
 def add_to_playlist_callback(self, track):
     self.playlist.add_track(QueryDict(track))
     self.fix_scrolling_workaround()
Example #12
0
    def _apply_rule(self,
                    widget,
                    rule,
                    rootrule,
                    template_ctx=None,
                    ignored_consts=set(),
                    rule_children=None):
        # widget: the current instantiated widget
        # rule: the current rule
        # rootrule: the current root rule (for children of a rule)

        # will collect reference to all the id in children
        assert (rule not in self.rulectx)
        self.rulectx[rule] = rctx = {
            'ids': {
                'root': widget.proxy_ref
            },
            'set': [],
            'hdl': []
        }

        # extract the context of the rootrule (not rule!)
        assert (rootrule in self.rulectx)
        rctx = self.rulectx[rootrule]

        # if a template context is passed, put it as "ctx"
        if template_ctx is not None:
            rctx['ids']['ctx'] = QueryDict(template_ctx)

        # if we got an id, put it in the root rule for a later global usage
        if rule.id:
            # use only the first word as `id` discard the rest.
            rule.id = rule.id.split('#', 1)[0].strip()
            rctx['ids'][rule.id] = widget.proxy_ref
            # set id name as a attribute for root widget so one can in python
            # code simply access root_widget.id_name
            _ids = dict(rctx['ids'])
            _root = _ids.pop('root')
            _new_ids = _root.ids
            for _key, _value in _ids.items():
                if _value == _root:
                    # skip on self
                    continue
                _new_ids[_key] = _value
            _root.ids = _new_ids

        # first, ensure that the widget have all the properties used in
        # the rule if not, they will be created as ObjectProperty.
        rule.create_missing(widget)

        # build the widget canvas
        if rule.canvas_before:
            with widget.canvas.before:
                self._build_canvas(widget.canvas.before, widget,
                                   rule.canvas_before, rootrule)
        if rule.canvas_root:
            with widget.canvas:
                self._build_canvas(widget.canvas, widget, rule.canvas_root,
                                   rootrule)
        if rule.canvas_after:
            with widget.canvas.after:
                self._build_canvas(widget.canvas.after, widget,
                                   rule.canvas_after, rootrule)

        # create children tree
        Factory_get = Factory.get
        Factory_is_template = Factory.is_template
        for crule in rule.children:
            cname = crule.name

            if cname in ('canvas', 'canvas.before', 'canvas.after'):
                raise ParserException(
                    crule.ctx, crule.line,
                    'Canvas instructions added in kv must '
                    'be declared before child widgets.')

            # depending if the child rule is a template or not, we are not
            # having the same approach
            cls = Factory_get(cname)

            if Factory_is_template(cname):
                # we got a template, so extract all the properties and
                # handlers, and push them in a "ctx" dictionary.
                ctx = {}
                idmap = copy(global_idmap)
                idmap.update({'root': rctx['ids']['root']})
                if 'ctx' in rctx['ids']:
                    idmap.update({'ctx': rctx['ids']['ctx']})
                try:
                    for prule in crule.properties.values():
                        value = prule.co_value
                        if type(value) is CodeType:
                            value = eval(value, idmap)
                        ctx[prule.name] = value
                    for prule in crule.handlers:
                        value = eval(prule.value, idmap)
                        ctx[prule.name] = value
                except Exception as e:
                    tb = sys.exc_info()[2]
                    raise BuilderException(prule.ctx,
                                           prule.line,
                                           '{}: {}'.format(
                                               e.__class__.__name__, e),
                                           cause=tb)

                # create the template with an explicit ctx
                child = cls(**ctx)
                widget.add_widget(child)

                # reference it on our root rule context
                if crule.id:
                    rctx['ids'][crule.id] = child

            else:
                # we got a "normal" rule, construct it manually
                # we can't construct it without __no_builder=True, because the
                # previous implementation was doing the add_widget() before
                # apply(), and so, we could use "self.parent".
                child = cls(__no_builder=True)
                widget.add_widget(child)
                child.apply_class_lang_rules(root=rctx['ids']['root'],
                                             rule_children=rule_children)
                self._apply_rule(child,
                                 crule,
                                 rootrule,
                                 rule_children=rule_children)

                if rule_children is not None:
                    rule_children.append(child)

        # append the properties and handlers to our final resolution task
        if rule.properties:
            rctx['set'].append(
                (widget.proxy_ref, list(rule.properties.values())))
            for key, crule in rule.properties.items():
                # clear previously applied rules if asked
                if crule.ignore_prev:
                    Builder.unbind_property(widget, key)
        if rule.handlers:
            rctx['hdl'].append((widget.proxy_ref, rule.handlers))

        # if we are applying another rule that the root one, then it's done for
        # us!
        if rootrule is not rule:
            del self.rulectx[rule]
            return

        # normally, we can apply a list of properties with a proper context
        try:
            rule = None
            for widget_set, rules in reversed(rctx['set']):
                for rule in rules:
                    assert (isinstance(rule, ParserRuleProperty))
                    key = rule.name
                    value = rule.co_value
                    if type(value) is CodeType:
                        value, bound = create_handler(widget_set, widget_set,
                                                      key, value, rule,
                                                      rctx['ids'])
                        # if there's a rule
                        if (widget_set != widget or bound
                                or key not in ignored_consts):
                            setattr(widget_set, key, value)
                    else:
                        if (widget_set != widget or key not in ignored_consts):
                            setattr(widget_set, key, value)

        except Exception as e:
            if rule is not None:
                tb = sys.exc_info()[2]
                raise BuilderException(rule.ctx,
                                       rule.line,
                                       '{}: {}'.format(e.__class__.__name__,
                                                       e),
                                       cause=tb)
            raise e

        # build handlers
        try:
            crule = None
            for widget_set, rules in rctx['hdl']:
                for crule in rules:
                    assert (isinstance(crule, ParserRuleProperty))
                    assert (crule.name.startswith('on_'))
                    key = crule.name
                    if not widget_set.is_event_type(key):
                        key = key[3:]
                    idmap = copy(global_idmap)
                    idmap.update(rctx['ids'])
                    idmap['self'] = widget_set.proxy_ref
                    if not widget_set.fbind(key, custom_callback, crule,
                                            idmap):
                        raise AttributeError(key)
                    # hack for on_parent
                    if crule.name == 'on_parent':
                        Factory.Widget.parent.dispatch(widget_set.__self__)
        except Exception as e:
            if crule is not None:
                tb = sys.exc_info()[2]
                raise BuilderException(crule.ctx,
                                       crule.line,
                                       '{}: {}'.format(e.__class__.__name__,
                                                       e),
                                       cause=tb)
            raise e

        # rule finished, forget it
        del self.rulectx[rootrule]
Example #13
0
    def _apply_rule(self, widget, rule, rootrule, template_ctx=None):
        # widget: the current instanciated widget
        # rule: the current rule
        # rootrule: the current root rule (for children of a rule)

        # will collect reference to all the id in children
        assert(rule not in self.rulectx)
        self.rulectx[rule] = rctx = {
            'ids': {'root': widget},
            'set': [], 'hdl': []}

        # extract the context of the rootrule (not rule!)
        assert(rootrule in self.rulectx)
        rctx = self.rulectx[rootrule]

        # if a template context is passed, put it as "ctx"
        if template_ctx is not None:
            rctx['ids']['ctx'] = QueryDict(template_ctx)

        # if we got an id, put it in the root rule for a later global usage
        if rule.id:
            rctx['ids'][rule.id] = widget

        # first, ensure that the widget have all the properties used in the rule
        # if not, they will be created as ObjectProperty.
        rule.create_missing(widget)

        # build the widget canvas
        if rule.canvas_before:
            with widget.canvas.before:
                self._build_canvas(widget.canvas.before, widget,
                        rule.canvas_before, rootrule)
        if rule.canvas_root:
            with widget.canvas:
                self._build_canvas(widget.canvas, widget,
                        rule.canvas_root, rootrule)
        if rule.canvas_after:
            with widget.canvas.after:
                self._build_canvas(widget.canvas.after, widget,
                        rule.canvas_after, rootrule)

        # create children tree
        Factory_get = Factory.get
        Factory_is_template = Factory.is_template
        for crule in rule.children:
            cname = crule.name

            # depending if the child rule is a template or not, we are not
            # having the same approach
            cls = Factory_get(cname)

            if Factory_is_template(cname):
                # we got a template, so extract all the properties and handlers,
                # and push them in a "ctx" dictionnary.
                ctx = {}
                idmap = copy(global_idmap)
                idmap.update({'root': rctx['ids']['root']})
                if 'ctx' in rctx['ids']:
                    idmap.update({'ctx': rctx['ids']['ctx']})
                try:
                    for prule in crule.properties.itervalues():
                        value = prule.co_value
                        if type(value) is CodeType:
                                value = eval(value, idmap)
                        ctx[prule.name] = value
                    for prule in crule.handlers:
                        value = eval(prule.value, idmap)
                        ctx[prule.name] = value
                except Exception, e:
                    raise BuilderException(prule.ctx, prule.line, str(e))

                # create the template with an explicit ctx
                child = cls(**ctx)
                widget.add_widget(child)

                # reference it on our root rule context
                if crule.id:
                    rctx['ids'][crule.id] = child

            else:
                # we got a "normal" rule, construct it manually
                # we can't construct it without __no_builder=True, because the
                # previous implementation was doing the add_widget() before
                # apply(), and so, we could use "self.parent".
                child = cls(__no_builder=True)
                widget.add_widget(child)
                self.apply(child)
                self._apply_rule(child, crule, rootrule)
Example #14
0
 def slides(self):
     return (QueryDict(x) for x in self._slides)
Example #15
0
 def objects(self):
     return (QueryDict(x) for x in self._objects)