-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
182 lines (154 loc) · 7.36 KB
/
main.py
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
app_name = 'Dynamics Theme'
version = '1.3'
import ctypes
import pystray
from PIL import Image
import winreg
import requests
import ephem
import pytz
from datetime import datetime, timezone
import threading
import time
import os
def set_windows_theme(theme): # Обновленный параметр для иконки
try:
# Открываем ключ реестра для изменения настроек темы
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", 0, winreg.KEY_WRITE) as key:
if theme == "light":
winreg.SetValueEx(key, "AppsUseLightTheme", 0, winreg.REG_DWORD, 1)
winreg.SetValueEx(key, "SystemUsesLightTheme", 0, winreg.REG_DWORD, 1)
icon.icon = Image.open("lib/icon_light.png") # Изменяем иконку на светлую
elif theme == "dark":
winreg.SetValueEx(key, "AppsUseLightTheme", 0, winreg.REG_DWORD, 0)
winreg.SetValueEx(key, "SystemUsesLightTheme", 0, winreg.REG_DWORD, 0)
icon.icon = Image.open("lib/icon_dark.png") # Изменяем иконку на тёмную
else:
print("Некорректная тема. Выберите 'light' или 'dark'.")
return False
# Уведомляем Windows о необходимости перезапуска темы
ctypes.windll.user32.SendMessageW(0xFFFF, 0x001A, 0, 0)
print(f"Тема успешно изменена на '{theme}'.")
return True
except Exception as e:
print("Ошибка при установке темы:", e)
return False
def get_system_language():
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
# Получаем текущий язык системы
GetUserDefaultUILanguage = kernel32.GetUserDefaultUILanguage
GetUserDefaultUILanguage.restype = ctypes.c_uint
lcid = GetUserDefaultUILanguage()
# Константа для получения имени языка
LOCALE_NAME_MAX_LENGTH = 85
LOCALE_SISO639LANGNAME = 0x59 # Локаль для ISO 639 языка
locale_name = ctypes.create_unicode_buffer(LOCALE_NAME_MAX_LENGTH)
# Получаем имя языка по LCID
if kernel32.GetLocaleInfoW(lcid, LOCALE_SISO639LANGNAME, locale_name, LOCALE_NAME_MAX_LENGTH):
lang = locale_name.value[:2]
return lang
else:
return 'en'
def get_current_theme(): # получение текущей темы
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize", 0, winreg.KEY_READ) as key:
current_theme = winreg.QueryValueEx(key, "AppsUseLightTheme")[0]
return current_theme
except Exception as e:
print("Ошибка при получении текущей темы:", e)
return None
def get_location(): # получение координат
try:
response = requests.get('https://ipinfo.io/json')
response.raise_for_status()
data = response.json()
latitude, longitude = map(float, data['loc'].split(','))
return latitude, longitude
except Exception as e:
print("Ошибка при получении координат:", e)
return None, None
def get_sunrise_and_sunset(latitude, longitude): # получение восхода и захода солнца
try:
observer = ephem.Observer()
observer.lat, observer.lon = str(latitude), str(longitude)
sunrise_time_utc = observer.next_rising(ephem.Sun()).datetime()
sunset_time_utc = observer.next_setting(ephem.Sun()).datetime()
return sunrise_time_utc, sunset_time_utc
except Exception as e:
print("Ошибка при определении времени восхода и захода солнца:", e)
return None, None
def sun_time_local(sunrise_datetime_utc, sunset_datetime_utc): # локальное время восхода солнца
try:
local_offset = datetime.now(timezone.utc).astimezone().utcoffset()
sunrise_time_local = sunrise_datetime_utc + local_offset
sunset_time_local = sunset_datetime_utc + local_offset
return sunrise_time_local.strftime('%H:%M:%S'), sunset_time_local.strftime('%H:%M:%S')
except Exception as e:
print("Ошибка при получении локального времени восхода и захода солнца:", e)
return None, None
def automatic_data(): # объединение функций
latitude, longitude = get_location()
if latitude is None or longitude is None:
return None
sunrise_datetime_utc, sunset_datetime_utc = get_sunrise_and_sunset(latitude, longitude)
if sunrise_datetime_utc is None or sunset_datetime_utc is None:
return None
return sun_time_local(sunrise_datetime_utc, sunset_datetime_utc)
def get_local_time(): # получение местного времени
local_time = datetime.now().strftime("%H:%M:%S")
return local_time
def select_theme(theme):
stop_event.set()
if theme == 'auto':
start_automatic()
else:
print("Автомтический режим выключен")
set_windows_theme(theme)
def start_automatic():
print("Автомтический режим включен")
global stop_event
stop_event = threading.Event()
thread = threading.Thread(target=automatic_theme)
thread.start()
def automatic_theme():
sunrise, sunset = automatic_data()
if sunrise is None or sunset is None:
print("Не удалось получить данные для автоматического режима")
return
while not stop_event.is_set():
local_time = get_local_time()
print(f"Восход: {sunrise}\nТекущее время: {local_time}\nЗаход: {sunset}")
if sunrise < local_time < sunset:
set_windows_theme("light")
else:
set_windows_theme("dark")
time.sleep(60)
def create_tray_icon(): # создание меню трея
global icon
current_theme = get_current_theme()
if current_theme is None:
return
icon = pystray.Icon("example", Image.open(f"lib/icon_{'light' if current_theme else 'dark'}.png"), app_name)
# Определяем язык и устанавливаем тексты для меню
language = get_system_language()
if language == 'ru':
menu_items = [
pystray.MenuItem("Тёмная ☾", lambda: select_theme('dark')),
pystray.MenuItem("Светлая ☼", lambda: select_theme('light')),
pystray.MenuItem("Автоматическая", lambda: select_theme('auto')),
pystray.MenuItem("Закрыть", lambda: hide_icon())
]
else:
menu_items = [
pystray.MenuItem("Dark ☾", lambda: select_theme('dark')),
pystray.MenuItem("Light ☼", lambda: select_theme('light')),
pystray.MenuItem("Automatic", lambda: select_theme('auto')),
pystray.MenuItem("Exit", lambda: hide_icon())
]
icon.menu = pystray.Menu(*menu_items)
start_automatic()
icon.run()
def hide_icon():
icon.stop()
os._exit(0)
create_tray_icon()