-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoverlay.html
More file actions
482 lines (446 loc) · 20.8 KB
/
overlay.html
File metadata and controls
482 lines (446 loc) · 20.8 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Overlay</title>
<style>
body {
background: transparent;
margin: 0;
padding: 0;
overflow: hidden;
pointer-events: none;
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
}
.mosaic {
position: absolute;
pointer-events: none;
z-index: 9999;
/* 默认样式:完全透明,由后端内联样式完全控制 */
box-sizing: border-box;
border: 0;
background: transparent;
background-color: transparent;
opacity: 1;
will-change: transform, width, height;
contain: layout paint style;
}
#test {
position: fixed;
top: 10px;
left: 10px;
color: white;
background: rgba(0, 0, 0, 0.7);
padding: 5px;
font-size: 12px;
z-index: 10000;
}
#mosaic-container {
position: absolute;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
pointer-events: none;
z-index: 9998;
}
#mosaic-canvas {
position: absolute;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
pointer-events: none;
z-index: 9998;
}
</style>
</head>
<body>
<div id="mosaic-container"></div>
<canvas id="mosaic-canvas"></canvas>
<script type="module">
import { invoke } from "@tauri-apps/api/core"; // v2
import { listen } from "@tauri-apps/api/event";
import { getCurrentWebview } from "@tauri-apps/api/webview";
const VERBOSE_LOG = false; // 关闭详细日志,避免控制台 I/O 干扰渲染
// 统一为 overlay 控制台日志添加时间戳(HH:mm:ss.SSS)
const __overlay__origConsole = {
log: console.log.bind(console),
info: console.info.bind(console),
warn: console.warn.bind(console),
error: console.error.bind(console),
debug: console.debug.bind(console),
};
function __overlay__ts() {
const d = new Date();
const pad = (n, l = 2) => String(n).padStart(l, '0');
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}`;
}
["log", "info", "warn", "error", "debug"].forEach((lvl) => {
console[lvl] = (...args) => __overlay__origConsole[lvl](`[${__overlay__ts()}]`, ...args);
});
const vlog = (...args) => { if (VERBOSE_LOG) console.log(...args); };
// 使用导入的 API 直接获取当前窗口
const currentWindow = getCurrentWebview();
const USE_PULL = false; // 默认使用推送 + rAF 应用;需要时可切为拉取模式
console.log("[Overlay] Simple overlay loaded successfully");
// 马赛克管理(DOM保留,但改用 Canvas 渲染)
let mosaics = [];
const mosaicContainer = document.getElementById('mosaic-container');
const mosaicCanvas = document.getElementById('mosaic-canvas');
const ctx = mosaicCanvas.getContext('2d');
let devicePixelRatioCached = 1;
function resizeCanvas() {
const dpr = window.devicePixelRatio || 1;
devicePixelRatioCached = dpr;
const w = document.documentElement.clientWidth;
const h = document.documentElement.clientHeight;
mosaicCanvas.width = Math.floor(w * dpr);
mosaicCanvas.height = Math.floor(h * dpr);
mosaicCanvas.style.width = w + 'px';
mosaicCanvas.style.height = h + 'px';
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.imageSmoothingEnabled = __mosaicSmoothing;
}
window.addEventListener('resize', resizeCanvas);
// 全局样式文本,由后端在窗口创建后一次性下发
let globalMosaicStyle = '';
let __mosaicPattern = null;
let __mosaicSmoothing = false; // 默认 crisp-edges
let __mosaicMode = 'stretch'; // 默认使用拉伸,不平铺
let __mosaicFit = 'fill'; // 'fill' | 'contain' | 'cover'
let __bgSizePx = null; // { w, h } when background-size uses px
function extractUrlFromCss(cssText) {
try {
const m = cssText.match(/url\(("|'|)([^\)"']+)\1\)/i);
return m ? m[2] : null;
} catch { return null; }
}
function detectSmoothingFromCss(cssText) {
const lower = (cssText || '').toLowerCase();
if (lower.includes('image-rendering: crisp-edges') || lower.includes('image-rendering: pixelated')) return false;
return true;
}
function loadPatternFromStyle(cssText) {
const text = cssText || '';
const url = extractUrlFromCss(text);
__mosaicSmoothing = detectSmoothingFromCss(text);
ctx.imageSmoothingEnabled = __mosaicSmoothing;
// 强制使用拉伸模式并根据 background-size 调整适配策略
__mosaicMode = 'stretch';
__mosaicFit = 'fill';
__bgSizePx = null;
const sizeMatch = text.match(/background-size\s*:\s*([^;]+);?/i);
if (sizeMatch) {
const val = sizeMatch[1].trim();
if (/^100%\s+100%$/i.test(val)) {
__mosaicMode = 'stretch';
__mosaicFit = 'fill';
} else if (/^contain$/i.test(val)) {
__mosaicMode = 'stretch';
__mosaicFit = 'contain';
} else if (/^cover$/i.test(val)) {
__mosaicMode = 'stretch';
__mosaicFit = 'cover';
} else {
const parts = val.split(/\s+/);
const parsePx = (s) => { const m = s.match(/^(\d+(?:\.\d+)?)px$/i); return m ? parseFloat(m[1]) : null; };
const w = parsePx(parts[0]);
const h = parts[1] ? parsePx(parts[1]) : w;
if (w && h) __bgSizePx = { w, h };
}
}
if (!url) { __mosaicPattern = null; window.__mosaicImage__ = null; return; }
const img = new Image();
img.onload = () => {
// 拉伸模式直接使用 image,不创建平铺 pattern
__mosaicPattern = null;
window.__mosaicImage__ = img;
};
img.onerror = () => { __mosaicPattern = null; window.__mosaicImage__ = null; };
img.src = url;
}
// 动态DPI缩放因子
let scaleFactor = 1.0; // 默认值
// 清除所有马赛克(DOM与Canvas)
function clearMosaics() {
mosaicContainer.innerHTML = '';
mosaics = [];
const w = mosaicCanvas.width / devicePixelRatioCached;
const h = mosaicCanvas.height / devicePixelRatioCached;
ctx.clearRect(0, 0, w, h);
}
// 显示所有马赛克
function showMosaics() {
mosaics.forEach(mosaic => {
mosaic.style.display = 'block';
});
}
// 隐藏所有马赛克
function hideMosaics() {
mosaics.forEach(mosaic => {
mosaic.style.display = 'none';
});
}
// 应用马赛克(Canvas 渲染),支持每块的 angle(度,逆时针为正,绕中心旋转)
function applyMosaicsInternal(payload) {
if (!payload || !payload.mosaics || !Array.isArray(payload.mosaics)) {
return;
}
// 更新scale_factor(仅记录)。实际坐标换算优先使用当前窗口 devicePixelRatio,避免 DPI 不匹配
if (typeof payload.scale_factor === 'number') {
scaleFactor = payload.scale_factor;
vlog(`[Overlay] Updated scale_factor to: ${scaleFactor}`);
}
if (VERBOSE_LOG) console.log('[Overlay] payload seq=', payload && payload.seq);
const rects = payload.mosaics;
const w = mosaicCanvas.width / devicePixelRatioCached;
const h = mosaicCanvas.height / devicePixelRatioCached;
ctx.clearRect(0, 0, w, h);
// 坐标换算采用“物理像素 -> CSS逻辑像素”:优先使用服务端传入的 scale_factor(对应工作显示器 DPI)
const coordScale = (typeof scaleFactor === 'number' && isFinite(scaleFactor) && scaleFactor > 0)
? scaleFactor
: devicePixelRatioCached;
for (let i = 0; i < rects.length; i++) {
const rect = rects[i];
const logicalX = rect.x / coordScale;
const logicalY = rect.y / coordScale;
const logicalWidth = rect.width / coordScale;
const logicalHeight = rect.height / coordScale;
const angleDeg = typeof rect.angle === 'number' ? rect.angle : 0;
const angleRad = angleDeg * Math.PI / 180;
const cx = logicalX + logicalWidth / 2;
const cy = logicalY + logicalHeight / 2;
// 与屏幕(画布)可视区域求交,避免“超过一半就整体消失”的错觉
const ix1 = Math.max(0, logicalX);
const iy1 = Math.max(0, logicalY);
const ix2 = Math.min(w, logicalX + logicalWidth);
const iy2 = Math.min(h, logicalY + logicalHeight);
if (ix2 <= ix1 || iy2 <= iy1) {
continue; // 完全在可视区域外
}
ctx.save();
ctx.beginPath();
ctx.rect(ix1, iy1, ix2 - ix1, iy2 - iy1);
ctx.clip();
if (__mosaicMode === 'stretch' && window.__mosaicImage__) {
const img = window.__mosaicImage__;
const imgW = img.naturalWidth || img.width;
const imgH = img.naturalHeight || img.height;
let dw = logicalWidth, dh = logicalHeight, dx = logicalX, dy = logicalY;
if (__mosaicFit === 'contain' || __mosaicFit === 'cover') {
const sx = logicalWidth / imgW;
const sy = logicalHeight / imgH;
const s = (__mosaicFit === 'contain') ? Math.min(sx, sy) : Math.max(sx, sy);
dw = imgW * s;
dh = imgH * s;
dx = logicalX + (logicalWidth - dw) / 2;
dy = logicalY + (logicalHeight - dh) / 2;
// cover 已由上方统一裁剪到屏幕与目标矩形交集
}
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(angleRad);
ctx.translate(-logicalWidth/2, -logicalHeight/2);
ctx.drawImage(img, dx - logicalX, dy - logicalY, dw, dh);
ctx.restore();
} else {
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(angleRad);
ctx.translate(-logicalWidth/2, -logicalHeight/2);
if (__mosaicPattern) {
ctx.fillStyle = __mosaicPattern;
} else {
ctx.fillStyle = 'rgba(0,0,0,0.85)';
}
ctx.fillRect(0, 0, logicalWidth, logicalHeight);
ctx.restore();
}
// 结束对该马赛克的裁剪上下文
ctx.restore();
}
vlog(`[Overlay] Canvas applied ${rects.length} mosaics (scale_factor=${scaleFactor})`);
}
// 合帧应用:仅保留最新一帧;消费端使用 rAF 渲染,自动与显示器刷新同步
let __latestPayload = null;
let __rafScheduled = false;
let __lastSeq = 0;
function applyMosaics(payload) {
__latestPayload = payload;
if (!__rafScheduled) {
__rafScheduled = true;
requestAnimationFrame(() => {
__rafScheduled = false;
if (__latestPayload) {
const p = __latestPayload; __latestPayload = null;
applyMosaicsInternal(p);
// 真实端到端延迟(依赖本机同一时钟):渲染时刻的 Date.now() - 服务端 UNIX ms
if (p && (typeof p.ts === 'number' || typeof p.emit_ts === 'number')) {
const nowMs = Date.now();
const genDelay = typeof p.ts === 'number' ? (nowMs - p.ts) : null;
const emitDelay = typeof p.emit_ts === 'number' ? (nowMs - p.emit_ts) : null;
const gap = (__lastSeq > 0 && typeof p.seq === 'number') ? (p.seq - __lastSeq - 1) : 0;
if (typeof p.seq === 'number') __lastSeq = p.seq;
if (VERBOSE_LOG) console.log('[Overlay] delay(gen,emit)=',
genDelay != null ? Math.max(0, Math.round(genDelay)) : null,
emitDelay != null ? Math.max(0, Math.round(emitDelay)) : null,
'ms, seq=', p.seq, 'gap=', gap);
}
}
});
}
}
// 监听后端推送(最新帧,不合并)——Pull 模式下禁用
if (!USE_PULL) {
listen('mosaic-update', (event) => {
const payload = event?.payload;
if (payload) {
window.__LATEST_MOSAIC__ = payload;
applyMosaics(payload);
}
});
}
// rAF 拉取最新帧(仅取最新,不排队)
let __pullInflight = false;
let __nextPullAt = 0; // 节流时间戳(ms)
let __pullBaseInterval = 16; // 最小间隔(ms)
let __pullBackoff = 80; // 无更新时退避增量(ms)
async function pullLatestOnce() {
const now = Date.now();
if (__pullInflight || now < __nextPullAt) return;
__pullInflight = true;
try {
const payload = await invoke('get_latest_mosaic');
if (payload && typeof payload === 'object') {
const seq = payload.seq;
if (typeof seq === 'number') {
if (__lastSeq === 0 || seq !== __lastSeq) {
window.__LATEST_MOSAIC__ = payload;
applyMosaics(payload);
__nextPullAt = Date.now() + __pullBaseInterval; // 有更新,立即恢复到基线间隔
} else {
__nextPullAt = Date.now() + __pullBackoff; // 无更新,退避一会儿
}
} else {
window.__LATEST_MOSAIC__ = payload;
applyMosaics(payload);
__nextPullAt = Date.now() + __pullBaseInterval;
}
}
} catch (e) {
// 静默失败,下一帧再试
__nextPullAt = Date.now() + 100; // 短暂退避
} finally {
__pullInflight = false;
}
}
function startPullLoop() {
const tick = () => {
if (USE_PULL) pullLatestOnce();
requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
}
// 取消固定 30fps 定时器,由 rAF 驱动
// 主初始化函数
async function initialize() {
try {
// 初始化时拉取一次样式
async function loadGlobalMosaicStyle() {
try {
const style = await invoke('get_mosaic_style');
if (typeof style === 'string') {
globalMosaicStyle = style;
// 将 CSS 声明块注入为 .mosaic 选择器样式
const styleTagId = 'mosaic-style';
const prev = document.getElementById(styleTagId);
if (prev) prev.remove();
let cssText = globalMosaicStyle.trim();
if (cssText.startsWith('{') && cssText.endsWith('}')) {
cssText = cssText.slice(1, -1);
}
const tag = document.createElement('style');
tag.id = styleTagId;
tag.textContent = `.mosaic { ${cssText} }`;
document.head.appendChild(tag);
console.log('[Overlay] Injected global mosaic CSS into <style>#mosaic-style: ', cssText);
// 依据样式加载平铺图案
loadPatternFromStyle(cssText);
} else {
console.log('[Overlay] No mosaic style returned, keep transparent default');
}
} catch (e) {
console.warn('[Overlay] Failed to load mosaic style via invoke:', e);
}
}
await loadGlobalMosaicStyle();
resizeCanvas();
// 设置 show-mosaic 事件监听
const unlistenShow = await currentWindow.listen('show-mosaic', (event) => {
console.log('[Overlay] Received show-mosaic event');
showMosaics();
});
console.log('[Overlay] show-mosaic listener set');
// 设置 hide-mosaic 事件监听
const unlistenHide = await currentWindow.listen('hide-mosaic', (event) => {
console.log('[Overlay] Received hide-mosaic event');
hideMosaics();
});
console.log('[Overlay] hide-mosaic listener set');
if (USE_PULL) {
console.log('[Overlay] start pull loop via rAF');
startPullLoop();
} else {
console.log('[Overlay] using push + rAF apply');
}
// 设置清理函数(无需轮询标志)
window.addEventListener('unload', () => {});
console.log('[Overlay] Event listeners setup completed');
} catch (error) {
console.error('[Overlay] Failed to setup event listeners:', error);
}
}
// 初始化:若 DOM 已就绪则立刻执行,否则等待 DOMContentLoaded
const boot = () => {
initialize().catch(error => console.error('[Overlay] initialize failed:', error));
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', boot, { once: true });
} else {
boot();
}
// 阻止所有鼠标和键盘事件
function preventAllEvents(event) {
event.preventDefault();
event.stopPropagation();
return false;
}
// 添加全局事件监听器来阻止所有交互事件
const eventsToPrevent = [
'mousedown', 'mouseup', 'click', 'dblclick', 'contextmenu',
'mousemove', 'mouseenter', 'mouseleave', 'mouseover', 'mouseout',
'keydown', 'keyup', 'keypress',
'touchstart', 'touchend', 'touchmove',
'wheel', 'scroll'
];
eventsToPrevent.forEach(eventType => {
document.addEventListener(eventType, preventAllEvents, true);
window.addEventListener(eventType, preventAllEvents, true);
});
console.log('[Overlay] Event blocking enabled for all interaction events');
// 错误处理
window.addEventListener('error', (event) => {
console.error('[Overlay] caught global error:', event.error);
});
window.addEventListener('unhandledrejection', (event) => {
console.error('[Overlay] caught unhandled rejection:', event.reason);
});
</script>
</body>
</html>