Example #1
0
    def helpView(self):
        """
        Show Help/Guides modal (show when help button pressed)
        """
        widgets = FloatLayout(size_hint=(None,None),
                         size=(300,300),
                         background_color=parse_color("#FF9933"),)
        sizer = NumericProperty(30)
        main = ModalView(title_color=parse_color("#FF9933"),
                     title_size=(25),
                     seperator_height=("9dp"),
                     separator_color=parse_color("#FF9933"),
                     #background_color=parse_color("#FF9933"),
                     size_hint=(None,None),
                     size=(400,620),
                     content = Image(source="coreEngine/Images/about.png"),
                             )
        

        
        white_bar = Image(source="coreEngine/Images/whitebar.png",
                          pos=(123,123),
                          size=(400,400))
        
        logo = Image(source="coreEngine/Images/about.png")
        
        main.add_widget(logo, 1)
        main.open()
Example #2
0
    def helpView(self):
        """
        Show Help/Guides modal (show when help button pressed)
        """
        widgets = FloatLayout(
            size_hint=(None, None),
            size=(300, 300),
            background_color=parse_color("#FF9933"),
        )
        sizer = NumericProperty(30)
        main = ModalView(
            title_color=parse_color("#FF9933"),
            title_size=(25),
            seperator_height=("9dp"),
            separator_color=parse_color("#FF9933"),
            #background_color=parse_color("#FF9933"),
            size_hint=(None, None),
            size=(400, 620),
            content=Image(source="coreEngine/Images/about.png"),
        )

        white_bar = Image(source="coreEngine/Images/whitebar.png",
                          pos=(123, 123),
                          size=(400, 400))

        logo = Image(source="coreEngine/Images/about.png")

        main.add_widget(logo, 1)
        main.open()
Example #3
0
 def __init__(self, **kwargs):
     super(B, self).__init__(**kwargs)
     self.size_hint=None,None
     self.size=123,50
     self.text="123"
     self.background_normal="#ffffff"
     self.color=parse_color("#000000")
     self.opacity=.9
Example #4
0
    def _pre_render(self):
        # split markup, words, and lines
        # result: list of word with position and width/height
        # during the first pass, we don't care about h/valign
        self._lines = lines = []
        self._refs = {}
        self._anchors = {}
        spush = self._push_style
        spop = self._pop_style
        options = self.options
        options['_ref'] = None
        for item in self.markup:
            if item == '[b]':
                spush('bold')
                options['bold'] = True
                self.resolve_font_name()
            elif item == '[/b]':
                spop('bold')
                self.resolve_font_name()
            elif item == '[i]':
                spush('italic')
                options['italic'] = True
                self.resolve_font_name()
            elif item == '[/i]':
                spop('italic')
                self.resolve_font_name()
            elif item[:6] == '[size=':
                item = item[6:-1]
                try:
                    if item[-2:] in ('px', 'pt', 'in', 'cm', 'mm'):
                        size = dpi2px(item[:-2], item[-2:])
                    else:
                        size = int(item)
                except ValueError:
                    raise
                    size = options['font_size']
                spush('font_size')
                options['font_size'] = size
            elif item == '[/size]':
                spop('font_size')
            elif item[:7] == '[color=':
                color = parse_color(item[7:-1])
                spush('color')
                options['color'] = color
            elif item == '[/color]':
                spop('color')
            elif item[:6] == '[font=':
                fontname = item[6:-1]
                spush('font_name')
                options['font_name'] = fontname
                self.resolve_font_name()
            elif item == '[/font]':
                spop('font_name')
                self.resolve_font_name()
            elif item[:5] == '[ref=':
                ref = item[5:-1]
                spush('_ref')
                options['_ref'] = ref
            elif item == '[/ref]':
                spop('_ref')
            elif item[:8] == '[anchor=':
                ref = item[8:-1]
                if len(lines):
                    x, y = lines[-1][0:2]
                else:
                    x = y = 0
                self._anchors[ref] = x, y
            else:
                item = item.replace('&bl;', '[').replace(
                        '&br;', ']').replace('&', '&')
                self._pre_render_label(item, options, lines)

        # calculate the texture size
        w, h = self.text_size
        if h < 0:
            h = None
        if w < 0:
            w = None
        if w is None:
            w = max([line[0] for line in lines])
        if h is None:
            h = sum([line[1] for line in lines])
        return w, h
Example #5
0
    def render(self, real=False):
        w, h = 0, 0
        x, y = 0, 0
        lw, lh = 0, 0
        nl = False
        if real:
            self._render_begin()

        for item in self.markup:
            if item == '[b]':
                self._push_style('bold')
                self.options['bold'] = True
            elif item == '[/b]':
                self._pop_style('bold')
            elif item == '[i]':
                self._push_style('italic')
                self.options['italic'] = True
            elif item == '[/i]':
                self._pop_style('italic')
            elif item.startswith('[size='):
                size = int(item[6:-1])
                self._push_style('font_size')
                self.options['font_size'] = size
            elif item == '[/size]':
                self._pop_style('font_size')
            elif item.startswith('[color='):
                color = parse_color(item[7:-1])
                self._push_style('color')
                self.options['color'] = color
            elif item == '[/color]':
                self._pop_style('color')
            elif item.startswith('[font='):
                fontname = item[6:-1]
                self._push_style('font_name')
                self.options['font_name'] = fontname
            elif item == '[/font]':
                self._pop_style('font_name')
            else:
                args = x, y, w, h, lw, lh, nl
                args = self.render_label(real, item, args)
                x, y, w, h, lw, lh, nl = args

        if not real:
            # was only the first pass
            # return with/height
            w = int(max(w, 1))
            h = int(max(h, 1))
            return w, h

        # get data from provider
        data = self._render_end()
        assert(data)

        # create texture is necessary
        w = self.texture.width
        h = self.texture.height
        if self.texture is None:
            self.texture = kivy.Texture.create(size=self.size)
            self.texture.flip_vertical()
        elif self.width > w or self.height > h:
            self.texture = kivy.Texture.create(size=self.size)
            self.texture.flip_vertical()
        else:
            self.texture = self.texture.get_region(
                0, 0, self.width, self.height)

        # update texture
        self.texture.blit_data(data)
Example #6
0
    def _pre_render(self):
        # split markup, words, and lines
        # result: list of word with position and width/height
        # during the first pass, we don't care about h/valign
        self._cached_lines = lines = []
        self._refs = {}
        self._anchors = {}
        clipped = False
        w = h = 0
        uw, uh = self.text_size
        spush = self._push_style
        spop = self._pop_style
        options = self.options
        options['_ref'] = None
        options['_anchor'] = None
        options['script'] = 'normal'
        shorten = options['shorten']
        # if shorten, then don't split lines to fit uw, because it will be
        # flattened later when shortening and broken up lines if broken
        # mid-word will have space mid-word when lines are joined
        uw_temp = None if shorten else uw
        xpad = options['padding_x']
        uhh = (None if uh is not None and options['valign'] != 'top'
               or options['shorten'] else uh)
        options['strip'] = options['strip'] or options['halign'] == 'justify'
        find_base_dir = Label.find_base_direction
        base_dir = options['base_direction']
        self._resolved_base_dir = None
        for item in self.markup:
            if item == '[b]':
                spush('bold')
                options['bold'] = True
                self.resolve_font_name()
            elif item == '[/b]':
                spop('bold')
                self.resolve_font_name()
            elif item == '[i]':
                spush('italic')
                options['italic'] = True
                self.resolve_font_name()
            elif item == '[/i]':
                spop('italic')
                self.resolve_font_name()
            elif item == '[u]':
                spush('underline')
                options['underline'] = True
                self.resolve_font_name()
            elif item == '[/u]':
                spop('underline')
                self.resolve_font_name()
            elif item == '[s]':
                spush('strikethrough')
                options['strikethrough'] = True
                self.resolve_font_name()
            elif item == '[/s]':
                spop('strikethrough')
                self.resolve_font_name()
            elif item[:6] == '[size=':
                item = item[6:-1]
                try:
                    if item[-2:] in ('px', 'pt', 'in', 'cm', 'mm', 'dp', 'sp'):
                        size = dpi2px(item[:-2], item[-2:])
                    else:
                        size = int(item)
                except ValueError:
                    raise
                    size = options['font_size']
                spush('font_size')
                options['font_size'] = size
            elif item == '[/size]':
                spop('font_size')
            elif item[:7] == '[color=':
                color = parse_color(item[7:-1])
                spush('color')
                options['color'] = color
            elif item == '[/color]':
                spop('color')
            elif item[:6] == '[font=':
                fontname = item[6:-1]
                spush('font_name')
                options['font_name'] = fontname
                self.resolve_font_name()
            elif item == '[/font]':
                spop('font_name')
                self.resolve_font_name()
            elif item[:13] == '[font_family=':
                spush('font_family')
                options['font_family'] = item[13:-1]
            elif item == '[/font_family]':
                spop('font_family')
            elif item[:14] == '[font_context=':
                fctx = item[14:-1]
                if not fctx or fctx.lower() == 'none':
                    fctx = None
                spush('font_context')
                options['font_context'] = fctx
            elif item == '[/font_context]':
                spop('font_context')
            elif item[:15] == '[font_features=':
                spush('font_features')
                options['font_features'] = item[15:-1]
            elif item == '[/font_features]':
                spop('font_features')
            elif item[:15] == '[text_language=':
                lang = item[15:-1]
                if not lang or lang.lower() == 'none':
                    lang = None
                spush('text_language')
                options['text_language'] = lang
            elif item == '[/text_language]':
                spop('text_language')
            elif item[:5] == '[sub]':
                spush('font_size')
                spush('script')
                options['font_size'] = options['font_size'] * .5
                options['script'] = 'subscript'
            elif item == '[/sub]':
                spop('font_size')
                spop('script')
            elif item[:5] == '[sup]':
                spush('font_size')
                spush('script')
                options['font_size'] = options['font_size'] * .5
                options['script'] = 'superscript'
            elif item == '[/sup]':
                spop('font_size')
                spop('script')
            elif item[:5] == '[ref=':
                ref = item[5:-1]
                spush('_ref')
                options['_ref'] = ref
            elif item == '[/ref]':
                spop('_ref')
            elif not clipped and item[:8] == '[anchor=':
                options['_anchor'] = item[8:-1]
            elif not clipped:
                item = item.replace('&bl;',
                                    '[').replace('&br;',
                                                 ']').replace('&amp;', '&')
                if not base_dir:
                    base_dir = self._resolved_base_dir = find_base_dir(item)
                opts = copy(options)
                extents = self.get_cached_extents()
                opts['space_width'] = extents(' ')[0]
                w, h, clipped = layout_text(item,
                                            lines, (w, h), (uw_temp, uhh),
                                            opts,
                                            extents,
                                            append_down=True,
                                            complete=False)

        if len(lines):  # remove any trailing spaces from the last line
            old_opts = self.options
            self.options = copy(opts)
            w, h, clipped = layout_text('',
                                        lines, (w, h), (uw_temp, uhh),
                                        self.options,
                                        self.get_cached_extents(),
                                        append_down=True,
                                        complete=True)
            self.options = old_opts

        self.is_shortened = False
        if shorten:
            options['_ref'] = None  # no refs for you!
            options['_anchor'] = None
            w, h, lines = self.shorten_post(lines, w, h)
            self._cached_lines = lines
        # when valign is not top, for markup we layout everything (text_size[1]
        # is temporarily set to None) and after layout cut to size if too tall
        elif uh != uhh and h > uh and len(lines) > 1:
            if options['valign'] == 'bottom':
                i = 0
                while i < len(lines) - 1 and h > uh:
                    h -= lines[i].h
                    i += 1
                del lines[:i]
            else:  # middle
                i = 0
                top = int(h / 2. + uh / 2.)  # remove extra top portion
                while i < len(lines) - 1 and h > top:
                    h -= lines[i].h
                    i += 1
                del lines[:i]
                i = len(lines) - 1  # remove remaining bottom portion
                while i and h > uh:
                    h -= lines[i].h
                    i -= 1
                del lines[i + 1:]

        # now justify the text
        if options['halign'] == 'justify' and uw is not None:
            # XXX: update refs to justified pos
            # when justify, each line should've been stripped already
            split = partial(re.split, re.compile('( +)'))
            uww = uw - 2 * xpad
            chr = type(self.text)
            space = chr(' ')
            empty = chr('')

            for i in range(len(lines)):
                line = lines[i]
                words = line.words
                # if there's nothing to justify, we're done
                if (not line.w or int(uww - line.w) <= 0 or not len(words)
                        or line.is_last_line):
                    continue

                done = False
                parts = [
                    None,
                ] * len(words)  # contains words split by space
                idxs = [
                    None,
                ] * len(words)  # indices of the space in parts
                # break each word into spaces and add spaces until it's full
                # do first round of split in case we don't need to split all
                for w in range(len(words)):
                    word = words[w]
                    sw = word.options['space_width']
                    p = parts[w] = split(word.text)
                    idxs[w] = [
                        v for v in range(len(p)) if p[v].startswith(' ')
                    ]
                    # now we have the indices of the spaces in split list
                    for k in idxs[w]:
                        # try to add single space at each space
                        if line.w + sw > uww:
                            done = True
                            break
                        line.w += sw
                        word.lw += sw
                        p[k] += space
                    if done:
                        break

                # there's not a single space in the line?
                if not any(idxs):
                    continue

                # now keep adding spaces to already split words until done
                while not done:
                    for w in range(len(words)):
                        if not idxs[w]:
                            continue
                        word = words[w]
                        sw = word.options['space_width']
                        p = parts[w]
                        for k in idxs[w]:
                            # try to add single space at each space
                            if line.w + sw > uww:
                                done = True
                                break
                            line.w += sw
                            word.lw += sw
                            p[k] += space
                        if done:
                            break

                # if not completely full, push last words to right edge
                diff = int(uww - line.w)
                if diff > 0:
                    # find the last word that had a space
                    for w in range(len(words) - 1, -1, -1):
                        if not idxs[w]:
                            continue
                        break
                    old_opts = self.options
                    self.options = word.options
                    word = words[w]
                    # split that word into left/right and push right till uww
                    l_text = empty.join(parts[w][:idxs[w][-1]])
                    r_text = empty.join(parts[w][idxs[w][-1]:])
                    left = LayoutWord(word.options,
                                      self.get_extents(l_text)[0], word.lh,
                                      l_text)
                    right = LayoutWord(word.options,
                                       self.get_extents(r_text)[0], word.lh,
                                       r_text)
                    left.lw = max(left.lw, word.lw + diff - right.lw)
                    self.options = old_opts

                    # now put words back together with right/left inserted
                    for k in range(len(words)):
                        if idxs[k]:
                            words[k].text = empty.join(parts[k])
                    words[w] = right
                    words.insert(w, left)
                else:
                    for k in range(len(words)):
                        if idxs[k]:
                            words[k].text = empty.join(parts[k])
                line.w = uww
                w = max(w, uww)

        self._internal_size = w, h
        if uw:
            w = uw
        if uh:
            h = uh
        if h > 1 and w < 2:
            w = 2
        if w < 1:
            w = 1
        if h < 1:
            h = 1
        return int(w), int(h)
Example #7
0
    def render(self, real=False):
        w, h = 0, 0
        x, y = 0, 0
        lw, lh = 0, 0
        nl = False
        if real:
            self._render_begin()

        for item in self.markup:
            if item == '[b]':
                self._push_style('bold')
                self.options['bold'] = True
            elif item == '[/b]':
                self._pop_style('bold')
            elif item == '[i]':
                self._push_style('italic')
                self.options['italic'] = True
            elif item == '[/i]':
                self._pop_style('italic')
            elif item.startswith('[size='):
                size = int(item[6:-1])
                self._push_style('font_size')
                self.options['font_size'] = size
            elif item == '[/size]':
                self._pop_style('font_size')
            elif item.startswith('[color='):
                color = parse_color(item[7:-1])
                self._push_style('color')
                self.options['color'] = color
            elif item == '[/color]':
                self._pop_style('color')
            elif item.startswith('[font='):
                fontname = item[6:-1]
                self._push_style('font_name')
                self.options['font_name'] = fontname
            elif item == '[/font]':
                self._pop_style('font_name')
            else:
                args = x, y, w, h, lw, lh, nl
                args = self.render_label(real, item, args)
                x, y, w, h, lw, lh, nl = args

        if not real:
            # was only the first pass
            # return with/height
            w = int(max(w, 1))
            h = int(max(h, 1))
            return w, h

        # get data from provider
        data = self._render_end()
        assert (data)

        # create texture is necessary
        w = self.texture.width
        h = self.texture.height
        if self.texture is None:
            self.texture = kivy.Texture.create(size=self.size)
            self.texture.flip_vertical()
        elif self.width > w or self.height > h:
            self.texture = kivy.Texture.create(size=self.size)
            self.texture.flip_vertical()
        else:
            self.texture = self.texture.get_region(0, 0, self.width,
                                                   self.height)

        # update texture
        self.texture.blit_data(data)
Example #8
0
    def _pre_render(self):
        # split markup, words, and lines
        # result: list of word with position and width/height
        # during the first pass, we don't care about h/valign
        self._cached_lines = lines = []
        self._refs = {}
        self._anchors = {}
        clipped = False
        w = h = 0
        uw, uh = self.text_size
        spush = self._push_style
        spop = self._pop_style
        opts = options = self.options
        options["_ref"] = None
        options["_anchor"] = None
        options["script"] = "normal"
        shorten = options["shorten"]
        # if shorten, then don't split lines to fit uw, because it will be
        # flattened later when shortening and broken up lines if broken
        # mid-word will have space mid-word when lines are joined
        uw_temp = None if shorten else uw
        xpad = options["padding_x"]
        uhh = None if uh is not None and options["valign"][-1] != "p" or options["shorten"] else uh
        options["strip"] = options["strip"] or options["halign"][-1] == "y"
        for item in self.markup:
            if item == "[b]":
                spush("bold")
                options["bold"] = True
                self.resolve_font_name()
            elif item == "[/b]":
                spop("bold")
                self.resolve_font_name()
            elif item == "[i]":
                spush("italic")
                options["italic"] = True
                self.resolve_font_name()
            elif item == "[/i]":
                spop("italic")
                self.resolve_font_name()
            elif item[:6] == "[size=":
                item = item[6:-1]
                try:
                    if item[-2:] in ("px", "pt", "in", "cm", "mm", "dp", "sp"):
                        size = dpi2px(item[:-2], item[-2:])
                    else:
                        size = int(item)
                except ValueError:
                    raise
                    size = options["font_size"]
                spush("font_size")
                options["font_size"] = size
            elif item == "[/size]":
                spop("font_size")
            elif item[:7] == "[color=":
                color = parse_color(item[7:-1])
                spush("color")
                options["color"] = color
            elif item == "[/color]":
                spop("color")
            elif item[:6] == "[font=":
                fontname = item[6:-1]
                spush("font_name")
                options["font_name"] = fontname
                self.resolve_font_name()
            elif item == "[/font]":
                spop("font_name")
                self.resolve_font_name()
            elif item[:5] == "[sub]":
                spush("font_size")
                spush("script")
                options["font_size"] = options["font_size"] * 0.5
                options["script"] = "subscript"
            elif item == "[/sub]":
                spop("font_size")
                spop("script")
            elif item[:5] == "[sup]":
                spush("font_size")
                spush("script")
                options["font_size"] = options["font_size"] * 0.5
                options["script"] = "superscript"
            elif item == "[/sup]":
                spop("font_size")
                spop("script")
            elif item[:5] == "[ref=":
                ref = item[5:-1]
                spush("_ref")
                options["_ref"] = ref
            elif item == "[/ref]":
                spop("_ref")
            elif not clipped and item[:8] == "[anchor=":
                options["_anchor"] = item[8:-1]
            elif not clipped:
                item = item.replace("&bl;", "[").replace("&br;", "]").replace("&amp;", "&")
                opts = copy(options)
                extents = self.get_cached_extents()
                opts["space_width"] = extents(" ")[0]
                w, h, clipped = layout_text(item, lines, (w, h), (uw_temp, uhh), opts, extents, True, False)

        if len(lines):  # remove any trailing spaces from the last line
            old_opts = self.options
            self.options = copy(opts)
            w, h, clipped = layout_text(
                "", lines, (w, h), (uw_temp, uhh), self.options, self.get_cached_extents(), True, True
            )
            self.options = old_opts

        if shorten:
            options["_ref"] = None  # no refs for you!
            options["_anchor"] = None
            w, h, lines = self.shorten_post(lines, w, h)
            self._cached_lines = lines
        # when valign is not top, for markup we layout everything (text_size[1]
        # is temporarily set to None) and after layout cut to size if too tall
        elif uh != uhh and h > uh and len(lines) > 1:
            if options["valign"][-1] == "m":  # bottom
                i = 0
                while i < len(lines) - 1 and h > uh:
                    h -= lines[i].h
                    i += 1
                del lines[:i]
            else:  # middle
                i = 0
                top = int(h / 2.0 + uh / 2.0)  # remove extra top portion
                while i < len(lines) - 1 and h > top:
                    h -= lines[i].h
                    i += 1
                del lines[:i]
                i = len(lines) - 1  # remove remaining bottom portion
                while i and h > uh:
                    h -= lines[i].h
                    i -= 1
                del lines[i + 1 :]

        # now justify the text
        if options["halign"][-1] == "y" and uw is not None:
            # XXX: update refs to justified pos
            # when justify, each line shouldv'e been stripped already
            split = partial(re.split, re.compile("( +)"))
            uww = uw - 2 * xpad
            chr = type(self.text)
            space = chr(" ")
            empty = chr("")

            for i in range(len(lines)):
                line = lines[i]
                words = line.words
                # if there's nothing to justify, we're done
                if not line.w or int(uww - line.w) <= 0 or not len(words) or line.is_last_line:
                    continue

                done = False
                parts = [None] * len(words)  # contains words split by space
                idxs = [None] * len(words)  # indices of the space in parts
                # break each word into spaces and add spaces until it's full
                # do first round of split in case we don't need to split all
                for w in range(len(words)):
                    word = words[w]
                    sw = word.options["space_width"]
                    p = parts[w] = split(word.text)
                    idxs[w] = [v for v in range(len(p)) if p[v].startswith(" ")]
                    # now we have the indices of the spaces in split list
                    for k in idxs[w]:
                        # try to add single space at each space
                        if line.w + sw > uww:
                            done = True
                            break
                        line.w += sw
                        word.lw += sw
                        p[k] += space
                    if done:
                        break

                # there's not a single space in the line?
                if not any(idxs):
                    continue

                # now keep adding spaces to already split words until done
                while not done:
                    for w in range(len(words)):
                        if not idxs[w]:
                            continue
                        word = words[w]
                        sw = word.options["space_width"]
                        p = parts[w]
                        for k in idxs[w]:
                            # try to add single space at each space
                            if line.w + sw > uww:
                                done = True
                                break
                            line.w += sw
                            word.lw += sw
                            p[k] += space
                        if done:
                            break

                # if not completely full, push last words to right edge
                diff = int(uww - line.w)
                if diff > 0:
                    # find the last word that had a space
                    for w in range(len(words) - 1, -1, -1):
                        if not idxs[w]:
                            continue
                        break
                    old_opts = self.options
                    self.options = word.options
                    word = words[w]
                    # split that word into left/right and push right till uww
                    l_text = empty.join(parts[w][: idxs[w][-1]])
                    r_text = empty.join(parts[w][idxs[w][-1] :])
                    left = LayoutWord(word.options, self.get_extents(l_text)[0], word.lh, l_text)
                    right = LayoutWord(word.options, self.get_extents(r_text)[0], word.lh, r_text)
                    left.lw = max(left.lw, word.lw + diff - right.lw)
                    self.options = old_opts

                    # now put words back together with right/left inserted
                    for k in range(len(words)):
                        if idxs[k]:
                            words[k].text = empty.join(parts[k])
                    words[w] = right
                    words.insert(w, left)
                else:
                    for k in range(len(words)):
                        if idxs[k]:
                            words[k].text = empty.join(parts[k])
                line.w = uww
                w = max(w, uww)

        self._internal_size = w, h
        if uw:
            w = uw
        if uh:
            h = uh
        if h > 1 and w < 2:
            w = 2
        if w < 1:
            w = 1
        if h < 1:
            h = 1
        return int(w), int(h)
Example #9
0
    def _pre_render(self):
        # split markup, words, and lines
        # result: list of word with position and width/height
        # during the first pass, we don't care about h/valign
        self._lines = lines = []
        self._refs = {}
        self._anchors = {}
        spush = self._push_style
        spop = self._pop_style
        options = self.options
        options['_ref'] = None
        options['script'] = 'normal'
        for item in self.markup:
            if item == '[b]':
                spush('bold')
                options['bold'] = True
                self.resolve_font_name()
            elif item == '[/b]':
                spop('bold')
                self.resolve_font_name()
            elif item == '[i]':
                spush('italic')
                options['italic'] = True
                self.resolve_font_name()
            elif item == '[/i]':
                spop('italic')
                self.resolve_font_name()
            elif item[:6] == '[size=':
                item = item[6:-1]
                try:
                    if item[-2:] in ('px', 'pt', 'in', 'cm', 'mm', 'dp', 'sp'):
                        size = dpi2px(item[:-2], item[-2:])
                    else:
                        size = int(item)
                except ValueError:
                    raise
                    size = options['font_size']
                spush('font_size')
                options['font_size'] = size
            elif item == '[/size]':
                spop('font_size')
            elif item[:7] == '[color=':
                color = parse_color(item[7:-1])
                spush('color')
                options['color'] = color
            elif item == '[/color]':
                spop('color')
            elif item[:6] == '[font=':
                fontname = item[6:-1]
                spush('font_name')
                options['font_name'] = fontname
                self.resolve_font_name()
            elif item == '[/font]':
                spop('font_name')
                self.resolve_font_name()
            elif item[:5] == '[sub]':
                spush('font_size')
                spush('script')
                options['font_size'] = options['font_size'] * .5
                options['script'] = 'subscript'
            elif item == '[/sub]':
                spop('font_size')
                spop('script')
            elif item[:5] == '[sup]':
                spush('font_size')
                spush('script')
                options['font_size'] = options['font_size'] * .5
                options['script'] = 'superscript'
            elif item == '[/sup]':
                spop('font_size')
                spop('script')
            elif item[:5] == '[ref=':
                ref = item[5:-1]
                spush('_ref')
                options['_ref'] = ref
            elif item == '[/ref]':
                spop('_ref')
            elif item[:8] == '[anchor=':
                ref = item[8:-1]
                if len(lines):
                    x, y = lines[-1][0:2]
                else:
                    x = y = 0
                self._anchors[ref] = x, y
            else:
                item = item.replace('&bl;',
                                    '[').replace('&br;',
                                                 ']').replace('&amp;', '&')
                self._pre_render_label(item, options, lines)

        # calculate the texture size
        w, h = self.text_size
        if h is None or h < 0:
            h = None
        if w is None or w < 0:
            w = None
        if w is None:
            if not lines:
                w = 1
            else:
                w = max([line[0] for line in lines])
        if h is None:
            if not lines:
                h = 1
            else:
                h = sum([line[1] for line in lines])
        return int(ceil(w)), int(ceil(h))
Example #10
0
    def _pre_render(self):
        # split markup, words, and lines
        # result: list of word with position and width/height
        # during the first pass, we don't care about h/valign
        self._cached_lines = lines = []
        self._refs = {}
        self._anchors = {}
        clipped = False
        w = h = 0
        uw, uh = self.text_size
        spush = self._push_style
        spop = self._pop_style
        opts = options = self.options
        options['_ref'] = None
        options['script'] = 'normal'
        shorten = options['shorten']
        # if shorten, then don't split lines to fit uw, because it will be
        # flattened later when shortening and broken up lines if broken
        # mid-word will have space mid-word when lines are joined
        uw_temp = None if shorten else uw
        xpad = options['padding_x']
        uhh = (None if uh is not None and options['valign'][-1] != 'p' or
               options['shorten'] else uh)
        options['strip'] = options['strip'] or options['halign'][-1] == 'y'
        for item in self.markup:
            if item == '[b]':
                spush('bold')
                options['bold'] = True
                self.resolve_font_name()
            elif item == '[/b]':
                spop('bold')
                self.resolve_font_name()
            elif item == '[i]':
                spush('italic')
                options['italic'] = True
                self.resolve_font_name()
            elif item == '[/i]':
                spop('italic')
                self.resolve_font_name()
            elif item[:6] == '[size=':
                item = item[6:-1]
                try:
                    if item[-2:] in ('px', 'pt', 'in', 'cm', 'mm', 'dp', 'sp'):
                        size = dpi2px(item[:-2], item[-2:])
                    else:
                        size = int(item)
                except ValueError:
                    raise
                    size = options['font_size']
                spush('font_size')
                options['font_size'] = size
            elif item == '[/size]':
                spop('font_size')
            elif item[:7] == '[color=':
                color = parse_color(item[7:-1])
                spush('color')
                options['color'] = color
            elif item == '[/color]':
                spop('color')
            elif item[:6] == '[font=':
                fontname = item[6:-1]
                spush('font_name')
                options['font_name'] = fontname
                self.resolve_font_name()
            elif item == '[/font]':
                spop('font_name')
                self.resolve_font_name()
            elif item[:5] == '[sub]':
                spush('font_size')
                spush('script')
                options['font_size'] = options['font_size'] * .5
                options['script'] = 'subscript'
            elif item == '[/sub]':
                spop('font_size')
                spop('script')
            elif item[:5] == '[sup]':
                spush('font_size')
                spush('script')
                options['font_size'] = options['font_size'] * .5
                options['script'] = 'superscript'
            elif item == '[/sup]':
                spop('font_size')
                spop('script')
            elif item[:5] == '[ref=':
                ref = item[5:-1]
                spush('_ref')
                options['_ref'] = ref
            elif item == '[/ref]':
                spop('_ref')
            elif not clipped and item[:8] == '[anchor=':
                ref = item[8:-1]
                if len(lines):
                    x, y = lines[-1].x, lines[-1].y
                else:
                    x = y = 0
                self._anchors[ref] = x, y
            elif not clipped:
                item = item.replace('&bl;', '[').replace(
                    '&br;', ']').replace('&amp;', '&')
                opts = copy(options)
                extents = self.get_cached_extents()
                opts['space_width'] = extents(' ')[0]
                w, h, clipped = layout_text(item, lines, (w, h),
                    (uw_temp, uhh), opts, extents, True, False)

        if len(lines):  # remove any trailing spaces from the last line
            old_opts = self.options
            self.options = copy(opts)
            w, h, clipped = layout_text('', lines, (w, h), (uw_temp, uhh),
                self.options, self.get_cached_extents(), True, True)
            self.options = old_opts

        if shorten:
            options['_ref'] = None  # no refs for you!
            w, h, lines = self.shorten_post(lines, w, h)
            self._cached_lines = lines
        # when valign is not top, for markup we layout everything (text_size[1]
        # is temporarily set to None) and after layout cut to size if too tall
        elif uh != uhh and h > uh and len(lines) > 1:
            if options['valign'][-1] == 'm':  # bottom
                i = 0
                while i < len(lines) - 1 and h > uh:
                    h -= lines[i].h
                    i += 1
                del lines[:i]
            else:  # middle
                i = 0
                top = int(h / 2. + uh / 2.)  # remove extra top portion
                while i < len(lines) - 1 and h > top:
                    h -= lines[i].h
                    i += 1
                del lines[:i]
                i = len(lines) - 1  # remove remaining bottom portion
                while i and h > uh:
                    h -= lines[i].h
                    i -= 1
                del lines[i + 1:]

        # now justify the text
        if options['halign'][-1] == 'y' and uw is not None:
            # XXX: update refs to justified pos
            # when justify, each line shouldv'e been stripped already
            split = partial(re.split, re.compile('( +)'))
            uww = uw - 2 * xpad
            chr = type(self.text)
            space = chr(' ')
            empty = chr('')

            for i in range(len(lines)):
                line = lines[i]
                words = line.words
                # if there's nothing to justify, we're done
                if (not line.w or int(uww - line.w) <= 0 or not len(words) or
                    line.is_last_line):
                    continue

                done = False
                parts = [None, ] * len(words)  # contains words split by space
                idxs = [None, ] * len(words)  # indices of the space in parts
                # break each word into spaces and add spaces until it's full
                # do first round of split in case we don't need to split all
                for w in range(len(words)):
                    word = words[w]
                    sw = word.options['space_width']
                    p = parts[w] = split(word.text)
                    idxs[w] = [v for v in range(len(p)) if
                               p[v].startswith(' ')]
                    # now we have the indices of the spaces in split list
                    for k in idxs[w]:
                        # try to add single space at each space
                        if line.w + sw > uww:
                            done = True
                            break
                        line.w += sw
                        word.lw += sw
                        p[k] += space
                    if done:
                        break

                # there's not a single space in the line?
                if not any(idxs):
                    continue

                # now keep adding spaces to already split words until done
                while not done:
                    for w in range(len(words)):
                        if not idxs[w]:
                            continue
                        word = words[w]
                        sw = word.options['space_width']
                        p = parts[w]
                        for k in idxs[w]:
                            # try to add single space at each space
                            if line.w + sw > uww:
                                done = True
                                break
                            line.w += sw
                            word.lw += sw
                            p[k] += space
                        if done:
                            break

                # if not completely full, push last words to right edge
                diff = int(uww - line.w)
                if diff > 0:
                    # find the last word that had a space
                    for w in range(len(words) - 1, -1, -1):
                        if not idxs[w]:
                            continue
                        break
                    old_opts = self.options
                    self.options = word.options
                    word = words[w]
                    # split that word into left/right and push right till uww
                    l_text = empty.join(parts[w][:idxs[w][-1]])
                    r_text = empty.join(parts[w][idxs[w][-1]:])
                    left = LayoutWord(word.options,
                        self.get_extents(l_text)[0], word.lh, l_text)
                    right = LayoutWord(word.options,
                        self.get_extents(r_text)[0], word.lh, r_text)
                    left.lw = max(left.lw, word.lw + diff - right.lw)
                    self.options = old_opts

                    # now put words back together with right/left inserted
                    for k in range(len(words)):
                        if idxs[k]:
                            words[k].text = empty.join(parts[k])
                    words[w] = right
                    words.insert(w, left)
                else:
                    for k in range(len(words)):
                        if idxs[k]:
                            words[k].text = empty.join(parts[k])
                line.w = uww
                w = max(w, uww)

        self._internal_size = w, h
        if uw:
            w = uw
        if uh:
            h = uh
        if h > 1 and w < 2:
            w = 2
        if w < 1:
            w = 1
        if h < 1:
            h = 1
        return w, h
Example #11
0
class Board(Widget):

    nrows = NumericProperty(16)
    ncols = NumericProperty(16)
    tsize = NumericProperty(0)
    hmargin = NumericProperty(dp(10))
    wmargin = NumericProperty(dp(10))
    tx = NumericProperty(0)
    ty = NumericProperty(0)
    tmargin = NumericProperty(dp(1))
    colors = ListProperty([parse_color(c) for c in COLORS])

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.matrix = None
        self.player = None
        self.totalCoins = 0
        self.nbCoins = 0
        self.display()
        self.getLevel()
        self.findPlayer()

    def display(self):
        level = self.getLevel()
        if self.matrix:
            for r in self.matrix:
                for t in r:
                    self.remove_widget(t)
        self.matrix = [[
            Tile(i, j, self, level[i][j]) for j in range(self.ncols)
        ] for i in range(self.nrows)]

    def findPlayer(self):
        if self.matrix:
            for r in self.matrix:
                for t in r:
                    if isinstance(t.prefab, Player):
                        self.player = t
                        return

    def getLevel(self):
        level = open('labyrinth/levels/level4.txt', 'r')
        matrixPrefabs = [[None for j in range(self.ncols)]
                         for i in range(self.nrows)]
        j = 0
        for x in level:
            i = 0
            for y in x:
                if i <= 15:
                    matrixPrefabs[j][i] = self.getRealPrefab(y)
                i += 1
            j += 1
        return matrixPrefabs

    def getRealPrefab(self, char):
        if char == "w":
            return Wall()
        if char == "f":
            return Finish()
        if char == "e":
            return Empty()
        if char == "c":
            self.totalCoins += 1
            return Coin()
        if char == "p":
            return Player()
        if char == "s":
            return Floor()

    #Event click on move button
    #Action = "up","down","left","right"
    def movePlayer(self, action):
        iPlayer = self.player.row
        jPlayer = self.player.col
        actionDone = False
        if action == "up":
            if not (isinstance(self.matrix[iPlayer + 1][jPlayer].prefab, Wall)
                    or isinstance(self.matrix[iPlayer + 1][jPlayer].prefab,
                                  Empty)):
                self.player.row = iPlayer + 1
                self.checkCoin()
                self.matrix[self.player.row][jPlayer] = self.player
                actionDone = True
        if action == "down":
            if not (isinstance(self.matrix[iPlayer - 1][jPlayer].prefab, Wall)
                    or isinstance(self.matrix[iPlayer - 1][jPlayer].prefab,
                                  Empty)):
                self.player.row = iPlayer - 1
                self.checkCoin()
                self.matrix[self.player.row][jPlayer] = self.player
                actionDone = True
        if action == "left":
            if not (isinstance(self.matrix[iPlayer][jPlayer - 1].prefab, Wall)
                    or isinstance(self.matrix[iPlayer][jPlayer - 1].prefab,
                                  Empty)):
                self.player.col = jPlayer - 1
                self.checkCoin()
                self.matrix[iPlayer][self.player.col] = self.player
                actionDone = True
        if action == "right":
            if not (isinstance(self.matrix[iPlayer][jPlayer + 1].prefab, Wall)
                    or isinstance(self.matrix[iPlayer][jPlayer + 1].prefab,
                                  Empty)):
                self.player.col = jPlayer + 1
                self.checkCoin()
                self.matrix[iPlayer][self.player.col] = self.player
                actionDone = True
        if actionDone:
            tmpTile = Tile(iPlayer, jPlayer, self, Empty())
            self.matrix[iPlayer][jPlayer] = tmpTile

    def checkCoin(self):
        if isinstance(self.matrix[self.player.row][self.player.col].prefab,
                      Coin):
            self.nbCoins += 1
            print(self.nbCoins)
        if self.nbCoins * 2 >= self.totalCoins:
            if isinstance(self.matrix[self.player.row][self.player.col].prefab,
                          Finish):
                print("gg")
Example #12
0
    def _pre_render(self):
        # split markup, words, and lines
        # result: list of word with position and width/height
        # during the first pass, we don't care about h/valign
        self._lines = lines = []
        self._refs = {}
        self._anchors = {}
        spush = self._push_style
        spop = self._pop_style
        options = self.options
        options["_ref"] = None
        options["script"] = "normal"
        for item in self.markup:
            if item == "[b]":
                spush("bold")
                options["bold"] = True
                self.resolve_font_name()
            elif item == "[/b]":
                spop("bold")
                self.resolve_font_name()
            elif item == "[i]":
                spush("italic")
                options["italic"] = True
                self.resolve_font_name()
            elif item == "[/i]":
                spop("italic")
                self.resolve_font_name()
            elif item[:6] == "[size=":
                item = item[6:-1]
                try:
                    if item[-2:] in ("px", "pt", "in", "cm", "mm", "dp", "sp"):
                        size = dpi2px(item[:-2], item[-2:])
                    else:
                        size = int(item)
                except ValueError:
                    raise
                    size = options["font_size"]
                spush("font_size")
                options["font_size"] = size
            elif item == "[/size]":
                spop("font_size")
            elif item[:7] == "[color=":
                color = parse_color(item[7:-1])
                spush("color")
                options["color"] = color
            elif item == "[/color]":
                spop("color")
            elif item[:6] == "[font=":
                fontname = item[6:-1]
                spush("font_name")
                options["font_name"] = fontname
                self.resolve_font_name()
            elif item == "[/font]":
                spop("font_name")
                self.resolve_font_name()
            elif item[:5] == "[sub]":
                spush("font_size")
                spush("script")
                options["font_size"] = options["font_size"] * 0.5
                options["script"] = "subscript"
            elif item == "[/sub]":
                spop("font_size")
                spop("script")
            elif item[:5] == "[sup]":
                spush("font_size")
                spush("script")
                options["font_size"] = options["font_size"] * 0.5
                options["script"] = "superscript"
            elif item == "[/sup]":
                spop("font_size")
                spop("script")
            elif item[:5] == "[ref=":
                ref = item[5:-1]
                spush("_ref")
                options["_ref"] = ref
            elif item == "[/ref]":
                spop("_ref")
            elif item[:8] == "[anchor=":
                ref = item[8:-1]
                if len(lines):
                    x, y = lines[-1][0:2]
                else:
                    x = y = 0
                self._anchors[ref] = x, y
            else:
                item = item.replace("&bl;", "[").replace("&br;", "]").replace("&amp;", "&")
                self._pre_render_label(item, options, lines)

        # calculate the texture size
        w, h = self.text_size
        if h < 0:
            h = None
        if w < 0:
            w = None
        if w is None:
            if not lines:
                w = 1
            else:
                w = max([line[0] for line in lines])
        if h is None:
            if not lines:
                h = 1
            else:
                h = sum([line[1] for line in lines])
        return w, h