Debian Codegraph @

libs/CCAppCommon/QDarkStyleSheet/qdarkstyle/utils/scss.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 """Utilities for compiling SASS files."""
4
5 # Standard library imports
6 import keyword
7 import logging
8 import os
9 import re
10 import shutil
11 import sys
12
13 # Third party imports
14 import qtsass
15
16 # Local imports
17 from qdarkstyle import (MAIN_SCSS_FILE, PACKAGE_PATH, QSS_FILE_SUFFIX, QSS_PATH,
18 VARIABLES_SCSS_FILE)
19 from qdarkstyle.palette import Palette
20 from qdarkstyle.utils.images import create_images, create_palette_image
21
22 # Constants
23 HEADER_SCSS = '''// ---------------------------------------------------------------------------
24 //
25 // WARNING! File created programmatically. All changes made in this file will be lost!
26 //
27 // Created by the qtsass compiler v{}
28 //
29 // The definitions are in the "qdarkstyle.palette" module
30 //
31 //----------------------------------------------------------------------------
32 '''
33
34 HEADER_QSS = '''/* ---------------------------------------------------------------------------
35
36 WARNING! File created programmatically. All changes made in this file will be lost!
37
38 Created by the qtsass compiler v{}
39
40 The definitions are in the "qdarkstyle.qss._styles.scss" module
41
42 --------------------------------------------------------------------------- */
43 '''
44
45 _logger = logging.getLogger(__name__)
46
47
48 def _dict_to_scss(data):
49 """Create a scss variables string from a dict."""
50 lines = []
51 template = "${}: {};"
52 for key, value in data.items():
53 line = template.format(key, value)
54 lines.append(line)
55
56 return '\n'.join(lines)
57
58
59 def _scss_to_dict(string):
60 """Parse variables and return a dict."""
61 data = {}
62 lines = string.split('\n')
63
64 for line in lines:
65 line = line.strip()
66
67 if line and line.startswith('$'):
68 key, value = line.split(':')
69 key = key[1:].strip()
70 key = key.replace('-', '_')
71 value = value.split(';')[0].strip()
72
73 data[key] = value
74
75 return data
76
77
78 def _create_scss_variables(variables_scss_filepath, palette,
79 header=HEADER_SCSS):
80 """Create a scss variables file."""
81
82 scss = _dict_to_scss(palette.to_dict())
83 data = header.format(qtsass.__version__) + scss + '\n'
84
85 _logger.info("Generating SCSS variables file ...")
86 _logger.info(f"File path: {variables_scss_filepath}")
87
88 with open(variables_scss_filepath, 'w') as f:
89 f.write(data)
90
91
92 def _create_qss(main_scss_path, qss_filepath, header=HEADER_QSS):
93 """Create a styles.qss file from qtsass."""
94
95 data = ''
96
97 _logger.info("Generating QSS file ...")
98 _logger.info(f"SCSS path: {main_scss_path}")
99 _logger.info(f"QSS path: {qss_filepath}")
100
101 qtsass.compile_filename(main_scss_path, qss_filepath,
102 output_style='expanded')
103
104 with open(qss_filepath, 'r') as f:
105 data = f.read()
106
107 data = header.format(qtsass.__version__) + data
108
109 with open(qss_filepath, 'w') as f:
110 f.write(data)
111
112 return data
113
114
115 def create_qss(palette, base_path=''):
116 """Create variables files and run qtsass compilation.
117
118 This function will use the structure that must contain::
119
120 base_path
121 [palette.ID]
122 main.scss
123 qss
124 _style.scss
125
126 The structure after the execution will contain::
127
128 base_path
129 [palette.ID]
130 _variables.scss
131 [palette.ID]style.qss
132 main.scss
133 qss
134 _style.scss
135
136 Args:
137 palette (Palette): Palette class.
138 base_path (str): Base path for the palette directory, required for
139 custom palettes. Defaults to '' that uses `[PACKAGE_PATH]`.
140
141 Returns:
142 str: Stylesheet in string format.
143 """
144
145 if palette.ID is None:
146 print("A QDarkStyle palette requires an ID!")
147 sys.exit(1)
148
149 palette_path = os.path.join(PACKAGE_PATH, palette.ID)
150
151 if base_path:
152 palette_path = os.path.join(base_path, palette.ID)
153
154 _logger.info(f"Creating QSS for palette: '{palette.ID} ...")
155 _logger.info(f"Palette path: {palette_path}")
156
157 variables_scss_filepath = os.path.join(palette_path, VARIABLES_SCSS_FILE)
158 main_scss_filepath = os.path.join(palette_path, MAIN_SCSS_FILE)
159 qss_filepath = os.path.join(palette_path, palette.ID + QSS_FILE_SUFFIX)
160
161 _create_scss_variables(variables_scss_filepath, palette)
162
163 stylesheet = _create_qss(main_scss_filepath, qss_filepath)
164
165 return stylesheet
166
167
168 def create_custom_qss(
169 id,
170 path,
171 color_backgroung=[], # 6 elements
172 color_text=[], # 4 elements
173 color_accent=[], # 4 elemetns
174 border=[], # 3 elements
175 border_selection=[], # 3 elements
176 opacity_tooltip=None,
177 size_border_radius=None,
178 w_status_bar_background_color=None,
179 path_resources=None
180 ):
181 """
182 Create a custom palette based on the parameters defined.
183
184 The `id` must be a valid Python identifier and will be stored
185 as a lowercased folder (even if the identifier had uppercase letters).
186
187 This function returns the custom stylesheet pointing to resources stored
188 at path_resources/[id].
189 """
190
191 stylesheet = ''
192
193 # Check if name/id is valid
194 if id.isidentifier():
195 name = id if id[0].isupper() else id.capitalize()
196 else:
197 raise Exception('The custom palette name must be a valid Python '
198 'identifier!')
199
200 # Copy resources folder
201 rc_loc = os.path.basename(RC_PATH)
202 qss_loc = os.path.basename(QSS_PATH)
203 theme_root_path = os.path.join(path, name.lower())
204 theme_rc_path = os.path.join(theme_root_path, rc_loc)
205
206 if os.path.isdir(theme_root_path):
207 shutil.rmtree(theme_root_path)
208
209 shutil.copytree(RC_PATH, theme_rc_path)
210
211 # Copy QSS folder and contents
212 theme_qss_path = os.path.join(theme_root_path, qss_loc)
213
214 if os.path.isdir(theme_qss_path):
215 os.removedirs(theme_qss_path)
216
217 shutil.copytree(QSS_PATH, theme_qss_path)
218
219 # Create custom palette
220 # ATTENTION: here we need to iterate over
221 # args of this function to fill the values
222 # of the Palette class member with correct values
223 # they still using the old values below
224 custom_palette = type(name, (Palette, ), {})
225 custom_palette.COLOR_BACKGROUND_LIGHT = color_background_light
226 custom_palette.COLOR_BACKGROUND_NORMAL = color_background_normal
227 custom_palette.COLOR_BACKGROUND_DARK = color_background_dark
228 custom_palette.COLOR_FOREGROUND_LIGHT = color_foreground_light
229 custom_palette.COLOR_FOREGROUND_NORMAL = color_foreground_normal
230 custom_palette.COLOR_FOREGROUND_DARK = color_foreground_dark
231 custom_palette.COLOR_SELECTION_LIGHT = color_selection_light
232 custom_palette.COLOR_SELECTION_NORMAL = color_selection_normal
233 custom_palette.COLOR_SELECTION_DARK = color_selection_dark
234 custom_palette.SIZE_BORDER_RADIUS = border_radius
235 custom_palette.PATH_RESOURCES = "'{}'".format(theme_root_path)
236
237 # Process images and save them to the custom platte rc folder
238 create_images(rc_path=theme_rc_path, palette=custom_palette)
239 create_palette_image(path=theme_root_path, palette=custom_palette)
240
241 # Compile SCSS
242 variables_scss_filepath = os.path.join(theme_qss_path, VARIABLES_SCSS_FILE)
243 theme_main_scss_filepath = os.path.join(theme_qss_path, MAIN_SCSS_FILE)
244 theme_qss_filepath = os.path.join(theme_root_path, palette.ID + QSS_FILE_SUFFIX)
245
246 stylesheet = create_qss(
247 qss_filepath=theme_qss_filepath,
248 main_scss_filepath=theme_main_scss_filepath,
249 variables_scss_filepath=variables_scss_filepath,
250 palette=custom_palette,
251 )
252
253 # Update colors in text
254 with open(theme_main_scss_filepath, 'r') as fh:
255 data = fh.read()
256
257 for key, color in Palette.color_palette().items():
258 custom_color = custom_palette.color_palette()[key].upper()
259 data = data.replace(color, custom_color)
260 stylesheet = stylesheet.replace(color, custom_color)
261
262 with open(theme_main_scss_filepath, 'w') as fh:
263 fh.write(data)
264
265 with open(theme_qss_filepath, 'w') as fh:
266 fh.write(stylesheet)
267
268 return stylesheet
269
270
271 def create_custom_qss_from_palette(name, path, palette):
272 """
273 Create a custom palette based on a palette class.
274 """
275 kwargs = {
276 'name': name,
277 'path': path,
278 'border_radius': palette.SIZE_BORDER_RADIUS,
279 }
280 kwargs.update(palette.color_palette())
281 stylesheet = create_custom_qss(**kwargs)
282
283 return stylesheet
284
285
286 def create_custom_qss_from_dict(name, path, palette_dict):
287 """
288 Create a custom palette based on a palette dictionary.
289 """
290 kwargs = {
291 'name': name,
292 'path': path,
293 'border_radius': palette_dict.get('SIZE_BORDER_RADIUS', '4px'),
294 }
295 kwargs.update(palette_dict)
296 stylesheet = create_custom_qss(**kwargs)
297
298 return stylesheet
299
300
301 if __name__ == '__main__':
302 # Example of a custom palette
303 # TODO: change to not use a specific path
304 # TODO: may move to other place, e.g., example.py
305 qss = create_custom_qss(
306 'MyAwesomePalette',
307 '/Users/gpena-castellanos/Desktop',
308 '#ff0000',
309 '#cc0000',
310 '#aa0000',
311 '#00ff00',
312 '#00cc00',
313 '#00aa00',
314 '#0000ff',
315 '#0000cc',
316 '#0000aa',
317 '0px',
318 )