-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpymenu-globicons.py
More file actions
executable file
·3207 lines (2672 loc) · 141 KB
/
pymenu-globicons.py
File metadata and controls
executable file
·3207 lines (2672 loc) · 141 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 gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GdkPixbuf, Gio, GLib
import xml.etree.ElementTree as ET
import os
import cairo
import subprocess
import sys
import shlex
import json
import urllib.parse
import locale
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
# === 🌍 Sistema de Traducción ===
try:
sys.path.insert(0, '/usr/local/bin')
from pymenupuplang import TranslationManager
TR = TranslationManager(app_name="pymenupup")
except:
# Si no existe pymenupuplang.py, usar inglés
class FallbackTranslator:
def __getitem__(self, key):
return key
def get(self, key, default=None):
return default or key
def get_category_map(self):
return {}
TR = FallbackTranslator()
print("Warning: pymenupuplang not found, using English")
# Generar CATEGORY_MAP automáticamente desde archivos .lang
CATEGORY_MAP = TR.get_category_map()
# Import the pango module using GObject Introspection
gi.require_version('Pango', '1.0')
from gi.repository import Pango
CONFIG_FILE = "/root/.config/pymenu.json"
def open_directory(path):
"""
Intenta expandir la ruta y abrirla con el administrador predeterminado del sistema.
"""
expanded_path = os.path.expanduser(path)
if not os.path.exists(expanded_path):
try:
os.makedirs(expanded_path, exist_ok=True)
print(f"{TR['Folder created:']} {expanded_path}")
except Exception as e:
print(f"Error al crear la carpeta {expanded_path}: {e}")
return
try:
# Esto le pide al sistema que abra la ruta con la APP PREDETERMINADA
# (Sea Thunar, PCManFM, Nautilus, etc.)
gio_file = Gio.File.new_for_path(expanded_path)
Gio.AppInfo.launch_default_for_uri(gio_file.get_uri(), None)
except Exception as e:
# Si falla Gio, intentamos con xdg-open como respaldo
try:
subprocess.Popen(["xdg-open", expanded_path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
except Exception as ex:
print(f"Error al abrir el directorio: {ex}")
class ConfigManager:
"""Manages reading and writing the application's JSON configuration."""
def __init__(self, config_file=CONFIG_FILE):
self.config_file = config_file
self.config = self.load_config()
def get_default_config(self):
"""Devuelve una configuración predeterminada."""
return {
"window": {
"width": 715,
"height": 491,
"decorated_window": False,
"hide_header": False,
"hide_profile_pic": False,
"profile_in_places": True,
"hide_places": False,
"hide_favorites": False,
"search_bar_position": "bottom",
"search_bar_container": "apps_column",
"hide_social_networks": True,
"halign": "left",
"icon_size": 32,
"profile_pic_size": 64,
"profile_pic_shape": "square",
"hide_category_text": False,
"category_icon_size": 16,
"header_layout": "left",
"header_text_align": "center",
"hide_os_name": False,
"hide_kernel": False,
"hide_hostname": False,
"hide_app_names": False
},
"font": {
"family": "Sans",
"family_categories": "Sans",
"size_categories": 13000,
"size_names": 11000,
"size_header": 13000
},
"colors": {
"use_gtk_theme": True,
"background_opacity": 0.7,
"background": "rgba(0, 0, 0, 0.88)",
"border": "rgba(255, 255, 255, 0.1)",
"text_normal": "#deddda",
"text_header_os": "#D8DEE9",
"text_header_kernel": "#deddda",
"text_header_hostname": "#deddda",
"hover_background": "rgba(255, 255, 255, 0.10)",
"selected_background": "rgba(255, 255, 255, 0.2)",
"selected_text": "#ECEFF4",
"button_normal_background": "rgba(191, 63, 63, 0.00)",
"button_text": "rgba(222, 221, 218, 1.00)",
"categories_background": "rgba(191, 63, 63, 0.00)"
},
"paths": {
"profile_pic": "",
"profile_manager": "",
"shutdown_cmd": "",
"jwmrc_tray": "/root/.jwmrc-tray",
"tint2rc": "/root/.config/tint2/tint2rc",
"xfce_panel": "/root/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml",
"lxde_panel": "/root/.config/lxpanel/LXDE/panels/panel"
},
"search_engine": {
"engine": "duckduckgo"
},
"tray": {
"use_tint2": False,
"use_xfce": False
},
"categories": {
"excluded": []
},
"favorites": [],
"places": {
"visible_folders": ["Home", "Downloads", "Documents", "Music", "Pictures", "Videos"],
"all_available": ["Home", "Downloads", "Documents", "Music", "Pictures", "Videos"]
},
}
def load_config(self):
"""Load configuration from the JSON file or create a default one."""
if not os.path.exists(self.config_file):
print(f"Config file not found. Creating default config at {self.config_file}")
self.save_config(self.get_default_config())
return self.get_default_config()
try:
with open(self.config_file, 'r') as f:
config = json.load(f)
# Merge with default config to ensure all keys exist
default_config = self.get_default_config()
for key in default_config:
if key not in config:
config[key] = default_config[key]
elif isinstance(config[key], dict) and isinstance(default_config[key], dict):
for sub_key in default_config[key]:
if sub_key not in config[key]:
config[key][sub_key] = default_config[key][sub_key]
return config
except (IOError, json.JSONDecodeError) as e:
print(f"Error loading config file: {e}. Using default settings.")
return self.get_default_config()
def save_config(self, config_data):
"""Save configuration to the JSON file."""
config_dir = os.path.dirname(self.config_file)
if not os.path.exists(config_dir):
os.makedirs(config_dir, exist_ok=True)
with open(self.config_file, 'w') as f:
json.dump(config_data, f, indent=4)
def detect_window_manager():
"""
Detecta el window manager desde /etc/windowmanager.
Retorna 'openbox' si encuentra openbox-session, 'jwm' en cualquier otro caso.
"""
try:
with open('/etc/windowmanager', 'r') as f:
wm_content = f.read().strip().lower()
if 'openbox-session' in wm_content or 'openbox' in wm_content:
return 'openbox'
elif 'xfce' in wm_content or 'xfce4' in wm_content:
return 'xfce'
elif 'lxde' in wm_content or 'lxpanel' in wm_content:
return 'lxde'
except FileNotFoundError:
print(f"{TR['File /etc/windowmanager not found, assuming JWM']}")
except Exception as e:
print(f"Error leyendo /etc/windowmanager: {e}")
return 'jwm'
def apply_circular_mask(pixbuf):
"""Aplica una máscara circular a un GdkPixbuf, mostrando la imagen dentro del círculo."""
try:
width = pixbuf.get_width()
height = pixbuf.get_height()
# Determinar el tamaño del cuadrado más pequeño
size = min(width, height)
# 1. Asegurar que el pixbuf tiene canal alfa
if not pixbuf.get_has_alpha():
pixbuf = pixbuf.add_alpha(True, 0, 0, 0)
# 2. Escalar a un cuadrado perfecto si no lo es
if width != height or width != size:
pixbuf = pixbuf.scale_simple(size, size, GdkPixbuf.InterpType.BILINEAR)
width = height = size
# 3. Crear una superficie temporal para la máscara
# Esta será completamente negra (transparente)
mask_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size, size)
mask_cr = cairo.Context(mask_surface)
# Llenar de negro transparente
mask_cr.set_source_rgba(0, 0, 0, 0)
mask_cr.paint()
# Dibujar un círculo blanco opaco en la máscara
# donde queremos que se vea la imagen
center_x = size / 2.0
center_y = size / 2.0
radius = size / 2.0
mask_cr.arc(center_x, center_y, radius, 0, 2 * 3.141592653589793)
mask_cr.set_source_rgba(1, 1, 1, 1) # Blanco opaco
mask_cr.fill()
# 4. Convertir el pixbuf a una superficie Cairo
original_surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, 0, None)
# 5. Crear la superficie final
final_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size, size)
final_cr = cairo.Context(final_surface)
# Dibujar la imagen original
final_cr.set_source_surface(original_surface, 0, 0)
final_cr.paint()
# Aplicar la máscara usando el operador IN
# Esto mantiene solo la parte de la imagen dentro del círculo
final_cr.set_source_surface(mask_surface, 0, 0)
final_cr.set_operator(cairo.OPERATOR_DEST_IN)
final_cr.paint()
# 6. Convertir la superficie final a GdkPixbuf
new_pixbuf = Gdk.pixbuf_get_from_surface(final_surface, 0, 0, size, size)
if new_pixbuf:
return new_pixbuf
else:
print("⚠️ Advertencia: No se pudo crear pixbuf circular, devolviendo original")
return pixbuf
except Exception as e:
print(f"❌ Error aplicando máscara circular: {e}")
import traceback
traceback.print_exc()
return pixbuf
class JWMMenuParser:
def __init__(self, jwm_file="/usr/share/jwm/jwm/jwmrc"):
self.jwm_file = jwm_file
self.applications = {}
self.icon_paths = []
self.tray_config = None
def parse_tray_config(self):
"""Parse tint2, XFCE, LXDE or JWM config based on user preference to get tray position and size"""
tray_info = {
'height': 30,
'width': 1300,
'valign': 'bottom',
'halign': 'center',
'layer': 'above',
'autohide': 'off',
'source': 'default'
}
# Leer preferencia de configuración desde el ConfigManager
config_manager = ConfigManager()
config = config_manager.config
# NUEVA FUNCIONALIDAD: Detectar automáticamente el window manager
detected_wm = detect_window_manager()
# Si es Openbox, forzar uso de tint2
if detected_wm == 'openbox':
use_tint2 = True
use_xfce = False
use_lxde = False
print(f"🔍 {TR['Window Manager detected:']} Openbox → {TR['Automatically using Tint2 config']}")
elif detected_wm == 'xfce':
use_tint2 = False
use_xfce = True
use_lxde = False
print(f"🔍 {TR['Window Manager detected:']} XFCE → {TR['Automatically using XFCE config']}")
# Guardar ruta del config para monitorear después
self.xfce_config_file = os.path.expanduser("~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml")
elif detected_wm == 'lxde':
use_tint2 = False
use_xfce = False
use_lxde = True
print(f"🔍 {TR['Window Manager detected:']} LXDE → {TR['Automatically using LXDE config']}")
else:
# Si es JWM, usar la preferencia del usuario del JSON
use_tint2 = config.get('tray', {}).get('use_tint2', False)
use_xfce = config.get('tray', {}).get('use_xfce', False)
use_lxde = config.get('tray', {}).get('use_lxde', False)
print(f"🔍 Window Manager detectado: JWM → Usando configuración del usuario (use_tint2={use_tint2}, use_xfce={use_xfce}, use_lxde={use_lxde})")
# PRIMERO: Intentar con XFCE si está configurado o detectado
if use_xfce or detected_wm == 'xfce':
xfce_config = self.parse_xfce_panel_config()
if xfce_config:
tray_info.update(xfce_config)
tray_info['source'] = 'xfce'
print(f"✅ Configuración de panel detectada desde XFCE: {tray_info}")
self.tray_config = tray_info
return tray_info
# SEGUNDO: Intentar con LXDE si está configurado o detectado
if use_lxde or detected_wm == 'lxde':
lxde_config = self.parse_lxde_panel_config()
if lxde_config:
tray_info.update(lxde_config)
tray_info['source'] = 'lxde'
print(f"✅ Configuración de panel detectada desde LXDE: {tray_info}")
self.tray_config = tray_info
return tray_info
# TERCERO: Intentar con Tint2 si está configurado
if use_tint2 or detected_wm == 'openbox':
tint2_config = config.get('paths', {}).get('tint2rc', os.path.expanduser("/usr/share/tint2/tint2/tint2rc"))
tint2_config = os.path.expanduser(tint2_config)
if os.path.exists(tint2_config):
try:
with open(tint2_config, 'r') as f:
for line in f:
line = line.strip()
# Extraer panel_size = 80% 30
if line.startswith('panel_size'):
parts = line.split('=')
if len(parts) == 2:
size_parts = parts[1].strip().split()
if len(size_parts) >= 2:
try:
tray_info['height'] = int(size_parts[1])
except ValueError:
pass
# Extraer panel_position = bottom center horizontal
elif line.startswith('panel_position'):
parts = line.split('=')
if len(parts) == 2:
pos_parts = parts[1].strip().split()
if len(pos_parts) >= 2:
# Primer valor: top/bottom
valign = pos_parts[0].lower()
if valign in ['top', 'bottom']:
tray_info['valign'] = valign
# Segundo valor: left/center/right
halign = pos_parts[1].lower()
if halign in ['left', 'center', 'right']:
tray_info['halign'] = halign
tray_info['source'] = 'tint2'
print(f"✅ Configuración de tray detectada desde tint2rc: {tray_info}")
self.tray_config = tray_info
return tray_info
except Exception as e:
print(f"❌ Error parsing tint2 config: {e}")
else:
print(f"⚠️ Tint2 config no encontrado en: {tint2_config}")
# TERCERO: Si no usa XFCE o Tint2, o fallaron, intentar con JWM
try:
jwm_tray_file = config.get('paths', {}).get('jwmrc_tray', os.path.expanduser("/usr/share/jwm/jwm/jwmrc-tray"))
jwm_tray_file = os.path.expanduser(jwm_tray_file)
if os.path.exists(jwm_tray_file):
target_file = jwm_tray_file
else:
target_file = self.jwm_file
if not os.path.exists(target_file):
print(f"JWM file not found: {target_file}")
self.tray_config = tray_info
return tray_info
tree = ET.parse(target_file)
root = tree.getroot()
tray_element = root.find('.//Tray')
if tray_element is not None:
tray_info['height'] = int(tray_element.get('height', '30'))
tray_info['width'] = int(tray_element.get('width', '1300'))
tray_info['valign'] = tray_element.get('valign', 'bottom').lower()
tray_info['halign'] = tray_element.get('halign', 'center').lower()
tray_info['layer'] = tray_element.get('layer', 'above').lower()
tray_info['autohide'] = tray_element.get('autohide', 'off').lower()
tray_info['source'] = 'jwm'
print(f"✅ Configuración de tray detectada desde {target_file}: {tray_info}")
except Exception as e:
print(f"❌ Error parsing JWM tray config: {e}")
self.tray_config = tray_info
return tray_info
def parse_jwm_menu(self):
"""Parse JWM menu file and extract applications"""
try:
if not os.path.exists(self.jwm_file):
print(f"JWM file not found: {self.jwm_file}")
return self.get_fallback_applications()
tree = ET.parse(self.jwm_file)
root = tree.getroot()
self.icon_paths = self.extract_icon_paths(root)
applications = {}
for menu in root.findall('.//Menu'):
label = menu.get('label', 'Unknown')
if label:
# NUEVA LÍNEA: Normalizar nombre de categoría
normalized_label = CATEGORY_MAP.get(label, label)
apps = self.extract_programs_from_menu(menu)
if apps:
if normalized_label not in applications:
applications[normalized_label] = []
applications[normalized_label].extend(apps)
root_programs = []
# Buscar elementos Program directos bajo root
for program in root.findall('./Program'):
label = program.get('label', '')
icon = program.get('icon', '')
tooltip = program.get('tooltip', '')
command = program.text.strip() if program.text else ''
if label and command:
app_info = {
'Name': label,
'Exec': command,
'Icon': icon,
'Comment': tooltip or label,
'Terminal': 'terminal' in command.lower() or 'urxvt' in command.lower(),
'Categories': []
}
if label.lower() in ['help', 'ayuda']:
if 'Help' not in applications:
applications['Help'] = []
applications['Help'].append(app_info)
elif label.lower() in ['leave', 'salir', 'exit', 'logout']:
if 'Leave' not in applications:
applications['Leave'] = []
applications['Leave'].append(app_info)
else:
root_programs.append(app_info)
# También buscar elementos Program dentro de RootMenu
for root_menu in root.findall('.//RootMenu'):
for program in root_menu.findall('./Program'):
label = program.get('label', '')
icon = program.get('icon', '')
tooltip = program.get('tooltip', '')
command = program.text.strip() if program.text else ''
if label and command:
app_info = {
'Name': label,
'Exec': command,
'Icon': icon,
'Comment': tooltip or label,
'Terminal': 'terminal' in command.lower() or 'urxvt' in command.lower(),
'Categories': []
}
if label.lower() in ['help', 'ayuda']:
if 'Help' not in applications:
applications['Help'] = []
applications['Help'].append(app_info)
elif label.lower() in ['leave', 'salir', 'exit', 'logout']:
if 'Leave' not in applications:
applications['Leave'] = []
applications['Leave'].append(app_info)
else:
root_programs.append(app_info)
if root_programs:
applications['System'] = applications.get('System', []) + root_programs
return applications if applications else self.get_fallback_applications()
except Exception as e:
print(f"Error parsing JWM menu: {e}")
return self.get_fallback_applications()
def parse_xfce_panel_config(self):
"""Parse XFCE panel configuration - supports multiple panels"""
xfce_config = None
xfce_config_paths = [
os.path.expanduser("~/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml"),
"/etc/xdg/xfce4/panel/default.xml",
"/usr/share/xfce4/panel/default.xml"
]
for config_file in xfce_config_paths:
if os.path.exists(config_file):
try:
tree = ET.parse(config_file)
root = tree.getroot()
# Buscar TODOS los paneles manualmente (panel-1, panel-2, etc.)
# No podemos usar starts-with() en ElementTree
all_properties = root.findall(".//property")
panels = [p for p in all_properties if p.get('name', '').startswith('panel-')]
print(f"🔍 DEBUG: Encontrados {len(panels)} paneles en {config_file}")
for panel in panels:
panel_name = panel.get('name')
temp_config = {}
# Tamaño
size_elem = panel.find(".//property[@name='size']")
if size_elem is not None:
temp_config['height'] = int(size_elem.get('value', '30'))
# Longitud
length_elem = panel.find(".//property[@name='length']")
if length_elem is not None:
try:
length_percent = float(length_elem.get('value', '100'))
temp_config['width'] = int(1920 * (length_percent / 100))
except ValueError:
temp_config['width'] = 1300
# Posición
position_elem = panel.find(".//property[@name='position']")
if position_elem is not None:
position = position_elem.get('value', 'p=6;')
print(f"🔍 DEBUG: {panel_name} position = '{position}'")
# WORKAROUND: Usar coordenada Y como fallback
y_coord = None
if 'y=' in position:
try:
y_str = position.split('y=')[1].split(';')[0]
y_coord = int(y_str)
print(f" → Y coordinate: {y_coord}")
except:
pass
if 'p=' in position:
p_value = position.split('p=')[1].split(';')[0]
try:
p_int = int(p_value)
# Top positions: 12, 2, 4
if p_int in [12, 2, 4]:
temp_config['valign'] = 'top'
# Bottom positions: 6, 8, 10
elif p_int in [6, 8, 10]:
temp_config['valign'] = 'bottom'
else:
temp_config['valign'] = 'bottom'
# Horizontal alignment
if p_int in [8, 12]: # Left
temp_config['halign'] = 'left'
elif p_int in [10, 4]: # Right
temp_config['halign'] = 'right'
else: # Center
temp_config['halign'] = 'center'
# WORKAROUND: Si Y es bajo (<100), forzar TOP
if y_coord is not None and y_coord < 100:
temp_config['valign'] = 'top'
print(f" ⚠️ XML dice bottom pero Y={y_coord} indica TOP - corrigiendo")
print(f" → Detectado: {temp_config.get('valign')} {temp_config.get('halign')}, altura {temp_config.get('height')}px")
except ValueError:
temp_config['valign'] = 'bottom'
temp_config['halign'] = 'center'
# ESTRATEGIA: Usar el panel TOP si existe, sino usar el primero que encuentre
if temp_config.get('valign') == 'top':
xfce_config = temp_config
print(f"✅ Usando {panel_name} (TOP) para posicionar el menú")
break # Priorizar panel superior
elif xfce_config is None:
xfce_config = temp_config
if xfce_config:
return xfce_config
except Exception as e:
print(f"❌ Error parsing XFCE config {config_file}: {e}")
import traceback
traceback.print_exc()
continue
return None
def extract_icon_paths(self, root):
"""Extract icon paths from JWM config"""
paths = []
for iconpath in root.findall('.//IconPath'):
if iconpath.text:
paths.append(iconpath.text.strip())
# MODIFICACIÓN: Siempre agregar rutas predeterminadas como fallback
default_paths = [
"/usr/local/lib/X11/pixmaps",
"/usr/share/pixmaps",
"/usr/share/icons/hicolor/48x48/apps",
"/usr/share/icons/hicolor/32x32/apps",
"/usr/share/icons/hicolor/64x64/apps",
"/usr/share/pixmaps/puppy"
]
# Agregar rutas que no estén ya incluidas
for path in default_paths:
if path not in paths:
paths.append(path)
return paths
def parse_lxde_panel_config(self):
"""Parse LXDE panel configuration to get position and size"""
lxde_config = {}
# Rutas comunes de configuración de LXDE
lxde_config_paths = [
os.path.expanduser("~/.config/lxpanel/LXDE/panels/panel"),
"/etc/xdg/lxpanel/LXDE/panels/panel",
"/usr/share/lxpanel/profile/LXDE/panels/panel"
]
for config_file in lxde_config_paths:
if os.path.exists(config_file):
try:
with open(config_file, 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
# Buscar configuración Global
if line.startswith('edge='):
edge = line.split('=')[1].strip()
lxde_config['valign'] = edge # top/bottom
elif line.startswith('allign='):
align = line.split('=')[1].strip()
lxde_config['halign'] = align # left/center/right
elif line.startswith('margin='):
try:
margin = int(line.split('=')[1].strip())
lxde_config['margin'] = margin
except ValueError:
pass
elif line.startswith('width='):
try:
width = int(line.split('=')[1].strip())
lxde_config['width'] = width
except ValueError:
pass
elif line.startswith('height='):
try:
height = int(line.split('=')[1].strip())
lxde_config['height'] = height
except ValueError:
pass
# Establecer valores por defecto si no se encontraron
if 'height' not in lxde_config:
lxde_config['height'] = 30
if 'width' not in lxde_config:
lxde_config['width'] = 1300
if 'valign' not in lxde_config:
lxde_config['valign'] = 'bottom'
if 'halign' not in lxde_config:
lxde_config['halign'] = 'center'
return lxde_config
except Exception as e:
print(f"❌ Error parsing LXDE config {config_file}: {e}")
continue
return None
def extract_programs_from_menu(self, menu_element):
"""Extract program entries from a menu element"""
programs = []
for program in menu_element.findall('./Program'):
label = program.get('label', '')
icon = program.get('icon', '')
tooltip = program.get('tooltip', '')
command = program.text.strip() if program.text else ''
if label and command:
app_info = {
'Name': label,
'Exec': command,
'Icon': icon,
'Comment': tooltip or label,
'Terminal': 'terminal' in command.lower() or 'urxvt' in command.lower(),
'Categories': []
}
programs.append(app_info)
return programs
def get_fallback_applications(self):
"""Fallback applications if JWM parsing fails"""
return {
'System': [
{'Name': 'Terminal', 'Exec': 'lxterminal', 'Icon': 'terminal', 'Comment': 'Terminal emulator', 'Terminal': False, 'Categories': []},
{'Name': 'File Manager', 'Exec': 'rox', 'Icon': 'folder', 'Comment': 'File manager', 'Terminal': False, 'Categories': []},
],
'Internet': [
{'Name': 'Firefox', 'Exec': 'firefox', 'Icon': 'firefox', 'Comment': 'Web browser', 'Terminal': False, 'Categories': []},
]
}
class ArcMenuLauncher(Gtk.Window):
def __init__(self, icon_size=None, jwm_file=None, x=None, y=None):
super().__init__(title="PyMenuPup")
self.config_manager = ConfigManager()
self.config = self.config_manager.config
self.is_resizing = False
# Use icon_size from config, or fallback to default
self.icon_size = self.config['window'].get('icon_size', 32)
self.parser = JWMMenuParser(jwm_file or "/root/.jwmrc")
self.tray_config = self.parser.parse_tray_config()
self.applications = self.parser.parse_jwm_menu()
self.apps_flowbox = None
self.categories_listbox = None
self.search_entry = None
self.profile_image = None
self.icon_cache = {}
self.current_category = "All"
self.hover_timeout = None
self.restore_timeout = None
self.mouse_in_menu = False
self.selected_category = None
self.hovered_category = None
self.selected_category_row = None
self.showing_favorites = False
self.favorites_cleanup_timeout = None
self.pos_x = x
self.pos_y = y
self.context_menu_active = False
screen = Gdk.Screen.get_default()
visual = screen.get_rgba_visual()
if visual and screen.is_composited():
self.set_visual(visual)
self.set_app_paintable(True)
self.apply_css()
self.setup_window()
self.create_interface()
jwm_file_path = jwm_file or "/root/.jwmrc"
self.jwm_file = Gio.File.new_for_path(jwm_file_path)
self.file_monitor = self.jwm_file.monitor_file(Gio.FileMonitorFlags.NONE, None)
self.file_monitor.connect("changed", self.on_jwm_file_changed)
print(f"{TR['Now monitoring JWM file for changes:']} {jwm_file_path}")
if hasattr(self.parser, 'xfce_config_file') and os.path.exists(self.parser.xfce_config_file):
try:
xfce_file = Gio.File.new_for_path(self.parser.xfce_config_file)
self.xfce_monitor = xfce_file.monitor_file(Gio.FileMonitorFlags.NONE, None)
self.xfce_monitor.connect("changed", self.on_xfce_panel_changed)
print(f"👀 Monitoreando cambios XFCE panel: {self.parser.xfce_config_file}")
except Exception as e:
print(f"⚠️ Error monitoreando XFCE: {e}")
def apply_css(self):
"""Loads and applies CSS from the configuration."""
# Verificar si debe usar tema GTK
use_gtk_theme = self.config['colors'].get('use_gtk_theme', False)
if use_gtk_theme:
# Si usa tema GTK, usar un fondo sólido compatible
css = """
GtkWindow, GtkEventBox {
background-color: @theme_bg_color;
border-radius: 0px;
box-shadow: none;
border: none;
}
.menu-window {
background-color: @theme_bg_color;
border-radius: 14px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.3);
border: 1px solid @theme_unfocused_fg_color;
padding: 5px 10px 10px 10px;
}
"""
print(TR['Using GTK theme colors'])
else:
# CSS personalizado original
colors = self.config['colors']
css = f"""
GtkWindow, GtkEventBox {{
background-color: {colors['background']};
border-radius: 0px;
box-shadow: none;
border: none;
}}
.tooltip, tooltip, GtkTooltip {{
background-color: {colors['background']};
color: {colors['text_normal']};
border-radius: 8px;
padding: 10px 10px;
border: 1px solid {colors['border']};
box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
}}
.menu-window {{
background-color: {colors['background']};
border-radius: 14px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.3);
border: 1px solid {colors['border']};
padding: 5px 10px 10px 10px;
}}
listbox {{
padding: 2px;
}}
listbox row {{
background-color: {self.config['colors'].get('categories_background', 'rgba(0,0,0,0.4)')};
color: {self.config['colors']['text_normal']};
border-radius: 6px;
padding: 2px;
margin: 1px;
min-height: 26px;
}}
listbox row:selected {{
background-color: {colors['selected_background']};
color: {colors['selected_text']};
}}
listbox row:hover {{
background-color: {colors['hover_background']};
}}
button {{
border-radius: 8px;
padding: 2px 2px;
background-color: {colors['button_normal_background']};
color: {colors['button_text']};
border: none;
}}
.action-button {{
border-radius: 6px;
background-color: {colors['button_normal_background']};
color: {colors['text_normal']};
border: 1px solid {colors['button_normal_background']};
}}
.action-button:hover {{
background-color: {colors['hover_background']};
}}
listbox row.selected-category {{
background-color: {colors['selected_background']};
color: {colors['selected_text']};
}}
button:hover {{
background-color: {colors['hover_background']};
}}
.search-box:focus {{
background-color: {colors['button_normal_background']};
color: {colors['text_normal']};
border: 1px solid {colors['border']} ;
border-radius: 8px;
}}
.app-box {{
min-width: {self.icon_size + 0}px;
}}
.category-list {{
background-color: {colors['categories_background']};
padding: 1px;
border-radius: 12px;
}}
menuitem {{
background-color: {colors['background']};
color: {colors['text_normal']};
border-radius: 8px;
padding: 10px 10px;
border: 1px solid {colors['border']};
box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
}}
menuitem:hover {{
background-color: {colors['hover_background']};
color: {colors['text_normal']};
}}
menuitem:selected {{
background-color: {colors['hover_background']};
color: {colors['text_normal']};
}}
.quick-access-button {{
padding: 5px;
margin: 2px;
}}
.quick-access-button:hover {{
background-color: {colors['hover_background']};
}}
#quick-access-icon {{
font-size: 18pt;
}}
.social-button {{
padding: 5px;
margin: 2px;
border-radius: 8px;
background-color: {colors['button_normal_background']};
}}
.social-button:hover {{
background-color: {colors['hover_background']};
}}
#social-icon {{
font-size: 16pt;
color: {colors['text_normal']};
}}
button.profile-circular-style {{
/* Esto hace que el botón sea circular */
border-radius: 50%;
padding: 0;
border: none;
min-width: 64px;
min-height: 64px;
}}
button.profile-circular-style:hover {{
/* Esto define el efecto HOVER circular */
background-color: rgba(255, 255, 255, 0.1);
box-shadow: none;
}}
"""
print("Using custom colors")
style_provider = Gtk.CssProvider()