Пример #1
0
    def format_colors(self, color_list, label, palette_type, delete=None):
        """Format colors under palette."""

        colors = ['\n## %s\n' % label]
        count = 0
        for f in color_list:
            if count != 0 and (count % 8 == 0):
                colors.append('\n\n')
            elif count != 0:
                if sublime.platform() == 'windows':
                    colors.append('  ')
                else:
                    colors.append(' ')
            if delete:
                colors.append(
                    '[%s](__delete_color__:%s:%s:%s)' % (
                        mdpopups.color_box([f], '#cccccc', '#333333', height=32, width=32, border_size=2),
                        f, palette_type, label,
                    )
                )
            else:
                colors.append(
                    '[%s](%s)' % (
                        mdpopups.color_box([f], '#cccccc', '#333333', height=32, width=32, border_size=2), f
                    )
                )
            count += 1
        return ''.join(colors)
Пример #2
0
    def get_color_map_hex(self):
        """Get color wheel."""

        global color_map
        global color_map_size
        global color_map_style
        global line_height

        if (color_map is None or self.graphic_size != color_map_size
                or self.line_height != line_height
                or color_map_style != "hex"):
            color_map_size = self.graphic_size
            line_height = self.line_height
            color_map_style = "hex"
            padding = (self.width * 9)
            decrement = True
            html_colors = []
            count = 0
            check_size = self.check_size(self.height)

            for row in color_map_data:
                html_colors.append('<span class="%scolor-map-row">' %
                                   util.LEGACY_CLASS)
                if padding:
                    pad = mdpopups.color_box([SPACER],
                                             border_size=0,
                                             height=self.height,
                                             width=padding,
                                             check_size=check_size,
                                             alpha=True)
                    html_colors.append(pad)
                for color in row:
                    if len(self.color) == 3:
                        color = '#' + ''.join([c * 2 for c in color]) + 'ff'
                    else:
                        color = '#' + color + 'ff'
                    html_colors.append(
                        '<a href="%s">%s</a>' %
                        (color,
                         mdpopups.color_box([color],
                                            OUTER_BORDER,
                                            INNER_BORDER,
                                            border_size=2,
                                            height=self.height,
                                            width=self.width,
                                            check_size=check_size)))
                html_colors.append('</span><br>')
                if count == 6:
                    decrement = False
                if decrement:
                    padding -= int(self.width / 2)
                else:
                    padding += int(self.width / 2)
                count += 1
            html_colors.append('\n\n')
            color_map = ''.join(html_colors)
        self.template_vars['color_picker'] = color_map
Пример #3
0
    def get_color_map_hex(self, text):
        """Get color wheel."""

        global color_map
        global color_map_size
        global color_map_style
        global line_height

        if (
            color_map is None or
            self.graphic_size != color_map_size or
            self.line_height != line_height or
            color_map_style != "hex"
        ):
            color_map_size = self.graphic_size
            line_height = self.line_height
            color_map_style = "hex"
            padding = (self.width * 9)
            decrement = True
            html_colors = []
            count = 0
            check_size = self.check_size(self.height)

            for row in color_map_data:
                html_colors.append('<span class="color-helper color-map-row">')
                if padding:
                    pad = mdpopups.color_box(
                        [SPACER], border_size=0,
                        height=self.height, width=padding, check_size=check_size, alpha=True
                    )
                    html_colors.append(pad)
                for color in row:
                    if len(self.color) == 3:
                        color = '#' + ''.join([c * 2 for c in color]) + 'ff'
                    else:
                        color = '#' + color + 'ff'
                    html_colors.append(
                        '<a href="%s">%s</a>' % (
                            color, mdpopups.color_box(
                                [color], OUTER_BORDER, INNER_BORDER,
                                border_size=2, height=self.height, width=self.width,
                                check_size=check_size
                            )
                        )
                    )
                html_colors.append('</span><br>')
                if count == 6:
                    decrement = False
                if decrement:
                    padding -= int(self.width / 2)
                else:
                    padding += int(self.width / 2)
                count += 1
            html_colors.append('\n\n')
            color_map = ''.join(html_colors)
        text.append(color_map)
Пример #4
0
    def get_channel(self, channel, label, minimum, maximum, color_filter):
        """Get color channel."""

        rgba1 = util.RGBA(self.color)
        rgba2 = util.RGBA(self.color)
        html = []
        html.append('<span class="%schannel"><a href="hirespick:%s">%s:</a>' %
                    (util.LEGACY_CLASS, color_filter, label))
        temp = []
        count = 12
        check_size = self.check_size(self.height)
        while count:
            getattr(rgba1, color_filter)(minimum)
            kwargs = {
                "border_size": 2,
                "height": self.height,
                "width": self.width,
                "check_size": check_size
            }
            temp.append(
                '[%s](%s)' %
                (mdpopups.color_box([rgba1.get_rgba()], OUTER_BORDER,
                                    INNER_BORDER, **kwargs), rgba1.get_rgba()))
            count -= 1
        html += reversed(temp)
        html.append('[%s](%s)' %
                    (mdpopups.color_box([self.color],
                                        OUTER_BORDER,
                                        INNER_BORDER,
                                        border_size=2,
                                        height=self.height_big,
                                        width=self.width,
                                        check_size=check_size), self.color))
        count = 12
        while count:
            getattr(rgba2, color_filter)(maximum)
            kwargs = {
                "border_size": 2,
                "height": self.height,
                "width": self.width,
                "check_size": check_size
            }
            html.append(
                '[%s](%s)' %
                (mdpopups.color_box([rgba2.get_rgba()], OUTER_BORDER,
                                    INNER_BORDER, **kwargs), rgba2.get_rgba()))
            count -= 1
        html.append('</span><br>')
        self.template_vars[channel] = ''.join(html)
    def get_current_color(self, text):
        """Get current color."""

        text.append(
            '<span class="color-helper current-color">%s</span>\n\n' % (
                mdpopups.color_box(
                    [SPACER], border_size=0,
                    height=self.height, width=(self.width * (6 if self.hex_map else 5)), check_size=2, alpha=True
                ) +
                mdpopups.color_box(
                    [self.color], OUTER_BORDER, INNER_BORDER,
                    border_size=2, height=self.height, width=self.width * (13 if self.hex_map else 16), check_size=2
                )
            )
        )
Пример #6
0
    def get_color_box(self, color, key, index):
        """Display an HTML color box using the given color."""

        border = '#CCCCCC'
        border2 = '#333333'
        padding = int(self.view.settings().get('line_padding_top', 0))
        padding += int(self.view.settings().get('line_padding_bottom', 0))
        box_height = int(self.view.line_height()) - padding - 2
        check_size = int((box_height - 4) / 4)
        if isinstance(color, list):
            box_width = box_height * (len(color) if len(color) >= 1 else 1)
            colors = [c.upper() for c in color]
        else:
            box_width = box_height
            colors = [color.upper()]
        if check_size < 2:
            check_size = 2
        self.template_vars['%s_preview' % key] = mdpopups.color_box(
            colors,
            border,
            border2,
            height=box_height,
            width=box_width,
            border_size=2,
            check_size=check_size)
        self.template_vars['%s_color' % key] = ', '.join(colors)
        self.template_vars['%s_index' % key] = index
Пример #7
0
    def format_palettes(self,
                        color_list,
                        label,
                        palette_type,
                        caption=None,
                        color=None,
                        delete=False):
        """Format color palette previews."""

        colors = ['\n## {}\n'.format(label)]
        if caption:
            colors.append('{}\n'.format(caption))
        if delete:
            label = '__delete__palette__:{}:{}'.format(palette_type, label)
        elif color:
            label = '__add_palette_color__:{}:{}:{}'.format(
                color, palette_type, label)
        else:
            label = '__colors__:{}:{}'.format(palette_type, label)

        color_box = []
        for color in color_list[:5]:
            c = Color(color)
            preview = self.get_preview(c)
            color_box.append(preview.preview2)

        colors.append('[{}]({})'.format(
            mdpopups.color_box(color_box,
                               self.default_border,
                               height=self.height * PALETTE_SCALE_Y,
                               width=self.palette_w * PALETTE_SCALE_X,
                               border_size=BORDER_SIZE,
                               check_size=self.check_size(
                                   self.height * PALETTE_SCALE_Y)), label))
        return ''.join(colors)
Пример #8
0
    def format_colors(self, color_list, label, palette_type, delete=None):
        """Format colors under palette."""

        colors = ['\n## {} {{.center}}\n'.format(label)]
        count = 0

        height = self.height * 2
        width = self.width * 2
        check_size = self.check_size(height)
        for f in color_list:
            color = Color(f)
            if count != 0 and (count % 8 == 0):
                colors.append('\n\n')
            elif count != 0:
                if sublime.platform() == 'windows':
                    colors.append('&nbsp; ')
                else:
                    colors.append('&nbsp;')

            preview = self.get_preview(color)
            message = color.to_string(**util.DEFAULT)
            if preview.message:
                message += ' ({})'.format(preview.message)

            if delete:
                colors.append(
                    '[{}](__delete_color__:{}:{}:{} "{}")'.format(
                        mdpopups.color_box(
                            [preview.preview1, preview.preview2],
                            preview.border, height=height, width=width, border_size=BORDER_SIZE,
                            check_size=check_size
                        ),
                        f, palette_type, label, message
                    )
                )
            else:
                colors.append(
                    '[{}](__insert__:{}:{}:{} "{}")'.format(
                        mdpopups.color_box(
                            [preview.preview1, preview.preview2],
                            preview.border, height=height, width=width, border_size=BORDER_SIZE,
                            check_size=check_size
                        ), f, palette_type, label, message
                    )
                )
            count += 1
        return ''.join(colors)
Пример #9
0
    def get_channel(self, text, label, minimum, maximum, color_filter):
        """Get color channel."""

        rgba1 = util.RGBA(self.color)
        rgba2 = util.RGBA(self.color)
        text.append('<span class="color-helper channel"><a href="hirespick:%s">%s:</a>' % (color_filter, label))
        temp = []
        count = 12
        check_size = self.check_size(self.height)
        while count:
            getattr(rgba1, color_filter)(minimum)
            kwargs = {"border_size": 2, "height": self.height, "width": self.width, "check_size": check_size}
            temp.append(
                '[%s](%s)' % (
                    mdpopups.color_box(
                        [rgba1.get_rgba()], OUTER_BORDER, INNER_BORDER,
                        **kwargs
                    ),
                    rgba1.get_rgba()
                )
            )
            count -= 1
        text += reversed(temp)
        text.append(
            '[%s](%s)' % (
                mdpopups.color_box(
                    [self.color], OUTER_BORDER, INNER_BORDER,
                    border_size=2, height=self.height_big, width=self.width, check_size=check_size
                ),
                self.color
            )
        )
        count = 12
        while count:
            getattr(rgba2, color_filter)(maximum)
            kwargs = {"border_size": 2, "height": self.height, "width": self.width, "check_size": check_size}
            text.append(
                '[%s](%s)' % (
                    mdpopups.color_box(
                        [rgba2.get_rgba()], OUTER_BORDER, INNER_BORDER,
                        **kwargs
                    ),
                    rgba2.get_rgba()
                )
            )
            count -= 1
        text.append('</span>\n\n')
Пример #10
0
    def get_spacer(self, width=1, height=1):
        """Get a spacer."""

        return mdpopups.color_box(
            [SPACER], border_size=0,
            height=self.height * height, width=self.width * width,
            check_size=self.check_size(self.height), alpha=True
        )
Пример #11
0
    def get_hires_color_channel(self, color_filter):
        """Get get a list of all colors within range."""

        ranges = {
            "red": (0, 255),
            "green": (0, 255),
            "blue": (0, 255),
            "alpha": (0, 100),
            "hue": (0, 360),
            "saturation": (0, 100),
            "lightness": (0, 100),
            "whiteness": (0, 100),
            "blackness": (0, 100)
        }

        minimum, maximum = ranges[color_filter]
        check_size = self.check_size(self.height)
        html = []
        color = self.color.clone()
        for x in range(minimum, maximum + 1):
            if color_filter == 'red':
                color.red = x / 255.0
                label = str(x)
            elif color_filter == 'green':
                color.green = x / 255.0
                label = str(x)
            elif color_filter == 'blue':
                color.blue = x / 255.0
                label = str(x)
            elif color_filter == 'alpha':
                color.alpha = x / 100.0
                label = "{:d}%".format(x)
            elif color_filter == 'hue':
                color.hue = x
                label = "{:d}deg".format(x)
            elif color_filter == 'saturation':
                color.saturation = x
                label = "{:d}%".format(x)
            elif color_filter == 'lightness':
                color.lightness = x
                label = "{:d}%".format(x)
            elif color_filter == "whiteness":
                color.whiteness = x
                label = "{:d}%".format(x)
            elif color_filter == "blackness":
                color.blackness = x
                label = "{:d}%".format(x)

            html.append('[{}]({}) {}<br>'.format(
                mdpopups.color_box([color.convert("srgb").to_string(**HEX)],
                                   self.default_border,
                                   border_size=BORDER_SIZE,
                                   height=self.height,
                                   width=self.height * 8,
                                   check_size=check_size),
                color.to_string(**COLOR_FULL_PREC), label))
        self.template_vars['channel_hires'] = ''.join(html)
Пример #12
0
    def format_info(self, obj, template_vars):
        """Format the selected color info."""

        s = sublime.load_settings('ColorHelper.sublime-settings')

        color = obj.color
        current = self.view.substr(sublime.Region(obj.start, obj.end))

        # Store color in normal and generic format.
        template_vars['current_color'] = "`#!color-helper {}`".format(current)
        template_vars['generic_color'] = color.to_string(**util.COLOR_FULL_PREC)
        template_vars['edit'] = '__colormod__' if self.edit_mode == "st-colormod" else '__edit__'

        show_global_palettes = s.get('enable_global_user_palettes', True)
        show_project_palettes = s.get('enable_project_user_palettes', True)
        show_favorite_palette = s.get('enable_favorite_palette', True)
        show_picker = s.get('enable_color_picker', True)
        palettes_enabled = (
            show_global_palettes or show_project_palettes or
            show_favorite_palette
        )
        click_color_box_to_pick = s.get('click_color_box_to_pick', 'none')

        # Make sure color versions are loaded proper so upgrades can happen if required
        color_ver_okay = color_ver >= util.REQUIRED_COLOR_VERSION

        template_vars['edit_mode'] = self.edit_mode
        if click_color_box_to_pick == 'color_picker' and show_picker:
            template_vars['click_color_picker'] = True
        elif click_color_box_to_pick == 'palette_picker' and palettes_enabled:
            template_vars['click_palette_picker'] = True
        elif click_color_box_to_pick == "edit":
            template_vars['click_color_edit'] = True

        if click_color_box_to_pick != 'palette_picker' and palettes_enabled:
            template_vars['show_palette_menu'] = True
        if click_color_box_to_pick != 'color_picker' and show_picker:
            template_vars['show_picker_menu'] = True

        if (show_global_palettes or show_project_palettes) and color_ver_okay:
            template_vars['show_global_palette_menu'] = True
        if show_favorite_palette and color_ver_okay:
            template_vars['show_favorite_menu'] = True
            template_vars['is_marked'] = color.to_string(**util.COLOR_FULL_PREC) in util.get_favs()['colors']

        preview = self.get_preview(color)
        message = ''
        if preview.message:
            message = '<p class="comment">* {}</p>'.format(preview.message)
        template_vars['color_preview'] = (
            mdpopups.color_box(
                [preview.preview1, preview.preview2], preview.border,
                height=self.height * PREVIEW_SCALE, width=self.width * PREVIEW_SCALE,
                border_size=BORDER_SIZE, check_size=self.check_size(self.height * PREVIEW_SCALE, scale=8)
            )
        )
        template_vars['color_preview_message'] = message
Пример #13
0
    def preview(self, text):
        """Preview."""

        style = self.get_html_style()

        try:
            colors = evaluate(text)

            html = ""
            for color in colors:
                orig = Color(color)
                message = ""
                color_string = ""
                if not orig.in_gamut('srgb'):
                    orig = orig.fit("srgb")
                    message = '<br><em style="font-size: 0.9em;">* preview out of gamut</em>'
                    color_string = "<strong>Gamut Mapped</strong>: {}<br>".format(
                        orig.to_string())
                    srgb = orig.convert('srgb', fit=True)
                else:
                    srgb = orig.convert('srgb')
                color_string += "<strong>Color</strong>: {}".format(
                    color.to_string(**util.DEFAULT))
                preview = srgb.to_string(**util.HEX_NA)
                preview_alpha = srgb.to_string(**util.HEX)
                preview_border = self.default_border
                temp = Color(preview_border)
                if temp.luminance() < 0.5:
                    second_border = temp.mix(
                        'white', 0.25, space="srgb").to_string(**util.HEX_NA)
                else:
                    second_border = temp.mix(
                        'black', 0.25, space="srgb").to_string(**util.HEX_NA)

                height = self.height * 3
                width = self.width * 3
                check_size = self.check_size(height, scale=8)

                html += tools.PREVIEW_IMG.format(
                    mdpopups.color_box([preview, preview_alpha],
                                       preview_border,
                                       second_border,
                                       border_size=2,
                                       height=height,
                                       width=width,
                                       check_size=check_size), message,
                    color_string)
            if html:
                return sublime.Html(
                    '<html><body>{}</body></html>'.format(style + html))
            else:
                return sublime.Html('<html><body>{}</body></html>'.format(
                    mdpopups.md2html(self.view, DEF_EDIT.format(style))))
        except Exception:
            return sublime.Html(
                mdpopups.md2html(self.view, DEF_EDIT.format(style)))
Пример #14
0
    def get_hires_color_channel(self, color_filter):
        """Get get a list of all colors within range."""

        ranges = {
            "red": (0, 255),
            "green": (0, 255),
            "blue": (0, 255),
            "alpha": (0, 255),
            "hue": (0, 360),
            "saturation": (0, 100),
            "luminance": (0, 100)
        }

        rgba = util.RGBA(self.color)
        h, l, s = rgba.tohls()
        minimum, maximum = ranges[color_filter]
        check_size = self.check_size(self.box_height)
        html = []
        for x in range(minimum, maximum + 1):
            if color_filter == 'red':
                rgba.r = x
                label = str(x)
            elif color_filter == 'green':
                rgba.g = x
                label = str(x)
            elif color_filter == 'blue':
                rgba.b = x
                label = str(x)
            elif color_filter == 'alpha':
                rgba.a = x
                label = util.fmt_float(
                    rgba.a * mdpopups.rgba.RGB_CHANNEL_SCALE, 3)
            elif color_filter == 'hue':
                h = x * mdpopups.rgba.HUE_SCALE
                rgba.fromhls(h, l, s)
                label = str(x)
            elif color_filter == 'saturation':
                s = x * 0.01
                rgba.fromhls(h, l, s)
                label = str(x)
            elif color_filter == 'luminance':
                l = x * 0.01
                rgba.fromhls(h, l, s)
                label = str(x)
            color = rgba.get_rgba()
            html.append(
                '[%s](%s) %s<br>' %
                (mdpopups.color_box([color],
                                    OUTER_BORDER,
                                    INNER_BORDER,
                                    border_size=2,
                                    height=self.box_height,
                                    width=self.box_height * 8,
                                    check_size=check_size), color, label))
        self.template_vars['channel_hires'] = ''.join(html)
Пример #15
0
    def get_hires_color_channel(self, text, color_filter):
        """Get get a list of all colors within range."""

        ranges = {
            "red": (0, 255),
            "green": (0, 255),
            "blue": (0, 255),
            "alpha": (0, 255),
            "hue": (0, 360),
            "saturation": (0, 100),
            "luminance": (0, 100)
        }

        rgba = util.RGBA(self.color)
        h, l, s = rgba.tohls()
        minimum, maximum = ranges[color_filter]
        check_size = self.check_size(self.box_height)
        for x in range(minimum, maximum + 1):
            if color_filter == 'red':
                rgba.r = x
                label = str(x)
            elif color_filter == 'green':
                rgba.g = x
                label = str(x)
            elif color_filter == 'blue':
                rgba.b = x
                label = str(x)
            elif color_filter == 'alpha':
                rgba.a = x
                label = util.fmt_float(rgba.a * mdpopups.rgba.RGB_CHANNEL_SCALE, 3)
            elif color_filter == 'hue':
                h = x * mdpopups.rgba.HUE_SCALE
                rgba.fromhls(h, l, s)
                label = str(x)
            elif color_filter == 'saturation':
                s = x * 0.01
                rgba.fromhls(h, l, s)
                label = str(x)
            elif color_filter == 'luminance':
                l = x * 0.01
                rgba.fromhls(h, l, s)
                label = str(x)
            color = rgba.get_rgba()
            text.append(
                '[%s](%s) %s\n' % (
                    mdpopups.color_box(
                        [color], OUTER_BORDER, INNER_BORDER,
                        border_size=2, height=self.box_height, width=self.box_height * 8, check_size=check_size
                    ),
                    color,
                    label
                )
            )
Пример #16
0
    def get_current_color(self):
        """Get current color."""

        check_size = self.check_size(self.height)
        html = ('<span class="current-color">%s</span>' %
                (mdpopups.color_box([SPACER],
                                    border_size=0,
                                    height=self.height,
                                    width=(self.width *
                                           (6 if self.hex_map else 5)),
                                    check_size=check_size,
                                    alpha=True) +
                 mdpopups.color_box([self.color],
                                    OUTER_BORDER,
                                    INNER_BORDER,
                                    border_size=2,
                                    height=self.height,
                                    width=self.width *
                                    (13 if self.hex_map else 16),
                                    check_size=check_size)))
        self.template_vars['current_color'] = html
Пример #17
0
def get_color_box(color, caption, link, index):
    """Display an HTML color box using the given color."""

    border = '#CCCCCC'
    border2 = '#333333'
    return (
        COLOR_BOX % (
            caption,
            mdpopups.color_box([color], border, border2, height=18, width=18, border_size=2),
            color.upper(),
            link,
            index
        )
    )
    def get_css_color_names(self, text):
        """Get CSS color names."""

        for name in sorted(csscolors.name2hex_map):
            color = util.RGBA(csscolors.name2hex(name)).get_rgba()

            text.append(
                '[%s](%s) %s\n' % (
                    mdpopups.color_box(
                        [color], OUTER_BORDER, INNER_BORDER,
                        border_size=2, height=self.height, width=self.width * 13, check_size=2
                    ),
                    color,
                    name
                )
            )
Пример #19
0
    def get_current_color(self):
        """Get current color."""

        # Show a preview of the current color.
        check_size = self.check_size(self.height * 2)
        preview = self.color.convert("srgb")
        html = ('<span class="current-color">{}</span>'.format(
            mdpopups.color_box(
                [preview.to_string(**HEX_NA),
                 preview.to_string(**HEX)],
                self.default_border,
                border_size=BORDER_SIZE,
                height=self.height * 3,
                width=self.width * 3,
                check_size=check_size)))
        self.template_vars['current_color'] = html
Пример #20
0
    def preview(self, text):
        """Preview."""

        style = self.get_html_style()

        try:
            color = self.color_mod_class(text.strip())
            if color is not None:
                srgb = Color(color).convert("srgb")
                preview_border = self.default_border
                message = ""
                if not srgb.in_gamut():
                    srgb.fit("srgb")
                    message = '<br><em style="font-size: 0.9em;">* preview out of gamut</em>'
                preview = srgb.to_string(**util.HEX_NA)
                preview_alpha = srgb.to_string(**util.HEX)
                preview_border = self.default_border
                temp = Color(preview_border)
                if temp.luminance() < 0.5:
                    second_border = temp.mix('white',
                                             0.25).to_string(**util.HEX_NA)
                else:
                    second_border = temp.mix('black',
                                             0.25).to_string(**util.HEX_NA)

                height = self.height * 3
                width = self.width * 3
                check_size = self.check_size(height, scale=8)

                html = PREVIEW_IMG.format(
                    mdpopups.color_box([preview, preview_alpha],
                                       preview_border,
                                       second_border,
                                       border_size=1,
                                       height=height,
                                       width=width,
                                       check_size=check_size), message,
                    color.to_string(**util.DEFAULT))
            if html:
                return sublime.Html(style + html)
            else:
                return sublime.Html(
                    mdpopups.md2html(self.view, DEF_COLORMOD.format(style)))
        except Exception:
            return sublime.Html(
                mdpopups.md2html(self.view, DEF_COLORMOD.format(style)))
Пример #21
0
    def get_color_box(self, color, key, index):
        """Display an HTML color box using the given color."""

        border = '#CCCCCC'
        border2 = '#333333'
        padding = int(self.view.settings().get('line_padding_top', 0))
        padding += int(self.view.settings().get('line_padding_bottom', 0))
        box_height = int(self.view.line_height()) - padding - 2
        check_size = int((box_height - 4) / 4)
        if check_size < 2:
            check_size = 2
        self.template_vars['%s_preview' % key] = mdpopups.color_box(
            [color], border, border2, height=box_height,
            width=box_height, border_size=2, check_size=check_size
        )
        self.template_vars['%s_color' % key] = color.upper()
        self.template_vars['%s_index' % key] = index
Пример #22
0
    def get_css_color_names(self):
        """Get CSS color names."""

        check_size = self.check_size(self.height)
        html = []
        for name in sorted(css_names.name2hex_map):
            color = Color(name, filters=util.SRGB_SPACES)

            html.append('[{}]({}) {}<br>'.format(
                mdpopups.color_box([color.to_string(**HEX)],
                                   self.default_border,
                                   border_size=BORDER_SIZE,
                                   height=self.height,
                                   width=self.height * 8,
                                   check_size=check_size),
                color.to_string(**COLOR_FULL_PREC), name))
        self.template_vars['channel_names'] = ''.join(html)
Пример #23
0
    def get_css_color_names(self):
        """Get CSS color names."""

        check_size = self.check_size(self.box_height)
        html = []
        for name in sorted(csscolors.name2hex_map):
            color = util.RGBA(csscolors.name2hex(name)).get_rgba()

            html.append(
                '[%s](%s) %s<br>' %
                (mdpopups.color_box([color],
                                    OUTER_BORDER,
                                    INNER_BORDER,
                                    border_size=2,
                                    height=self.box_height,
                                    width=self.box_height * 8,
                                    check_size=check_size), color, name))
        self.template_vars['channel_names'] = ''.join(html)
Пример #24
0
    def format_palettes(self, color_list, label, palette_type, caption=None, color=None, delete=False):
        """Format color palette previews."""

        colors = ['\n## %s\n' % label]
        if caption:
            colors.append('%s\n' % caption)
        if delete:
            label = '__delete__palette__:%s:%s' % (palette_type, label)
        elif color:
            label = '__add_palette_color__:%s:%s:%s' % (color, palette_type, label)
        else:
            label = '__colors__:%s:%s' % (palette_type, label)
        colors.append(
            '[%s](%s)' % (
                mdpopups.color_box(color_list, '#cccccc', '#333333', height=32, width=32 * 8, border_size=2),
                label
            )
        )
        return ''.join(colors)
Пример #25
0
    def preview(self, text):
        """Preview."""

        style = self.get_html_style()

        try:
            colors = evaluate(text)

            html = ""
            for color in colors:
                srgb = Color(color).convert("srgb")
                preview_border = self.default_border
                message = ""
                color_string = ""
                if not srgb.in_gamut():
                    srgb.fit("srgb")
                    message = '<br><em style="font-size: 0.9em;">* preview out of gamut</em>'
                    color_string = "<strong>Gamut Mapped</strong>: {}<br>".format(srgb.to_string())
                color_string += "<strong>Color</strong>: {}".format(color.to_string(**util.DEFAULT))
                preview = srgb.to_string(**util.HEX_NA)
                preview_alpha = srgb.to_string(**util.HEX)
                preview_border = self.default_border

                height = self.height * 3
                width = self.width * 3
                check_size = self.check_size(height, scale=8)

                html += PREVIEW_IMG.format(
                    mdpopups.color_box(
                        [
                            preview,
                            preview_alpha
                        ], preview_border, border_size=1, height=height, width=width, check_size=check_size
                    ),
                    message,
                    color_string
                )
            if html:
                return sublime.Html(style + html)
            else:
                return sublime.Html(mdpopups.md2html(self.view, DEF_EDIT.format(style)))
        except Exception:
            return sublime.Html(mdpopups.md2html(self.view, DEF_EDIT.format(style)))
Пример #26
0
	def udpate_ProgressBar( self, view ):

		self.progressPercent   += 1
		progressPercent_String  = str( self.progressPercent ) + "%"
		progressBar_Colors      = []

		popUp_Label = self.popUp_Label_InProgress

		for index in range( 0, self.maxPercent ):
			if  index <= self.progressPercent \
			and self.progressPercent < self.maxPercent:
				progressBar_Colors.append( self.progressBar_Progress_Color )
			elif index > self.progressPercent \
			and  self.progressPercent < self.maxPercent:
				progressBar_Colors.append( self.progressBar_Incomplete_Color )
			elif self.progressPercent >= self.maxPercent:
				progressBar_Colors.append( self.progressBar_Complete_Color )
				popUp_Label = self.popUp_Label_Complete

		progressBar = mdpopups.color_box(
			progressBar_Colors,           # [ colors ]
			self.progressBar_BorderColor, # border1_color
			None,                         # border2_color
			self.progressBar_Height,      # height
			self.progressBar_Width,       # width
			0,                            # border_size
			4,                            # check_size
			self.maxPercent               # max_colors
		)

		space     = "&nbsp;"
		blankLine = space + "\n"
		h5        = "#####"
		h6        = "######"

		markdown_PopUp_Text =                  \
				h5 + popUp_Label + "\n"            \
			+	blankLine                          \
			+	h6 + progressPercent_String + "\n" \
			+	progressBar

		mdpopups.update_popup( view, markdown_PopUp_Text, True, self.popupCSS )
Пример #27
0
    def get_color_box(self, color, key, index):
        """Display an HTML color box using the given color."""

        border = '#CCCCCC'
        border2 = '#333333'
        padding = int(self.view.settings().get('line_padding_top', 0))
        padding += int(self.view.settings().get('line_padding_bottom', 0))
        box_height = int(self.view.line_height()) - padding - 2
        check_size = int((box_height - 4) / 4)
        if isinstance(color, list):
            box_width = box_height * (len(color) if len(color) >= 1 else 1)
            colors = [c.upper() for c in color]
        else:
            box_width = box_height
            colors = [color.upper()]
        if check_size < 2:
            check_size = 2
        self.template_vars['%s_preview' % key] = mdpopups.color_box(
            colors, border, border2, height=box_height,
            width=box_width, border_size=2, check_size=check_size
        )
        self.template_vars['%s_color' % key] = ', '.join(colors)
        self.template_vars['%s_index' % key] = index
Пример #28
0
    def get_color_map_square(self):
        """Get a square variant of the color map."""

        global color_map
        global color_map_size
        global color_map_style
        global line_height

        if (color_map is None or self.graphic_size != color_map_size
                or self.line_height != line_height
                or color_map_style != "square"):
            color_map_size = self.graphic_size
            color_map_style = "square"
            line_height = self.line_height

            html_colors = []

            rgba = util.RGBA()
            h = 0
            s = 0.9
            l = 0.9
            hfac = 15.0 / 360.0
            lfac = 8.0 / 100.0
            check_size = self.check_size(self.height)
            for y in range(0, 11):
                html_colors.append([
                    mdpopups.color_box([SPACER],
                                       border_size=0,
                                       height=self.height,
                                       width=(self.width *
                                              (6 if self.hex_map else 5)),
                                       check_size=check_size,
                                       alpha=True)
                ])
                for x in range(0, 15):
                    rgba.fromhls(h, l, s)
                    color = rgba.get_rgba()
                    kwargs = {
                        "border_size": 2,
                        "height": self.height,
                        "width": self.width,
                        "check_size": check_size
                    }

                    if BORDER_MAP_SUPPORT:
                        if y == 0 and x == 0:
                            border_map = colorbox.TOP | colorbox.LEFT
                        elif y == 0 and x == 14:
                            border_map = colorbox.TOP | colorbox.RIGHT
                        elif y == 0:
                            border_map = colorbox.TOP
                        elif y == 10 and x == 0:
                            border_map = colorbox.BOTTOM | colorbox.LEFT
                        elif y == 10 and x == 14:
                            border_map = colorbox.BOTTOM | colorbox.RIGHT
                        elif y == 10:
                            border_map = colorbox.BOTTOM
                        elif x == 0:
                            border_map = colorbox.LEFT
                        elif x == 14:
                            border_map = colorbox.RIGHT
                        else:
                            border_map = 0
                        kwargs["border_map"] = border_map

                    html_colors[-1].append(
                        '<a href="%s">%s</a>' %
                        (color,
                         mdpopups.color_box([color], OUTER_BORDER,
                                            INNER_BORDER, **kwargs)))
                    h += hfac
                h = 0
                l -= lfac

            l = 1.0
            lfac = 10.0 / 100.0
            rgba.r = 255.0
            rgba.g = 255.0
            rgba.b = 255.0
            check_size = self.check_size(self.height)
            for y in range(0, 11):
                h, lum, s = rgba.tohls()
                rgba.fromhls(h, l, s)
                color = rgba.get_rgba()
                kwargs = {
                    "border_size": 2,
                    "height": self.height,
                    "width": self.width,
                    "check_size": check_size
                }

                if BORDER_MAP_SUPPORT:
                    if y == 0:
                        border_map = 0xb
                    elif y == 10:
                        border_map = 0xe
                    else:
                        border_map = 0xa
                    kwargs["border_map"] = border_map

                html_colors[y].append(
                    '<a href="%s">%s</a>' %
                    (color,
                     mdpopups.color_box([color], OUTER_BORDER, INNER_BORDER, **
                                        kwargs)))
                l -= lfac

            color_map = ''.join([
                '<span>%s</span><br>' % ''.join([y1 for y1 in x1])
                for x1 in html_colors
            ]) + '\n\n'
        self.template_vars['color_picker'] = color_map
Пример #29
0
    def get_channel(self, channel, label, minimum, maximum, color_filter):
        """Get color channel."""

        html = []
        html.append(
            '<span class="channel"><a href="__hirespick__:{}">{}:</a>'.format(
                color_filter, label))
        temp = []
        count = 12
        check_size = self.check_size(self.height)
        clone = self.color.clone()

        mn = minimum
        first = True
        while count:
            coord = getattr(clone, color_filter) + mn
            setattr(clone, color_filter, coord)

            if not clone.in_gamut():
                temp.append(self.get_spacer(width=count))
                break
            elif color_filter == "alpha" and (coord < 0 or coord > 1.0):
                temp.append(self.get_spacer(width=count))
                break
            elif self.mode in ("hsl", "hwb") and color_filter == "hue" and (
                    coord < 0 or coord > 360):
                temp.append(self.get_spacer(width=count))
                break
            else:
                border_map = colorbox.TOP | colorbox.BOTTOM | colorbox.LEFT
                if first:
                    border_map |= colorbox.RIGHT
                    first = False

                kwargs = {
                    "border_size": BORDER_SIZE,
                    "height": self.height,
                    "width": self.width,
                    "check_size": check_size,
                    "border_map": border_map
                }

                temp.append('[{}]({})'.format(
                    mdpopups.color_box(
                        [clone.convert("srgb").to_string(**HEX)],
                        self.default_border, **kwargs),
                    clone.to_string(**COLOR_FULL_PREC)))
            clone.update(self.color)
            mn += minimum
            count -= 1
        html += reversed(temp)
        html.append('[{}]({})'.format(
            mdpopups.color_box([self.color.convert("srgb").to_string(**HEX)],
                               self.default_border,
                               border_size=BORDER_SIZE,
                               height=self.height_big,
                               width=self.width,
                               check_size=check_size),
            self.color.to_string(**COLOR_FULL_PREC)))
        first = True
        count = 12
        mx = maximum

        clone.update(self.color)
        while count:
            coord = getattr(clone, color_filter) + mx
            setattr(clone, color_filter, coord)

            if not clone.in_gamut():
                html.append(self.get_spacer(width=count))
                break
            elif color_filter == "alpha" and (coord < 0 or coord > 1.0):
                html.append(self.get_spacer(width=count))
                break
            elif self.mode in ("hsl", "hwb") and color_filter == "hue" and (
                    coord < 0 or coord > 360):
                html.append(self.get_spacer(width=count))
                break
            else:
                border_map = colorbox.TOP | colorbox.BOTTOM | colorbox.RIGHT
                if first:
                    border_map |= colorbox.LEFT
                    first = False

                kwargs = {
                    "border_size": BORDER_SIZE,
                    "height": self.height,
                    "width": self.width,
                    "check_size": check_size,
                    "border_map": border_map
                }

                html.append('[{}]({})'.format(
                    mdpopups.color_box(
                        [clone.convert("srgb").to_string(**HEX)],
                        self.default_border, **kwargs),
                    clone.to_string(**COLOR_FULL_PREC)))
            clone.update(self.color)
            mx += maximum
            count -= 1
        html.append('</span><br>')
        self.template_vars[channel] = ''.join(html)
Пример #30
0
    def get_channel(self, channel, label, color_filter):
        """Get color channel."""

        html = []
        html.append(
            '<span class="channel"><a class="small button" href="__hirespick__:{}">{}:</a> '
            .format(color_filter, label))
        temp = []
        count = 10
        check_size = self.check_size(self.height)
        clone = self.color.clone()
        options = HEX_NA if color_filter != 'alpha' else HEX

        coord = cutil.no_nan(getattr(clone, color_filter))
        if color_filter in ('red', 'green', 'blue', 'alpha'):
            rounded = cutil.round_half_up(coord, 2)
            setattr(clone, color_filter, rounded)
            step = 0.01
        elif color_filter in ('lightness', 'saturation', 'whiteness',
                              'blackness'):
            rounded = cutil.round_half_up(coord, 0)
            setattr(clone, color_filter, rounded)
            step = 1
        else:
            rounded = cutil.round_half_up(coord / 359, 2) * 359
            setattr(clone, color_filter, rounded)
            step = 3.59

        first = True
        while count:
            coord = cutil.no_nan(getattr(clone, color_filter)) - step
            setattr(clone, color_filter, coord)

            if not clone.in_gamut():
                temp.append(self.get_spacer(width=count))
                break
            elif color_filter == "alpha" and (coord < 0 or coord > 1.0):
                temp.append(self.get_spacer(width=count))
                break
            elif self.mode in ("hsl", "hwb") and color_filter == "hue" and (
                    coord < 0 or coord > 359):
                temp.append(self.get_spacer(width=count))
                break
            else:
                border_map = colorbox.TOP | colorbox.BOTTOM | colorbox.LEFT
                if first:
                    border_map |= colorbox.RIGHT
                    first = False

                kwargs = {
                    "border_size": BORDER_SIZE,
                    "height": self.height,
                    "width": self.width,
                    "check_size": check_size,
                    "border_map": border_map
                }

                temp.append('<a href="{}" title="{}">{}</a>'.format(
                    clone.to_string(**COLOR_FULL_PREC), clone.to_string(),
                    mdpopups.color_box(
                        [clone.convert("srgb").to_string(**options)],
                        self.default_border, **kwargs)))
            count -= 1
        html += reversed(temp)
        html.append('<a href="{}" title="{}">{}</a>'.format(
            self.color.to_string(**COLOR_FULL_PREC), clone.to_string(),
            mdpopups.color_box(
                [self.color.convert("srgb").to_string(**options)],
                self.default_border,
                border_size=BORDER_SIZE,
                height=self.height_big,
                width=self.width,
                check_size=check_size)))
        first = True
        count = 10

        clone.update(self.color)
        setattr(clone, color_filter, rounded)
        while count:
            coord = cutil.no_nan(getattr(clone, color_filter)) + step
            setattr(clone, color_filter, coord)

            if not clone.in_gamut():
                html.append(self.get_spacer(width=count))
                break
            elif color_filter == "alpha" and (coord < 0 or coord > 1.0):
                html.append(self.get_spacer(width=count))
                break
            elif self.mode in ("hsl", "hwb") and color_filter == "hue" and (
                    coord < 0 or coord > 359):
                html.append(self.get_spacer(width=count))
                break
            else:
                border_map = colorbox.TOP | colorbox.BOTTOM | colorbox.RIGHT
                if first:
                    border_map |= colorbox.LEFT
                    first = False

                kwargs = {
                    "border_size": BORDER_SIZE,
                    "height": self.height,
                    "width": self.width,
                    "check_size": check_size,
                    "border_map": border_map
                }

                html.append('<a href="{}" title="{}">{}</a>'.format(
                    clone.to_string(**COLOR_FULL_PREC), clone.to_string(),
                    mdpopups.color_box(
                        [clone.convert("srgb").to_string(**options)],
                        self.default_border, **kwargs)))
            count -= 1
        html.append('</span><br>')
        self.template_vars[channel] = ''.join(html)
Пример #31
0
    def do_search(self, force=False):
        """
        Perform the search for the highlighted word.

        TODO: This function is a big boy. We should look into breaking it up.
              With that said, this is low priority.
        """

        # Since the plugin has been reloaded, force update.
        global reload_flag
        settings = self.view.settings()
        colors = []

        view_id = self.view.id()

        # Allow per view scan override
        option = settings.get("color_helper.scan_override", None)
        if option in ("Force enable", "Force disable"):
            override = option == "Force enable"
        else:
            override = None

        # Get the rules and use them to get the needed scopes.
        # The scopes will be used to get the searchable regions.
        rules = util.get_rules(self.view)
        # Bail if this if this view has no valid rule or scanning is disabled.
        if (rules is None or not rules.get("enabled", False)
                or (not rules.get("allow_scanning", True) and not override)
                or override is False):
            self.erase_phantoms()
            return

        if reload_flag:
            reload_flag = False
            force = True

        # Calculate size of preview boxes
        box_height = self.calculate_box_size()
        check_size = int((box_height - 2) / 4)
        if check_size < 2:
            check_size = 2

        # If desired preview boxes are different than current,
        # we need to reload the boxes.
        old_box_height = int(settings.get('color_helper.box_height', 0))
        current_color_scheme = settings.get('color_scheme')
        if (force or old_box_height != box_height
                or current_color_scheme != settings.get(
                    'color_helper.color_scheme', '')
                or settings.get('color_helper.refresh')):
            self.erase_phantoms()
            settings.set('color_helper.color_scheme', current_color_scheme)
            settings.set('color_helper.box_height', box_height)
            force = True

        # Get viewable bounds so we can constrain both vertically and horizontally.
        visible_region = self.view.visible_region()
        position = self.view.viewport_position()
        dimensions = self.view.viewport_extent()
        bounds = Dimensions(
            Extent(position[0], position[0] + dimensions[0] - 1),
            Extent(position[1], position[1] + dimensions[1] - 1))

        # If we don't need to force previews,
        # quit if visible region is the same as last time
        if not force and self.previous_region[view_id] == bounds:
            return
        self.previous_region[view_id] = bounds

        # Setup "preview on select"
        preview_on_select = ch_settings.get("preview_on_select", False)
        show_preview = True
        sels = []
        if preview_on_select:
            show_preview = False
            sels = self.get_selections(bounds)
            if sels:
                show_preview = True

        # Get the scan scopes
        scanning = rules.get("scanning")
        classes = rules.get("color_class", "css-level-4")
        if show_preview and visible_region.size() and scanning and classes:
            # Get out of gamut related options
            self.setup_gamut_options()

            # Get triggers that identify where colors are likely
            color_trigger = re.compile(
                rules.get("color_trigger", util.RE_COLOR_START))

            # Find source content in the visible region.
            # We will return consecutive content, but if the lines are too wide
            # horizontally, they will be clipped and returned as separate chunks.
            for src_region in self.source_iter(visible_region, bounds):
                source = self.view.substr(src_region)
                start = 0

                # Find colors in this source chunk.
                for m in color_trigger.finditer(source):
                    # Test if we have found a valid color
                    start = m.start()
                    src_start = src_region.begin() + start

                    # Check if the first point within the color matches our scope rules
                    # and load up the appropriate color class
                    color_class, filters = self.get_color_class(
                        src_start, classes)
                    if color_class is None:
                        continue

                    # Check if scope matches for scanning
                    try:
                        value = self.view.score_selector(src_start, scanning)
                        if not value:
                            continue
                    except Exception:
                        continue

                    obj = color_class.match(source,
                                            start=start,
                                            filters=filters)
                    if obj is not None:
                        # Calculate true start and end of the color source
                        src_end = src_region.begin() + obj.end
                        region = sublime.Region(src_start, src_end)

                        # If "preview on select" is enabled, only show preview if within a selection
                        # or if the selection as no width and the color comes right after.
                        if preview_on_select and not self.is_selected(
                                region, sels):
                            continue
                    else:
                        continue

                    # Calculate point at which we which to insert preview
                    position_on_left = preview_is_on_left()
                    pt = src_start if position_on_left else src_end
                    if str(region.begin()) in self.previews[view_id]:
                        # Already exists
                        continue

                    # Calculate a reasonable border color for our image at this location and get color strings
                    hsl = Color(mdpopups.scope2style(
                        self.view, self.view.scope_name(pt))['background'],
                                filters=util.SRGB_SPACES).convert("hsl")
                    hsl.lightness = hsl.lightness + (
                        30 if hsl.luminance() < 0.5 else -30)
                    preview_border = hsl.convert(
                        "srgb", fit=True).to_string(**util.HEX)

                    color = Color(obj.color)
                    title = ''
                    if not color.in_gamut("srgb"):
                        title = ' title="Preview out of gamut"'
                        if self.show_out_of_gamut_preview:
                            srgb = color.convert("srgb", fit=True)
                            preview1 = srgb.to_string(**util.HEX_NA)
                            preview2 = srgb.to_string(**util.HEX)
                        else:
                            preview1 = self.out_of_gamut
                            preview2 = self.out_of_gamut
                            preview_border = self.out_of_gamut_border
                    else:
                        srgb = color.convert("srgb")
                        preview1 = srgb.to_string(**util.HEX_NA)
                        preview2 = srgb.to_string(**util.HEX)

                    # Create preview
                    unique_id = str(time()) + str(region)
                    html = PREVIEW_IMG.format(
                        unique_id, title,
                        mdpopups.color_box([preview1, preview2],
                                           preview_border,
                                           height=box_height,
                                           width=box_height,
                                           border_size=PREVIEW_BORDER_SIZE,
                                           check_size=check_size))
                    colors.append(
                        (html, pt, region.begin(), region.end(), unique_id))

            # Add all previews
            self.add_phantoms(colors)

            # The phantoms may have altered the viewable region,
            # so set previous region to the current viewable region
            visible_region = self.view.visible_region()
            position = self.view.viewport_position()
            dimensions = self.view.viewport_extent()
            bounds = Dimensions(
                Extent(position[0], position[0] + dimensions[0] - 1),
                Extent(position[1], position[1] + dimensions[1] - 1))
            self.previous_region[view_id] = bounds
    def get_color_map_square(self, text):
        """Get a square variant of the color map."""

        global color_map
        global color_map_size
        global color_map_style

        if (
            color_map is None or
            self.graphic_size != color_map_size or
            color_map_style != "square"
        ):
            color_map_size = self.graphic_size
            color_map_style = "square"

            html_colors = []

            rgba = util.RGBA()
            h = 0
            s = 0.9
            l = 0.9
            hfac = 15.0 / 360.0
            lfac = 8.0 / 100.0
            for y in range(0, 11):
                html_colors.append(
                    [
                        mdpopups.color_box(
                            [SPACER], border_size=0,
                            height=self.height, width=(self.width * (6 if self.hex_map else 5)), alpha=True
                        )
                    ]
                )
                for x in range(0, 15):
                    rgba.fromhls(h, l, s)
                    color = rgba.get_rgba()
                    kwargs = {"border_size": 2, "height": self.height, "width": self.width}

                    if BORDER_MAP_SUPPORT:
                        if y == 0 and x == 0:
                            border_map = colorbox.TOP | colorbox.LEFT
                        elif y == 0 and x == 14:
                            border_map = colorbox.TOP | colorbox.RIGHT
                        elif y == 0:
                            border_map = colorbox.TOP
                        elif y == 10 and x == 0:
                            border_map = colorbox.BOTTOM | colorbox.LEFT
                        elif y == 10 and x == 14:
                            border_map = colorbox.BOTTOM | colorbox.RIGHT
                        elif y == 10:
                            border_map = colorbox.BOTTOM
                        elif x == 0:
                            border_map = colorbox.LEFT
                        elif x == 14:
                            border_map = colorbox.RIGHT
                        else:
                            border_map = 0
                        kwargs["border_map"] = border_map

                    html_colors[-1].append(
                        '<a href="%s">%s</a>' % (
                            color, mdpopups.color_box(
                                [color], OUTER_BORDER, INNER_BORDER,
                                **kwargs
                            )
                        )
                    )
                    h += hfac
                h = 0
                l -= lfac

            l = 1.0
            lfac = 10.0 / 100.0
            rgba.r = 255.0
            rgba.g = 255.0
            rgba.b = 255.0
            for y in range(0, 11):
                h, lum, s = rgba.tohls()
                rgba.fromhls(h, l, s)
                color = rgba.get_rgba()
                kwargs = {"border_size": 2, "height": self.height, "width": self.width}

                if BORDER_MAP_SUPPORT:
                    if y == 0:
                        border_map = 0xb
                    elif y == 10:
                        border_map = 0xe
                    else:
                        border_map = 0xa
                    kwargs["border_map"] = border_map

                html_colors[y].append(
                    '<a href="%s">%s</a>' % (
                        color, mdpopups.color_box(
                            [color], OUTER_BORDER, INNER_BORDER,
                            **kwargs
                        )
                    )
                )
                l -= lfac

            color_map = ''.join(['<span>%s</span><br>' % ''.join([y1 for y1 in x1]) for x1 in html_colors]) + '\n\n'
        text.append(color_map)
Пример #33
0
    def get_hires_color_channel(self, color_filter):
        """Get get a list of all colors within range."""

        ranges = {
            "red": (0, 255),
            "green": (0, 255),
            "blue": (0, 255),
            "alpha": (0, 100),
            "hue": (0, 359),
            "saturation": (0, 100),
            "lightness": (0, 100),
            "whiteness": (0, 100),
            "blackness": (0, 100)
        }

        options = HEX_NA if color_filter != 'alpha' else HEX
        minimum, maximum = ranges[color_filter]
        check_size = self.check_size(self.height)
        html = []
        color = self.color.clone()
        current = color.get(color_filter)
        if color_filter in ('red', 'green', 'blue'):
            estimate = int(cutil.fmt_float(current * 255, 0))
            current = '{}'.format(cutil.fmt_float(current * 255, 5))
        elif color_filter in ('alpha', ):
            estimate = int(cutil.fmt_float(current * 100, 0))
            current = '{}%'.format(cutil.fmt_float(current * 100, 5))
        elif color_filter in ('whiteness', 'blackness', 'saturation',
                              'lightness'):
            estimate = int(cutil.fmt_float(current, 0))
            current = '{}%'.format(cutil.fmt_float(current, 5))
        elif color_filter in ('hue', ):
            estimate = int(cutil.fmt_float(current, 0))
            current = '{}\xb0'.format(cutil.fmt_float(current, 5))

        for x in range(minimum, maximum + 1):
            if x == estimate:
                label = '{} <'
            else:
                label = '{}'
            if color_filter in ('red', 'green', 'blue'):
                color.set(color_filter, x / 255.0)
                label = label.format(str(x))
            elif color_filter == 'alpha':
                color.alpha = x / 100.0
                label = label.format("{:d}%".format(x))
            elif color_filter == 'hue':
                color.hue = x
                label = label.format("{:d}\xb0".format(x))
            elif color_filter in ('saturation', 'lightness', 'whiteness',
                                  'blackness'):
                color.set(color_filter, x)
                label = label.format("{:d}%".format(x))

            html.append('[{}]({}) {}<br>'.format(
                mdpopups.color_box(
                    [color.convert("srgb").to_string(**options)],
                    self.default_border,
                    border_size=BORDER_SIZE,
                    height=self.height,
                    width=self.height * 8,
                    check_size=check_size), color.to_string(**COLOR_FULL_PREC),
                label))
        self.template_vars['hires_color'] = '{} ({})'.format(
            color_filter, current)
        self.template_vars['channel_hires'] = ''.join(html)
Пример #34
0
    def format_info(self, color, alpha=None):
        """Format the selected color info."""
        rgba = RGBA(color)

        try:
            web_color = csscolors.hex2name(rgba.get_rgb())
        except Exception:
            web_color = None

        color_picker = util.color_picker_available()
        s = sublime.load_settings('color_helper.sublime-settings')
        show_global_palettes = s.get('enable_global_user_palettes', True)
        show_project_palettes = s.get('enable_project_user_palettes', True)
        show_favorite_palette = s.get('enable_favorite_palette', True)
        show_current_palette = s.get('enable_current_file_palette', True)
        show_conversions = s.get('enable_color_conversions', True)
        show_picker = s.get('enable_color_picker', True)
        palettes_enabled = (
            show_global_palettes or show_project_palettes or
            show_favorite_palette or show_current_palette
        )
        click_color_box_to_pick = s.get('click_color_box_to_pick', 'none')

        if click_color_box_to_pick == 'color_picker' and color_picker and show_picker:
            color_box_wrapper = '\n\n[%s]' + ('(__color_picker__:%s)' % color)
        elif click_color_box_to_pick == 'palette_picker' and palettes_enabled:
            color_box_wrapper = '\n\n[%s](__palettes__)'
        else:
            color_box_wrapper = '\n\n%s'

        info = []

        if click_color_box_to_pick != 'palette_picker' and palettes_enabled:
            info.append(PALETTE_MENU)
        if click_color_box_to_pick != 'color_picker' and color_picker and show_picker:
            info.append(PICK_MENU % color)
        if show_global_palettes or show_project_palettes:
            info.append(ADD_COLOR_MENU % color.lower())
        if show_favorite_palette:
            if color in util.get_favs()['colors']:
                info.append(UNMARK_MENU % color.lower())
            else:
                info.append(MARK_MENU % color.lower())

        info.append(
            color_box_wrapper % mdpopups.color_box([color], '#cccccc', '#333333', height=64, width=192, border_size=2)
        )

        if show_conversions:
            info.append('\n\n---\n\n')
            if web_color:
                info.append(WEB_COLOR % (color, web_color))
            info.append(HEX_COLOR % (color, (color.lower() if not alpha else color[:-2].lower())))
            info.append(RGB_COLOR % (color, rgba.r, rgba.g, rgba.b))
            info.append(RGBA_COLOR % (color, rgba.r, rgba.g, rgba.b, alpha if alpha else '1'))
            h, l, s = rgba.tohls()
            info.append(
                HSL_COLOR % (color, util.fmt_float(h * 360.0), util.fmt_float(s * 100.0), util.fmt_float(l * 100.0))
            )
            info.append(
                HSLA_COLOR % (
                    color, util.fmt_float(h * 360.0), util.fmt_float(s * 100.0), util.fmt_float(l * 100.0),
                    alpha if alpha else '1'
                )
            )
        return ''.join(info)
Пример #35
0
    def get_color_map_square(self):
        """Get a square variant of the color map."""

        global color_map
        global color_map_size
        global line_height
        global default_border
        global color_scale

        hue, saturation, lightness = cutil.no_nan(
            self.color.convert('hsl').coords())
        alpha = cutil.no_nan(self.color.alpha)

        r_sat = cutil.round_half_up(saturation / 100, 1) * 100
        r_lit = cutil.round_half_up(lightness / 100, 1) * 100

        # Only update if the last time we rendered we changed
        # something that would require a new render.
        if (True):
            color_map_size = self.graphic_size
            color_scale = self.graphic_scale

            line_height = self.line_height
            default_border = self.default_border

            html_colors = []

            # Generate the colors with each row being darker than the last.
            # Each column will progress through hues.
            color = Color("hsl(0 100% {}% / {})".format(lightness, alpha),
                          filters=util.SRGB_SPACES)
            if color.is_nan("hue"):
                color.hue = 0.0
            check_size = self.check_size(self.height)
            for y in range(0, 11):
                html_colors.append([])
                for x in range(0, 17):
                    this_hue = False
                    this_sat = color.saturation == r_sat
                    border_color = self.default_border
                    if this_sat:
                        this_hue = abs(color.hue - hue) < 11.21875
                        if this_hue:
                            lum = color.luminance()
                            border_color = '#ffffff' if lum < 0.5 else '#000000'
                    value = color.convert("srgb").to_string(**HEX_NA)
                    kwargs = {
                        "border_size": BORDER_SIZE,
                        "height": self.height,
                        "width": self.width,
                        "check_size": check_size
                    }

                    if this_hue and this_sat:
                        border_map = colorbox.TOP | colorbox.LEFT | colorbox.BOTTOM | colorbox.RIGHT
                    elif y == 0 and x == 0:
                        border_map = colorbox.TOP | colorbox.LEFT
                    elif y == 0 and x == 16:
                        border_map = colorbox.TOP | colorbox.RIGHT
                    elif y == 0:
                        border_map = colorbox.TOP
                    elif y == 10 and x == 0:
                        border_map = colorbox.BOTTOM | colorbox.LEFT
                    elif y == 10 and x == 16:
                        border_map = colorbox.BOTTOM | colorbox.RIGHT
                    elif y == 10:
                        border_map = colorbox.BOTTOM
                    elif x == 0:
                        border_map = colorbox.LEFT
                    elif x == 16:
                        border_map = colorbox.RIGHT
                    else:
                        border_map = 0
                    kwargs["border_map"] = border_map

                    html_colors[-1].append('<a href="{}">{}</a>'.format(
                        color.to_string(**COLOR_FULL_PREC),
                        mdpopups.color_box([value], border_color, **kwargs)))
                    color.hue = color.hue + 22.4375
                color.hue = 0.0
                color.saturation = color.saturation - 10

            # Generate a grayscale bar.
            color = Color('hsl({} {}% 100% / {})'.format(
                hue, saturation, alpha),
                          filters=util.SRGB_SPACES)
            if color.is_nan("hue"):
                color.hue = 0.0
            check_size = self.check_size(self.height)
            for y in range(0, 11):
                value = color.convert("srgb").to_string(**HEX_NA)
                kwargs = {
                    "border_size": BORDER_SIZE,
                    "height": self.height,
                    "width": self.width,
                    "check_size": check_size
                }

                this_lit = color.lightness == r_lit
                border_color = self.default_border
                if this_lit:
                    lum = color.luminance()
                    border_color = '#ffffff' if lum < 0.5 else '#000000'

                if this_lit:
                    border_map = colorbox.TOP | colorbox.LEFT | colorbox.BOTTOM | colorbox.RIGHT
                elif y == 0:
                    border_map = colorbox.TOP | colorbox.LEFT | colorbox.RIGHT
                elif y == 10:
                    border_map = colorbox.BOTTOM | colorbox.LEFT | colorbox.RIGHT
                else:
                    border_map = colorbox.LEFT | colorbox.RIGHT
                kwargs["border_map"] = border_map

                html_colors[y].append('<a href="{}">{}</a>'.format(
                    color.to_string(**COLOR_FULL_PREC),
                    mdpopups.color_box([value], border_color, **kwargs)))
                color.lightness = color.lightness - 10

            color_map = (''.join([
                '<span>{}</span><br>'.format(''.join([y1 for y1 in x1]))
                for x1 in html_colors
            ]))
        self.template_vars['color_picker'] = color_map
Пример #36
0
    def get_color_map_square(self):
        """Get a square variant of the color map."""

        global color_map
        global color_map_size
        global line_height
        global default_border
        global color_scale
        global last_saturation

        s = self.color.convert("hsl").saturation

        # Only update if the last time we rendered we changed
        # something that would require a new render.
        if (color_map is None or s != last_saturation
                or self.graphic_size != color_map_size
                or self.graphic_scale != color_scale
                or self.line_height != line_height
                or self.default_border != default_border):
            color_map_size = self.graphic_size
            color_scale = self.graphic_scale

            line_height = self.line_height
            default_border = self.default_border

            html_colors = []

            # Generate the colors with each row being dark than the last.
            # Each column will progress through hues.
            color = Color("hsl(0 {}% 90%)".format(s), filters=util.SRGB_SPACES)
            hfac = 24.0
            lfac = 8.0
            check_size = self.check_size(self.height)
            for y in range(0, 11):
                html_colors.append([self.get_spacer(width=5)])
                for x in range(0, 15):
                    value = color.convert("srgb").to_string(**HEX)
                    kwargs = {
                        "border_size": BORDER_SIZE,
                        "height": self.height,
                        "width": self.width,
                        "check_size": check_size
                    }

                    if y == 0 and x == 0:
                        border_map = colorbox.TOP | colorbox.LEFT
                    elif y == 0 and x == 14:
                        border_map = colorbox.TOP | colorbox.RIGHT
                    elif y == 0:
                        border_map = colorbox.TOP
                    elif y == 10 and x == 0:
                        border_map = colorbox.BOTTOM | colorbox.LEFT
                    elif y == 10 and x == 14:
                        border_map = colorbox.BOTTOM | colorbox.RIGHT
                    elif y == 10:
                        border_map = colorbox.BOTTOM
                    elif x == 0:
                        border_map = colorbox.LEFT
                    elif x == 14:
                        border_map = colorbox.RIGHT
                    else:
                        border_map = 0
                    kwargs["border_map"] = border_map

                    html_colors[-1].append('<a href="{}">{}</a>'.format(
                        color.to_string(**COLOR_FULL_PREC),
                        mdpopups.color_box([value], self.default_border,
                                           **kwargs)))
                    color.hue = color.hue + hfac
                color.hue = 0.0
                color.lightness = color.lightness - lfac

            # Generate a grayscale bar.
            lfac = 10.0
            color = Color('hsl(0 0% 100%)', filters=util.SRGB_SPACES)
            check_size = self.check_size(self.height)
            for y in range(0, 11):
                value = color.convert("srgb").to_string(**HEX)
                kwargs = {
                    "border_size": BORDER_SIZE,
                    "height": self.height,
                    "width": self.width,
                    "check_size": check_size
                }

                if y == 0:
                    border_map = 0xb
                elif y == 10:
                    border_map = 0xe
                else:
                    border_map = 0xa
                kwargs["border_map"] = border_map

                html_colors[y].append('<a href="{}">{}</a>'.format(
                    color.to_string(**COLOR_FULL_PREC),
                    mdpopups.color_box([value], self.default_border,
                                       **kwargs)))
                color.lightness = color.lightness - lfac

            color_map = (''.join([
                '<span>{}</span><br>'.format(''.join([y1 for y1 in x1]))
                for x1 in html_colors
            ]) + '\n\n')
        self.template_vars['color_picker'] = color_map