예제 #1
0
파일: views.py 프로젝트: funkybob/dumpling
def styles(request, name):
    src = ''
    namespace = Namespace()
    for tv in ThemeValue.objects.all():
        namespace.set_variable('${}-{}'.format(tv.group, tv.name), String(tv.value))
    compiler = Compiler(namespace=namespace)
    return HttpResponse(compiler.compile_string(src), content_type='text/css')
예제 #2
0
    def style_scss(self, *path):
        css_namespace = Namespace()
        for key, value in self.settings['keys'].items():
            if isinstance(value, LCText):
                css_value = String(value)
            elif isinstance(value, LCColour):
                css_value = Color.from_hex(value)
            elif isinstance(value, LCBool):
                css_value = Boolean(value.simple())
            elif isinstance(value, LCSpin):
                css_value = Number(value.simple())
            else:
                raise ValueError("Unable to find comparable values")
            css_namespace.set_variable('${}'.format(key), css_value)

        cherrypy.response.headers['Content-Type'] = 'text/css'
        with open(os.path.join(self.settings['location'], *path), 'r') as css:
            css_content = css.read()
            compiler = Compiler(namespace=css_namespace, output_style='nested')
            # Something wrong with PyScss,
            #  Syntax error: Found u'100%' but expected one of ADD.
            # Doesn't happen on next attempt, so we are doing bad thing
            attempts = 0
            while attempts < 100:
                try:
                    attempts += 1
                    ret_string = compiler.compile_string(css_content)
                    return ret_string
                except Exception as exc:
                    if attempts == 100:
                        log.debug(exc)
예제 #3
0
파일: views.py 프로젝트: funkybob/dumpling
def styles(request, name):
    src = ''
    namespace = Namespace()
    for tv in ThemeValue.objects.all():
        namespace.set_variable('${}-{}'.format(tv.group, tv.name),
                               String(tv.value))
    compiler = Compiler(namespace=namespace)
    return HttpResponse(compiler.compile_string(src), content_type='text/css')
예제 #4
0
def customise_css():
    colour = colours.get_from_qs(flask.request.args)
    namespace = Namespace()
    namespace.set_variable('$fg', Color.from_hex(colour.fg))
    namespace.set_variable('$bg', Color.from_hex(colour.bg))
    namespace.set_variable('$highFg', Color.from_hex(colour.highFg))
    namespace.set_variable('$highBg', Color.from_hex(colour.highBg))

    compiler = Compiler(namespace=namespace)
    res = make_response(compiler.compile('style/index.scss'))
    res.mimetype = 'text/css'
    return res
예제 #5
0
class HorizonScssFilter(DjangoScssFilter):
    def __init__(self, *args, **kwargs):
        super(HorizonScssFilter, self).__init__(*args, **kwargs)

        self.namespace = Namespace()

        # Add variables to the SCSS Global Namespace Here
        self.namespace.set_variable('$static_url', String(six.text_type(getattr(settings, 'STATIC_URL', '/static/'))))

    # Create a compiler with the right namespace
    @property
    def compiler(self):
        return DjangoScssCompiler(namespace=self.namespace)
예제 #6
0
class HorizonScssFilter(DjangoScssFilter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.namespace = Namespace()

        # Add variables to the SCSS Global Namespace Here
        self.namespace.set_variable('$static_url', String(settings.STATIC_URL))

    # Create a compiler with the right namespace
    @property
    def compiler(self):
        return DjangoScssCompiler(
            # output_style is 'nested' by default, which is crazy. See:
            # https://github.com/Kronuz/pyScss/issues/243
            output_style='compact',  # or 'compressed'
            namespace=self.namespace)
예제 #7
0
class HorizonScssFilter(DjangoScssFilter):
    def __init__(self, *args, **kwargs):
        super(HorizonScssFilter, self).__init__(*args, **kwargs)

        self.namespace = Namespace()

        # Add variables to the SCSS Global Namespace Here
        self.namespace.set_variable(
            '$static_url',
            String(six.text_type(getattr(settings, 'STATIC_URL', '/static/')))
        )

    # Create a compiler with the right namespace
    @property
    def compiler(self):
        return DjangoScssCompiler(
            namespace=self.namespace
        )
예제 #8
0
파일: tool.py 프로젝트: 7c00/staticpycon
class SassRepl(object):
    def __init__(self, is_sass=False):
        # TODO it would be lovely to get these out of here, somehow
        self.namespace = Namespace(variables=_default_scss_vars)

        self.compiler = Compiler(namespace=self.namespace)
        self.compilation = self.compiler.make_compilation()
        self.legacy_compiler_options = {}
        self.source_file = SourceFile.from_string('', '<shell>', is_sass=is_sass)
        self.calculator = Calculator(self.namespace)

    def __call__(self, s):
        # TODO this is kind of invasive; surely it's possible to do this
        # without calling only private methods
        from pprint import pformat

        if s in ('exit', 'quit'):
            raise KeyboardInterrupt

        for s in s.split(';'):
            s = self.source_file.prepare_source(s.strip())
            if not s:
                continue
            elif s.startswith('@'):
                scope = None
                properties = []
                children = deque()
                rule = SassRule(self.source_file, namespace=self.namespace, legacy_compiler_options=self.legacy_compiler_options, properties=properties)
                block = UnparsedBlock(rule, 1, s, None)
                code, name = (s.split(None, 1) + [''])[:2]
                if code == '@option':
                    self.compilation._at_options(self.calculator, rule, scope, block)
                    continue
                elif code == '@import':
                    self.compilation._at_import(self.calculator, rule, scope, block)
                    continue
                elif code == '@include':
                    final_cont = ''
                    self.compilation._at_include(self.calculator, rule, scope, block)
                    code = self.compilation._print_properties(properties).rstrip('\n')
                    if code:
                        final_cont += code
                    if children:
                        self.compilation.children.extendleft(children)
                        self.compilation.parse_children()
                        code = self.compilation._create_css(self.compilation.rules).rstrip('\n')
                        if code:
                            final_cont += code
                    yield final_cont
                    continue
            elif s == 'ls' or s.startswith('show(') or s.startswith('show ') or s.startswith('ls(') or s.startswith('ls '):
                m = re.match(r'(?:show|ls)(\()?\s*([^,/\\) ]*)(?:[,/\\ ]([^,/\\ )]+))*(?(1)\))', s, re.IGNORECASE)
                if m:
                    name = m.group(2)
                    code = m.group(3)
                    name = name and name.strip().rstrip('s')  # remove last 's' as in functions
                    code = code and code.strip()
                    ns = self.namespace
                    if not name:
                        yield pformat(list(sorted(['vars', 'options', 'mixins', 'functions'])))
                    elif name in ('v', 'var', 'variable'):
                        variables = dict(ns._variables)
                        if code == '*':
                            pass
                        elif code:
                            variables = dict((k, v) for k, v in variables.items() if code in k)
                        else:
                            variables = dict((k, v) for k, v in variables.items() if not k.startswith('$--'))
                        yield pformat(variables)

                    elif name in ('o', 'opt', 'option'):
                        opts = self.legacy_compiler_options
                        if code == '*':
                            pass
                        elif code:
                            opts = dict((k, v) for k, v in opts.items() if code in k)
                        else:
                            opts = dict((k, v) for k, v in opts.items())
                        yield pformat(opts)

                    elif name in ('m', 'mix', 'mixin', 'f', 'func', 'funct', 'function'):
                        if name.startswith('m'):
                            funcs = dict(ns._mixins)
                        elif name.startswith('f'):
                            funcs = dict(ns._functions)
                        if code == '*':
                            pass
                        elif code:
                            funcs = dict((k, v) for k, v in funcs.items() if code in k[0])
                        else:
                            pass
                        # TODO print source when possible
                        yield pformat(funcs)
                    continue
            elif s.startswith('$') and (':' in s or '=' in s):
                prop, value = [a.strip() for a in _prop_split_re.split(s, 1)]
                prop = self.calculator.do_glob_math(prop)
                value = self.calculator.calculate(value)
                self.namespace.set_variable(prop, value)
                continue

            # TODO respect compress?
            try:
                yield(self.calculator.calculate(s).render())
            except (SyntaxError, SassEvaluationError) as e:
                print("%s" % e, file=sys.stderr)
예제 #9
0
class SassRepl(object):
    def __init__(self, is_sass=False):
        # TODO it would be lovely to get these out of here, somehow
        self.namespace = Namespace(variables=_default_scss_vars)

        self.compiler = Compiler(namespace=self.namespace)
        self.compilation = self.compiler.make_compilation()
        self.legacy_compiler_options = {}
        self.source_file = SourceFile.from_string('',
                                                  '<shell>',
                                                  is_sass=is_sass)
        self.calculator = Calculator(self.namespace)

    def __call__(self, s):
        # TODO this is kind of invasive; surely it's possible to do this
        # without calling only private methods
        from pprint import pformat

        if s in ('exit', 'quit'):
            raise KeyboardInterrupt

        for s in s.split(';'):
            s = self.source_file.prepare_source(s.strip())
            if not s:
                continue
            elif s.startswith('@'):
                scope = None
                properties = []
                children = deque()
                rule = SassRule(
                    self.source_file,
                    namespace=self.namespace,
                    legacy_compiler_options=self.legacy_compiler_options,
                    properties=properties)
                block = UnparsedBlock(rule, 1, s, None)
                code, name = (s.split(None, 1) + [''])[:2]
                if code == '@option':
                    self.compilation._at_options(self.calculator, rule, scope,
                                                 block)
                    continue
                elif code == '@import':
                    self.compilation._at_import(self.calculator, rule, scope,
                                                block)
                    continue
                elif code == '@include':
                    final_cont = ''
                    self.compilation._at_include(self.calculator, rule, scope,
                                                 block)
                    code = self.compilation._print_properties(
                        properties).rstrip('\n')
                    if code:
                        final_cont += code
                    if children:
                        self.compilation.children.extendleft(children)
                        self.compilation.parse_children()
                        code = self.compilation._create_css(
                            self.compilation.rules).rstrip('\n')
                        if code:
                            final_cont += code
                    yield final_cont
                    continue
            elif s == 'ls' or s.startswith('show(') or s.startswith(
                    'show ') or s.startswith('ls(') or s.startswith('ls '):
                m = re.match(
                    r'(?:show|ls)(\()?\s*([^,/\\) ]*)(?:[,/\\ ]([^,/\\ )]+))*(?(1)\))',
                    s, re.IGNORECASE)
                if m:
                    name = m.group(2)
                    code = m.group(3)
                    name = name and name.strip().rstrip(
                        's')  # remove last 's' as in functions
                    code = code and code.strip()
                    ns = self.namespace
                    if not name:
                        yield pformat(
                            list(
                                sorted(
                                    ['vars', 'options', 'mixins',
                                     'functions'])))
                    elif name in ('v', 'var', 'variable'):
                        variables = dict(ns._variables)
                        if code == '*':
                            pass
                        elif code:
                            variables = dict((k, v)
                                             for k, v in variables.items()
                                             if code in k)
                        else:
                            variables = dict((k, v)
                                             for k, v in variables.items()
                                             if not k.startswith('$--'))
                        yield pformat(variables)

                    elif name in ('o', 'opt', 'option'):
                        opts = self.legacy_compiler_options
                        if code == '*':
                            pass
                        elif code:
                            opts = dict(
                                (k, v) for k, v in opts.items() if code in k)
                        else:
                            opts = dict((k, v) for k, v in opts.items())
                        yield pformat(opts)

                    elif name in ('m', 'mix', 'mixin', 'f', 'func', 'funct',
                                  'function'):
                        if name.startswith('m'):
                            funcs = dict(ns._mixins)
                        elif name.startswith('f'):
                            funcs = dict(ns._functions)
                        if code == '*':
                            pass
                        elif code:
                            funcs = dict((k, v) for k, v in funcs.items()
                                         if code in k[0])
                        else:
                            pass
                        # TODO print source when possible
                        yield pformat(funcs)
                    continue
            elif s.startswith('$') and (':' in s or '=' in s):
                prop, value = [a.strip() for a in _prop_split_re.split(s, 1)]
                prop = self.calculator.do_glob_math(prop)
                value = self.calculator.calculate(value)
                self.namespace.set_variable(prop, value)
                continue

            # TODO respect compress?
            try:
                yield (self.calculator.calculate(s).render())
            except (SyntaxError, SassEvaluationError) as e:
                print("%s" % e, file=sys.stderr)
예제 #10
0
#! /usr/bin/env python3

from scss.namespace import Namespace
from scss.types import String
from scss import compiler
import glob
import os

scss_list = glob.glob("gnome-shell/*.scss")
print("\nSCSS_FILES:", scss_list)
for scss_path in scss_list:
	css_path = scss_path.replace("scss", "css")
	print("\nscss path:", scss_path)
	print("css path:", css_path)
	
	namespace = Namespace()
	namespace.set_variable("$variant", String("light"))
	css_data = compiler.compile_file(scss_path, namespace=namespace)
	with open(css_path, "w") as css_file:
		css_file.write(css_data)

예제 #11
0
def render_scss_file(filename, namespace):
    root_dir = os.path.dirname(filename)
    base_name, base_extension = os.path.splitext(os.path.basename(filename))
    render_filename = os.path.join(root_dir, 'render_{}.css'.format(base_name))
    with open(filename, 'r') as css_file, open(render_filename, 'w') as render_file:
        css_content = css_file.read()
        compiler = Compiler(namespace=namespace, output_style='compressed')
        render_file.write(compiler.compile_string(css_content))

for folder in os.listdir('http'):
    # Load keys
    cur_path = os.path.join('http', folder)
    with open(os.path.join(cur_path, 'settings.json'), 'r') as json_settings:
        setting_keys = json.load(json_settings)

    css_namespace = Namespace()
    for key, value in setting_keys.items():
        for base_class, scss_class in SCSS_MAP.items():
            if isinstance(value, base_class):
                css_namespace.set_variable('${}'.format(key), scss_class(value))
                break

    for item in os.listdir(os.path.join(cur_path, 'css')):
        if item.endswith('.css'):
            pass
        elif item.endswith('.scss'):
            render_scss_file(os.path.join(cur_path, 'css', item), css_namespace)
        else:
            pass