-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtray_indicator.py
More file actions
446 lines (370 loc) · 15.1 KB
/
Copy pathtray_indicator.py
File metadata and controls
446 lines (370 loc) · 15.1 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
"""
System Tray Indicator for Lightgiz
Enhanced with mode selection, quick colors, and device controls
"""
import logging
import threading
import time
from PIL import Image, ImageDraw
import pystray
from pystray import MenuItem as item
from config_manager import (
MODE_OFF, MODE_STATIC, MODE_AMBILIGHT, MODE_AUDIO, MODE_EFFECT,
AUDIO_MODE_BASS, AUDIO_MODE_SPECTRUM, AUDIO_MODE_ADAPTIVE,
AUDIO_MODE_STROBE, AUDIO_MODE_COLOR_FADE, AUDIO_MODE_VU_METER,
AUDIO_MODE_RAINBOW_REACT, AUDIO_MODE_DUAL_COLOR, AUDIO_MODE_FREQ_SPLIT,
COLOR_PRESETS
)
logger = logging.getLogger(__name__)
# IMPORTANT: Set up DBus GLib integration BEFORE pystray/GTK starts
# This ensures DBus signals work properly with GTK's main loop
try:
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
logger.debug("DBusGMainLoop set as default")
except ImportError:
logger.warning("dbus-python not available")
# Try to import GTK for settings window
try:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
GTK_AVAILABLE = True
except ImportError:
GTK_AVAILABLE = False
logger.warning("GTK not available, settings window disabled")
# Mode display names (English)
MODE_NAMES = {
MODE_OFF: '⚫ Off',
MODE_STATIC: '🎨 Static',
MODE_AMBILIGHT: '🖥️ Ambilight',
MODE_AUDIO: '🎵 Audio Reactive',
MODE_EFFECT: '✨ Effects',
}
# Quick color presets
QUICK_COLORS = {
'white': ('⚪ White', (255, 255, 255)),
'red': ('🔴 Red', (255, 0, 0)),
'green': ('🟢 Green', (0, 255, 0)),
'blue': ('🔵 Blue', (0, 0, 255)),
'yellow': ('🟡 Yellow', (255, 255, 0)),
'purple': ('🟣 Purple', (128, 0, 255)),
'cyan': ('🔵 Cyan', (0, 255, 255)),
'orange': ('🟠 Orange', (255, 100, 0)),
}
# Effect types
EFFECT_NAMES = {
'rainbow': '🌈 Rainbow',
'breathing': '💨 Breathing',
'pulse': '💓 Pulse',
'fire': '🔥 Fire',
'wave': '🌊 Wave',
}
# Audio modes
AUDIO_MODE_NAMES = {
AUDIO_MODE_BASS: '🎸 Bass Pulse',
AUDIO_MODE_SPECTRUM: '🌈 Spectrum',
AUDIO_MODE_ADAPTIVE: '🎵 Adaptive',
AUDIO_MODE_STROBE: '⚡ Strobe/Flash',
AUDIO_MODE_COLOR_FADE: '🔀 Color Fade',
AUDIO_MODE_VU_METER: '📊 VU Meter',
AUDIO_MODE_RAINBOW_REACT: '🌈 Rainbow React',
AUDIO_MODE_DUAL_COLOR: '🔄 Dual Color',
AUDIO_MODE_FREQ_SPLIT: '🎚️ Freq Split',
}
def create_icon_image(mode: str = MODE_OFF, config_manager=None) -> Image.Image:
"""Create tray icon based on current mode and user customization settings."""
# Get customization settings from config
if config_manager:
style = config_manager.get('tray_icon_style', 'bulb')
custom_color = config_manager.get('tray_icon_color', 'auto')
size = config_manager.get('tray_icon_size', 64)
show_mode_color = config_manager.get('tray_icon_show_mode_color', True)
else:
style = 'bulb'
custom_color = 'auto'
size = 64
show_mode_color = True
width = size
height = size
image = Image.new('RGBA', (width, height), (0, 0, 0, 0))
dc = ImageDraw.Draw(image)
# Mode-based background colors
mode_colors = {
MODE_OFF: (80, 80, 80),
MODE_STATIC: (88, 101, 242),
MODE_AMBILIGHT: (50, 200, 100),
MODE_AUDIO: (255, 100, 50),
MODE_EFFECT: (200, 50, 200),
}
# Determine background color
if custom_color != 'auto' and isinstance(custom_color, (tuple, list)):
bg_color = tuple(custom_color[:3])
elif show_mode_color:
bg_color = mode_colors.get(mode, (88, 101, 242))
else:
bg_color = (88, 101, 242) # Default brand color
# Scale factors based on size
scale = size / 64.0
# Draw icon based on style
if style == 'circle':
# Simple circle style
margin = int(4 * scale)
dc.ellipse((margin, margin, width - margin, height - margin), fill=bg_color)
# Inner highlight
inner_margin = int(16 * scale)
highlight_color = tuple(min(255, c + 60) for c in bg_color)
dc.ellipse((inner_margin, inner_margin, width - inner_margin, height - inner_margin),
fill=highlight_color)
elif style == 'square':
# Rounded square style
margin = int(4 * scale)
dc.rounded_rectangle((margin, margin, width - margin, height - margin),
radius=int(8 * scale), fill=bg_color)
# Inner "L" for Lightgiz
inner_margin = int(18 * scale)
text_color = (255, 255, 255)
dc.rectangle((inner_margin, inner_margin, inner_margin + int(8 * scale), height - inner_margin),
fill=text_color)
dc.rectangle((inner_margin, height - inner_margin - int(8 * scale), width - inner_margin, height - inner_margin),
fill=text_color)
else: # 'bulb' style (default)
# Background circle
margin = int(4 * scale)
dc.ellipse((margin, margin, width - margin, height - margin), fill=bg_color)
# Light bulb symbol
bulb_top = int(15 * scale)
bulb_bottom = int(40 * scale)
bulb_left = int(20 * scale)
bulb_right = int(44 * scale)
dc.ellipse((bulb_left, bulb_top, bulb_right, bulb_bottom), fill=(255, 255, 200))
# Bulb base
base_left = int(26 * scale)
base_right = int(38 * scale)
base_top = int(40 * scale)
base_bottom = int(50 * scale)
dc.rectangle((base_left, base_top, base_right, base_bottom), fill=(200, 200, 200))
return image
def run_with_tray(daemon):
"""Run the daemon with a system tray icon."""
# Start the daemon loop in a background thread
daemon_thread = threading.Thread(target=daemon.run, daemon=True)
daemon_thread.start()
settings_win = None
# ==========================================================================
# CALLBACK FUNCTIONS
# ==========================================================================
def on_mode_change(mode: str):
"""Change operating mode."""
def callback(icon, item):
daemon.set_mode(mode)
update_icon()
return callback
def on_effect_change(effect: str):
"""Change effect type."""
def callback(icon, item):
daemon.config_manager.set('effect_type', effect)
daemon.set_mode(MODE_EFFECT)
update_icon()
return callback
def on_audio_mode_change(audio_mode: str):
"""Change audio mode."""
def callback(icon, item):
daemon.config_manager.set('audio_mode', audio_mode)
daemon.set_mode(MODE_AUDIO)
update_icon()
return callback
def on_quick_color(color_key: str):
"""Apply quick color to all devices."""
def callback(icon, item):
_, color = QUICK_COLORS[color_key]
daemon.set_static_color_all(color)
daemon.set_mode(MODE_STATIC)
update_icon()
return callback
def on_preset(preset_name: str):
"""Apply color preset."""
def callback(icon, item):
daemon.config_manager.apply_preset(preset_name)
daemon.set_mode(MODE_STATIC)
if daemon.config_manager.get('mode') == MODE_STATIC:
daemon._apply_static_colors()
update_icon()
return callback
def on_toggle_keyboard(icon, item):
"""Toggle keyboard enabled."""
daemon.set_keyboard_enabled(not daemon._keyboard_enabled)
def on_toggle_wiz(icon, item):
"""Toggle Wiz bulb enabled."""
daemon.set_wiz_enabled(not daemon._wiz_enabled)
def on_settings(icon, item):
"""Open settings window."""
nonlocal settings_win
if not GTK_AVAILABLE:
logger.warning("GTK not available for settings window")
return
def show_window():
nonlocal settings_win
try:
from settings_window import SettingsWindow
if settings_win is None:
settings_win = SettingsWindow(daemon)
settings_win.connect('destroy', lambda w: cleanup_window())
settings_win.show_all()
settings_win.present()
except Exception as e:
logger.error(f"Failed to open settings: {e}")
def cleanup_window():
nonlocal settings_win
settings_win = None
GLib.idle_add(show_window)
def on_quit(icon, item):
"""Quit application."""
daemon.stop()
icon.stop()
def update_icon():
"""Update icon based on current mode and customization settings."""
mode = daemon.config_manager.get('mode', MODE_OFF)
logger.debug(f"Updating tray icon for mode: {mode}")
icon.icon = create_icon_image(mode, daemon.config_manager)
# Force pystray to refresh
try:
icon.update_menu()
except Exception as e:
logger.debug(f"update_menu failed (may be normal): {e}")
def on_config_changed(key, value):
"""Handle config changes from other sources (e.g. Settings Window)."""
logger.debug(f"Tray received config change: {key}={value}")
# Update icon for mode and visual changes
if key in ['mode', 'tray_icon_style', 'tray_icon_color',
'tray_icon_size', 'tray_icon_show_mode_color',
'keyboard_enabled', 'wiz_enabled',
'audio_mode', 'effect_type']:
update_icon()
# Register listener
daemon.config_manager.add_listener(on_config_changed)
# ==========================================================================
# MENU BUILDERS
# ==========================================================================
def is_mode_checked(mode: str):
"""Check if mode is active."""
def checker(item):
return daemon.config_manager.get('mode', MODE_OFF) == mode
return checker
def is_effect_checked(effect: str):
"""Check if effect is active."""
def checker(item):
return (daemon.config_manager.get('mode') == MODE_EFFECT and
daemon.config_manager.get('effect_type') == effect)
return checker
def is_audio_mode_checked(audio_mode: str):
"""Check if audio mode is active."""
def checker(item):
return (daemon.config_manager.get('mode') == MODE_AUDIO and
daemon.config_manager.get('audio_mode') == audio_mode)
return checker
def build_mode_menu():
"""Build mode selection submenu."""
items = []
# Basic modes
for mode in [MODE_OFF, MODE_STATIC, MODE_AMBILIGHT]:
items.append(item(
MODE_NAMES[mode],
on_mode_change(mode),
checked=is_mode_checked(mode),
radio=True
))
items.append(pystray.Menu.SEPARATOR)
# Audio modes submenu
audio_items = [
item(name, on_audio_mode_change(mode), checked=is_audio_mode_checked(mode), radio=True)
for mode, name in AUDIO_MODE_NAMES.items()
]
items.append(item('🎵 Audio Reactive', pystray.Menu(*audio_items)))
# Effects submenu
effect_items = [
item(name, on_effect_change(effect), checked=is_effect_checked(effect), radio=True)
for effect, name in EFFECT_NAMES.items()
]
items.append(item('✨ Effects', pystray.Menu(*effect_items)))
return items
def build_quick_colors_menu():
"""Build quick colors submenu."""
items = [
item(name, on_quick_color(key))
for key, (name, _) in QUICK_COLORS.items()
]
return items
def on_user_schema(schema_name: str):
"""Apply user schema."""
def callback(icon, item):
daemon.config_manager.apply_user_schema(schema_name)
daemon.set_mode(MODE_STATIC)
if daemon.config_manager.get('mode') == MODE_STATIC:
daemon._apply_static_colors()
update_icon()
return callback
def build_presets_menu():
"""Build color presets submenu with built-in and user schemas."""
items = []
# Built-in presets
for name in daemon.config_manager.get_preset_names():
display_name = daemon.config_manager.get_preset_display_name(name)
items.append(item(f"🎨 {display_name}", on_preset(name)))
items.append(pystray.Menu.SEPARATOR)
# User schemas - always show submenu
user_schemas = daemon.config_manager.get_user_schema_names()
if user_schemas:
user_items = [
item(f"⭐ {name}", on_user_schema(name))
for name in user_schemas
]
else:
# Show placeholder when no schemas exist
user_items = [item("(No schemas yet)", lambda i, it: None, enabled=False)]
items.append(item("📁 My Schemas", pystray.Menu(*user_items)))
return items
def get_menu():
"""Build complete menu."""
current_mode = daemon.config_manager.get('mode', MODE_OFF)
mode_name = MODE_NAMES.get(current_mode, current_mode)
return [
# Mode selection
item(f'🔄 Mode: {mode_name}', pystray.Menu(*build_mode_menu())),
pystray.Menu.SEPARATOR,
# Device toggles
item('⌨️ Keyboard', on_toggle_keyboard,
checked=lambda i: daemon._keyboard_enabled),
item('💡 Wiz Bulb', on_toggle_wiz,
checked=lambda i: daemon._wiz_enabled),
pystray.Menu.SEPARATOR,
# Quick colors - apply to all
item('🎨 Quick Color', pystray.Menu(*build_quick_colors_menu())),
# Presets (built-in + user)
item('🌈 Schemas', pystray.Menu(*build_presets_menu())),
pystray.Menu.SEPARATOR,
# Settings & Exit
item('⚙️ Settings', on_settings),
item('❌ Exit', on_quit),
]
# ==========================================================================
# CREATE AND RUN ICON
# ==========================================================================
current_mode = daemon.config_manager.get('mode', MODE_OFF)
icon = pystray.Icon(
"Lightgiz",
create_icon_image(current_mode, daemon.config_manager),
"Lightgiz",
menu=pystray.Menu(get_menu)
)
logger.info("Starting system tray icon...")
try:
icon.run()
except Exception as e:
logger.error(f"Failed to start tray icon: {e}")
logger.info("Falling back to console mode...")
try:
while daemon._running:
time.sleep(1)
except KeyboardInterrupt:
daemon.stop()