-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathaddMenuPlus.uc.js
More file actions
1834 lines (1701 loc) · 87.6 KB
/
addMenuPlus.uc.js
File metadata and controls
1834 lines (1701 loc) · 87.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
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 addMenuPlus.uc.js
// @description 通过配置文件增加修改菜单,修改版
// @namespace http://d.hatena.ne.jp/Griever/
// @author Ryan, ywzhaiqi, Griever
// @include main
// @license MIT
// @compatibility Firefox 136
// @charset UTF-8
// @version 0.2.1 r4
// @shutdown window.addMenu.destroy();
// @homepageURL https://github.com/benzBrake/FirefoxCustomize/tree/master/userChromeJS/addMenuPlus
// @reviewURL https://bbs.kafan.cn/thread-2246475-1-1.html
// @note 0.2.1 r3 新增 command 菜单跟随原菜单的 disabled/collapsed/hidden 属性,标签页右键菜单支持,无 command 二级菜单在第一个子菜单为 disabled 点击该二级菜单不再执行该子菜单的 command
// @note 0.2.1 fix openUILinkIn was removed, Bug 1820534 - Move front-end to modern flexbox, 修复 about:neterror 页面获取的地址不对, Bug 1815439 - Remove useless loadURI wrapper from browser.js, 扩展 %FAVICON% %FAVICON_BASE64% 的应用范围, condition 支持多个条件,支持 resource url 获取选中文本,支持 %sl 选中文本或者链接文本,openCommand 函数增加额外参数, Bug 1870644 - Provide a single function for obtaining icon URLs from search engines,dom 属性 image 转换为css 属性 list-style-image,强制 enableContentAreaContextMenuCompact 在 Firefox 版本号小于 90 时无效,移除 openScriptInScratchpad,移除 getSelection、getRangeAll、getInputSelection、focusedWindow、$$,修复大部分小书签兼容性问题(因为 CSP 有效部分还是不能运行)
// @note 0.2.0 采用 JSWindowActor 与内容进程通信(替代 e10s 时代的 loadFrameScript,虽然目前还能用),修复 onshowing 仅在页面右键生效的 bug,修复合并窗口后 CSS 失效的问题
// ==/UserScript==
/***** 説明 *****
* _addMenu.js Demo: https://github.com/benzBrake/FirefoxCustomize/blob/master/userChromeJS/addMenuPlus/_addmenu.js
*/
if (typeof window == "undefined" || globalThis !== window) {
if (!Services.appinfo.remoteType) {
this.EXPORTED_SYMBOLS = ["AddMenuParent"];
try {
const actorParams = {
parent: {
moduleURI: __URI__,
},
child: {
moduleURI: __URI__,
events: {},
},
allFrames: true,
messageManagerGroups: ["browsers"],
matches: ["*://*/*", "file:///*", "about:*", "view-source:*", "moz-extension://*/*"],
};
ChromeUtils.registerWindowActor("AddMenu", actorParams);
} catch (e) { console.error(e) }
this.AddMenuParent = class extends JSWindowActorParent {
receiveMessage ({ name, data }) {
// https://searchfox.org/mozilla-central/rev/43ee5e789b079e94837a21336e9ce2420658fd19/browser/actors/ContextMenuParent.sys.mjs#60-63
let windowGlobal = this.manager.browsingContext.currentWindowGlobal;
let browser = windowGlobal.rootFrameLoader.ownerElement;
let win = browser.ownerGlobal;
let addMenu = win.addMenu;
switch (name) {
case "AM:SetSeletedText":
addMenu.setSelectedText(data.text);
break;
case "AM:FaviconLink":
if (data?.href && data.hash) {
win.gBrowser.tabs.forEach(t => {
t.faviconHash === data.hash && (t.faviconUrl = data.href)
});
}
break;
case "AM:ExectueScriptEnd":
break;
case "AM:OnElement":
Object.assign(win.addMenu.ContextMenu, data);
break;
}
}
}
}
else {
this.EXPORTED_SYMBOLS = ["AddMenuChild"];
this.AddMenuChild = class extends JSWindowActorChild {
actorCreated () {
const win = this.contentWindow;
if (window.addMenu) return;
win.addMenu = {};
const { console, document: doc } = window;
const actor = win.windowGlobalChild.getActor("AddMenu");;
doc.addEventListener("mouseup", function(event) {
var selectedText = getSelectedText();
if (selectedText) {
actor.sendAsyncMessage("AM:SetSeletedText", {
text: selectedText,
isEditableElement: isEditableElement()
});
}
});
doc.addEventListener("contextmenu", function(event) {
let data = {
onSvg: event.target.namespaceURI === "http://www.w3.org/2000/svg"
}
if (event.target.namespaceURI === "http://www.w3.org/2000/svg") {
data.svg = event.target.closest('svg')?.outerHTML;
}
actor.sendAsyncMessage("AM:OnElement", data);
});
function getSelectedText() {
var text = "";
if (win.getSelection) {
text = win.getSelection().toString();
} else if (doc?.selection?.type != "Control") {
text = doc.selection.createRange().text;
}
return text;
}
function isEditableElement() {
var el = win.getSelection().focusNode.parentNode;
return el.isContentEditable || el.matches('input,textarea');
}
}
receiveMessage ({ name, data }) {
const win = this.contentWindow;
const { console, document: doc } = win;
const actor = win.windowGlobalChild.getActor("AddMenu");
switch (name) {
case "AM:GetFaviconLink":
if (!doc.head || doc.location.href.startsWith("about:")) return;
let link = doc.head.querySelector('[rel~="shortcut"],[rel="icon"]');
let href = "";
if (link) {
href = processRelLink(link.getAttribute("href"));
} else {
href = `${doc.location.protocol}//${doc.location.host}/favicon.ico`;
}
actor.sendAsyncMessage("AM:FaviconLink", { href, hash: data.hash });
function processRelLink(href) {
if (href.startsWith("//")) {
return doc.location.protocol + href;
}
if (/^(https?|chrome|resource|data):/.test(href)) {
return href;
}
const { protocol, host } = doc.location;
if (/^\.?\//.test(href)) {
return protocol + "//" + host + href.replace(/^\./, "");
}
return `${protocol}//${host}/${href}`;
}
break;
case "AM:ExectueScript":
if (data?.script) {
eval('(' + decodeURIComponent(atob(data.script)) + ').call(this, doc, win, actor)');
}
break;
}
}
}
}
}
else {
try {
let fileHandler = Services.io.getProtocolHandler("file").QueryInterface(Ci.nsIFileProtocolHandler);
let scriptPath = Components.stack.filename;
if (scriptPath.startsWith("chrome")) {
scriptPath = resolveChromeURL(scriptPath);
function resolveChromeURL(str) {
const registry = Cc["@mozilla.org/chrome/chrome-registry;1"].getService(Ci.nsIChromeRegistry);
try {
return registry.convertChromeURL(Services.io.newURI(str.replace(/\\/g, "/"))).spec;
} catch (e) {
console.error(e);
return ""
}
}
}
let scriptFile = fileHandler.getFileFromURLSpec(scriptPath);
let resourceHandler = Services.io.getProtocolHandler("resource").QueryInterface(Ci.nsIResProtocolHandler);
if (!resourceHandler.hasSubstitution("addmenu-ucjs")) {
resourceHandler.setSubstitution("addmenu-ucjs", Services.io.newFileURI(scriptFile.parent));
}
try {
// ChromeUtils.import(
ChromeUtils.importESModule(`resource://addmenu-ucjs/${encodeURIComponent(scriptFile.leafName)}?${scriptFile.lastModifiedTime}`);
} catch (e) {
Cu.reportError(e);
}
} catch (e) { console.log(e) }
(function(css, getURLSpecFromFile, loadText, versionGE, isFirefoxSupportedImageMime) {
const {SelectionUtils} = ChromeUtils.importESModule("resource://gre/modules/SelectionUtils.sys.mjs");
var enableFileRefreshing = false; // 打开右键菜单时,检查配置文件是否变化,可能会减慢速度
var onshowinglabelMaxLength = 15; // 通过 onshowinglabel 设置标签的标签最大长度
var enableidentityBoxContextMenu = true; // 启用 SSL 状态按钮右键菜单
var enableContentAreaContextMenuCompact = true; // Photon 界面下右键菜单兼容开关(网页右键隐藏非纯图标菜单的图标,Firefox 版本号小于90无效)
var enableConvertImageAttrToListStyleImage = true; // 将图片属性转换为 css 属性 list-style-image
window?.addMenu?.destroy();
// i18n
const _LANG = {
'zh': {
'config example': '// 这是一个 addMenuPlus 配置文件\n' +
'// 请到 http://ywzhaiqi.github.io/addMenu_creator/ 生成配置文件\n\n' +
'tab({\n label: "addMenuPlus 配置",\n oncommand: "addMenu.edit(addMenu.FILE);"\n});',
'example is empty': '目前 addMenuPlus 的配置文件为空,请在打开的链接中生成配置并放入配置文件。\n通过右键标签打开配置文件。',
'addmenuplus label': 'addMenuPlus',
'addmenuplus tooltip': '左键:重载配置\n右键:编辑配置',
'custom showing method error': 'addMenuPlus 自定义显示错误',
'url is invalid': 'URL 不正确: %s',
'config file': '配置文件',
'not exists': ' 不存在',
'check config file with line': '\n请重新检查配置文件第 %s 行',
'file not found': '文件不存在: %s',
'config has reload': '配置已经重新载入',
'please set editor path': '请先设置编辑器的路径!!!',
'set global editor': '设置全局脚本编辑器',
'could not load': '无法载入:%s'
},
'en': {
'config example': '// This is an addMenuPlus configuration file.\n' +
'// Please visit http://ywzhaiqi.github.io/addMenu_creator/ to generate configuration.' +
'\n\n' +
'tab({\n label: "Edit addMenuPlus Configuration",\n oncommand: "addMenu.edit(addMenu.FILE);"\n});',
'example is empty': 'The configuration file for addMenuPlus is currently empty, please generate the configuration and put it in the configuration file in the open link. \nOpen the configuration file by right-clicking the tab.',
'addmenuplus label': 'addMenuPlus',
'addmenuplus tooltip': 'Left Click:Reload configuration\nRight Click:Edit configuration',
'custom showing method error': 'addMenuPlus customize popupshow error',
'url is invalid': 'URL is invalid: %s',
'check config file with line': '\nPlease recheck line %s of the configuration file',
'file not found': 'File not found: %s',
'config has reload': 'The configuration has been reloaded',
'please set editor path': 'Please set the path to the editor first!!!',
'set global editor': 'Setting up the global script editor',
'could not load': 'Could not load:%s'
},
};
const _LOCALE = Services.prefs.getCharPref("general.useragent.locale", "zh-CN").split('-')[0];
const LANG = _LANG[_LOCALE] || _LANG.en;
// 增加菜单类型请在这里加入插入点,名称不能是 ident 或者 group
const MENU_ATTRS = {
tab: {
insRef: $("context_closeTab"),
current: "tab",
submenu: "TabMenu",
groupmenu: "TabGroup"
},
page: {
insRef: $("context-viewsource"),
current: "page",
submenu: "PageMenu",
groupmenu: "PageGroup"
},
tool: {
insRef: $("#prefSep, #webDeveloperMenu"),
current: "tool",
submenu: "ToolMenu",
groupmenu: "ToolGroup"
},
app: {
insRef: $("#appmenu-quit,#appMenu-quit-button,#appMenu-quit-button2,#menu_FileQuitItem"),
current: "app",
submenu: "AppMenu",
groupmenu: "AppGroup"
},
nav: {
insRef: $("#toolbar-context-undoCloseTab, #toolbarItemsMenuSeparator"),
current: "nav",
submenu: "NavMenu",
groupmenu: "NavGroup"
}
};
window.addMenu = {
_selectedText: "",
ContextMenu: { svg: null, onSvg: false },
error, log,
get prefs() {
delete this.prefs;
return this.prefs = Services.prefs.getBranch("addMenu.")
},
get platform() {
return AppConstants.platform;
},
get FILE() {
delete this.FILE;
let path;
try {
path = this.prefs.getStringPref("FILE_PATH")
} catch (e) {
path = '_addmenu.js';
}
const aFile = Services.dirsvc.get("UChrm", Ci.nsIFile);
aFile.appendRelativePath(path);
if (!aFile.exists()) {
saveFile(aFile, $L('config example'));
alert($L('example is empty'));
addMenu.openCommand({
target: this
}, 'https://ywzhaiqi.github.io/addMenu_creator/', 'tab');
}
this._modifiedTime = aFile.lastModifiedTime;
return this.FILE = aFile;
},
get supportLocalization() {
return typeof Localization == "function";
},
get locale() {
return _LOCALE || "en";
},
get panelId() {
return this.panelId = Math.floor(Math.random() * 900000 + 99999);
},
init() {
this.win = window;
// prepare regex
let he = "(?:_HTML(?:IFIED)?|_ENCODE)?";
let rTITLE = "%TITLE" + he + "%|%t\\b";
let rTITLES = "%TITLES" + he + "%|%t\\b";
let rURL = "%(?:R?LINK_OR_)?URL" + he + "%|%u\\b";
let rHOST = "%HOST" + he + "%|%h\\b";
let rSEL = "%SEL" + he + "%|%s\\b";
let rLINK = "%R?LINK(?:_TEXT|_HOST)?" + he + "%|%l\\b";
let rIMAGE = "%IMAGE(?:_URL|_ALT|_TITLE)" + he + "%|%i\\b";
let rIMAGE_BASE64 = "%IMAGE_BASE64" + he + "%|%i\\b";
let rSVG_BASE64 = "%SVG_BASE64" + he + "%|%i\\b";
let rMEDIA = "%MEDIA_URL" + he + "%|%m\\b";
let rCLIPBOARD = "%CLIPBOARD" + he + "%|%p\\b";
let rFAVICON = "%FAVICON" + he + "%";
let rEMAIL = "%EMAIL" + he + "%";
let rExt = "%EOL" + he + "%";
let rFAVICON_BASE64 = "%FAVICON_BASE64" + he + "%";
let rRLT_OR_UT = "%RLT_OR_UT" + he + "%"; // 链接文本或网页标题
let rSEL_OR_LT = "%(?:SEL_OR_LINK_TEXT|SEL_OR_LT)" + he + "%|%sl\\b"; // 选中文本或者链接文本
this.rTITLE = new RegExp(rTITLE, "i");
this.rTITLES = new RegExp(rTITLES, "i");
this.rURL = new RegExp(rURL, "i");
this.rHOST = new RegExp(rHOST, "i");
this.rSEL = new RegExp(rSEL, "i");
this.rLINK = new RegExp(rLINK, "i");
this.rIMAGE = new RegExp(rIMAGE, "i");
this.rMEDIA = new RegExp(rMEDIA, "i");
this.rCLIPBOARD = new RegExp(rCLIPBOARD, "i");
this.rFAVICON = new RegExp(rFAVICON, "i");
this.rEMAIL = new RegExp(rEMAIL, "i");
this.rExt = new RegExp(rExt, "i");
this.rFAVICON_BASE64 = new RegExp(rFAVICON_BASE64, "i");
this.rIMAGE_BASE64 = new RegExp(rIMAGE_BASE64, "i");
this.rSVG_BASE64 = new RegExp(rSVG_BASE64, "i");
this.rRLT_OR_UT = new RegExp(rRLT_OR_UT, "i");
this.rSEL_OR_LT = new RegExp(rSEL_OR_LT, "i");
this.regexp = new RegExp(
[rTITLE, rTITLES, rURL, rHOST, rSEL, rLINK, rIMAGE, rIMAGE_BASE64, rMEDIA, rSVG_BASE64, rCLIPBOARD, rFAVICON, rFAVICON_BASE64, rEMAIL, rExt, rRLT_OR_UT, rSEL_OR_LT].join("|"), "ig");
// add menuitem insertpoint
for (let type in MENU_ATTRS) {
let ins = MENU_ATTRS[type].insRef;
if (ins) {
let tag = ins.localName.startsWith("menu") ? "menuseparator" : "toolbarseparator";
let insertPoint = $C(tag, {
id: `addMenu-${type}-insertpoint`,
class: "addMenu-insert-point",
hidden: true
})
MENU_ATTRS[type].insertId = insertPoint.id;
ins.after(insertPoint);
delete MENU_ATTRS[type].insRef;
} else {
delete MENU_ATTRS[type];
}
}
// old style groupmenu compatibility
MENU_ATTRS['group'] = {
current: "group",
submenu: "GroupMenu",
insertId: "addMenu-page-insertpoint"
};
$("contentAreaContextMenu").addEventListener("popupshowing", this, false);
$("tabContextMenu").addEventListener("popupshowing", this, false);
$("toolbar-context-menu").addEventListener("popupshowing", this, false);
$("menu_FilePopup").addEventListener("popupshowing", this, false);
$("menu_ToolsPopup").addEventListener("popupshowing", this, false);
// move menuitems to Hamburger menu when firstly clicks the PanelUI button
PanelUI.mainView.addEventListener("ViewShowing", this.moveToAppMenu, { once: true });
// PanelUI 增加 CustomShowing 支持
PanelUI.mainView.addEventListener("ViewShowing", this);
this.APP_LITENER_REMOVER = function() {
PanelUI.mainView.removeEventListener("ViewShowing", this);
};
this.identityBox = $('#identity-icon, #identity-box');
if (enableidentityBoxContextMenu && this.identityBox) {
// SSL 小锁右键菜单
this.identityBox.addEventListener("click", this, false);
this.identityBox.setAttribute('contextmenu', false);
const popup = $C('menupopup', {
id: 'identity-box-contextmenu'
});
popup.appendChild($C("menuseparator", {
id: "addMenu-identity-insertpoint",
class: "addMenu-insert-point",
hidden: true
}));
$("mainPopupSet").appendChild(popup);
popup.addEventListener("popupshowing", this, false);
MENU_ATTRS['ident'] = {
current: "ident",
submenu: "IdentMenu",
groupmenu: "IdentGroup",
insertId: 'addMenu-identity-insertpoint'
}
}
// 增加工具菜单
$("devToolsSeparator")?.before($C("menuitem", {
id: "addMenu-rebuild",
label: $L('addmenuplus label'),
tooltiptext: $L('addmenuplus tooltip'),
oncommand: "setTimeout(function(){ addMenu.rebuild(true); }, 10);",
onclick: "if (event.button == 2) { event.preventDefault(); addMenu.edit(addMenu.FILE); }",
}));
// Photon Compact
if (enableContentAreaContextMenuCompact && versionGE("90a1")) {
$("contentAreaContextMenu").setAttribute("photoncompact", "true");
$("tabContextMenu").setAttribute("photoncompact", "true");
}
// 响应鼠标键释放事件(eg:获取选中文本)
gBrowser.tabpanels.addEventListener("mouseup", this, false);
// 响应标签修改事件
gBrowser.tabContainer.addEventListener('TabAttrModified', this);
this.style = addStyle(css);
this.rebuild();
},
destroy() {
ChromeUtils.unregisterWindowActor('AddMenu');
$("contentAreaContextMenu").removeEventListener("popupshowing", this, false);
$("contentAreaContextMenu").removeEventListener("popuphiding", this, false);
$("tabContextMenu").removeEventListener("popupshowing", this, false);
$("toolbar-context-menu").removeEventListener("popupshowing", this, false);
$("menu_FilePopup").removeEventListener("popupshowing", this, false);
$("menu_ToolsPopup").removeEventListener("popupshowing", this, false);
$("contentAreaContextMenu").removeAttribute("photoncompact");
if (typeof this.APP_LITENER_REMOVER === "function")
this.APP_LITENER_REMOVER();
gBrowser.tabpanels.removeEventListener("mouseup", this, false);
gBrowser.tabContainer.removeEventListener('TabAttrModified', this);
this.removeMenuitem();
$$('#addMenu-rebuild, .addMenu-insert-point').forEach(function(e) {
e.remove()
});
$('identity-box-contextmenu')?.remove();
this.identityBox?.removeAttribute('contextmenu');
this.identityBox?.removeEventListener("click", this, false);
this.style?.remove();
this.style2?.remove();
delete window.addMenu;
},
handleEvent(event) {
switch (event.type) {
case "ViewShowing":
case "popupshowing":
if (event.target != event.currentTarget) return;
if (enableFileRefreshing) {
this.updateModifiedFile();
}
for (const m of $$(`.addMenu`, event.target)) {
// 强制去除隐藏属性
m.removeAttribute("hidden");
// 显示时自动更新标签
if (m.hasAttribute('onshowinglabel')) {
onshowinglabelMaxLength ||= 15;
let sel = addMenu.convertText(m.getAttribute('onshowinglabel'));
if (sel?.length > 15) sel = sel.substr(0, 15) + "...";
m.setAttribute('label', sel);
}
}
let insertPoint = "";
if (gContextMenu && event.target.id == 'contentAreaContextMenu') {
var state = [];
if (gContextMenu.onTextInput)
state.push("input");
if (gContextMenu.isContentSelected || gContextMenu.isTextSelected)
state.push("select");
if (gContextMenu.onLink || event.target.matches("#context-openlinkincurrent:not([hidden=true])"))
state.push(gContextMenu.onMailtoLink ? "mailto" : "link");
if (gContextMenu.onCanvas)
state.push("canvas image");
if (gContextMenu.onImage)
state.push("image");
if (gContextMenu.onVideo || gContextMenu.onAudio)
state.push("media");
event.currentTarget.setAttribute("addMenu", state.join(" "));
insertPoint = "addMenu-page-insertpoint";
}
if (event.target.id === "toolbar-context-menu") {
const triggerNode = event.target.triggerNode;
const state = [];
const map = {
'toolbar-menubar': 'menubar',
'TabsToolbar': 'tabs',
'nav-bar': 'navbar',
'PersonalToolbar': 'personal',
};
Object.keys(map).forEach(i => $(i).contains(triggerNode) && state.push(map[i]));
if (triggerNode?.matches("toolbarbutton")) {
state.push("button");
}
event.currentTarget.setAttribute("addMenu", state.join(" "));
insertPoint = "addMenu-nav-insertpoint";
}
if (event.target.id === "tabContextMenu") {
insertPoint = "addMenu-tab-insertpoint";
triggerFavMsg(TabContextMenu.contextTab);
}
if (event.target.id === "identity-box-contextmenu") {
insertPoint = "addMenu-identity-insertpoint";
}
if (event.target.matches('#menu_FilePopup, #appMenu-protonMainView')) {
insertPoint = "addMenu-app-insertpoint";
}
if (event.target.id === "menu_ToolsPopup") {
insertPoint = "addMenu-tool-insertpoint";
}
this.customShowings?.forEach(function(obj) {
if (obj.insertPoint !== insertPoint) return;
let {item, fnSource: fn} = obj;
if (typeof fn == 'function') fn = fn.toString();
if (!fn.startsWith('function')) fn = 'function ' + fn;
try {
eval(`(${fn}).call(item, item)`);
} catch (ex) {
error($L('custom showing method error'), fn, ex);
}
});
setTimeout(_ => {
event.target.querySelectorAll('.addMenu[command]').forEach(elem => {
if (elem.parentNode.matches('menugroup')) return;
let original = $(elem.getAttribute('command'));
if (original) {
elem.hidden = original.hidden;
elem.collapsed = original.collapsed;
elem.disabled = original.disabled;
}
});
event.target.querySelectorAll('menugroup.addMenu').forEach(group => {
[...group.children].forEach(elem => {
if (!elem.matches(`menu [command], menuitem[command]`)) return;
elem.removeAttribute('hidden');
const oringal = $(elem.getAttribute('command'));
if (oringal) elem.disabled = oringal.hidden;
});
});
}, 9);
break;
case "popuphiding":
if (event.target != event.currentTarget) return;
if (event.target.id === "contentAreaContextMenu") {
Object.assign(this.ContextMenu, {
svg: null, onSvg: false
});
}
break;
case 'mouseup':
// get selected text
if (event.button === 0 && content) {
// 内置页面
this.setSelectedText(SelectionUtils.getSelectionDetails(content).fullText);
}
break;
case 'click':
if (event.button == 2 && event.target.id === this.identityBox.id)
$("identity-box-contextmenu").openPopup(event.target, "after_pointer", 0, 0, true, false);
break;
case 'TabAttrModified':
triggerFavMsg(event.target);
break;
}
function triggerFavMsg(tab) {
if (content) return;
if (tab === void 0) return;
const browser = gBrowser.getBrowserForTab(tab);
const URI = browser.currentURI || browser.documentURI;
if (!URI || !/^(f|ht)tps?:/.test(URI.spec)) return;
try {
let hash = calculateHashFromStr(URI.spec);
tab.faviconHash = hash;
let actor = browser.browsingContext.currentWindowGlobal.getActor("AddMenu");
actor.sendAsyncMessage("AM:GetFaviconLink", { hash });
} catch (error) { }
}
function calculateHashFromStr(data) {
// Lazily create a reusable hasher
let gCryptoHash = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash);
gCryptoHash.init(gCryptoHash.MD5);
// Convert the data to a byte array for hashing
gCryptoHash.update(
data.split("").map(c => c.charCodeAt(0)),
data.length
);
// Request the has result as ASCII base64
return gCryptoHash.finish(true);
}
},
updateModifiedFile() {
if (!this.FILE.exists()) return;
if (this._modifiedTime != this.FILE.lastModifiedTime) {
this._modifiedTime = this.FILE.lastModifiedTime;
setTimeout(function() {
addMenu.rebuild(true);
}, 10);
}
},
onCommand(event) {
var menuitem = event.target;
var text = menuitem.getAttribute("text") || "";
var keyword = menuitem.getAttribute("keyword") || "";
var url = menuitem.getAttribute("url") || "";
var where = menuitem.getAttribute("where") || "";
var exec = menuitem.getAttribute("exec") || "";
if (keyword) {
let param = text ? (text = this.convertText(text)) : "";
let engine = keyword === "@default" ? Services.search.getDefault() : Services.search.getEngineByAlias(keyword);
engine.then((engine) => {
let submission = engine.getSubmission(param);
this.openCommand(event, submission.uri.spec, where);
}).catch(() => {
PlacesUtils.keywords.fetch(keyword).then(entry => {
if (!entry) return;
let newurl = entry.url.href.replace('%s', encodeURIComponent(param));
this.openCommand(event, newurl, where);
});
})
}
else if (url)
this.openCommand(event, this.convertText(url), where);
else if (exec)
this.exec(exec, this.convertText(text));
else if (text)
this.copy(this.convertText(text));
},
openCommand(event, url, aWhere = 'tab', aAllowThirdPartyFixup, aPostData, aReferrerInfo) {
const isJavaScriptURL = url.startsWith("javascript:");
const isWebURL = /^(f|ht)tps?:/.test(url);
if (aWhere?.includes('tab') && gBrowser.selectedTab.isEmpty) {
// reuse empty tab
aWhere = 'current';
}
const where = event.button === 1 ? 'tab' : aWhere;
// Assign values to allowThirdPartyFixup if provided, or initialize with an empty object
const allowThirdPartyFixup = { ...aAllowThirdPartyFixup };
// 遵循容器设定
if (!allowThirdPartyFixup.userContextId && isWebURL) {
allowThirdPartyFixup.userContextId = gBrowser.contentPrincipal.userContextId || gBrowser.selectedBrowser.contentPrincipal.userContextId || null;
}
if (aPostData) allowThirdPartyFixup.postData = aPostData;
if (aReferrerInfo) allowThirdPartyFixup.referrerInfo = aReferrerInfo;
// Set triggeringPrincipal based on 'where' and URL scheme
allowThirdPartyFixup.triggeringPrincipal = (() => {
if (where === 'current' && !isJavaScriptURL) {
return gBrowser.selectedBrowser.contentPrincipal;
}
return isWebURL ? Services.scriptSecurityManager
.createNullPrincipal({ userContextId: allowThirdPartyFixup.userContextId }) :
Services.scriptSecurityManager.getSystemPrincipal();
})();
if (isJavaScriptURL) {
openTrustedLinkIn(url, 'current', {
allowPopups: true,
inBackground: allowThirdPartyFixup.inBackground || false,
allowInheritPrincipal: true,
private: PrivateBrowsingUtils.isWindowPrivate(window),
userContextId: allowThirdPartyFixup.userContextId,
});
} else if (where || event.button === 1) {
openTrustedLinkIn(url, where, allowThirdPartyFixup);
} else {
openUILink(url, event, {
triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal()
});
}
},
exec(path, arg = []) {
var file = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
var process = Cc['@mozilla.org/process/util;1'].createInstance(Ci.nsIProcess);
try {
var a;
if (typeof arg == 'string' || arg instanceof String) {
a = arg.split(/\s+/)
} else if (Array.isArray(arg)) {
a = arg;
} else {
a = [arg];
}
file.initWithPath(path);
if (!file.exists()) {
error($L("file not found", path));
return;
}
// Linux 下目录也是 executable
if (!file.isDirectory() && file.isExecutable()) {
process.init(file);
process.run(false, a, a.length);
} else {
file.launch();
}
} catch (e) { log(e) }
},
handleRelativePath(path, parentPath) {
if (path) {
var ffdir = parentPath || Cc['@mozilla.org/file/directory_service;1']
.getService(Ci.nsIProperties).get("ProfD", Ci.nsIFile).path;
// windows 的目录分隔符不一样
if (this.platform === "win") {
path = path.replace(/\//g, '\\');
if (/^(\\)/.test(path)) {
return ffdir + path;
}
} else {
path = path.replace(/\\/g, '//');
if (/^(\/\/)/.test(path)) {
return ffdir + path.replace(/^\/\//, "/");
}
}
return path;
}
},
moveToAppMenu() {
let ins = $('addMenu-app-insertpoint');
if (ins?.matches('menuseparator')) {
let separator = $('appMenu-quit-button2')?.previousSibling;
if (separator) {
ins.remove();
// addMenu.removeMenuitem();
separator.before($C('toolbarseparator', {
'id': 'addMenu-app-insertpoint',
class: "addMenu-insert-point",
hidden: true
}));
addMenu.rebuild();
}
}
},
rebuild(isAlert) {
const aFile = this.FILE;
if (!aFile?.exists() || !aFile.isFile()) {
log(aFile ? aFile.path : U($L('config file')) + U($L('not exists')));
return;
}
var data = loadText(aFile.path);
var sandbox = new Cu.Sandbox(new XPCNativeWrapper(window));
Object.assign(sandbox, {
Cc, Ci, Cr, Cu, Services, $, $L, loadText,
locale: this.locale,
'addMenu': this,
_css: [],
gBrowser: gBrowser
});
sandbox.Components = Components;
var includeSrc = "";
sandbox.include = function(aLeafName) {
var file = addMenu.FILE.parent.clone();
file.appendRelativePath(aLeafName);
var data = loadText(file.path);
if (data) includeSrc += data + "\n";
};
Object.values(MENU_ATTRS).forEach(({ current, submenu, groupmenu }) => {
sandbox["_" + current] = [];
if (submenu !== "GroupMenu") {
sandbox[current] = function(itemObj) {
ps(itemObj, sandbox["_" + current]);
}
}
sandbox[submenu] = function(menuObj = {}) {
menuObj._items = [];
if (submenu == 'GroupMenu') menuObj._group = true;
sandbox["_" + current].push(menuObj);
return function(itemObj) {
ps(itemObj, menuObj._items);
}
}
if (isDef(groupmenu)) sandbox[groupmenu] = function(menuObj = {}) {
menuObj._items = [];
menuObj._group = true;
sandbox["_" + current].push(menuObj);
return function(itemObj) {
ps(itemObj, menuObj._items);
}
}
});
function ps(item, a) {
Array.isArray(item) ? a.push.apply(a, item) : a.push(item);
}
try {
var lineFinder = new Error();
Cu.evalInSandbox("function css(code){ this._css.push(code+'') };"+ data, sandbox);
Cu.evalInSandbox(includeSrc, sandbox, "latest");
} catch (e) {
let line = e.lineNumber - lineFinder.lineNumber - 1;
this.alert(e + $L("check config file with line", line), null, function() {
addMenu.edit(addMenu.FILE, line);
});
return log(e);
}
this.style2?.remove();
if (sandbox._css.length) this.style2 = addStyle(sandbox._css.join("\n"));
this.removeMenuitem();
this.customShowings = [];
this.customFrameResult = [];
Object.values(MENU_ATTRS).forEach(function({ current, insertId }) {
if (!sandbox["_" + current]?.length) return;
this.createMenuitem(sandbox["_" + current], $(insertId));
}, this);
if (isAlert) this.alert(U($L('config has reload')));
},
newGroupMenu(menuObj, opt) {
const group = $C('menugroup');
// 增加 onshowing 事件
if (menuObj.onshowing) {
this.customShowings.push({
item: group,
insertPoint: opt.insertPoint.id,
fnSource: menuObj.onshowing
});
delete menuObj.onshowing;
}
this.procFrameScript(menuObj);
Object.keys(menuObj).forEach((key) => {
if (key === "_items") return;
if (key === "_group") return;
var val = menuObj[key];
if (typeof val == "function")
menuObj[key] = val = "(" + val.toString() + ").call(this, event);";
group.setAttribute(key, val);
});
group.classList.add('addMenu');
this.setCondition(group, menuObj, opt);
// Sync condition attribute to child menus
menuObj._items.forEach((obj) => {
if (!("condition" in obj)) {
obj.condition = group.getAttribute("condition");
}
group.appendChild(this.newMenuitem(obj, {
isMenuGroup: true
}));
});
return group;
},
newMenu(menuObj, opt = {}) {
if (menuObj._group) {
return this.newGroupMenu(menuObj, opt);
}
const isAppMenu = opt.insertPoint?.matches('toolbarseparator#addMenu-app-insertpoint'),
separatorType = isAppMenu ? "toolbarseparator" : "menuseparator",
menuitemType = isAppMenu ? "toolbarbutton" : "menu",
menu = $C(menuitemType);
let popup, panelId;
// fix for appmenu
const viewCache = $('appMenu-viewCache')?.content || $('appMenu-multiView');
if (isAppMenu && viewCache) {
menu.setAttribute('closemenu', "none");
panelId = menuObj.id ? menuObj.id + "-panel" : "addMenu-panel-" + this.panelId++;
popup = viewCache.appendChild($C('panelview', {
'id': panelId,
'class': 'addMenu PanelUI-subView'
}));
popup = popup.appendChild($C('vbox', {
class: 'panel-subview-body',
panelId: panelId
}));
} else {
popup = menu.appendChild($C("menupopup"));
}
if (menuObj.onshowing) {
this.customShowings.push({
item: menu,
insertPoint: opt.insertPoint.id,
fnSource: menuObj.onshowing.toString()
});
delete menuObj.onshowing;
}
this.procFrameScript(menuObj);
for (let key in menuObj) {
if (key === "_items") continue;
let val = menuObj[key];
if (typeof val == "function")
menuObj[key] = val = "(" + val.toString() + ").call(this, event);"
menu.setAttribute(key, val);
}
let cls = menu.classList;
cls.add("addMenu");
if (isAppMenu) {
cls.add("subviewbutton");
cls.add("subviewbutton-nav");
} else {
cls.add("menu-iconic");
}
this.setCondition(menu, menuObj, opt);
menuObj._items?.forEach(obj => {
popup.appendChild(this.newMenuitem(obj, opt))
});
// menu に label が無い場合、最初の menuitem の label 等を持ってくる
// menu 部分をクリックで実行できるようにする(splitmenu みたいな感じ)
if (isAppMenu) {
menu.setAttribute('oncommand', `PanelUI.showSubView('${panelId}', this)`);
} else if (!menu.hasAttribute('label')) {
let firstItem = menu.querySelector('menuitem');
if (firstItem) {
let command = firstItem.getAttribute('command');
if (firstItem.matches('.copy')) {
menu.classList.add('copy');
}
if (command) firstItem = $(command) || firstItem;
['label', 'data-l10n-href', 'data-l10n-id', 'accesskey', 'icon', 'tooltiptext'].forEach(function(n) {
if (!menu.hasAttribute(n) && firstItem.hasAttribute(n))
menu.setAttribute(n, firstItem.getAttribute(n));
}, this);
setImage(menu, menuObj.image || firstItem.getAttribute("image") || firstItem.style.listStyleImage.slice(4, -1));
menu.setAttribute('onclick', `
if (event.target != event.currentTarget) return;
var firstItem = event.currentTarget.querySelector('menuitem');
if (!firstItem) return;
if (event.button === 1) {
checkForMiddleClick(firstItem, event);
} else {
if (firstItem.disabled) return;
firstItem.doCommand();
closeMenus(event.currentTarget);
}`);
}
}
return menu;
},
procFrameScript(menuObj) {
let r = menuObj.framescript;
if (!r) return;
if (typeof r == "function") r = r.toString();
else if (r instanceof Object) {
const { keyword, result, script } = r;
if (keyword && result && script) {
this.customFrameResult.push({ keyword, result });
}
if (script) r = script.toString();
}
menuObj.framescript = btoa(encodeURIComponent(r));
},
newMenuitem(obj, opt = {}) {
const isAppMenu = opt.insertPoint?.matches('toolbarseparator#addMenu-app-insertpoint'),
separatorType = isAppMenu ? "toolbarseparator" : "menuseparator",