-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqr-auto-decoder.user.js
More file actions
2210 lines (1908 loc) · 85.3 KB
/
Copy pathqr-auto-decoder.user.js
File metadata and controls
2210 lines (1908 loc) · 85.3 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
// ==UserScript==
// @name 二维码自动解析
// @description 鼠标悬停时自动在本地解析二维码
// @namespace http://tampermonkey.net/
// @require https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js
// @require https://unpkg.com/@zxing/library@latest/umd/index.min.js
// @match *://*/*
// @match file:///*
// @grant GM_setClipboard
// @grant GM_openInTab
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @connect cdnimg.hxcy.top
// @connect pic.hxcy.top
// @connect image.acg.lol
// @connect zxing.org
// @connect api.2dcode.biz
// @connect *
// @run-at document-start
// @version 3.4.4
// @author Gemini
// @license GPLv3
// @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAAABmJLR0QA/wD/AP+gvaeTAAABZElEQVR4nO3cQUrEMBiAURXv5QFceVJXHsCT6VYGpA5J+6X2vbVI4OPvZNJpHx4AAICredz6g5e3j68jFvKbz/fXzTX+dLb1Pu21EP5GgJgAMQFiAsQEiAkQex79B/fue28dvW9fbb0mICZATIDY8GfAra1r5Og1eLZ6vSYgJkBMgJgAMQFiAsQEiE3/HrDaPn9LvV4TEBMgJkBs+DOg/h3OvVZbrwmICRATICZATICYADEBYrufg4zecx3dt89+vmD22ZEJiAkQEyAmQEyAmAAxAWLDe9p6nz/b6Ho9J3wyAsQEiG3eEx69Rq92jV+NCYgJEBMgdvr3BdXPeI0yATEBYgLELveuiL3PrpwFncz0J2Rmq3dhezMBscu/K6JmAmICxASILb8Lmm21syUTEFt+As72q4p7mYDY5d8VUTMBMQFiAsSWvye85ehnwNwP+GcEiAkQEyAmQEyAmAAAAAAAcJBvjUVu7tMNP9IAAAAASUVORK5CYII=
// ==/UserScript==
(function() {
'use strict';
// === 配置 ===
const AUTO_PENDING_RETRY_MS = 100;
const AUTO_RESCAN_DISTANCE_PX = 120;
const AUTO_IMAGE_MIN_EDGE_PX = 48;
const AUTO_IMAGE_MAX_RATIO = (4 / 3) + 0.03;
const AUTO_CONTENT_SCORE_MIN = 2;
const AUTO_CONTENT_SCORE_HIGH = 5;
const AUTO_QUICK_MAX_SIZE = 720;
const AUTO_DETAIL_MAX_SIZE = 1152;
const AUTO_LOCAL_QUICK_SIZE_PX = 320;
const AUTO_LOCAL_DETAIL_SIZE_PX = 520;
const AUTO_CORS_MAX_SOURCE_DIMENSION = 6000;
const AUTO_CANVAS_MAX_SIZE = 2000;
const CANVAS_SQUARE_TOLERANCE = 2;
const CROP_TARGET_SIZE = 500; // 框选解析的最大尺寸 (超过此尺寸才缩小)
const INPUT_SUPPRESSION_TIMEOUT_MS = 1500;
// 与现有右键+左键次数一致:请求越深入,结果等级越高。
const SCAN_PRIORITY = Object.freeze({
AUTO: 0,
FORCE_LOCAL: 10,
REMOTE: 20,
CROP_SCALED: 30,
CROP_ORIGINAL: 40
});
// === ZXing 初始化 ===
let zxingReaderStrict = null; // 仅用于悬停 (只识二维码)
let zxingReaderAll = null; // 用于强制解析 (识别所有)
function getZXingReader(isForce) {
if (!window.ZXing) return null;
if (isForce) {
// --- 模式 B: 强制解析 (全格式) ---
if (!zxingReaderAll) {
const hints = new Map();
// 不设置 POSSIBLE_FORMATS 默认识别所有格式 (EAN, Code128, QR等)
hints.set(ZXing.DecodeHintType.TRY_HARDER, true);
zxingReaderAll = new ZXing.BrowserMultiFormatReader(hints);
}
return zxingReaderAll;
} else {
// --- 模式 A: 悬停自动解析 (仅二维码) ---
if (!zxingReaderStrict) {
const hints = new Map();
// 显式限制只识别 QR Code 和 Data Matrix
const formats = [ZXing.BarcodeFormat.QR_CODE, ZXing.BarcodeFormat.DATA_MATRIX];
hints.set(ZXing.DecodeHintType.POSSIBLE_FORMATS, formats);
// 悬停时也可以开启深度扫描 或者为了性能设为 false (这里建议开启以保证识别率)
hints.set(ZXing.DecodeHintType.TRY_HARDER, true);
zxingReaderStrict = new ZXing.BrowserMultiFormatReader(hints);
}
return zxingReaderStrict;
}
}
// === 全局变量 ===
let autoHoverState = null;
let autoScanSequence = 0;
let tooltip = null;
let currentTarget = null;
let displayedResultState = null;
let tooltipRenderRevision = 0;
// 坐标相关
let lastMouseScreenX = 0;
let lastMouseScreenY = 0;
let lastMouseClientX = 0;
let lastMouseClientY = 0;
let topWinOffset = null;
// 组合键状态控制
let isRightClickHolding = false;
let leftClickCount = 0;
let interactionTarget = null;
let pendingContextMenuSuppression = null;
let pendingClickSuppression = null;
let longPressTimer = null;
// 框选相关
let isCropping = false;
let isNoScaleCrop = false;
let cropOverlay = null;
let cropBox = null;
let cropStart = { x: 0, y: 0 };
let cropTarget = null;
let cropDragCleanup = null;
// 会话缓存
const qrCache = new Map();
const canvasCache = new WeakMap();
const autoAttemptCache = new Map();
function getImageSource(img) {
if (!img || img.tagName !== 'IMG') return '';
return img.currentSrc || img.src || '';
}
function normalizePriority(priority) {
return Number.isFinite(priority) ? priority : SCAN_PRIORITY.AUTO;
}
function getResultIdentity(text) {
const value = String(text ?? '');
return isUrl(value) ? value.trim() : value;
}
function getCachedEntry(type, cacheKey, targetEl) {
if (type === 'IMG' && cacheKey) return qrCache.get(cacheKey);
if (type === 'CANVAS' && targetEl) return canvasCache.get(targetEl);
return null;
}
function setCachedEntry(type, cacheKey, targetEl, entry) {
if (type === 'IMG' && cacheKey) qrCache.set(cacheKey, entry);
else if (type === 'CANVAS' && targetEl) canvasCache.set(targetEl, entry);
}
function commitCacheEntry(type, cacheKey, targetEl, candidate) {
const existing = getCachedEntry(type, cacheKey, targetEl);
if (existing && existing.status === 'success') {
if (!candidate || candidate.status !== 'success') return existing;
const existingPriority = normalizePriority(existing.priority);
const candidatePriority = normalizePriority(candidate.priority);
if (getResultIdentity(candidate.text) === getResultIdentity(existing.text)) {
if (candidatePriority > existingPriority) {
const upgraded = { ...existing, priority: candidatePriority };
setCachedEntry(type, cacheKey, targetEl, upgraded);
return upgraded;
}
return existing;
}
if (candidatePriority <= existingPriority) return existing;
}
const committed = candidate && candidate.status === 'success'
? { ...candidate, priority: normalizePriority(candidate.priority) }
: candidate;
setCachedEntry(type, cacheKey, targetEl, committed);
return committed;
}
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
function getRepeatedImageCount(source) {
if (!source) return 0;
let count = 0;
for (const image of document.images) {
if (getImageSource(image) === source && ++count >= 3) return count;
}
return count;
}
function hasFixedOrStickyAncestor(element) {
let node = element;
let depth = 0;
while (node && node !== document.documentElement && depth < 8) {
const position = getComputedStyle(node).position;
if (position === 'fixed' || position === 'sticky') return true;
node = node.parentElement;
depth++;
}
return false;
}
function evaluateAutoImageCandidate(img) {
if (!img.complete || !img.naturalWidth || !img.naturalHeight) {
return { eligible: false, reason: 'not_loaded' };
}
const rect = img.getBoundingClientRect();
const style = getComputedStyle(img);
const visibleWidth = Math.min(rect.right, window.innerWidth) - Math.max(rect.left, 0);
const visibleHeight = Math.min(rect.bottom, window.innerHeight) - Math.max(rect.top, 0);
if (style.display === 'none' || style.visibility !== 'visible' || Number(style.opacity) <= 0.01 ||
rect.width < AUTO_IMAGE_MIN_EDGE_PX || rect.height < AUTO_IMAGE_MIN_EDGE_PX ||
visibleWidth <= 0 || visibleHeight <= 0) {
return { eligible: false, reason: 'not_visible' };
}
const ratio = Math.max(rect.width, rect.height) / Math.min(rect.width, rect.height);
if (ratio > AUTO_IMAGE_MAX_RATIO) {
return { eligible: false, reason: 'invalid_ratio' };
}
const minEdge = Math.min(rect.width, rect.height);
const area = rect.width * rect.height;
const source = getImageSource(img);
if (!source) return { eligible: false, reason: 'missing_source' };
const sourceName = source.startsWith('data:') ? '' : source.split(/[?#]/)[0].slice(-160);
const descriptor = `${img.id || ''} ${img.className || ''} ${img.alt || ''} ${img.title || ''} ${sourceName}`;
let score = minEdge >= 64 ? 2 : -1;
if (area >= 20000) score++;
if (area >= 90000) score++;
if (img.closest('main, article, figure, [role="main"]')) score += 3;
if (/(?:qr(?:code)?|二维码|收款码|付款码|weixin|wechat|alipay|payment|scan[-_ ]?code)/i.test(descriptor)) score += 3;
if (img.closest('nav, header, footer, [role="navigation"], [role="menu"], [role="menubar"], [role="toolbar"], button, [role="button"]')) {
score -= 5;
}
if (img.closest('aside, [role="complementary"]')) score -= 2;
if (hasFixedOrStickyAncestor(img)) score -= 3;
if (/(?:^|[\s_./-])(?:logo|icon|avatar|badge|emoji|sprite|favicon|toolbar|menu)(?:$|[\s_.-])/i.test(descriptor)) {
score -= 5;
}
if (getRepeatedImageCount(source) >= 3) score -= 3;
return {
eligible: score >= AUTO_CONTENT_SCORE_MIN,
highConfidence: score >= AUTO_CONTENT_SCORE_HIGH,
score,
rect,
ratio,
source,
reason: score >= AUTO_CONTENT_SCORE_MIN ? 'accepted' : 'low_content_score'
};
}
function getObjectPositionTokens(value) {
const parts = String(value || '50% 50%').trim().split(/\s+/);
if (parts.length === 1) {
return /^(top|bottom)$/i.test(parts[0]) ? ['50%', parts[0]] : [parts[0], '50%'];
}
if (parts.length === 2 && /^(top|bottom)$/i.test(parts[0]) && /^(left|right|center)$/i.test(parts[1])) {
return [parts[1], parts[0]];
}
return parts.length === 2 ? parts : ['50%', '50%'];
}
function resolveObjectPosition(token, freeSpace, axis) {
const value = String(token || '50%').toLowerCase();
if (value === 'center') return freeSpace * 0.5;
if (value === (axis === 'x' ? 'left' : 'top')) return 0;
if (value === (axis === 'x' ? 'right' : 'bottom')) return freeSpace;
if (value.endsWith('%')) return freeSpace * (parseFloat(value) || 0) / 100;
const pixels = parseFloat(value);
return Number.isFinite(pixels) ? pixels : freeSpace * 0.5;
}
function getDisplayedImageMapping(img) {
const naturalWidth = img.naturalWidth;
const naturalHeight = img.naturalHeight;
if (!naturalWidth || !naturalHeight) return null;
const rect = img.getBoundingClientRect();
const style = getComputedStyle(img);
const number = value => parseFloat(value) || 0;
const insetLeft = number(style.borderLeftWidth) + number(style.paddingLeft);
const insetRight = number(style.borderRightWidth) + number(style.paddingRight);
const insetTop = number(style.borderTopWidth) + number(style.paddingTop);
const insetBottom = number(style.borderBottomWidth) + number(style.paddingBottom);
const contentWidth = rect.width - insetLeft - insetRight;
const contentHeight = rect.height - insetTop - insetBottom;
if (contentWidth <= 0 || contentHeight <= 0) return null;
const contentLeft = rect.left + insetLeft;
const contentTop = rect.top + insetTop;
const objectFit = style.objectFit || 'fill';
let scaleX = contentWidth / naturalWidth;
let scaleY = contentHeight / naturalHeight;
if (objectFit !== 'fill') {
const containScale = Math.min(scaleX, scaleY);
let uniformScale;
if (objectFit === 'cover') uniformScale = Math.max(scaleX, scaleY);
else if (objectFit === 'none') uniformScale = 1;
else if (objectFit === 'scale-down') uniformScale = Math.min(1, containScale);
else uniformScale = containScale;
scaleX = uniformScale;
scaleY = uniformScale;
}
const objectWidth = naturalWidth * scaleX;
const objectHeight = naturalHeight * scaleY;
const [positionX, positionY] = getObjectPositionTokens(style.objectPosition);
const objectLeft = contentLeft + resolveObjectPosition(positionX, contentWidth - objectWidth, 'x');
const objectTop = contentTop + resolveObjectPosition(positionY, contentHeight - objectHeight, 'y');
const visibleLeft = Math.max(contentLeft, objectLeft);
const visibleTop = Math.max(contentTop, objectTop);
const visibleRight = Math.min(contentLeft + contentWidth, objectLeft + objectWidth);
const visibleBottom = Math.min(contentTop + contentHeight, objectTop + objectHeight);
if (visibleRight <= visibleLeft || visibleBottom <= visibleTop) return null;
const sourceX = clamp((visibleLeft - objectLeft) / scaleX, 0, naturalWidth);
const sourceY = clamp((visibleTop - objectTop) / scaleY, 0, naturalHeight);
const sourceRight = clamp((visibleRight - objectLeft) / scaleX, 0, naturalWidth);
const sourceBottom = clamp((visibleBottom - objectTop) / scaleY, 0, naturalHeight);
return {
naturalWidth,
naturalHeight,
objectFit,
objectPosition: style.objectPosition || '50% 50%',
scaleX,
scaleY,
objectLeft,
objectTop,
visibleDisplayRect: {
left: visibleLeft,
top: visibleTop,
right: visibleRight,
bottom: visibleBottom,
width: visibleRight - visibleLeft,
height: visibleBottom - visibleTop
},
visibleSourceRect: {
x: sourceX,
y: sourceY,
width: sourceRight - sourceX,
height: sourceBottom - sourceY
}
};
}
function mapPointerToSource(mapping, pointer) {
const visible = mapping.visibleDisplayRect;
const clientX = clamp(pointer.clientX, visible.left, visible.right);
const clientY = clamp(pointer.clientY, visible.top, visible.bottom);
return {
x: clamp((clientX - mapping.objectLeft) / mapping.scaleX, 0, mapping.naturalWidth),
y: clamp((clientY - mapping.objectTop) / mapping.scaleY, 0, mapping.naturalHeight)
};
}
function getCenteredSourceRect(mapping, pointer, displaySize) {
const bounds = mapping.visibleSourceRect;
const center = mapPointerToSource(mapping, pointer);
const width = Math.min(bounds.width, displaySize / mapping.scaleX);
const height = Math.min(bounds.height, displaySize / mapping.scaleY);
const maxX = bounds.x + bounds.width - width;
const maxY = bounds.y + bounds.height - height;
return {
x: clamp(center.x - width / 2, bounds.x, maxX),
y: clamp(center.y - height / 2, bounds.y, maxY),
width,
height
};
}
function buildAutoAttemptKey(img, mapping, pointer) {
const source = getImageSource(img);
const visible = mapping.visibleSourceRect;
const sourcePoint = mapPointerToSource(mapping, pointer);
const relativeX = (sourcePoint.x - visible.x) / Math.max(1, visible.width);
const relativeY = (sourcePoint.y - visible.y) / Math.max(1, visible.height);
const round = value => Math.round(value / 4) * 4;
return [
'auto-v3',
source,
`${mapping.naturalWidth}x${mapping.naturalHeight}`,
`${round(mapping.visibleDisplayRect.width)}x${round(mapping.visibleDisplayRect.height)}`,
`${round(visible.x)},${round(visible.y)},${round(visible.width)},${round(visible.height)}`,
`${mapping.objectFit}:${mapping.objectPosition}`,
`${Math.round(relativeX * 12)},${Math.round(relativeY * 12)}`
].join('|');
}
const isTop = window.self === window.top;
// === 样式注入 ===
GM_addStyle(`
#qr-custom-tooltip {
position: fixed;
z-index: 2147483647;
background: rgba(0, 0, 0, 0.9);
color: #fff;
padding: 8px 12px;
font-size: 12px;
max-width: 320px;
word-break: break-all;
pointer-events: none;
display: none;
border: 1px solid #555;
border-radius: 0px !important;
box-shadow: none !important;
line-height: 1.5;
text-align: left;
}
.qr-detected-style {
cursor: pointer !important;
outline: none !important;
}
/* 框选遮罩 */
#qr-crop-overlay {
position: fixed;
top: 0; left: 0; width: 100vw; height: 100vh;
background: rgba(0, 0, 0, 0.3);
z-index: 2147483646;
cursor: crosshair;
display: none;
}
#qr-crop-box {
position: absolute;
border: 2px solid #4CAF50;
background: rgba(76, 175, 80, 0.2);
pointer-events: none;
display: none;
}
`);
// ==========================================
// 通信模块 (跨域支持)
// ==========================================
function sendToTop(type, payload = {}) {
if (isTop) {
handleMessage({ data: { type, payload } });
} else {
window.top.postMessage({ type: 'QR_SCRIPT_MSG', action: type, payload }, '*');
}
}
if (isTop) {
window.addEventListener('message', (event) => {
if (event.data && event.data.type === 'QR_SCRIPT_MSG') {
handleMessage({ data: { type: event.data.action, payload: event.data.payload } });
}
});
}
function handleMessage(e) {
const { type, payload } = e.data;
switch (type) {
case 'SHOW_TOOLTIP':
renderTooltip(
payload.text,
payload.coords,
payload.isLink,
payload.method,
payload.kind,
payload.priority
);
break;
case 'HIDE_TOOLTIP':
hideTooltipDOM();
break;
case 'SHOW_FEEDBACK':
showFeedbackDOM();
break;
}
}
// ==========================================
// UI 渲染模块 (仅顶层窗口)
// ==========================================
function getTooltip() {
if (!tooltip) {
tooltip = document.getElementById('qr-custom-tooltip');
if (!tooltip) {
tooltip = document.createElement('div');
tooltip.id = 'qr-custom-tooltip';
document.body.appendChild(tooltip);
}
}
return tooltip;
}
function shouldRenderTooltip(text, kind, priority) {
if (!displayedResultState) return true;
if (kind !== 'result') return false;
const displayedIdentity = displayedResultState.identity ?? getResultIdentity(displayedResultState.text);
if (getResultIdentity(text) === displayedIdentity) {
displayedResultState.priority = Math.max(displayedResultState.priority, priority);
return false;
}
return priority > displayedResultState.priority;
}
function renderTooltip(text, coords, isLink, method, kind, priority) {
const resolvedKind = kind || (text.startsWith('⌛') ? 'status' : text.startsWith('❌') ? 'error' : 'result');
const resolvedPriority = normalizePriority(priority);
if (!shouldRenderTooltip(text, resolvedKind, resolvedPriority)) return;
const tip = getTooltip();
const contentColor = isLink ? '#4dabf7' : '#ffffff';
const actionColor = '#4CAF50';
const bracketColor = '#F6B64E';
const parenColor = '#B28BF7';
const isLoading = text.startsWith('⌛');
const isError = text.startsWith('❌');
// --- 修改开始:标题构建逻辑 ---
let titleHtml = '';
// 检查是否以 "远程解析" 开头
if (method && method.startsWith('远程解析')) {
// 提取括号内的源 (如果有)
let source = "";
const match = method.match(/\((.+?)\)/);
if (match) source = match[1];
titleHtml = `<div style="margin-bottom:4px;">
<span style="color:${bracketColor}; font-weight:bold;">[远程解析]</span>
${source ? `<span style="color:${parenColor}; font-weight:bold;"> (${escapeHtml(source)})</span>` : ''}
</div>`;
} else {
// 本地解析
titleHtml = `<div style="margin-bottom:4px;">
<span style="color:${bracketColor}; font-weight:bold;">[本地解析]</span>
<span style="color:${parenColor}; font-weight:bold;"> (${escapeHtml(method || '未知')})</span>
</div>`;
}
let htmlContent = '';
if (isLoading) {
htmlContent = `<div style="color:#FFD700; font-weight:bold;">${escapeHtml(text)}</div>`;
} else if (isError) {
htmlContent = `<div style="color:#FF5252; font-weight:bold;">${escapeHtml(text)}</div>`;
} else {
htmlContent = `
${titleHtml}
<div style="color:${contentColor}; margin-bottom:6px;">${escapeHtml(text)}</div>
<div style="color:${actionColor}; font-weight:bold; border-top:1px solid #444; padding-top:4px;">
${isLink ? '🔗 点击打开 | 📋 按住复制' : '📋 点击复制文本'}
</div>
`;
}
tip.innerHTML = htmlContent;
tip.style.display = 'block';
tooltipRenderRevision++;
displayedResultState = resolvedKind === 'result'
? { text, identity: getResultIdentity(text), priority: resolvedPriority }
: null;
// --- 坐标计算 ---
let offsetY, offsetX;
if (topWinOffset) {
offsetX = topWinOffset.x;
offsetY = topWinOffset.y;
} else {
const winScreenX = window.screenX !== undefined ? window.screenX : window.screenLeft;
const winScreenY = window.screenY !== undefined ? window.screenY : window.screenTop;
offsetX = winScreenX + (window.outerWidth - window.innerWidth);
offsetY = winScreenY + (window.outerHeight - window.innerHeight);
}
let left = coords.absLeft - offsetX;
let top = coords.absBottom - offsetY + 10;
const tipRect = tip.getBoundingClientRect();
const winHeight = window.innerHeight;
const winWidth = window.innerWidth;
if (top + tipRect.height > winHeight) {
top = (coords.absTop - offsetY) - tipRect.height - 10;
}
if (left + tipRect.width > winWidth) left = winWidth - tipRect.width - 10;
if (left < 0) left = 10;
tip.style.top = top + 'px';
tip.style.left = left + 'px';
}
function hideTooltipDOM() {
if (tooltip) tooltip.style.display = 'none';
displayedResultState = null;
tooltipRenderRevision++;
}
function showFeedbackDOM() {
const tip = getTooltip();
if (tip.style.display === 'none') return;
const originalHTML = tip.innerHTML;
const revision = ++tooltipRenderRevision;
tip.innerHTML = `<div style="font-size:14px; text-align:center; color:#4dabf7; font-weight:bold;">✅ 已复制到剪贴板</div>`;
setTimeout(() => {
if (tip.style.display !== 'none' && tooltipRenderRevision === revision) {
tip.innerHTML = originalHTML;
}
}, 1000);
}
// ==========================================
// 逻辑处理模块 (所有 Frame)
// ==========================================
function requestShowTooltip(text, element, method = "JSQR", options = {}) {
if (currentTarget !== element) currentTarget = element;
const isLink = isUrl(text);
const kind = options.kind || (text.startsWith('⌛') ? 'status' : text.startsWith('❌') ? 'error' : 'result');
const priority = normalizePriority(options.priority);
const rect = element.getBoundingClientRect();
const frameOffsetX = (lastMouseScreenX && lastMouseClientX) ? (lastMouseScreenX - lastMouseClientX) : 0;
const frameOffsetY = (lastMouseScreenY && lastMouseClientY) ? (lastMouseScreenY - lastMouseClientY) : 0;
const coords = {
absLeft: rect.left + frameOffsetX,
absTop: rect.top + frameOffsetY,
absBottom: rect.bottom + frameOffsetY
};
sendToTop('SHOW_TOOLTIP', { text, coords, isLink, method, kind, priority });
}
function requestHideTooltip() {
currentTarget = null;
sendToTop('HIDE_TOOLTIP');
}
function requestFeedback() {
sendToTop('SHOW_FEEDBACK');
}
// ==========================================
// 框选逻辑
// ==========================================
function startCropMode(target, noScale = false) {
if (isCropping) return;
stopAutoHover(true);
isCropping = true;
isNoScaleCrop = noScale;
cropTarget = target;
if (!cropOverlay) {
cropOverlay = document.createElement('div');
cropOverlay.id = 'qr-crop-overlay';
cropBox = document.createElement('div');
cropBox.id = 'qr-crop-box';
cropOverlay.appendChild(cropBox);
document.body.appendChild(cropOverlay);
// 辅助函数
const clamp = (val, min, max) => Math.min(Math.max(val, min), max);
// 右键取消
cropOverlay.addEventListener('contextmenu', (e) => {
e.preventDefault();
e.stopPropagation();
const target = cropTarget;
const priority = isNoScaleCrop ? SCAN_PRIORITY.CROP_ORIGINAL : SCAN_PRIORITY.CROP_SCALED;
endCropMode();
if (target) requestShowTooltip("❌ 已取消框选", target, "JSQR", { priority });
return false;
});
// 鼠标按下开始框选
cropOverlay.addEventListener('mousedown', (e) => {
if (e.button !== 0 || !cropTarget) return;
e.preventDefault();
// 关键修复 2: 在点击瞬间动态获取当前目标的 Rect
// 确保获取的是当前 cropTarget 的位置 而不是第一次初始化时的位置
const target = cropTarget;
const imgRect = target.getBoundingClientRect();
// 限制起点坐标
const startX = clamp(e.clientX, imgRect.left, imgRect.right);
const startY = clamp(e.clientY, imgRect.top, imgRect.bottom);
cropStart = { x: startX, y: startY };
cropBox.style.left = startX + 'px';
cropBox.style.top = startY + 'px';
cropBox.style.width = '0px';
cropBox.style.height = '0px';
cropBox.style.display = 'block';
const onMove = (ev) => {
// 鼠标在窗口外释放时可能收不到 mouseup;重新进入后立即取消框选。
if ((ev.buttons & 1) === 0) {
endCropMode();
return;
}
// 限制终点坐标
const curX = clamp(ev.clientX, imgRect.left, imgRect.right);
const curY = clamp(ev.clientY, imgRect.top, imgRect.bottom);
const width = Math.abs(curX - cropStart.x);
const height = Math.abs(curY - cropStart.y);
const left = Math.min(curX, cropStart.x);
const top = Math.min(curY, cropStart.y);
cropBox.style.width = width + 'px';
cropBox.style.height = height + 'px';
cropBox.style.left = left + 'px';
cropBox.style.top = top + 'px';
};
const onUp = (ev) => {
if (ev.button !== 0) return;
if (!isCropping) {
if (cropDragCleanup) cropDragCleanup();
return;
}
const rect = cropBox.getBoundingClientRect();
endCropMode();
if (rect.width < 5 || rect.height < 5) return;
// 关键修复 3: 将当前的 cropTarget 传递给处理函数
processCropScan(target, rect);
};
window.addEventListener('mousemove', onMove);
window.addEventListener('mouseup', onUp);
cropDragCleanup = () => {
window.removeEventListener('mousemove', onMove);
window.removeEventListener('mouseup', onUp);
cropDragCleanup = null;
};
});
}
cropOverlay.style.display = 'block';
const tipText = noScale ? "⌛ 原图框选" : "⌛ 缩放框选";
const priority = noScale ? SCAN_PRIORITY.CROP_ORIGINAL : SCAN_PRIORITY.CROP_SCALED;
requestShowTooltip(tipText, target, "JSQR", { priority });
}
function endCropMode() {
isCropping = false;
if (cropDragCleanup) cropDragCleanup();
if (cropOverlay) cropOverlay.style.display = 'none';
if (cropBox) cropBox.style.display = 'none';
cropTarget = null;
}
function processCropScan(target, selectionRect) {
const targetRect = target.getBoundingClientRect();
const selX = selectionRect.left;
const selY = selectionRect.top;
const selW = selectionRect.width;
const selH = selectionRect.height;
const imgX = targetRect.left;
const imgY = targetRect.top;
const relX = selX - imgX;
const relY = selY - imgY;
const cropRect = {
x: relX,
y: relY,
w: selW,
h: selH,
noScale: isNoScaleCrop
};
scanElement(target, true, cropRect);
}
// === 统一入口 ===
function scanElement(target, force = false, cropRect = null) {
const priority = cropRect
? (cropRect.noScale ? SCAN_PRIORITY.CROP_ORIGINAL : SCAN_PRIORITY.CROP_SCALED)
: (force ? SCAN_PRIORITY.FORCE_LOCAL : SCAN_PRIORITY.AUTO);
// 获取当前缓存状态 (用于强制解析时的判断)
let prevCache = null;
if (target.tagName === 'IMG' && getImageSource(target)) prevCache = getCachedEntry('IMG', getImageSource(target), target);
else if (target.tagName === 'CANVAS') prevCache = getCachedEntry('CANVAS', target, target);
if (target.tagName === 'IMG') {
scanImage(target, force, cropRect, prevCache, priority);
} else if (target.tagName === 'CANVAS') {
scanCanvas(target, force, cropRect, prevCache, priority);
}
}
// === 远程解析 ===
// === 远程解析辅助函数 ===
// 1. 请求 zxing.org
function fetchZxing(src) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: "GET",
url: "https://zxing.org/w/decode?u=" + encodeURIComponent(src),
timeout: 10000, // 10秒超时
onload: function(response) {
if (response.status === 200) {
const parser = new DOMParser();
const doc = parser.parseFromString(response.responseText, "text/html");
const tds = doc.querySelectorAll('td');
let resultText = null;
for (let i = 0; i < tds.length; i++) {
if (tds[i].textContent.trim() === "Parsed Result") {
const nextTd = tds[i].nextElementSibling;
if (nextTd) {
const pre = nextTd.querySelector('pre');
if (pre) { resultText = pre.textContent; break; }
}
}
}
if (resultText) resolve({ text: resultText, source: "zxing.org" });
else reject("zxing parse error");
} else {
reject("zxing status " + response.status);
}
},
onerror: (e) => reject("zxing network error"),
ontimeout: () => reject("zxing timeout")
});
});
}
// 2. 请求 api.2dcode.biz
function fetch2dCode(src) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: "GET",
url: "https://api.2dcode.biz/v1/read-qr-code?file_url=" + encodeURIComponent(src),
timeout: 10000,
onload: function(response) {
if (response.status === 200) {
try {
const json = JSON.parse(response.responseText);
// 检查 code: 0 和 data.contents 数组
if (json.code === 0 && json.data && json.data.contents && json.data.contents.length > 0) {
resolve({ text: json.data.contents[0], source: "api.2dcode.biz" });
} else {
reject("2dcode api error: " + (json.message || "no data"));
}
} catch (e) {
reject("2dcode json parse error");
}
} else {
reject("2dcode status " + response.status);
}
},
onerror: (e) => reject("2dcode network error"),
ontimeout: () => reject("2dcode timeout")
});
});
}
// 3. Promise.any Polyfill (确保兼容性)
// 返回最先成功的那个 如果全部失败则报错
function promiseAny(promises) {
if (Promise.any) return Promise.any(promises);
return new Promise((resolve, reject) => {
let errors = [];
let rejectedCount = 0;
promises.forEach((p, index) => {
Promise.resolve(p).then(resolve).catch(error => {
errors[index] = error;
rejectedCount++;
if (rejectedCount === promises.length) {
reject(new Error("All promises rejected"));
}
});
});
});
}
// === 远程解析主入口 ===
function scanExternal(target) {
const priority = SCAN_PRIORITY.REMOTE;
const src = getImageSource(target);
if (target.tagName !== 'IMG' || !src || !/^https?:/i.test(src)) {
requestShowTooltip("❌ 远程解析仅支持 http/https 图片链接", target, "JSQR", { priority });
return;
}
requestShowTooltip("⌛ 正在连接远程服务器解析...", target, "JSQR", { priority });
// 并行发起请求
const p1 = fetchZxing(src);
const p2 = fetch2dCode(src);
// 竞速:谁先成功用谁
promiseAny([p1, p2])
.then(result => {
const methodStr = `远程解析 (${result.source})`;
const committed = commitCacheEntry('IMG', src, target, {
status: 'success',
text: result.text,
method: methodStr,
priority
});
if (committed && committed.status === 'success') {
applyQrSuccess(target, committed.text, committed.method, committed.priority);
}
})
.catch(err => {
const committed = commitCacheEntry('IMG', src, target, {
status: 'failed',
reason: 'remote_all_failed'
});
if (committed && committed.status === 'success') {
applyQrSuccess(target, committed.text, committed.method, committed.priority);
} else {
requestShowTooltip("❌ 远程解析失败", target, "JSQR", { priority });
}
});
}
// ==========================================
// 图像获取与预处理
// ==========================================
function rememberAutoAttempt(key, entry) {
autoAttemptCache.set(key, entry);
if (autoAttemptCache.size > 500) {
autoAttemptCache.delete(autoAttemptCache.keys().next().value);
}
}
function forgetAutoAttempt(key, scanId) {
const current = autoAttemptCache.get(key);
if (current && current.scanId === scanId) autoAttemptCache.delete(key);
}
function loadImageWithCors(src) {
return new Promise((resolve, reject) => {
const image = new Image();
image.crossOrigin = 'Anonymous';
image.decoding = 'async';
image.onload = () => resolve({ image, release: null });
image.onerror = () => reject(new Error('cors_image_load_failed'));
image.src = src;
});
}
function loadImageWithRequest(src) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: src,
responseType: 'arraybuffer',
headers: {
Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
},
onload: response => {
if (response.status < 200 || response.status >= 300 || !response.response) {
reject(new Error(`image_status_${response.status}`));
return;
}
const contentTypeMatch = String(response.responseHeaders || '')
.match(/^content-type:\s*([^;\r\n]+)/im);
const blob = new Blob([response.response], {
type: contentTypeMatch ? contentTypeMatch[1].trim() : 'application/octet-stream'
});
const blobUrl = URL.createObjectURL(blob);
const image = new Image();
image.decoding = 'async';
image.onload = () => resolve({
image,
release: () => URL.revokeObjectURL(blobUrl)
});
image.onerror = () => {
URL.revokeObjectURL(blobUrl);
reject(new Error('blob_image_load_failed'));
};
image.src = blobUrl;
},
onerror: () => reject(new Error('image_request_failed')),
ontimeout: () => reject(new Error('image_request_timeout')),
timeout: 12000