-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoverlayThemeManager.js
More file actions
3318 lines (2843 loc) · 138 KB
/
overlayThemeManager.js
File metadata and controls
3318 lines (2843 loc) · 138 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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* overlayThemeManager.js
*
* CSS Gnommé Extension Module - GNOME 46+
* Dynamic theme overlay system with CSS generation
*/
import GLib from "gi://GLib";
import Gio from "gi://Gio";
import System from "system";
import { Constants } from "./constants.js";
import { CSSTemplates } from "./cssTemplates.js";
import { ThemeUtils } from "./themeUtils.js";
import { GlobalSignalsHandler } from "./signalHandler.js";
/* overlayThemeManager.js
*
* GTK Theme Overlay Manager for CSSGnomme
* Creates non-destructive theme overlays with symlinks and custom CSS
*/
export class OverlayThemeManager {
constructor(extensionName = "CSSGnomme", logger = null) {
this.extensionName = extensionName;
this.overlayName = extensionName;
this.overlayPath = `${GLib.get_home_dir()}/.themes/${this.overlayName}`;
this.metadataFile = `${this.overlayPath}/index.theme`;
// Use provided logger or create fallback
if (logger) {
this._logger = logger;
} else {
// Fallback if no logger provided
this._logger = {
info: msg => log(`[CSSGnomme:OverlayTheme:INFO] ${msg}`),
warn: msg => log(`[CSSGnomme:OverlayTheme:WARN] ${msg}`),
error: msg => log(`[CSSGnomme:OverlayTheme:ERROR] ${msg}`),
debug: msg => log(`[CSSGnomme:OverlayTheme:DEBUG] ${msg}`)
};
}
// Settings singleton instances (prevent memory leaks)
this._interfaceSettings = null;
this._shellSettings = null;
// CSS template system for string pooling (memory optimization)
this._cssTemplates = new CSSTemplates();
// Track pending GLib timers for cleanup (prevent memory leaks)
this._pendingTimers = [];
// Centralized signal management (ready for future file watchers or settings monitoring)
this._signalsHandler = new GlobalSignalsHandler();
// Base theme CSS cache (TIER 1 optimization - processed source CSS)
// Cache key format: "gtk-base:ThemeName:version:light|dark:tintStrength"
// "shell-base:ThemeName:tintStrength"
// Invalidated only on source theme change or tint strength adjustment
this._baseThemeCache = new Map();
this._baseThemeCacheStats = { hits: 0, misses: 0 };
this._baseThemeCacheMaxSize = Constants.CACHE_LIMITS.baseTheme;
// Component CSS cache (TIER 2 optimization - Shell CSS components)
// Cache key format: "component-name:hash-of-relevant-settings"
// Components: panel, popup, zorin, fluent
// Invalidated when relevant settings change (smart invalidation)
this._componentCssCache = new Map();
this._componentCacheStats = { hits: 0, misses: 0 };
this._componentCacheMaxSize = Constants.CACHE_LIMITS.componentCss;
// Accent color cache (TIER 3 optimization - theme accent color parsing)
// Cache key format: "themePath:colorScheme"
// Example: "/usr/share/themes/ZorinBlue-Dark:prefer-dark"
// Invalidated on source theme change or extension disable
// Benefit: 6x speedup (6ms → 1ms per CSS update with 6 accent detection calls)
this._accentColorCache = new Map();
this._accentCacheStats = { hits: 0, misses: 0 };
this._logger.info("OverlayThemeManager initialized (sync mode)");
}
// ===== SETTINGS SINGLETON GETTERS =====
/**
* Get org.gnome.desktop.interface Settings singleton
* @returns {Gio.Settings} Interface settings instance
*/
_getInterfaceSettings() {
if (!this._interfaceSettings) {
this._interfaceSettings = new Gio.Settings({ schema: "org.gnome.desktop.interface" });
}
return this._interfaceSettings;
}
/**
* Get org.gnome.shell.extensions.user-theme Settings singleton
* @returns {Gio.Settings} Shell theme settings instance
*/
_getShellSettings() {
if (!this._shellSettings) {
const shellThemeSchema = "org.gnome.shell.extensions.user-theme";
this._shellSettings = new Gio.Settings({ schema: shellThemeSchema });
}
return this._shellSettings;
}
// ===== THEME DISCOVERY =====
/**
* Discover source theme location and validate
* Searches in standard GTK theme locations
* @param {string} themeName - Name of the source theme
* @returns {string|null} Full path to theme or null if not found
*/
discoverSourceTheme(themeName) {
const locations = [
`${GLib.get_home_dir()}/.themes/${themeName}`,
`${GLib.get_home_dir()}/.local/share/themes/${themeName}`,
`/usr/share/themes/${themeName}`,
`/usr/local/share/themes/${themeName}`
];
for (const path of locations) {
const themeDir = Gio.File.new_for_path(path);
if (themeDir.query_exists(null)) {
this._logger.info(` Found source theme at: ${path}`);
return path;
}
}
this._logger.info(` Source theme ${themeName} not found in any location`);
return null;
}
/**
* Get list of available themes from all locations
* @returns {Array} Array of theme names
*/
getAvailableThemes() {
const themes = new Set();
const locations = [
`${GLib.get_home_dir()}/.themes`,
`${GLib.get_home_dir()}/.local/share/themes`,
"/usr/share/themes",
"/usr/local/share/themes"
];
locations.forEach(location => {
const dir = Gio.File.new_for_path(location);
if (!dir.query_exists(null)) return;
try {
const enumerator = dir.enumerate_children(
"standard::name,standard::type",
Gio.FileQueryInfoFlags.NONE,
null
);
try {
let fileInfo;
while ((fileInfo = enumerator.next_file(null)) !== null) {
if (fileInfo.get_file_type() === Gio.FileType.DIRECTORY) {
const themeName = fileInfo.get_name();
// Skip our overlay theme
if (themeName !== this.overlayName) {
themes.add(themeName);
}
}
}
} finally {
enumerator.close(null);
}
} catch (e) {
// Ignore permission errors
}
});
return Array.from(themes).sort();
}
/**
* Detect GTK versions and their structure in source theme
* @param {string} sourcePath - Path to source theme
* @returns {Object} Object with gtk-3.0 and gtk-4.0 info
*/
detectGtkVersions(sourcePath) {
const versions = {};
["gtk-3.0", "gtk-4.0"].forEach(version => {
const gtkDir = Gio.File.new_for_path(`${sourcePath}/${version}`);
versions[version] = {
exists: gtkDir.query_exists(null),
hasGtkCss: false,
hasDarkCss: false,
assets: []
};
if (versions[version].exists) {
// Check for gtk.css
const gtkCss = Gio.File.new_for_path(`${sourcePath}/${version}/gtk.css`);
versions[version].hasGtkCss = gtkCss.query_exists(null);
// Check for gtk-dark.css
const darkCss = Gio.File.new_for_path(`${sourcePath}/${version}/gtk-dark.css`);
versions[version].hasDarkCss = darkCss.query_exists(null);
// List all assets/subdirectories
try {
const enumerator = gtkDir.enumerate_children(
"standard::name,standard::type",
Gio.FileQueryInfoFlags.NONE,
null
);
try {
let fileInfo;
while ((fileInfo = enumerator.next_file(null)) !== null) {
const name = fileInfo.get_name();
// Skip CSS files we'll override
if (name !== "gtk.css" && name !== "gtk-dark.css") {
versions[version].assets.push(name);
}
}
} finally {
enumerator.close(null);
}
} catch (e) {
this._logger.info(` Error listing ${version} assets: ${e}`);
}
}
});
return versions;
}
/**
* Detect GNOME Shell theme structure in source
* @param {string} sourcePath - Path to source theme
* @returns {Object} Shell theme info
*/
detectShellTheme(sourcePath) {
const shellDir = Gio.File.new_for_path(`${sourcePath}/gnome-shell`);
const shellInfo = {
exists: shellDir.query_exists(null),
hasShellCss: false,
hasPadOsdCss: false,
assets: []
};
if (!shellInfo.exists) {
return shellInfo;
}
// Check for gnome-shell.css (main file)
const shellCss = Gio.File.new_for_path(`${sourcePath}/gnome-shell/gnome-shell.css`);
shellInfo.hasShellCss = shellCss.query_exists(null);
// Check for pad-osd.css (on-screen display for drawing tablets)
const padOsdCss = Gio.File.new_for_path(`${sourcePath}/gnome-shell/pad-osd.css`);
shellInfo.hasPadOsdCss = padOsdCss.query_exists(null);
// List all assets to symlink
try {
const enumerator = shellDir.enumerate_children(
"standard::name,standard::type",
Gio.FileQueryInfoFlags.NONE,
null
);
try {
let fileInfo;
while ((fileInfo = enumerator.next_file(null)) !== null) {
const name = fileInfo.get_name();
// Skip CSS files we'll override
if (name !== "gnome-shell.css" && name !== "pad-osd.css") {
shellInfo.assets.push(name);
}
}
} finally {
enumerator.close(null);
}
} catch (e) {
this._logger.error(` Error listing shell assets: ${e}`);
}
this._logger.info(
` Shell theme detected: shellCss=${shellInfo.hasShellCss}, padOsd=${shellInfo.hasPadOsdCss}, assets=${shellInfo.assets.length}`
);
return shellInfo;
}
/**
* Get all non-GTK directories from source theme for symlinking
* @param {string} sourcePath - Path to source theme
* @returns {Array} Array of directory names
*/
getNonGtkDirectories(sourcePath) {
const sourceDir = Gio.File.new_for_path(sourcePath);
const directories = [];
if (!sourceDir.query_exists(null)) {
return directories;
}
try {
const enumerator = sourceDir.enumerate_children(
"standard::name,standard::type",
Gio.FileQueryInfoFlags.NONE,
null
);
try {
let fileInfo;
while ((fileInfo = enumerator.next_file(null)) !== null) {
if (fileInfo.get_file_type() === Gio.FileType.DIRECTORY) {
const name = fileInfo.get_name();
// Exclude gtk-*, gnome-shell (we handle separately), and metadata
if (!name.match(/^gtk-\d/) && name !== "gnome-shell" && name !== "index.theme") {
directories.push(name);
}
}
}
} finally {
enumerator.close(null);
}
} catch (e) {
this._logger.info(` Error listing source directories: ${e}`);
}
return directories;
}
// ===== OVERLAY CREATION =====
/**
* Create complete overlay theme structure
* Uses sync file operations for simplicity and speed
* @param {string} sourceThemeName - Name of source theme to overlay
* @param {Object} settings - Extension settings object
* @param {Gio.Settings} interfaceSettings - GNOME interface settings (optional, for saving original themes)
* @returns {boolean} Success status
*/
createOverlayTheme(sourceThemeName, settings, interfaceSettings = null) {
const sourcePath = this.discoverSourceTheme(sourceThemeName);
if (!sourcePath) {
this._logger.info(` Cannot create overlay - source theme not found`);
return false;
}
// Check if source theme changed - invalidate base theme cache
const metadata = this.readIndexTheme();
if (metadata && metadata[`X-${this.extensionName}-Extension`]) {
const previousSourceTheme = metadata[`X-${this.extensionName}-Extension`].SourceTheme;
if (previousSourceTheme && previousSourceTheme !== sourceThemeName) {
this._logger.info(
`🔄 Source theme changed (${previousSourceTheme} → ${sourceThemeName}) - clearing base theme cache`
);
this._baseThemeCache.clear();
this._baseThemeCacheStats = { hits: 0, misses: 0 };
// Clear accent color cache on source theme change
this._clearAccentColorCache();
}
}
// ← FIX: Read original themes BEFORE checking if overlay active
// This prevents circular bug where OriginalGtkTheme = "CSSGnomme"
let originalGtkTheme = sourceThemeName; // Fallback
let originalShellTheme = sourceThemeName; // Fallback
// Parse icon theme from source GTK theme's index.theme (designer's intent)
let originalIconTheme = this._parseSourceIconTheme(sourcePath);
if (interfaceSettings) {
const currentGtkTheme = interfaceSettings.get_string("gtk-theme");
// ← FIX: If current theme is overlay, read from existing metadata
if (currentGtkTheme === this.overlayName) {
const metadata = this.readIndexTheme();
if (metadata && metadata[`X-${this.extensionName}-Extension`]) {
originalGtkTheme =
metadata[`X-${this.extensionName}-Extension`].OriginalGtkTheme || sourceThemeName;
originalShellTheme =
metadata[`X-${this.extensionName}-Extension`].OriginalShellTheme || sourceThemeName;
originalIconTheme =
metadata[`X-${this.extensionName}-Extension`].OriginalIconTheme || originalIconTheme;
this._logger.info(
` Preserved original themes from metadata: GTK=${originalGtkTheme}, Icon=${originalIconTheme}`
);
} else {
// No metadata, use sourceThemeName as fallback
originalGtkTheme = sourceThemeName;
// originalIconTheme already set from _parseSourceIconTheme above
this._logger.warn(
` Overlay active but no metadata found - likely switching to new theme (${sourceThemeName})`
);
}
} else {
// Not using overlay, save current themes as originals
originalGtkTheme = currentGtkTheme;
// originalIconTheme already set from _parseSourceIconTheme above (designer's intent)
this._logger.info(
` Saved current GTK theme as original: GTK=${originalGtkTheme}, Icon=${originalIconTheme} (from source theme)`
);
}
try {
const shellThemeSettings = new Gio.Settings({
schema: "org.gnome.shell.extensions.user-theme"
});
const currentShellTheme = shellThemeSettings.get_string("name");
this._logger.debug(` Current Shell theme from user-theme extension: '${currentShellTheme}'`);
// Same logic for Shell theme
if (currentShellTheme === this.overlayName) {
const metadata = this.readIndexTheme();
if (metadata && metadata[`X-${this.extensionName}-Extension`]) {
originalShellTheme =
metadata[`X-${this.extensionName}-Extension`].OriginalShellTheme || sourceThemeName;
this._logger.info(` Preserved original Shell theme from metadata: ${originalShellTheme}`);
} else {
originalShellTheme = sourceThemeName;
this._logger.warn(
` Overlay Shell theme active but no metadata - using sourceTheme as fallback`
);
}
} else {
originalShellTheme = currentShellTheme;
this._logger.info(` Saved current Shell theme as original: ${originalShellTheme}`);
}
} catch (e) {
originalShellTheme = originalGtkTheme; // Fallback to GTK theme
this._logger.warn(
` user-theme extension not available, using GTK theme as Shell theme: ${originalShellTheme}`
);
}
} else {
// ← FIX: If interfaceSettings not provided, read directly from GSettings
try {
const ifaceSettings = this._getInterfaceSettings();
const currentGtkTheme = ifaceSettings.get_string("gtk-theme");
const currentIconTheme = ifaceSettings.get_string("icon-theme");
// Same circular reference check
if (currentGtkTheme === this.overlayName) {
const metadata = this.readIndexTheme();
if (metadata && metadata[`X-${this.extensionName}-Extension`]) {
originalGtkTheme =
metadata[`X-${this.extensionName}-Extension`].OriginalGtkTheme || sourceThemeName;
originalIconTheme =
metadata[`X-${this.extensionName}-Extension`].OriginalIconTheme || sourceThemeName;
} else {
originalGtkTheme = sourceThemeName;
originalIconTheme = sourceThemeName;
}
} else {
originalGtkTheme = currentGtkTheme;
originalIconTheme = currentIconTheme;
}
this._logger.info(
` Read original themes from GSettings: GTK=${originalGtkTheme}, Icon=${originalIconTheme}`
);
} catch (e) {
this._logger.warn(` Could not read original themes from GSettings: ${e.message}`);
}
}
// === Manual Icon Theme Override (v2.5.3+) ===
// Allows user to select icon theme independently from source GTK theme
// Useful for themes with missing icon packs (e.g., Fluent GTK without Fluent icons)
let sourceIconTheme = null; // null = auto-detect from source theme
let manualIconOverrideEnabled = false;
if (settings) {
try {
manualIconOverrideEnabled = settings.get_boolean("manual-icon-theme-override");
if (manualIconOverrideEnabled) {
const selectedIconTheme = settings.get_string("selected-icon-theme");
if (selectedIconTheme && selectedIconTheme.trim() !== "") {
sourceIconTheme = selectedIconTheme;
this._logger.info(` Using MANUAL icon theme: ${sourceIconTheme}`);
} else {
this._logger.warn(` Manual icon override enabled but no theme selected - using auto-detection`);
}
}
} catch (e) {
this._logger.warn(` Could not read manual-icon-theme-override setting: ${e.message}`);
}
}
// If manual override not set, sourceIconTheme remains null
// _writeIndexTheme() will call _parseSourceIconTheme() for auto-detection
if (!sourceIconTheme) {
this._logger.debug(` Using AUTO icon theme detection from source theme`);
}
try {
// Create base overlay directory (sync - very fast)
this._createDirectory(this.overlayPath);
// Get theme structure (sync - just directory scans)
const gtkVersions = this.detectGtkVersions(sourcePath);
const shellTheme = this.detectShellTheme(sourcePath);
const otherDirs = this.getNonGtkDirectories(sourcePath);
this._logger.info(` Creating overlay with ${otherDirs.length} symlinked directories`);
// Collect all CSS generation tasks
// Using 'let' instead of 'const' to allow later reassignment for memory cleanup
let cssFiles = {};
// Generate GTK CSS (sync - template generation)
for (const version of Object.keys(gtkVersions)) {
if (gtkVersions[version].exists) {
// Generate base-theme.css files (neutralized, tint removed)
// IMPORTANT: Generate separate light/dark base themes for future-proofing
// (some themes may have different tint colors in gtk.css vs gtk-dark.css)
// Light variant base theme (if gtk.css exists)
if (gtkVersions[version].hasGtkCss) {
const baseCss = this._generateGtkBaseCss(version, sourcePath, false, settings);
cssFiles[`${this.overlayPath}/${version}/base-theme.css`] = baseCss;
}
// Dark variant base theme (if gtk-dark.css exists)
if (gtkVersions[version].hasDarkCss) {
const baseDarkCss = this._generateGtkBaseCss(version, sourcePath, true, settings);
cssFiles[`${this.overlayPath}/${version}/base-theme-dark.css`] = baseDarkCss;
}
// Generate gtk.css (import base-theme.css + overrides)
if (gtkVersions[version].hasGtkCss) {
const gtkCss = this._generateGtkCss(version, sourcePath, false, settings);
cssFiles[`${this.overlayPath}/${version}/gtk.css`] = gtkCss;
}
// Generate gtk-dark.css (import base-theme-dark.css + overrides)
if (gtkVersions[version].hasDarkCss) {
const darkCss = this._generateGtkCss(version, sourcePath, true, settings);
cssFiles[`${this.overlayPath}/${version}/gtk-dark.css`] = darkCss;
}
// Create version directory
this._createDirectory(`${this.overlayPath}/${version}`);
}
}
// Generate Shell CSS (sync - template generation)
if (shellTheme.exists) {
// Create shell directory first
this._createDirectory(`${this.overlayPath}/gnome-shell`);
// Generate base-theme.css (modified original CSS)
const baseThemeCss = this._generateBaseThemeCss(sourcePath, settings);
cssFiles[`${this.overlayPath}/gnome-shell/base-theme.css`] = baseThemeCss;
// Generate gnome-shell.css (our dynamic overrides)
const shellCss = this._generateShellCss(sourcePath, settings);
cssFiles[`${this.overlayPath}/gnome-shell/gnome-shell.css`] = shellCss;
// Generate pad-osd.css if source has it
if (shellTheme.hasPadOsd) {
const padOsdCss = this._generatePadOsdCss(sourcePath, settings);
cssFiles[`${this.overlayPath}/gnome-shell/pad-osd.css`] = padOsdCss;
}
}
// Write ALL CSS files synchronously (simpler, faster for small batches)
this._logger.info(` Writing ${Object.keys(cssFiles).length} CSS files synchronously...`);
const batchStart = Date.now();
let writeErrors = 0;
for (const [filePath, content] of Object.entries(cssFiles)) {
try {
this._writeFile(filePath, content);
} catch (error) {
this._logger.error(` Failed to write ${filePath}: ${error.message}`);
writeErrors++;
}
}
const batchElapsed = Date.now() - batchStart;
this._logger.info(` CSS sync write completed in ${batchElapsed}ms`);
if (writeErrors > 0) {
this._logger.warn(` CSS write had ${writeErrors} errors`);
}
// MEMORY LEAK FIX: Clear CSS file map to release large strings from memory
// These strings can be 100KB+ each (6 files = ~600KB total)
const memBefore = this._getMemoryUsageMB();
const cssFileCount = Object.keys(cssFiles).length;
let totalCssSize = 0;
for (const key in cssFiles) {
totalCssSize += cssFiles[key].length;
delete cssFiles[key]; // Explicit property deletion
}
const cssSizeMB = (totalCssSize / (1024 * 1024)).toFixed(2);
this._logger.info(
`📊 Memory BEFORE CSS cleanup: ${memBefore}MB (${cssFileCount} files, ${cssSizeMB}MB CSS data)`
);
// Hint garbage collector to clean up large CSS strings
try {
System.gc();
// Wait 100ms for GC to complete, then check memory
GLib.timeout_add(GLib.PRIORITY_DEFAULT, 100, () => {
const memAfter = this._getMemoryUsageMB();
const delta = memAfter - memBefore;
this._logger.info(
`📊 Memory AFTER CSS cleanup + GC: ${memAfter}MB (Δ ${delta >= 0 ? "+" : ""}${delta.toFixed(
1
)}MB)`
);
return false; // One-shot timeout
});
this._logger.debug(` Triggered GC after clearing ${cssFileCount} CSS strings (${cssSizeMB}MB)`);
} catch (e) {
this._logger.error(` ⚠️ GC ERROR after CSS cleanup: ${e.message}`);
}
// Symlink GTK version assets (Sprint 5 fix - Fluent theme support)
for (const version of Object.keys(gtkVersions)) {
if (
gtkVersions[version].exists &&
gtkVersions[version].assets &&
gtkVersions[version].assets.length > 0
) {
gtkVersions[version].assets.forEach(asset => {
this._createSymlink(
`${sourcePath}/${version}/${asset}`,
`${this.overlayPath}/${version}/${asset}`
);
});
this._logger.info(` Symlinked ${gtkVersions[version].assets.length} ${version} assets`);
}
}
// Symlink ALL other directories (sync - fast symlink operations)
otherDirs.forEach(dir => {
this._createSymlink(`${sourcePath}/${dir}`, `${this.overlayPath}/${dir}`);
});
// Symlink Shell theme assets if exists (sync - fast symlink operations)
if (shellTheme.exists && shellTheme.assets && shellTheme.assets.length > 0) {
shellTheme.assets.forEach(asset => {
this._createSymlink(
`${sourcePath}/gnome-shell/${asset}`,
`${this.overlayPath}/gnome-shell/${asset}`
);
});
this._logger.info(` Symlinked ${shellTheme.assets.length} Shell theme assets`);
}
// Detect and apply theme accent color to settings (sync - just settings write)
this.detectAndApplyAccentColor(sourcePath, settings);
// Write metadata with original themes (sync - small file)
this._writeIndexTheme({
sourceThemeName,
sourcePath,
gtkVersions,
originalGtkTheme,
originalShellTheme,
originalIconTheme,
sourceIconTheme, // Manual icon theme override (null = auto-detect)
manualIconOverrideEnabled // Whether user manually selected icon theme
});
// Write README (sync - small file)
this._writeReadme(sourceThemeName);
this._logger.info(` Overlay theme created successfully`);
return true;
} catch (e) {
this._logger.error(` Error creating overlay theme: ${e.message}`);
this._logger.error(` Stack: ${e.stack}`);
return false;
}
}
/**
* Create GNOME Shell theme overlay
* @param {string} sourcePath - Source theme path
* @param {Object} shellInfo - Shell theme info
* @param {Object} settings - Extension settings
*/
_createShellOverlay(sourcePath, shellInfo, settings) {
if (!shellInfo.exists) {
this._logger.info(` Source has no gnome-shell directory, skipping`);
return;
}
const overlayShellDir = `${this.overlayPath}/gnome-shell`;
this._createDirectory(overlayShellDir);
this._logger.info(` Creating gnome-shell overlay with ${shellInfo.assets.length} assets`);
// Generate gnome-shell.css
if (shellInfo.hasShellCss) {
// First, generate base-theme.css (modified original CSS)
const baseThemeCss = this._generateBaseThemeCss(sourcePath, settings);
this._writeFile(`${overlayShellDir}/base-theme.css`, baseThemeCss);
this._logger.info(` Generated base-theme.css with modifications`);
// Then generate gnome-shell.css (our dynamic overrides)
const shellCss = this._generateShellCss(sourcePath, settings);
this._writeFile(`${overlayShellDir}/gnome-shell.css`, shellCss);
this._logger.info(` Generated gnome-shell.css`);
}
// Generate pad-osd.css if source has it
if (shellInfo.hasPadOsdCss) {
const padOsdCss = this._generatePadOsdCss(sourcePath, settings);
this._writeFile(`${overlayShellDir}/pad-osd.css`, padOsdCss);
this._logger.info(` Generated pad-osd.css`);
}
// Symlink all assets (icons, images, etc.)
shellInfo.assets.forEach(asset => {
this._createSymlink(`${sourcePath}/gnome-shell/${asset}`, `${overlayShellDir}/${asset}`);
});
this._logger.info(` GNOME Shell overlay created successfully`);
}
/**
* Generate GTK base-theme.css with tint removal and modifications
* Same logic as Shell CSS - processes original theme CSS to remove Zorin tint colors
* @param {string} version - GTK version (e.g., 'gtk-3.0')
* @param {string} sourcePath - Source theme path
* @param {boolean} isDark - Is dark variant
* @param {Object} settings - Extension settings
* @returns {string} Modified CSS with tint removed
*/
_generateGtkBaseCss(version, sourcePath, isDark, settings) {
const cssFile = isDark ? "gtk-dark.css" : "gtk.css";
const sourceFile = `${sourcePath}/${version}/${cssFile}`;
const sourceThemeName = sourcePath.split("/").pop();
const isZorinTheme = sourceThemeName.toLowerCase().includes("zorin");
// === BASE THEME CACHE (TIER 1 OPTIMIZATION) ===
// Create cache key from immutable parameters
const tintStrength = settings.get_int("zorin-tint-strength") || 0;
const cacheKey = `gtk-base:${sourceThemeName}:${version}:${isDark ? "dark" : "light"}:${tintStrength}`;
// Check cache first
if (this._baseThemeCache.has(cacheKey)) {
this._baseThemeCacheStats.hits++;
this._logger.debug(` ✅ Base theme cache HIT: ${cacheKey}`);
return this._baseThemeCache.get(cacheKey);
}
// Cache miss - generate CSS
this._baseThemeCacheStats.misses++;
this._logger.info(` ❌ Base theme cache MISS - generating: ${cacheKey}`);
try {
// Read original CSS
const file = Gio.File.new_for_path(sourceFile);
if (!file.query_exists(null)) {
logError(new Error(`[${this.extensionName}] GTK source CSS not found: ${sourceFile}`));
return null;
}
const { success, contents } = this._readCSSFileSync(file);
if (!success) {
logError(new Error(`[${this.extensionName}] Failed to read GTK CSS: ${sourceFile}`));
return null;
}
const decoder = new TextDecoder("utf-8");
let css = decoder.decode(contents);
// For non-Zorin themes, return original CSS unchanged
if (!isZorinTheme) {
this._logger.info(` GTK Base: Non-Zorin theme, using original CSS`);
return css;
}
// === ZORIN THEME: Detect and process tint colors (foreground + background) ===
// Delegate tint detection to ThemeUtils
const tintColors = ThemeUtils.detectGtkTintColors(css, isZorinTheme);
const { fgHex: tintFgHex, fgRgb: tintFgRgb, bgHex: tintBgHex, bgRgb: tintBgRgb } = tintColors;
if (tintFgHex && tintFgRgb) {
this._logger.info(
` GTK Base: Detected Zorin FOREGROUND tint: ${tintFgHex} (rgb ${tintFgRgb[0]}, ${tintFgRgb[1]}, ${tintFgRgb[2]})`
);
}
if (tintBgHex && tintBgRgb) {
this._logger.info(
` GTK Base: Detected Zorin BACKGROUND tint: ${tintBgHex} (rgb ${tintBgRgb[0]}, ${tintBgRgb[1]}, ${tintBgRgb[2]})`
);
}
// If no tints detected, return original CSS
if (!tintFgHex && !tintBgHex) {
this._logger.info(` GTK Base: No .background colors or @define-color detected (not a Zorin theme)`);
return css; // No tint to process
}
// === DETERMINE DOMINANT TINT CHANNEL (for algorithmic neutralization) ===
// Use foreground tint as reference (if available), else background tint
const referenceTintRgb = tintFgRgb || tintBgRgb;
// Calculate adaptive threshold using ThemeUtils
const tintThreshold = ThemeUtils.calculateAdaptiveThreshold(referenceTintRgb);
// Determine dominant channel using ThemeUtils
const dominantChannel = ThemeUtils.determineDominantChannel(referenceTintRgb, tintThreshold);
const [refR, refG, refB] = referenceTintRgb;
const maxChannel = Math.max(refR, refG, refB);
const minChannel = Math.min(refR, refG, refB);
const tintStrengthInRef = maxChannel - minChannel;
this._logger.info(
` GTK Base: Dominant tint channel: ${
dominantChannel ? dominantChannel.toUpperCase() : "NONE"
} (ref: rgb(${refR}, ${refG}, ${refB}), adaptive threshold: ${tintThreshold}, ref tint: ${tintStrengthInRef})`
);
// Determine neutral colors based on theme variant
const isLightTheme =
sourceThemeName.includes("Light") ||
sourceThemeName.includes("light") ||
(!sourceThemeName.includes("Dark") && !sourceThemeName.includes("dark"));
const neutralFgRgb = isLightTheme ? [50, 50, 50] : [200, 200, 200];
// TRUE NEUTRAL gray - all channels equal (no blue/red/green tint!)
const neutralBgRgb = isLightTheme ? [250, 250, 250] : [50, 50, 50]; // Pure neutral gray
// Get tint strength setting (0-100%)
const tintStrength = settings.get_int("zorin-tint-strength") || 0;
this._logger.info(` GTK Base: Zorin tint strength: ${tintStrength}%`);
// Track replacement counts
let totalDefineColorMatches = 0;
let totalRgbaMatches = 0;
let totalHexMatches = 0;
// === PROCESS FOREGROUND TINT (if detected) ===
if (tintFgHex && tintFgRgb) {
const targetFgRgb = this._blendTintColor(tintFgRgb, neutralFgRgb, tintStrength);
const targetFgRgbString = `${targetFgRgb[0]}, ${targetFgRgb[1]}, ${targetFgRgb[2]}`;
const targetFgHex = "#" + targetFgRgb.map(c => c.toString(16).padStart(2, "0")).join("");
this._logger.info(
` GTK Base: Target FOREGROUND (${tintStrength}% blend): ${targetFgHex} (rgb ${targetFgRgbString})`
);
// STEP 1: Replace @define-color directives
const fgDefineColorRegex = new RegExp(
`(@define-color\\s+[\\w_-]+\\s+)${tintFgHex.replace("#", "#")}(\\s*;)`,
"gi"
);
const fgDefineColorMatches = css.match(fgDefineColorRegex);
css = css.replace(fgDefineColorRegex, `$1${targetFgHex}$2`);
totalDefineColorMatches += fgDefineColorMatches ? fgDefineColorMatches.length : 0;
// STEP 2: Replace inline rgba(tintR, tintG, tintB, alpha) patterns
const tintFgRgbString = `${tintFgRgb[0]}, ${tintFgRgb[1]}, ${tintFgRgb[2]}`;
const fgRgbaRegex = new RegExp(
`rgba?\\(\\s*${tintFgRgbString.replace(/,/g, "\\s*,\\s*")}\\s*,\\s*([\\d.]+)\\s*\\)`,
"gi"
);
const fgRgbaMatches = css.match(fgRgbaRegex);
css = css.replace(fgRgbaRegex, `rgba(${targetFgRgbString}, $1)`);
totalRgbaMatches += fgRgbaMatches ? fgRgbaMatches.length : 0;
// STEP 3: Replace inline #tintHex color codes
const fgHexRegex = new RegExp(tintFgHex.replace("#", "#"), "gi");
const fgHexMatches = css.match(fgHexRegex);
css = css.replace(fgHexRegex, targetFgHex);
totalHexMatches += fgHexMatches ? fgHexMatches.length : 0;
}
// === PROCESS BACKGROUND TINT (if detected) ===
if (tintBgHex && tintBgRgb) {
const targetBgRgb = this._blendTintColor(tintBgRgb, neutralBgRgb, tintStrength);
const targetBgRgbString = `${targetBgRgb[0]}, ${targetBgRgb[1]}, ${targetBgRgb[2]}`;
const targetBgHex = "#" + targetBgRgb.map(c => c.toString(16).padStart(2, "0")).join("");
this._logger.info(
` GTK Base: Target BACKGROUND (${tintStrength}% blend): ${targetBgHex} (rgb ${targetBgRgbString})`
);
// STEP 1: Replace @define-color directives
const bgDefineColorRegex = new RegExp(
`(@define-color\\s+[\\w_-]+\\s+)${tintBgHex.replace("#", "#")}(\\s*;)`,
"gi"
);
const bgDefineColorMatches = css.match(bgDefineColorRegex);
css = css.replace(bgDefineColorRegex, `$1${targetBgHex}$2`);
totalDefineColorMatches += bgDefineColorMatches ? bgDefineColorMatches.length : 0;
// STEP 2: Replace inline rgba(tintR, tintG, tintB, alpha) patterns
const tintBgRgbString = `${tintBgRgb[0]}, ${tintBgRgb[1]}, ${tintBgRgb[2]}`;
const bgRgbaRegex = new RegExp(
`rgba?\\(\\s*${tintBgRgbString.replace(/,/g, "\\s*,\\s*")}\\s*,\\s*([\\d.]+)\\s*\\)`,
"gi"
);
const bgRgbaMatches = css.match(bgRgbaRegex);
css = css.replace(bgRgbaRegex, `rgba(${targetBgRgbString}, $1)`);
totalRgbaMatches += bgRgbaMatches ? bgRgbaMatches.length : 0;
// STEP 3: Replace inline #tintHex color codes
const bgHexRegex = new RegExp(tintBgHex.replace("#", "#"), "gi");
const bgHexMatches = css.match(bgHexRegex);
css = css.replace(bgHexRegex, targetBgHex);
totalHexMatches += bgHexMatches ? bgHexMatches.length : 0;
}
this._logger.info(
` GTK Base: Replaced ${totalDefineColorMatches} @define-color + ${totalRgbaMatches} rgba() + ${totalHexMatches} hex tint colors (FG+BG combined)`
);
// === STEP 4: ALGORITHMIC NEUTRALIZATION of tinted BACKGROUND colors ===
// Find and neutralize ONLY background-related colors with dominant channel tint
// Preserves foreground colors (text, borders, accents) to maintain theme identity
if (dominantChannel) {
this._logger.info(
` GTK Base: Starting algorithmic neutralization for ${dominantChannel.toUpperCase()}-tinted BACKGROUND colors...`
);
// Delegate to ThemeUtils for context-aware neutralization
const neutralizationResult = ThemeUtils.neutralizeTintedCss(css, {
dominantChannel,
threshold: tintThreshold,
tintStrength,
blendFunction: this._blendTintColor.bind(this)
});
css = neutralizationResult.css;
this._logger.info(
` GTK Base: Algorithmic neutralization replaced ${neutralizationResult.replacementCount} tinted colors (backgrounds + @define-color, ${neutralizationResult.whitelistedBlocks} blocks preserved)`
);
}
// Add header comment
const timestamp = new Date().toISOString().slice(0, 19).replace("T", " ");
const tintModification =
tintStrength === 0
? "Tint removed"
: tintStrength === 100
? "Original tint preserved"
: `Tint reduced to ${tintStrength}%`;
const header = `/*
* CSSGnomme GTK Base Theme
* Generated: ${timestamp}
* Theme: ${sourceThemeName} (${isZorinTheme ? "Zorin" : "Standard"}, ${isLightTheme ? "Light" : "Dark"})
* Source: ${sourceFile}
* Modifications: ${tintModification}
*/
`;
const result = header + css;
// Cache the result for future use
this._baseThemeCache.set(cacheKey, result);
this._logger.info(` 💾 Cached base theme: ${(result.length / 1024).toFixed(1)}KB`);
// Enforce LRU eviction if cache exceeds limit
this._enforceCacheLRU(this._baseThemeCache, this._baseThemeCacheMaxSize, "base theme");
return result;
} catch (e) {
logError(e, `[${this.extensionName}] Error generating GTK base CSS`);
return null;
}
}
/**
* Generate gtk.css with import + overrides
* Now imports base-theme.css instead of original theme CSS
* @param {string} version - GTK version
* @param {string} sourcePath - Source theme path
* @param {boolean} isDark - Is dark variant
* @param {Object} settings - Extension settings
* @returns {string} Generated CSS content
*/
_generateGtkCss(version, sourcePath, isDark, settings, isLightTheme = null) {
const cssFile = isDark ? "gtk-dark.css" : "gtk.css";
// Detect source theme name and type
const sourceThemeName = sourcePath.split("/").pop();
const isZorinTheme = sourceThemeName.toLowerCase().includes("zorin");
const enableZorinIntegration = settings.get_boolean("enable-zorin-integration");
// Get settings values (allow 0 for flat appearance)
const borderRadius = settings.get_int("border-radius");
// Detect theme accent color for switch/checkbox styling (cached for performance)