colours.py

Thu, 26 Aug 2021 19:37:00 +0300

author
Teemu Piippo <teemu@hecknology.net>
date
Thu, 26 Aug 2021 19:37:00 +0300
changeset 148
8f621aa4cfd7
parent 147
bec55b021ae7
permissions
-rw-r--r--

Update license year

#!/usr/bin/env python3
class Colour:
    '''
        Colour interface. Supports LDConfig colours and direct colours.
        For LDConfig colours to work, load_colours must be called first.
    '''
    def __init__(self, index):
        if not isinstance(index, int):
            index = int(index, 0)
        self.index = index
    def __str__(self):
        if self.is_direct_colour:
            # write direct colours with hex codes
            return '0x%07X' % self.index
        else:
            return str(self.index)
    def __repr__(self):
        return str.format('Colour({!r})', self.index)
    @property
    def is_direct_colour(self):
        return self.index >= 0x2000000
    def __eq__(self, other):
        return self.index == other.index
    def __lt__(self, other):
        return self.index < other.index
    def __le__(self, other):
        return self.index <= other.index
    def __gt__(self, other):
        return self.index > other.index
    def __ge__(self, other):
        return self.index >= other.index

def parse_ldconfig_ldr_line(line):
    '''
        Parses a single LDConfig.ldr line.

        Returns:
            · a dict for a successful parsed colour.
            · None for empty lines and comments.

        Raises an error for invalid lines.
    '''
    line = line.strip()
    import re
    def parse_tag(tag):
        match = re.search(tag + r'\s+([^ ]+)', line)
        if match:
            return match.group(1)
        else:
            raise KeyError(str.format('Tag {} not found', tag))
    # parse 0 !COLOUR and get the name
    match = re.search(r'^0\s+!COLOUR\s([^ ]+)', line)
    if not match:
        raise ValueError('Bad LDConfig.ldr line: ' + line)
    # replace underscores for readability
    name = match.group(1).replace('_', ' ')
    # parse tags
    code = int(parse_tag('CODE'))
    value = parse_tag('VALUE')
    edge = parse_tag('EDGE')
    return {
        'name': name,
        'code': code,
        'value': value,
        'edge': edge,
    }

def parse_ldconfig_ldr(ldconfig_ldr):
    '''
        Parses LDConfig.ldr and returns pairs
    '''
    for line in ldconfig_ldr:
        line = line.strip()
        if line.startswith('0 !COLOUR'):
            colour = parse_ldconfig_ldr_line(line)
            yield (colour['code'], colour)

def load_colours(ldconfig_ldr):
    '''
        Loads colours. Expects a file pointer to LDConfig.ldr as the parameter.
        Returns a lookup table
    '''
    return dict(parse_ldconfig_ldr(ldconfig_ldr))

mercurial