|
| 1 | +import sass |
| 2 | +import argparse |
| 3 | +import logging |
| 4 | + |
| 5 | +logging.basicConfig(level=logging.DEBUG) |
| 6 | +logger = logging.getLogger(__name__) |
| 7 | + |
| 8 | + |
| 9 | +def rgba(r, g, b, a): |
| 10 | + result = "rgba({}, {}, {}, {}%)" |
| 11 | + if isinstance(r, sass.SassNumber): |
| 12 | + return result.format(int(r.value), int(g.value), int(b.value), int(a.value)*100) |
| 13 | + elif isinstance(r, float): |
| 14 | + return result.format(int(r), int(g), int(b), int(a)*100) |
| 15 | + |
| 16 | + |
| 17 | +def rgba_from_color(color): |
| 18 | + """ |
| 19 | + Conform rgba |
| 20 | + :type color: sass.SassColor |
| 21 | + """ |
| 22 | + return rgba(color.r, color.g, color.b, color.a) |
| 23 | + |
| 24 | + |
| 25 | +def qlineargradient(x1, y1, x2, y2, stops): |
| 26 | + """ |
| 27 | + :type x1: sass.SassNumber |
| 28 | + :type y1: sass.SassNumber |
| 29 | + :type x2: sass.SassNumber |
| 30 | + :type y2: sass.SassNumber |
| 31 | + :type stops: sass.SassList |
| 32 | + :return: |
| 33 | + """ |
| 34 | + stops_str = "" |
| 35 | + for stop in stops[0]: |
| 36 | + pos, color = stop[0] |
| 37 | + stops_str += " stop: {} {}".format(pos.value, rgba_from_color(color)) |
| 38 | + |
| 39 | + return "qlineargradient(x1:{}, y1:{}, x2:{}, y2:{} {})".format(x1.value, y1.value, x2.value, y2.value, stops_str.rstrip(",")) |
| 40 | + |
| 41 | + |
| 42 | +def css_conform(input_file): |
| 43 | + with open(input_file, "r") as f: |
| 44 | + # Remove "!" in selectors |
| 45 | + input_str = f.read().replace(":!", ":_qnot_") |
| 46 | + return input_str |
| 47 | + |
| 48 | + |
| 49 | +def qt_conform(input_str): |
| 50 | + """ |
| 51 | + :param input_str: |
| 52 | + :type input_str: string |
| 53 | + :return: |
| 54 | + """ |
| 55 | + conformed = input_str.replace(":_qnot_", ":!") |
| 56 | + return conformed |
| 57 | + |
| 58 | + |
| 59 | +def compile_to_css(input_file): |
| 60 | + return qt_conform(sass.compile(string=css_conform(input_file), |
| 61 | + source_comments=False, |
| 62 | + custom_functions={ |
| 63 | + 'qlineargradient': qlineargradient, |
| 64 | + 'rgba': rgba |
| 65 | + } |
| 66 | + ) |
| 67 | + ) |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + parser = argparse.ArgumentParser(prog="QtSASS", |
| 72 | + description="Compile a Qt compliant CSS file from a SCSS stylesheet.", |
| 73 | + ) |
| 74 | + parser.add_argument('input', type=str, help="The SCSS stylesheet file.") |
| 75 | + parser.add_argument('-o', '--output', type=str, help="The path of the generated Qt compliant CSS file.") |
| 76 | + |
| 77 | + args = parser.parse_args() |
| 78 | + |
| 79 | + stylesheet = compile_to_css(args.input) |
| 80 | + |
| 81 | + if args.output: |
| 82 | + with open(args.output, 'w') as css_file: |
| 83 | + css_file.write(stylesheet) |
| 84 | + logger.info("Created CSS file {}".format(args.output)) |
| 85 | + else: |
| 86 | + print(stylesheet) |
0 commit comments