-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIconHelper.py
More file actions
2851 lines (2599 loc) · 121 KB
/
IconHelper.py
File metadata and controls
2851 lines (2599 loc) · 121 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
#!/usr/bin/env python3
import os
import json
import subprocess
import threading
import time
import shutil
import datetime
import gi
gi.require_version('Gtk', '3.0')
import xml.etree.ElementTree as ET
import xml.sax
from typing import Callable, Dict, List, Optional, Tuple
from gi.repository import Gtk, GdkPixbuf, GLib, Gdk
import tempfile
from collections import OrderedDict
import hashlib
from pathlib import Path
import queue
import re
# --------------------------------------------------------------------------
# Globals and Constants
# --------------------------------------------------------------------------
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
PLACEHOLDER_PATH = os.path.join(SCRIPT_DIR, "emblem-unreadable.svg")
SYMLINK_EMBLEM_PATH = os.path.join(SCRIPT_DIR, "emblem-symlink.png")
BACKUP_EMBLEM_PATH = os.path.join(SCRIPT_DIR, "emblem-history.png")
TEMPLATE_SVG = os.path.join(SCRIPT_DIR, "template.svg")
BITMAP_SIZES = [16, 22, 24, 32, 48]
CATEGORIES_FILE = os.path.join(SCRIPT_DIR, "icon_categories.json")
PNG_EMBLEM = os.path.join(SCRIPT_DIR, "emblem-png.png")
# Config file
CONFIG_FILE = os.path.join(SCRIPT_DIR, "iconhelper_config.json")
# Supersampling defaults (we keep existing controls but will expose via Settings)
SUPERSAMPLE_ENABLED = True
SUPERSAMPLE_FACTOR = 3
# Disk cache defaults (exposed via Settings)
DEFAULT_DISK_CACHE_DIR = os.path.join(SCRIPT_DIR, ".thumbcache")
DISK_CACHE_ENABLED = True
DISK_CACHE_DIR = DEFAULT_DISK_CACHE_DIR
DISK_CACHE_SIZE_LIMIT = 200 * 1024 * 1024 # 200MB default
# Mint-Y export defaults (new settings)
MINTY_ENABLED = False
MINTY_EXPORT_PATH = "" # when set, used as export root for Mint-Y style (can be absolute or inside theme)
MINTY_2X_ENABLED = True # create @2x variants
# Loader pool defaults
PIXBUF_WORKER_COUNT = 6
ICON_PAGE_SIZE = 150 # number of icons to create initially / per page when scrolling
# Backups defaults
MAX_SVG_BACKUPS = 10 # per-icon backup limit
# In-memory pixbuf cache (LRU-like)
PIXBUF_CACHE: "OrderedDict[Tuple[str,int], GdkPixbuf.Pixbuf]" = OrderedDict()
CACHE_LOCK = threading.Lock()
MAX_PIXBUF_CACHE_ITEMS = 1200
# Disk cache index file
DISK_CACHE_INDEX = "index.json"
DISK_CACHE_LOCK = threading.Lock()
# Active preview popups registry
ACTIVE_PREVIEWS = set()
ACTIVE_PREVIEWS_LOCK = threading.Lock()
# Loader task queue; tasks are (path, size, callback)
_LOADER_QUEUE: "queue.Queue[Tuple[str,int,Callable]]" = queue.Queue()
_WORKERS_STARTED = False
# Mint-Y style rendering DPI factors (1x, optionally 2x for HiDPI)
MINTY_DPI_FACTORS = [1, 2]
# Detect inkscape DPI behaviour similar to moka script (90 vs 96)
try:
ver_raw = subprocess.check_output(["inkscape", "-V"], stderr=subprocess.STDOUT).decode()
m = re.search(r'(\d+)\.(\d+)', ver_raw)
if m:
major = int(m.group(1)); minor = int(m.group(2))
if major == 0 and minor < 92:
DPI_1_TO_1 = 90
else:
DPI_1_TO_1 = 96
else:
DPI_1_TO_1 = 96
except Exception:
DPI_1_TO_1 = 96
# --------------------------------------------------------------------------
# Global backups (stored under SCRIPT_DIR, NOT inside themes)
# --------------------------------------------------------------------------
BACKUP_ROOT = os.path.join(SCRIPT_DIR, ".iconhelper_backups")
BACKUP_FILES_DIR = os.path.join(BACKUP_ROOT, "files")
BACKUP_INDEX_PATH = os.path.join(BACKUP_ROOT, "index.json")
def ensure_backup_dirs():
try:
os.makedirs(BACKUP_FILES_DIR, exist_ok=True)
except Exception as e:
print(f"Failed to create backup dirs: {e}")
def _load_backup_index() -> Dict[str, Dict]:
try:
if os.path.isfile(BACKUP_INDEX_PATH):
with open(BACKUP_INDEX_PATH, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
return data
except Exception as e:
print(f"Failed to load backup index: {e}")
return {}
def _save_backup_index(idx: Dict[str, Dict]):
try:
ensure_backup_dirs()
with open(BACKUP_INDEX_PATH, "w", encoding="utf-8") as f:
json.dump(idx, f, indent=2)
except Exception as e:
print(f"Failed to write backup index: {e}")
# --------------------------------------------------------------------------
# Config helpers
# --------------------------------------------------------------------------
def load_config():
global SUPERSAMPLE_ENABLED, SUPERSAMPLE_FACTOR, DISK_CACHE_ENABLED, DISK_CACHE_DIR, DISK_CACHE_SIZE_LIMIT
global PIXBUF_WORKER_COUNT, ICON_PAGE_SIZE, MAX_SVG_BACKUPS
global MINTY_ENABLED, MINTY_EXPORT_PATH, MINTY_2X_ENABLED
try:
if os.path.isfile(CONFIG_FILE):
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
cfg = json.load(f)
SUPERSAMPLE_ENABLED = bool(cfg.get("supersample_enabled", SUPERSAMPLE_ENABLED))
SUPERSAMPLE_FACTOR = int(cfg.get("supersample_factor", SUPERSAMPLE_FACTOR))
DISK_CACHE_ENABLED = bool(cfg.get("disk_cache_enabled", DISK_CACHE_ENABLED))
DISK_CACHE_DIR = cfg.get("disk_cache_dir", DISK_CACHE_DIR)
DISK_CACHE_SIZE_LIMIT = int(cfg.get("disk_cache_size_limit", DISK_CACHE_SIZE_LIMIT))
PIXBUF_WORKER_COUNT = int(cfg.get("pixbuf_worker_count", PIXBUF_WORKER_COUNT))
ICON_PAGE_SIZE = int(cfg.get("icon_page_size", ICON_PAGE_SIZE))
MAX_SVG_BACKUPS = int(cfg.get("max_svg_backups", MAX_SVG_BACKUPS))
MINTY_ENABLED = bool(cfg.get("minty_enabled", MINTY_ENABLED))
MINTY_EXPORT_PATH = cfg.get("minty_export_path", MINTY_EXPORT_PATH)
MINTY_2X_ENABLED = bool(cfg.get("minty_2x_enabled", MINTY_2X_ENABLED))
except Exception as e:
print(f"Failed to load config {CONFIG_FILE}: {e}")
def save_config():
try:
cfg = {
"supersample_enabled": SUPERSAMPLE_ENABLED,
"supersample_factor": SUPERSAMPLE_FACTOR,
"disk_cache_enabled": DISK_CACHE_ENABLED,
"disk_cache_dir": DISK_CACHE_DIR,
"disk_cache_size_limit": DISK_CACHE_SIZE_LIMIT,
"pixbuf_worker_count": PIXBUF_WORKER_COUNT,
"icon_page_size": ICON_PAGE_SIZE,
"max_svg_backups": MAX_SVG_BACKUPS,
"minty_enabled": MINTY_ENABLED,
"minty_export_path": MINTY_EXPORT_PATH,
"minty_2x_enabled": MINTY_2X_ENABLED
}
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=2)
except Exception as e:
print(f"Failed to save config {CONFIG_FILE}: {e}")
# Load config at startup (overrides defaults)
load_config()
# --------------------------------------------------------------------------
# Disk cache utilities (LRU eviction by last_used)
# --------------------------------------------------------------------------
def ensure_disk_cache_dir():
global DISK_CACHE_DIR
if not DISK_CACHE_DIR:
DISK_CACHE_DIR = DEFAULT_DISK_CACHE_DIR
try:
os.makedirs(DISK_CACHE_DIR, exist_ok=True)
except Exception as e:
print(f"Failed to create disk cache dir {DISK_CACHE_DIR}: {e}")
def _disk_index_path():
return os.path.join(DISK_CACHE_DIR, DISK_CACHE_INDEX)
def _load_disk_index() -> Dict[str, Dict]:
"""
Load the disk cache index and return a dict. If the file contains a
legacy/list format (or is corrupt), try to heal common cases or return {}.
"""
try:
idx_path = _disk_index_path()
if os.path.isfile(idx_path):
with open(idx_path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, dict):
return data
if isinstance(data, list):
healed = {}
for item in data:
if isinstance(item, dict):
key = item.get("key")
if not key:
fname = item.get("fname") or item.get("file") or ""
if fname:
key = hashlib.sha1(fname.encode("utf-8")).hexdigest()
if key:
healed[key] = item
return healed
except Exception:
pass
return {}
def _save_disk_index(idx: Dict[str, Dict]):
try:
ensure_disk_cache_dir()
with open(_disk_index_path(), "w", encoding="utf-8") as f:
json.dump(idx, f, indent=2)
except Exception as e:
print(f"Failed to write disk cache index: {e}")
def _cache_key_for(path: str, size: int) -> str:
try:
mtime = int(os.path.getmtime(path))
except Exception:
mtime = 0
key = f"{os.path.abspath(path)}|{mtime}|{size}"
return hashlib.sha1(key.encode("utf-8")).hexdigest()
def get_disk_cache_path(path: str, size: int) -> Optional[str]:
if not DISK_CACHE_ENABLED:
return None
try:
ensure_disk_cache_dir()
fname = _cache_key_for(path, size) + ".png"
return os.path.join(DISK_CACHE_DIR, fname)
except Exception:
return None
def _get_disk_cache_total_size_and_count(idx: Dict[str, Dict]) -> Tuple[int,int]:
total = 0
cnt = 0
for v in idx.values():
if isinstance(v, dict):
sz = v.get("size", 0)
total += sz
cnt += 1
return total, cnt
def _prune_disk_cache_if_needed():
if not DISK_CACHE_ENABLED:
return
try:
with DISK_CACHE_LOCK:
idx = _load_disk_index()
if not isinstance(idx, dict):
return
total, cnt = _get_disk_cache_total_size_and_count(idx)
if total <= DISK_CACHE_SIZE_LIMIT:
return
# Evict by oldest last_used (entries missing last_used treated as oldest)
items = sorted(idx.items(), key=lambda kv: kv[1].get("last_used", 0) if isinstance(kv[1], dict) else 0)
for key, meta in items:
if total <= DISK_CACHE_SIZE_LIMIT:
break
fname = meta.get("fname") if isinstance(meta, dict) else None
p = os.path.join(DISK_CACHE_DIR, fname) if fname else None
try:
size_removed = meta.get("size", 0) if isinstance(meta, dict) else 0
if p and os.path.exists(p):
try:
os.remove(p)
except Exception:
pass
if not size_removed:
try:
size_removed = os.path.getsize(p)
except Exception:
size_removed = 0
total -= size_removed
except Exception:
pass
idx.pop(key, None)
_save_disk_index(idx)
except Exception as e:
print(f"Disk prune error: {e}")
# store disk cache and update index (atomic, robust)
def store_disk_cache(path: str, size: int, pixbuf: GdkPixbuf.Pixbuf):
if not DISK_CACHE_ENABLED:
return
try:
ensure_disk_cache_dir()
cache_path = get_disk_cache_path(path, size)
if not cache_path:
return
# create a tmp file inside the cache dir to avoid cross-filesystem/permission races
tmp = None
try:
# create named temp file in disk cache dir
with tempfile.NamedTemporaryFile(dir=DISK_CACHE_DIR, delete=False, suffix=".png.tmp") as tf:
tmp = tf.name
# Try saving via GdkPixbuf first
saved = False
try:
pixbuf.savev(tmp, "png", [], [])
saved = True
except Exception:
# fallback to PIL if available
try:
from PIL import Image
buf = pixbuf.get_pixels()
width = pixbuf.get_width()
height = pixbuf.get_height()
rowstride = pixbuf.get_rowstride()
has_alpha = pixbuf.get_has_alpha()
mode = "RGBA" if has_alpha else "RGB"
img = Image.frombytes(mode, (width, height), buf, "raw", mode, rowstride)
img.save(tmp, format="PNG")
saved = True
except Exception:
# last-ditch: try pixbuf.savev again (some pixbuf implementations behave differently)
try:
pixbuf.savev(tmp, "png", [], [])
saved = True
except Exception:
saved = False
if saved and os.path.exists(tmp):
try:
os.replace(tmp, cache_path)
except FileNotFoundError:
# tmp got removed concurrently; ignore
pass
except Exception as e:
print(f"Failed to move temp cache file into place: {e}")
try:
with DISK_CACHE_LOCK:
idx = _load_disk_index()
key = _cache_key_for(path, size)
try:
stat = os.stat(cache_path)
idx[key] = {"fname": os.path.basename(cache_path), "size": stat.st_size, "last_used": int(time.time())}
_save_disk_index(idx)
except Exception:
# if stat fails, still try to record something
idx[key] = {"fname": os.path.basename(cache_path), "size": 0, "last_used": int(time.time())}
_save_disk_index(idx)
threading.Thread(target=_prune_disk_cache_if_needed, daemon=True).start()
except Exception as e:
print(f"Failed to update disk cache index: {e}")
finally:
# cleanup tmp if still present
if tmp and os.path.exists(tmp):
try:
os.remove(tmp)
except Exception:
pass
except Exception as e:
print(f"Failed to store disk cache for {path} size {size}: {e}")
def load_disk_cache(path: str, size: int) -> Optional[GdkPixbuf.Pixbuf]:
if not DISK_CACHE_ENABLED:
return None
try:
cache_path = get_disk_cache_path(path, size)
if cache_path and os.path.isfile(cache_path):
try:
pb = GdkPixbuf.Pixbuf.new_from_file(cache_path)
with DISK_CACHE_LOCK:
idx = _load_disk_index()
key = _cache_key_for(path, size)
if key in idx and isinstance(idx[key], dict):
idx[key]["last_used"] = int(time.time())
_save_disk_index(idx)
return pb
except Exception:
try:
return GdkPixbuf.Pixbuf.new_from_file_at_size(cache_path, size, size)
except Exception:
return None
except Exception:
pass
return None
def invalidate_disk_cache_for_path(path: str):
if not DISK_CACHE_ENABLED:
return
try:
with DISK_CACHE_LOCK:
idx = _load_disk_index()
if not isinstance(idx, dict):
return
for size in BITMAP_SIZES + [64, 96, 256, 512]:
key = _cache_key_for(path, size)
meta = idx.pop(key, None)
if meta and isinstance(meta, dict):
p = os.path.join(DISK_CACHE_DIR, meta.get("fname", ""))
try:
if os.path.exists(p):
os.remove(p)
except Exception:
pass
_save_disk_index(idx)
except Exception as e:
print(f"Failed to invalidate disk cache for {path}: {e}")
# --------------------------------------------------------------------------
# In-memory pixbuf cache helpers
# --------------------------------------------------------------------------
def _cache_get(key):
with CACHE_LOCK:
val = PIXBUF_CACHE.get(key)
if val is not None:
PIXBUF_CACHE.move_to_end(key)
return val
def _cache_set(key, pixbuf):
with CACHE_LOCK:
PIXBUF_CACHE[key] = pixbuf
PIXBUF_CACHE.move_to_end(key)
while len(PIXBUF_CACHE) > MAX_PIXBUF_CACHE_ITEMS:
PIXBUF_CACHE.popitem(last=False)
def clear_pixbuf_cache():
with CACHE_LOCK:
PIXBUF_CACHE.clear()
def invalidate_pixbuf_cache_for_path(path):
with CACHE_LOCK:
keys_to_remove = [k for k in PIXBUF_CACHE.keys() if k[0] == path]
for k in keys_to_remove:
PIXBUF_CACHE.pop(k, None)
try:
invalidate_disk_cache_for_path(path)
except Exception:
pass
# --------------------------------------------------------------------------
# Loader pool (bounded worker threads)
# --------------------------------------------------------------------------
def _start_loader_workers():
global _WORKERS_STARTED
if _WORKERS_STARTED:
return
_WORKERS_STARTED = True
for i in range(max(1, PIXBUF_WORKER_COUNT)):
t = threading.Thread(target=_loader_worker, daemon=True, name=f"pixbuf-worker-{i}")
t.start()
def _loader_worker():
while True:
try:
path, size, cb = _LOADER_QUEUE.get()
key = (path, size)
pix = _cache_get(key)
if pix:
GLib.idle_add(cb, pix)
_LOADER_QUEUE.task_done()
continue
pix = load_disk_cache(path, size)
if pix:
_cache_set(key, pix)
GLib.idle_add(cb, pix)
_LOADER_QUEUE.task_done()
continue
try:
if not path or not os.path.exists(path):
source = PLACEHOLDER_PATH
else:
source = path
pix = GdkPixbuf.Pixbuf.new_from_file_at_size(source, size, size)
except Exception:
try:
pix = GdkPixbuf.Pixbuf.new_from_file_at_size(PLACEHOLDER_PATH, size, size)
except Exception:
pix = None
if pix:
_cache_set(key, pix)
try:
store_disk_cache(path if os.path.exists(path) else PLACEHOLDER_PATH, size, pix)
except Exception:
pass
GLib.idle_add(cb, pix)
_LOADER_QUEUE.task_done()
except Exception:
try:
_LOADER_QUEUE.task_done()
except Exception:
pass
time.sleep(0.1)
def enqueue_pixbuf_load(path: str, size: int, callback: Callable[[GdkPixbuf.Pixbuf], None]):
_start_loader_workers()
key = (path if path else PLACEHOLDER_PATH, size)
pix = _cache_get(key)
if pix:
GLib.idle_add(callback, pix)
return
disk = load_disk_cache(key[0], size)
if disk:
_cache_set(key, disk)
GLib.idle_add(callback, disk)
return
try:
_LOADER_QUEUE.put((key[0], size, callback))
except Exception:
try:
pb = GdkPixbuf.Pixbuf.new_from_file_at_size(key[0], size, size)
_cache_set(key, pb)
GLib.idle_add(callback, pb)
except Exception:
try:
pb = GdkPixbuf.Pixbuf.new_from_file_at_size(PLACEHOLDER_PATH, size, size)
GLib.idle_add(callback, pb)
except Exception:
pass
# --------------------------------------------------------------------------
# Helper to close previews
# --------------------------------------------------------------------------
def close_all_previews():
try:
with ACTIVE_PREVIEWS_LOCK:
for p in list(ACTIVE_PREVIEWS):
try:
p.destroy()
except Exception:
pass
ACTIVE_PREVIEWS.clear()
except Exception:
pass
# --------------------------------------------------------------------------
# Utility Functions
# --------------------------------------------------------------------------
def check_file_exists(path: str) -> bool:
if not os.path.isfile(path):
print(f"Required file missing: {path}")
return False
return True
# --------------------------------------------------------------------------
# LazyIconBox Widget
# --------------------------------------------------------------------------
class LazyIconBox(Gtk.EventBox):
def __init__(self, icon_name: str, icon_path: str, click_cb: Callable):
super().__init__()
self.icon_name = icon_name
self.icon_path = icon_path
self.click_cb = click_cb
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
self.add(vbox)
self.overlay = Gtk.Overlay()
vbox.pack_start(self.overlay, False, False, 0)
# Container for multiple small emblems in the top-right corner
self.top_right_emblems = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
self.top_right_emblems.set_halign(Gtk.Align.END)
self.top_right_emblems.set_valign(Gtk.Align.START)
# Make it non-visible-window (so only images show)
self.top_right_emblems.set_no_show_all(False)
self.overlay.add_overlay(self.top_right_emblems)
self.top_right_emblems.show()
self.image = Gtk.Image()
self.overlay.add(self.image)
label = Gtk.Label(label=icon_name)
label.set_ellipsize(True)
label.set_max_width_chars(15)
vbox.pack_start(label, False, False, 0)
self.connect("button-press-event", self.on_button_press)
placeholder_pix = get_or_load_pixbuf_sync(PLACEHOLDER_PATH, 64)
if placeholder_pix:
self.image.set_from_pixbuf(placeholder_pix)
self.update_icon(icon_path)
self.hover_timeout_id = None
self.popup = None
self._enlarge_image_widget = None
self.connect("enter-notify-event", self.on_mouse_enter)
self.connect("leave-notify-event", self.on_mouse_leave)
def on_mouse_enter(self, widget, event):
if self.hover_timeout_id is None:
self.hover_timeout_id = GLib.timeout_add(700, self.show_enlarged_preview)
return True
def on_mouse_leave(self, widget, event):
if self.hover_timeout_id is not None:
try:
GLib.source_remove(self.hover_timeout_id)
except Exception:
pass
self.hover_timeout_id = None
self.hide_enlarged_preview()
return True
def cancel_hover(self):
if getattr(self, "hover_timeout_id", None) is not None:
try:
GLib.source_remove(self.hover_timeout_id)
except Exception:
pass
self.hover_timeout_id = None
def show_enlarged_preview(self):
if self.popup:
try:
self.popup.destroy()
except Exception:
pass
self.popup = None
self.popup = Gtk.Window(type=Gtk.WindowType.POPUP)
self.popup.set_decorated(False)
self.popup.set_border_width(8)
self.popup.set_resizable(False)
large_placeholder = get_or_load_pixbuf_sync(PLACEHOLDER_PATH, 512)
image = Gtk.Image.new_from_pixbuf(large_placeholder)
self._enlarge_image_widget = image
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
box.pack_start(image, True, True, 0)
label = Gtk.Label(label=self.icon_name)
box.pack_start(label, False, False, 0)
self.popup.add(box)
self.popup.show_all()
try:
with ACTIVE_PREVIEWS_LOCK:
ACTIVE_PREVIEWS.add(self.popup)
except Exception:
pass
try:
display = Gdk.Display.get_default()
pointer = display.get_default_seat().get_pointer()
screen, x, y = pointer.get_position()
self.popup.move(x + 16, y + 16)
except Exception:
pass
def _set_large(pb):
if self.popup and self._enlarge_image_widget:
try:
self._enlarge_image_widget.set_from_pixbuf(pb)
except Exception:
pass
enqueue_pixbuf_load(self.icon_path, 512, _set_large)
self.hover_timeout_id = None
return False
def hide_enlarged_preview(self):
try:
with ACTIVE_PREVIEWS_LOCK:
if self.popup in ACTIVE_PREVIEWS:
ACTIVE_PREVIEWS.discard(self.popup)
except Exception:
pass
if self.popup:
try:
self.popup.destroy()
except Exception:
pass
self.popup = None
if getattr(self, "hover_timeout_id", None) is not None:
try:
GLib.source_remove(self.hover_timeout_id)
except Exception:
pass
self.hover_timeout_id = None
def update_icon(self, icon_path: str):
requested_path = icon_path if icon_path else PLACEHOLDER_PATH
placeholder_pix = get_or_load_pixbuf_sync(PLACEHOLDER_PATH, 64)
if placeholder_pix:
self.image.set_from_pixbuf(placeholder_pix)
# remove any individual emblem attributes
for attr in ('emblem', 'png_emblem', 'versions_emblem', 'warning_overlay'):
if hasattr(self, attr):
try:
w = getattr(self, attr)
# if the widget was packed into the top_right_emblems container, unparent it
if getattr(self, 'top_right_emblems', None) and w.get_parent() is self.top_right_emblems:
try:
self.top_right_emblems.remove(w)
except Exception:
pass
else:
try:
self.overlay.remove(w)
except Exception:
pass
except Exception:
pass
try:
delattr(self, attr)
except Exception:
pass
# also clear any remaining widgets inside the top_right_emblems container
try:
if getattr(self, 'top_right_emblems', None):
for child in list(self.top_right_emblems.get_children()):
try:
self.top_right_emblems.remove(child)
except Exception:
pass
except Exception:
pass
def _on_pix_loaded(pb):
try:
self.image.set_from_pixbuf(pb)
if requested_path and os.path.exists(requested_path):
self.icon_path = requested_path
else:
self.icon_path = PLACEHOLDER_PATH
except Exception:
pass
enqueue_pixbuf_load(requested_path, 64, _on_pix_loaded)
try:
if requested_path != PLACEHOLDER_PATH and os.path.islink(requested_path):
if check_file_exists(SYMLINK_EMBLEM_PATH):
emblem_pixbuf = get_or_load_pixbuf_sync(SYMLINK_EMBLEM_PATH, 16)
if emblem_pixbuf:
self.emblem = Gtk.Image.new_from_pixbuf(emblem_pixbuf)
self.emblem.set_halign(Gtk.Align.END)
self.emblem.set_valign(Gtk.Align.START)
self.top_right_emblems.pack_start(self.emblem, False, False, 0)
self.emblem.show()
except Exception:
pass
try:
if requested_path != PLACEHOLDER_PATH and requested_path.lower().endswith('.png'):
if check_file_exists(PNG_EMBLEM):
png_emblem_pixbuf = get_or_load_pixbuf_sync(PNG_EMBLEM, 16)
if png_emblem_pixbuf:
self.png_emblem = Gtk.Image.new_from_pixbuf(png_emblem_pixbuf)
self.png_emblem.set_halign(Gtk.Align.END)
self.png_emblem.set_valign(Gtk.Align.START)
self.top_right_emblems.pack_start(self.png_emblem, False, False, 0)
self.png_emblem.show()
except Exception:
pass
try:
if requested_path.lower().endswith(".svg") and os.path.exists(requested_path):
size_bytes = os.path.getsize(requested_path)
if size_bytes > 1024 * 1024:
warning_pixbuf = get_or_load_pixbuf_sync(os.path.join(SCRIPT_DIR, "warning-triangle.svg"), 20)
if warning_pixbuf:
warn_eventbox = Gtk.EventBox()
warning_img = Gtk.Image.new_from_pixbuf(warning_pixbuf)
warn_eventbox.add(warning_img)
warn_eventbox.set_tooltip_text("SVG file too large: %.1f MB" % (size_bytes / (1024 * 1024)))
warn_eventbox.set_visible_window(False)
warn_eventbox.set_halign(Gtk.Align.START)
warn_eventbox.set_valign(Gtk.Align.START)
self.warning_overlay = warn_eventbox
self.overlay.add_overlay(self.warning_overlay)
self.warning_overlay.show_all()
except Exception:
pass
# Versions emblem: show if backups exist (requires icon_helper to be set)
try:
helper = getattr(self, "icon_helper", None)
if helper:
# Try to determine category more reliably:
category = helper.current_category
# If icon_path is available, try to infer category from it relative to theme_path
try:
theme_root = helper.theme_path
if not category and theme_root and self.icon_path:
try:
rel = os.path.relpath(self.icon_path, theme_root)
parts = rel.split(os.sep)
# Expect structure like "<category>/<size>/<file>"
if len(parts) >= 2:
category = parts[0]
except Exception:
category = category
except Exception:
pass
# Final fallback: scan icon_categories to find the icon name
if not category:
for cat, icons in helper.icon_categories.items():
if self.icon_name in icons:
category = cat
break
if category:
backups = helper.list_backups(self.icon_name, category)
if backups:
# Add emblem overlay same way as PNG_EMBLEM / SYMLINK_EMBLEM
if check_file_exists(BACKUP_EMBLEM_PATH):
try:
versions_pix = get_or_load_pixbuf_sync(BACKUP_EMBLEM_PATH, 16)
if versions_pix:
self.versions_emblem = Gtk.Image.new_from_pixbuf(versions_pix)
# match position/style of PNG/SYMLINK emblems (END / START)
self.versions_emblem.set_halign(Gtk.Align.END)
self.versions_emblem.set_valign(Gtk.Align.START)
self.overlay.add_overlay(self.versions_emblem)
self.versions_emblem.show()
except Exception:
pass
except Exception:
pass
def on_button_press(self, widget, event):
if event.button == 3:
self.show_context_menu(event)
return True
elif event.button == 1:
self.click_cb(self.icon_path, self.icon_name)
return True
return False
def delete_icon(self, menu_item):
dialog = Gtk.MessageDialog(
transient_for=self.get_toplevel(),
flags=0,
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.YES_NO,
text=f"Delete icon '{self.icon_name}' in all sizes?",
)
dialog.format_secondary_text(
"This will delete all files (PNG, SVG, symlinks) with this name for all sizes in this category."
)
remove_check = Gtk.CheckButton(label="Permanently remove icon from theme")
remove_check.set_tooltip_text("Also remove this icon from the icon list (JSON) so it never appears again.")
dialog.get_content_area().pack_start(remove_check, False, False, 0)
dialog.show_all()
response = dialog.run()
remove_from_json = remove_check.get_active()
dialog.destroy()
if response == Gtk.ResponseType.YES and hasattr(self, 'icon_helper'):
self.icon_helper.delete_icon_files(self.icon_name, remove_from_json=remove_from_json)
def show_context_menu(self, event):
menu = Gtk.Menu()
is_missing = (self.icon_path == PLACEHOLDER_PATH)
is_svg = (not is_missing and self.icon_path.lower().endswith(".svg") and not os.path.islink(self.icon_path))
if is_svg:
edit_item = Gtk.MenuItem(label="Edit Metadata")
edit_item.connect("activate", self.edit_metadata)
menu.append(edit_item)
# Versions submenu if helper has backups
try:
helper = getattr(self, "icon_helper", None)
if helper:
category = helper.current_category
if category is None:
for cat, icons in helper.icon_categories.items():
if self.icon_name in icons:
category = cat
break
if category:
if helper.list_backups(self.icon_name, category):
versions_item = Gtk.MenuItem(label="Versions...")
versions_item.connect("activate", lambda w: helper.show_versions_dialog(self.icon_name, category))
menu.append(versions_item)
except Exception:
pass
if not is_missing:
clear_item = Gtk.MenuItem(label="Clear Existing Icon")
clear_item.connect("activate", self.clear_icon)
menu.append(clear_item)
remove_item = Gtk.MenuItem(label="Permanently remove icon from theme")
remove_item.connect("activate", self.permanently_remove_icon)
menu.append(remove_item)
menu.show_all()
menu.popup(None, None, None, None, event.button, event.time)
def show_metadata_menu(self, event):
menu = Gtk.Menu()
edit_item = Gtk.MenuItem(label="Edit Metadata")
edit_item.connect("activate", self.edit_metadata)
menu.append(edit_item)
menu.show_all()
menu.popup(None, None, None, None, event.button, event.time)
def edit_metadata(self, menu_item):
if hasattr(self, 'icon_helper'):
self.icon_helper.show_svg_metadata_dialog(self.icon_path)
def clear_icon(self, menu_item):
dialog = Gtk.MessageDialog(
transient_for=self.get_toplevel(),
flags=0,
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.YES_NO,
text=f"Clear '{self.icon_name}'?",
)
dialog.format_secondary_text(
"This will clear the existing bitmaps and svg files from the theme and leave a empty icon."
)
dialog.show_all()
response = dialog.run()
dialog.destroy()
if hasattr(self, 'icon_helper'):
self.icon_helper.delete_icon_files(self.icon_name, remove_from_json=False)
def permanently_remove_icon(self, menu_item):
dialog = Gtk.MessageDialog(
transient_for=self.get_toplevel(),
flags=0,
message_type=Gtk.MessageType.QUESTION,
buttons=Gtk.ButtonsType.YES_NO,
text=f"Permanently remove '{self.icon_name}' from the theme?",
)
dialog.format_secondary_text(
"This will remove the icon from the icon list and it will not show up (even as missing) in this category."
)
dialog.show_all()
response = dialog.run()
dialog.destroy()
if hasattr(self, 'icon_helper'):
self.icon_helper.delete_icon_files(self.icon_name, remove_from_json=True)
# --------------------------------------------------------------------------
# IconThemeHelper Main Window
# --------------------------------------------------------------------------
class IconThemeHelper(Gtk.Window):
def __init__(self):
super().__init__(title="Icon Theme Helper")
self.set_default_size(1200, 800)
self.icon_categories: Dict[str, List[str]] = {}
self.theme_path: Optional[str] = None
self.current_category: Optional[str] = None
self.icon_index: Dict[str, str] = {}
self.icon_boxes: List[LazyIconBox] = []
self.indexing_done: bool = False
self._export_progress_dialog = None
self._export_progress_bar = None
self._export_progress_label = None
self._export_total_tasks = 0
self._export_done_tasks = 0
self._export_cancel_requested = False
self._export_lock = threading.Lock()
icon_path = os.path.join(SCRIPT_DIR, 'icon-helper-logo.svg')
if os.path.exists(icon_path):
self.set_icon_from_file(icon_path)
self.search_text: str = ""
if not check_file_exists(CATEGORIES_FILE):
self.show_message("Error", f"Missing categories file: {CATEGORIES_FILE}")
return
try:
with open(CATEGORIES_FILE, "r", encoding="utf-8") as f:
self.icon_categories = json.load(f)
except Exception as e:
self.show_message("Error", f"Cannot load categories: {e}")
return
self._page_loaded_until = 0
self._current_filtered_list: List[str] = []
self.current_status_filter = "All Icons"
self.setup_ui()
def setup_ui(self):