-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvpy_theme_manager.py
More file actions
378 lines (299 loc) · 13.5 KB
/
vpy_theme_manager.py
File metadata and controls
378 lines (299 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
#!/usr/bin/env python3
"""
Theme Management System for VysualPy
Provides runtime theme switching, custom CSS loading, and style management
for the editor interface and node graph system.
"""
import os
import json
from typing import Dict, List, Optional, Any
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtGui import QFont
class ThemeManager(QObject):
"""Manages theme switching and style application for VysualPy."""
# Signal emitted when theme changes
themeChanged = pyqtSignal(str) # theme_name
def __init__(self):
super().__init__()
self.config_dir = os.path.join(os.path.dirname(__file__), 'config')
self.current_theme = 'dark'
self.available_themes = ['dark', 'light', 'high_contrast']
self.custom_styles = {}
# Load theme configurations
self.load_theme_configs()
# Load current theme from config
if hasattr(self, 'theme_config') and 'current_theme' in self.theme_config:
self.current_theme = self.theme_config['current_theme']
def load_theme_configs(self):
"""Load theme configurations from config directory."""
theme_config_file = os.path.join(self.config_dir, 'themes.json')
# Create default theme config if it doesn't exist
if not os.path.exists(theme_config_file):
self.create_default_theme_config()
try:
with open(theme_config_file, 'r', encoding='utf-8') as f:
self.theme_config = json.load(f)
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Error loading theme config: {e}")
self.theme_config = self.get_default_theme_config()
def create_default_theme_config(self):
"""Create default theme configuration file."""
default_config = self.get_default_theme_config()
theme_config_file = os.path.join(self.config_dir, 'themes.json')
try:
with open(theme_config_file, 'w', encoding='utf-8') as f:
json.dump(default_config, f, indent=4)
except Exception as e:
print(f"Error creating default theme config: {e}")
def get_default_theme_config(self) -> Dict[str, Any]:
"""Get default theme configuration."""
return {
"themes": {
"dark": {
"name": "Dark Theme",
"description": "Professional dark theme for coding",
"colors": {
"background": "#2d3748",
"foreground": "#e2e8f0",
"accent": "#4a5568",
"highlight": "#718096",
"selection": "#4a5568"
},
"fonts": {
"editor": {
"family": "Courier New",
"size": 11,
"weight": "normal"
},
"ui": {
"family": "Segoe UI",
"size": 9,
"weight": "normal"
}
}
},
"light": {
"name": "Light Theme",
"description": "Clean light theme for day work",
"colors": {
"background": "#ffffff",
"foreground": "#2d3748",
"accent": "#e2e8f0",
"highlight": "#bee3f8",
"selection": "#bee3f8"
},
"fonts": {
"editor": {
"family": "Courier New",
"size": 11,
"weight": "normal"
},
"ui": {
"family": "Segoe UI",
"size": 9,
"weight": "normal"
}
}
},
"high_contrast": {
"name": "High Contrast",
"description": "Accessibility-focused high contrast theme",
"colors": {
"background": "#000000",
"foreground": "#ffffff",
"accent": "#ffffff",
"highlight": "#ffff00",
"selection": "#ffffff"
},
"fonts": {
"editor": {
"family": "Courier New",
"size": 12,
"weight": "bold"
},
"ui": {
"family": "Segoe UI",
"size": 10,
"weight": "bold"
}
}
}
},
"current_theme": "dark",
"custom_css_enabled": True,
"font_scaling": 1.0
}
def get_available_themes(self) -> List[str]:
"""Get list of available theme names."""
if hasattr(self, 'theme_config') and 'themes' in self.theme_config:
return list(self.theme_config['themes'].keys())
return self.available_themes
def get_theme_info(self, theme_name: str) -> Dict[str, Any]:
"""Get theme information by name."""
if hasattr(self, 'theme_config') and 'themes' in self.theme_config:
return self.theme_config['themes'].get(theme_name, {})
return {}
def set_theme(self, theme_name: str) -> bool:
"""Set the current theme."""
if theme_name not in self.get_available_themes():
print(f"Theme '{theme_name}' not found")
return False
self.current_theme = theme_name
self.apply_theme()
self.themeChanged.emit(theme_name)
# Save current theme to config
if hasattr(self, 'theme_config'):
self.theme_config['current_theme'] = theme_name
self.save_theme_config()
return True
def apply_theme(self):
"""Apply the current theme to the application."""
css_content = self.load_theme_css()
if css_content:
app = QApplication.instance()
if app:
app.setStyleSheet(css_content)
def load_theme_css(self) -> str:
"""Load CSS content for current theme."""
css_file = os.path.join(self.config_dir, 'editor_style.css')
if not os.path.exists(css_file):
return ""
try:
with open(css_file, 'r', encoding='utf-8') as f:
css_content = f.read()
# Apply theme-specific modifications
css_content = self.customize_css_for_theme(css_content)
return css_content
except Exception as e:
print(f"Error loading CSS file: {e}")
return ""
def customize_css_for_theme(self, css_content: str) -> str:
"""Customize CSS content based on current theme."""
theme_info = self.get_theme_info(self.current_theme)
if not theme_info or 'colors' not in theme_info:
return css_content
# Replace color variables based on theme
colors = theme_info['colors']
# Simple color replacement - in a production system, you'd want
# more sophisticated CSS variable replacement
replacements = {
'#2d3748': colors.get('background', '#2d3748'),
'#e2e8f0': colors.get('foreground', '#e2e8f0'),
'#4a5568': colors.get('accent', '#4a5568'),
'#718096': colors.get('highlight', '#718096'),
}
for old_color, new_color in replacements.items():
css_content = css_content.replace(old_color, new_color)
return css_content
def get_editor_font(self) -> QFont:
"""Get the font configuration for the editor."""
theme_info = self.get_theme_info(self.current_theme)
if theme_info and 'fonts' in theme_info and 'editor' in theme_info['fonts']:
font_info = theme_info['fonts']['editor']
font = QFont(font_info.get('family', 'Courier New'))
font.setPointSize(int(font_info.get('size', 11)))
weight = font_info.get('weight', 'normal')
if weight == 'bold':
font.setBold(True)
return font
# Default font
return QFont('Courier New', 11)
def get_ui_font(self) -> QFont:
"""Get the font configuration for UI elements."""
theme_info = self.get_theme_info(self.current_theme)
if theme_info and 'fonts' in theme_info and 'ui' in theme_info['fonts']:
font_info = theme_info['fonts']['ui']
font = QFont(font_info.get('family', 'Segoe UI'))
font.setPointSize(int(font_info.get('size', 9)))
weight = font_info.get('weight', 'normal')
if weight == 'bold':
font.setBold(True)
return font
# Default font
return QFont('Segoe UI', 9)
def add_custom_style(self, widget_name: str, css_rules: str):
"""Add custom CSS rules for specific widgets."""
self.custom_styles[widget_name] = css_rules
self.apply_theme() # Re-apply theme with custom styles
def remove_custom_style(self, widget_name: str):
"""Remove custom CSS rules for a widget."""
if widget_name in self.custom_styles:
del self.custom_styles[widget_name]
self.apply_theme() # Re-apply theme without custom styles
def get_theme_colors(self) -> Dict[str, str]:
"""Get color palette for current theme."""
theme_info = self.get_theme_info(self.current_theme)
return theme_info.get('colors', {})
def save_theme_config(self):
"""Save current theme configuration to file."""
theme_config_file = os.path.join(self.config_dir, 'themes.json')
try:
with open(theme_config_file, 'w', encoding='utf-8') as f:
json.dump(self.theme_config, f, indent=4)
except Exception as e:
print(f"Error saving theme config: {e}")
def create_custom_theme(self, theme_name: str, theme_data: Dict[str, Any]) -> bool:
"""Create a new custom theme."""
if not hasattr(self, 'theme_config'):
self.theme_config = self.get_default_theme_config()
if 'themes' not in self.theme_config:
self.theme_config['themes'] = {}
self.theme_config['themes'][theme_name] = theme_data
self.save_theme_config()
return True
def delete_custom_theme(self, theme_name: str) -> bool:
"""Delete a custom theme (cannot delete built-in themes)."""
builtin_themes = ['dark', 'light', 'high_contrast']
if theme_name in builtin_themes:
print(f"Cannot delete built-in theme: {theme_name}")
return False
if hasattr(self, 'theme_config') and 'themes' in self.theme_config:
if theme_name in self.theme_config['themes']:
del self.theme_config['themes'][theme_name]
self.save_theme_config()
# Switch to default theme if we deleted the current theme
if self.current_theme == theme_name:
self.set_theme('dark')
return True
return False
# Global theme manager instance
theme_manager = ThemeManager()
def get_theme_manager() -> ThemeManager:
"""Get the global theme manager instance."""
return theme_manager
def apply_theme_to_widget(widget, theme_colors: Optional[Dict[str, str]] = None):
"""Apply current theme colors to a specific widget."""
if theme_colors is None:
theme_colors = theme_manager.get_theme_colors()
if not theme_colors:
return
# Apply basic styling based on theme colors
style = f"""
QWidget {{
background-color: {theme_colors.get('background', '#2d3748')};
color: {theme_colors.get('foreground', '#e2e8f0')};
}}
"""
widget.setStyleSheet(style)
if __name__ == "__main__":
# Test the theme manager
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QVBoxLayout, QWidget
app = QApplication(sys.argv)
# Create test window
window = QMainWindow()
window.setWindowTitle("Theme Manager Test")
central_widget = QWidget()
layout = QVBoxLayout(central_widget)
text_edit = QTextEdit()
text_edit.setText("This is a test of the theme system.\nColors should change when theme is switched.")
layout.addWidget(text_edit)
window.setCentralWidget(central_widget)
# Apply initial theme
theme_manager.apply_theme()
# Show window
window.show()
print(f"Available themes: {theme_manager.get_available_themes()}")
print(f"Current theme: {theme_manager.current_theme}")
app.exec_()