Esempio n. 1
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)
Esempio n. 2
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))
Esempio n. 3
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)
Esempio n. 4
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 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
Esempio n. 6
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 = []
Esempio n. 7
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)
     with self.assertRaises(AttributeError):
         foo = qd.not_an_attribute
Esempio n. 8
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)
Esempio n. 9
0
class ArithmeBricksApp(App):
    def build(self):
        self.icon = 'icon.png'
        self.load_sounds()
        game = ArithmeBricksGame()
        Clock.schedule_once(lambda dt: game.show_title(), 1)
        return game

    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)

    def play_sound(self, symbol, delay=None, volume=0.15):
        sound = self.symbol_to_sound.get(symbol)
        if sound is not None:

            def callback(dt):
                sound.volume = volume
                sound.play()

            if delay is None:
                delay = random.randint(0, 20) / 50
            Clock.schedule_once(callback, delay)
Esempio n. 10
0
File: lang.py Progetto: 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
Esempio n. 11
0
class ArithmeBricksApp(App):

    def build(self):
        self.icon = 'icon.png'
        self.load_sounds()
        game = ArithmeBricksGame()
        Clock.schedule_once(lambda dt: game.show_title(), 1)
        return game

    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)

    def play_sound(self, symbol, delay=None, volume=0.15):
        sound = self.symbol_to_sound.get(symbol)
        if sound is not None:
            def callback(dt):
                sound.volume = volume
                sound.play()
            if delay is None:
                delay = random.randint(0, 20) / 50
            Clock.schedule_once(callback, delay)
Esempio n. 12
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()
Esempio n. 13
0
    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
Esempio n. 14
0
    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
Esempio n. 15
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
Esempio n. 16
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)
Esempio n. 17
0
class Document(object):
    available_objects = {}

    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 = []

    @staticmethod
    def register(name, cls):
        Document.available_objects[name] = cls

    @property
    def objects(self):
        return (QueryDict(x) for x in self._objects)

    @property
    def slides(self):
        return (QueryDict(x) for x in self._slides)

    def load(self, filename):
        with open(filename, 'r') as fd:
            j = json.loads(fd.read())
        self.infos.update(j['document'])
        for slide in j['slides']:
            thumb = slide['thumb']
            if thumb is not None:
                slide['thumb'] = self.decode_thumb(thumb)
            self._slides.append(DocumentSlide(slide))
        for obj in j['objects']:
            # No dict comprehensions in 2.6 yet :'-(
            kwargs = {}
            for k, v in obj.iteritems():
                kwargs[str(k)] = v
            inst = Document.available_objects[obj['dtype']](**kwargs)
            self._objects.append(inst)

    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))

    def create_text(self, **attrs):
        text = TextObject(**attrs)
        text.dtype = 'text'
        self._objects.append(text)
        return text

    def create_image(self, **attrs):
        image = ImageObject(**attrs)
        image.dtype = 'image'
        self._objects.append(image)
        return image

    def create_video(self, **attrs):
        video = VideoObject(**attrs)
        video.dtype = 'video'
        self._objects.append(video)
        return video

    def encode_thumb(self, thumb):
        import pygame
        import tempfile
        import os
        import base64

        w, h, pixels = thumb
        # convert pixels to jpeg
        surface = pygame.image.fromstring(pixels, (w, h), 'RGB', True)
        fn = tempfile.mktemp('.jpg')
        pygame.image.save(surface, fn)
        # read jpeg
        with open(fn) as fd:
            data = fd.read()
        # delete file
        os.unlink(fn)
        # convert to base64
        data = base64.b64encode(data)
        return (w, h, 'data:image/jpeg;base64,' + data)

    def decode_thumb(self, thumb):
        header = 'data:image/jpeg;base64,'
        w, h, data = thumb
        if not data.startswith('data:image/jpeg;base64,'):
            return None
        data = data[len(header):]
        import base64
        import StringIO
        import pygame
        data = StringIO.StringIO(base64.b64decode(data))
        surface = pygame.image.load(data, 'image.jpg')
        return (w, h, pygame.image.tostring(surface, 'RGB', True))

    def add_slide(self, pos, rotation, scale, thumb):
        if thumb is not None:
            thumb = self.encode_thumb(thumb)
        slide = DocumentSlide()
        slide.pos = pos
        slide.rotation = rotation
        slide.scale = scale
        slide.thumb = thumb
        self._slides.append(slide)
        return slide

    def remove_slide(self, slide):
        self._slides.remove(slide)

    def clear_slides(self):
        self._slides = {}
Esempio n. 18
0
 def objects(self):
     return (QueryDict(x) for x in self._objects)
Esempio n. 19
0
 def slides(self):
     return (QueryDict(x) for x in self._slides)
Esempio n. 20
0
 def add_to_playlist_callback(self, track):
     self.playlist.add_track(QueryDict(track))
     self.fix_scrolling_workaround()
Esempio n. 21
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]