-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlock_screen.py
More file actions
424 lines (358 loc) · 14.6 KB
/
lock_screen.py
File metadata and controls
424 lines (358 loc) · 14.6 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
import webview
import threading
import os
import queue
import json
class LockScreenManager:
def __init__(self, config_file="config.json"):
self.window = None
self.is_shown = False
self.command_queue = queue.Queue()
# 从配置文件读取参数
self.config = self._load_config(config_file)
# 创建一个隐藏的初始窗口以满足webview的要求
self._create_hidden_window()
def _load_config(self, config_file):
"""加载配置文件"""
try:
with open(config_file, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
return {}
except Exception as e:
print(f"加载配置文件出错: {e}")
return {}
def _create_hidden_window(self):
"""创建一个隐藏的初始窗口以满足webview的要求"""
# 获取当前脚本目录
current_dir = os.path.dirname(os.path.abspath(__file__))
html_path = os.path.join(current_dir, 'assets', 'index.html')
# 如果HTML文件不存在,创建一个默认的
if not os.path.exists(html_path):
os.makedirs(os.path.join(current_dir, 'assets'), exist_ok=True)
with open(html_path, 'w', encoding='utf-8') as f:
f.write(self._get_default_html())
else:
# 如果HTML文件存在,读取并更新其中的配置
with open(html_path, 'r', encoding='utf-8') as f:
html_content = f.read()
# 更新HTML内容中的配置
updated_html = self._update_html_config(html_content)
# 写回文件
with open(html_path, 'w', encoding='utf-8') as f:
f.write(updated_html)
# 获取窗口设置
window_settings = self.config.get("window_settings", {})
# 创建一个隐藏的窗口
self.hidden_window = webview.create_window(
'LockPoster-Hidden',
html_path,
width=1,
height=1,
hidden=True,
fullscreen=window_settings.get("fullscreen", True),
frameless=window_settings.get("frameless", True),
on_top=window_settings.get("on_top", True),
easy_drag=window_settings.get("easy_drag", False)
)
def show_lock_screen(self):
"""显示锁屏界面"""
if not self.is_shown:
self.is_shown = True
# 使用队列机制在主线程中创建窗口
self.command_queue.put(('show', None))
def hide_lock_screen(self):
"""隐藏锁屏界面"""
if self.is_shown:
self.is_shown = False
# 使用队列机制在主线程中销毁窗口
self.command_queue.put(('hide', None))
def process_commands(self):
"""处理命令队列,在主线程中调用"""
try:
while True:
command, data = self.command_queue.get_nowait()
if command == 'show':
self._create_window()
elif command == 'hide' and self.window:
try:
self.window.destroy()
except:
pass # 窗口可能已经关闭
self.command_queue.task_done()
except queue.Empty:
pass
def _create_window(self):
"""创建锁屏窗口"""
# 获取当前脚本目录
current_dir = os.path.dirname(os.path.abspath(__file__))
html_path = os.path.join(current_dir, 'assets', 'index.html')
# 如果HTML文件不存在,创建一个默认的
if not os.path.exists(html_path):
os.makedirs(os.path.join(current_dir, 'assets'), exist_ok=True)
with open(html_path, 'w', encoding='utf-8') as f:
f.write(self._get_default_html())
else:
# 如果HTML文件存在,读取并更新其中的配置
with open(html_path, 'r', encoding='utf-8') as f:
html_content = f.read()
# 更新HTML内容中的配置
updated_html = self._update_html_config(html_content)
# 写回文件
with open(html_path, 'w', encoding='utf-8') as f:
f.write(updated_html)
# 获取窗口设置
window_settings = self.config.get("window_settings", {})
# 创建全屏无边框窗口
self.window = webview.create_window(
'LockPoster',
html_path,
fullscreen=window_settings.get("fullscreen", True),
frameless=window_settings.get("frameless", True),
on_top=window_settings.get("on_top", True),
easy_drag=window_settings.get("easy_drag", False)
)
# 启动webview(仅在主线程中调用)
# webview.start() 不再在这里调用,而是在主程序中统一调用
def _get_default_html(self):
"""获取默认HTML内容"""
# 读取配置中的图片目录
image_dir = self.config.get("image_dir", "images")
image_switch_interval = self.config.get("image_switch_interval", 30)
# 获取图片列表
images = []
image_dir_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), image_dir)
if os.path.exists(image_dir_path):
for file in os.listdir(image_dir_path):
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
images.append(file)
# 如果没有找到图片,使用默认图片
if not images:
images = ['1.png', '2.png']
# 生成图片列表的JavaScript数组
image_list_js = ',\n '.join([f"'{image_dir}/{img}'" for img in images])
print(image_list_js)
return f'''<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>LockPoster</title>
<style>
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
}}
body {{
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
font-family: 'Microsoft YaHei', sans-serif;
overflow: hidden;
position: relative;
}}
/* 背景图片容器 */
.background-container {{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
}}
.background-image {{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0;
transition: opacity 2s ease-in-out;
}}
.background-image.active {{
opacity: 1;
}}
/* 时间容器 */
.container {{
text-align: center;
z-index: 2;
border-radius: 20px;
padding: 40px 60px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(10px);
/* 使用白色文字配合黑色描边,确保在任何背景下都清晰可见 */
color: white;
text-shadow:
-2px -2px 0 #000,
2px -2px 0 #000,
-2px 2px 0 #000,
2px 2px 0 #000;
}}
.time {{
font-size: 6rem;
font-weight: 300;
letter-spacing: 2px;
margin-bottom: 10px;
font-family: 'Arial', sans-serif;
}}
.date {{
font-size: 2rem;
font-weight: 300;
letter-spacing: 1px;
opacity: 0.9;
}}
/* 粒子效果 */
.particles {{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
}}
.particle {{
position: absolute;
border-radius: 50%;
background: rgba(255, 255, 255, 0.8);
animation: float linear infinite;
}}
@keyframes float {{
to {{
transform: translateY(-100px) rotate(360deg);
opacity: 0;
}}
}}
</style>
</head>
<body>
<!-- 背景图片容器 -->
<div class="background-container" id="backgroundContainer"></div>
<!-- 粒子效果 -->
<div class="particles" id="particles"></div>
<!-- 时间显示容器 -->
<div class="container">
<div class="time" id="time">00:00:00</div>
<div class="date" id="date">YYYY年MM月DD日 星期X</div>
</div>
<script>
// 图片切换相关变量
let images = [];
let currentImageIndex = 0;
let imageSwitchInterval = {image_switch_interval} * 1000; // 转换为毫秒
// 创建粒子效果
function createParticles() {{
const particlesContainer = document.getElementById('particles');
const particleCount = 50;
for (let i = 0; i < particleCount; i++) {{
const particle = document.createElement('div');
particle.classList.add('particle');
// 随机大小
const size = Math.random() * 10 + 2;
particle.style.width = `${{size}}px`;
particle.style.height = `${{size}}px`;
// 随机位置
particle.style.left = `${{Math.random() * 100}}%`;
particle.style.top = `${{Math.random() * 100}}%`;
// 随机动画
const duration = Math.random() * 10 + 5;
const delay = Math.random() * 5;
particle.style.animationDuration = `${{duration}}s`;
particle.style.animationDelay = `${{delay}}s`;
particlesContainer.appendChild(particle);
}}
}}
// 加载图片列表
function loadImages(imageList) {{
images = imageList;
// 创建图片元素
const container = document.getElementById('backgroundContainer');
// 清空容器
container.innerHTML = '';
images.forEach((imgSrc, index) => {{
const imgElement = document.createElement('img');
imgElement.src = imgSrc;
imgElement.classList.add('background-image');
if (index === 0) {{
imgElement.classList.add('active');
}}
container.appendChild(imgElement);
}});
}}
// 切换背景图片
function switchBackgroundImage() {{
if (images.length === 0) return;
const imageElements = document.querySelectorAll('.background-image');
imageElements[currentImageIndex].classList.remove('active');
currentImageIndex = (currentImageIndex + 1) % images.length;
imageElements[currentImageIndex].classList.add('active');
}}
// 更新时间函数
function updateTime() {{
const now = new Date();
const timeStr = now.toTimeString().substr(0, 8);
const dateStr = now.getFullYear() + '年' +
String(now.getMonth()+1).padStart(2, '0') + '月' +
String(now.getDate()).padStart(2, '0') + '日';
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
const weekdayStr = weekdays[now.getDay()];
document.getElementById('time').textContent = timeStr;
document.getElementById('date').textContent = dateStr + ' ' + weekdayStr;
}}
// 初始化
function init() {{
// 图片列表
const imageList = [
{image_list_js}
];
// 加载图片
loadImages(imageList);
// 创建粒子效果
createParticles();
// 更新时间
updateTime();
// 设置定时器
setInterval(updateTime, 1000);
setInterval(switchBackgroundImage, imageSwitchInterval);
}}
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);
</script>
</body>
</html>'''
def _update_html_config(self, html_content):
"""更新HTML内容中的配置"""
# 读取配置中的图片目录和切换间隔
image_dir = self.config.get("image_dir", "assets/images")
image_switch_interval = self.config.get("image_switch_interval", 30)
# 获取图片列表
images = []
image_dir_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), image_dir)
if os.path.exists(image_dir_path):
for file in os.listdir(image_dir_path):
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
images.append(file)
# 如果没有找到图片,使用默认图片
if not images:
images = ['1.png', '2.png']
# 生成图片列表的JavaScript数组
image_list_js = ',\n '.join([f"'{image_dir}/{img}'" for img in images])
# 更新图片列表
# 找到图片列表的位置并替换
start_marker = "const imageList = ["
end_marker = "];"
start_pos = html_content.find(start_marker)
if start_pos != -1:
end_pos = html_content.find(end_marker, start_pos)
if end_pos != -1:
# 提取前缀和后缀
prefix = html_content[:start_pos + len(start_marker)]
suffix = html_content[end_pos:]
# 构造新的HTML内容
new_html_content = prefix + "\n " + image_list_js + "\n " + suffix
return new_html_content
# 如果没有找到图片列表,返回原始内容
return html_content